mulguard 1.1.1 → 1.1.3
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 +34 -0
- package/dist/core/auth/oauth-providers.d.ts +175 -47
- package/dist/core/mulguard/auth-handlers.d.ts +100 -0
- package/dist/core/mulguard/defaults.d.ts +58 -0
- package/dist/core/mulguard/index.d.ts +9 -0
- package/dist/core/mulguard/oauth-handler.d.ts +93 -0
- package/dist/core/mulguard/session-manager.d.ts +94 -0
- package/dist/core/security/index.d.ts +113 -9
- package/dist/core/security/validation.d.ts +231 -33
- package/dist/core/types/auth.d.ts +234 -75
- package/dist/core/types/errors.d.ts +174 -18
- package/dist/core/types/index.d.ts +399 -306
- package/dist/core/utils/logger.d.ts +112 -8
- package/dist/handlers/route.d.ts +59 -5
- package/dist/index/index.js +1 -1
- package/dist/index/index.mjs +1540 -1190
- package/dist/mulguard.d.ts +76 -1
- package/dist/server/helpers.d.ts +3 -3
- package/dist/server/utils.d.ts +3 -3
- package/package.json +1 -1
|
@@ -1,17 +1,121 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Structured logging utilities for Mulguard Authentication Library.
|
|
3
|
+
*
|
|
4
|
+
* Provides type-safe, structured logging with context and error handling.
|
|
5
|
+
*
|
|
6
|
+
* @module @mulguard/core/utils/logger
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Log level enumeration.
|
|
10
|
+
*/
|
|
11
|
+
export declare enum LogLevel {
|
|
12
|
+
DEBUG = 0,
|
|
13
|
+
INFO = 1,
|
|
14
|
+
WARN = 2,
|
|
15
|
+
ERROR = 3
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Log entry structure.
|
|
19
|
+
*/
|
|
20
|
+
export interface LogEntry {
|
|
21
|
+
readonly level: LogLevel;
|
|
22
|
+
readonly message: string;
|
|
23
|
+
readonly timestamp: Date;
|
|
24
|
+
readonly context?: string;
|
|
25
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
26
|
+
readonly error?: Error;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Logger interface.
|
|
3
30
|
*/
|
|
4
31
|
export interface Logger {
|
|
5
|
-
debug(message: string, data?: unknown)
|
|
6
|
-
info(message: string, data?: unknown)
|
|
7
|
-
warn(message: string, data?: unknown)
|
|
8
|
-
error(message: string, error?: Error | unknown)
|
|
32
|
+
readonly debug: (message: string, data?: Readonly<Record<string, unknown>>) => void;
|
|
33
|
+
readonly info: (message: string, data?: Readonly<Record<string, unknown>>) => void;
|
|
34
|
+
readonly warn: (message: string, data?: Readonly<Record<string, unknown>>) => void;
|
|
35
|
+
readonly error: (message: string, error?: Error | Readonly<Record<string, unknown>>) => void;
|
|
9
36
|
}
|
|
10
37
|
/**
|
|
11
|
-
*
|
|
38
|
+
* Logger configuration.
|
|
12
39
|
*/
|
|
13
|
-
export
|
|
40
|
+
export interface LoggerConfig {
|
|
41
|
+
readonly enabled?: boolean;
|
|
42
|
+
readonly level?: LogLevel;
|
|
43
|
+
readonly prefix?: string;
|
|
44
|
+
readonly context?: string;
|
|
45
|
+
readonly formatter?: (entry: LogEntry) => string;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Creates a logger instance with configuration.
|
|
49
|
+
*
|
|
50
|
+
* @param config - Logger configuration
|
|
51
|
+
* @returns Logger instance
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```typescript
|
|
55
|
+
* const logger = createLogger({
|
|
56
|
+
* enabled: true,
|
|
57
|
+
* level: LogLevel.INFO,
|
|
58
|
+
* context: 'Auth'
|
|
59
|
+
* })
|
|
60
|
+
*
|
|
61
|
+
* logger.info('User signed in', { userId: '123' })
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare function createLogger(config?: LoggerConfig): Logger;
|
|
14
65
|
/**
|
|
15
|
-
* Default logger instance
|
|
66
|
+
* Default logger instance.
|
|
67
|
+
*
|
|
68
|
+
* Uses development settings by default.
|
|
16
69
|
*/
|
|
17
70
|
export declare const logger: Logger;
|
|
71
|
+
/**
|
|
72
|
+
* Type predicate to check if a value is a valid Logger.
|
|
73
|
+
*
|
|
74
|
+
* @param value - Value to check
|
|
75
|
+
* @returns True if value is a Logger
|
|
76
|
+
*/
|
|
77
|
+
export declare function isLogger(value: unknown): value is Logger;
|
|
78
|
+
/**
|
|
79
|
+
* TODO: Performance
|
|
80
|
+
* - [ ] Add log batching for high-frequency operations
|
|
81
|
+
* - [ ] Implement async logging for non-blocking operations
|
|
82
|
+
* - [ ] Add log rotation and cleanup
|
|
83
|
+
* - [ ] Consider structured logging libraries (pino, winston)
|
|
84
|
+
*
|
|
85
|
+
* TODO: Features
|
|
86
|
+
* - [ ] Add log levels filtering at runtime
|
|
87
|
+
* - [ ] Implement log transport abstraction (console, file, remote)
|
|
88
|
+
* - [ ] Add log correlation IDs
|
|
89
|
+
* - [ ] Create log aggregation support
|
|
90
|
+
* - [ ] Add performance metrics logging
|
|
91
|
+
* - [ ] Implement log sampling for high-volume scenarios
|
|
92
|
+
*
|
|
93
|
+
* TODO: Type Safety
|
|
94
|
+
* - [ ] Add type-safe log data validation
|
|
95
|
+
* - [ ] Create log schema definitions
|
|
96
|
+
* - [ ] Add compile-time log level checking
|
|
97
|
+
* - [ ] Implement type-safe log context
|
|
98
|
+
*
|
|
99
|
+
* TODO: Security
|
|
100
|
+
* - [ ] Enhance sensitive data detection
|
|
101
|
+
* - [ ] Add PII (Personally Identifiable Information) masking
|
|
102
|
+
* - [ ] Implement log encryption for sensitive logs
|
|
103
|
+
* - [ ] Add audit log support
|
|
104
|
+
*
|
|
105
|
+
* TODO: Testing
|
|
106
|
+
* - [ ] Add logger unit tests
|
|
107
|
+
* - [ ] Test log sanitization
|
|
108
|
+
* - [ ] Test log formatting
|
|
109
|
+
* - [ ] Add performance tests
|
|
110
|
+
*
|
|
111
|
+
* TODO: Documentation
|
|
112
|
+
* - [ ] Document logging best practices
|
|
113
|
+
* - [ ] Add logging configuration guide
|
|
114
|
+
* - [ ] Document log levels and when to use them
|
|
115
|
+
*
|
|
116
|
+
* TODO: Limitations
|
|
117
|
+
* - [ ] Current implementation uses console (consider transport abstraction)
|
|
118
|
+
* - [ ] Log sanitization is basic (may need enhancement)
|
|
119
|
+
* - [ ] No log persistence (consider file/remote logging)
|
|
120
|
+
* - [ ] No log correlation (consider adding request IDs)
|
|
121
|
+
*/
|
package/dist/handlers/route.d.ts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
2
|
import { MulguardInstance } from '../mulguard';
|
|
3
|
+
/**
|
|
4
|
+
* Route handler options.
|
|
5
|
+
*/
|
|
3
6
|
export interface RouteHandlerOptions {
|
|
4
|
-
auth: MulguardInstance;
|
|
7
|
+
readonly auth: MulguardInstance;
|
|
5
8
|
}
|
|
6
9
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
10
|
+
* Creates Next.js route handlers for Mulguard authentication.
|
|
11
|
+
*
|
|
12
|
+
* @param auth - Mulguard instance
|
|
13
|
+
* @returns Route handlers for GET and POST requests
|
|
9
14
|
*
|
|
10
15
|
* @example
|
|
11
16
|
* ```typescript
|
|
@@ -17,6 +22,55 @@ export interface RouteHandlerOptions {
|
|
|
17
22
|
* ```
|
|
18
23
|
*/
|
|
19
24
|
export declare function toNextJsHandler(auth: MulguardInstance): {
|
|
20
|
-
GET: (request: NextRequest) => Promise<NextResponse
|
|
21
|
-
POST: (request: NextRequest) => Promise<NextResponse
|
|
25
|
+
GET: (request: NextRequest) => Promise<NextResponse>;
|
|
26
|
+
POST: (request: NextRequest) => Promise<NextResponse>;
|
|
22
27
|
};
|
|
28
|
+
/**
|
|
29
|
+
* TODO: Performance
|
|
30
|
+
* - [ ] Add request rate limiting middleware
|
|
31
|
+
* - [ ] Implement request caching for GET /session
|
|
32
|
+
* - [ ] Add request body size limits
|
|
33
|
+
* - [ ] Optimize path matching with compiled regex
|
|
34
|
+
*
|
|
35
|
+
* TODO: Features
|
|
36
|
+
* - [ ] Add request logging middleware
|
|
37
|
+
* - [ ] Implement request validation middleware
|
|
38
|
+
* - [ ] Add CORS support configuration
|
|
39
|
+
* - [ ] Create request/response transformation hooks
|
|
40
|
+
* - [ ] Add request timeout handling
|
|
41
|
+
*
|
|
42
|
+
* TODO: Type Safety
|
|
43
|
+
* - [ ] Add runtime validation for request bodies
|
|
44
|
+
* - [ ] Create type-safe route definitions
|
|
45
|
+
* - [ ] Implement compile-time route validation
|
|
46
|
+
* - [ ] Add type guards for all request bodies
|
|
47
|
+
*
|
|
48
|
+
* TODO: Security
|
|
49
|
+
* - [ ] Add CSRF token validation for state-changing operations
|
|
50
|
+
* - [ ] Implement request origin validation
|
|
51
|
+
* - [ ] Add request signing verification
|
|
52
|
+
* - [ ] Create security headers middleware
|
|
53
|
+
*
|
|
54
|
+
* TODO: Error Handling
|
|
55
|
+
* - [ ] Add structured error responses
|
|
56
|
+
* - [ ] Implement error logging
|
|
57
|
+
* - [ ] Create error recovery strategies
|
|
58
|
+
* - [ ] Add error reporting
|
|
59
|
+
*
|
|
60
|
+
* TODO: Testing
|
|
61
|
+
* - [ ] Add comprehensive route handler tests
|
|
62
|
+
* - [ ] Test all error scenarios
|
|
63
|
+
* - [ ] Test path matching logic
|
|
64
|
+
* - [ ] Add integration tests
|
|
65
|
+
*
|
|
66
|
+
* TODO: Documentation
|
|
67
|
+
* - [ ] Document all supported routes
|
|
68
|
+
* - [ ] Add route examples
|
|
69
|
+
* - [ ] Create troubleshooting guide
|
|
70
|
+
*
|
|
71
|
+
* TODO: Limitations
|
|
72
|
+
* - [ ] Path matching is basic (consider route table)
|
|
73
|
+
* - [ ] No request body validation (add schema validation)
|
|
74
|
+
* - [ ] Error messages may expose internal details
|
|
75
|
+
* - [ ] No request timeout configuration
|
|
76
|
+
*/
|
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 we=Object.defineProperty;var pe=(e,r,t)=>r in e?we(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var x=(e,r,t)=>pe(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-CzIWQq3s.js"),m=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 Ee(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 Y{constructor(r){x(this,"attempts",new Map);x(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 me(e){return new Y(e)}const Q={"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 j(e){return{...Q,...e}}function Se(e,r){const t=j(r);for(const[n,s]of Object.entries(t))s&&e.set(n,s)}const ye=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ae=254;function $(e){var t;if(typeof e!="string"||!e)return{valid:!1,error:"Email is required"};const r=e.trim().toLowerCase();return ye.test(r)?r.length>Ae?{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 Z(e){return e.valid===!0&&e.sanitized!==void 0}const Re=new Set(["password","12345678","qwerty","abc123","password123","123456789","1234567890","letmein","welcome","monkey","dragon","master","sunshine","princess","football","admin","root","test","guest","user"]),ve=/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,ke=8,Ce=128;function Te(e,r=ke){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>Ce)return{valid:!1,error:"Password is too long"};const t=e.toLowerCase();if(Re.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(ve.test(e))return{valid:!1,error:"Password contains sequential characters"};const n=Oe(e);return{valid:!0,sanitized:e,strength:n}}function Oe(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 Ie(e){return e.valid===!0&&e.sanitized!==void 0}const Pe=100;function _e(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>Pe)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 Ne(e){return e.valid===!0&&e.sanitized!==void 0}const Ue=new Set(["http:","https:"]);function be(e){if(typeof e!="string"||!e)return{valid:!1,error:"URL is required"};try{const r=new URL(e);return Ue.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 xe(e){return e.valid===!0&&e.sanitized!==void 0}const Fe=16,Le=512,De=/^[A-Za-z0-9_-]+$/;function Me(e,r=Fe){return typeof e!="string"||!e?{valid:!1,error:"Token is required"}:e.length<r?{valid:!1,error:"Token is too short"}:e.length>Le?{valid:!1,error:"Token is too long"}:De.test(e)?/(.)\1{10,}/.test(e)?{valid:!1,error:"Token contains suspicious pattern"}:{valid:!0,sanitized:e}:{valid:!1,error:"Invalid token format"}}function Ve(e){return e.valid===!0&&e.sanitized!==void 0}const ze=1e3;function q(e,r){const{maxLength:t=ze,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,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")),o=o.replace(/[\x00-\x1F\x7F]/g,""),{valid:!0,sanitized:o})}function je(e){return e.valid===!0&&e.sanitized!==void 0}class ee{constructor(){x(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 re{constructor(r,t=32){x(this,"store");x(this,"tokenLength");this.store=r||new ee,this.tokenLength=t}generateToken(r,t){const n=H(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=W(t,n);return s&&this.store.delete(r),s}getToken(r){return this.store.get(r)}deleteToken(r){this.store.delete(r)}}function $e(e){return new re(e)}function te(e){if(typeof e!="string")return"";const r={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,t=>r[t]||t)}function qe(e){return typeof e!="string"?"":e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript:/gi,"")}function He(e){return typeof e!="string"?"":te(e.trim())}function We(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 ne=32;function H(e=ne){if(e<1||e>256)throw new Error("Token length must be between 1 and 256 bytes");const r=Ee(e);return Buffer.from(r).toString("base64url")}function se(){return H(ne)}function W(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 Be(e,r){return W(e,r)}function Ge(e){return typeof e!="string"?"":e.trim().replace(/[<>]/g,"")}const Ke=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Xe(e){return typeof e=="string"&&Ke.test(e)}function oe(e){return!e.success&&!!e.error}function Je(e){return e.requires2FA===!0||e.errorCode===h.AuthErrorCode.TWO_FA_REQUIRED}function Ye(e,r){return e.error?e.error:r||"Authentication failed"}function Qe(e){return e.errorCode}function Ze(e){return e.success===!0&&!!e.user}function er(e,r){return e.errorCode===r}function rr(e){if(!oe(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 tr(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 nr(e,r,t){return e.signIn(r,t)}const ie={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 ie[e]??null}function sr(e){return e in ie}function ae(e,r,t,n){const s=z(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[f,l]of Object.entries(s.defaultParams))a.append(f,l);if(r.params)for(const[f,l]of Object.entries(r.params))a.set(f,l);return`${s.authorizationUrl}?${a.toString()}`}async function ce(e,r,t,n){const s=z(e);if(!s)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 o=new URLSearchParams({client_id:r.clientId,code:t,redirect_uri:n,grant_type:"authorization_code"});r.clientSecret&&o.append("client_secret",r.clientSecret);try{const i=await fetch(s.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:o.toString()});if(!i.ok){const f=await i.text();let l=`Failed to exchange code for tokens: ${f}`;try{const p=JSON.parse(f);l=p.error_description??p.error??l}catch{}throw new Error(l)}const a=await i.json();if(!or(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 or(e){return typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string"}async function ue(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 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 ir(e,s,r)}catch(n){throw n instanceof Error?n:new Error(`OAuth user info retrieval failed: ${String(n)}`)}}async function ir(e,r,t){switch(e){case"google":return ar(r);case"github":return await cr(r,t);case"apple":return ur(r);case"facebook":return lr(r);default:return fr(r)}}function ar(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 cr(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 ur(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 lr(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 fr(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 dr(e){return typeof e=="object"&&e!==null&&"clientId"in e&&typeof e.clientId=="string"}class le{constructor(){x(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 fe(){return new le}function L(e){return e.success===!0&&e.user!==void 0&&e.session!==void 0}var de=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(de||{});const hr=process.env.NODE_ENV==="development"?0:1;function gr(e={}){const{enabled:r=process.env.NODE_ENV==="development",level:t=hr,context:n,formatter:s=wr}=e,o=a=>r&&a>=t,i=(a,f,l,p)=>({level:a,message:f,timestamp:new Date,context:n,data:l?pr(l):void 0,error:p});return{debug:(a,f)=>{if(o(0)){const l=i(0,a,f);console.debug(s(l))}},info:(a,f)=>{if(o(1)){const l=i(1,a,f);console.info(s(l))}},warn:(a,f)=>{if(o(2)){const l=i(2,a,f);console.warn(s(l))}},error:(a,f)=>{if(o(3)){const l=f instanceof Error?f:void 0,p=f instanceof Error?void 0:f,w=i(3,a,p,l);console.error(s(w)),l&&console.error(l)}}}}function wr(e){const r=e.timestamp.toISOString(),t=de[e.level],n=e.context?`[${e.context}]`:"",s=e.data?` ${JSON.stringify(e.data)}`:"";return`${r} [${t}]${n} ${e.message}${s}`}function pr(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}const I=gr();function Er(e,r,t,n={}){const{enabled:s=!0,maxRetries:o=1,retryDelay:i=1e3,rateLimit:a=3,autoSignOutOnFailure:f=!0,redirectToLogin:l="/login",autoRedirectOnFailure:p=!0}=n;let w=null,k=!1;const R=[],A=[],S=60*1e3;let g=0,O=!1,P=null;const D=2,M=60*1e3;function c(){const y=Date.now();if(O&&P){if(y<P)return!1;O=!1,P=null,g=0}for(;A.length>0;){const E=A[0];if(E!==void 0&&E<y-S)A.shift();else break}return A.length>=a?!1:(A.push(y),!0)}function u(){g++,g>=D&&(O=!0,P=Date.now()+M,process.env.NODE_ENV==="development"&&console.warn("[TokenRefreshManager] Circuit breaker opened - too many consecutive failures"))}function d(){g=0,O=!1,P=null}async function v(y=1){if(!s)return null;if(!c())throw new Error("Rate limit exceeded for token refresh");try{const E=await e();if(E)return d(),_(E),n.onTokenRefreshed&&await Promise.resolve(n.onTokenRefreshed(E)),E;if(u(),y<o)return await G(i*y),v(y+1);throw new Error("Token refresh failed: refresh function returned null")}catch(E){if(u(),y<o&&N(E))return await G(i*y),v(y+1);throw E}}function N(y){if(y instanceof Error){const E=y.message.toLowerCase();if(E.includes("rate limit")||E.includes("too many requests")||E.includes("429")||E.includes("limit:")||E.includes("requests per minute")||E.includes("token_blacklisted")||E.includes("blacklisted")||E.includes("invalid")||E.includes("401")||E.includes("unauthorized")||E.includes("session has been revoked")||E.includes("session expired"))return!1;if(E.includes("network")||E.includes("fetch")||E.includes("timeout"))return!0}return!1}function _(y){const E=[...R];R.length=0;for(const{resolve:b}of E)b(y)}function B(y){const E=[...R];R.length=0;for(const{reject:b}of E)b(y)}function G(y){return new Promise(E=>setTimeout(E,y))}async function K(y){try{if(n.onTokenRefreshFailed&&await Promise.resolve(n.onTokenRefreshFailed(y)),f&&(await t(),await r(),p&&typeof window<"u")){let E=!0;if(n.onBeforeRedirect&&(E=await Promise.resolve(n.onBeforeRedirect(y))),E){const b=new URL(l,window.location.origin);b.searchParams.set("reason","session_expired"),b.searchParams.set("redirect",window.location.pathname+window.location.search),window.location.href=b.toString()}}}catch(E){process.env.NODE_ENV==="development"&&console.error("[TokenRefreshManager] Error in handleRefreshFailure:",E)}}return{async refreshToken(){return s?w||(k=!0,w=v().then(y=>(k=!1,w=null,y)).catch(y=>{throw k=!1,w=null,B(y),K(y).catch(()=>{}),y}),w):null},isRefreshing(){return k},async waitForRefresh(){return w?new Promise((y,E)=>{R.push({resolve:y,reject:E})}):null},clear(){w=null,k=!1,A.length=0,d(),B(new Error("Token refresh manager cleared"))},async handleRefreshFailure(y){return K(y)}}}function mr(){const e=process.env.NODE_ENV==="production";return{cookieName:"__mulguard_session",expiresIn:60*60*24*7,httpOnly:!0,secure:e,sameSite:"lax",path:"/"}}function Sr(){return{enabled:!0,refreshThreshold:300,maxRetries:0,retryDelay:1e3,rateLimit:1,autoSignOutOnFailure:!0,redirectToLogin:"/login",autoRedirectOnFailure:!0}}function yr(){return process.env.NEXT_PUBLIC_URL??(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:"http://localhost:3000")}function Ar(e){const{sessionConfig:r,cacheTtl:t,getSessionAction:n,onSessionExpired:s,onError:o}=e,i=r.cookieName??"__mulguard_session";let a=null;const f=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 p(),a=null)}catch(g){I.debug("getSession error",{error:g}),o&&await o(g instanceof Error?g:new Error(String(g)),"getSession"),a=null}try{const g=await h.getCookie(i);if(g)try{const O=JSON.parse(g);if(C.validateSessionStructure(O))return O.expiresAt&&new Date(O.expiresAt)<new Date?(s&&await s(O),await p(),a=null,null):(a={session:O,timestamp:S},O);await p(),a=null}catch{await p(),a=null}}catch(g){const O=g instanceof Error?g.message:String(g);!O.includes("request scope")&&!O.includes("cookies")&&(I.warn("getSession cookie error",{error:g}),o&&await o(g instanceof Error?g:new Error(String(g)),"getSession.cookie"))}return null},l=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),O=h.buildCookieOptions(i,g,r),P=await h.setCookie(O);return P.success&&(a={session:S,timestamp:Date.now()}),P}catch(g){const O=g instanceof Error?g.message:"Failed to set session";return I.error("setSession error",{error:g}),o&&await o(g instanceof Error?g:new Error(String(g)),"setSession"),{success:!1,error:O}}},p=async()=>{try{await h.deleteCookie(i,{path:r.path,domain:r.domain}),a=null}catch(S){I.warn("clearSessionCookie error",{error:S})}},w=async()=>{const S=await f();return S!=null&&S.accessToken&&typeof S.accessToken=="string"?S.accessToken:null};return{getSession:f,setSession:l,clearSessionCookie:p,getAccessToken:w,getRefreshToken:async()=>{const S=await f();return S!=null&&S.refreshToken&&typeof S.refreshToken=="string"?S.refreshToken:null},hasValidTokens:async()=>!!await w(),clearCache:()=>{a=null},getSessionConfig:()=>({cookieName:i,config:r})}}function Rr(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=$(r.email);if(!Z(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},s=await e.actions.signIn.email(n);if(L(s)){const o=await e.saveSessionAfterAuth(s);!o.success&&o.warning&&I.warn("Session save warning",{warning:o.warning})}return s.success?I.info("Sign in successful",{email:n.email.substring(0,3)+"***"}):I.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 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 vr(e,r){return async t=>{if(!t||typeof t!="string")throw new Error("Provider is required");const n=q(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),I.info("OAuth sign in initiated",{provider:s}),o}}function kr(e){return async(r,t)=>{if(!r||typeof r!="string")return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const n=$(r);if(!Z(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 s=await e.actions.signIn.otp(n.sanitized,t);if(L(s)){const o=await e.saveSessionAfterAuth(s);!o.success&&o.warning&&I.warn("Session save warning",{warning:o.warning})}return s.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)+"***"}),s}catch(s){return I.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:h.AuthErrorCode.UNKNOWN_ERROR}}}}function Cr(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(L(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 Tr(e,r){const t=Rr(e),n=vr(e,r),s=kr(e),o=Cr(e);return Object.assign(async(f,l)=>{if(!f||typeof f!="string")throw new Error("Provider is required");const p=q(f,{maxLength:50,allowHtml:!1,required:!0});if(!p.valid||!p.sanitized)throw new Error("Invalid provider");const w=p.sanitized.toLowerCase();if(w==="google"||w==="github"||w==="apple"||w==="facebook"||typeof w=="string"&&!["credentials","otp","passkey"].includes(w))return n(w);if(w==="credentials")return!l||!("email"in l)||!("password"in l)?{success:!1,error:"Credentials are required",errorCode:h.AuthErrorCode.VALIDATION_ERROR}:t(l);if(w==="otp"){if(!l||!("email"in l))return{success:!1,error:"Email is required",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const k=l;return s(k.email,k.code)}return w==="passkey"?o(l):{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?o:void 0,otp:e.actions.signIn.otp?s:void 0})}function Or(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(L(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 Ir(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:h.AuthErrorCode.VALIDATION_ERROR};try{const i=o.redirectUri??`${e.baseUrl}/api/auth/callback/${t}`,a=await ce(t,o,n,i),f=await ue(t,a.access_token),l={id:f.id,email:f.email,name:f.name,avatar:f.avatar,emailVerified:f.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:f.rawProfile};if(e.callbacks.onOAuthUser){const p=await X(e.callbacks.onOAuthUser,[l,t],e.onError);if(!p)return{success:!1,error:"Failed to create or retrieve user",errorCode:h.AuthErrorCode.VALIDATION_ERROR};const w=e.createSession(p,l,a);return await e.saveSession(w),e.callbacks.onSignIn&&await X(e.callbacks.onSignIn,[w.user,w],e.onError),{success:!0,user:w.user,session:w}}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 X(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 Pr(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 _r(e){var D,M;const r={...mr(),...e.session},t=e.actions,n=e.callbacks||{},s=((D=e.providers)==null?void 0:D.oauth)||{},o=yr(),i={...Sr(),...e.tokenRefresh},a=((M=e.session)==null?void 0:M.cacheTtl)??e.sessionCacheTtl??5e3,f=e.oauthStateStore||fe(),l={...t},p=async(c,u)=>{const d={provider:u,expiresAt:Date.now()+6e5};await Promise.resolve(f.set(c,d,10*60*1e3)),f.cleanup&&await Promise.resolve(f.cleanup())},w=async(c,u)=>{const d=await Promise.resolve(f.get(c));return d?d.expiresAt<Date.now()?(await Promise.resolve(f.delete(c)),!1):d.provider!==u?!1:(await Promise.resolve(f.delete(c)),!0):!1},k=Pr(s,o,se,ae);if(k&&!l.signIn.oauth){const c=l.signIn;l.signIn={...c,oauth:async u=>{const d=await k(u);return await p(d.state,u),d}}}if(!l.signIn||!l.signIn.email)throw new Error("mulguard: signIn.email action is required");const R=async(c,...u)=>{if(c)try{return await c(...u)}catch(d){throw n.onError&&await n.onError(d instanceof Error?d:new Error(String(d)),"callback"),d}},A=Ar({sessionConfig:r,cacheTtl:a,getSessionAction:t.getSession,onSessionExpired:n.onSessionExpired,onError:n.onError}),S=async c=>{if(!L(c)||!c.session)return{success:!0};const u=await A.setSession(c.session);return c.user&&n.onSignIn&&await R(n.onSignIn,c.user,c.session),u};if(Object.keys(s).length>0&&!l.oauthCallback){const c=Ir({oauthProviders:s,baseUrl:o,callbacks:n,createSession:(u,d,v)=>({user:{...u,avatar:d.avatar,emailVerified:d.emailVerified},expiresAt:new Date(Date.now()+(r.expiresIn||604800)*1e3),accessToken:v.access_token,refreshToken:v.refresh_token,tokenType:"Bearer",expiresIn:v.expires_in}),saveSession:async u=>{await A.setSession(u)},onError:n.onError});l.oauthCallback=c}const g=Tr({actions:l,callbacks:n,saveSessionAfterAuth:S,onError:n.onError},p),O=Or({actions:l,callbacks:n,saveSessionAfterAuth:S,onError:n.onError}),P={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(!O)throw new Error("Sign up is not configured. Provide signUp action in config.");return await O(c)},async signOut(){try{const c=await this.getSession(),u=c==null?void 0:c.user;return t.signOut&&await t.signOut(),await A.clearSessionCookie(),A.clearCache(),u&&n.onSignOut&&await R(n.onSignOut,u),{success:!0}}catch(c){return await A.clearSessionCookie(),A.clearCache(),n.onError&&await R(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(u){return n.onError&&await R(n.onError,u instanceof Error?u:new Error(String(u)),"resetPassword"),{success:!1,error:u instanceof Error?u.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(u){return n.onError&&await R(n.onError,u instanceof Error?u:new Error(String(u)),"verifyEmail"),{success:!1,error:u instanceof Error?u.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 u=await R(n.onSessionUpdate,c);if(u&&C.validateSessionStructure(u)){if(await A.setSession(u),n.onTokenRefresh){const d=await this.getSession();d&&await R(n.onTokenRefresh,d,u)}return u}}if(n.onTokenRefresh){const u=await this.getSession();u&&await R(n.onTokenRefresh,u,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 R(n.onError,c instanceof Error?c:new Error(String(c)),"refreshSession"),null}},async oauthCallback(c,u,d){if(!l.oauthCallback)throw new Error("OAuth callback is not configured. Either provide oauthCallback action, or configure providers.oauth in config.");if(!u||!d)return{success:!1,error:"Missing required OAuth parameters (code or state)",errorCode:h.AuthErrorCode.VALIDATION_ERROR};let v=c;if(!v){const _=await Promise.resolve(f.get(d));if(_&&_.provider)v=_.provider;else return{success:!1,error:"Provider is required and could not be extracted from state",errorCode:h.AuthErrorCode.VALIDATION_ERROR}}if(!await w(d,v))return{success:!1,error:"Invalid or expired state parameter",errorCode:h.AuthErrorCode.VALIDATION_ERROR};try{return await l.oauthCallback(v,u,d)}catch(_){return n.onError&&await R(n.onError,_ instanceof Error?_:new Error(String(_)),"oauthCallback"),{success:!1,error:_ instanceof Error?_.message:"OAuth callback failed",errorCode:h.AuthErrorCode.NETWORK_ERROR}}},async verify2FA(c,u){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&&!(u!=null&&u.skipCookieSave)){const v=await S(d);v.success||(process.env.NODE_ENV==="development"&&I.debug("Failed to save session cookie after verify2FA",{error:v.error,warning:v.warning}),n.onError&&await R(n.onError,new Error(v.warning||v.error||"Failed to save session cookie"),"verify2FA.setSession"))}return d}catch(d){return n.onError&&await R(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},passkey:t.passkey?{register:t.passkey.register,authenticate:async c=>{var u;if(!((u=t.passkey)!=null&&u.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 R(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 u;if(!((u=t.passkey)!=null&&u.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 u=((d=t.twoFactor)==null?void 0:d.verify2FA)||t.verify2FA;if(!u)throw new Error("2FA verification is not configured. Provide verify2FA action in config.");try{const v=await u(c);if(v.success&&v.session){const N=await S(v);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 R(n.onError,new Error(N.warning||N.error||"Failed to save session cookie"),"twoFactor.verify2FA.setSession"))}return v}catch(v){return n.onError&&await R(n.onError,v instanceof Error?v:new Error(String(v)),"twoFactor.verify2FA"),{success:!1,error:v instanceof Error?v.message:"2FA verification failed",errorCode:h.AuthErrorCode.UNKNOWN_ERROR}}}}:void 0,signInMethods:{email:c=>g.email(c),oauth:c=>{var u;return((u=g.oauth)==null?void 0:u.call(g,c))||Promise.reject(new Error("OAuth not configured"))},passkey:c=>{var u;return((u=g.passkey)==null?void 0:u.call(g,c))||Promise.reject(new Error("Passkey not configured"))},otp:(c,u)=>{var d;return((d=g.otp)==null?void 0:d.call(g,c,u))||Promise.reject(new Error("OTP not configured"))}}};if(t.refreshSession){const c=Er(async()=>await P.refreshSession(),async()=>await P.signOut(),async()=>{await A.clearSessionCookie(),A.clearCache()},{...i,onTokenRefreshed:i.onTokenRefreshed,onTokenRefreshFailed:i.onTokenRefreshFailed,onBeforeRedirect:i.onBeforeRedirect});P._tokenRefreshManager=c,P._getTokenRefreshManager=()=>c}return P}function Nr(e){return{GET:async r=>J(r,e,"GET"),POST:async r=>J(r,e,"POST")}}async function J(e,r,t){const n=new URL(e.url),s=Ur(n.pathname),o=s.split("/").filter(Boolean);try{return t==="GET"?await br(e,r,s,o,n):t==="POST"?await xr(e,r,s,o,n):T("Method not allowed",405)}catch(i){return T(i instanceof Error?i.message:"Request failed",500)}}function Ur(e){return e.replace(/^\/api\/auth/,"")||"/session"}async function br(e,r,t,n,s){if(t==="/session"||t==="/"){const o=await r.getSession();return m.NextResponse.json({session:o})}return t==="/providers"?m.NextResponse.json({providers:{email:!!r.signIn.email,oauth:!!r.signIn.oauth,passkey:!!r.signIn.passkey}}):he(t,n)?await ge(e,r,t,n,s,"GET"):T("Not found",404)}async function xr(e,r,t,n,s){const o=await Fr(e);return t==="/sign-in"||n[0]==="sign-in"?await Dr(r,o):t==="/sign-up"||n[0]==="sign-up"?await Mr(r,o):t==="/sign-out"||n[0]==="sign-out"?await Vr(r):t==="/reset-password"||n[0]==="reset-password"?await zr(r,o):t==="/verify-email"||n[0]==="verify-email"?await jr(r,o):t==="/refresh"||n[0]==="refresh"?await $r(r):he(t,n)?await ge(e,r,t,n,s,"POST",o):t.startsWith("/passkey")?await Hr(r,t,n,o):t==="/verify-2fa"||n[0]==="verify-2fa"?await qr(r,o):t.startsWith("/two-factor")?await Wr(r,n,o):T("Not found",404)}async function Fr(e){try{return await e.json()}catch{return{}}}function he(e,r){return e==="/callback"||e.startsWith("/oauth/callback")||r[0]==="oauth"&&r[1]==="callback"||r[0]==="callback"}async function ge(e,r,t,n,s,o,i){if(!r.oauthCallback)return o==="GET"?V(e.url,"oauth_not_configured"):T("OAuth callback is not configured",400);const a=Lr(n,s,i),f=(i==null?void 0:i.code)??s.searchParams.get("code"),l=(i==null?void 0:i.state)??s.searchParams.get("state");if(!f||!l)return o==="GET"?V(e.url,"oauth_missing_params"):T("Missing required OAuth parameters. Code and state are required.",400);try{const p=await r.oauthCallback(a??"",f,l);return o==="GET"?p.success?Br(e.url,s.searchParams.get("callbackUrl")):V(e.url,p.error??"oauth_failed"):m.NextResponse.json(p)}catch(p){return o==="GET"?V(e.url,p instanceof Error?p.message:"oauth_error"):T(p instanceof Error?p.message:"OAuth callback failed",500)}}function Lr(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 Dr(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 m.NextResponse.json(n)}if(r.provider==="oauth"&&r.providerName){if(!e.signIn.oauth)return T("OAuth is not configured",400);const t=await e.signIn.oauth(r.providerName);return m.NextResponse.json(t)}if(r.provider==="passkey"){if(!e.signIn.passkey)return T("PassKey is not configured",400);const t=await e.signIn.passkey(r.options);return m.NextResponse.json(t)}return T("Invalid sign in request",400)}async function Mr(e,r){if(!e.signUp)return T("Sign up is not configured",400);const t=await e.signUp(r);return m.NextResponse.json(t)}async function Vr(e){const r=await e.signOut();return m.NextResponse.json(r)}async function zr(e,r){if(!e.resetPassword)return T("Password reset is not configured",400);if(!r.email||typeof r.email!="string")return T("Email is required",400);const t=await e.resetPassword(r.email);return m.NextResponse.json(t)}async function jr(e,r){if(!e.verifyEmail)return T("Email verification is not configured",400);if(!r.token||typeof r.token!="string")return T("Token is required",400);const t=await e.verifyEmail(r.token);return m.NextResponse.json(t)}async function $r(e){if(!e.refreshSession){const t=await e.getSession();return m.NextResponse.json({session:t})}const r=await e.refreshSession();return m.NextResponse.json({session:r})}async function qr(e,r){if(!e.verify2FA)return T("2FA verification is not configured",400);if(!r.email||!r.userId||!r.code)return T("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 m.NextResponse.json(n)}async function Hr(e,r,t,n){if(!e.passkey)return T("PassKey is not configured",400);const s=t[1];if(s==="register"&&e.passkey.register){const o=await e.passkey.register(n.options);return m.NextResponse.json(o)}if(s==="list"&&e.passkey.list){const o=await e.passkey.list();return m.NextResponse.json(o)}if(s==="remove"&&e.passkey.remove){if(!n.passkeyId||typeof n.passkeyId!="string")return T("Passkey ID is required",400);const o=await e.passkey.remove(n.passkeyId);return m.NextResponse.json(o)}return T("Invalid Passkey request",400)}async function Wr(e,r,t){if(!e.twoFactor)return T("Two-Factor Authentication is not configured",400);const n=r[1];if(n==="enable"&&e.twoFactor.enable){const s=await e.twoFactor.enable();return m.NextResponse.json(s)}if(n==="verify"&&e.twoFactor.verify){if(!t.code||typeof t.code!="string")return T("Code is required",400);const s=await e.twoFactor.verify(t.code);return m.NextResponse.json(s)}if(n==="disable"&&e.twoFactor.disable){const s=await e.twoFactor.disable();return m.NextResponse.json(s)}if(n==="backup-codes"&&e.twoFactor.generateBackupCodes){const s=await e.twoFactor.generateBackupCodes();return m.NextResponse.json(s)}if(n==="is-enabled"&&e.twoFactor.isEnabled){const s=await e.twoFactor.isEnabled();return m.NextResponse.json({enabled:s})}return T("Invalid two-factor request",400)}function T(e,r){return m.NextResponse.json({success:!1,error:e},{status:r})}function V(e,r){return m.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(r)}`,e))}function Br(e,r){const t=r??"/";return m.NextResponse.redirect(new URL(t,e))}function Gr(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()),f=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}),l=await f.json();return m.NextResponse.json(l,{status:f.status,headers:{...Object.fromEntries(f.headers.entries())}})}catch(i){return console.error("API handler error:",i),m.NextResponse.json({success:!1,error:i instanceof Error?i.message:"Internal server error"},{status:500})}}}function Kr(e){return async r=>{const{searchParams:t}=r.nextUrl,n=t.get("provider"),s=t.get("code"),o=t.get("state");if(!n||!s||!o)return m.NextResponse.redirect(new URL("/login?error=oauth_missing_params",r.url));try{if(!e.oauthCallback)return m.NextResponse.redirect(new URL("/login?error=oauth_not_configured",r.url));const i=await e.oauthCallback(n,s,o);if(i.success){const a=t.get("callbackUrl")||"/";return m.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 m.NextResponse.redirect(new URL(`/login?error=${a}`,r.url))}}catch(i){return process.env.NODE_ENV==="development"&&console.error("[Mulguard] OAuth callback error:",i),m.NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(i instanceof Error?i.message:"oauth_error")}`,r.url))}}}function U(e,r){const t=j({"X-Frame-Options":"SAMEORIGIN"});for(const[n,s]of Object.entries(t))s&&typeof s=="string"&&r.headers.set(n,s);return r}function Xr(){return async e=>{const r=m.NextResponse.next();return U(e,r)}}function Jr(e,r={}){const{protectedRoutes:t=[],publicRoutes:n=[],redirectTo:s="/login",redirectIfAuthenticated:o}=r;return async i=>{const{pathname:a}=i.nextUrl,f=t.some(w=>a.startsWith(w));let l=null;try{l=await e.getSession()}catch(w){console.error("Middleware: Failed to get session:",w)}if(f&&!l){const w=i.nextUrl.clone();return w.pathname=s,w.searchParams.set("callbackUrl",a),m.NextResponse.redirect(w)}if(o&&l&&(a.startsWith("/login")||a.startsWith("/register"))){const k=i.nextUrl.clone();k.pathname=o;const R=m.NextResponse.redirect(k);return U(i,R)}const p=m.NextResponse.next();return U(i,p)}}async function Yr(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 Qr(e){const{auth:r,protectedRoutes:t=[],publicRoutes:n=[],redirectTo:s="/login",redirectIfAuthenticated:o,apiPrefix:i="/api/auth"}=e;return async a=>{const{pathname:f}=a.nextUrl;if(f.startsWith(i)){const k=m.NextResponse.next();return U(a,k)}const l=t.some(k=>f.startsWith(k));let p=null;if(l||o)try{p=await r.getSession()}catch(k){console.error("Middleware: Failed to get session:",k)}if(l&&!p){const k=a.nextUrl.clone();k.pathname=s,k.searchParams.set("callbackUrl",f);const R=m.NextResponse.redirect(k);return U(a,R)}if(o&&p&&(f.startsWith("/login")||f.startsWith("/register"))){const R=a.nextUrl.clone();R.pathname=o;const A=m.NextResponse.redirect(R);return U(a,A)}const w=m.NextResponse.next();return U(a,w)}}async function Zr(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=re;exports.DEFAULT_SECURITY_HEADERS=Q;exports.MemoryCSRFStore=ee;exports.MemoryOAuthStateStore=le;exports.RateLimiter=Y;exports.applySecurityHeaders=Se;exports.buildOAuthAuthorizationUrl=ae;exports.checkRole=Yr;exports.checkRoleProxy=Zr;exports.containsXSSPattern=We;exports.createApiHandler=Gr;exports.createAuthMiddleware=Jr;exports.createCSRFProtection=$e;exports.createMemoryOAuthStateStore=fe;exports.createOAuthCallbackHandler=Kr;exports.createProxyMiddleware=Qr;exports.createRateLimiter=me;exports.createSecurityMiddleware=Xr;exports.escapeHTML=te;exports.exchangeOAuthCode=ce;exports.generateCSRFToken=se;exports.generateToken=H;exports.getErrorCode=Qe;exports.getErrorMessage=Ye;exports.getOAuthUserInfo=ue;exports.getProviderMetadata=z;exports.getSecurityHeaders=j;exports.getUserFriendlyError=tr;exports.hasErrorCode=er;exports.isAuthError=oe;exports.isAuthSuccess=Ze;exports.isOAuthProviderConfig=dr;exports.isRetryableError=rr;exports.isSupportedProvider=sr;exports.isTwoFactorRequired=Je;exports.isValidCSRFToken=Be;exports.isValidEmail=Xe;exports.isValidInput=je;exports.isValidName=Ne;exports.isValidPassword=Ie;exports.isValidToken=Ve;exports.isValidURL=xe;exports.mulguard=_r;exports.sanitizeHTML=qe;exports.sanitizeInput=Ge;exports.sanitizeUserInput=He;exports.signIn=nr;exports.toNextJsHandler=Nr;exports.validateAndSanitizeEmail=$;exports.validateAndSanitizeInput=q;exports.validateAndSanitizeName=_e;exports.validateAndSanitizePassword=Te;exports.validateCSRFToken=W;exports.validateToken=Me;exports.validateURL=be;exports.withSecurityHeaders=U;
|