@payez/next-mvp 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/callbacks/jwt.js +305 -305
- package/dist/auth/providers/credentials.js +223 -223
- package/dist/config/vibe-log-transport.d.ts +5 -3
- package/dist/config/vibe-log-transport.js +14 -5
- package/dist/server/auth-guard.d.ts +46 -0
- package/dist/server/auth-guard.js +128 -0
- package/dist/server/decode-session.d.ts +30 -0
- package/dist/server/decode-session.js +78 -0
- package/dist/server/slim-middleware.d.ts +23 -0
- package/dist/server/slim-middleware.js +89 -0
- package/dist/server/with-auth.d.ts +33 -0
- package/dist/server/with-auth.js +59 -0
- package/package.json +21 -1
- package/src/config/vibe-log-transport.ts +17 -3
- package/src/server/auth-guard.ts +170 -0
- package/src/server/decode-session.ts +91 -0
- package/src/server/slim-middleware.ts +117 -0
- package/src/server/with-auth.ts +93 -0
|
@@ -1,223 +1,223 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Credentials Provider
|
|
4
|
-
*
|
|
5
|
-
* Handles email/password authentication via PayEz IDP.
|
|
6
|
-
* Creates Redis session and returns minimal user object to NextAuth.
|
|
7
|
-
*
|
|
8
|
-
* FLOW:
|
|
9
|
-
* 1. User submits email/password
|
|
10
|
-
* 2. We call IDP /api/ExternalAuth/login
|
|
11
|
-
* 3. IDP returns tokens if credentials valid
|
|
12
|
-
* 4. We create Redis session with tokens
|
|
13
|
-
* 5. Return user object with redisSessionId to NextAuth
|
|
14
|
-
*
|
|
15
|
-
* @version 1.0.0
|
|
16
|
-
* @since auth-refactor-2026-01
|
|
17
|
-
*/
|
|
18
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
19
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
|
-
};
|
|
21
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
-
exports.createCredentialsProvider = createCredentialsProvider;
|
|
23
|
-
const credentials_1 = __importDefault(require("next-auth/providers/credentials"));
|
|
24
|
-
const session_store_1 = require("../../lib/session-store");
|
|
25
|
-
const idp_client_1 = require("../utils/idp-client");
|
|
26
|
-
const token_utils_1 = require("../utils/token-utils");
|
|
27
|
-
const auth_types_1 = require("../types/auth-types");
|
|
28
|
-
// NOTE: Using any for sessionData until Phase 3 normalizes types
|
|
29
|
-
// ============================================================================
|
|
30
|
-
// CREDENTIALS PROVIDER
|
|
31
|
-
// ============================================================================
|
|
32
|
-
/**
|
|
33
|
-
* Create the CredentialsProvider for NextAuth.
|
|
34
|
-
*
|
|
35
|
-
* This provider handles email/password login. The authorize function
|
|
36
|
-
* is called when a user submits the login form.
|
|
37
|
-
*/
|
|
38
|
-
function createCredentialsProvider() {
|
|
39
|
-
return (0, credentials_1.default)({
|
|
40
|
-
id: 'credentials',
|
|
41
|
-
name: 'Credentials',
|
|
42
|
-
credentials: {
|
|
43
|
-
email: { label: 'Email', type: 'email' },
|
|
44
|
-
password: { label: 'Password', type: 'password' },
|
|
45
|
-
},
|
|
46
|
-
authorize: authorizeCredentials,
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Authorize user with email/password.
|
|
51
|
-
*
|
|
52
|
-
* This is the core authentication function. It:
|
|
53
|
-
* 1. Validates credentials with IDP
|
|
54
|
-
* 2. Decodes the returned tokens
|
|
55
|
-
* 3. Creates a Redis session
|
|
56
|
-
* 4. Returns user info for NextAuth JWT
|
|
57
|
-
*
|
|
58
|
-
* @param credentials - Email and password from login form
|
|
59
|
-
* @param req - The incoming request (for IP/UA forwarding)
|
|
60
|
-
* @returns User object for NextAuth, or null/throws on failure
|
|
61
|
-
*/
|
|
62
|
-
async function authorizeCredentials(credentials, req) {
|
|
63
|
-
// -------------------------------------------------------------------------
|
|
64
|
-
// Validate Input
|
|
65
|
-
// -------------------------------------------------------------------------
|
|
66
|
-
if (!credentials?.email || !credentials?.password) {
|
|
67
|
-
throw new Error('Email and password required');
|
|
68
|
-
}
|
|
69
|
-
const loginCredentials = {
|
|
70
|
-
email: credentials.email,
|
|
71
|
-
password: credentials.password,
|
|
72
|
-
};
|
|
73
|
-
// Extract client info for audit logging
|
|
74
|
-
const clientHeaders = extractClientHeaders(req);
|
|
75
|
-
// -------------------------------------------------------------------------
|
|
76
|
-
// Call IDP
|
|
77
|
-
// -------------------------------------------------------------------------
|
|
78
|
-
const loginResult = await (0, idp_client_1.idpLogin)(loginCredentials, clientHeaders);
|
|
79
|
-
if (!loginResult.success || !loginResult.result) {
|
|
80
|
-
// Build structured error for frontend
|
|
81
|
-
const errorResponse = buildAuthError(loginResult.error);
|
|
82
|
-
throw new Error(JSON.stringify(errorResponse));
|
|
83
|
-
}
|
|
84
|
-
const { access_token, refresh_token, user: idpUser } = loginResult.result;
|
|
85
|
-
// -------------------------------------------------------------------------
|
|
86
|
-
// Decode Token
|
|
87
|
-
// -------------------------------------------------------------------------
|
|
88
|
-
const decoded = (0, token_utils_1.decodeIdpAccessToken)(access_token);
|
|
89
|
-
if (!decoded) {
|
|
90
|
-
throw new Error('Failed to decode token');
|
|
91
|
-
}
|
|
92
|
-
// Extract kid from JWT header (CRITICAL: this is different from client_id in payload)
|
|
93
|
-
const bearerKeyId = (0, token_utils_1.extractKidFromToken)(access_token);
|
|
94
|
-
if (bearerKeyId) {
|
|
95
|
-
console.log('[CREDENTIALS] Extracted bearerKeyId (kid) from JWT header:', bearerKeyId);
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
console.warn('[CREDENTIALS] No kid found in JWT header - token may be unsigned or malformed');
|
|
99
|
-
}
|
|
100
|
-
// Extract claims from token
|
|
101
|
-
const email = (0, token_utils_1.extractEmailFromToken)(decoded);
|
|
102
|
-
const roles = (0, token_utils_1.extractRolesFromToken)(decoded);
|
|
103
|
-
const amrClaims = (0, token_utils_1.extractAmrFromToken)(decoded);
|
|
104
|
-
const acrLevel = decoded.acr || '1';
|
|
105
|
-
const userId = decoded.sub;
|
|
106
|
-
// Check if 2FA is complete based on ACR level
|
|
107
|
-
// ACR=1: Provisional token (requires 2FA)
|
|
108
|
-
// ACR=2: Full authentication (2FA complete)
|
|
109
|
-
const mfaVerified = acrLevel === '2';
|
|
110
|
-
// Decode refresh token expiry if available
|
|
111
|
-
let refreshTokenExpires;
|
|
112
|
-
try {
|
|
113
|
-
const refreshDecoded = (0, token_utils_1.decodeIdpAccessToken)(refresh_token);
|
|
114
|
-
if (refreshDecoded?.exp) {
|
|
115
|
-
refreshTokenExpires = (0, token_utils_1.expClaimToMs)(refreshDecoded.exp);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
catch {
|
|
119
|
-
// Ignore - will use default expiry
|
|
120
|
-
}
|
|
121
|
-
// -------------------------------------------------------------------------
|
|
122
|
-
// Create Redis Session
|
|
123
|
-
// -------------------------------------------------------------------------
|
|
124
|
-
// Using normalized field names (session-store handles backward compatibility)
|
|
125
|
-
const sessionData = {
|
|
126
|
-
userId,
|
|
127
|
-
email,
|
|
128
|
-
roles,
|
|
129
|
-
// IDP tokens (normalized names)
|
|
130
|
-
idpAccessToken: access_token,
|
|
131
|
-
idpRefreshToken: refresh_token,
|
|
132
|
-
idpAccessTokenExpires: (0, token_utils_1.expClaimToMs)(decoded.exp),
|
|
133
|
-
idpRefreshTokenExpires: refreshTokenExpires,
|
|
134
|
-
decodedAccessToken: decoded,
|
|
135
|
-
// Bearer key ID from JWT header (NOT client_id from payload)
|
|
136
|
-
bearerKeyId,
|
|
137
|
-
// MFA state (normalized names)
|
|
138
|
-
mfaVerified,
|
|
139
|
-
authenticationMethods: amrClaims,
|
|
140
|
-
authenticationLevel: acrLevel,
|
|
141
|
-
// MFA timing info from token
|
|
142
|
-
mfaCompletedAt: decoded.mfa_time ? (0, token_utils_1.expClaimToMs)(decoded.mfa_time) : undefined,
|
|
143
|
-
mfaExpiresAt: decoded.mfa_expires ? (0, token_utils_1.expClaimToMs)(decoded.mfa_expires) : undefined,
|
|
144
|
-
mfaValidityHours: decoded.mfa_validity_hours,
|
|
145
|
-
};
|
|
146
|
-
// Determine MFA method from IDP user info
|
|
147
|
-
let mfaMethod;
|
|
148
|
-
if (idpUser?.isEmailConfirmed) {
|
|
149
|
-
mfaMethod = 'email';
|
|
150
|
-
}
|
|
151
|
-
else if (idpUser?.isSmsConfirmed) {
|
|
152
|
-
mfaMethod = 'sms';
|
|
153
|
-
}
|
|
154
|
-
if (mfaMethod) {
|
|
155
|
-
sessionData.mfaMethod = mfaMethod;
|
|
156
|
-
}
|
|
157
|
-
// Create the Redis session
|
|
158
|
-
const redisSessionId = await (0, session_store_1.createSession)(sessionData);
|
|
159
|
-
// -------------------------------------------------------------------------
|
|
160
|
-
// Return User Object for NextAuth
|
|
161
|
-
// -------------------------------------------------------------------------
|
|
162
|
-
// NextAuth requires 'id' field - we use userId from IDP
|
|
163
|
-
// The redisSessionId is passed through to the JWT callback
|
|
164
|
-
return {
|
|
165
|
-
id: userId,
|
|
166
|
-
email,
|
|
167
|
-
roles,
|
|
168
|
-
redisSessionId: (0, auth_types_1.toRedisSessionId)(redisSessionId),
|
|
169
|
-
mfaRequired: !mfaVerified,
|
|
170
|
-
mfaMethod,
|
|
171
|
-
};
|
|
172
|
-
}
|
|
173
|
-
// ============================================================================
|
|
174
|
-
// HELPER FUNCTIONS
|
|
175
|
-
// ============================================================================
|
|
176
|
-
/**
|
|
177
|
-
* Extract client headers from request for audit logging.
|
|
178
|
-
*/
|
|
179
|
-
function extractClientHeaders(req) {
|
|
180
|
-
const headers = {};
|
|
181
|
-
// Extract client IP
|
|
182
|
-
const forwardedFor = req?.headers?.['x-forwarded-for'];
|
|
183
|
-
const realIp = req?.headers?.['x-real-ip'];
|
|
184
|
-
if (forwardedFor) {
|
|
185
|
-
const ip = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0].trim();
|
|
186
|
-
headers.ip = ip;
|
|
187
|
-
}
|
|
188
|
-
else if (realIp) {
|
|
189
|
-
headers.ip = Array.isArray(realIp) ? realIp[0] : realIp;
|
|
190
|
-
}
|
|
191
|
-
// Extract User-Agent
|
|
192
|
-
const userAgent = req?.headers?.['user-agent'];
|
|
193
|
-
if (userAgent) {
|
|
194
|
-
headers.userAgent = Array.isArray(userAgent) ? userAgent[0] : userAgent;
|
|
195
|
-
}
|
|
196
|
-
return headers;
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Build structured error response for frontend.
|
|
200
|
-
*
|
|
201
|
-
* The frontend expects a specific error structure to display
|
|
202
|
-
* appropriate messages and handle things like lockout.
|
|
203
|
-
*/
|
|
204
|
-
function buildAuthError(error) {
|
|
205
|
-
if (!error) {
|
|
206
|
-
return {
|
|
207
|
-
success: false,
|
|
208
|
-
error: {
|
|
209
|
-
code: 'AUTH_ERROR',
|
|
210
|
-
message: 'Authentication failed',
|
|
211
|
-
details: {},
|
|
212
|
-
},
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
return {
|
|
216
|
-
success: false,
|
|
217
|
-
error: {
|
|
218
|
-
code: error.code || 'AUTH_ERROR',
|
|
219
|
-
message: error.message || 'Authentication failed',
|
|
220
|
-
details: error.details || {},
|
|
221
|
-
},
|
|
222
|
-
};
|
|
223
|
-
}
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Credentials Provider
|
|
4
|
+
*
|
|
5
|
+
* Handles email/password authentication via PayEz IDP.
|
|
6
|
+
* Creates Redis session and returns minimal user object to NextAuth.
|
|
7
|
+
*
|
|
8
|
+
* FLOW:
|
|
9
|
+
* 1. User submits email/password
|
|
10
|
+
* 2. We call IDP /api/ExternalAuth/login
|
|
11
|
+
* 3. IDP returns tokens if credentials valid
|
|
12
|
+
* 4. We create Redis session with tokens
|
|
13
|
+
* 5. Return user object with redisSessionId to NextAuth
|
|
14
|
+
*
|
|
15
|
+
* @version 1.0.0
|
|
16
|
+
* @since auth-refactor-2026-01
|
|
17
|
+
*/
|
|
18
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
19
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
|
+
};
|
|
21
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
+
exports.createCredentialsProvider = createCredentialsProvider;
|
|
23
|
+
const credentials_1 = __importDefault(require("next-auth/providers/credentials"));
|
|
24
|
+
const session_store_1 = require("../../lib/session-store");
|
|
25
|
+
const idp_client_1 = require("../utils/idp-client");
|
|
26
|
+
const token_utils_1 = require("../utils/token-utils");
|
|
27
|
+
const auth_types_1 = require("../types/auth-types");
|
|
28
|
+
// NOTE: Using any for sessionData until Phase 3 normalizes types
|
|
29
|
+
// ============================================================================
|
|
30
|
+
// CREDENTIALS PROVIDER
|
|
31
|
+
// ============================================================================
|
|
32
|
+
/**
|
|
33
|
+
* Create the CredentialsProvider for NextAuth.
|
|
34
|
+
*
|
|
35
|
+
* This provider handles email/password login. The authorize function
|
|
36
|
+
* is called when a user submits the login form.
|
|
37
|
+
*/
|
|
38
|
+
function createCredentialsProvider() {
|
|
39
|
+
return (0, credentials_1.default)({
|
|
40
|
+
id: 'credentials',
|
|
41
|
+
name: 'Credentials',
|
|
42
|
+
credentials: {
|
|
43
|
+
email: { label: 'Email', type: 'email' },
|
|
44
|
+
password: { label: 'Password', type: 'password' },
|
|
45
|
+
},
|
|
46
|
+
authorize: authorizeCredentials,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Authorize user with email/password.
|
|
51
|
+
*
|
|
52
|
+
* This is the core authentication function. It:
|
|
53
|
+
* 1. Validates credentials with IDP
|
|
54
|
+
* 2. Decodes the returned tokens
|
|
55
|
+
* 3. Creates a Redis session
|
|
56
|
+
* 4. Returns user info for NextAuth JWT
|
|
57
|
+
*
|
|
58
|
+
* @param credentials - Email and password from login form
|
|
59
|
+
* @param req - The incoming request (for IP/UA forwarding)
|
|
60
|
+
* @returns User object for NextAuth, or null/throws on failure
|
|
61
|
+
*/
|
|
62
|
+
async function authorizeCredentials(credentials, req) {
|
|
63
|
+
// -------------------------------------------------------------------------
|
|
64
|
+
// Validate Input
|
|
65
|
+
// -------------------------------------------------------------------------
|
|
66
|
+
if (!credentials?.email || !credentials?.password) {
|
|
67
|
+
throw new Error('Email and password required');
|
|
68
|
+
}
|
|
69
|
+
const loginCredentials = {
|
|
70
|
+
email: credentials.email,
|
|
71
|
+
password: credentials.password,
|
|
72
|
+
};
|
|
73
|
+
// Extract client info for audit logging
|
|
74
|
+
const clientHeaders = extractClientHeaders(req);
|
|
75
|
+
// -------------------------------------------------------------------------
|
|
76
|
+
// Call IDP
|
|
77
|
+
// -------------------------------------------------------------------------
|
|
78
|
+
const loginResult = await (0, idp_client_1.idpLogin)(loginCredentials, clientHeaders);
|
|
79
|
+
if (!loginResult.success || !loginResult.result) {
|
|
80
|
+
// Build structured error for frontend
|
|
81
|
+
const errorResponse = buildAuthError(loginResult.error);
|
|
82
|
+
throw new Error(JSON.stringify(errorResponse));
|
|
83
|
+
}
|
|
84
|
+
const { access_token, refresh_token, user: idpUser } = loginResult.result;
|
|
85
|
+
// -------------------------------------------------------------------------
|
|
86
|
+
// Decode Token
|
|
87
|
+
// -------------------------------------------------------------------------
|
|
88
|
+
const decoded = (0, token_utils_1.decodeIdpAccessToken)(access_token);
|
|
89
|
+
if (!decoded) {
|
|
90
|
+
throw new Error('Failed to decode token');
|
|
91
|
+
}
|
|
92
|
+
// Extract kid from JWT header (CRITICAL: this is different from client_id in payload)
|
|
93
|
+
const bearerKeyId = (0, token_utils_1.extractKidFromToken)(access_token);
|
|
94
|
+
if (bearerKeyId) {
|
|
95
|
+
console.log('[CREDENTIALS] Extracted bearerKeyId (kid) from JWT header:', bearerKeyId);
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
console.warn('[CREDENTIALS] No kid found in JWT header - token may be unsigned or malformed');
|
|
99
|
+
}
|
|
100
|
+
// Extract claims from token
|
|
101
|
+
const email = (0, token_utils_1.extractEmailFromToken)(decoded);
|
|
102
|
+
const roles = (0, token_utils_1.extractRolesFromToken)(decoded);
|
|
103
|
+
const amrClaims = (0, token_utils_1.extractAmrFromToken)(decoded);
|
|
104
|
+
const acrLevel = decoded.acr || '1';
|
|
105
|
+
const userId = decoded.sub;
|
|
106
|
+
// Check if 2FA is complete based on ACR level
|
|
107
|
+
// ACR=1: Provisional token (requires 2FA)
|
|
108
|
+
// ACR=2: Full authentication (2FA complete)
|
|
109
|
+
const mfaVerified = acrLevel === '2';
|
|
110
|
+
// Decode refresh token expiry if available
|
|
111
|
+
let refreshTokenExpires;
|
|
112
|
+
try {
|
|
113
|
+
const refreshDecoded = (0, token_utils_1.decodeIdpAccessToken)(refresh_token);
|
|
114
|
+
if (refreshDecoded?.exp) {
|
|
115
|
+
refreshTokenExpires = (0, token_utils_1.expClaimToMs)(refreshDecoded.exp);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Ignore - will use default expiry
|
|
120
|
+
}
|
|
121
|
+
// -------------------------------------------------------------------------
|
|
122
|
+
// Create Redis Session
|
|
123
|
+
// -------------------------------------------------------------------------
|
|
124
|
+
// Using normalized field names (session-store handles backward compatibility)
|
|
125
|
+
const sessionData = {
|
|
126
|
+
userId,
|
|
127
|
+
email,
|
|
128
|
+
roles,
|
|
129
|
+
// IDP tokens (normalized names)
|
|
130
|
+
idpAccessToken: access_token,
|
|
131
|
+
idpRefreshToken: refresh_token,
|
|
132
|
+
idpAccessTokenExpires: (0, token_utils_1.expClaimToMs)(decoded.exp),
|
|
133
|
+
idpRefreshTokenExpires: refreshTokenExpires,
|
|
134
|
+
decodedAccessToken: decoded,
|
|
135
|
+
// Bearer key ID from JWT header (NOT client_id from payload)
|
|
136
|
+
bearerKeyId,
|
|
137
|
+
// MFA state (normalized names)
|
|
138
|
+
mfaVerified,
|
|
139
|
+
authenticationMethods: amrClaims,
|
|
140
|
+
authenticationLevel: acrLevel,
|
|
141
|
+
// MFA timing info from token
|
|
142
|
+
mfaCompletedAt: decoded.mfa_time ? (0, token_utils_1.expClaimToMs)(decoded.mfa_time) : undefined,
|
|
143
|
+
mfaExpiresAt: decoded.mfa_expires ? (0, token_utils_1.expClaimToMs)(decoded.mfa_expires) : undefined,
|
|
144
|
+
mfaValidityHours: decoded.mfa_validity_hours,
|
|
145
|
+
};
|
|
146
|
+
// Determine MFA method from IDP user info
|
|
147
|
+
let mfaMethod;
|
|
148
|
+
if (idpUser?.isEmailConfirmed) {
|
|
149
|
+
mfaMethod = 'email';
|
|
150
|
+
}
|
|
151
|
+
else if (idpUser?.isSmsConfirmed) {
|
|
152
|
+
mfaMethod = 'sms';
|
|
153
|
+
}
|
|
154
|
+
if (mfaMethod) {
|
|
155
|
+
sessionData.mfaMethod = mfaMethod;
|
|
156
|
+
}
|
|
157
|
+
// Create the Redis session
|
|
158
|
+
const redisSessionId = await (0, session_store_1.createSession)(sessionData);
|
|
159
|
+
// -------------------------------------------------------------------------
|
|
160
|
+
// Return User Object for NextAuth
|
|
161
|
+
// -------------------------------------------------------------------------
|
|
162
|
+
// NextAuth requires 'id' field - we use userId from IDP
|
|
163
|
+
// The redisSessionId is passed through to the JWT callback
|
|
164
|
+
return {
|
|
165
|
+
id: userId,
|
|
166
|
+
email,
|
|
167
|
+
roles,
|
|
168
|
+
redisSessionId: (0, auth_types_1.toRedisSessionId)(redisSessionId),
|
|
169
|
+
mfaRequired: !mfaVerified,
|
|
170
|
+
mfaMethod,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
// ============================================================================
|
|
174
|
+
// HELPER FUNCTIONS
|
|
175
|
+
// ============================================================================
|
|
176
|
+
/**
|
|
177
|
+
* Extract client headers from request for audit logging.
|
|
178
|
+
*/
|
|
179
|
+
function extractClientHeaders(req) {
|
|
180
|
+
const headers = {};
|
|
181
|
+
// Extract client IP
|
|
182
|
+
const forwardedFor = req?.headers?.['x-forwarded-for'];
|
|
183
|
+
const realIp = req?.headers?.['x-real-ip'];
|
|
184
|
+
if (forwardedFor) {
|
|
185
|
+
const ip = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0].trim();
|
|
186
|
+
headers.ip = ip;
|
|
187
|
+
}
|
|
188
|
+
else if (realIp) {
|
|
189
|
+
headers.ip = Array.isArray(realIp) ? realIp[0] : realIp;
|
|
190
|
+
}
|
|
191
|
+
// Extract User-Agent
|
|
192
|
+
const userAgent = req?.headers?.['user-agent'];
|
|
193
|
+
if (userAgent) {
|
|
194
|
+
headers.userAgent = Array.isArray(userAgent) ? userAgent[0] : userAgent;
|
|
195
|
+
}
|
|
196
|
+
return headers;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Build structured error response for frontend.
|
|
200
|
+
*
|
|
201
|
+
* The frontend expects a specific error structure to display
|
|
202
|
+
* appropriate messages and handle things like lockout.
|
|
203
|
+
*/
|
|
204
|
+
function buildAuthError(error) {
|
|
205
|
+
if (!error) {
|
|
206
|
+
return {
|
|
207
|
+
success: false,
|
|
208
|
+
error: {
|
|
209
|
+
code: 'AUTH_ERROR',
|
|
210
|
+
message: 'Authentication failed',
|
|
211
|
+
details: {},
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
success: false,
|
|
217
|
+
error: {
|
|
218
|
+
code: error.code || 'AUTH_ERROR',
|
|
219
|
+
message: error.message || 'Authentication failed',
|
|
220
|
+
details: error.details || {},
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
|
@@ -10,8 +10,10 @@
|
|
|
10
10
|
* - Redis buffering with 1-week TTL
|
|
11
11
|
* - Graceful degradation on failure
|
|
12
12
|
*/
|
|
13
|
-
|
|
14
|
-
export interface VibeLogTransportOptions
|
|
13
|
+
declare let TransportBase: any;
|
|
14
|
+
export interface VibeLogTransportOptions {
|
|
15
|
+
/** Winston transport level */
|
|
16
|
+
level?: string;
|
|
15
17
|
/** Redis URL (optional, uses REDIS_URL env var by default) */
|
|
16
18
|
redisUrl?: string;
|
|
17
19
|
/** Vibe client ID (for log metadata) */
|
|
@@ -30,7 +32,7 @@ export interface VibeLogTransportOptions extends Transport.TransportStreamOption
|
|
|
30
32
|
/**
|
|
31
33
|
* Winston transport that buffers logs to Redis for Vibe drain processing
|
|
32
34
|
*/
|
|
33
|
-
export declare class VibeLogTransport extends
|
|
35
|
+
export declare class VibeLogTransport extends TransportBase {
|
|
34
36
|
private vibeClientId;
|
|
35
37
|
private appSlug;
|
|
36
38
|
private minLevelNum;
|
|
@@ -11,14 +11,23 @@
|
|
|
11
11
|
* - Redis buffering with 1-week TTL
|
|
12
12
|
* - Graceful degradation on failure
|
|
13
13
|
*/
|
|
14
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
15
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
16
|
-
};
|
|
17
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
15
|
exports.VibeLogTransport = void 0;
|
|
19
16
|
exports.createVibeLogTransport = createVibeLogTransport;
|
|
20
|
-
const winston_transport_1 = __importDefault(require("winston-transport"));
|
|
21
17
|
const redis_1 = require("../lib/redis");
|
|
18
|
+
// Dynamic import — winston is a peerDependency and may not be installed.
|
|
19
|
+
// We resolve the base class lazily so builds don't break without it.
|
|
20
|
+
let TransportBase;
|
|
21
|
+
try {
|
|
22
|
+
TransportBase = require('winston-transport');
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// Fallback: minimal base class for when winston is not installed
|
|
26
|
+
TransportBase = class {
|
|
27
|
+
constructor(_opts) { }
|
|
28
|
+
emit(_event, _info) { }
|
|
29
|
+
};
|
|
30
|
+
}
|
|
22
31
|
/** Redis key for pending log entries */
|
|
23
32
|
const REDIS_LOG_KEY = 'vibe:logs:pending';
|
|
24
33
|
/** TTL in seconds: 1 week */
|
|
@@ -33,7 +42,7 @@ const LEVEL_ORDER = {
|
|
|
33
42
|
/**
|
|
34
43
|
* Winston transport that buffers logs to Redis for Vibe drain processing
|
|
35
44
|
*/
|
|
36
|
-
class VibeLogTransport extends
|
|
45
|
+
class VibeLogTransport extends TransportBase {
|
|
37
46
|
vibeClientId;
|
|
38
47
|
appSlug;
|
|
39
48
|
minLevelNum;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-Side Auth Guard for Layouts
|
|
3
|
+
*
|
|
4
|
+
* Replaces middleware's self-fetch auth checks with direct Redis/function calls.
|
|
5
|
+
* Call from server-component layouts to protect routes.
|
|
6
|
+
*
|
|
7
|
+
* Zero HTTP self-fetches. ~8ms total (Redis + in-memory checks).
|
|
8
|
+
*/
|
|
9
|
+
import 'server-only';
|
|
10
|
+
import type { SessionData } from '../lib/session-store';
|
|
11
|
+
export interface AuthGuardOptions {
|
|
12
|
+
/** Custom checks to run after standard auth validation */
|
|
13
|
+
checks?: AuthCheck[];
|
|
14
|
+
/** Override login redirect URL (default: /account-auth/login) */
|
|
15
|
+
loginUrl?: string;
|
|
16
|
+
/** Override 2FA redirect URL (default: /account-auth/verify-code) */
|
|
17
|
+
verifyCodeUrl?: string;
|
|
18
|
+
/** Override service unavailable URL (default: /service-unavailable) */
|
|
19
|
+
serviceUnavailableUrl?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface AuthCheck {
|
|
22
|
+
/** Name for logging */
|
|
23
|
+
name: string;
|
|
24
|
+
/** Returns redirect URL if check fails, null if passes */
|
|
25
|
+
check: (session: SessionData, pathname: string) => Promise<string | null>;
|
|
26
|
+
}
|
|
27
|
+
export interface AuthGuardResult {
|
|
28
|
+
userId: string;
|
|
29
|
+
email: string;
|
|
30
|
+
roles: string[];
|
|
31
|
+
sessionData: SessionData;
|
|
32
|
+
accessToken?: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Server-side auth guard. Call from async server layouts.
|
|
36
|
+
*
|
|
37
|
+
* Redirects (via next/navigation redirect()) if:
|
|
38
|
+
* - No session cookie / invalid JWT
|
|
39
|
+
* - Session not in Redis (stale)
|
|
40
|
+
* - Session force-invalidated
|
|
41
|
+
* - 2FA required but not completed / expired
|
|
42
|
+
* - Any custom check fails
|
|
43
|
+
*
|
|
44
|
+
* Returns the authenticated user's session data on success.
|
|
45
|
+
*/
|
|
46
|
+
export declare function authGuard(options?: AuthGuardOptions): Promise<AuthGuardResult>;
|