@payez/next-mvp 4.1.11 → 4.1.20
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/api-handlers/account/profile.d.ts +38 -0
- package/dist/api-handlers/account/profile.js +73 -45
- package/dist/api-handlers/account/recovery/send-code.d.ts +33 -0
- package/dist/api-handlers/account/recovery/send-code.js +52 -18
- package/dist/api-handlers/account/recovery/verify-code.d.ts +33 -0
- package/dist/api-handlers/account/recovery/verify-code.js +52 -18
- package/dist/api-handlers/account/verify-email.js +15 -1
- package/dist/api-handlers/account/verify-sms.js +15 -1
- package/dist/api-handlers/auth/passkey-signin.d.ts +29 -0
- package/dist/api-handlers/auth/passkey-signin.js +97 -0
- package/dist/api-handlers/mfa/backup-code-verify.d.ts +73 -0
- package/dist/api-handlers/mfa/backup-code-verify.js +153 -0
- package/dist/api-handlers/mfa/backup-codes.d.ts +7 -0
- package/dist/api-handlers/mfa/backup-codes.js +40 -0
- package/dist/api-handlers/mfa/methods.d.ts +3 -0
- package/dist/api-handlers/mfa/methods.js +41 -0
- package/dist/api-handlers/mfa/totp-confirm.d.ts +8 -0
- package/dist/api-handlers/mfa/totp-confirm.js +41 -0
- package/dist/api-handlers/mfa/totp-enroll.d.ts +8 -0
- package/dist/api-handlers/mfa/totp-enroll.js +41 -0
- package/dist/api-handlers/mfa/totp-verify.d.ts +47 -0
- package/dist/api-handlers/mfa/totp-verify.js +134 -0
- package/dist/api-handlers/passkeys/list.d.ts +7 -0
- package/dist/api-handlers/passkeys/list.js +29 -0
- package/dist/api-handlers/passkeys/manage.d.ts +3 -0
- package/dist/api-handlers/passkeys/manage.js +54 -0
- package/dist/api-handlers/passkeys/register-options.d.ts +8 -0
- package/dist/api-handlers/passkeys/register-options.js +41 -0
- package/dist/api-handlers/passkeys/register-verify.d.ts +7 -0
- package/dist/api-handlers/passkeys/register-verify.js +40 -0
- package/dist/api-handlers/session/viability.js +19 -0
- package/dist/auth/better-auth.d.ts +68 -5
- package/dist/auth/better-auth.js +256 -42
- package/dist/auth/utils/idp-client.d.ts +13 -22
- package/dist/auth/utils/idp-client.js +12 -82
- package/dist/client/better-auth-client.d.ts +14 -2
- package/dist/lib/session-store.js +28 -21
- package/dist/lib/startup-init.js +19 -19
- package/dist/lib/token-lifecycle.js +40 -4
- package/dist/models/SessionModel.d.ts +17 -0
- package/dist/pages/login/page.d.ts +10 -1
- package/dist/pages/login/page.js +69 -80
- package/dist/pages/verify-code/page.d.ts +10 -1
- package/dist/pages/verify-code/page.js +72 -4
- package/dist/routes/auth/passkey-signin.d.ts +13 -0
- package/dist/routes/auth/passkey-signin.js +18 -0
- package/dist/routes/auth/viability.d.ts +2 -0
- package/dist/routes/auth/viability.js +88 -0
- package/dist/routes/mfa/backup-code-verify.d.ts +1 -0
- package/dist/routes/mfa/backup-code-verify.js +5 -0
- package/dist/routes/mfa/backup-codes.d.ts +10 -0
- package/dist/routes/mfa/backup-codes.js +14 -0
- package/dist/routes/mfa/methods.d.ts +21 -0
- package/dist/routes/mfa/methods.js +10 -0
- package/dist/routes/mfa/totp-confirm.d.ts +10 -0
- package/dist/routes/mfa/totp-confirm.js +14 -0
- package/dist/routes/mfa/totp-enroll.d.ts +10 -0
- package/dist/routes/mfa/totp-enroll.js +14 -0
- package/dist/routes/mfa/totp-verify.d.ts +14 -0
- package/dist/routes/mfa/totp-verify.js +18 -0
- package/dist/routes/passkeys/list.d.ts +10 -0
- package/dist/routes/passkeys/list.js +14 -0
- package/dist/routes/passkeys/manage.d.ts +18 -0
- package/dist/routes/passkeys/manage.js +13 -0
- package/dist/routes/passkeys/register-options.d.ts +10 -0
- package/dist/routes/passkeys/register-options.js +14 -0
- package/dist/routes/passkeys/register-verify.d.ts +10 -0
- package/dist/routes/passkeys/register-verify.js +14 -0
- package/dist/server/auth.d.ts +2 -2
- package/dist/server/decode-session.js +37 -3
- package/package.json +958 -893
- package/scripts/check-internal-url-usage.sh +73 -73
- package/src/api/index.ts +17 -17
- package/src/api-handlers/account/masked-info.ts +45 -45
- package/src/api-handlers/account/profile.ts +99 -80
- package/src/api-handlers/account/recovery/initiate.ts +23 -23
- package/src/api-handlers/account/recovery/send-code.ts +73 -25
- package/src/api-handlers/account/recovery/verify-code.ts +73 -25
- package/src/api-handlers/account/reset-password.ts +23 -23
- package/src/api-handlers/account/send-code.ts +76 -76
- package/src/api-handlers/account/validate-password.ts +118 -118
- package/src/api-handlers/account/verify-email.ts +15 -1
- package/src/api-handlers/account/verify-sms.ts +15 -1
- package/src/api-handlers/admin/stats.ts +249 -249
- package/src/api-handlers/anon/preferences.ts +123 -123
- package/src/api-handlers/auth/jwks.ts +20 -20
- package/src/api-handlers/auth/login.ts +240 -240
- package/src/api-handlers/auth/passkey-signin.ts +98 -0
- package/src/api-handlers/auth/validate.ts +43 -43
- package/src/api-handlers/mfa/backup-code-verify.ts +175 -0
- package/src/api-handlers/mfa/backup-codes.ts +41 -0
- package/src/api-handlers/mfa/methods.ts +46 -0
- package/src/api-handlers/mfa/totp-confirm.ts +42 -0
- package/src/api-handlers/mfa/totp-enroll.ts +42 -0
- package/src/api-handlers/mfa/totp-verify.ts +156 -0
- package/src/api-handlers/passkeys/list.ts +31 -0
- package/src/api-handlers/passkeys/manage.ts +54 -0
- package/src/api-handlers/passkeys/register-options.ts +42 -0
- package/src/api-handlers/passkeys/register-verify.ts +41 -0
- package/src/api-handlers/session/viability.ts +161 -142
- package/src/auth/better-auth.ts +247 -6
- package/src/auth/unauthenticated-routes.ts +2 -2
- package/src/auth/utils/idp-client.ts +13 -95
- package/src/client/better-auth-client.ts +70 -70
- package/src/client/fetchWithSession.ts +21 -21
- package/src/client/index.ts +13 -13
- package/src/client/useAnonSession.ts +131 -131
- package/src/components/admin/VibeAdminContext.tsx +87 -87
- package/src/config/logging-config.ts +82 -82
- package/src/config/unauthenticated-routes.ts +19 -19
- package/src/edge/internal-api-url.ts +65 -65
- package/src/edge/middleware.ts +42 -42
- package/src/hooks/useProfile.ts +75 -75
- package/src/lib/anon-session.ts +213 -213
- package/src/lib/auth-secret.ts +137 -137
- package/src/lib/demo-mode.ts +17 -17
- package/src/lib/idp-client-config.ts +559 -559
- package/src/lib/idp-fetch.ts +126 -126
- package/src/lib/internal-api.ts +171 -171
- package/src/lib/jwt-decode-client.ts +45 -45
- package/src/lib/rate-limit-service.ts +9 -9
- package/src/lib/redis.ts +26 -26
- package/src/lib/refresh-token-validator.ts +64 -64
- package/src/lib/secret-validation.ts +8 -8
- package/src/lib/session-store.ts +702 -695
- package/src/lib/session.ts +34 -34
- package/src/lib/startup-init.ts +251 -251
- package/src/lib/token-expiry.ts +40 -40
- package/src/lib/token-lifecycle.ts +533 -497
- package/src/lib/types/api-responses.ts +336 -336
- package/src/middleware/auth-decision.ts +43 -43
- package/src/models/DecodedAccessToken.ts +16 -16
- package/src/models/SessionModel.ts +282 -264
- package/src/pages/admin-roles/index.ts +9 -9
- package/src/pages/login/page.tsx +123 -228
- package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
- package/src/pages/verify-code/page.tsx +71 -5
- package/src/routes/account/index.ts +31 -31
- package/src/routes/account/masked-info.ts +36 -36
- package/src/routes/account/send-code.ts +39 -39
- package/src/routes/account/verify-email.ts +40 -40
- package/src/routes/account/verify-sms.ts +40 -40
- package/src/routes/auth/index.ts +22 -22
- package/src/routes/auth/passkey-signin.ts +13 -0
- package/src/routes/auth/refresh.ts +48 -48
- package/src/routes/auth/session.ts +166 -166
- package/src/routes/auth/viability.ts +89 -0
- package/src/routes/index.ts +17 -17
- package/src/routes/mfa/backup-code-verify.ts +1 -0
- package/src/routes/mfa/backup-codes.ts +10 -0
- package/src/routes/mfa/methods.ts +22 -0
- package/src/routes/mfa/totp-confirm.ts +10 -0
- package/src/routes/mfa/totp-enroll.ts +10 -0
- package/src/routes/mfa/totp-verify.ts +14 -0
- package/src/routes/passkeys/list.ts +10 -0
- package/src/routes/passkeys/manage.ts +23 -0
- package/src/routes/passkeys/register-options.ts +10 -0
- package/src/routes/passkeys/register-verify.ts +10 -0
- package/src/routes/session/index.ts +7 -7
- package/src/routes/session/refresh-viability.ts +17 -17
- package/src/server/auth.ts +373 -373
- package/src/server/decode-session.ts +235 -202
- package/src/services/signalrActivityService.ts +258 -258
- package/src/theme/ThemeProvider.tsx +39 -39
- package/src/theme/default.ts +33 -33
- package/src/theme/index.ts +31 -31
- package/src/theme/types.ts +69 -69
- package/src/theme/useTheme.ts +57 -57
- package/src/theme/utils.ts +40 -40
- package/src/types/api.ts +12 -12
- package/src/types/auth.d.ts +23 -23
- package/src/types/auth.ts +22 -22
- package/src/types/logging.ts +11 -11
- package/src/types/recovery.ts +54 -54
- package/src/utils/api.ts +353 -353
- package/src/utils/circuitBreaker.ts +40 -40
- package/src/utils/error-message.ts +108 -108
- package/src/utils/layout/reservedSpace.ts +124 -124
package/src/lib/idp-fetch.ts
CHANGED
|
@@ -1,127 +1,127 @@
|
|
|
1
|
-
import { NextRequest } from 'next/server';
|
|
2
|
-
import { getTokenTestAware } from './test-aware-get-token';
|
|
3
|
-
import { getSession } from './session-store';
|
|
4
|
-
import { internalRefresh } from './internal-api';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Centralized IDP fetch helper
|
|
8
|
-
* - Injects Bearer from Redis session
|
|
9
|
-
* - If access token is expired/near-expiry, triggers one refresh and retries fetch once
|
|
10
|
-
* - Returns parsed JSON and HTTP status
|
|
11
|
-
*/
|
|
12
|
-
export interface IdpFetchResult<T = any> {
|
|
13
|
-
ok: boolean;
|
|
14
|
-
status: number;
|
|
15
|
-
json: T | null;
|
|
16
|
-
attemptedRefresh: boolean;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function buildHeaders(req: NextRequest, bearer?: string, extra?: Record<string, string>) {
|
|
20
|
-
const headers: Record<string, string> = {
|
|
21
|
-
Accept: 'application/json',
|
|
22
|
-
'Content-Type': 'application/json',
|
|
23
|
-
...extra,
|
|
24
|
-
};
|
|
25
|
-
const xfwd = req.headers.get('x-forwarded-for') || req.headers.get('x-real-ip');
|
|
26
|
-
if (xfwd) headers['X-Forwarded-For'] = xfwd.split(',')[0].trim();
|
|
27
|
-
const ua = req.headers.get('user-agent');
|
|
28
|
-
if (ua) headers['User-Agent'] = ua;
|
|
29
|
-
if (bearer) headers['Authorization'] = `Bearer ${bearer}`;
|
|
30
|
-
return headers;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function ensureFreshAccessToken(req: NextRequest): Promise<{ sessionToken?: string; accessToken?: string; hasRefreshToken?: boolean }> {
|
|
34
|
-
const token = await getTokenTestAware(req);
|
|
35
|
-
// Support both field names: sessionToken (auth.ts JWT) and redisSessionId (legacy)
|
|
36
|
-
const sessionToken = (token?.sessionToken || token?.redisSessionId) as string | undefined;
|
|
37
|
-
console.log('[IDP_FETCH] ensureFreshAccessToken:', {
|
|
38
|
-
hasToken: !!token,
|
|
39
|
-
sessionToken: sessionToken?.substring(0, 20) + '...',
|
|
40
|
-
pathname: req.nextUrl.pathname
|
|
41
|
-
});
|
|
42
|
-
if (!sessionToken) {
|
|
43
|
-
console.warn('[IDP_FETCH] No sessionToken found in JWT - Bearer token will NOT be sent!');
|
|
44
|
-
return {};
|
|
45
|
-
}
|
|
46
|
-
let session = await getSession(sessionToken);
|
|
47
|
-
// Fall back to Better Auth Redis key when app session is missing/stale
|
|
48
|
-
if (!session || !session.idpAccessToken) {
|
|
49
|
-
const { getBetterAuthSession } = await import('./session-store');
|
|
50
|
-
const baSession = await getBetterAuthSession(sessionToken);
|
|
51
|
-
if (baSession?.idpAccessToken) {
|
|
52
|
-
session = baSession;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
// Fall back to Better Auth: decode session from cookies to get IDP tokens
|
|
56
|
-
if (!session?.idpAccessToken) {
|
|
57
|
-
try {
|
|
58
|
-
const { decodeSession } = await import('../server/decode-session');
|
|
59
|
-
const decoded = await decodeSession(req.cookies);
|
|
60
|
-
if (decoded?.sessionData?.idpAccessToken) {
|
|
61
|
-
session = decoded.sessionData;
|
|
62
|
-
}
|
|
63
|
-
} catch { /* decodeSession unavailable in edge */ }
|
|
64
|
-
}
|
|
65
|
-
console.log('[IDP_FETCH] Redis session lookup:', {
|
|
66
|
-
hasSession: !!session,
|
|
67
|
-
hasAccessToken: !!session?.idpAccessToken,
|
|
68
|
-
hasRefreshToken: !!session?.idpRefreshToken,
|
|
69
|
-
bearerKeyId: session?.bearerKeyId || 'NOT_SET',
|
|
70
|
-
idpClientId: session?.idpClientId || 'NOT_SET',
|
|
71
|
-
});
|
|
72
|
-
if (!session?.idpAccessToken) return { sessionToken };
|
|
73
|
-
const hasRefreshToken = !!session.idpRefreshToken;
|
|
74
|
-
const now = Date.now();
|
|
75
|
-
const timeLeft = (session.idpAccessTokenExpires ?? now) - now;
|
|
76
|
-
// Treat tokens as effectively expired if within 5 minutes of expiry
|
|
77
|
-
if (timeLeft > 5 * 60 * 1000) {
|
|
78
|
-
return { sessionToken, accessToken: session.idpAccessToken, hasRefreshToken };
|
|
79
|
-
}
|
|
80
|
-
// Only attempt refresh when we actually have a refresh token to use.
|
|
81
|
-
// Provisional tokens (issued before 2FA completion) have no refresh token.
|
|
82
|
-
if (hasRefreshToken) {
|
|
83
|
-
try {
|
|
84
|
-
await internalRefresh(req.headers.get('cookie') || '', sessionToken);
|
|
85
|
-
} catch {}
|
|
86
|
-
session = await getSession(sessionToken);
|
|
87
|
-
return { sessionToken, accessToken: session?.idpAccessToken, hasRefreshToken: !!session?.idpRefreshToken };
|
|
88
|
-
}
|
|
89
|
-
return { sessionToken, accessToken: session.idpAccessToken, hasRefreshToken };
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export async function idpFetchJSON<T = any>(
|
|
93
|
-
req: NextRequest,
|
|
94
|
-
targetUrl: string,
|
|
95
|
-
init: RequestInit = {}
|
|
96
|
-
): Promise<IdpFetchResult<T>> {
|
|
97
|
-
let attemptedRefresh = false;
|
|
98
|
-
let { accessToken, sessionToken, hasRefreshToken } = await ensureFreshAccessToken(req);
|
|
99
|
-
|
|
100
|
-
const makeCall = async (bearer?: string) => {
|
|
101
|
-
const res = await fetch(targetUrl, {
|
|
102
|
-
...init,
|
|
103
|
-
headers: buildHeaders(req, bearer, init.headers as any),
|
|
104
|
-
});
|
|
105
|
-
let json: any = null;
|
|
106
|
-
try { json = await res.json(); } catch { json = null; }
|
|
107
|
-
return { res, json } as const;
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
// First attempt
|
|
111
|
-
let { res, json } = await makeCall(accessToken);
|
|
112
|
-
// Only attempt refresh on 401/403 if we actually have a refresh token.
|
|
113
|
-
// Provisional tokens (pre-2FA) have no refresh token — refreshing is futile.
|
|
114
|
-
if ((res.status === 401 || res.status === 403) && sessionToken && hasRefreshToken && !attemptedRefresh) {
|
|
115
|
-
attemptedRefresh = true;
|
|
116
|
-
try {
|
|
117
|
-
// Use centralized internal API helper for server-to-server calls
|
|
118
|
-
const rf = await internalRefresh(req.headers.get('cookie') || '', sessionToken);
|
|
119
|
-
if (rf.ok) {
|
|
120
|
-
const fresh = await getSession(sessionToken);
|
|
121
|
-
({ res, json } = await makeCall(fresh?.idpAccessToken));
|
|
122
|
-
}
|
|
123
|
-
} catch {}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
return { ok: res.ok, status: res.status, json: json as T | null, attemptedRefresh };
|
|
1
|
+
import { NextRequest } from 'next/server';
|
|
2
|
+
import { getTokenTestAware } from './test-aware-get-token';
|
|
3
|
+
import { getSession } from './session-store';
|
|
4
|
+
import { internalRefresh } from './internal-api';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Centralized IDP fetch helper
|
|
8
|
+
* - Injects Bearer from Redis session
|
|
9
|
+
* - If access token is expired/near-expiry, triggers one refresh and retries fetch once
|
|
10
|
+
* - Returns parsed JSON and HTTP status
|
|
11
|
+
*/
|
|
12
|
+
export interface IdpFetchResult<T = any> {
|
|
13
|
+
ok: boolean;
|
|
14
|
+
status: number;
|
|
15
|
+
json: T | null;
|
|
16
|
+
attemptedRefresh: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function buildHeaders(req: NextRequest, bearer?: string, extra?: Record<string, string>) {
|
|
20
|
+
const headers: Record<string, string> = {
|
|
21
|
+
Accept: 'application/json',
|
|
22
|
+
'Content-Type': 'application/json',
|
|
23
|
+
...extra,
|
|
24
|
+
};
|
|
25
|
+
const xfwd = req.headers.get('x-forwarded-for') || req.headers.get('x-real-ip');
|
|
26
|
+
if (xfwd) headers['X-Forwarded-For'] = xfwd.split(',')[0].trim();
|
|
27
|
+
const ua = req.headers.get('user-agent');
|
|
28
|
+
if (ua) headers['User-Agent'] = ua;
|
|
29
|
+
if (bearer) headers['Authorization'] = `Bearer ${bearer}`;
|
|
30
|
+
return headers;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function ensureFreshAccessToken(req: NextRequest): Promise<{ sessionToken?: string; accessToken?: string; hasRefreshToken?: boolean }> {
|
|
34
|
+
const token = await getTokenTestAware(req);
|
|
35
|
+
// Support both field names: sessionToken (auth.ts JWT) and redisSessionId (legacy)
|
|
36
|
+
const sessionToken = (token?.sessionToken || token?.redisSessionId) as string | undefined;
|
|
37
|
+
console.log('[IDP_FETCH] ensureFreshAccessToken:', {
|
|
38
|
+
hasToken: !!token,
|
|
39
|
+
sessionToken: sessionToken?.substring(0, 20) + '...',
|
|
40
|
+
pathname: req.nextUrl.pathname
|
|
41
|
+
});
|
|
42
|
+
if (!sessionToken) {
|
|
43
|
+
console.warn('[IDP_FETCH] No sessionToken found in JWT - Bearer token will NOT be sent!');
|
|
44
|
+
return {};
|
|
45
|
+
}
|
|
46
|
+
let session = await getSession(sessionToken);
|
|
47
|
+
// Fall back to Better Auth Redis key when app session is missing/stale
|
|
48
|
+
if (!session || !session.idpAccessToken) {
|
|
49
|
+
const { getBetterAuthSession } = await import('./session-store');
|
|
50
|
+
const baSession = await getBetterAuthSession(sessionToken);
|
|
51
|
+
if (baSession?.idpAccessToken) {
|
|
52
|
+
session = baSession;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Fall back to Better Auth: decode session from cookies to get IDP tokens
|
|
56
|
+
if (!session?.idpAccessToken) {
|
|
57
|
+
try {
|
|
58
|
+
const { decodeSession } = await import('../server/decode-session');
|
|
59
|
+
const decoded = await decodeSession(req.cookies);
|
|
60
|
+
if (decoded?.sessionData?.idpAccessToken) {
|
|
61
|
+
session = decoded.sessionData;
|
|
62
|
+
}
|
|
63
|
+
} catch { /* decodeSession unavailable in edge */ }
|
|
64
|
+
}
|
|
65
|
+
console.log('[IDP_FETCH] Redis session lookup:', {
|
|
66
|
+
hasSession: !!session,
|
|
67
|
+
hasAccessToken: !!session?.idpAccessToken,
|
|
68
|
+
hasRefreshToken: !!session?.idpRefreshToken,
|
|
69
|
+
bearerKeyId: session?.bearerKeyId || 'NOT_SET',
|
|
70
|
+
idpClientId: session?.idpClientId || 'NOT_SET',
|
|
71
|
+
});
|
|
72
|
+
if (!session?.idpAccessToken) return { sessionToken };
|
|
73
|
+
const hasRefreshToken = !!session.idpRefreshToken;
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
const timeLeft = (session.idpAccessTokenExpires ?? now) - now;
|
|
76
|
+
// Treat tokens as effectively expired if within 5 minutes of expiry
|
|
77
|
+
if (timeLeft > 5 * 60 * 1000) {
|
|
78
|
+
return { sessionToken, accessToken: session.idpAccessToken, hasRefreshToken };
|
|
79
|
+
}
|
|
80
|
+
// Only attempt refresh when we actually have a refresh token to use.
|
|
81
|
+
// Provisional tokens (issued before 2FA completion) have no refresh token.
|
|
82
|
+
if (hasRefreshToken) {
|
|
83
|
+
try {
|
|
84
|
+
await internalRefresh(req.headers.get('cookie') || '', sessionToken);
|
|
85
|
+
} catch {}
|
|
86
|
+
session = await getSession(sessionToken);
|
|
87
|
+
return { sessionToken, accessToken: session?.idpAccessToken, hasRefreshToken: !!session?.idpRefreshToken };
|
|
88
|
+
}
|
|
89
|
+
return { sessionToken, accessToken: session.idpAccessToken, hasRefreshToken };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function idpFetchJSON<T = any>(
|
|
93
|
+
req: NextRequest,
|
|
94
|
+
targetUrl: string,
|
|
95
|
+
init: RequestInit = {}
|
|
96
|
+
): Promise<IdpFetchResult<T>> {
|
|
97
|
+
let attemptedRefresh = false;
|
|
98
|
+
let { accessToken, sessionToken, hasRefreshToken } = await ensureFreshAccessToken(req);
|
|
99
|
+
|
|
100
|
+
const makeCall = async (bearer?: string) => {
|
|
101
|
+
const res = await fetch(targetUrl, {
|
|
102
|
+
...init,
|
|
103
|
+
headers: buildHeaders(req, bearer, init.headers as any),
|
|
104
|
+
});
|
|
105
|
+
let json: any = null;
|
|
106
|
+
try { json = await res.json(); } catch { json = null; }
|
|
107
|
+
return { res, json } as const;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// First attempt
|
|
111
|
+
let { res, json } = await makeCall(accessToken);
|
|
112
|
+
// Only attempt refresh on 401/403 if we actually have a refresh token.
|
|
113
|
+
// Provisional tokens (pre-2FA) have no refresh token — refreshing is futile.
|
|
114
|
+
if ((res.status === 401 || res.status === 403) && sessionToken && hasRefreshToken && !attemptedRefresh) {
|
|
115
|
+
attemptedRefresh = true;
|
|
116
|
+
try {
|
|
117
|
+
// Use centralized internal API helper for server-to-server calls
|
|
118
|
+
const rf = await internalRefresh(req.headers.get('cookie') || '', sessionToken);
|
|
119
|
+
if (rf.ok) {
|
|
120
|
+
const fresh = await getSession(sessionToken);
|
|
121
|
+
({ res, json } = await makeCall(fresh?.idpAccessToken));
|
|
122
|
+
}
|
|
123
|
+
} catch {}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return { ok: res.ok, status: res.status, json: json as T | null, attemptedRefresh };
|
|
127
127
|
}
|
package/src/lib/internal-api.ts
CHANGED
|
@@ -1,171 +1,171 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Centralized internal API helper for the app to call ITSELF.
|
|
3
|
-
*
|
|
4
|
-
* IMPORTANT: All calls from the Next.js server to its own API routes MUST use
|
|
5
|
-
* these functions. Never use req.url, req.nextUrl.origin, or construct URLs
|
|
6
|
-
* from the incoming request.
|
|
7
|
-
*
|
|
8
|
-
* WHY HTTP IS REQUIRED (not optional):
|
|
9
|
-
* - This is the app calling its OWN backend within the same pod/container
|
|
10
|
-
* - NextAuth cookies are encrypted based on request protocol
|
|
11
|
-
* - TLS is terminated at ingress, so the pod receives HTTP internally
|
|
12
|
-
* - Using HTTPS here causes cookie decryption failures and 403 errors
|
|
13
|
-
* - This is NOT about "K8s traffic doesn't need TLS" - it's about
|
|
14
|
-
* protocol consistency for cookie/session encryption
|
|
15
|
-
*
|
|
16
|
-
* Environment:
|
|
17
|
-
* - INTERNAL_API_URL: Required in production (e.g., http://service.namespace.svc.cluster.local:80)
|
|
18
|
-
* - Falls back to http://localhost:3200 in development only
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Get the internal API base URL for the app to call itself.
|
|
23
|
-
*
|
|
24
|
-
* @throws Error in production if INTERNAL_API_URL is not set
|
|
25
|
-
* @returns The base URL (no trailing slash)
|
|
26
|
-
*/
|
|
27
|
-
export function getInternalApiUrl(): string {
|
|
28
|
-
const url = process.env.INTERNAL_API_URL;
|
|
29
|
-
if (url) return url.replace(/\/$/, ''); // strip trailing slash
|
|
30
|
-
|
|
31
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
32
|
-
return 'http://localhost:3200';
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
throw new Error(
|
|
36
|
-
'[INTERNAL_API_URL] FATAL: INTERNAL_API_URL environment variable is REQUIRED in production. ' +
|
|
37
|
-
'This is for the app to call ITSELF. MUST be HTTP (not HTTPS) due to cookie encryption. ' +
|
|
38
|
-
'Set to http://service.namespace.svc.cluster.local:80'
|
|
39
|
-
);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Options for internal fetch calls
|
|
44
|
-
*/
|
|
45
|
-
export interface InternalFetchOptions extends Omit<RequestInit, 'headers'> {
|
|
46
|
-
/** Additional headers to include */
|
|
47
|
-
headers?: Record<string, string>;
|
|
48
|
-
/** Cookie header to forward (typically from req.headers.get('cookie')) */
|
|
49
|
-
cookie?: string;
|
|
50
|
-
/** Session token for x-session-token header */
|
|
51
|
-
sessionToken?: string;
|
|
52
|
-
/** Request ID for tracing */
|
|
53
|
-
requestId?: string;
|
|
54
|
-
/** Parse response as JSON (default: true) */
|
|
55
|
-
parseJson?: boolean;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Result of an internal fetch call
|
|
60
|
-
*/
|
|
61
|
-
export interface InternalFetchResult<T = unknown> {
|
|
62
|
-
ok: boolean;
|
|
63
|
-
status: number;
|
|
64
|
-
statusText: string;
|
|
65
|
-
data: T | null;
|
|
66
|
-
response: Response;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Make a fetch call to an internal API route (app calling itself).
|
|
71
|
-
*
|
|
72
|
-
* @param path - The API path (e.g., '/api/auth/refresh')
|
|
73
|
-
* @param options - Fetch options
|
|
74
|
-
* @returns The fetch result with parsed data
|
|
75
|
-
*
|
|
76
|
-
* @example
|
|
77
|
-
* ```ts
|
|
78
|
-
* // Simple GET
|
|
79
|
-
* const result = await internalFetch('/api/health');
|
|
80
|
-
*
|
|
81
|
-
* // POST with session
|
|
82
|
-
* const result = await internalFetch('/api/auth/refresh', {
|
|
83
|
-
* method: 'POST',
|
|
84
|
-
* cookie: req.headers.get('cookie') || '',
|
|
85
|
-
* sessionToken: token.redisSessionId,
|
|
86
|
-
* body: JSON.stringify({ refresh_token: refreshToken }),
|
|
87
|
-
* });
|
|
88
|
-
* ```
|
|
89
|
-
*/
|
|
90
|
-
export async function internalFetch<T = unknown>(
|
|
91
|
-
path: string,
|
|
92
|
-
options: InternalFetchOptions = {}
|
|
93
|
-
): Promise<InternalFetchResult<T>> {
|
|
94
|
-
const {
|
|
95
|
-
headers: extraHeaders = {},
|
|
96
|
-
cookie,
|
|
97
|
-
sessionToken,
|
|
98
|
-
requestId,
|
|
99
|
-
parseJson = true,
|
|
100
|
-
...fetchOptions
|
|
101
|
-
} = options;
|
|
102
|
-
|
|
103
|
-
const baseUrl = getInternalApiUrl();
|
|
104
|
-
const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
|
105
|
-
|
|
106
|
-
// Build headers
|
|
107
|
-
const headers: Record<string, string> = {
|
|
108
|
-
'Accept': 'application/json',
|
|
109
|
-
'Content-Type': 'application/json',
|
|
110
|
-
...extraHeaders,
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
if (cookie) {
|
|
114
|
-
headers['Cookie'] = cookie;
|
|
115
|
-
}
|
|
116
|
-
if (sessionToken) {
|
|
117
|
-
headers['X-Session-Token'] = sessionToken;
|
|
118
|
-
}
|
|
119
|
-
if (requestId) {
|
|
120
|
-
headers['X-Request-Id'] = requestId;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const response = await fetch(url, {
|
|
124
|
-
...fetchOptions,
|
|
125
|
-
headers,
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
let data: T | null = null;
|
|
129
|
-
if (parseJson) {
|
|
130
|
-
try {
|
|
131
|
-
data = await response.json() as T;
|
|
132
|
-
} catch {
|
|
133
|
-
data = null;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
return {
|
|
138
|
-
ok: response.ok,
|
|
139
|
-
status: response.status,
|
|
140
|
-
statusText: response.statusText,
|
|
141
|
-
data,
|
|
142
|
-
response,
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Trigger a token refresh via the internal API.
|
|
148
|
-
* This is a convenience wrapper for the common refresh pattern.
|
|
149
|
-
*
|
|
150
|
-
* @param cookie - The cookie header from the incoming request
|
|
151
|
-
* @param sessionToken - The session token
|
|
152
|
-
* @param refreshToken - Optional refresh token to include in body
|
|
153
|
-
* @param requestId - Optional request ID for tracing
|
|
154
|
-
* @returns Whether the refresh was successful
|
|
155
|
-
*/
|
|
156
|
-
export async function internalRefresh(
|
|
157
|
-
cookie: string,
|
|
158
|
-
sessionToken: string,
|
|
159
|
-
refreshToken?: string,
|
|
160
|
-
requestId?: string
|
|
161
|
-
): Promise<{ ok: boolean; status: number }> {
|
|
162
|
-
const result = await internalFetch('/api/auth/refresh', {
|
|
163
|
-
method: 'POST',
|
|
164
|
-
cookie,
|
|
165
|
-
sessionToken,
|
|
166
|
-
requestId,
|
|
167
|
-
body: refreshToken ? JSON.stringify({ refresh_token: refreshToken }) : undefined,
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
return { ok: result.ok, status: result.status };
|
|
171
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Centralized internal API helper for the app to call ITSELF.
|
|
3
|
+
*
|
|
4
|
+
* IMPORTANT: All calls from the Next.js server to its own API routes MUST use
|
|
5
|
+
* these functions. Never use req.url, req.nextUrl.origin, or construct URLs
|
|
6
|
+
* from the incoming request.
|
|
7
|
+
*
|
|
8
|
+
* WHY HTTP IS REQUIRED (not optional):
|
|
9
|
+
* - This is the app calling its OWN backend within the same pod/container
|
|
10
|
+
* - NextAuth cookies are encrypted based on request protocol
|
|
11
|
+
* - TLS is terminated at ingress, so the pod receives HTTP internally
|
|
12
|
+
* - Using HTTPS here causes cookie decryption failures and 403 errors
|
|
13
|
+
* - This is NOT about "K8s traffic doesn't need TLS" - it's about
|
|
14
|
+
* protocol consistency for cookie/session encryption
|
|
15
|
+
*
|
|
16
|
+
* Environment:
|
|
17
|
+
* - INTERNAL_API_URL: Required in production (e.g., http://service.namespace.svc.cluster.local:80)
|
|
18
|
+
* - Falls back to http://localhost:3200 in development only
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Get the internal API base URL for the app to call itself.
|
|
23
|
+
*
|
|
24
|
+
* @throws Error in production if INTERNAL_API_URL is not set
|
|
25
|
+
* @returns The base URL (no trailing slash)
|
|
26
|
+
*/
|
|
27
|
+
export function getInternalApiUrl(): string {
|
|
28
|
+
const url = process.env.INTERNAL_API_URL;
|
|
29
|
+
if (url) return url.replace(/\/$/, ''); // strip trailing slash
|
|
30
|
+
|
|
31
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
32
|
+
return 'http://localhost:3200';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
throw new Error(
|
|
36
|
+
'[INTERNAL_API_URL] FATAL: INTERNAL_API_URL environment variable is REQUIRED in production. ' +
|
|
37
|
+
'This is for the app to call ITSELF. MUST be HTTP (not HTTPS) due to cookie encryption. ' +
|
|
38
|
+
'Set to http://service.namespace.svc.cluster.local:80'
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Options for internal fetch calls
|
|
44
|
+
*/
|
|
45
|
+
export interface InternalFetchOptions extends Omit<RequestInit, 'headers'> {
|
|
46
|
+
/** Additional headers to include */
|
|
47
|
+
headers?: Record<string, string>;
|
|
48
|
+
/** Cookie header to forward (typically from req.headers.get('cookie')) */
|
|
49
|
+
cookie?: string;
|
|
50
|
+
/** Session token for x-session-token header */
|
|
51
|
+
sessionToken?: string;
|
|
52
|
+
/** Request ID for tracing */
|
|
53
|
+
requestId?: string;
|
|
54
|
+
/** Parse response as JSON (default: true) */
|
|
55
|
+
parseJson?: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Result of an internal fetch call
|
|
60
|
+
*/
|
|
61
|
+
export interface InternalFetchResult<T = unknown> {
|
|
62
|
+
ok: boolean;
|
|
63
|
+
status: number;
|
|
64
|
+
statusText: string;
|
|
65
|
+
data: T | null;
|
|
66
|
+
response: Response;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Make a fetch call to an internal API route (app calling itself).
|
|
71
|
+
*
|
|
72
|
+
* @param path - The API path (e.g., '/api/auth/refresh')
|
|
73
|
+
* @param options - Fetch options
|
|
74
|
+
* @returns The fetch result with parsed data
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts
|
|
78
|
+
* // Simple GET
|
|
79
|
+
* const result = await internalFetch('/api/health');
|
|
80
|
+
*
|
|
81
|
+
* // POST with session
|
|
82
|
+
* const result = await internalFetch('/api/auth/refresh', {
|
|
83
|
+
* method: 'POST',
|
|
84
|
+
* cookie: req.headers.get('cookie') || '',
|
|
85
|
+
* sessionToken: token.redisSessionId,
|
|
86
|
+
* body: JSON.stringify({ refresh_token: refreshToken }),
|
|
87
|
+
* });
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export async function internalFetch<T = unknown>(
|
|
91
|
+
path: string,
|
|
92
|
+
options: InternalFetchOptions = {}
|
|
93
|
+
): Promise<InternalFetchResult<T>> {
|
|
94
|
+
const {
|
|
95
|
+
headers: extraHeaders = {},
|
|
96
|
+
cookie,
|
|
97
|
+
sessionToken,
|
|
98
|
+
requestId,
|
|
99
|
+
parseJson = true,
|
|
100
|
+
...fetchOptions
|
|
101
|
+
} = options;
|
|
102
|
+
|
|
103
|
+
const baseUrl = getInternalApiUrl();
|
|
104
|
+
const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
|
105
|
+
|
|
106
|
+
// Build headers
|
|
107
|
+
const headers: Record<string, string> = {
|
|
108
|
+
'Accept': 'application/json',
|
|
109
|
+
'Content-Type': 'application/json',
|
|
110
|
+
...extraHeaders,
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
if (cookie) {
|
|
114
|
+
headers['Cookie'] = cookie;
|
|
115
|
+
}
|
|
116
|
+
if (sessionToken) {
|
|
117
|
+
headers['X-Session-Token'] = sessionToken;
|
|
118
|
+
}
|
|
119
|
+
if (requestId) {
|
|
120
|
+
headers['X-Request-Id'] = requestId;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const response = await fetch(url, {
|
|
124
|
+
...fetchOptions,
|
|
125
|
+
headers,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
let data: T | null = null;
|
|
129
|
+
if (parseJson) {
|
|
130
|
+
try {
|
|
131
|
+
data = await response.json() as T;
|
|
132
|
+
} catch {
|
|
133
|
+
data = null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
ok: response.ok,
|
|
139
|
+
status: response.status,
|
|
140
|
+
statusText: response.statusText,
|
|
141
|
+
data,
|
|
142
|
+
response,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Trigger a token refresh via the internal API.
|
|
148
|
+
* This is a convenience wrapper for the common refresh pattern.
|
|
149
|
+
*
|
|
150
|
+
* @param cookie - The cookie header from the incoming request
|
|
151
|
+
* @param sessionToken - The session token
|
|
152
|
+
* @param refreshToken - Optional refresh token to include in body
|
|
153
|
+
* @param requestId - Optional request ID for tracing
|
|
154
|
+
* @returns Whether the refresh was successful
|
|
155
|
+
*/
|
|
156
|
+
export async function internalRefresh(
|
|
157
|
+
cookie: string,
|
|
158
|
+
sessionToken: string,
|
|
159
|
+
refreshToken?: string,
|
|
160
|
+
requestId?: string
|
|
161
|
+
): Promise<{ ok: boolean; status: number }> {
|
|
162
|
+
const result = await internalFetch('/api/auth/refresh', {
|
|
163
|
+
method: 'POST',
|
|
164
|
+
cookie,
|
|
165
|
+
sessionToken,
|
|
166
|
+
requestId,
|
|
167
|
+
body: refreshToken ? JSON.stringify({ refresh_token: refreshToken }) : undefined,
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
return { ok: result.ok, status: result.status };
|
|
171
|
+
}
|