mulguard 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -4
- package/dist/client/index.js +1 -1
- package/dist/client/index.mjs +42 -39
- package/dist/client/provider.d.ts +50 -6
- package/dist/core/auth/oauth-providers.d.ts +2 -0
- package/dist/core/types/index.d.ts +29 -0
- package/dist/index/index.js +1 -1
- package/dist/index/index.mjs +328 -301
- package/package.json +1 -1
package/dist/index/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ne=Object.defineProperty;var ie=(r,e,s)=>e in r?ne(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var L=(r,e,s)=>ie(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("../actions-CExpv_dD.js"),k=require("../oauth-state-CzIWQq3s.js"),f=require("next/server"),j=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ae(r=32){if(j&&typeof j.getRandomValues=="function")return j.getRandomValues(new Uint8Array(r));if(j&&typeof j.randomBytes=="function")return Uint8Array.from(j.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}class B{constructor(e){L(this,"attempts",new Map);L(this,"config");this.config=e}check(e){const s=Date.now(),t=this.attempts.get(e);return!t||t.resetAt<s?(this.attempts.set(e,{count:1,resetAt:s+this.config.windowMs}),{allowed:!0,remaining:this.config.maxAttempts-1,resetAt:new Date(s+this.config.windowMs)}):t.count>=this.config.maxAttempts?{allowed:!1,remaining:0,resetAt:new Date(t.resetAt)}:(t.count++,{allowed:!0,remaining:this.config.maxAttempts-t.count,resetAt:new Date(t.resetAt)})}reset(e){this.attempts.delete(e)}clear(){this.attempts.clear()}}function ce(r){return new B(r)}const K={"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(r){return{...K,...r}}function ue(r,e){const s=q(e);for(const[t,i]of Object.entries(s))i&&r.set(t,i)}function $(r){if(!r||typeof r!="string")return{valid:!1,error:"Email is required"};const e=r.trim().toLowerCase();return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?e.length>254?{valid:!1,error:"Email is too long"}:e.includes("..")||e.startsWith(".")||e.endsWith(".")?{valid:!1,error:"Invalid email format"}:{valid:!0,sanitized:e}:{valid:!1,error:"Invalid email format"}}function le(r,e=8){if(!r||typeof r!="string")return{valid:!1,error:"Password is required"};if(r.length<e)return{valid:!1,error:`Password must be at least ${e} characters`};if(r.length>128)return{valid:!1,error:"Password is too long"};if(["password","12345678","qwerty","abc123","password123","123456789","1234567890","letmein","welcome","monkey","dragon","master","sunshine","princess","football"].includes(r.toLowerCase()))return{valid:!1,error:"Password is too common"};if(/(.)\1{3,}/.test(r))return{valid:!1,error:"Password contains too many repeated characters"};if(/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.test(r))return{valid:!1,error:"Password contains sequential characters"};let t="weak",i=0;return r.length>=12?i+=2:r.length>=8&&(i+=1),/[a-z]/.test(r)&&(i+=1),/[A-Z]/.test(r)&&(i+=1),/[0-9]/.test(r)&&(i+=1),/[^a-zA-Z0-9]/.test(r)&&(i+=1),i>=5?t="strong":i>=3&&(t="medium"),{valid:!0,strength:t}}function fe(r){if(!r||typeof r!="string")return{valid:!1,error:"Name is required"};const e=r.trim();return e.length<1?{valid:!1,error:"Name cannot be empty"}:e.length>100?{valid:!1,error:"Name is too long"}:{valid:!0,sanitized:e.replace(/[<>\"']/g,"")}}function de(r){if(!r||typeof r!="string")return{valid:!1,error:"URL is required"};try{const e=new URL(r);return["http:","https:"].includes(e.protocol)?{valid:!0}:{valid:!1,error:"URL must use http or https protocol"}}catch{return{valid:!1,error:"Invalid URL format"}}}function he(r,e=16){return!r||typeof r!="string"?{valid:!1,error:"Token is required"}:r.length<e?{valid:!1,error:"Token is too short"}:r.length>512?{valid:!1,error:"Token is too long"}:/^[A-Za-z0-9_-]+$/.test(r)?/(.)\1{10,}/.test(r)?{valid:!1,error:"Token contains suspicious pattern"}:{valid:!0}:{valid:!1,error:"Invalid token format"}}function z(r,e){const{maxLength:s=1e3,allowHtml:t=!1,required:i=!0}=e||{};if(i&&(!r||typeof r!="string"||r.trim().length===0))return{valid:!1,error:"Input is required"};if(!r||typeof r!="string")return{valid:!0,sanitized:""};let d=r.trim();return d.length>s?{valid:!1,error:`Input must be less than ${s} characters`}:(t||(d=d.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")),d=d.replace(/[\x00-\x1F\x7F]/g,""),{valid:!0,sanitized:d})}class X{constructor(){L(this,"tokens",new Map)}get(e){const s=this.tokens.get(e);return s?s.expiresAt<Date.now()?(this.delete(e),null):s.value:null}set(e,s,t=36e5){this.tokens.set(e,{value:s,expiresAt:Date.now()+t})}delete(e){this.tokens.delete(e)}clear(){this.tokens.clear()}}class Y{constructor(e,s=32){L(this,"store");L(this,"tokenLength");this.store=e||new X,this.tokenLength=s}generateToken(e,s){const t=W(this.tokenLength);return this.store.set(e,t,s),t}validateToken(e,s){const t=this.store.get(e);if(!t)return!1;const i=Q(s,t);return i&&this.store.delete(e),i}getToken(e){return this.store.get(e)}deleteToken(e){this.store.delete(e)}}function ge(r){return new Y(r)}function G(r){if(typeof r!="string")return"";const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return r.replace(/[&<>"']/g,s=>e[s]||s)}function pe(r){return typeof r!="string"?"":r.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript:/gi,"")}function we(r){return typeof r!="string"?"":G(r.trim())}function me(r){return typeof r!="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(s=>s.test(r))}function W(r=32){const e=ae(r);return Buffer.from(e).toString("base64url")}function J(){return W(32)}function Q(r,e){if(!r||!e||r.length!==e.length)return!1;let s=0;for(let t=0;t<r.length;t++)s|=r.charCodeAt(t)^e.charCodeAt(t);return s===0}function Ee(r){return r.trim().replace(/[<>]/g,"")}function Re(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Z(r){return!r.success&&!!r.error}function ye(r){return r.requires2FA===!0||r.errorCode===h.AuthErrorCode.TWO_FA_REQUIRED}function ve(r,e){return r.error?r.error:e||"Authentication failed"}function Ae(r){return r.errorCode}function ke(r){return r.success===!0&&!!r.user}function Se(r,e){return r.errorCode===e}function Ce(r){if(!Z(r))return!1;const e=[h.AuthErrorCode.NETWORK_ERROR,h.AuthErrorCode.RATE_LIMITED,h.AuthErrorCode.UNKNOWN_ERROR];return r.errorCode?e.includes(r.errorCode):!1}function Ie(r){if(r.error)return r.error;switch(r.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 Oe(r,e,s){return r.signIn(e,s)}const Ne={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 V(r){return Ne[r]||null}function ee(r,e,s,t){const i=V(r);if(!i)throw new Error(`Unknown OAuth provider: ${r}`);const d=e.redirectUri||`${s}/api/auth/callback/${r}`,c=e.scopes||i.defaultScopes,a=new URLSearchParams({client_id:e.clientId,redirect_uri:d,response_type:"code",scope:c.join(" "),state:t,...i.defaultParams,...e.params});return`${i.authorizationUrl}?${a.toString()}`}async function re(r,e,s,t){const i=V(r);if(!i)throw new Error(`Unknown OAuth provider: ${r}`);const d=new URLSearchParams({client_id:e.clientId,code:s,redirect_uri:t,grant_type:"authorization_code"});e.clientSecret&&d.append("client_secret",e.clientSecret);const c=await fetch(i.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:d.toString()});if(!c.ok){const a=await c.text();throw new Error(`Failed to exchange code for tokens: ${a}`)}return await c.json()}async function te(r,e){var d,c,a,m;const s=V(r);if(!s)throw new Error(`Unknown OAuth provider: ${r}`);const t=await fetch(s.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!t.ok){const v=await t.text();throw new Error(`Failed to fetch user info: ${v}`)}const i=await t.json();switch(r){case"google":return{id:i.sub||i.id,email:i.email,name:i.name,avatar:i.picture,emailVerified:i.email_verified};case"github":let v=i.email;if(!v){const g=await(await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`}})).json();v=((d=g.find(S=>S.primary))==null?void 0:d.email)||((c=g[0])==null?void 0:c.email)||`${i.login}@users.noreply.github.com`}return{id:String(i.id),email:v,name:i.name||i.login,avatar:i.avatar_url,emailVerified:!!v};case"apple":return{id:i.sub,email:i.email,name:i.name?`${i.name.firstName} ${i.name.lastName}`:"",emailVerified:i.email_verified};case"facebook":return{id:i.id,email:i.email,name:i.name,avatar:(m=(a=i.picture)==null?void 0:a.data)==null?void 0:m.url,emailVerified:!0};default:return{id:String(i.id||i.sub),email:i.email,name:i.name||i.display_name||i.username,avatar:i.avatar||i.picture||i.avatar_url,emailVerified:i.email_verified||i.emailVerified||!1}}}class se{constructor(){L(this,"states",new Map)}set(e,s,t){this.states.set(e,s),this.cleanup()}get(e){const s=this.states.get(e);return s?s.expiresAt<Date.now()?(this.delete(e),null):s:null}delete(e){this.states.delete(e)}cleanup(){const e=Date.now();for(const[s,t]of this.states.entries())t.expiresAt<e&&this.states.delete(s)}}function oe(){return new se}function be(r=process.env.NODE_ENV==="development"){const e="[Mulguard]";return{debug:r?(s,t)=>{t!==void 0?console.debug(`${e} ${s}`,t):console.debug(`${e} ${s}`)}:()=>{},info:r?(s,t)=>{t!==void 0?console.info(`${e} ${s}`,t):console.info(`${e} ${s}`)}:()=>{},warn:r?(s,t)=>{t!==void 0?console.warn(`${e} ${s}`,t):console.warn(`${e} ${s}`)}:()=>{},error:r?(s,t)=>{t!==void 0?console.error(`${e} ${s}`,t):console.error(`${e} ${s}`)}:()=>{}}}const x=be();function Te(r,e,s,t={}){const{enabled:i=!0,maxRetries:d=1,retryDelay:c=1e3,rateLimit:a=3,autoSignOutOnFailure:m=!0,redirectToLogin:v="/login",autoRedirectOnFailure:C=!0}=t;let g=null,S=!1;const N=[],b=[],P=60*1e3;let T=0,I=!1,_=null;const D=2,M=60*1e3;function o(){const u=Date.now();if(I&&_){if(u<_)return!1;I=!1,_=null,T=0}for(;b.length>0;){const w=b[0];if(w!==void 0&&w<u-P)b.shift();else break}return b.length>=a?!1:(b.push(u),!0)}function n(){T++,T>=D&&(I=!0,_=Date.now()+M,process.env.NODE_ENV==="development"&&console.warn("[TokenRefreshManager] Circuit breaker opened - too many consecutive failures"))}function l(){T=0,I=!1,_=null}async function E(u=1){if(!i)return null;if(!o())throw new Error("Rate limit exceeded for token refresh");try{const w=await r();if(w)return l(),O(w),t.onTokenRefreshed&&await Promise.resolve(t.onTokenRefreshed(w)),w;if(n(),u<d)return await p(c*u),E(u+1);throw new Error("Token refresh failed: refresh function returned null")}catch(w){if(n(),u<d&&A(w))return await p(c*u),E(u+1);throw w}}function A(u){if(u instanceof Error){const w=u.message.toLowerCase();if(w.includes("rate limit")||w.includes("too many requests")||w.includes("429")||w.includes("limit:")||w.includes("requests per minute")||w.includes("token_blacklisted")||w.includes("blacklisted")||w.includes("invalid")||w.includes("401")||w.includes("unauthorized")||w.includes("session has been revoked")||w.includes("session expired"))return!1;if(w.includes("network")||w.includes("fetch")||w.includes("timeout"))return!0}return!1}function O(u){const w=[...N];N.length=0;for(const{resolve:F}of w)F(u)}function R(u){const w=[...N];N.length=0;for(const{reject:F}of w)F(u)}function p(u){return new Promise(w=>setTimeout(w,u))}async function y(u){try{if(t.onTokenRefreshFailed&&await Promise.resolve(t.onTokenRefreshFailed(u)),m&&(await s(),await e(),C&&typeof window<"u")){let w=!0;if(t.onBeforeRedirect&&(w=await Promise.resolve(t.onBeforeRedirect(u))),w){const F=new URL(v,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(w){process.env.NODE_ENV==="development"&&console.error("[TokenRefreshManager] Error in handleRefreshFailure:",w)}}return{async refreshToken(){return i?g||(S=!0,g=E().then(u=>(S=!1,g=null,u)).catch(u=>{throw S=!1,g=null,R(u),y(u).catch(()=>{}),u}),g):null},isRefreshing(){return S},async waitForRefresh(){return g?new Promise((u,w)=>{N.push({resolve:u,reject:w})}):null},clear(){g=null,S=!1,b.length=0,l(),R(new Error("Token refresh manager cleared"))},async handleRefreshFailure(u){return y(u)}}}function xe(){const r=process.env.NODE_ENV==="production";return{cookieName:"__mulguard_session",expiresIn:60*60*24*7,httpOnly:!0,secure:r,sameSite:"lax",path:"/"}}function _e(){return{enabled:!0,refreshThreshold:300,maxRetries:0,retryDelay:1e3,rateLimit:1,autoSignOutOnFailure:!0,redirectToLogin:"/login",autoRedirectOnFailure:!0}}function Pe(r){var D,M;const e={...xe(),...r.session},s=r.actions,t=r.callbacks||{},i=((D=r.providers)==null?void 0:D.oauth)||{},d=process.env.NEXT_PUBLIC_URL||(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:"http://localhost:3000"),c={..._e(),...r.tokenRefresh},a={...s};if(Object.keys(i).length>0&&!a.signIn.oauth&&(a.signIn.oauth=async o=>{const n=i[o];if(!n)throw new Error(`OAuth provider "${o}" is not configured. Add it to providers.oauth in config.`);if(!n.clientId)throw new Error(`OAuth provider "${o}" is missing clientId`);const l=J();return{url:ee(o,n,d,l),state:l}}),Object.keys(i).length>0&&!a.oauthCallback&&(a.oauthCallback=async(o,n,l)=>{const E=i[o];if(!E)return{success:!1,error:`OAuth provider "${o}" is not configured`,errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const A=E.redirectUri||`${d}/api/auth/callback/${o}`,O=await re(o,E,n,A),R=await te(o,O.access_token);if(t.onOAuthUser){const p=await g(t.onOAuthUser,R,o);if(!p)return{success:!1,error:"Failed to create or retrieve user",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const y={user:{id:p.id,email:p.email,name:p.name,avatar:R.avatar,emailVerified:R.emailVerified},expiresAt:new Date(Date.now()+7*24*60*60*1e3),accessToken:O.access_token,refreshToken:O.refresh_token,tokenType:"Bearer",expiresIn:O.expires_in};return await b(y),m={session:y,timestamp:Date.now()},t.onSignIn&&await g(t.onSignIn,y.user,y),{success:!0,user:y.user,session:y}}return{success:!1,error:"OAuth user callback not implemented. Provide onOAuthUser callback or implement oauthCallback action.",errorCode:h.AuthErrorCode.VALIDATION_ERROR}}catch(A){return x.error("OAuth callback failed",{provider:o,error:A}),{success:!1,error:A instanceof Error?A.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}}),!a.signIn||!a.signIn.email)throw new Error("mulguard: signIn.email action is required");let m=null;const v=((M=r.session)==null?void 0:M.cacheTtl)??r.sessionCacheTtl??5e3,C=r.oauthStateStore||oe(),g=async(o,...n)=>{if(o)try{return await o(...n)}catch(l){throw t.onError&&await t.onError(l instanceof Error?l:new Error(String(l)),"callback"),l}},S=async(o,n)=>{const l={provider:n,expiresAt:Date.now()+6e5};await Promise.resolve(C.set(o,l,10*60*1e3)),C.cleanup&&await Promise.resolve(C.cleanup())},N=async(o,n)=>{const l=await Promise.resolve(C.get(o));return l?l.expiresAt<Date.now()?(await Promise.resolve(C.delete(o)),!1):l.provider!==n?!1:(await Promise.resolve(C.delete(o)),!0):!1},b=async o=>{const n=e.cookieName||"__mulguard_session",l=typeof o=="object"&&"token"in o?String(o.token):JSON.stringify(o),E=h.buildCookieOptions(n,l,e);return await h.setCookie(E)},P=async o=>{if(!o.success||!o.session)return{success:!0};const n=await b(o.session);return m={session:o.session,timestamp:Date.now()},o.user&&t.onSignIn&&await g(t.onSignIn,o.user,o.session),n},T=async()=>{const o=e.cookieName||"__mulguard_session";await h.deleteCookie(o,{path:e.path,domain:e.domain})};let I=null;const _={async getSession(){const o=Date.now();if(m&&o-m.timestamp<v)return m.session;if(s.getSession)try{const n=await s.getSession();if(n&&k.validateSessionStructure(n))return m={session:n,timestamp:o},n;n&&!k.validateSessionStructure(n)&&(await T(),m=null)}catch(n){x.debug("getSession error",{error:n}),t.onError&&await g(t.onError,n instanceof Error?n:new Error(String(n)),"getSession"),m=null}try{const n=e.cookieName||"__mulguard_session",l=await h.getCookie(n);if(l)try{const E=JSON.parse(l);if(k.validateSessionStructure(E))return E.expiresAt&&new Date(E.expiresAt)<new Date?(t.onSessionExpired&&await g(t.onSessionExpired,E),await T(),m=null,null):(m={session:E,timestamp:o},E);await T(),m=null}catch{await T(),m=null}}catch(n){const l=n instanceof Error?n.message:String(n);!l.includes("request scope")&&!l.includes("cookies")&&(x.warn("getSession cookie error",{error:n}),t.onError&&await g(t.onError,n instanceof Error?n:new Error(String(n)),"getSession.cookie"))}return null},async getAccessToken(){const o=await this.getSession();return o!=null&&o.accessToken&&typeof o.accessToken=="string"?o.accessToken:null},async getRefreshToken(){const o=await this.getSession();return o!=null&&o.refreshToken&&typeof o.refreshToken=="string"?o.refreshToken:null},async hasValidTokens(){return!!await this.getAccessToken()},signIn:(()=>{const o=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 p=$(R.email);if(!p.valid)return{success:!1,error:p.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 y={email:p.sanitized,password:R.password},u=await a.signIn.email(y);return u.success&&u.session&&await P(u),u.success?x.info("Sign in successful",{email:y.email.substring(0,3)+"***"}):x.warn("Sign in failed",{email:y.email.substring(0,3)+"***",errorCode:u.errorCode}),u}catch(p){const y=p instanceof Error?p.message:"Sign in failed";return x.error("Sign in error",{error:y,context:"signIn.email"}),t.onError&&await g(t.onError,p instanceof Error?p:new Error(String(p)),"signIn.email"),{success:!1,error:"Sign in failed. Please try again.",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}},n=async R=>{if(!R||typeof R!="string")throw new Error("Provider is required");const p=z(R,{maxLength:50,allowHtml:!1,required:!0});if(!p.valid||!p.sanitized)throw new Error("Invalid provider");const y=p.sanitized.toLowerCase();if(!a.signIn.oauth)throw new Error("OAuth sign in is not configured. Either provide oauth action in signIn, or configure providers.oauth in config.");const u=await a.signIn.oauth(y);return await S(u.state,y),x.info("OAuth sign in initiated",{provider:y}),u},l=async R=>{if(!a.signIn.passkey)throw new Error("PassKey sign in is not configured. Provide passkey action in signIn.");try{const p=await a.signIn.passkey(R);return p.success&&p.session&&await P(p),p}catch(p){return t.onError&&await g(t.onError,p instanceof Error?p:new Error(String(p)),"signIn.passkey"),{success:!1,error:p instanceof Error?p.message:"PassKey sign in failed"}}},E=async(R,p)=>{if(!R||typeof R!="string")return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const y=$(R);if(!y.valid)return{success:!1,error:y.error||"Invalid email format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(p!==void 0&&(typeof p!="string"||p.length<4||p.length>10))return{success:!1,error:"Invalid OTP code format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!a.signIn.otp)return{success:!1,error:"OTP sign in is not configured",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const u=await a.signIn.otp(y.sanitized,p);return u.success&&u.session&&await P(u),u.success?x.info("OTP sign in successful",{email:y.sanitized.substring(0,3)+"***"}):x.warn("OTP sign in failed",{email:y.sanitized.substring(0,3)+"***"}),u}catch(u){return x.error("OTP sign in error",{error:u instanceof Error?u.message:"Unknown error",context:"signIn.otp"}),t.onError&&await g(t.onError,u instanceof Error?u:new Error(String(u)),"signIn.otp"),{success:!1,error:"OTP sign in failed. Please try again.",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}},O=Object.assign(async(R,p)=>{if(!R||typeof R!="string")throw new Error("Provider is required");const y=z(R,{maxLength:50,allowHtml:!1,required:!0});if(!y.valid||!y.sanitized)throw new Error("Invalid provider");const u=y.sanitized.toLowerCase();if(u==="google"||u==="github"||u==="apple"||u==="facebook"||typeof u=="string"&&!["credentials","otp","passkey"].includes(u))return n(u);if(u==="credentials")return!p||!("email"in p)||!("password"in p)?{success:!1,error:"Credentials are required",errorCode:h.AuthErrorCode.VALIDATION_ERROR}:o(p);if(u==="otp"){if(!p||!("email"in p))return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const w=p;return E(w.email,w.code)}return u==="passkey"?l(p):{success:!1,error:"Invalid provider",errorCode:h.AuthErrorCode.VALIDATION_ERROR}},{email:o,oauth:a.signIn.oauth?n:void 0,passkey:a.signIn.passkey?l:void 0,otp:a.signIn.otp?E:void 0});return I=O,O})(),async signUp(o){if(!a.signUp)throw new Error("Sign up is not configured. Provide signUp action in config.");try{const n=await a.signUp(o);return n.success&&n.session&&await P(n),n}catch(n){return t.onError&&await g(t.onError,n instanceof Error?n:new Error(String(n)),"signUp"),{success:!1,error:n instanceof Error?n.message:"Sign up failed"}}},async signOut(){try{const o=await this.getSession(),n=o==null?void 0:o.user;return s.signOut&&await s.signOut(),await T(),m=null,n&&t.onSignOut&&await g(t.onSignOut,n),{success:!0}}catch(o){return await T(),t.onError&&await g(t.onError,o instanceof Error?o:new Error(String(o)),"signOut"),{success:!1,error:o instanceof Error?o.message:"Sign out failed"}}},async resetPassword(o){if(!s.resetPassword)throw new Error("Password reset is not configured. Provide resetPassword action in config.");try{return await s.resetPassword(o)}catch(n){return t.onError&&await g(t.onError,n instanceof Error?n:new Error(String(n)),"resetPassword"),{success:!1,error:n instanceof Error?n.message:"Password reset failed"}}},async verifyEmail(o){if(!s.verifyEmail)throw new Error("Email verification is not configured. Provide verifyEmail action in config.");try{return await s.verifyEmail(o)}catch(n){return t.onError&&await g(t.onError,n instanceof Error?n:new Error(String(n)),"verifyEmail"),{success:!1,error:n instanceof Error?n.message:"Email verification failed"}}},async refreshSession(){if(!s.refreshSession)return this.getSession();try{const o=await s.refreshSession();if(o&&k.validateSessionStructure(o)){if(await b(o),m={session:o,timestamp:Date.now()},t.onSessionUpdate){const n=await g(t.onSessionUpdate,o);if(n&&k.validateSessionStructure(n)){if(await b(n),t.onTokenRefresh){const l=await this.getSession();l&&await g(t.onTokenRefresh,l,n)}return n}}if(t.onTokenRefresh){const n=await this.getSession();n&&await g(t.onTokenRefresh,n,o)}return o}else if(o&&!k.validateSessionStructure(o))return await T(),null;return null}catch(o){return await T(),t.onError&&await g(t.onError,o instanceof Error?o:new Error(String(o)),"refreshSession"),null}},async oauthCallback(o,n,l){if(!a.oauthCallback)throw new Error("OAuth callback is not configured. Either provide oauthCallback action, or configure providers.oauth in config.");if(!o||!n||!l)return{success:!1,error:"Missing required OAuth parameters (provider, code, or state)",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!await N(l,o))return{success:!1,error:"Invalid or expired state parameter",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const A=await a.oauthCallback(o,n,l);if(A.success&&A.session){const O=await P(A);O.success||(process.env.NODE_ENV==="development"&&x.debug("Failed to save session cookie after oauthCallback",{error:O.error,warning:O.warning}),t.onError&&await g(t.onError,new Error(O.warning||O.error||"Failed to save session cookie"),"oauthCallback.setSession"))}return A}catch(A){return t.onError&&await g(t.onError,A instanceof Error?A:new Error(String(A)),"oauthCallback"),{success:!1,error:A instanceof Error?A.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}},async verify2FA(o,n){if(!s.verify2FA)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const l=await s.verify2FA(o);if(l.success&&l.session&&!(n!=null&&n.skipCookieSave)){const E=await P(l);E.success||(process.env.NODE_ENV==="development"&&x.debug("Failed to save session cookie after verify2FA",{error:E.error,warning:E.warning}),t.onError&&await g(t.onError,new Error(E.warning||E.error||"Failed to save session cookie"),"verify2FA.setSession"))}return l}catch(l){return t.onError&&await g(t.onError,l instanceof Error?l:new Error(String(l)),"verify2FA"),{success:!1,error:l instanceof Error?l.message:"2FA verification failed",errorCode:h.AuthErrorCode.TWO_FA_REQUIRED}}},async setSession(o){return k.validateSessionStructure(o)?await b(o):{success:!1,error:"Invalid session structure"}},_getSessionConfig(){return{cookieName:e.cookieName||"__mulguard_session",config:e}},_getCallbacks(){return t},passkey:s.passkey?{register:s.passkey.register,authenticate:async o=>{var n;if(!((n=s.passkey)!=null&&n.authenticate))throw new Error("PassKey authenticate is not configured.");try{const l=await s.passkey.authenticate(o);return l.success&&l.session&&await P(l),l}catch(l){return t.onError&&await g(t.onError,l instanceof Error?l:new Error(String(l)),"passkey.authenticate"),{success:!1,error:l instanceof Error?l.message:"PassKey authentication failed"}}},list:s.passkey.list,remove:s.passkey.remove}:void 0,twoFactor:s.twoFactor?{enable:s.twoFactor.enable,verify:s.twoFactor.verify,disable:s.twoFactor.disable,generateBackupCodes:s.twoFactor.generateBackupCodes,isEnabled:s.twoFactor.isEnabled,verify2FA:async o=>{var l;const n=((l=s.twoFactor)==null?void 0:l.verify2FA)||s.verify2FA;if(!n)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const E=await n(o);if(E.success&&E.session){const A=await P(E);A.success||(process.env.NODE_ENV==="development"&&x.debug("Failed to save session cookie after twoFactor.verify2FA",{error:A.error,warning:A.warning}),t.onError&&await g(t.onError,new Error(A.warning||A.error||"Failed to save session cookie"),"twoFactor.verify2FA.setSession"))}return E}catch(E){return t.onError&&await g(t.onError,E instanceof Error?E:new Error(String(E)),"twoFactor.verify2FA"),{success:!1,error:E instanceof Error?E.message:"2FA verification failed",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}}}:void 0,signInMethods:{email:o=>I.email(o),oauth:o=>{var n;return((n=I.oauth)==null?void 0:n.call(I,o))||Promise.reject(new Error("OAuth not configured"))},passkey:o=>{var n;return((n=I.passkey)==null?void 0:n.call(I,o))||Promise.reject(new Error("Passkey not configured"))},otp:(o,n)=>{var l;return((l=I.otp)==null?void 0:l.call(I,o,n))||Promise.reject(new Error("OTP not configured"))}}};if(s.refreshSession){const o=Te(async()=>await _.refreshSession(),async()=>await _.signOut(),async()=>{await T()},{...c,onTokenRefreshed:c.onTokenRefreshed,onTokenRefreshFailed:c.onTokenRefreshFailed,onBeforeRedirect:c.onBeforeRedirect});_._tokenRefreshManager=o,_._getTokenRefreshManager=()=>o}return _}function Ue(r){return{GET:async e=>H(e,r,"GET"),POST:async e=>H(e,r,"POST")}}async function H(r,e,s){const t=new URL(r.url),i=t.pathname.replace(/^\/api\/auth/,"")||"/session",d=i.split("/").filter(Boolean);try{if(s==="GET"){if(i==="/session"||i==="/"){const c=await e.getSession();return f.NextResponse.json({session:c})}if(i==="/providers")return f.NextResponse.json({providers:{email:!!e.signIn.email,oauth:!!e.signIn.oauth,passkey:!!e.signIn.passkey}});if(i.startsWith("/oauth/callback")||d[0]==="oauth"&&d[1]==="callback"){if(!e.oauthCallback)return f.NextResponse.redirect(new URL("/login?error=oauth_not_configured",r.url));const c=d[2]||t.searchParams.get("provider"),a=t.searchParams.get("code"),m=t.searchParams.get("state");if(!c||!a||!m)return f.NextResponse.redirect(new URL("/login?error=oauth_missing_params",r.url));try{const v=await e.oauthCallback(c,a,m);if(v.success){const C=t.searchParams.get("callbackUrl")||"/";return f.NextResponse.redirect(new URL(C,r.url))}else return f.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(v.error||"oauth_failed")}`,r.url))}catch(v){return f.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(v instanceof Error?v.message:"oauth_error")}`,r.url))}}return f.NextResponse.json({error:"Not found"},{status:404})}if(s==="POST"){const c=await r.json().catch(()=>({}));if(i==="/sign-in"||d[0]==="sign-in"){if(c.provider==="email"&&c.email&&c.password){const a=await e.signIn.email({email:c.email,password:c.password});return f.NextResponse.json(a)}if(c.provider==="oauth"&&c.providerName){if(!e.signIn.oauth)return f.NextResponse.json({success:!1,error:"OAuth is not configured"},{status:400});const a=await e.signIn.oauth(c.providerName);return f.NextResponse.json(a)}if(c.provider==="passkey"){if(!e.signIn.passkey)return f.NextResponse.json({success:!1,error:"PassKey is not configured"},{status:400});const a=await e.signIn.passkey(c.options);return f.NextResponse.json(a)}return f.NextResponse.json({success:!1,error:"Invalid sign in request"},{status:400})}if(i==="/sign-up"||d[0]==="sign-up"){if(!e.signUp)return f.NextResponse.json({success:!1,error:"Sign up is not configured"},{status:400});const a=await e.signUp(c);return f.NextResponse.json(a)}if(i==="/sign-out"||d[0]==="sign-out"){const a=await e.signOut();return f.NextResponse.json(a)}if(i==="/reset-password"||d[0]==="reset-password"){if(!e.resetPassword)return f.NextResponse.json({success:!1,error:"Password reset is not configured"},{status:400});const a=await e.resetPassword(c.email);return f.NextResponse.json(a)}if(i==="/verify-email"||d[0]==="verify-email"){if(!e.verifyEmail)return f.NextResponse.json({success:!1,error:"Email verification is not configured"},{status:400});const a=await e.verifyEmail(c.token);return f.NextResponse.json(a)}if(i==="/refresh"||d[0]==="refresh"){if(!e.refreshSession){const m=await e.getSession();return f.NextResponse.json({session:m})}const a=await e.refreshSession();return f.NextResponse.json({session:a})}if(i.startsWith("/oauth/callback")||d[0]==="oauth"&&d[1]==="callback"){if(!e.oauthCallback)return f.NextResponse.json({success:!1,error:"OAuth callback is not configured"},{status:400});const a=c.provider||d[2]||t.searchParams.get("provider"),m=c.code||t.searchParams.get("code"),v=c.state||t.searchParams.get("state");if(!a||!m||!v)return f.NextResponse.json({success:!1,error:"Missing required OAuth parameters. Provider, code, and state are required."},{status:400});const C=await e.oauthCallback(a,m,v);return f.NextResponse.json(C)}if(i.startsWith("/passkey")){if(!e.passkey)return f.NextResponse.json({success:!1,error:"PassKey is not configured"},{status:400});if(d[1]==="register"&&e.passkey.register){const a=await e.passkey.register(c.options);return f.NextResponse.json(a)}if(d[1]==="list"&&e.passkey.list){const a=await e.passkey.list();return f.NextResponse.json(a)}if(d[1]==="remove"&&e.passkey.remove){const a=await e.passkey.remove(c.passkeyId);return f.NextResponse.json(a)}}if(i==="/verify-2fa"||d[0]==="verify-2fa"){if(!e.verify2FA)return f.NextResponse.json({success:!1,error:"2FA verification is not configured"},{status:400});if(!c.email||!c.userId||!c.code)return f.NextResponse.json({success:!1,error:"Missing required parameters. Email, userId, and code are required."},{status:400});const a=await e.verify2FA({email:c.email,userId:c.userId,code:c.code});return f.NextResponse.json(a)}if(i.startsWith("/two-factor")){if(!e.twoFactor)return f.NextResponse.json({success:!1,error:"Two-Factor Authentication is not configured"},{status:400});if(d[1]==="enable"&&e.twoFactor.enable){const a=await e.twoFactor.enable();return f.NextResponse.json(a)}if(d[1]==="verify"&&e.twoFactor.verify){const a=await e.twoFactor.verify(c.code);return f.NextResponse.json(a)}if(d[1]==="disable"&&e.twoFactor.disable){const a=await e.twoFactor.disable();return f.NextResponse.json(a)}if(d[1]==="backup-codes"&&e.twoFactor.generateBackupCodes){const a=await e.twoFactor.generateBackupCodes();return f.NextResponse.json(a)}if(d[1]==="is-enabled"&&e.twoFactor.isEnabled){const a=await e.twoFactor.isEnabled();return f.NextResponse.json({enabled:a})}}return f.NextResponse.json({error:"Not found"},{status:404})}return f.NextResponse.json({error:"Method not allowed"},{status:405})}catch(c){return f.NextResponse.json({success:!1,error:c instanceof Error?c.message:"Request failed"},{status:500})}}function Fe(r){return async e=>{const{method:s,nextUrl:t}=e,d=t.pathname.replace(/^\/api\/auth/,"")||"/";try{let c;if(s!=="GET"&&s!=="HEAD")try{c=await e.json()}catch{}const a=Object.fromEntries(t.searchParams.entries()),m=await fetch(`${process.env.NEXT_PUBLIC_API_URL||""}/api/auth${d}${Object.keys(a).length>0?`?${new URLSearchParams(a).toString()}`:""}`,{method:s,headers:{"Content-Type":"application/json",...Object.fromEntries(e.headers.entries())},body:c?JSON.stringify(c):void 0}),v=await m.json();return f.NextResponse.json(v,{status:m.status,headers:{...Object.fromEntries(m.headers.entries())}})}catch(c){return console.error("API handler error:",c),f.NextResponse.json({success:!1,error:c instanceof Error?c.message:"Internal server error"},{status:500})}}}function Le(r){return async e=>{const{searchParams:s}=e.nextUrl,t=s.get("provider"),i=s.get("code"),d=s.get("state");if(!t||!i||!d)return f.NextResponse.redirect(new URL("/login?error=oauth_missing_params",e.url));try{if(!r.oauthCallback)return f.NextResponse.redirect(new URL("/login?error=oauth_not_configured",e.url));const c=await r.oauthCallback(t,i,d);if(c.success){const a=s.get("callbackUrl")||"/";return f.NextResponse.redirect(new URL(a,e.url))}else{const a=c.errorCode?`${encodeURIComponent(c.error||"oauth_failed")}&code=${c.errorCode}`:encodeURIComponent(c.error||"oauth_failed");return f.NextResponse.redirect(new URL(`/login?error=${a}`,e.url))}}catch(c){return process.env.NODE_ENV==="development"&&console.error("[Mulguard] OAuth callback error:",c),f.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(c instanceof Error?c.message:"oauth_error")}`,e.url))}}}function U(r,e){const s=q({"X-Frame-Options":"SAMEORIGIN"});for(const[t,i]of Object.entries(s))i&&typeof i=="string"&&e.headers.set(t,i);return e}function je(){return async r=>{const e=f.NextResponse.next();return U(r,e)}}function De(r,e={}){const{protectedRoutes:s=[],publicRoutes:t=[],redirectTo:i="/login",redirectIfAuthenticated:d}=e;return async c=>{const{pathname:a}=c.nextUrl,m=s.some(g=>a.startsWith(g));let v=null;try{v=await r.getSession()}catch(g){console.error("Middleware: Failed to get session:",g)}if(m&&!v){const g=c.nextUrl.clone();return g.pathname=i,g.searchParams.set("callbackUrl",a),f.NextResponse.redirect(g)}if(d&&v&&(a.startsWith("/login")||a.startsWith("/register"))){const S=c.nextUrl.clone();S.pathname=d;const N=f.NextResponse.redirect(S);return U(c,N)}const C=f.NextResponse.next();return U(c,C)}}async function Me(r,e){var s;try{const t=await r.getSession();return t?((s=t.user.roles)==null?void 0:s.includes(e))??!1:!1}catch{return!1}}function Ve(r){const{auth:e,protectedRoutes:s=[],publicRoutes:t=[],redirectTo:i="/login",redirectIfAuthenticated:d,apiPrefix:c="/api/auth"}=r;return async a=>{const{pathname:m}=a.nextUrl;if(m.startsWith(c)){const S=f.NextResponse.next();return U(a,S)}const v=s.some(S=>m.startsWith(S));let C=null;if(v||d)try{C=await e.getSession()}catch(S){console.error("Middleware: Failed to get session:",S)}if(v&&!C){const S=a.nextUrl.clone();S.pathname=i,S.searchParams.set("callbackUrl",m);const N=f.NextResponse.redirect(S);return U(a,N)}if(d&&C&&(m.startsWith("/login")||m.startsWith("/register"))){const N=a.nextUrl.clone();N.pathname=d;const b=f.NextResponse.redirect(N);return U(a,b)}const g=f.NextResponse.next();return U(a,g)}}async function $e(r,e){var s;try{const t=await r.getSession();return t?((s=t.user.roles)==null?void 0:s.includes(e))??!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=k.createAuthMiddleware;exports.createServerHelpers=k.createServerHelpers;exports.createServerUtils=k.createServerUtils;exports.createSessionManager=k.createSessionManager;exports.deleteOAuthStateCookie=k.deleteOAuthStateCookie;exports.getCurrentUser=k.getCurrentUser;exports.getOAuthStateCookie=k.getOAuthStateCookie;exports.getServerSession=k.getServerSession;exports.getSessionTimeUntilExpiry=k.getSessionTimeUntilExpiry;exports.isSessionExpiredNullable=k.isSessionExpiredNullable;exports.isSessionExpiringSoon=k.isSessionExpiringSoon;exports.isSessionValid=k.isSessionValid;exports.refreshSession=k.refreshSession;exports.requireAuth=k.requireAuth;exports.requireRole=k.requireRole;exports.requireServerAuthMiddleware=k.requireAuthMiddleware;exports.requireServerRoleMiddleware=k.requireRoleMiddleware;exports.storeOAuthStateCookie=k.storeOAuthStateCookie;exports.validateSessionStructure=k.validateSessionStructure;exports.CSRFProtection=Y;exports.DEFAULT_SECURITY_HEADERS=K;exports.MemoryCSRFStore=X;exports.MemoryOAuthStateStore=se;exports.RateLimiter=B;exports.applySecurityHeaders=ue;exports.buildOAuthAuthorizationUrl=ee;exports.checkRole=Me;exports.checkRoleProxy=$e;exports.containsXSSPattern=me;exports.createApiHandler=Fe;exports.createAuthMiddleware=De;exports.createCSRFProtection=ge;exports.createMemoryOAuthStateStore=oe;exports.createOAuthCallbackHandler=Le;exports.createProxyMiddleware=Ve;exports.createRateLimiter=ce;exports.createSecurityMiddleware=je;exports.escapeHTML=G;exports.exchangeOAuthCode=re;exports.generateCSRFToken=J;exports.generateToken=W;exports.getErrorCode=Ae;exports.getErrorMessage=ve;exports.getOAuthUserInfo=te;exports.getProviderMetadata=V;exports.getSecurityHeaders=q;exports.getUserFriendlyError=Ie;exports.hasErrorCode=Se;exports.isAuthError=Z;exports.isAuthSuccess=ke;exports.isRetryableError=Ce;exports.isTwoFactorRequired=ye;exports.isValidEmail=Re;exports.mulguard=Pe;exports.sanitizeHTML=pe;exports.sanitizeInput=Ee;exports.sanitizeUserInput=we;exports.signIn=Oe;exports.toNextJsHandler=Ue;exports.validateAndSanitizeEmail=$;exports.validateAndSanitizeInput=z;exports.validateAndSanitizeName=fe;exports.validateAndSanitizePassword=le;exports.validateCSRFToken=Q;exports.validateToken=he;exports.validateURL=de;exports.withSecurityHeaders=U;
|
|
1
|
+
"use strict";var ne=Object.defineProperty;var ie=(r,e,s)=>e in r?ne(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var L=(r,e,s)=>ie(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("../actions-CExpv_dD.js"),A=require("../oauth-state-CzIWQq3s.js"),f=require("next/server"),j=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ae(r=32){if(j&&typeof j.getRandomValues=="function")return j.getRandomValues(new Uint8Array(r));if(j&&typeof j.randomBytes=="function")return Uint8Array.from(j.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}class B{constructor(e){L(this,"attempts",new Map);L(this,"config");this.config=e}check(e){const s=Date.now(),t=this.attempts.get(e);return!t||t.resetAt<s?(this.attempts.set(e,{count:1,resetAt:s+this.config.windowMs}),{allowed:!0,remaining:this.config.maxAttempts-1,resetAt:new Date(s+this.config.windowMs)}):t.count>=this.config.maxAttempts?{allowed:!1,remaining:0,resetAt:new Date(t.resetAt)}:(t.count++,{allowed:!0,remaining:this.config.maxAttempts-t.count,resetAt:new Date(t.resetAt)})}reset(e){this.attempts.delete(e)}clear(){this.attempts.clear()}}function ce(r){return new B(r)}const K={"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(r){return{...K,...r}}function ue(r,e){const s=q(e);for(const[t,n]of Object.entries(s))n&&r.set(t,n)}function $(r){if(!r||typeof r!="string")return{valid:!1,error:"Email is required"};const e=r.trim().toLowerCase();return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?e.length>254?{valid:!1,error:"Email is too long"}:e.includes("..")||e.startsWith(".")||e.endsWith(".")?{valid:!1,error:"Invalid email format"}:{valid:!0,sanitized:e}:{valid:!1,error:"Invalid email format"}}function le(r,e=8){if(!r||typeof r!="string")return{valid:!1,error:"Password is required"};if(r.length<e)return{valid:!1,error:`Password must be at least ${e} characters`};if(r.length>128)return{valid:!1,error:"Password is too long"};if(["password","12345678","qwerty","abc123","password123","123456789","1234567890","letmein","welcome","monkey","dragon","master","sunshine","princess","football"].includes(r.toLowerCase()))return{valid:!1,error:"Password is too common"};if(/(.)\1{3,}/.test(r))return{valid:!1,error:"Password contains too many repeated characters"};if(/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.test(r))return{valid:!1,error:"Password contains sequential characters"};let t="weak",n=0;return r.length>=12?n+=2:r.length>=8&&(n+=1),/[a-z]/.test(r)&&(n+=1),/[A-Z]/.test(r)&&(n+=1),/[0-9]/.test(r)&&(n+=1),/[^a-zA-Z0-9]/.test(r)&&(n+=1),n>=5?t="strong":n>=3&&(t="medium"),{valid:!0,strength:t}}function fe(r){if(!r||typeof r!="string")return{valid:!1,error:"Name is required"};const e=r.trim();return e.length<1?{valid:!1,error:"Name cannot be empty"}:e.length>100?{valid:!1,error:"Name is too long"}:{valid:!0,sanitized:e.replace(/[<>\"']/g,"")}}function de(r){if(!r||typeof r!="string")return{valid:!1,error:"URL is required"};try{const e=new URL(r);return["http:","https:"].includes(e.protocol)?{valid:!0}:{valid:!1,error:"URL must use http or https protocol"}}catch{return{valid:!1,error:"Invalid URL format"}}}function he(r,e=16){return!r||typeof r!="string"?{valid:!1,error:"Token is required"}:r.length<e?{valid:!1,error:"Token is too short"}:r.length>512?{valid:!1,error:"Token is too long"}:/^[A-Za-z0-9_-]+$/.test(r)?/(.)\1{10,}/.test(r)?{valid:!1,error:"Token contains suspicious pattern"}:{valid:!0}:{valid:!1,error:"Invalid token format"}}function z(r,e){const{maxLength:s=1e3,allowHtml:t=!1,required:n=!0}=e||{};if(n&&(!r||typeof r!="string"||r.trim().length===0))return{valid:!1,error:"Input is required"};if(!r||typeof r!="string")return{valid:!0,sanitized:""};let d=r.trim();return d.length>s?{valid:!1,error:`Input must be less than ${s} characters`}:(t||(d=d.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")),d=d.replace(/[\x00-\x1F\x7F]/g,""),{valid:!0,sanitized:d})}class X{constructor(){L(this,"tokens",new Map)}get(e){const s=this.tokens.get(e);return s?s.expiresAt<Date.now()?(this.delete(e),null):s.value:null}set(e,s,t=36e5){this.tokens.set(e,{value:s,expiresAt:Date.now()+t})}delete(e){this.tokens.delete(e)}clear(){this.tokens.clear()}}class Y{constructor(e,s=32){L(this,"store");L(this,"tokenLength");this.store=e||new X,this.tokenLength=s}generateToken(e,s){const t=W(this.tokenLength);return this.store.set(e,t,s),t}validateToken(e,s){const t=this.store.get(e);if(!t)return!1;const n=Q(s,t);return n&&this.store.delete(e),n}getToken(e){return this.store.get(e)}deleteToken(e){this.store.delete(e)}}function ge(r){return new Y(r)}function G(r){if(typeof r!="string")return"";const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return r.replace(/[&<>"']/g,s=>e[s]||s)}function pe(r){return typeof r!="string"?"":r.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript:/gi,"")}function we(r){return typeof r!="string"?"":G(r.trim())}function me(r){return typeof r!="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(s=>s.test(r))}function W(r=32){const e=ae(r);return Buffer.from(e).toString("base64url")}function J(){return W(32)}function Q(r,e){if(!r||!e||r.length!==e.length)return!1;let s=0;for(let t=0;t<r.length;t++)s|=r.charCodeAt(t)^e.charCodeAt(t);return s===0}function Ee(r){return r.trim().replace(/[<>]/g,"")}function Re(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Z(r){return!r.success&&!!r.error}function ye(r){return r.requires2FA===!0||r.errorCode===h.AuthErrorCode.TWO_FA_REQUIRED}function ke(r,e){return r.error?r.error:e||"Authentication failed"}function ve(r){return r.errorCode}function Ae(r){return r.success===!0&&!!r.user}function Se(r,e){return r.errorCode===e}function Ce(r){if(!Z(r))return!1;const e=[h.AuthErrorCode.NETWORK_ERROR,h.AuthErrorCode.RATE_LIMITED,h.AuthErrorCode.UNKNOWN_ERROR];return r.errorCode?e.includes(r.errorCode):!1}function Ie(r){if(r.error)return r.error;switch(r.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 Oe(r,e,s){return r.signIn(e,s)}const Ne={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 V(r){return Ne[r]||null}function ee(r,e,s,t){const n=V(r);if(!n)throw new Error(`Unknown OAuth provider: ${r}`);const d=e.redirectUri||`${s}/api/auth/callback/${r}`,c=e.scopes||n.defaultScopes,a=new URLSearchParams({client_id:e.clientId,redirect_uri:d,response_type:"code",scope:c.join(" "),state:t,...n.defaultParams,...e.params});return`${n.authorizationUrl}?${a.toString()}`}async function re(r,e,s,t){const n=V(r);if(!n)throw new Error(`Unknown OAuth provider: ${r}`);const d=new URLSearchParams({client_id:e.clientId,code:s,redirect_uri:t,grant_type:"authorization_code"});e.clientSecret&&d.append("client_secret",e.clientSecret);const c=await fetch(n.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:d.toString()});if(!c.ok){const a=await c.text();throw new Error(`Failed to exchange code for tokens: ${a}`)}return await c.json()}async function te(r,e){var d,c,a,m;const s=V(r);if(!s)throw new Error(`Unknown OAuth provider: ${r}`);const t=await fetch(s.userInfoUrl,{headers:{Authorization:`Bearer ${e}`,Accept:"application/json"}});if(!t.ok){const y=await t.text();throw new Error(`Failed to fetch user info: ${y}`)}const n=await t.json();switch(r){case"google":return{id:n.sub||n.id,email:n.email,name:n.name,avatar:n.picture,emailVerified:n.email_verified,rawProfile:n};case"github":let y=n.email,I={...n};if(!y){const S=await(await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`}})).json();y=((d=S.find(O=>O.primary))==null?void 0:d.email)||((c=S[0])==null?void 0:c.email)||`${n.login}@users.noreply.github.com`,I={...n,emails:S}}return{id:String(n.id),email:y,name:n.name||n.login,avatar:n.avatar_url,emailVerified:!!y,rawProfile:I};case"apple":return{id:n.sub,email:n.email,name:n.name?`${n.name.firstName} ${n.name.lastName}`:"",emailVerified:n.email_verified,rawProfile:n};case"facebook":return{id:n.id,email:n.email,name:n.name,avatar:(m=(a=n.picture)==null?void 0:a.data)==null?void 0:m.url,emailVerified:!0,rawProfile:n};default:return{id:String(n.id||n.sub),email:n.email,name:n.name||n.display_name||n.username,avatar:n.avatar||n.picture||n.avatar_url,emailVerified:n.email_verified||n.emailVerified||!1,rawProfile:n}}}class se{constructor(){L(this,"states",new Map)}set(e,s,t){this.states.set(e,s),this.cleanup()}get(e){const s=this.states.get(e);return s?s.expiresAt<Date.now()?(this.delete(e),null):s:null}delete(e){this.states.delete(e)}cleanup(){const e=Date.now();for(const[s,t]of this.states.entries())t.expiresAt<e&&this.states.delete(s)}}function oe(){return new se}function Te(r=process.env.NODE_ENV==="development"){const e="[Mulguard]";return{debug:r?(s,t)=>{t!==void 0?console.debug(`${e} ${s}`,t):console.debug(`${e} ${s}`)}:()=>{},info:r?(s,t)=>{t!==void 0?console.info(`${e} ${s}`,t):console.info(`${e} ${s}`)}:()=>{},warn:r?(s,t)=>{t!==void 0?console.warn(`${e} ${s}`,t):console.warn(`${e} ${s}`)}:()=>{},error:r?(s,t)=>{t!==void 0?console.error(`${e} ${s}`,t):console.error(`${e} ${s}`)}:()=>{}}}const b=Te();function _e(r,e,s,t={}){const{enabled:n=!0,maxRetries:d=1,retryDelay:c=1e3,rateLimit:a=3,autoSignOutOnFailure:m=!0,redirectToLogin:y="/login",autoRedirectOnFailure:I=!0}=t;let g=null,S=!1;const O=[],T=[],x=60*1e3;let _=0,N=!1,P=null;const D=2,M=60*1e3;function o(){const u=Date.now();if(N&&P){if(u<P)return!1;N=!1,P=null,_=0}for(;T.length>0;){const w=T[0];if(w!==void 0&&w<u-x)T.shift();else break}return T.length>=a?!1:(T.push(u),!0)}function i(){_++,_>=D&&(N=!0,P=Date.now()+M,process.env.NODE_ENV==="development"&&console.warn("[TokenRefreshManager] Circuit breaker opened - too many consecutive failures"))}function l(){_=0,N=!1,P=null}async function E(u=1){if(!n)return null;if(!o())throw new Error("Rate limit exceeded for token refresh");try{const w=await r();if(w)return l(),C(w),t.onTokenRefreshed&&await Promise.resolve(t.onTokenRefreshed(w)),w;if(i(),u<d)return await p(c*u),E(u+1);throw new Error("Token refresh failed: refresh function returned null")}catch(w){if(i(),u<d&&v(w))return await p(c*u),E(u+1);throw w}}function v(u){if(u instanceof Error){const w=u.message.toLowerCase();if(w.includes("rate limit")||w.includes("too many requests")||w.includes("429")||w.includes("limit:")||w.includes("requests per minute")||w.includes("token_blacklisted")||w.includes("blacklisted")||w.includes("invalid")||w.includes("401")||w.includes("unauthorized")||w.includes("session has been revoked")||w.includes("session expired"))return!1;if(w.includes("network")||w.includes("fetch")||w.includes("timeout"))return!0}return!1}function C(u){const w=[...O];O.length=0;for(const{resolve:F}of w)F(u)}function R(u){const w=[...O];O.length=0;for(const{reject:F}of w)F(u)}function p(u){return new Promise(w=>setTimeout(w,u))}async function k(u){try{if(t.onTokenRefreshFailed&&await Promise.resolve(t.onTokenRefreshFailed(u)),m&&(await s(),await e(),I&&typeof window<"u")){let w=!0;if(t.onBeforeRedirect&&(w=await Promise.resolve(t.onBeforeRedirect(u))),w){const F=new URL(y,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(w){process.env.NODE_ENV==="development"&&console.error("[TokenRefreshManager] Error in handleRefreshFailure:",w)}}return{async refreshToken(){return n?g||(S=!0,g=E().then(u=>(S=!1,g=null,u)).catch(u=>{throw S=!1,g=null,R(u),k(u).catch(()=>{}),u}),g):null},isRefreshing(){return S},async waitForRefresh(){return g?new Promise((u,w)=>{O.push({resolve:u,reject:w})}):null},clear(){g=null,S=!1,T.length=0,l(),R(new Error("Token refresh manager cleared"))},async handleRefreshFailure(u){return k(u)}}}function be(){const r=process.env.NODE_ENV==="production";return{cookieName:"__mulguard_session",expiresIn:60*60*24*7,httpOnly:!0,secure:r,sameSite:"lax",path:"/"}}function Pe(){return{enabled:!0,refreshThreshold:300,maxRetries:0,retryDelay:1e3,rateLimit:1,autoSignOutOnFailure:!0,redirectToLogin:"/login",autoRedirectOnFailure:!0}}function xe(r){var D,M;const e={...be(),...r.session},s=r.actions,t=r.callbacks||{},n=((D=r.providers)==null?void 0:D.oauth)||{},d=process.env.NEXT_PUBLIC_URL||(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:"http://localhost:3000"),c={...Pe(),...r.tokenRefresh},a={...s};if(Object.keys(n).length>0&&!a.signIn.oauth&&(a.signIn.oauth=async o=>{const i=n[o];if(!i)throw new Error(`OAuth provider "${o}" is not configured. Add it to providers.oauth in config.`);if(!i.clientId)throw new Error(`OAuth provider "${o}" is missing clientId`);const l=J();return{url:ee(o,i,d,l),state:l}}),Object.keys(n).length>0&&!a.oauthCallback&&(a.oauthCallback=async(o,i,l)=>{const E=n[o];if(!E)return{success:!1,error:`OAuth provider "${o}" is not configured`,errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const v=E.redirectUri||`${d}/api/auth/callback/${o}`,C=await re(o,E,i,v),R=await te(o,C.access_token),p={id:R.id,email:R.email,name:R.name,avatar:R.avatar,emailVerified:R.emailVerified,provider:o,accessToken:C.access_token,refreshToken:C.refresh_token,tokens:{access_token:C.access_token,refresh_token:C.refresh_token,expires_in:C.expires_in,token_type:C.token_type,id_token:C.id_token},rawProfile:R.rawProfile};if(t.onOAuthUser){const k=await g(t.onOAuthUser,p,o);if(!k)return{success:!1,error:"Failed to create or retrieve user",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const u={user:{id:k.id,email:k.email,name:k.name,avatar:p.avatar,emailVerified:p.emailVerified},expiresAt:new Date(Date.now()+7*24*60*60*1e3),accessToken:C.access_token,refreshToken:C.refresh_token,tokenType:"Bearer",expiresIn:C.expires_in};return await T(u),m={session:u,timestamp:Date.now()},t.onSignIn&&await g(t.onSignIn,u.user,u),{success:!0,user:u.user,session:u}}return{success:!1,error:"OAuth user callback not implemented. Provide onOAuthUser callback or implement oauthCallback action.",errorCode:h.AuthErrorCode.VALIDATION_ERROR}}catch(v){return b.error("OAuth callback failed",{provider:o,error:v}),{success:!1,error:v instanceof Error?v.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}}),!a.signIn||!a.signIn.email)throw new Error("mulguard: signIn.email action is required");let m=null;const y=((M=r.session)==null?void 0:M.cacheTtl)??r.sessionCacheTtl??5e3,I=r.oauthStateStore||oe(),g=async(o,...i)=>{if(o)try{return await o(...i)}catch(l){throw t.onError&&await t.onError(l instanceof Error?l:new Error(String(l)),"callback"),l}},S=async(o,i)=>{const l={provider:i,expiresAt:Date.now()+6e5};await Promise.resolve(I.set(o,l,10*60*1e3)),I.cleanup&&await Promise.resolve(I.cleanup())},O=async(o,i)=>{const l=await Promise.resolve(I.get(o));return l?l.expiresAt<Date.now()?(await Promise.resolve(I.delete(o)),!1):l.provider!==i?!1:(await Promise.resolve(I.delete(o)),!0):!1},T=async o=>{const i=e.cookieName||"__mulguard_session",l=typeof o=="object"&&"token"in o?String(o.token):JSON.stringify(o),E=h.buildCookieOptions(i,l,e);return await h.setCookie(E)},x=async o=>{if(!o.success||!o.session)return{success:!0};const i=await T(o.session);return m={session:o.session,timestamp:Date.now()},o.user&&t.onSignIn&&await g(t.onSignIn,o.user,o.session),i},_=async()=>{const o=e.cookieName||"__mulguard_session";await h.deleteCookie(o,{path:e.path,domain:e.domain})};let N=null;const P={async getSession(){const o=Date.now();if(m&&o-m.timestamp<y)return m.session;if(s.getSession)try{const i=await s.getSession();if(i&&A.validateSessionStructure(i))return m={session:i,timestamp:o},i;i&&!A.validateSessionStructure(i)&&(await _(),m=null)}catch(i){b.debug("getSession error",{error:i}),t.onError&&await g(t.onError,i instanceof Error?i:new Error(String(i)),"getSession"),m=null}try{const i=e.cookieName||"__mulguard_session",l=await h.getCookie(i);if(l)try{const E=JSON.parse(l);if(A.validateSessionStructure(E))return E.expiresAt&&new Date(E.expiresAt)<new Date?(t.onSessionExpired&&await g(t.onSessionExpired,E),await _(),m=null,null):(m={session:E,timestamp:o},E);await _(),m=null}catch{await _(),m=null}}catch(i){const l=i instanceof Error?i.message:String(i);!l.includes("request scope")&&!l.includes("cookies")&&(b.warn("getSession cookie error",{error:i}),t.onError&&await g(t.onError,i instanceof Error?i:new Error(String(i)),"getSession.cookie"))}return null},async getAccessToken(){const o=await this.getSession();return o!=null&&o.accessToken&&typeof o.accessToken=="string"?o.accessToken:null},async getRefreshToken(){const o=await this.getSession();return o!=null&&o.refreshToken&&typeof o.refreshToken=="string"?o.refreshToken:null},async hasValidTokens(){return!!await this.getAccessToken()},signIn:(()=>{const o=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 p=$(R.email);if(!p.valid)return{success:!1,error:p.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 k={email:p.sanitized,password:R.password},u=await a.signIn.email(k);return u.success&&u.session&&await x(u),u.success?b.info("Sign in successful",{email:k.email.substring(0,3)+"***"}):b.warn("Sign in failed",{email:k.email.substring(0,3)+"***",errorCode:u.errorCode}),u}catch(p){const k=p instanceof Error?p.message:"Sign in failed";return b.error("Sign in error",{error:k,context:"signIn.email"}),t.onError&&await g(t.onError,p instanceof Error?p:new Error(String(p)),"signIn.email"),{success:!1,error:"Sign in failed. Please try again.",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}},i=async R=>{if(!R||typeof R!="string")throw new Error("Provider is required");const p=z(R,{maxLength:50,allowHtml:!1,required:!0});if(!p.valid||!p.sanitized)throw new Error("Invalid provider");const k=p.sanitized.toLowerCase();if(!a.signIn.oauth)throw new Error("OAuth sign in is not configured. Either provide oauth action in signIn, or configure providers.oauth in config.");const u=await a.signIn.oauth(k);return await S(u.state,k),b.info("OAuth sign in initiated",{provider:k}),u},l=async R=>{if(!a.signIn.passkey)throw new Error("PassKey sign in is not configured. Provide passkey action in signIn.");try{const p=await a.signIn.passkey(R);return p.success&&p.session&&await x(p),p}catch(p){return t.onError&&await g(t.onError,p instanceof Error?p:new Error(String(p)),"signIn.passkey"),{success:!1,error:p instanceof Error?p.message:"PassKey sign in failed"}}},E=async(R,p)=>{if(!R||typeof R!="string")return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const k=$(R);if(!k.valid)return{success:!1,error:k.error||"Invalid email format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(p!==void 0&&(typeof p!="string"||p.length<4||p.length>10))return{success:!1,error:"Invalid OTP code format",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!a.signIn.otp)return{success:!1,error:"OTP sign in is not configured",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const u=await a.signIn.otp(k.sanitized,p);return u.success&&u.session&&await x(u),u.success?b.info("OTP sign in successful",{email:k.sanitized.substring(0,3)+"***"}):b.warn("OTP sign in failed",{email:k.sanitized.substring(0,3)+"***"}),u}catch(u){return b.error("OTP sign in error",{error:u instanceof Error?u.message:"Unknown error",context:"signIn.otp"}),t.onError&&await g(t.onError,u instanceof Error?u:new Error(String(u)),"signIn.otp"),{success:!1,error:"OTP sign in failed. Please try again.",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}},C=Object.assign(async(R,p)=>{if(!R||typeof R!="string")throw new Error("Provider is required");const k=z(R,{maxLength:50,allowHtml:!1,required:!0});if(!k.valid||!k.sanitized)throw new Error("Invalid provider");const u=k.sanitized.toLowerCase();if(u==="google"||u==="github"||u==="apple"||u==="facebook"||typeof u=="string"&&!["credentials","otp","passkey"].includes(u))return i(u);if(u==="credentials")return!p||!("email"in p)||!("password"in p)?{success:!1,error:"Credentials are required",errorCode:h.AuthErrorCode.VALIDATION_ERROR}:o(p);if(u==="otp"){if(!p||!("email"in p))return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const w=p;return E(w.email,w.code)}return u==="passkey"?l(p):{success:!1,error:"Invalid provider",errorCode:h.AuthErrorCode.VALIDATION_ERROR}},{email:o,oauth:a.signIn.oauth?i:void 0,passkey:a.signIn.passkey?l:void 0,otp:a.signIn.otp?E:void 0});return N=C,C})(),async signUp(o){if(!a.signUp)throw new Error("Sign up is not configured. Provide signUp action in config.");try{const i=await a.signUp(o);return i.success&&i.session&&await x(i),i}catch(i){return t.onError&&await g(t.onError,i instanceof Error?i:new Error(String(i)),"signUp"),{success:!1,error:i instanceof Error?i.message:"Sign up failed"}}},async signOut(){try{const o=await this.getSession(),i=o==null?void 0:o.user;return s.signOut&&await s.signOut(),await _(),m=null,i&&t.onSignOut&&await g(t.onSignOut,i),{success:!0}}catch(o){return await _(),t.onError&&await g(t.onError,o instanceof Error?o:new Error(String(o)),"signOut"),{success:!1,error:o instanceof Error?o.message:"Sign out failed"}}},async resetPassword(o){if(!s.resetPassword)throw new Error("Password reset is not configured. Provide resetPassword action in config.");try{return await s.resetPassword(o)}catch(i){return t.onError&&await g(t.onError,i instanceof Error?i:new Error(String(i)),"resetPassword"),{success:!1,error:i instanceof Error?i.message:"Password reset failed"}}},async verifyEmail(o){if(!s.verifyEmail)throw new Error("Email verification is not configured. Provide verifyEmail action in config.");try{return await s.verifyEmail(o)}catch(i){return t.onError&&await g(t.onError,i instanceof Error?i:new Error(String(i)),"verifyEmail"),{success:!1,error:i instanceof Error?i.message:"Email verification failed"}}},async refreshSession(){if(!s.refreshSession)return this.getSession();try{const o=await s.refreshSession();if(o&&A.validateSessionStructure(o)){if(await T(o),m={session:o,timestamp:Date.now()},t.onSessionUpdate){const i=await g(t.onSessionUpdate,o);if(i&&A.validateSessionStructure(i)){if(await T(i),t.onTokenRefresh){const l=await this.getSession();l&&await g(t.onTokenRefresh,l,i)}return i}}if(t.onTokenRefresh){const i=await this.getSession();i&&await g(t.onTokenRefresh,i,o)}return o}else if(o&&!A.validateSessionStructure(o))return await _(),null;return null}catch(o){return await _(),t.onError&&await g(t.onError,o instanceof Error?o:new Error(String(o)),"refreshSession"),null}},async oauthCallback(o,i,l){if(!a.oauthCallback)throw new Error("OAuth callback is not configured. Either provide oauthCallback action, or configure providers.oauth in config.");if(!o||!i||!l)return{success:!1,error:"Missing required OAuth parameters (provider, code, or state)",errorCode:h.AuthErrorCode.VALIDATION_ERROR};if(!await O(l,o))return{success:!1,error:"Invalid or expired state parameter",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{const v=await a.oauthCallback(o,i,l);if(v.success&&v.session){const C=await x(v);C.success||(process.env.NODE_ENV==="development"&&b.debug("Failed to save session cookie after oauthCallback",{error:C.error,warning:C.warning}),t.onError&&await g(t.onError,new Error(C.warning||C.error||"Failed to save session cookie"),"oauthCallback.setSession"))}return v}catch(v){return t.onError&&await g(t.onError,v instanceof Error?v:new Error(String(v)),"oauthCallback"),{success:!1,error:v instanceof Error?v.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}},async verify2FA(o,i){if(!s.verify2FA)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const l=await s.verify2FA(o);if(l.success&&l.session&&!(i!=null&&i.skipCookieSave)){const E=await x(l);E.success||(process.env.NODE_ENV==="development"&&b.debug("Failed to save session cookie after verify2FA",{error:E.error,warning:E.warning}),t.onError&&await g(t.onError,new Error(E.warning||E.error||"Failed to save session cookie"),"verify2FA.setSession"))}return l}catch(l){return t.onError&&await g(t.onError,l instanceof Error?l:new Error(String(l)),"verify2FA"),{success:!1,error:l instanceof Error?l.message:"2FA verification failed",errorCode:h.AuthErrorCode.TWO_FA_REQUIRED}}},async setSession(o){return A.validateSessionStructure(o)?await T(o):{success:!1,error:"Invalid session structure"}},_getSessionConfig(){return{cookieName:e.cookieName||"__mulguard_session",config:e}},_getCallbacks(){return t},passkey:s.passkey?{register:s.passkey.register,authenticate:async o=>{var i;if(!((i=s.passkey)!=null&&i.authenticate))throw new Error("PassKey authenticate is not configured.");try{const l=await s.passkey.authenticate(o);return l.success&&l.session&&await x(l),l}catch(l){return t.onError&&await g(t.onError,l instanceof Error?l:new Error(String(l)),"passkey.authenticate"),{success:!1,error:l instanceof Error?l.message:"PassKey authentication failed"}}},list:s.passkey.list,remove:s.passkey.remove}:void 0,twoFactor:s.twoFactor?{enable:s.twoFactor.enable,verify:s.twoFactor.verify,disable:s.twoFactor.disable,generateBackupCodes:s.twoFactor.generateBackupCodes,isEnabled:s.twoFactor.isEnabled,verify2FA:async o=>{var l;const i=((l=s.twoFactor)==null?void 0:l.verify2FA)||s.verify2FA;if(!i)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const E=await i(o);if(E.success&&E.session){const v=await x(E);v.success||(process.env.NODE_ENV==="development"&&b.debug("Failed to save session cookie after twoFactor.verify2FA",{error:v.error,warning:v.warning}),t.onError&&await g(t.onError,new Error(v.warning||v.error||"Failed to save session cookie"),"twoFactor.verify2FA.setSession"))}return E}catch(E){return t.onError&&await g(t.onError,E instanceof Error?E:new Error(String(E)),"twoFactor.verify2FA"),{success:!1,error:E instanceof Error?E.message:"2FA verification failed",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}}}:void 0,signInMethods:{email:o=>N.email(o),oauth:o=>{var i;return((i=N.oauth)==null?void 0:i.call(N,o))||Promise.reject(new Error("OAuth not configured"))},passkey:o=>{var i;return((i=N.passkey)==null?void 0:i.call(N,o))||Promise.reject(new Error("Passkey not configured"))},otp:(o,i)=>{var l;return((l=N.otp)==null?void 0:l.call(N,o,i))||Promise.reject(new Error("OTP not configured"))}}};if(s.refreshSession){const o=_e(async()=>await P.refreshSession(),async()=>await P.signOut(),async()=>{await _()},{...c,onTokenRefreshed:c.onTokenRefreshed,onTokenRefreshFailed:c.onTokenRefreshFailed,onBeforeRedirect:c.onBeforeRedirect});P._tokenRefreshManager=o,P._getTokenRefreshManager=()=>o}return P}function Ue(r){return{GET:async e=>H(e,r,"GET"),POST:async e=>H(e,r,"POST")}}async function H(r,e,s){const t=new URL(r.url),n=t.pathname.replace(/^\/api\/auth/,"")||"/session",d=n.split("/").filter(Boolean);try{if(s==="GET"){if(n==="/session"||n==="/"){const c=await e.getSession();return f.NextResponse.json({session:c})}if(n==="/providers")return f.NextResponse.json({providers:{email:!!e.signIn.email,oauth:!!e.signIn.oauth,passkey:!!e.signIn.passkey}});if(n.startsWith("/oauth/callback")||d[0]==="oauth"&&d[1]==="callback"){if(!e.oauthCallback)return f.NextResponse.redirect(new URL("/login?error=oauth_not_configured",r.url));const c=d[2]||t.searchParams.get("provider"),a=t.searchParams.get("code"),m=t.searchParams.get("state");if(!c||!a||!m)return f.NextResponse.redirect(new URL("/login?error=oauth_missing_params",r.url));try{const y=await e.oauthCallback(c,a,m);if(y.success){const I=t.searchParams.get("callbackUrl")||"/";return f.NextResponse.redirect(new URL(I,r.url))}else return f.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(y.error||"oauth_failed")}`,r.url))}catch(y){return f.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(y instanceof Error?y.message:"oauth_error")}`,r.url))}}return f.NextResponse.json({error:"Not found"},{status:404})}if(s==="POST"){const c=await r.json().catch(()=>({}));if(n==="/sign-in"||d[0]==="sign-in"){if(c.provider==="email"&&c.email&&c.password){const a=await e.signIn.email({email:c.email,password:c.password});return f.NextResponse.json(a)}if(c.provider==="oauth"&&c.providerName){if(!e.signIn.oauth)return f.NextResponse.json({success:!1,error:"OAuth is not configured"},{status:400});const a=await e.signIn.oauth(c.providerName);return f.NextResponse.json(a)}if(c.provider==="passkey"){if(!e.signIn.passkey)return f.NextResponse.json({success:!1,error:"PassKey is not configured"},{status:400});const a=await e.signIn.passkey(c.options);return f.NextResponse.json(a)}return f.NextResponse.json({success:!1,error:"Invalid sign in request"},{status:400})}if(n==="/sign-up"||d[0]==="sign-up"){if(!e.signUp)return f.NextResponse.json({success:!1,error:"Sign up is not configured"},{status:400});const a=await e.signUp(c);return f.NextResponse.json(a)}if(n==="/sign-out"||d[0]==="sign-out"){const a=await e.signOut();return f.NextResponse.json(a)}if(n==="/reset-password"||d[0]==="reset-password"){if(!e.resetPassword)return f.NextResponse.json({success:!1,error:"Password reset is not configured"},{status:400});const a=await e.resetPassword(c.email);return f.NextResponse.json(a)}if(n==="/verify-email"||d[0]==="verify-email"){if(!e.verifyEmail)return f.NextResponse.json({success:!1,error:"Email verification is not configured"},{status:400});const a=await e.verifyEmail(c.token);return f.NextResponse.json(a)}if(n==="/refresh"||d[0]==="refresh"){if(!e.refreshSession){const m=await e.getSession();return f.NextResponse.json({session:m})}const a=await e.refreshSession();return f.NextResponse.json({session:a})}if(n.startsWith("/oauth/callback")||d[0]==="oauth"&&d[1]==="callback"){if(!e.oauthCallback)return f.NextResponse.json({success:!1,error:"OAuth callback is not configured"},{status:400});const a=c.provider||d[2]||t.searchParams.get("provider"),m=c.code||t.searchParams.get("code"),y=c.state||t.searchParams.get("state");if(!a||!m||!y)return f.NextResponse.json({success:!1,error:"Missing required OAuth parameters. Provider, code, and state are required."},{status:400});const I=await e.oauthCallback(a,m,y);return f.NextResponse.json(I)}if(n.startsWith("/passkey")){if(!e.passkey)return f.NextResponse.json({success:!1,error:"PassKey is not configured"},{status:400});if(d[1]==="register"&&e.passkey.register){const a=await e.passkey.register(c.options);return f.NextResponse.json(a)}if(d[1]==="list"&&e.passkey.list){const a=await e.passkey.list();return f.NextResponse.json(a)}if(d[1]==="remove"&&e.passkey.remove){const a=await e.passkey.remove(c.passkeyId);return f.NextResponse.json(a)}}if(n==="/verify-2fa"||d[0]==="verify-2fa"){if(!e.verify2FA)return f.NextResponse.json({success:!1,error:"2FA verification is not configured"},{status:400});if(!c.email||!c.userId||!c.code)return f.NextResponse.json({success:!1,error:"Missing required parameters. Email, userId, and code are required."},{status:400});const a=await e.verify2FA({email:c.email,userId:c.userId,code:c.code});return f.NextResponse.json(a)}if(n.startsWith("/two-factor")){if(!e.twoFactor)return f.NextResponse.json({success:!1,error:"Two-Factor Authentication is not configured"},{status:400});if(d[1]==="enable"&&e.twoFactor.enable){const a=await e.twoFactor.enable();return f.NextResponse.json(a)}if(d[1]==="verify"&&e.twoFactor.verify){const a=await e.twoFactor.verify(c.code);return f.NextResponse.json(a)}if(d[1]==="disable"&&e.twoFactor.disable){const a=await e.twoFactor.disable();return f.NextResponse.json(a)}if(d[1]==="backup-codes"&&e.twoFactor.generateBackupCodes){const a=await e.twoFactor.generateBackupCodes();return f.NextResponse.json(a)}if(d[1]==="is-enabled"&&e.twoFactor.isEnabled){const a=await e.twoFactor.isEnabled();return f.NextResponse.json({enabled:a})}}return f.NextResponse.json({error:"Not found"},{status:404})}return f.NextResponse.json({error:"Method not allowed"},{status:405})}catch(c){return f.NextResponse.json({success:!1,error:c instanceof Error?c.message:"Request failed"},{status:500})}}function Fe(r){return async e=>{const{method:s,nextUrl:t}=e,d=t.pathname.replace(/^\/api\/auth/,"")||"/";try{let c;if(s!=="GET"&&s!=="HEAD")try{c=await e.json()}catch{}const a=Object.fromEntries(t.searchParams.entries()),m=await fetch(`${process.env.NEXT_PUBLIC_API_URL||""}/api/auth${d}${Object.keys(a).length>0?`?${new URLSearchParams(a).toString()}`:""}`,{method:s,headers:{"Content-Type":"application/json",...Object.fromEntries(e.headers.entries())},body:c?JSON.stringify(c):void 0}),y=await m.json();return f.NextResponse.json(y,{status:m.status,headers:{...Object.fromEntries(m.headers.entries())}})}catch(c){return console.error("API handler error:",c),f.NextResponse.json({success:!1,error:c instanceof Error?c.message:"Internal server error"},{status:500})}}}function Le(r){return async e=>{const{searchParams:s}=e.nextUrl,t=s.get("provider"),n=s.get("code"),d=s.get("state");if(!t||!n||!d)return f.NextResponse.redirect(new URL("/login?error=oauth_missing_params",e.url));try{if(!r.oauthCallback)return f.NextResponse.redirect(new URL("/login?error=oauth_not_configured",e.url));const c=await r.oauthCallback(t,n,d);if(c.success){const a=s.get("callbackUrl")||"/";return f.NextResponse.redirect(new URL(a,e.url))}else{const a=c.errorCode?`${encodeURIComponent(c.error||"oauth_failed")}&code=${c.errorCode}`:encodeURIComponent(c.error||"oauth_failed");return f.NextResponse.redirect(new URL(`/login?error=${a}`,e.url))}}catch(c){return process.env.NODE_ENV==="development"&&console.error("[Mulguard] OAuth callback error:",c),f.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(c instanceof Error?c.message:"oauth_error")}`,e.url))}}}function U(r,e){const s=q({"X-Frame-Options":"SAMEORIGIN"});for(const[t,n]of Object.entries(s))n&&typeof n=="string"&&e.headers.set(t,n);return e}function je(){return async r=>{const e=f.NextResponse.next();return U(r,e)}}function De(r,e={}){const{protectedRoutes:s=[],publicRoutes:t=[],redirectTo:n="/login",redirectIfAuthenticated:d}=e;return async c=>{const{pathname:a}=c.nextUrl,m=s.some(g=>a.startsWith(g));let y=null;try{y=await r.getSession()}catch(g){console.error("Middleware: Failed to get session:",g)}if(m&&!y){const g=c.nextUrl.clone();return g.pathname=n,g.searchParams.set("callbackUrl",a),f.NextResponse.redirect(g)}if(d&&y&&(a.startsWith("/login")||a.startsWith("/register"))){const S=c.nextUrl.clone();S.pathname=d;const O=f.NextResponse.redirect(S);return U(c,O)}const I=f.NextResponse.next();return U(c,I)}}async function Me(r,e){var s;try{const t=await r.getSession();return t?((s=t.user.roles)==null?void 0:s.includes(e))??!1:!1}catch{return!1}}function Ve(r){const{auth:e,protectedRoutes:s=[],publicRoutes:t=[],redirectTo:n="/login",redirectIfAuthenticated:d,apiPrefix:c="/api/auth"}=r;return async a=>{const{pathname:m}=a.nextUrl;if(m.startsWith(c)){const S=f.NextResponse.next();return U(a,S)}const y=s.some(S=>m.startsWith(S));let I=null;if(y||d)try{I=await e.getSession()}catch(S){console.error("Middleware: Failed to get session:",S)}if(y&&!I){const S=a.nextUrl.clone();S.pathname=n,S.searchParams.set("callbackUrl",m);const O=f.NextResponse.redirect(S);return U(a,O)}if(d&&I&&(m.startsWith("/login")||m.startsWith("/register"))){const O=a.nextUrl.clone();O.pathname=d;const T=f.NextResponse.redirect(O);return U(a,T)}const g=f.NextResponse.next();return U(a,g)}}async function $e(r,e){var s;try{const t=await r.getSession();return t?((s=t.user.roles)==null?void 0:s.includes(e))??!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=A.createAuthMiddleware;exports.createServerHelpers=A.createServerHelpers;exports.createServerUtils=A.createServerUtils;exports.createSessionManager=A.createSessionManager;exports.deleteOAuthStateCookie=A.deleteOAuthStateCookie;exports.getCurrentUser=A.getCurrentUser;exports.getOAuthStateCookie=A.getOAuthStateCookie;exports.getServerSession=A.getServerSession;exports.getSessionTimeUntilExpiry=A.getSessionTimeUntilExpiry;exports.isSessionExpiredNullable=A.isSessionExpiredNullable;exports.isSessionExpiringSoon=A.isSessionExpiringSoon;exports.isSessionValid=A.isSessionValid;exports.refreshSession=A.refreshSession;exports.requireAuth=A.requireAuth;exports.requireRole=A.requireRole;exports.requireServerAuthMiddleware=A.requireAuthMiddleware;exports.requireServerRoleMiddleware=A.requireRoleMiddleware;exports.storeOAuthStateCookie=A.storeOAuthStateCookie;exports.validateSessionStructure=A.validateSessionStructure;exports.CSRFProtection=Y;exports.DEFAULT_SECURITY_HEADERS=K;exports.MemoryCSRFStore=X;exports.MemoryOAuthStateStore=se;exports.RateLimiter=B;exports.applySecurityHeaders=ue;exports.buildOAuthAuthorizationUrl=ee;exports.checkRole=Me;exports.checkRoleProxy=$e;exports.containsXSSPattern=me;exports.createApiHandler=Fe;exports.createAuthMiddleware=De;exports.createCSRFProtection=ge;exports.createMemoryOAuthStateStore=oe;exports.createOAuthCallbackHandler=Le;exports.createProxyMiddleware=Ve;exports.createRateLimiter=ce;exports.createSecurityMiddleware=je;exports.escapeHTML=G;exports.exchangeOAuthCode=re;exports.generateCSRFToken=J;exports.generateToken=W;exports.getErrorCode=ve;exports.getErrorMessage=ke;exports.getOAuthUserInfo=te;exports.getProviderMetadata=V;exports.getSecurityHeaders=q;exports.getUserFriendlyError=Ie;exports.hasErrorCode=Se;exports.isAuthError=Z;exports.isAuthSuccess=Ae;exports.isRetryableError=Ce;exports.isTwoFactorRequired=ye;exports.isValidEmail=Re;exports.mulguard=xe;exports.sanitizeHTML=pe;exports.sanitizeInput=Ee;exports.sanitizeUserInput=we;exports.signIn=Oe;exports.toNextJsHandler=Ue;exports.validateAndSanitizeEmail=$;exports.validateAndSanitizeInput=z;exports.validateAndSanitizeName=fe;exports.validateAndSanitizePassword=le;exports.validateCSRFToken=Q;exports.validateToken=he;exports.validateURL=de;exports.withSecurityHeaders=U;
|