mulguard 1.1.6 → 1.1.7

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.
Files changed (61) hide show
  1. package/README.md +210 -706
  2. package/dist/actions-CMtg7FGv.js +1 -0
  3. package/dist/{actions-DeCfLtHA.mjs → actions-CjQUKaXF.mjs} +54 -38
  4. package/dist/client/index.js +1 -1
  5. package/dist/client/index.mjs +84 -78
  6. package/dist/core/auth/email-password.d.ts +145 -0
  7. package/dist/core/auth/oauth/index.d.ts +14 -0
  8. package/dist/core/auth/oauth/oauth-handler.d.ts +172 -0
  9. package/dist/core/auth/oauth/pkce.d.ts +168 -0
  10. package/dist/core/auth/{oauth-providers.d.ts → oauth/providers.d.ts} +8 -7
  11. package/dist/core/auth/{oauth-state-store-cookie.d.ts → oauth/state-store-cookie.d.ts} +4 -4
  12. package/dist/core/auth/{oauth-state-store-redis.d.ts → oauth/state-store-redis.d.ts} +1 -1
  13. package/dist/core/auth/{oauth-state-store.d.ts → oauth/state-store.d.ts} +4 -1
  14. package/dist/core/auth/otp.d.ts +184 -0
  15. package/dist/core/errors/index.d.ts +269 -0
  16. package/dist/core/index.d.ts +1 -3
  17. package/dist/core/logger/index.d.ts +147 -0
  18. package/dist/core/mulguard/integration.d.ts +104 -0
  19. package/dist/core/mulguard/oauth-handler.d.ts +1 -1
  20. package/dist/core/security/security-manager.d.ts +236 -0
  21. package/dist/core/session/session-manager.d.ts +235 -0
  22. package/dist/core/types/index.d.ts +27 -5
  23. package/dist/index/index.js +1 -1
  24. package/dist/index/index.mjs +1388 -881
  25. package/dist/index.d.ts +3 -6
  26. package/dist/{client → nextjs/client}/hooks.d.ts +2 -2
  27. package/dist/nextjs/client/index.d.ts +13 -0
  28. package/dist/{client → nextjs/client}/provider.d.ts +1 -1
  29. package/dist/{client → nextjs/client}/server-actions-helper.d.ts +2 -2
  30. package/dist/{handlers → nextjs/handlers}/api.d.ts +1 -1
  31. package/dist/nextjs/handlers/index.d.ts +9 -0
  32. package/dist/{handlers → nextjs/handlers}/route.d.ts +1 -1
  33. package/dist/nextjs/index.d.ts +15 -0
  34. package/dist/nextjs/proxy/index.d.ts +149 -0
  35. package/dist/nextjs/server/actions.d.ts +30 -0
  36. package/dist/{server → nextjs/server}/auth.d.ts +6 -6
  37. package/dist/{server → nextjs/server}/cookies.d.ts +5 -6
  38. package/dist/nextjs/server/index.d.ts +18 -0
  39. package/dist/{server → nextjs/server}/oauth-state.d.ts +5 -3
  40. package/dist/{server → nextjs/server}/session-helpers.d.ts +1 -3
  41. package/dist/nextjs/server/session.d.ts +144 -0
  42. package/dist/oauth-state-Drwz6fES.js +1 -0
  43. package/dist/oauth-state-pdypStuS.mjs +210 -0
  44. package/dist/server/index.js +1 -1
  45. package/dist/server/index.mjs +27 -29
  46. package/package.json +64 -11
  47. package/dist/actions-CExpv_dD.js +0 -1
  48. package/dist/client/index.d.ts +0 -5
  49. package/dist/core/auth/index.d.ts +0 -40
  50. package/dist/core/auth/oauth.d.ts +0 -20
  51. package/dist/middleware/index.d.ts +0 -28
  52. package/dist/middleware/proxy.d.ts +0 -53
  53. package/dist/oauth-state-DKle8eCr.mjs +0 -289
  54. package/dist/oauth-state-DlvrCV11.js +0 -1
  55. package/dist/server/actions.d.ts +0 -86
  56. package/dist/server/helpers.d.ts +0 -10
  57. package/dist/server/index.d.ts +0 -14
  58. package/dist/server/middleware.d.ts +0 -39
  59. package/dist/server/session.d.ts +0 -28
  60. package/dist/server/utils.d.ts +0 -10
  61. /package/dist/{middleware → nextjs/proxy}/security.d.ts +0 -0
@@ -1 +1 @@
1
- "use strict";var Ee=Object.create;var j=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var ve=(e,r,t)=>r in e?j(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Re=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of ye(r))!Ae.call(e,o)&&o!==t&&j(e,o,{get:()=>r[o],enumerable:!(n=Se(r,o))||n.enumerable});return e};var $=(e,r,t)=>(t=e!=null?Ee(ke(e)):{},Re(r||!e||!e.__esModule?j(t,"default",{value:e,enumerable:!0}):t,e));var b=(e,r,t)=>ve(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("../actions-CExpv_dD.js"),C=require("../oauth-state-DlvrCV11.js"),E=require("next/server"),F=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ce(e=32){if(F&&typeof F.getRandomValues=="function")return F.getRandomValues(new Uint8Array(e));if(F&&typeof F.randomBytes=="function")return Uint8Array.from(F.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}class Z{constructor(r){b(this,"attempts",new Map);b(this,"config");this.config=r}check(r){const t=Date.now(),n=this.attempts.get(r);return!n||n.resetAt<t?(this.attempts.set(r,{count:1,resetAt:t+this.config.windowMs}),{allowed:!0,remaining:this.config.maxAttempts-1,resetAt:new Date(t+this.config.windowMs)}):n.count>=this.config.maxAttempts?{allowed:!1,remaining:0,resetAt:new Date(n.resetAt)}:(n.count++,{allowed:!0,remaining:this.config.maxAttempts-n.count,resetAt:new Date(n.resetAt)})}reset(r){this.attempts.delete(r)}clear(){this.attempts.clear()}}function Oe(e){return new Z(e)}const ee={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"1; mode=block","Strict-Transport-Security":"max-age=31536000; includeSubDomains","Content-Security-Policy":"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"geolocation=(), microphone=(), camera=()"};function H(e){return{...ee,...e}}function Te(e,r){const t=H(r);for(const[n,o]of Object.entries(t))o&&e.set(n,o)}const Ie=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,_e=254;function q(e){var t;if(typeof e!="string"||!e)return{valid:!1,error:"Email is required"};const r=e.trim().toLowerCase();return Ie.test(r)?r.length>_e?{valid:!1,error:"Email is too long"}:r.includes("..")||r.startsWith(".")||r.endsWith(".")?{valid:!1,error:"Invalid email format"}:(t=r.split("@")[1])!=null&&t.includes("..")?{valid:!1,error:"Invalid email format"}:{valid:!0,sanitized:r}:{valid:!1,error:"Invalid email format"}}function re(e){return e.valid===!0&&e.sanitized!==void 0}const Pe=new Set(["password","12345678","qwerty","abc123","password123","123456789","1234567890","letmein","welcome","monkey","dragon","master","sunshine","princess","football","admin","root","test","guest","user"]),Ne=/012|123|234|345|456|567|678|789|abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz/i,xe=8,Ue=128;function be(e,r=xe){if(typeof e!="string"||!e)return{valid:!1,error:"Password is required"};if(e.length<r)return{valid:!1,error:`Password must be at least ${r} characters`};if(e.length>Ue)return{valid:!1,error:"Password is too long"};const t=e.toLowerCase();if(Pe.has(t))return{valid:!1,error:"Password is too common"};if(/(.)\1{3,}/.test(e))return{valid:!1,error:"Password contains too many repeated characters"};if(Ne.test(e))return{valid:!1,error:"Password contains sequential characters"};const n=Fe(e);return{valid:!0,sanitized:e,strength:n}}function Fe(e){let r=0;return e.length>=12?r+=2:e.length>=8&&(r+=1),/[a-z]/.test(e)&&(r+=1),/[A-Z]/.test(e)&&(r+=1),/[0-9]/.test(e)&&(r+=1),/[^a-zA-Z0-9]/.test(e)&&(r+=1),r>=5?"strong":r>=3?"medium":"weak"}function De(e){return e.valid===!0&&e.sanitized!==void 0}const Le=100;function Me(e){if(typeof e!="string"||!e)return{valid:!1,error:"Name is required"};const r=e.trim();if(r.length<1)return{valid:!1,error:"Name cannot be empty"};if(r.length>Le)return{valid:!1,error:"Name is too long"};const t=r.replace(/[<>"']/g,"");return t.length===0?{valid:!1,error:"Name contains only invalid characters"}:{valid:!0,sanitized:t}}function Ve(e){return e.valid===!0&&e.sanitized!==void 0}const ze=new Set(["http:","https:"]);function je(e){if(typeof e!="string"||!e)return{valid:!1,error:"URL is required"};try{const r=new URL(e);return ze.has(r.protocol)?{valid:!0,sanitized:e}:{valid:!1,error:"URL must use http or https protocol"}}catch{return{valid:!1,error:"Invalid URL format"}}}function $e(e){return e.valid===!0&&e.sanitized!==void 0}const He=16,qe=512,We=/^[A-Za-z0-9_-]+$/;function Be(e,r=He){return typeof e!="string"||!e?{valid:!1,error:"Token is required"}:e.length<r?{valid:!1,error:"Token is too short"}:e.length>qe?{valid:!1,error:"Token is too long"}:We.test(e)?/(.)\1{10,}/.test(e)?{valid:!1,error:"Token contains suspicious pattern"}:{valid:!0,sanitized:e}:{valid:!1,error:"Invalid token format"}}function Ge(e){return e.valid===!0&&e.sanitized!==void 0}const Ke=1e3;function W(e,r){const{maxLength:t=Ke,allowHtml:n=!1,required:o=!0}=r??{};if(o&&(typeof e!="string"||!e||e.trim().length===0))return{valid:!1,error:"Input is required"};if(typeof e!="string"||!e)return{valid:!0,sanitized:""};let s=e.trim();return s.length>t?{valid:!1,error:`Input must be less than ${t} characters`}:(n||(s=s.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;")),s=s.replace(/[\x00-\x1F\x7F]/g,""),{valid:!0,sanitized:s})}function Xe(e){return e.valid===!0&&e.sanitized!==void 0}class te{constructor(){b(this,"tokens",new Map)}get(r){const t=this.tokens.get(r);return t?t.expiresAt<Date.now()?(this.delete(r),null):t.value:null}set(r,t,n=36e5){this.tokens.set(r,{value:t,expiresAt:Date.now()+n})}delete(r){this.tokens.delete(r)}clear(){this.tokens.clear()}}class ne{constructor(r,t=32){b(this,"store");b(this,"tokenLength");this.store=r||new te,this.tokenLength=t}generateToken(r,t){const n=B(this.tokenLength);return this.store.set(r,n,t),n}validateToken(r,t){const n=this.store.get(r);if(!n)return!1;const o=G(t,n);return o&&this.store.delete(r),o}getToken(r){return this.store.get(r)}deleteToken(r){this.store.delete(r)}}function Je(e){return new ne(e)}function oe(e){if(typeof e!="string")return"";const r={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return e.replace(/[&<>"']/g,t=>r[t]||t)}function Ye(e){return typeof e!="string"?"":e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript:/gi,"")}function Qe(e){return typeof e!="string"?"":oe(e.trim())}function Ze(e){return typeof e!="string"?!1:[/<script/i,/javascript:/i,/on\w+\s*=/i,/<iframe/i,/<object/i,/<embed/i,/<link/i,/<meta/i,/expression\s*\(/i,/vbscript:/i].some(t=>t.test(e))}const se=32;function B(e=se){if(e<1||e>256)throw new Error("Token length must be between 1 and 256 bytes");const r=Ce(e);return Buffer.from(r).toString("base64url")}function ie(){return B(se)}function G(e,r){if(typeof e!="string"||typeof r!="string"||!e||!r||e.length!==r.length)return!1;let t=0;for(let n=0;n<e.length;n++)t|=e.charCodeAt(n)^r.charCodeAt(n);return t===0}function er(e,r){return G(e,r)}function rr(e){return typeof e!="string"?"":e.trim().replace(/[<>]/g,"")}const tr=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function nr(e){return typeof e=="string"&&tr.test(e)}function ae(e){return!e.success&&!!e.error}function or(e){return e.requires2FA===!0||e.errorCode===h.AuthErrorCode.TWO_FA_REQUIRED}function sr(e,r){return e.error?e.error:r||"Authentication failed"}function ir(e){return e.errorCode}function ar(e){return e.success===!0&&!!e.user}function cr(e,r){return e.errorCode===r}function ur(e){if(!ae(e))return!1;const r=[h.AuthErrorCode.NETWORK_ERROR,h.AuthErrorCode.RATE_LIMITED,h.AuthErrorCode.UNKNOWN_ERROR];return e.errorCode?r.includes(e.errorCode):!1}function lr(e){if(e.error)return e.error;switch(e.errorCode){case h.AuthErrorCode.INVALID_CREDENTIALS:return"Invalid email or password. Please try again.";case h.AuthErrorCode.ACCOUNT_LOCKED:return"Your account has been temporarily locked. Please try again later.";case h.AuthErrorCode.ACCOUNT_INACTIVE:return"Your account is inactive. Please contact support.";case h.AuthErrorCode.TWO_FA_REQUIRED:return"Two-factor authentication is required. Please enter your code.";case h.AuthErrorCode.INVALID_TWO_FA_CODE:return"Invalid two-factor authentication code. Please try again.";case h.AuthErrorCode.SESSION_EXPIRED:return"Your session has expired. Please sign in again.";case h.AuthErrorCode.UNAUTHORIZED:return"You are not authorized to perform this action.";case h.AuthErrorCode.NETWORK_ERROR:return"Network error. Please check your connection and try again.";case h.AuthErrorCode.VALIDATION_ERROR:return"Please check your input and try again.";case h.AuthErrorCode.RATE_LIMITED:return"Too many attempts. Please try again later.";case h.AuthErrorCode.UNKNOWN_ERROR:default:return"An unexpected error occurred. Please try again."}}async function fr(e,r,t){return e.signIn(r,t)}const ce={google:{authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",userInfoUrl:"https://www.googleapis.com/oauth2/v2/userinfo",defaultScopes:["openid","profile","email"]},github:{authorizationUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",userInfoUrl:"https://api.github.com/user",defaultScopes:["user:email"]},apple:{authorizationUrl:"https://appleid.apple.com/auth/authorize",tokenUrl:"https://appleid.apple.com/auth/token",userInfoUrl:"https://appleid.apple.com/auth/userinfo",defaultScopes:["name","email"],defaultParams:{response_mode:"form_post",response_type:"code id_token"}},facebook:{authorizationUrl:"https://www.facebook.com/v18.0/dialog/oauth",tokenUrl:"https://graph.facebook.com/v18.0/oauth/access_token",userInfoUrl:"https://graph.facebook.com/v18.0/me?fields=id,name,email,picture",defaultScopes:["email","public_profile"]}};function z(e){return ce[e]??null}function dr(e){return e in ce}function ue(e,r,t,n){const o=z(e);if(!o)throw new Error(`Unknown OAuth provider: ${e}`);if(!r.clientId)throw new Error(`OAuth provider "${e}" is missing clientId`);const s=r.redirectUri??`${t}/api/auth/callback/${e}`,i=r.scopes??o.defaultScopes,a=new URLSearchParams({client_id:r.clientId,redirect_uri:s,response_type:"code",scope:Array.isArray(i)?i.join(" "):String(i),state:n});if(o.defaultParams)for(const[u,f]of Object.entries(o.defaultParams))a.append(u,f);if(r.params)for(const[u,f]of Object.entries(r.params))a.set(u,f);return`${o.authorizationUrl}?${a.toString()}`}async function le(e,r,t,n){const o=z(e);if(!o)throw new Error(`Unknown OAuth provider: ${e}`);if(!t||typeof t!="string")throw new Error("Authorization code is required");if(!r.clientId)throw new Error(`OAuth provider "${e}" is missing clientId`);const s=new URLSearchParams({client_id:r.clientId,code:t,redirect_uri:n,grant_type:"authorization_code"});r.clientSecret&&s.append("client_secret",r.clientSecret);try{const i=await fetch(o.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:s.toString()});if(!i.ok){const u=await i.text();let f=`Failed to exchange code for tokens: ${u}`;try{const w=JSON.parse(u);f=w.error_description??w.error??f}catch{}throw new Error(f)}const a=await i.json();if(!hr(a))throw new Error("Invalid token exchange response format");return a}catch(i){throw i instanceof Error?i:new Error(`OAuth token exchange failed: ${String(i)}`)}}function hr(e){return typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string"}async function fe(e,r){const t=z(e);if(!t)throw new Error(`Unknown OAuth provider: ${e}`);if(!r||typeof r!="string")throw new Error("Access token is required");try{const n=await fetch(t.userInfoUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});if(!n.ok){const s=await n.text();let i=`Failed to fetch user info: ${s}`;try{const a=JSON.parse(s);i=a.error_description??a.error??i}catch{}throw new Error(i)}const o=await n.json();return gr(e,o,r)}catch(n){throw n instanceof Error?n:new Error(`OAuth user info retrieval failed: ${String(n)}`)}}async function gr(e,r,t){switch(e){case"google":return wr(r);case"github":return await pr(r,t);case"apple":return mr(r);case"facebook":return Er(r);default:return Sr(r)}}function wr(e){return{id:String(e.sub??e.id??""),email:String(e.email??""),name:String(e.name??""),avatar:typeof e.picture=="string"?e.picture:void 0,emailVerified:!!e.email_verified,rawProfile:e}}async function pr(e,r){let t=typeof e.email=="string"?e.email:void 0,n={...e};if(!t)try{const o=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${r}`}});if(o.ok){const s=await o.json(),i=s.find(a=>a.primary)??s[0];t=(i==null?void 0:i.email)??`${String(e.login??"user")}@users.noreply.github.com`,n={...e,emails:s}}else t=`${String(e.login??"user")}@users.noreply.github.com`}catch{t=`${String(e.login??"user")}@users.noreply.github.com`}return{id:String(e.id??""),email:t??"",name:String(e.name??e.login??""),avatar:typeof e.avatar_url=="string"?e.avatar_url:void 0,emailVerified:!!t,rawProfile:n}}function mr(e){const r=e.name,t=r?`${r.firstName??""} ${r.lastName??""}`.trim():"";return{id:String(e.sub??""),email:String(e.email??""),name:t,emailVerified:!!e.email_verified,rawProfile:e}}function Er(e){var t;const r=e.picture;return{id:String(e.id??""),email:String(e.email??""),name:String(e.name??""),avatar:(t=r==null?void 0:r.data)==null?void 0:t.url,emailVerified:!0,rawProfile:e}}function Sr(e){return{id:String(e.id??e.sub??""),email:String(e.email??""),name:String(e.name??e.display_name??e.username??""),avatar:typeof e.avatar=="string"?e.avatar:typeof e.picture=="string"?e.picture:typeof e.avatar_url=="string"?e.avatar_url:void 0,emailVerified:!!(e.email_verified??e.emailVerified??!1),rawProfile:e}}function yr(e){return typeof e=="object"&&e!==null&&"clientId"in e&&typeof e.clientId=="string"}const kr="__mulguard_oauth_state",Ar=10*60*1e3;function de(e){const r=e.cookieName||kr,t=e.ttl||Ar,n=process.env.NODE_ENV==="production",o=e.secure??n,s=e.sameSite||"strict",i=e.cookieHandler,a=u=>({httpOnly:!0,secure:o,sameSite:s,maxAge:Math.floor(u/1e3),path:"/"});return{async set(u,f,w){const p=JSON.stringify({state:u,provider:f.provider,expiresAt:f.expiresAt});await Promise.resolve(i.setCookie(r,p,a(t)))},async get(u){const f=await Promise.resolve(i.getCookie(r));if(!f)return null;try{const w=JSON.parse(f);return w.state!==u?null:w.expiresAt<Date.now()?(await Promise.resolve(i.deleteCookie(r,{path:"/"})),null):{provider:w.provider,expiresAt:w.expiresAt}}catch{return await Promise.resolve(i.deleteCookie(r,{path:"/"})),null}},async delete(u){await this.get(u)&&await Promise.resolve(i.deleteCookie(r,{path:"/"}))},async cleanup(){}}}function vr(){return de({cookieHandler:{async getCookie(e){var r;try{const{cookies:t}=await import("next/headers");return((r=(await t()).get(e))==null?void 0:r.value)||null}catch{return null}},async setCookie(e,r,t){try{const{cookies:n}=await import("next/headers");(await n()).set(e,r,{httpOnly:t.httpOnly??!0,secure:t.secure??process.env.NODE_ENV==="production",sameSite:t.sameSite||"strict",maxAge:t.maxAge,path:t.path||"/"})}catch(n){console.warn("[Mulguard] Failed to set OAuth state cookie:",n)}},async deleteCookie(e,r){try{const{cookies:t}=await import("next/headers");(await t()).set(e,"",{maxAge:0,expires:new Date(0),path:(r==null?void 0:r.path)||"/"})}catch{}}}})}class he{constructor(){b(this,"states",new Map)}set(r,t,n){this.states.set(r,t),this.cleanup()}get(r){const t=this.states.get(r);return t?t.expiresAt<Date.now()?(this.delete(r),null):t:null}delete(r){this.states.delete(r)}cleanup(){const r=Date.now();for(const[t,n]of this.states.entries())n.expiresAt<r&&this.states.delete(t)}}function ge(){return new he}function Rr(e,r="mulguard:oauth:state:"){const t=o=>`${r}${o}`,n=async o=>{const s=t(o);await e.del(s)};return{async set(o,s,i){const a=t(o),u=JSON.stringify(s);await e.set(a,u,"EX",Math.floor(i/1e3))},async get(o){const s=t(o),i=await e.get(s);if(!i)return null;try{const a=JSON.parse(i);return a.expiresAt<Date.now()?(await n(o),null):a}catch{return await n(o),null}},async delete(o){await n(o)},async cleanup(){try{const o=await e.keys(`${r}*`),s=Date.now();for(const i of o){const a=await e.get(i);if(a)try{JSON.parse(a).expiresAt<s&&await e.del(i)}catch{await e.del(i)}}}catch(o){console.warn("[Mulguard] OAuth state cleanup warning:",o)}}}}function D(e){return e.success===!0&&e.user!==void 0&&e.session!==void 0}var we=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(we||{});const Cr=process.env.NODE_ENV==="development"?0:1;function Or(e={}){const{enabled:r=process.env.NODE_ENV==="development",level:t=Cr,context:n,formatter:o=Tr}=e,s=a=>r&&a>=t,i=(a,u,f,w)=>({level:a,message:u,timestamp:new Date,context:n,data:f?Ir(f):void 0,error:w});return{debug:(a,u)=>{if(s(0)){const f=i(0,a,u);console.debug(o(f))}},info:(a,u)=>{if(s(1)){const f=i(1,a,u);console.info(o(f))}},warn:(a,u)=>{if(s(2)){const f=i(2,a,u);console.warn(o(f))}},error:(a,u)=>{if(s(3)){const f=u instanceof Error?u:void 0,w=u instanceof Error?void 0:u,p=i(3,a,w,f);console.error(o(p)),f&&console.error(f)}}}}function Tr(e){const r=e.timestamp.toISOString(),t=we[e.level],n=e.context?`[${e.context}]`:"",o=e.data?` ${JSON.stringify(e.data)}`:"";return`${r} [${t}]${n} ${e.message}${o}`}function Ir(e){const r=new Set(["password","token","secret","key","accessToken","refreshToken"]),t={};for(const[n,o]of Object.entries(e))if(r.has(n.toLowerCase()))t[n]="***REDACTED***";else if(typeof o=="string"&&n.toLowerCase().includes("email")){const s=o.split("@");if(s.length===2&&s[0]){const i=s[0].substring(0,3)+"***@"+s[1];t[n]=i}else t[n]=o}else t[n]=o;return t}const I=Or();function _r(e,r,t,n={}){const{enabled:o=!0,maxRetries:s=1,retryDelay:i=1e3,rateLimit:a=3,autoSignOutOnFailure:u=!0,redirectToLogin:f="/login",autoRedirectOnFailure:w=!0}=n;let p=null,R=!1;const v=[],A=[],S=60*1e3;let g=0,T=!1,_=null;const L=2,M=60*1e3;function c(){const y=Date.now();if(T&&_){if(y<_)return!1;T=!1,_=null,g=0}for(;A.length>0;){const m=A[0];if(m!==void 0&&m<y-S)A.shift();else break}return A.length>=a?!1:(A.push(y),!0)}function l(){g++,g>=L&&(T=!0,_=Date.now()+M,process.env.NODE_ENV==="development"&&console.warn("[TokenRefreshManager] Circuit breaker opened - too many consecutive failures"))}function d(){g=0,T=!1,_=null}async function k(y=1){if(!o)return null;if(!c())throw new Error("Rate limit exceeded for token refresh");try{const m=await e();if(m)return d(),P(m),n.onTokenRefreshed&&await Promise.resolve(n.onTokenRefreshed(m)),m;if(l(),y<s)return await X(i*y),k(y+1);throw new Error("Token refresh failed: refresh function returned null")}catch(m){if(l(),y<s&&N(m))return await X(i*y),k(y+1);throw m}}function N(y){if(y instanceof Error){const m=y.message.toLowerCase();if(m.includes("rate limit")||m.includes("too many requests")||m.includes("429")||m.includes("limit:")||m.includes("requests per minute")||m.includes("token_blacklisted")||m.includes("blacklisted")||m.includes("invalid")||m.includes("401")||m.includes("unauthorized")||m.includes("session has been revoked")||m.includes("session expired"))return!1;if(m.includes("network")||m.includes("fetch")||m.includes("timeout"))return!0}return!1}function P(y){const m=[...v];v.length=0;for(const{resolve:U}of m)U(y)}function K(y){const m=[...v];v.length=0;for(const{reject:U}of m)U(y)}function X(y){return new Promise(m=>setTimeout(m,y))}async function J(y){try{if(n.onTokenRefreshFailed&&await Promise.resolve(n.onTokenRefreshFailed(y)),u&&(await t(),await r(),w&&typeof window<"u")){let m=!0;if(n.onBeforeRedirect&&(m=await Promise.resolve(n.onBeforeRedirect(y))),m){const U=new URL(f,window.location.origin);U.searchParams.set("reason","session_expired"),U.searchParams.set("redirect",window.location.pathname+window.location.search),window.location.href=U.toString()}}}catch(m){process.env.NODE_ENV==="development"&&console.error("[TokenRefreshManager] Error in handleRefreshFailure:",m)}}return{async refreshToken(){return o?p||(R=!0,p=k().then(y=>(R=!1,p=null,y)).catch(y=>{throw R=!1,p=null,K(y),J(y).catch(()=>{}),y}),p):null},isRefreshing(){return R},async waitForRefresh(){return p?new Promise((y,m)=>{v.push({resolve:y,reject:m})}):null},clear(){p=null,R=!1,A.length=0,d(),K(new Error("Token refresh manager cleared"))},async handleRefreshFailure(y){return J(y)}}}function Pr(){const e=process.env.NODE_ENV==="production";return{cookieName:"__mulguard_session",expiresIn:60*60*24*7,httpOnly:!0,secure:e,sameSite:"lax",path:"/"}}function Nr(){return{enabled:!0,refreshThreshold:300,maxRetries:0,retryDelay:1e3,rateLimit:1,autoSignOutOnFailure:!0,redirectToLogin:"/login",autoRedirectOnFailure:!0}}function xr(){return process.env.NEXT_PUBLIC_URL??(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:"http://localhost:3000")}function Ur(e){const{sessionConfig:r,cacheTtl:t,getSessionAction:n,onSessionExpired:o,onError:s}=e,i=r.cookieName??"__mulguard_session";let a=null;const u=async()=>{const S=Date.now();if(a&&S-a.timestamp<t)return a.session;if(n)try{const g=await n();if(g&&C.validateSessionStructure(g))return a={session:g,timestamp:S},g;g&&!C.validateSessionStructure(g)&&(await w(),a=null)}catch(g){I.debug("getSession error",{error:g}),s&&await s(g instanceof Error?g:new Error(String(g)),"getSession"),a=null}try{const g=await h.getCookie(i);if(g)try{const T=JSON.parse(g);if(C.validateSessionStructure(T))return T.expiresAt&&new Date(T.expiresAt)<new Date?(o&&await o(T),await w(),a=null,null):(a={session:T,timestamp:S},T);await w(),a=null}catch{await w(),a=null}}catch(g){const T=g instanceof Error?g.message:String(g);!T.includes("request scope")&&!T.includes("cookies")&&(I.warn("getSession cookie error",{error:g}),s&&await s(g instanceof Error?g:new Error(String(g)),"getSession.cookie"))}return null},f=async S=>{if(!C.validateSessionStructure(S))return{success:!1,error:"Invalid session structure"};try{const g=typeof S=="object"&&"token"in S?String(S.token):JSON.stringify(S),T=h.buildCookieOptions(i,g,r),_=await h.setCookie(T);return _.success&&(a={session:S,timestamp:Date.now()}),_}catch(g){const T=g instanceof Error?g.message:"Failed to set session";return I.error("setSession error",{error:g}),s&&await s(g instanceof Error?g:new Error(String(g)),"setSession"),{success:!1,error:T}}},w=async()=>{try{await h.deleteCookie(i,{path:r.path,domain:r.domain}),a=null}catch(S){I.warn("clearSessionCookie error",{error:S})}},p=async()=>{const S=await u();return S!=null&&S.accessToken&&typeof S.accessToken=="string"?S.accessToken:null};return{getSession:u,setSession:f,clearSessionCookie:w,getAccessToken:p,getRefreshToken:async()=>{const S=await u();return S!=null&&S.refreshToken&&typeof S.refreshToken=="string"?S.refreshToken:null},hasValidTokens:async()=>!!await p(),clearCache:()=>{a=null},getSessionConfig:()=>({cookieName:i,config:r})}}function br(e){return async r=>{try{if(!r||typeof r!="object")return{success:!1,error:"Invalid credentials",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!r.email||typeof r.email!="string")return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const t=q(r.email);if(!re(t))return{success:!1,error:t.error??"Invalid email format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!r.password||typeof r.password!="string")return{success:!1,error:"Password is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(r.password.length>128)return{success:!1,error:"Invalid credentials",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const n={email:t.sanitized,password:r.password},o=await e.actions.signIn.email(n);if(D(o)){const s=await e.saveSessionAfterAuth(o);!s.success&&s.warning&&I.warn("Session save warning",{warning:s.warning})}return o.success?I.info("Sign in successful",{email:n.email.substring(0,3)+"***"}):I.warn("Sign in failed",{email:n.email.substring(0,3)+"***",errorCode:o.errorCode}),o}catch(t){const n=t instanceof Error?t.message:"Sign in failed";return I.error("Sign in error",{error:n,context:"signIn.email"}),e.onError&&await e.onError(t instanceof Error?t:new Error(String(t)),"signIn.email"),{success:!1,error:"Sign in failed. Please try again.",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}}}function Fr(e,r){return async t=>{if(!t||typeof t!="string")throw new Error("Provider is required");const n=W(t,{maxLength:50,allowHtml:!1,required:!0});if(!n.valid||!n.sanitized)throw new Error("Invalid provider");const o=n.sanitized.toLowerCase();if(!e.actions.signIn.oauth)throw new Error("OAuth sign in is not configured. Either provide oauth action in signIn, or configure providers.oauth in config.");const s=await e.actions.signIn.oauth(o);return await r(s.state,o),I.info("OAuth sign in initiated",{provider:o}),s}}function Dr(e){return async(r,t)=>{if(!r||typeof r!="string")return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const n=q(r);if(!re(n))return{success:!1,error:n.error??"Invalid email format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(t!==void 0&&(typeof t!="string"||t.length<4||t.length>10))return{success:!1,error:"Invalid OTP code format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!e.actions.signIn.otp)return{success:!1,error:"OTP sign in is not configured",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const o=await e.actions.signIn.otp(n.sanitized,t);if(D(o)){const s=await e.saveSessionAfterAuth(o);!s.success&&s.warning&&I.warn("Session save warning",{warning:s.warning})}return o.success?I.info("OTP sign in successful",{email:n.sanitized.substring(0,3)+"***"}):I.warn("OTP sign in failed",{email:n.sanitized.substring(0,3)+"***"}),o}catch(o){return I.error("OTP sign in error",{error:o instanceof Error?o.message:"Unknown error",context:"signIn.otp"}),e.onError&&await e.onError(o instanceof Error?o:new Error(String(o)),"signIn.otp"),{success:!1,error:"OTP sign in failed. Please try again.",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}}}function Lr(e){return async r=>{if(!e.actions.signIn.passkey)throw new Error("PassKey sign in is not configured. Provide passkey action in signIn.");try{const t=await e.actions.signIn.passkey(r);if(D(t)){const n=await e.saveSessionAfterAuth(t);!n.success&&n.warning&&I.warn("Session save warning",{warning:n.warning})}return t}catch(t){return e.onError&&await e.onError(t instanceof Error?t:new Error(String(t)),"signIn.passkey"),{success:!1,error:t instanceof Error?t.message:"PassKey sign in failed"}}}}function Mr(e,r){const t=br(e),n=Fr(e,r),o=Dr(e),s=Lr(e);return Object.assign(async(u,f)=>{if(!u||typeof u!="string")throw new Error("Provider is required");const w=W(u,{maxLength:50,allowHtml:!1,required:!0});if(!w.valid||!w.sanitized)throw new Error("Invalid provider");const p=w.sanitized.toLowerCase();if(p==="google"||p==="github"||p==="apple"||p==="facebook"||typeof p=="string"&&!["credentials","otp","passkey"].includes(p))return n(p);if(p==="credentials")return!f||!("email"in f)||!("password"in f)?{success:!1,error:"Credentials are required",errorCode:h.AuthErrorCode.VALIDATION_ERROR}:t(f);if(p==="otp"){if(!f||!("email"in f))return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const R=f;return o(R.email,R.code)}return p==="passkey"?s(f):{success:!1,error:"Invalid provider",errorCode:h.AuthErrorCode.VALIDATION_ERROR}},{email:t,oauth:e.actions.signIn.oauth?n:void 0,passkey:e.actions.signIn.passkey?s:void 0,otp:e.actions.signIn.otp?o:void 0})}function Vr(e){return async r=>{if(!e.actions.signUp)throw new Error("Sign up is not configured. Provide signUp action in config.");try{const t=await e.actions.signUp(r);if(D(t)){const n=await e.saveSessionAfterAuth(t);!n.success&&n.warning&&I.warn("Session save warning",{warning:n.warning})}return t}catch(t){return e.onError&&await e.onError(t instanceof Error?t:new Error(String(t)),"signUp"),{success:!1,error:t instanceof Error?t.message:"Sign up failed"}}}}function zr(e,r){return async(t,n,o)=>{const s=e.oauthProviders[t];if(!s)return{success:!1,error:`OAuth provider "${t}" is not configured`,errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const i=s.redirectUri??`${e.baseUrl}/api/auth/callback/${t}`,a=await le(t,s,n,i),u=await fe(t,a.access_token),f={id:u.id,email:u.email,name:u.name,avatar:u.avatar,emailVerified:u.emailVerified,provider:t,accessToken:a.access_token,refreshToken:a.refresh_token,tokens:{access_token:a.access_token,refresh_token:a.refresh_token,expires_in:a.expires_in,token_type:a.token_type,id_token:a.id_token},rawProfile:u.rawProfile};if(e.callbacks.onOAuthUser){const w=await Y(e.callbacks.onOAuthUser,[f,t],e.onError);if(!w)return{success:!1,error:"Failed to create or retrieve user",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const p=e.createSession(w,f,a);return await e.saveSession(p),e.callbacks.onSignIn&&await Y(e.callbacks.onSignIn,[p.user,p],e.onError),{success:!0,user:p.user,session:p}}return{success:!1,error:"OAuth user callback not implemented. Provide onOAuthUser callback or implement oauthCallback action.",errorCode:h.AuthErrorCode.VALIDATION_ERROR}}catch(i){return I.error("OAuth callback failed",{provider:t,error:i}),{success:!1,error:i instanceof Error?i.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}}}async function Y(e,r,t){if(e)try{return await e(...r)}catch(n){throw t&&await t(n instanceof Error?n:new Error(String(n)),"callback"),n}}function jr(e,r,t,n){if(Object.keys(e).length!==0)return async o=>{const s=e[o];if(!s)throw new Error(`OAuth provider "${o}" is not configured. Add it to providers.oauth in config.`);if(!s.clientId)throw new Error(`OAuth provider "${o}" is missing clientId`);const i=t();return{url:n(o,s,r,i),state:i}}}function $r(e){var L,M;const r={...Pr(),...e.session},t=e.actions,n=e.callbacks||{},o=((L=e.providers)==null?void 0:L.oauth)||{},s=xr(),i={...Nr(),...e.tokenRefresh},a=((M=e.session)==null?void 0:M.cacheTtl)??e.sessionCacheTtl??5e3,u=e.oauthStateStore||ge(),f={...t},w=async(c,l)=>{const d={provider:l,expiresAt:Date.now()+6e5};await Promise.resolve(u.set(c,d,10*60*1e3)),u.cleanup&&await Promise.resolve(u.cleanup())},p=async(c,l)=>{let d=await Promise.resolve(u.get(c));if(!d)try{const{getOAuthStateCookie:k}=await Promise.resolve().then(()=>require("../oauth-state-DlvrCV11.js")).then(P=>P.oauthState),N=await k();if(N&&N.state===c&&N.provider===l)return!0}catch{}return d?d.expiresAt<Date.now()?(await Promise.resolve(u.delete(c)),!1):d.provider!==l?!1:(await Promise.resolve(u.delete(c)),!0):!1},R=jr(o,s,ie,ue);if(R&&!f.signIn.oauth){const c=f.signIn;f.signIn={...c,oauth:async l=>{const d=await R(l);return await w(d.state,l),d}}}if(!f.signIn||!f.signIn.email)throw new Error("mulguard: signIn.email action is required");const v=async(c,...l)=>{if(c)try{return await c(...l)}catch(d){throw n.onError&&await n.onError(d instanceof Error?d:new Error(String(d)),"callback"),d}},A=Ur({sessionConfig:r,cacheTtl:a,getSessionAction:t.getSession,onSessionExpired:n.onSessionExpired,onError:n.onError}),S=async c=>{if(!D(c)||!c.session)return{success:!0};const l=await A.setSession(c.session);return c.user&&n.onSignIn&&await v(n.onSignIn,c.user,c.session),l};if(Object.keys(o).length>0&&!f.oauthCallback){const c=zr({oauthProviders:o,baseUrl:s,callbacks:n,createSession:(l,d,k)=>({user:{...l,avatar:d.avatar,emailVerified:d.emailVerified},expiresAt:new Date(Date.now()+(r.expiresIn||604800)*1e3),accessToken:k.access_token,refreshToken:k.refresh_token,tokenType:"Bearer",expiresIn:k.expires_in}),saveSession:async l=>{await A.setSession(l)},onError:n.onError});f.oauthCallback=c}const g=Mr({actions:f,callbacks:n,saveSessionAfterAuth:S,onError:n.onError},w),T=Vr({actions:f,callbacks:n,saveSessionAfterAuth:S,onError:n.onError}),_={async getSession(){return await A.getSession()},async getAccessToken(){return await A.getAccessToken()},async getRefreshToken(){return await A.getRefreshToken()},async hasValidTokens(){return await A.hasValidTokens()},signIn:g,async signUp(c){if(!T)throw new Error("Sign up is not configured. Provide signUp action in config.");return await T(c)},async signOut(){try{const c=await this.getSession(),l=c==null?void 0:c.user;return t.signOut&&await t.signOut(),await A.clearSessionCookie(),A.clearCache(),l&&n.onSignOut&&await v(n.onSignOut,l),{success:!0}}catch(c){return await A.clearSessionCookie(),A.clearCache(),n.onError&&await v(n.onError,c instanceof Error?c:new Error(String(c)),"signOut"),{success:!1,error:c instanceof Error?c.message:"Sign out failed"}}},async resetPassword(c){if(!t.resetPassword)throw new Error("Password reset is not configured. Provide resetPassword action in config.");try{return await t.resetPassword(c)}catch(l){return n.onError&&await v(n.onError,l instanceof Error?l:new Error(String(l)),"resetPassword"),{success:!1,error:l instanceof Error?l.message:"Password reset failed"}}},async verifyEmail(c){if(!t.verifyEmail)throw new Error("Email verification is not configured. Provide verifyEmail action in config.");try{return await t.verifyEmail(c)}catch(l){return n.onError&&await v(n.onError,l instanceof Error?l:new Error(String(l)),"verifyEmail"),{success:!1,error:l instanceof Error?l.message:"Email verification failed"}}},async refreshSession(){if(!t.refreshSession)return this.getSession();try{const c=await t.refreshSession();if(c&&C.validateSessionStructure(c)){if(await A.setSession(c),n.onSessionUpdate){const l=await v(n.onSessionUpdate,c);if(l&&C.validateSessionStructure(l)){if(await A.setSession(l),n.onTokenRefresh){const d=await this.getSession();d&&await v(n.onTokenRefresh,d,l)}return l}}if(n.onTokenRefresh){const l=await this.getSession();l&&await v(n.onTokenRefresh,l,c)}return c}else if(c&&!C.validateSessionStructure(c))return await A.clearSessionCookie(),A.clearCache(),null;return null}catch(c){return await A.clearSessionCookie(),A.clearCache(),n.onError&&await v(n.onError,c instanceof Error?c:new Error(String(c)),"refreshSession"),null}},async oauthCallback(c,l,d){if(!f.oauthCallback)throw new Error("OAuth callback is not configured. Either provide oauthCallback action, or configure providers.oauth in config.");if(!l||!d)return{success:!1,error:"Missing required OAuth parameters (code or state)",errorCode:h.AuthErrorCode.VALIDATION_ERROR};let k=c;if(!k){const P=await Promise.resolve(u.get(d));if(P&&P.provider)k=P.provider;else return{success:!1,error:"Provider is required and could not be extracted from state",errorCode:h.AuthErrorCode.VALIDATION_ERROR}}if(!await p(d,k))return{success:!1,error:"Invalid or expired state parameter",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{return await f.oauthCallback(k,l,d)}catch(P){return n.onError&&await v(n.onError,P instanceof Error?P:new Error(String(P)),"oauthCallback"),{success:!1,error:P instanceof Error?P.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}},async verify2FA(c,l){if(!t.verify2FA)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const d=await t.verify2FA(c);if(d.success&&d.session&&!(l!=null&&l.skipCookieSave)){const k=await S(d);k.success||(process.env.NODE_ENV==="development"&&I.debug("Failed to save session cookie after verify2FA",{error:k.error,warning:k.warning}),n.onError&&await v(n.onError,new Error(k.warning||k.error||"Failed to save session cookie"),"verify2FA.setSession"))}return d}catch(d){return n.onError&&await v(n.onError,d instanceof Error?d:new Error(String(d)),"verify2FA"),{success:!1,error:d instanceof Error?d.message:"2FA verification failed",errorCode:h.AuthErrorCode.TWO_FA_REQUIRED}}},async setSession(c){return await A.setSession(c)},_getSessionConfig(){return A.getSessionConfig()},_getCallbacks(){return n},async storeOAuthState(c,l){await w(c,l)},passkey:t.passkey?{register:t.passkey.register,authenticate:async c=>{var l;if(!((l=t.passkey)!=null&&l.authenticate))throw new Error("PassKey authenticate is not configured.");try{const d=await t.passkey.authenticate(c);return d.success&&d.session&&await S(d),d}catch(d){return n.onError&&await v(n.onError,d instanceof Error?d:new Error(String(d)),"passkey.authenticate"),{success:!1,error:d instanceof Error?d.message:"PassKey authentication failed"}}},list:t.passkey.list?async()=>{var l;if(!((l=t.passkey)!=null&&l.list))throw new Error("PassKey list is not configured.");return[...await t.passkey.list()]}:void 0,remove:t.passkey.remove}:void 0,twoFactor:t.twoFactor?{enable:t.twoFactor.enable,verify:t.twoFactor.verify,disable:t.twoFactor.disable,generateBackupCodes:t.twoFactor.generateBackupCodes,isEnabled:t.twoFactor.isEnabled,verify2FA:async c=>{var d;const l=((d=t.twoFactor)==null?void 0:d.verify2FA)||t.verify2FA;if(!l)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const k=await l(c);if(k.success&&k.session){const N=await S(k);N.success||(process.env.NODE_ENV==="development"&&I.debug("Failed to save session cookie after twoFactor.verify2FA",{error:N.error,warning:N.warning}),n.onError&&await v(n.onError,new Error(N.warning||N.error||"Failed to save session cookie"),"twoFactor.verify2FA.setSession"))}return k}catch(k){return n.onError&&await v(n.onError,k instanceof Error?k:new Error(String(k)),"twoFactor.verify2FA"),{success:!1,error:k instanceof Error?k.message:"2FA verification failed",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}}}:void 0,signInMethods:{email:c=>g.email(c),oauth:c=>{var l;return((l=g.oauth)==null?void 0:l.call(g,c))||Promise.reject(new Error("OAuth not configured"))},passkey:c=>{var l;return((l=g.passkey)==null?void 0:l.call(g,c))||Promise.reject(new Error("Passkey not configured"))},otp:(c,l)=>{var d;return((d=g.otp)==null?void 0:d.call(g,c,l))||Promise.reject(new Error("OTP not configured"))}}};if(t.refreshSession){const c=_r(async()=>await _.refreshSession(),async()=>await _.signOut(),async()=>{await A.clearSessionCookie(),A.clearCache()},{...i,onTokenRefreshed:i.onTokenRefreshed,onTokenRefreshFailed:i.onTokenRefreshFailed,onBeforeRedirect:i.onBeforeRedirect});_._tokenRefreshManager=c,_._getTokenRefreshManager=()=>c}return _}function Hr(e){return{GET:async r=>Q(r,e,"GET"),POST:async r=>Q(r,e,"POST")}}async function Q(e,r,t){const n=new URL(e.url),o=qr(n.pathname),s=o.split("/").filter(Boolean);try{return t==="GET"?await Wr(e,r,o,s,n):t==="POST"?await Br(e,r,o,s,n):O("Method not allowed",405)}catch(i){return O(i instanceof Error?i.message:"Request failed",500)}}function qr(e){return e.replace(/^\/api\/auth/,"")||"/session"}async function Wr(e,r,t,n,o){if(t==="/session"||t==="/"){const s=await r.getSession();return E.NextResponse.json({session:s})}return t==="/providers"?E.NextResponse.json({providers:{email:!!r.signIn.email,oauth:!!r.signIn.oauth,passkey:!!r.signIn.passkey}}):pe(t,n)?await me(e,r,t,n,o,"GET"):O("Not found",404)}async function Br(e,r,t,n,o){const s=await Gr(e);return t==="/sign-in"||n[0]==="sign-in"?await Xr(r,s):t==="/sign-up"||n[0]==="sign-up"?await Jr(r,s):t==="/sign-out"||n[0]==="sign-out"?await Yr(r):t==="/reset-password"||n[0]==="reset-password"?await Qr(r,s):t==="/verify-email"||n[0]==="verify-email"?await Zr(r,s):t==="/refresh"||n[0]==="refresh"?await et(r):pe(t,n)?await me(e,r,t,n,o,"POST",s):t.startsWith("/passkey")?await tt(r,t,n,s):t==="/verify-2fa"||n[0]==="verify-2fa"?await rt(r,s):t.startsWith("/two-factor")?await nt(r,n,s):O("Not found",404)}async function Gr(e){try{return await e.json()}catch{return{}}}function pe(e,r){return e==="/callback"||e.startsWith("/oauth/callback")||r[0]==="oauth"&&r[1]==="callback"||r[0]==="callback"}async function me(e,r,t,n,o,s,i){if(!r.oauthCallback)return s==="GET"?V(e.url,"oauth_not_configured"):O("OAuth callback is not configured",400);const a=Kr(n,o,i),u=(i==null?void 0:i.code)??o.searchParams.get("code"),f=(i==null?void 0:i.state)??o.searchParams.get("state");if(!u||!f)return s==="GET"?V(e.url,"oauth_missing_params"):O("Missing required OAuth parameters. Code and state are required.",400);try{const w=await r.oauthCallback(a??"",u,f);return s==="GET"?w.success?ot(e.url,o.searchParams.get("callbackUrl")):V(e.url,w.error??"oauth_failed"):E.NextResponse.json(w)}catch(w){return s==="GET"?V(e.url,w instanceof Error?w.message:"oauth_error"):O(w instanceof Error?w.message:"OAuth callback failed",500)}}function Kr(e,r,t){return t!=null&&t.provider?t.provider:e[0]==="callback"&&e[1]?e[1]:e[0]==="oauth"&&e[1]==="callback"&&e[2]?e[2]:r.searchParams.get("provider")}async function Xr(e,r){if(r.provider==="email"&&r.email&&r.password){const t={email:r.email,password:r.password},n=await e.signIn.email(t);return E.NextResponse.json(n)}if(r.provider==="oauth"&&r.providerName){if(!e.signIn.oauth)return O("OAuth is not configured",400);const t=await e.signIn.oauth(r.providerName);return E.NextResponse.json(t)}if(r.provider==="passkey"){if(!e.signIn.passkey)return O("PassKey is not configured",400);const t=await e.signIn.passkey(r.options);return E.NextResponse.json(t)}return O("Invalid sign in request",400)}async function Jr(e,r){if(!e.signUp)return O("Sign up is not configured",400);const t=await e.signUp(r);return E.NextResponse.json(t)}async function Yr(e){const r=await e.signOut();return E.NextResponse.json(r)}async function Qr(e,r){if(!e.resetPassword)return O("Password reset is not configured",400);if(!r.email||typeof r.email!="string")return O("Email is required",400);const t=await e.resetPassword(r.email);return E.NextResponse.json(t)}async function Zr(e,r){if(!e.verifyEmail)return O("Email verification is not configured",400);if(!r.token||typeof r.token!="string")return O("Token is required",400);const t=await e.verifyEmail(r.token);return E.NextResponse.json(t)}async function et(e){if(!e.refreshSession){const t=await e.getSession();return E.NextResponse.json({session:t})}const r=await e.refreshSession();return E.NextResponse.json({session:r})}async function rt(e,r){if(!e.verify2FA)return O("2FA verification is not configured",400);if(!r.email||!r.userId||!r.code)return O("Missing required parameters. Email, userId, and code are required.",400);const t={email:r.email,userId:r.userId,code:r.code},n=await e.verify2FA(t);return E.NextResponse.json(n)}async function tt(e,r,t,n){if(!e.passkey)return O("PassKey is not configured",400);const o=t[1];if(o==="register"&&e.passkey.register){const s=await e.passkey.register(n.options);return E.NextResponse.json(s)}if(o==="list"&&e.passkey.list){const s=await e.passkey.list();return E.NextResponse.json(s)}if(o==="remove"&&e.passkey.remove){if(!n.passkeyId||typeof n.passkeyId!="string")return O("Passkey ID is required",400);const s=await e.passkey.remove(n.passkeyId);return E.NextResponse.json(s)}return O("Invalid Passkey request",400)}async function nt(e,r,t){if(!e.twoFactor)return O("Two-Factor Authentication is not configured",400);const n=r[1];if(n==="enable"&&e.twoFactor.enable){const o=await e.twoFactor.enable();return E.NextResponse.json(o)}if(n==="verify"&&e.twoFactor.verify){if(!t.code||typeof t.code!="string")return O("Code is required",400);const o=await e.twoFactor.verify(t.code);return E.NextResponse.json(o)}if(n==="disable"&&e.twoFactor.disable){const o=await e.twoFactor.disable();return E.NextResponse.json(o)}if(n==="backup-codes"&&e.twoFactor.generateBackupCodes){const o=await e.twoFactor.generateBackupCodes();return E.NextResponse.json(o)}if(n==="is-enabled"&&e.twoFactor.isEnabled){const o=await e.twoFactor.isEnabled();return E.NextResponse.json({enabled:o})}return O("Invalid two-factor request",400)}function O(e,r){return E.NextResponse.json({success:!1,error:e},{status:r})}function V(e,r){return E.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(r)}`,e))}function ot(e,r){const t=r??"/";return E.NextResponse.redirect(new URL(t,e))}function st(e){return async r=>{const{method:t,nextUrl:n}=r,s=n.pathname.replace(/^\/api\/auth/,"")||"/";try{let i;if(t!=="GET"&&t!=="HEAD")try{i=await r.json()}catch{}const a=Object.fromEntries(n.searchParams.entries()),u=await fetch(`${process.env.NEXT_PUBLIC_API_URL||""}/api/auth${s}${Object.keys(a).length>0?`?${new URLSearchParams(a).toString()}`:""}`,{method:t,headers:{"Content-Type":"application/json",...Object.fromEntries(r.headers.entries())},body:i?JSON.stringify(i):void 0}),f=await u.json();return E.NextResponse.json(f,{status:u.status,headers:{...Object.fromEntries(u.headers.entries())}})}catch(i){return console.error("API handler error:",i),E.NextResponse.json({success:!1,error:i instanceof Error?i.message:"Internal server error"},{status:500})}}}function it(e){return async r=>{const{searchParams:t}=r.nextUrl,n=t.get("provider"),o=t.get("code"),s=t.get("state");if(!n||!o||!s)return E.NextResponse.redirect(new URL("/login?error=oauth_missing_params",r.url));try{if(!e.oauthCallback)return E.NextResponse.redirect(new URL("/login?error=oauth_not_configured",r.url));const i=await e.oauthCallback(n,o,s);if(i.success){const a=t.get("callbackUrl")||"/";return E.NextResponse.redirect(new URL(a,r.url))}else{const a=i.errorCode?`${encodeURIComponent(i.error||"oauth_failed")}&code=${i.errorCode}`:encodeURIComponent(i.error||"oauth_failed");return E.NextResponse.redirect(new URL(`/login?error=${a}`,r.url))}}catch(i){return process.env.NODE_ENV==="development"&&console.error("[Mulguard] OAuth callback error:",i),E.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(i instanceof Error?i.message:"oauth_error")}`,r.url))}}}function x(e,r){const t=H({"X-Frame-Options":"SAMEORIGIN"});for(const[n,o]of Object.entries(t))o&&typeof o=="string"&&r.headers.set(n,o);return r}function at(){return async e=>{const r=E.NextResponse.next();return x(e,r)}}function ct(e,r={}){const{protectedRoutes:t=[],publicRoutes:n=[],redirectTo:o="/login",redirectIfAuthenticated:s}=r;return async i=>{const{pathname:a}=i.nextUrl,u=t.some(p=>a.startsWith(p));let f=null;try{f=await e.getSession()}catch(p){console.error("Middleware: Failed to get session:",p)}if(u&&!f){const p=i.nextUrl.clone();return p.pathname=o,p.searchParams.set("callbackUrl",a),E.NextResponse.redirect(p)}if(s&&f&&(a.startsWith("/login")||a.startsWith("/register"))){const R=i.nextUrl.clone();R.pathname=s;const v=E.NextResponse.redirect(R);return x(i,v)}const w=E.NextResponse.next();return x(i,w)}}async function ut(e,r){var t;try{const n=await e.getSession();return n?((t=n.user.roles)==null?void 0:t.includes(r))??!1:!1}catch{return!1}}function lt(e){const{auth:r,protectedRoutes:t=[],publicRoutes:n=[],redirectTo:o="/login",redirectIfAuthenticated:s,apiPrefix:i="/api/auth"}=e;return async a=>{const{pathname:u}=a.nextUrl;if(u.startsWith(i)){const R=E.NextResponse.next();return x(a,R)}const f=t.some(R=>u.startsWith(R));let w=null;if(f||s)try{w=await r.getSession()}catch(R){console.error("Middleware: Failed to get session:",R)}if(f&&!w){const R=a.nextUrl.clone();R.pathname=o,R.searchParams.set("callbackUrl",u);const v=E.NextResponse.redirect(R);return x(a,v)}if(s&&w&&(u.startsWith("/login")||u.startsWith("/register"))){const v=a.nextUrl.clone();v.pathname=s;const A=E.NextResponse.redirect(v);return x(a,A)}const p=E.NextResponse.next();return x(a,p)}}async function ft(e,r){var t;try{const n=await e.getSession();return n?((t=n.user.roles)==null?void 0:t.includes(r))??!1:!1}catch{return!1}}exports.buildCookieOptions=h.buildCookieOptions;exports.deleteCookie=h.deleteCookie;exports.getCookie=h.getCookie;exports.setCookie=h.setCookie;exports.signInEmailAction=h.signInEmailAction;exports.signOutAction=h.signOutAction;exports.signUpAction=h.signUpAction;exports.verify2FAAction=h.verify2FAAction;exports.createServerAuthMiddleware=C.createAuthMiddleware;exports.createServerHelpers=C.createServerHelpers;exports.createServerUtils=C.createServerUtils;exports.createSessionManager=C.createSessionManager;exports.deleteOAuthStateCookie=C.deleteOAuthStateCookie;exports.getCurrentUser=C.getCurrentUser;exports.getOAuthStateCookie=C.getOAuthStateCookie;exports.getServerSession=C.getServerSession;exports.getSessionTimeUntilExpiry=C.getSessionTimeUntilExpiry;exports.isSessionExpiredNullable=C.isSessionExpiredNullable;exports.isSessionExpiringSoon=C.isSessionExpiringSoon;exports.isSessionValid=C.isSessionValid;exports.refreshSession=C.refreshSession;exports.requireAuth=C.requireAuth;exports.requireRole=C.requireRole;exports.requireServerAuthMiddleware=C.requireAuthMiddleware;exports.requireServerRoleMiddleware=C.requireRoleMiddleware;exports.storeOAuthStateCookie=C.storeOAuthStateCookie;exports.validateSessionStructure=C.validateSessionStructure;exports.CSRFProtection=ne;exports.DEFAULT_SECURITY_HEADERS=ee;exports.MemoryCSRFStore=te;exports.MemoryOAuthStateStore=he;exports.RateLimiter=Z;exports.applySecurityHeaders=Te;exports.buildOAuthAuthorizationUrl=ue;exports.checkRole=ut;exports.checkRoleProxy=ft;exports.containsXSSPattern=Ze;exports.createApiHandler=st;exports.createAuthMiddleware=ct;exports.createCSRFProtection=Je;exports.createCookieOAuthStateStore=de;exports.createMemoryOAuthStateStore=ge;exports.createNextJsCookieOAuthStateStore=vr;exports.createOAuthCallbackHandler=it;exports.createProxyMiddleware=lt;exports.createRateLimiter=Oe;exports.createRedisOAuthStateStore=Rr;exports.createSecurityMiddleware=at;exports.escapeHTML=oe;exports.exchangeOAuthCode=le;exports.generateCSRFToken=ie;exports.generateToken=B;exports.getErrorCode=ir;exports.getErrorMessage=sr;exports.getOAuthUserInfo=fe;exports.getProviderMetadata=z;exports.getSecurityHeaders=H;exports.getUserFriendlyError=lr;exports.hasErrorCode=cr;exports.isAuthError=ae;exports.isAuthSuccess=ar;exports.isOAuthProviderConfig=yr;exports.isRetryableError=ur;exports.isSupportedProvider=dr;exports.isTwoFactorRequired=or;exports.isValidCSRFToken=er;exports.isValidEmail=nr;exports.isValidInput=Xe;exports.isValidName=Ve;exports.isValidPassword=De;exports.isValidToken=Ge;exports.isValidURL=$e;exports.mulguard=$r;exports.sanitizeHTML=Ye;exports.sanitizeInput=rr;exports.sanitizeUserInput=Qe;exports.signIn=fr;exports.toNextJsHandler=Hr;exports.validateAndSanitizeEmail=q;exports.validateAndSanitizeInput=W;exports.validateAndSanitizeName=Me;exports.validateAndSanitizePassword=be;exports.validateCSRFToken=G;exports.validateToken=Be;exports.validateURL=je;exports.withSecurityHeaders=x;
1
+ "use strict";var Ve=Object.create;var W=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var je=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var Be=(e,r,t)=>r in e?W(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var $e=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of ze(r))!He.call(e,s)&&s!==t&&W(e,s,{get:()=>r[s],enumerable:!(n=Me(r,s))||n.enumerable});return e};var G=(e,r,t)=>(t=e!=null?Ve(je(e)):{},$e(r||!e||!e.__esModule?W(t,"default",{value:e,enumerable:!0}):t,e));var P=(e,r,t)=>Be(e,typeof r!="symbol"?r+"":r,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("../actions-CMtg7FGv.js"),C=require("../oauth-state-Drwz6fES.js"),v=require("next/server"),L=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function qe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Y(e,...r){if(!qe(e))throw new Error("Uint8Array expected");if(r.length>0&&!r.includes(e.length))throw new Error("Uint8Array expected of length "+r+", got length="+e.length)}function le(e,r=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(r&&e.finished)throw new Error("Hash#digest() has already been called")}function We(e,r){Y(e);const t=r.outputLen;if(e.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function X(...e){for(let r=0;r<e.length;r++)e[r].fill(0)}function K(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function N(e,r){return e<<32-r|e>>>r}function Ge(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function he(e){return typeof e=="string"&&(e=Ge(e)),Y(e),e}class Ke{}function Xe(e){const r=n=>e().update(he(n)).digest(),t=e();return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=()=>e(),r}function ge(e=32){if(L&&typeof L.getRandomValues=="function")return L.getRandomValues(new Uint8Array(e));if(L&&typeof L.randomBytes=="function")return Uint8Array.from(L.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}class pe{constructor(r){P(this,"attempts",new Map);P(this,"config");this.config=r}check(r){const t=Date.now(),n=this.attempts.get(r);return!n||n.resetAt<t?(this.attempts.set(r,{count:1,resetAt:t+this.config.windowMs}),{allowed:!0,remaining:this.config.maxAttempts-1,resetAt:new Date(t+this.config.windowMs)}):n.count>=this.config.maxAttempts?{allowed:!1,remaining:0,resetAt:new Date(n.resetAt)}:(n.count++,{allowed:!0,remaining:this.config.maxAttempts-n.count,resetAt:new Date(n.resetAt)})}reset(r){this.attempts.delete(r)}clear(){this.attempts.clear()}}function Je(e){return new pe(e)}const we={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","X-XSS-Protection":"1; mode=block","Strict-Transport-Security":"max-age=31536000; includeSubDomains","Content-Security-Policy":"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';","Referrer-Policy":"strict-origin-when-cross-origin","Permissions-Policy":"geolocation=(), microphone=(), camera=()"};function Q(e){return{...we,...e}}function Ye(e,r){const t=Q(r);for(const[n,s]of Object.entries(t))s&&e.set(n,s)}const Qe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ze=254;function Z(e){var t;if(typeof e!="string"||!e)return{valid:!1,error:"Email is required"};const r=e.trim().toLowerCase();return Qe.test(r)?r.length>Ze?{valid:!1,error:"Email is too long"}:r.includes("..")||r.startsWith(".")||r.endsWith(".")?{valid:!1,error:"Invalid email format"}:(t=r.split("@")[1])!=null&&t.includes("..")?{valid:!1,error:"Invalid email format"}:{valid:!0,sanitized:r}:{valid:!1,error:"Invalid email format"}}function Ee(e){return e.valid===!0&&e.sanitized!==void 0}const er=new Set(["password","12345678","qwerty","abc123","password123","123456789","1234567890","letmein","welcome","monkey","dragon","master","sunshine","princess","football","admin","root","test","guest","user"]),rr=/012|123|234|345|456|567|678|789|abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz/i,tr=8,nr=128;function sr(e,r=tr){if(typeof e!="string"||!e)return{valid:!1,error:"Password is required"};if(e.length<r)return{valid:!1,error:`Password must be at least ${r} characters`};if(e.length>nr)return{valid:!1,error:"Password is too long"};const t=e.toLowerCase();if(er.has(t))return{valid:!1,error:"Password is too common"};if(/(.)\1{3,}/.test(e))return{valid:!1,error:"Password contains too many repeated characters"};if(rr.test(e))return{valid:!1,error:"Password contains sequential characters"};const n=or(e);return{valid:!0,sanitized:e,strength:n}}function or(e){let r=0;return e.length>=12?r+=2:e.length>=8&&(r+=1),/[a-z]/.test(e)&&(r+=1),/[A-Z]/.test(e)&&(r+=1),/[0-9]/.test(e)&&(r+=1),/[^a-zA-Z0-9]/.test(e)&&(r+=1),r>=5?"strong":r>=3?"medium":"weak"}function ir(e){return e.valid===!0&&e.sanitized!==void 0}const ar=100;function cr(e){if(typeof e!="string"||!e)return{valid:!1,error:"Name is required"};const r=e.trim();if(r.length<1)return{valid:!1,error:"Name cannot be empty"};if(r.length>ar)return{valid:!1,error:"Name is too long"};const t=r.replace(/[<>"']/g,"");return t.length===0?{valid:!1,error:"Name contains only invalid characters"}:{valid:!0,sanitized:t}}function ur(e){return e.valid===!0&&e.sanitized!==void 0}const lr=new Set(["http:","https:"]);function fr(e){if(typeof e!="string"||!e)return{valid:!1,error:"URL is required"};try{const r=new URL(e);return lr.has(r.protocol)?{valid:!0,sanitized:e}:{valid:!1,error:"URL must use http or https protocol"}}catch{return{valid:!1,error:"Invalid URL format"}}}function dr(e){return e.valid===!0&&e.sanitized!==void 0}const hr=16,gr=512,pr=/^[A-Za-z0-9_-]+$/;function wr(e,r=hr){return typeof e!="string"||!e?{valid:!1,error:"Token is required"}:e.length<r?{valid:!1,error:"Token is too short"}:e.length>gr?{valid:!1,error:"Token is too long"}:pr.test(e)?/(.)\1{10,}/.test(e)?{valid:!1,error:"Token contains suspicious pattern"}:{valid:!0,sanitized:e}:{valid:!1,error:"Invalid token format"}}function Er(e){return e.valid===!0&&e.sanitized!==void 0}const mr=1e3;function ee(e,r){const{maxLength:t=mr,allowHtml:n=!1,required:s=!0}=r??{};if(s&&(typeof e!="string"||!e||e.trim().length===0))return{valid:!1,error:"Input is required"};if(typeof e!="string"||!e)return{valid:!0,sanitized:""};let o=e.trim();return o.length>t?{valid:!1,error:`Input must be less than ${t} characters`}:(n||(o=o.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;")),o=o.replace(/[\x00-\x1F\x7F]/g,""),{valid:!0,sanitized:o})}function yr(e){return e.valid===!0&&e.sanitized!==void 0}class me{constructor(){P(this,"tokens",new Map)}get(r){const t=this.tokens.get(r);return t?t.expiresAt<Date.now()?(this.delete(r),null):t.value:null}set(r,t,n=36e5){this.tokens.set(r,{value:t,expiresAt:Date.now()+n})}delete(r){this.tokens.delete(r)}clear(){this.tokens.clear()}}class ye{constructor(r,t=32){P(this,"store");P(this,"tokenLength");this.store=r||new me,this.tokenLength=t}generateToken(r,t){const n=re(this.tokenLength);return this.store.set(r,n,t),n}validateToken(r,t){const n=this.store.get(r);if(!n)return!1;const s=ne(t,n);return s&&this.store.delete(r),s}getToken(r){return this.store.get(r)}deleteToken(r){this.store.delete(r)}}function Ar(e){return new ye(e)}function Ae(e){if(typeof e!="string")return"";const r={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return e.replace(/[&<>"']/g,t=>r[t]||t)}function Sr(e){return typeof e!="string"?"":e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript:/gi,"")}function kr(e){return typeof e!="string"?"":Ae(e.trim())}function vr(e){return typeof e!="string"?!1:[/<script/i,/javascript:/i,/on\w+\s*=/i,/<iframe/i,/<object/i,/<embed/i,/<link/i,/<meta/i,/expression\s*\(/i,/vbscript:/i].some(t=>t.test(e))}const Se=32;function re(e=Se){if(e<1||e>256)throw new Error("Token length must be between 1 and 256 bytes");const r=ge(e);return Buffer.from(r).toString("base64url")}function te(){return re(Se)}function ne(e,r){if(typeof e!="string"||typeof r!="string"||!e||!r||e.length!==r.length)return!1;let t=0;for(let n=0;n<e.length;n++)t|=e.charCodeAt(n)^r.charCodeAt(n);return t===0}function Rr(e,r){return ne(e,r)}function Cr(e){return typeof e!="string"?"":e.trim().replace(/[<>]/g,"")}const xr=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Or(e){return typeof e=="string"&&xr.test(e)}function ke(e){return!e.success&&!!e.error}function Tr(e){return e.requires2FA===!0||e.errorCode===g.AuthErrorCode.TWO_FA_REQUIRED}function _r(e,r){return e.error?e.error:r||"Authentication failed"}function br(e){return e.errorCode}function Ir(e){return e.success===!0&&!!e.user}function Pr(e,r){return e.errorCode===r}function Nr(e){if(!ke(e))return!1;const r=[g.AuthErrorCode.NETWORK_ERROR,g.AuthErrorCode.RATE_LIMITED,g.AuthErrorCode.UNKNOWN_ERROR];return e.errorCode?r.includes(e.errorCode):!1}function Ur(e){if(e.error)return e.error;switch(e.errorCode){case g.AuthErrorCode.INVALID_CREDENTIALS:return"Invalid email or password. Please try again.";case g.AuthErrorCode.ACCOUNT_LOCKED:return"Your account has been temporarily locked. Please try again later.";case g.AuthErrorCode.ACCOUNT_INACTIVE:return"Your account is inactive. Please contact support.";case g.AuthErrorCode.TWO_FA_REQUIRED:return"Two-factor authentication is required. Please enter your code.";case g.AuthErrorCode.INVALID_TWO_FA_CODE:return"Invalid two-factor authentication code. Please try again.";case g.AuthErrorCode.SESSION_EXPIRED:return"Your session has expired. Please sign in again.";case g.AuthErrorCode.UNAUTHORIZED:return"You are not authorized to perform this action.";case g.AuthErrorCode.NETWORK_ERROR:return"Network error. Please check your connection and try again.";case g.AuthErrorCode.VALIDATION_ERROR:return"Please check your input and try again.";case g.AuthErrorCode.RATE_LIMITED:return"Too many attempts. Please try again later.";case g.AuthErrorCode.UNKNOWN_ERROR:default:return"An unexpected error occurred. Please try again."}}async function Dr(e,r,t){return r==="credentials"?!t||!("email"in t)||!("password"in t)?{success:!1,error:"Credentials are required"}:e.signIn("credentials",t):r==="otp"?!t||!("email"in t)?{success:!1,error:"Email is required"}:e.signIn("otp",t):r==="passkey"?e.signIn("passkey",t):e.signIn(r)}const ve={google:{authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",userInfoUrl:"https://www.googleapis.com/oauth2/v2/userinfo",defaultScopes:["openid","profile","email"]},github:{authorizationUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",userInfoUrl:"https://api.github.com/user",defaultScopes:["user:email"]},apple:{authorizationUrl:"https://appleid.apple.com/auth/authorize",tokenUrl:"https://appleid.apple.com/auth/token",userInfoUrl:"https://appleid.apple.com/auth/userinfo",defaultScopes:["name","email"],defaultParams:{response_mode:"form_post",response_type:"code id_token"}},facebook:{authorizationUrl:"https://www.facebook.com/v18.0/dialog/oauth",tokenUrl:"https://graph.facebook.com/v18.0/oauth/access_token",userInfoUrl:"https://graph.facebook.com/v18.0/me?fields=id,name,email,picture",defaultScopes:["email","public_profile"]}};function $(e){return ve[e]??null}function Fr(e){return e in ve}function se(e,r,t,n){const s=$(e);if(!s)throw new Error(`Unknown OAuth provider: ${e}`);if(!r.clientId)throw new Error(`OAuth provider "${e}" is missing clientId`);const o=r.redirectUri??`${t}/api/auth/callback/${e}`,i=r.scopes??s.defaultScopes,a=new URLSearchParams({client_id:r.clientId,redirect_uri:o,response_type:"code",scope:Array.isArray(i)?i.join(" "):String(i),state:n});if(s.defaultParams)for(const[c,u]of Object.entries(s.defaultParams))a.append(c,u);if(r.params)for(const[c,u]of Object.entries(r.params))a.set(c,u);return`${s.authorizationUrl}?${a.toString()}`}async function oe(e,r,t,n,s){const o=$(e);if(!o)throw new Error(`Unknown OAuth provider: ${e}`);if(!t||typeof t!="string")throw new Error("Authorization code is required");if(!r.clientId)throw new Error(`OAuth provider "${e}" is missing clientId`);const i=new URLSearchParams({client_id:r.clientId,code:t,redirect_uri:n,grant_type:"authorization_code"});s&&i.append("code_verifier",s),r.clientSecret&&i.append("client_secret",r.clientSecret);try{const a=await fetch(o.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:i.toString()});if(!a.ok){const u=await a.text();let h=`Failed to exchange code for tokens: ${u}`;try{const f=JSON.parse(u);h=f.error_description??f.error??h}catch{}throw new Error(h)}const c=await a.json();if(!Lr(c))throw new Error("Invalid token exchange response format");return c}catch(a){throw a instanceof Error?a:new Error(`OAuth token exchange failed: ${String(a)}`)}}function Lr(e){return typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string"}async function q(e,r){const t=$(e);if(!t)throw new Error(`Unknown OAuth provider: ${e}`);if(!r||typeof r!="string")throw new Error("Access token is required");try{const n=await fetch(t.userInfoUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});if(!n.ok){const o=await n.text();let i=`Failed to fetch user info: ${o}`;try{const a=JSON.parse(o);i=a.error_description??a.error??i}catch{}throw new Error(i)}const s=await n.json();return Vr(e,s,r)}catch(n){throw n instanceof Error?n:new Error(`OAuth user info retrieval failed: ${String(n)}`)}}async function Vr(e,r,t){switch(e){case"google":return Mr(r);case"github":return await zr(r,t);case"apple":return jr(r);case"facebook":return Hr(r);default:return Br(r)}}function Mr(e){return{id:String(e.sub??e.id??""),email:String(e.email??""),name:String(e.name??""),avatar:typeof e.picture=="string"?e.picture:void 0,emailVerified:!!e.email_verified,rawProfile:e}}async function zr(e,r){let t=typeof e.email=="string"?e.email:void 0,n={...e};if(!t)try{const s=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${r}`}});if(s.ok){const o=await s.json(),i=o.find(a=>a.primary)??o[0];t=(i==null?void 0:i.email)??`${String(e.login??"user")}@users.noreply.github.com`,n={...e,emails:o}}else t=`${String(e.login??"user")}@users.noreply.github.com`}catch{t=`${String(e.login??"user")}@users.noreply.github.com`}return{id:String(e.id??""),email:t??"",name:String(e.name??e.login??""),avatar:typeof e.avatar_url=="string"?e.avatar_url:void 0,emailVerified:!!t,rawProfile:n}}function jr(e){const r=e.name,t=r?`${r.firstName??""} ${r.lastName??""}`.trim():"";return{id:String(e.sub??""),email:String(e.email??""),name:t,emailVerified:!!e.email_verified,rawProfile:e}}function Hr(e){var t;const r=e.picture;return{id:String(e.id??""),email:String(e.email??""),name:String(e.name??""),avatar:(t=r==null?void 0:r.data)==null?void 0:t.url,emailVerified:!0,rawProfile:e}}function Br(e){return{id:String(e.id??e.sub??""),email:String(e.email??""),name:String(e.name??e.display_name??e.username??""),avatar:typeof e.avatar=="string"?e.avatar:typeof e.picture=="string"?e.picture:typeof e.avatar_url=="string"?e.avatar_url:void 0,emailVerified:!!(e.email_verified??e.emailVerified??!1),rawProfile:e}}function $r(e){return typeof e=="object"&&e!==null&&"clientId"in e&&typeof e.clientId=="string"}function qr(e,r,t,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(r,t,n);const s=BigInt(32),o=BigInt(4294967295),i=Number(t>>s&o),a=Number(t&o),c=n?4:0,u=n?0:4;e.setUint32(r+c,i,n),e.setUint32(r+u,a,n)}function Wr(e,r,t){return e&r^~e&t}function Gr(e,r,t){return e&r^e&t^r&t}class Kr extends Ke{constructor(r,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=r,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(r),this.view=K(this.buffer)}update(r){le(this),r=he(r),Y(r);const{view:t,buffer:n,blockLen:s}=this,o=r.length;for(let i=0;i<o;){const a=Math.min(s-this.pos,o-i);if(a===s){const c=K(r);for(;s<=o-i;i+=s)this.process(c,i);continue}n.set(r.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=r.length,this.roundClean(),this}digestInto(r){le(this),We(r,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:o}=this;let{pos:i}=this;t[i++]=128,X(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let f=i;f<s;f++)t[f]=0;qr(n,s-8,BigInt(this.length*8),o),this.process(n,0);const a=K(r),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,h[f],o)}digest(){const{buffer:r,outputLen:t}=this;this.digestInto(r);const n=r.slice(0,t);return this.destroy(),n}_cloneInto(r){r||(r=new this.constructor),r.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:o,destroyed:i,pos:a}=this;return r.destroyed=i,r.finished=o,r.length=s,r.pos=a,s%t&&r.buffer.set(n),r}clone(){return this._cloneInto()}}const U=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),D=new Uint32Array(64);class Jr extends Kr{constructor(r=32){super(64,r,8,!1),this.A=U[0]|0,this.B=U[1]|0,this.C=U[2]|0,this.D=U[3]|0,this.E=U[4]|0,this.F=U[5]|0,this.G=U[6]|0,this.H=U[7]|0}get(){const{A:r,B:t,C:n,D:s,E:o,F:i,G:a,H:c}=this;return[r,t,n,s,o,i,a,c]}set(r,t,n,s,o,i,a,c){this.A=r|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(r,t){for(let f=0;f<16;f++,t+=4)D[f]=r.getUint32(t,!1);for(let f=16;f<64;f++){const y=D[f-15],m=D[f-2],S=N(y,7)^N(y,18)^y>>>3,E=N(m,17)^N(m,19)^m>>>10;D[f]=E+D[f-7]+S+D[f-16]|0}let{A:n,B:s,C:o,D:i,E:a,F:c,G:u,H:h}=this;for(let f=0;f<64;f++){const y=N(a,6)^N(a,11)^N(a,25),m=h+y+Wr(a,c,u)+Xr[f]+D[f]|0,E=(N(n,2)^N(n,13)^N(n,22))+Gr(n,s,o)|0;h=u,u=c,c=a,a=i+m|0,i=o,o=s,s=n,n=m+E|0}n=n+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(n,s,o,i,a,c,u,h)}roundClean(){X(D)}destroy(){this.set(0,0,0,0,0,0,0,0),X(this.buffer)}}const Yr=Xe(()=>new Jr),Qr=Yr,Re=43;function Ce(e=Re){if(e<43||e>128)throw new Error("Code verifier length must be between 43 and 128 characters");const r=ge(Math.ceil(e*.75));return Buffer.from(r).toString("base64url").substring(0,e)}function ie(e){if(!e||e.length<43||e.length>128)throw new Error("Invalid code verifier");const r=Qr(e);return Buffer.from(r).toString("base64url")}function xe(e=Re,r="S256"){const t=Ce(e),n=r==="S256"?ie(t):t;return{codeVerifier:t,codeChallenge:n,codeChallengeMethod:r}}function Zr(e,r,t="S256"){if(!e||!r)return{valid:!1,error:"Code verifier and challenge are required"};let n;if(t==="S256")try{n=ie(e)}catch(s){return{valid:!1,error:s instanceof Error?s.message:"Failed to generate expected challenge"}}else n=e;return et(r,n)?{valid:!0}:{valid:!1,error:"Code challenge verification failed"}}function et(e,r){if(e.length!==r.length)return!1;let t=0;for(let n=0;n<e.length;n++)t|=e.charCodeAt(n)^r.charCodeAt(n);return t===0}class Oe{constructor(){P(this,"storage",new Map)}async set(r,t,n){this.storage.set(r,{codeVerifier:t,expiresAt:Date.now()+n})}async get(r){const t=this.storage.get(r);return t?t.expiresAt<Date.now()?(this.storage.delete(r),null):t.codeVerifier:null}async delete(r){this.storage.delete(r)}}const rt="__mulguard_oauth_state",tt=10*60*1e3;function Te(e){const r=e.cookieName||rt,t=e.ttl||tt,n=process.env.NODE_ENV==="production",s=e.secure??n,o=e.sameSite||"strict",i=e.cookieHandler,a=c=>({httpOnly:!0,secure:s,sameSite:o,maxAge:Math.floor(c/1e3),path:"/"});return{async set(c,u,h){const f=JSON.stringify({state:c,provider:u.provider,expiresAt:u.expiresAt});await Promise.resolve(i.setCookie(r,f,a(t)))},async get(c){const u=await Promise.resolve(i.getCookie(r));if(!u)return null;try{const h=JSON.parse(u);return h.state!==c?null:h.expiresAt<Date.now()?(await Promise.resolve(i.deleteCookie(r,{path:"/"})),null):{provider:h.provider,expiresAt:h.expiresAt}}catch{return await Promise.resolve(i.deleteCookie(r,{path:"/"})),null}},async delete(c){await this.get(c)&&await Promise.resolve(i.deleteCookie(r,{path:"/"}))},async cleanup(){}}}function nt(){return Te({cookieHandler:{async getCookie(e){var r;try{const{cookies:t}=await import("next/headers");return((r=(await t()).get(e))==null?void 0:r.value)||null}catch{return null}},async setCookie(e,r,t){try{const{cookies:n}=await import("next/headers");(await n()).set(e,r,{httpOnly:t.httpOnly??!0,secure:t.secure??process.env.NODE_ENV==="production",sameSite:t.sameSite||"strict",maxAge:t.maxAge,path:t.path||"/"})}catch(n){console.warn("[Mulguard] Failed to set OAuth state cookie:",n)}},async deleteCookie(e,r){try{const{cookies:t}=await import("next/headers");(await t()).set(e,"",{maxAge:0,expires:new Date(0),path:(r==null?void 0:r.path)||"/"})}catch{}}}})}function st(e,r="mulguard:oauth:state:"){const t=s=>`${r}${s}`,n=async s=>{const o=t(s);await e.del(o)};return{async set(s,o,i){const a=t(s),c=JSON.stringify(o);await e.set(a,c,"EX",Math.floor(i/1e3))},async get(s){const o=t(s),i=await e.get(o);if(!i)return null;try{const a=JSON.parse(i);return a.expiresAt<Date.now()?(await n(s),null):a}catch{return await n(s),null}},async delete(s){await n(s)},async cleanup(){try{const s=await e.keys(`${r}*`),o=Date.now();for(const i of s){const a=await e.get(i);if(a)try{JSON.parse(a).expiresAt<o&&await e.del(i)}catch{await e.del(i)}}}catch(s){console.warn("[Mulguard] OAuth state cleanup warning:",s)}}}}class _e{constructor(){P(this,"states",new Map)}set(r,t,n){this.states.set(r,t),this.cleanup()}get(r){const t=this.states.get(r);return t?t.expiresAt<Date.now()?(this.delete(r),null):t:null}delete(r){this.states.delete(r)}cleanup(){const r=Date.now();for(const[t,n]of this.states.entries())n.expiresAt<r&&this.states.delete(t)}}function be(){return new _e}class Ie{constructor(r){P(this,"config");P(this,"pkceStorage");var t,n;this.config={...r,pkce:{enabled:((t=r.pkce)==null?void 0:t.enabled)??!0,storage:(n=r.pkce)==null?void 0:n.storage},stateStore:r.stateStore,logger:r.logger},this.pkceStorage=this.config.pkce.enabled?this.config.pkce.storage||new Oe:null}async initiate(r){const t=this.config.providers[r];if(!t)throw new Error(`OAuth provider "${r}" is not configured`);const n=te();let s,o;if(this.config.pkce.enabled&&this.pkceStorage){const a=xe();s=a.codeVerifier,o=a.codeChallenge,await this.pkceStorage.set(n,s,10*60*1e3)}const i=se(r,{...t,params:{...t.params,...o&&{code_challenge:o,code_challenge_method:"S256"}}},this.config.baseUrl,n);return this.config.stateStore&&await this.config.stateStore.set(n,{provider:r,expiresAt:Date.now()+10*60*1e3},10*60*1e3),{url:i,state:n,...s&&{codeVerifier:s}}}async handleCallback(r,t,n,s,o,i){try{if(!t||!n)return{success:!1,error:"Authorization code and state are required",errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(!await this.validateState(n,r))return{success:!1,error:"Invalid or expired state token",errorCode:g.AuthErrorCode.VALIDATION_ERROR};const c=this.config.providers[r];if(!c)return{success:!1,error:`OAuth provider "${r}" is not configured`,errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(this.config.pkce.enabled&&this.pkceStorage){const E=s||await this.pkceStorage.get(n);if(!E)return{success:!1,error:"PKCE code verifier not found",errorCode:g.AuthErrorCode.VALIDATION_ERROR};s=E}const u=c.redirectUri||`${this.config.baseUrl}/api/auth/callback/${r}`;let h;try{h=await oe(r,c,t,u,s)}catch(E){return this.config.logger&&this.config.logger.error("OAuth token exchange failed",E),{success:!1,error:E instanceof Error?E.message:"Token exchange failed",errorCode:g.AuthErrorCode.NETWORK_ERROR}}let f;try{f=await q(r,h.access_token)}catch(E){return this.config.logger&&this.config.logger.error("OAuth user profile retrieval failed",E),{success:!1,error:"Failed to retrieve user profile",errorCode:g.AuthErrorCode.NETWORK_ERROR}}const y={id:f.id,email:f.email,name:f.name,avatar:f.avatar,emailVerified:f.emailVerified,provider:r,accessToken:h.access_token,refreshToken:h.refresh_token,tokens:h,rawProfile:f.rawProfile};let m;o?m=await o(y):m={id:y.id,email:y.email,name:y.name,avatar:y.avatar,emailVerified:y.emailVerified};const S=i?await i(m,y):{user:m,expiresAt:new Date(Date.now()+7*24*60*60*1e3),accessToken:h.access_token,refreshToken:h.refresh_token,tokenType:h.token_type||"Bearer",expiresIn:h.expires_in};return this.config.pkce.enabled&&this.pkceStorage&&await this.pkceStorage.delete(n),{success:!0,user:m,session:S}}catch(a){return this.config.logger&&this.config.logger.error("OAuth callback error",a),{success:!1,error:a instanceof Error?a.message:"OAuth callback failed",errorCode:g.AuthErrorCode.UNKNOWN_ERROR}}}async validateState(r,t){if(this.config.stateStore){const n=await this.config.stateStore.get(r);return n?n.expiresAt<Date.now()?(await this.config.stateStore.delete(r),!1):n.provider!==t?!1:(await this.config.stateStore.delete(r),!0):!1}return!0}}function ot(e){return new Ie(e)}function z(e){return e.success===!0&&e.user!==void 0&&e.session!==void 0}var M=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(M||{});const it=process.env.NODE_ENV==="development"?0:1;function Pe(e={}){const{enabled:r=process.env.NODE_ENV==="development",level:t=it,context:n,formatter:s=at}=e,o=a=>r&&a>=t,i=(a,c,u,h)=>({level:a,message:c,timestamp:new Date,context:n,data:u?ct(u):void 0,error:h});return{debug:(a,c)=>{if(o(0)){const u=i(0,a,c);console.debug(s(u))}},info:(a,c)=>{if(o(1)){const u=i(1,a,c);console.info(s(u))}},warn:(a,c)=>{if(o(2)){const u=i(2,a,c);console.warn(s(u))}},error:(a,c)=>{if(o(3)){const u=c instanceof Error?c:void 0,h=c instanceof Error?void 0:c,f=i(3,a,h,u);console.error(s(f)),u&&console.error(u)}}}}function at(e){const r=e.timestamp.toISOString(),t=M[e.level],n=e.context?`[${e.context}]`:"",s=e.data?` ${JSON.stringify(e.data)}`:"";return`${r} [${t}]${n} ${e.message}${s}`}function ct(e){const r=new Set(["password","token","secret","key","accessToken","refreshToken"]),t={};for(const[n,s]of Object.entries(e))if(r.has(n.toLowerCase()))t[n]="***REDACTED***";else if(typeof s=="string"&&n.toLowerCase().includes("email")){const o=s.split("@");if(o.length===2&&o[0]){const i=o[0].substring(0,3)+"***@"+o[1];t[n]=i}else t[n]=s}else t[n]=s;return t}Pe();function Ne(e={}){return Pe(e)}function ut(e={}){try{const r=require("pino"),t={level:e.level!==void 0?M[e.level].toLowerCase():"info",base:e.context?{context:e.context}:void 0,timestamp:!0},n=r(t);return{debug:(s,o)=>{n.debug(o||{},s)},info:(s,o)=>{n.info(o||{},s)},warn:(s,o)=>{n.warn(o||{},s)},error:(s,o)=>{o instanceof Error?n.error({err:o},s):n.error(o||{},s)}}}catch{return Ne(e)}}function lt(e={}){const{adapter:r="console",...t}=e;let n;if(typeof r=="string")switch(r){case"pino":n=ut(t);break;case"console":default:n=Ne(t);break}else n=r;return n}const T=lt({adapter:process.env.MULGUARD_LOGGER_ADAPTER||"console",level:process.env.NODE_ENV==="production"?M.WARN:M.DEBUG});function ft(e,r,t,n={}){const{enabled:s=!0,maxRetries:o=1,retryDelay:i=1e3,rateLimit:a=3,autoSignOutOnFailure:c=!0,redirectToLogin:u="/login",autoRedirectOnFailure:h=!0}=n;let f=null,y=!1;const m=[],S=[],E=60*1e3;let w=0,O=!1,_=null;const j=2,H=60*1e3;function l(){const k=Date.now();if(O&&_){if(k<_)return!1;O=!1,_=null,w=0}for(;S.length>0;){const A=S[0];if(A!==void 0&&A<k-E)S.shift();else break}return S.length>=a?!1:(S.push(k),!0)}function d(){w++,w>=j&&(O=!0,_=Date.now()+H,process.env.NODE_ENV==="development"&&console.warn("[TokenRefreshManager] Circuit breaker opened - too many consecutive failures"))}function p(){w=0,O=!1,_=null}async function R(k=1){if(!s)return null;if(!l())throw new Error("Rate limit exceeded for token refresh");try{const A=await e();if(A)return p(),b(A),n.onTokenRefreshed&&await Promise.resolve(n.onTokenRefreshed(A)),A;if(d(),k<o)return await ce(i*k),R(k+1);throw new Error("Token refresh failed: refresh function returned null")}catch(A){if(d(),k<o&&I(A))return await ce(i*k),R(k+1);throw A}}function I(k){if(k instanceof Error){const A=k.message.toLowerCase();if(A.includes("rate limit")||A.includes("too many requests")||A.includes("429")||A.includes("limit:")||A.includes("requests per minute")||A.includes("token_blacklisted")||A.includes("blacklisted")||A.includes("invalid")||A.includes("401")||A.includes("unauthorized")||A.includes("session has been revoked")||A.includes("session expired"))return!1;if(A.includes("network")||A.includes("fetch")||A.includes("timeout"))return!0}return!1}function b(k){const A=[...m];m.length=0;for(const{resolve:F}of A)F(k)}function ae(k){const A=[...m];m.length=0;for(const{reject:F}of A)F(k)}function ce(k){return new Promise(A=>setTimeout(A,k))}async function ue(k){try{if(n.onTokenRefreshFailed&&await Promise.resolve(n.onTokenRefreshFailed(k)),c&&(await t(),await r(),h&&typeof window<"u")){let A=!0;if(n.onBeforeRedirect&&(A=await Promise.resolve(n.onBeforeRedirect(k))),A){const F=new URL(u,window.location.origin);F.searchParams.set("reason","session_expired"),F.searchParams.set("redirect",window.location.pathname+window.location.search),window.location.href=F.toString()}}}catch(A){process.env.NODE_ENV==="development"&&console.error("[TokenRefreshManager] Error in handleRefreshFailure:",A)}}return{async refreshToken(){return s?f||(y=!0,f=R().then(k=>(y=!1,f=null,k)).catch(k=>{throw y=!1,f=null,ae(k),ue(k).catch(()=>{}),k}),f):null},isRefreshing(){return y},async waitForRefresh(){return f?new Promise((k,A)=>{m.push({resolve:k,reject:A})}):null},clear(){f=null,y=!1,S.length=0,p(),ae(new Error("Token refresh manager cleared"))},async handleRefreshFailure(k){return ue(k)}}}function dt(){const e=process.env.NODE_ENV==="production";return{cookieName:"__mulguard_session",expiresIn:60*60*24*7,httpOnly:!0,secure:e,sameSite:"lax",path:"/"}}function ht(){return{enabled:!0,refreshThreshold:300,maxRetries:0,retryDelay:1e3,rateLimit:1,autoSignOutOnFailure:!0,redirectToLogin:"/login",autoRedirectOnFailure:!0}}function gt(){return process.env.NEXT_PUBLIC_URL??(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:"http://localhost:3000")}function pt(e){const{sessionConfig:r,cacheTtl:t,getSessionAction:n,onSessionExpired:s,onError:o}=e,i=r.cookieName??"__mulguard_session";let a=null;const c=async()=>{const E=Date.now();if(a&&E-a.timestamp<t)return a.session;if(n)try{const w=await n();if(w&&C.validateSessionStructure(w))return a={session:w,timestamp:E},w;w&&!C.validateSessionStructure(w)&&(await h(),a=null)}catch(w){T.debug("getSession error",{error:w}),o&&await o(w instanceof Error?w:new Error(String(w)),"getSession"),a=null}try{const w=await g.getCookie(i);if(w)try{const O=JSON.parse(w);if(C.validateSessionStructure(O))return O.expiresAt&&new Date(O.expiresAt)<new Date?(s&&await s(O),await h(),a=null,null):(a={session:O,timestamp:E},O);await h(),a=null}catch{await h(),a=null}}catch(w){const O=w instanceof Error?w.message:String(w);!O.includes("request scope")&&!O.includes("cookies")&&(T.warn("getSession cookie error",{error:w}),o&&await o(w instanceof Error?w:new Error(String(w)),"getSession.cookie"))}return null},u=async E=>{if(!C.validateSessionStructure(E))return{success:!1,error:"Invalid session structure"};try{const w=typeof E=="object"&&"token"in E?String(E.token):JSON.stringify(E),O=g.buildCookieOptions(i,w,r),_=await g.setCookie(O);return _.success&&(a={session:E,timestamp:Date.now()}),_}catch(w){const O=w instanceof Error?w.message:"Failed to set session";return T.error("setSession error",{error:w}),o&&await o(w instanceof Error?w:new Error(String(w)),"setSession"),{success:!1,error:O}}},h=async()=>{try{await g.deleteCookie(i,{path:r.path,domain:r.domain}),a=null}catch(E){T.warn("clearSessionCookie error",{error:E})}},f=async()=>{const E=await c();return E!=null&&E.accessToken&&typeof E.accessToken=="string"?E.accessToken:null};return{getSession:c,setSession:u,clearSessionCookie:h,getAccessToken:f,getRefreshToken:async()=>{const E=await c();return E!=null&&E.refreshToken&&typeof E.refreshToken=="string"?E.refreshToken:null},hasValidTokens:async()=>!!await f(),clearCache:()=>{a=null},getSessionConfig:()=>({cookieName:i,config:r})}}function wt(e){return async r=>{try{if(!r||typeof r!="object")return{success:!1,error:"Invalid credentials",errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(!r.email||typeof r.email!="string")return{success:!1,error:"Email is required",errorCode:g.AuthErrorCode.VALIDATION_ERROR};const t=Z(r.email);if(!Ee(t))return{success:!1,error:t.error??"Invalid email format",errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(!r.password||typeof r.password!="string")return{success:!1,error:"Password is required",errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(r.password.length>128)return{success:!1,error:"Invalid credentials",errorCode:g.AuthErrorCode.VALIDATION_ERROR};const n={email:t.sanitized,password:r.password},s=await e.actions.signIn.email(n);if(z(s)){const o=await e.saveSessionAfterAuth(s);!o.success&&o.warning&&T.warn("Session save warning",{warning:o.warning})}return s.success?T.info("Sign in successful",{email:n.email.substring(0,3)+"***"}):T.warn("Sign in failed",{email:n.email.substring(0,3)+"***",errorCode:s.errorCode}),s}catch(t){const n=t instanceof Error?t.message:"Sign in failed";return T.error("Sign in error",{error:n,context:"signIn.email"}),e.onError&&await e.onError(t instanceof Error?t:new Error(String(t)),"signIn.email"),{success:!1,error:"Sign in failed. Please try again.",errorCode:g.AuthErrorCode.UNKNOWN_ERROR}}}}function Et(e,r){return async t=>{if(!t||typeof t!="string")throw new Error("Provider is required");const n=ee(t,{maxLength:50,allowHtml:!1,required:!0});if(!n.valid||!n.sanitized)throw new Error("Invalid provider");const s=n.sanitized.toLowerCase();if(!e.actions.signIn.oauth)throw new Error("OAuth sign in is not configured. Either provide oauth action in signIn, or configure providers.oauth in config.");const o=await e.actions.signIn.oauth(s);return await r(o.state,s),T.info("OAuth sign in initiated",{provider:s}),o}}function mt(e){return async(r,t)=>{if(!r||typeof r!="string")return{success:!1,error:"Email is required",errorCode:g.AuthErrorCode.VALIDATION_ERROR};const n=Z(r);if(!Ee(n))return{success:!1,error:n.error??"Invalid email format",errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(t!==void 0&&(typeof t!="string"||t.length<4||t.length>10))return{success:!1,error:"Invalid OTP code format",errorCode:g.AuthErrorCode.VALIDATION_ERROR};if(!e.actions.signIn.otp)return{success:!1,error:"OTP sign in is not configured",errorCode:g.AuthErrorCode.VALIDATION_ERROR};try{const s=await e.actions.signIn.otp(n.sanitized,t);if(z(s)){const o=await e.saveSessionAfterAuth(s);!o.success&&o.warning&&T.warn("Session save warning",{warning:o.warning})}return s.success?T.info("OTP sign in successful",{email:n.sanitized.substring(0,3)+"***"}):T.warn("OTP sign in failed",{email:n.sanitized.substring(0,3)+"***"}),s}catch(s){return T.error("OTP sign in error",{error:s instanceof Error?s.message:"Unknown error",context:"signIn.otp"}),e.onError&&await e.onError(s instanceof Error?s:new Error(String(s)),"signIn.otp"),{success:!1,error:"OTP sign in failed. Please try again.",errorCode:g.AuthErrorCode.UNKNOWN_ERROR}}}}function yt(e){return async r=>{if(!e.actions.signIn.passkey)throw new Error("PassKey sign in is not configured. Provide passkey action in signIn.");try{const t=await e.actions.signIn.passkey(r);if(z(t)){const n=await e.saveSessionAfterAuth(t);!n.success&&n.warning&&T.warn("Session save warning",{warning:n.warning})}return t}catch(t){return e.onError&&await e.onError(t instanceof Error?t:new Error(String(t)),"signIn.passkey"),{success:!1,error:t instanceof Error?t.message:"PassKey sign in failed"}}}}function At(e,r){const t=wt(e),n=Et(e,r),s=mt(e),o=yt(e);return Object.assign(async(c,u)=>{if(!c||typeof c!="string")throw new Error("Provider is required");const h=ee(c,{maxLength:50,allowHtml:!1,required:!0});if(!h.valid||!h.sanitized)throw new Error("Invalid provider");const f=h.sanitized.toLowerCase();if(f==="google"||f==="github"||f==="apple"||f==="facebook"||typeof f=="string"&&!["credentials","otp","passkey"].includes(f))return n(f);if(f==="credentials")return!u||!("email"in u)||!("password"in u)?{success:!1,error:"Credentials are required",errorCode:g.AuthErrorCode.VALIDATION_ERROR}:t(u);if(f==="otp"){if(!u||!("email"in u))return{success:!1,error:"Email is required",errorCode:g.AuthErrorCode.VALIDATION_ERROR};const y=u;return s(y.email,y.code)}return f==="passkey"?o(u):{success:!1,error:"Invalid provider",errorCode:g.AuthErrorCode.VALIDATION_ERROR}},{email:t,oauth:e.actions.signIn.oauth?n:void 0,passkey:e.actions.signIn.passkey?o:void 0,otp:e.actions.signIn.otp?s:void 0})}function St(e){return async r=>{if(!e.actions.signUp)throw new Error("Sign up is not configured. Provide signUp action in config.");try{const t=await e.actions.signUp(r);if(z(t)){const n=await e.saveSessionAfterAuth(t);!n.success&&n.warning&&T.warn("Session save warning",{warning:n.warning})}return t}catch(t){return e.onError&&await e.onError(t instanceof Error?t:new Error(String(t)),"signUp"),{success:!1,error:t instanceof Error?t.message:"Sign up failed"}}}}function kt(e,r){return async(t,n,s)=>{const o=e.oauthProviders[t];if(!o)return{success:!1,error:`OAuth provider "${t}" is not configured`,errorCode:g.AuthErrorCode.VALIDATION_ERROR};try{const i=o.redirectUri??`${e.baseUrl}/api/auth/callback/${t}`,a=await oe(t,o,n,i),c=await q(t,a.access_token),u={id:c.id,email:c.email,name:c.name,avatar:c.avatar,emailVerified:c.emailVerified,provider:t,accessToken:a.access_token,refreshToken:a.refresh_token,tokens:{access_token:a.access_token,refresh_token:a.refresh_token,expires_in:a.expires_in,token_type:a.token_type,id_token:a.id_token},rawProfile:c.rawProfile};if(e.callbacks.onOAuthUser){const h=await fe(e.callbacks.onOAuthUser,[u,t],e.onError);if(!h)return{success:!1,error:"Failed to create or retrieve user",errorCode:g.AuthErrorCode.VALIDATION_ERROR};const f=e.createSession(h,u,a);return await e.saveSession(f),e.callbacks.onSignIn&&await fe(e.callbacks.onSignIn,[f.user,f],e.onError),{success:!0,user:f.user,session:f}}return{success:!1,error:"OAuth user callback not implemented. Provide onOAuthUser callback or implement oauthCallback action.",errorCode:g.AuthErrorCode.VALIDATION_ERROR}}catch(i){return T.error("OAuth callback failed",{provider:t,error:i}),{success:!1,error:i instanceof Error?i.message:"OAuth callback failed",errorCode:g.AuthErrorCode.NETWORK_ERROR}}}}async function fe(e,r,t){if(e)try{return await e(...r)}catch(n){throw t&&await t(n instanceof Error?n:new Error(String(n)),"callback"),n}}function vt(e,r,t,n){if(Object.keys(e).length!==0)return async s=>{const o=e[s];if(!o)throw new Error(`OAuth provider "${s}" is not configured. Add it to providers.oauth in config.`);if(!o.clientId)throw new Error(`OAuth provider "${s}" is missing clientId`);const i=t();return{url:n(s,o,r,i),state:i}}}function Rt(e){var j,H;const r={...dt(),...e.session},t=e.actions,n=e.callbacks||{},s=((j=e.providers)==null?void 0:j.oauth)||{},o=gt(),i={...ht(),...e.tokenRefresh},a=((H=e.session)==null?void 0:H.cacheTtl)??e.sessionCacheTtl??5e3,c=e.oauthStateStore||be(),u={...t},h=async(l,d)=>{const p={provider:d,expiresAt:Date.now()+6e5};await Promise.resolve(c.set(l,p,10*60*1e3)),c.cleanup&&await Promise.resolve(c.cleanup())},f=async(l,d)=>{let p=await Promise.resolve(c.get(l));if(!p)try{const{getOAuthStateCookie:R}=await Promise.resolve().then(()=>require("../oauth-state-Drwz6fES.js")).then(b=>b.oauthState),I=await R();if(I&&I.state===l&&I.provider===d)return!0}catch{}return p?p.expiresAt<Date.now()?(await Promise.resolve(c.delete(l)),!1):p.provider!==d?!1:(await Promise.resolve(c.delete(l)),!0):!1},y=vt(s,o,te,se);if(y&&!u.signIn.oauth){const l=u.signIn;u.signIn={...l,oauth:async d=>{const p=await y(d);return await h(p.state,d),p}}}if(!u.signIn||!u.signIn.email)throw new Error("mulguard: signIn.email action is required");const m=async(l,...d)=>{if(l)try{return await l(...d)}catch(p){throw n.onError&&await n.onError(p instanceof Error?p:new Error(String(p)),"callback"),p}},S=pt({sessionConfig:r,cacheTtl:a,getSessionAction:t.getSession,onSessionExpired:n.onSessionExpired,onError:n.onError}),E=async l=>{if(!z(l)||!l.session)return{success:!0};const d=await S.setSession(l.session);return l.user&&n.onSignIn&&await m(n.onSignIn,l.user,l.session),d};if(Object.keys(s).length>0&&!u.oauthCallback){const l=kt({oauthProviders:s,baseUrl:o,callbacks:n,createSession:(d,p,R)=>({user:{...d,avatar:p.avatar,emailVerified:p.emailVerified},expiresAt:new Date(Date.now()+(r.expiresIn||604800)*1e3),accessToken:R.access_token,refreshToken:R.refresh_token,tokenType:"Bearer",expiresIn:R.expires_in}),saveSession:async d=>{await S.setSession(d)},onError:n.onError});u.oauthCallback=l}const w=At({actions:u,callbacks:n,saveSessionAfterAuth:E,onError:n.onError},h),O=St({actions:u,callbacks:n,saveSessionAfterAuth:E,onError:n.onError}),_={async getSession(){return await S.getSession()},async getAccessToken(){return await S.getAccessToken()},async getRefreshToken(){return await S.getRefreshToken()},async hasValidTokens(){return await S.hasValidTokens()},signIn:w,async signUp(l){if(!O)throw new Error("Sign up is not configured. Provide signUp action in config.");return await O(l)},async signOut(){try{const l=await this.getSession(),d=l==null?void 0:l.user;return t.signOut&&await t.signOut(),await S.clearSessionCookie(),S.clearCache(),d&&n.onSignOut&&await m(n.onSignOut,d),{success:!0}}catch(l){return await S.clearSessionCookie(),S.clearCache(),n.onError&&await m(n.onError,l instanceof Error?l:new Error(String(l)),"signOut"),{success:!1,error:l instanceof Error?l.message:"Sign out failed"}}},async resetPassword(l){if(!t.resetPassword)throw new Error("Password reset is not configured. Provide resetPassword action in config.");try{return await t.resetPassword(l)}catch(d){return n.onError&&await m(n.onError,d instanceof Error?d:new Error(String(d)),"resetPassword"),{success:!1,error:d instanceof Error?d.message:"Password reset failed"}}},async verifyEmail(l){if(!t.verifyEmail)throw new Error("Email verification is not configured. Provide verifyEmail action in config.");try{return await t.verifyEmail(l)}catch(d){return n.onError&&await m(n.onError,d instanceof Error?d:new Error(String(d)),"verifyEmail"),{success:!1,error:d instanceof Error?d.message:"Email verification failed"}}},async refreshSession(){if(!t.refreshSession)return this.getSession();try{const l=await t.refreshSession();if(l&&C.validateSessionStructure(l)){if(await S.setSession(l),n.onSessionUpdate){const d=await m(n.onSessionUpdate,l);if(d&&C.validateSessionStructure(d)){if(await S.setSession(d),n.onTokenRefresh){const p=await this.getSession();p&&await m(n.onTokenRefresh,p,d)}return d}}if(n.onTokenRefresh){const d=await this.getSession();d&&await m(n.onTokenRefresh,d,l)}return l}else if(l&&!C.validateSessionStructure(l))return await S.clearSessionCookie(),S.clearCache(),null;return null}catch(l){return await S.clearSessionCookie(),S.clearCache(),n.onError&&await m(n.onError,l instanceof Error?l:new Error(String(l)),"refreshSession"),null}},async oauthCallback(l,d,p){if(!u.oauthCallback)throw new Error("OAuth callback is not configured. Either provide oauthCallback action, or configure providers.oauth in config.");if(!d||!p)return{success:!1,error:"Missing required OAuth parameters (code or state)",errorCode:g.AuthErrorCode.VALIDATION_ERROR};let R=l;if(!R){const b=await Promise.resolve(c.get(p));if(b&&b.provider)R=b.provider;else return{success:!1,error:"Provider is required and could not be extracted from state",errorCode:g.AuthErrorCode.VALIDATION_ERROR}}if(!await f(p,R))return{success:!1,error:"Invalid or expired state parameter",errorCode:g.AuthErrorCode.VALIDATION_ERROR};try{return await u.oauthCallback(R,d,p)}catch(b){return n.onError&&await m(n.onError,b instanceof Error?b:new Error(String(b)),"oauthCallback"),{success:!1,error:b instanceof Error?b.message:"OAuth callback failed",errorCode:g.AuthErrorCode.NETWORK_ERROR}}},async verify2FA(l,d){if(!t.verify2FA)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const p=await t.verify2FA(l);if(p.success&&p.session&&!(d!=null&&d.skipCookieSave)){const R=await E(p);R.success||(process.env.NODE_ENV==="development"&&T.debug("Failed to save session cookie after verify2FA",{error:R.error,warning:R.warning}),n.onError&&await m(n.onError,new Error(R.warning||R.error||"Failed to save session cookie"),"verify2FA.setSession"))}return p}catch(p){return n.onError&&await m(n.onError,p instanceof Error?p:new Error(String(p)),"verify2FA"),{success:!1,error:p instanceof Error?p.message:"2FA verification failed",errorCode:g.AuthErrorCode.TWO_FA_REQUIRED}}},async setSession(l){return await S.setSession(l)},_getSessionConfig(){return S.getSessionConfig()},_getCallbacks(){return n},async storeOAuthState(l,d){await h(l,d)},passkey:t.passkey?{register:t.passkey.register,authenticate:async l=>{var d;if(!((d=t.passkey)!=null&&d.authenticate))throw new Error("PassKey authenticate is not configured.");try{const p=await t.passkey.authenticate(l);return p.success&&p.session&&await E(p),p}catch(p){return n.onError&&await m(n.onError,p instanceof Error?p:new Error(String(p)),"passkey.authenticate"),{success:!1,error:p instanceof Error?p.message:"PassKey authentication failed"}}},list:t.passkey.list?async()=>{var d;if(!((d=t.passkey)!=null&&d.list))throw new Error("PassKey list is not configured.");return[...await t.passkey.list()]}:void 0,remove:t.passkey.remove}:void 0,twoFactor:t.twoFactor?{enable:t.twoFactor.enable,verify:t.twoFactor.verify,disable:t.twoFactor.disable,generateBackupCodes:t.twoFactor.generateBackupCodes,isEnabled:t.twoFactor.isEnabled,verify2FA:async l=>{var p;const d=((p=t.twoFactor)==null?void 0:p.verify2FA)||t.verify2FA;if(!d)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const R=await d(l);if(R.success&&R.session){const I=await E(R);I.success||(process.env.NODE_ENV==="development"&&T.debug("Failed to save session cookie after twoFactor.verify2FA",{error:I.error,warning:I.warning}),n.onError&&await m(n.onError,new Error(I.warning||I.error||"Failed to save session cookie"),"twoFactor.verify2FA.setSession"))}return R}catch(R){return n.onError&&await m(n.onError,R instanceof Error?R:new Error(String(R)),"twoFactor.verify2FA"),{success:!1,error:R instanceof Error?R.message:"2FA verification failed",errorCode:g.AuthErrorCode.UNKNOWN_ERROR}}}}:void 0,signInMethods:{email:l=>w.email(l),oauth:l=>{var d;return((d=w.oauth)==null?void 0:d.call(w,l))||Promise.reject(new Error("OAuth not configured"))},passkey:l=>{var d;return((d=w.passkey)==null?void 0:d.call(w,l))||Promise.reject(new Error("Passkey not configured"))},otp:(l,d)=>{var p;return((p=w.otp)==null?void 0:p.call(w,l,d))||Promise.reject(new Error("OTP not configured"))}}};if(t.refreshSession){const l=ft(async()=>await _.refreshSession(),async()=>await _.signOut(),async()=>{await S.clearSessionCookie(),S.clearCache()},{...i,onTokenRefreshed:i.onTokenRefreshed,onTokenRefreshFailed:i.onTokenRefreshFailed,onBeforeRedirect:i.onBeforeRedirect});_._tokenRefreshManager=l,_._getTokenRefreshManager=()=>l}return _}function J(e){if(!e)return e;const{accessToken:r,refreshToken:t,...n}=e;return n}function Ct(e){return{GET:async r=>de(r,e,"GET"),POST:async r=>de(r,e,"POST")}}async function de(e,r,t){const n=new URL(e.url),s=xt(n.pathname),o=s.split("/").filter(Boolean);try{return t==="GET"?await Ot(e,r,s,o,n):t==="POST"?await Tt(e,r,s,o,n):x("Method not allowed",405)}catch(i){return x(i instanceof Error?i.message:"Request failed",500)}}function xt(e){return e.replace(/^\/api\/auth/,"")||"/session"}async function Ot(e,r,t,n,s){if(t==="/session"||t==="/"){const o=await r.getSession(),i=J(o);return v.NextResponse.json({session:i})}return t==="/providers"?v.NextResponse.json({providers:{email:!!r.signIn.email,oauth:!!r.signIn.oauth,passkey:!!r.signIn.passkey}}):Ue(t,n)?await De(e,r,t,n,s,"GET"):x("Not found",404)}async function Tt(e,r,t,n,s){const o=await _t(e);return t==="/sign-in"||n[0]==="sign-in"?await It(r,o):t==="/sign-up"||n[0]==="sign-up"?await Pt(r,o):t==="/sign-out"||n[0]==="sign-out"?await Nt(r):t==="/reset-password"||n[0]==="reset-password"?await Ut(r,o):t==="/verify-email"||n[0]==="verify-email"?await Dt(r,o):t==="/refresh"||n[0]==="refresh"?await Ft(r):Ue(t,n)?await De(e,r,t,n,s,"POST",o):t.startsWith("/passkey")?await Vt(r,t,n,o):t==="/verify-2fa"||n[0]==="verify-2fa"?await Lt(r,o):t.startsWith("/two-factor")?await Mt(r,n,o):x("Not found",404)}async function _t(e){try{return await e.json()}catch{return{}}}function Ue(e,r){return e==="/callback"||e.startsWith("/oauth/callback")||r[0]==="oauth"&&r[1]==="callback"||r[0]==="callback"}async function De(e,r,t,n,s,o,i){if(!r.oauthCallback)return o==="GET"?B(e.url,"oauth_not_configured"):x("OAuth callback is not configured",400);const a=bt(n,s,i),c=(i==null?void 0:i.code)??s.searchParams.get("code"),u=(i==null?void 0:i.state)??s.searchParams.get("state");if(!c||!u)return o==="GET"?B(e.url,"oauth_missing_params"):x("Missing required OAuth parameters. Code and state are required.",400);try{const h=await r.oauthCallback(a??"",c,u);return o==="GET"?h.success?jt(e.url,s.searchParams.get("callbackUrl")):B(e.url,h.error??"oauth_failed"):v.NextResponse.json(h)}catch(h){return o==="GET"?B(e.url,h instanceof Error?h.message:"oauth_error"):x(h instanceof Error?h.message:"OAuth callback failed",500)}}function bt(e,r,t){return t!=null&&t.provider?t.provider:e[0]==="callback"&&e[1]?e[1]:e[0]==="oauth"&&e[1]==="callback"&&e[2]?e[2]:r.searchParams.get("provider")}async function It(e,r){if(r.provider==="email"&&r.email&&r.password){const t={email:r.email,password:r.password},n=await e.signIn.email(t);return v.NextResponse.json(n)}if(r.provider==="oauth"&&r.providerName){if(!e.signIn.oauth)return x("OAuth is not configured",400);const t=await e.signIn.oauth(r.providerName);return v.NextResponse.json(t)}if(r.provider==="passkey"){if(!e.signIn.passkey)return x("PassKey is not configured",400);const t=await e.signIn.passkey(r.options);return v.NextResponse.json(t)}return x("Invalid sign in request",400)}async function Pt(e,r){if(!e.signUp)return x("Sign up is not configured",400);const t=await e.signUp(r);return v.NextResponse.json(t)}async function Nt(e){const r=await e.signOut();return v.NextResponse.json(r)}async function Ut(e,r){if(!e.resetPassword)return x("Password reset is not configured",400);if(!r.email||typeof r.email!="string")return x("Email is required",400);const t=await e.resetPassword(r.email);return v.NextResponse.json(t)}async function Dt(e,r){if(!e.verifyEmail)return x("Email verification is not configured",400);if(!r.token||typeof r.token!="string")return x("Token is required",400);const t=await e.verifyEmail(r.token);return v.NextResponse.json(t)}async function Ft(e){if(!e.refreshSession){const n=await e.getSession(),s=J(n);return v.NextResponse.json({session:s})}const r=await e.refreshSession(),t=J(r);return v.NextResponse.json({session:t})}async function Lt(e,r){if(!e.verify2FA)return x("2FA verification is not configured",400);if(!r.email||!r.userId||!r.code)return x("Missing required parameters. Email, userId, and code are required.",400);const t={email:r.email,userId:r.userId,code:r.code},n=await e.verify2FA(t);return v.NextResponse.json(n)}async function Vt(e,r,t,n){if(!e.passkey)return x("PassKey is not configured",400);const s=t[1];if(s==="register"&&e.passkey.register){const o=await e.passkey.register(n.options);return v.NextResponse.json(o)}if(s==="list"&&e.passkey.list){const o=await e.passkey.list();return v.NextResponse.json(o)}if(s==="remove"&&e.passkey.remove){if(!n.passkeyId||typeof n.passkeyId!="string")return x("Passkey ID is required",400);const o=await e.passkey.remove(n.passkeyId);return v.NextResponse.json(o)}return x("Invalid Passkey request",400)}async function Mt(e,r,t){if(!e.twoFactor)return x("Two-Factor Authentication is not configured",400);const n=r[1];if(n==="enable"&&e.twoFactor.enable){const s=await e.twoFactor.enable();return v.NextResponse.json(s)}if(n==="verify"&&e.twoFactor.verify){if(!t.code||typeof t.code!="string")return x("Code is required",400);const s=await e.twoFactor.verify(t.code);return v.NextResponse.json(s)}if(n==="disable"&&e.twoFactor.disable){const s=await e.twoFactor.disable();return v.NextResponse.json(s)}if(n==="backup-codes"&&e.twoFactor.generateBackupCodes){const s=await e.twoFactor.generateBackupCodes();return v.NextResponse.json(s)}if(n==="is-enabled"&&e.twoFactor.isEnabled){const s=await e.twoFactor.isEnabled();return v.NextResponse.json({enabled:s})}return x("Invalid two-factor request",400)}function x(e,r){return v.NextResponse.json({success:!1,error:e},{status:r})}function B(e,r){return v.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(r)}`,e))}function zt(e,r){if(!e)return null;try{const t=new URL(e,r),n=new URL(r);return t.protocol!==n.protocol||t.hostname!==n.hostname||t.port!==n.port?(process.env.NODE_ENV==="development"&&console.warn("[Mulguard] Blocked redirect to external URL:",e),null):t.protocol==="javascript:"||t.protocol==="data:"?(process.env.NODE_ENV==="development"&&console.warn("[Mulguard] Blocked dangerous redirect URL:",e),null):t.pathname+t.search+t.hash}catch{return null}}function jt(e,r){const n=zt(r,e)??"/";return v.NextResponse.redirect(new URL(n,e))}function Ht(e){return async r=>{const{method:t,nextUrl:n}=r,o=n.pathname.replace(/^\/api\/auth/,"")||"/";try{let i;if(t!=="GET"&&t!=="HEAD")try{i=await r.json()}catch{}const a=Object.fromEntries(n.searchParams.entries()),c=await fetch(`${process.env.NEXT_PUBLIC_API_URL||""}/api/auth${o}${Object.keys(a).length>0?`?${new URLSearchParams(a).toString()}`:""}`,{method:t,headers:{"Content-Type":"application/json",...Object.fromEntries(r.headers.entries())},body:i?JSON.stringify(i):void 0}),u=await c.json();return v.NextResponse.json(u,{status:c.status,headers:{...Object.fromEntries(c.headers.entries())}})}catch(i){return console.error("API handler error:",i),v.NextResponse.json({success:!1,error:i instanceof Error?i.message:"Internal server error"},{status:500})}}}function V(e,r){const t=Q({"X-Frame-Options":"SAMEORIGIN"});for(const[n,s]of Object.entries(t))s&&typeof s=="string"&&r.headers.set(n,s);return r}function Fe(e){const{auth:r,protectedRoutes:t=[],redirectTo:n="/login",redirectIfAuthenticated:s,apiPrefix:o="/api/auth",enableSecurityHeaders:i=!0}=e;return async a=>{const{pathname:c}=a.nextUrl;if(c.startsWith(o)){const y=v.NextResponse.next();return i?V(a,y):y}if(c.startsWith("/_next/")||c.startsWith("/api/")||c.match(/\.(ico|png|jpg|jpeg|svg|gif|webp|css|js|woff|woff2|ttf|eot)$/))return v.NextResponse.next();const u=t.length>0?t.some(y=>c.startsWith(y)):!1;let h=null;if(u||s)try{h=await r.getSession()}catch(y){process.env.NODE_ENV==="development"&&console.error("Proxy: Failed to get session:",y)}if(u&&!h){const y=a.nextUrl.clone();y.pathname=n,y.searchParams.set("callbackUrl",c);const m=v.NextResponse.redirect(y);return i?V(a,m):m}if(s&&h&&(c.startsWith("/login")||c.startsWith("/register")||c.startsWith("/signup")||c.startsWith("/sign-in"))){const m=a.nextUrl.clone();m.pathname=s;const S=v.NextResponse.redirect(m);return i?V(a,S):S}const f=v.NextResponse.next();return i?V(a,f):f}}async function Le(e,r){try{const t=await e.getSession();return t?(t.user.roles||[]).includes(r):!1}catch{return!1}}function Bt(e,r){const t=Fe(e);return async n=>{var i;const{pathname:s}=n.nextUrl;return((i=e.protectedRoutes)==null?void 0:i.some(a=>s.startsWith(a)))&&!await Le(e.auth,r)?v.NextResponse.json({error:"Forbidden"},{status:403}):t(n)}}exports.buildCookieOptions=g.buildCookieOptions;exports.deleteCookie=g.deleteCookie;exports.getCookie=g.getCookie;exports.setCookie=g.setCookie;exports.signInEmailAction=g.signInEmailAction;exports.signOutAction=g.signOutAction;exports.signUpAction=g.signUpAction;exports.verify2FAAction=g.verify2FAAction;exports.SessionExpiredError=C.SessionExpiredError;exports.createAuthenticatedAction=C.createAuthenticatedAction;exports.createServerAction=C.createServerAction;exports.deleteOAuthStateCookie=C.deleteOAuthStateCookie;exports.getCurrentUser=C.getCurrentUser;exports.getOAuthStateCookie=C.getOAuthStateCookie;exports.getServerSession=C.getServerSession;exports.getServerUser=C.getServerUser;exports.getSessionTimeUntilExpiry=C.getSessionTimeUntilExpiry;exports.isAuthenticated=C.isAuthenticated;exports.isSessionExpiredNullable=C.isSessionExpiredNullable;exports.isSessionExpiringSoon=C.isSessionExpiringSoon;exports.isSessionValid=C.isSessionValid;exports.requireAuth=C.requireAuth;exports.requireRole=C.requireRole;exports.storeOAuthStateCookie=C.storeOAuthStateCookie;exports.validateSessionStructure=C.validateSessionStructure;exports.CSRFProtection=ye;exports.DEFAULT_SECURITY_HEADERS=we;exports.MemoryCSRFStore=me;exports.MemoryOAuthStateStore=_e;exports.MemoryPKCEStorage=Oe;exports.OAuthHandler=Ie;exports.RateLimiter=pe;exports.applySecurityHeaders=Ye;exports.buildOAuthAuthorizationUrl=se;exports.checkRole=Le;exports.containsXSSPattern=vr;exports.createApiHandler=Ht;exports.createCSRFProtection=Ar;exports.createCookieOAuthStateStore=Te;exports.createMemoryOAuthStateStore=be;exports.createNextJsCookieOAuthStateStore=nt;exports.createOAuthHandler=ot;exports.createProxyMiddleware=Fe;exports.createRateLimiter=Je;exports.createRedisOAuthStateStore=st;exports.createRoleBasedProxy=Bt;exports.escapeHTML=Ae;exports.exchangeOAuthCode=oe;exports.generateCSRFToken=te;exports.generateCodeChallenge=ie;exports.generateCodeVerifier=Ce;exports.generatePKCECodePair=xe;exports.generateToken=re;exports.getErrorCode=br;exports.getErrorMessage=_r;exports.getOAuthUserInfo=q;exports.getProviderMetadata=$;exports.getSecurityHeaders=Q;exports.getUserFriendlyError=Ur;exports.getUserProfile=q;exports.hasErrorCode=Pr;exports.isAuthError=ke;exports.isAuthSuccess=Ir;exports.isOAuthProviderConfig=$r;exports.isRetryableError=Nr;exports.isSupportedProvider=Fr;exports.isTwoFactorRequired=Tr;exports.isValidCSRFToken=Rr;exports.isValidEmail=Or;exports.isValidInput=yr;exports.isValidName=ur;exports.isValidPassword=ir;exports.isValidToken=Er;exports.isValidURL=dr;exports.mulguard=Rt;exports.sanitizeHTML=Sr;exports.sanitizeInput=Cr;exports.sanitizeUserInput=kr;exports.signIn=Dr;exports.toNextJsHandler=Ct;exports.validateAndSanitizeEmail=Z;exports.validateAndSanitizeInput=ee;exports.validateAndSanitizeName=cr;exports.validateAndSanitizePassword=sr;exports.validateCSRFToken=ne;exports.validateToken=wr;exports.validateURL=fr;exports.verifyPKCECode=Zr;exports.withSecurityHeaders=V;