@payez/next-mvp 4.1.11 → 4.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/api-handlers/auth/refresh.js +15 -38
  2. package/dist/auth/better-auth.d.ts +0 -3
  3. package/dist/auth/better-auth.js +164 -69
  4. package/dist/client/better-auth-client.d.ts +14 -2
  5. package/dist/lib/ensure-fresh-access-token.js +8 -42
  6. package/dist/lib/session-store.d.ts +0 -1
  7. package/dist/lib/session-store.js +29 -33
  8. package/dist/lib/startup-init.js +19 -19
  9. package/dist/lib/token-lifecycle.d.ts +0 -2
  10. package/dist/lib/token-lifecycle.js +3 -21
  11. package/package.json +5 -4
  12. package/scripts/check-internal-url-usage.sh +73 -73
  13. package/src/api/index.ts +17 -17
  14. package/src/api-handlers/account/masked-info.ts +45 -45
  15. package/src/api-handlers/account/profile.ts +80 -80
  16. package/src/api-handlers/account/recovery/initiate.ts +23 -23
  17. package/src/api-handlers/account/recovery/send-code.ts +25 -25
  18. package/src/api-handlers/account/recovery/verify-code.ts +25 -25
  19. package/src/api-handlers/account/reset-password.ts +23 -23
  20. package/src/api-handlers/account/send-code.ts +76 -76
  21. package/src/api-handlers/account/validate-password.ts +118 -118
  22. package/src/api-handlers/admin/stats.ts +249 -249
  23. package/src/api-handlers/anon/preferences.ts +123 -123
  24. package/src/api-handlers/auth/jwks.ts +20 -20
  25. package/src/api-handlers/auth/login.ts +240 -240
  26. package/src/api-handlers/auth/refresh.ts +15 -38
  27. package/src/api-handlers/auth/validate.ts +43 -43
  28. package/src/api-handlers/session/viability.ts +142 -142
  29. package/src/auth/better-auth.ts +130 -29
  30. package/src/auth/unauthenticated-routes.ts +2 -2
  31. package/src/client/better-auth-client.ts +70 -70
  32. package/src/client/fetchWithSession.ts +21 -21
  33. package/src/client/index.ts +13 -13
  34. package/src/client/useAnonSession.ts +131 -131
  35. package/src/components/admin/VibeAdminContext.tsx +87 -87
  36. package/src/config/logging-config.ts +82 -82
  37. package/src/config/unauthenticated-routes.ts +19 -19
  38. package/src/edge/internal-api-url.ts +65 -65
  39. package/src/edge/middleware.ts +42 -42
  40. package/src/hooks/useProfile.ts +75 -75
  41. package/src/lib/anon-session.ts +213 -213
  42. package/src/lib/auth-secret.ts +137 -137
  43. package/src/lib/demo-mode.ts +17 -17
  44. package/src/lib/ensure-fresh-access-token.ts +8 -42
  45. package/src/lib/idp-client-config.ts +559 -559
  46. package/src/lib/idp-fetch.ts +126 -126
  47. package/src/lib/internal-api.ts +171 -171
  48. package/src/lib/jwt-decode-client.ts +45 -45
  49. package/src/lib/rate-limit-service.ts +9 -9
  50. package/src/lib/redis.ts +26 -26
  51. package/src/lib/refresh-token-validator.ts +64 -64
  52. package/src/lib/secret-validation.ts +8 -8
  53. package/src/lib/session-store.ts +692 -695
  54. package/src/lib/session.ts +34 -34
  55. package/src/lib/startup-init.ts +251 -251
  56. package/src/lib/token-expiry.ts +40 -40
  57. package/src/lib/token-lifecycle.ts +470 -497
  58. package/src/lib/types/api-responses.ts +336 -336
  59. package/src/middleware/auth-decision.ts +43 -43
  60. package/src/models/DecodedAccessToken.ts +16 -16
  61. package/src/models/SessionModel.ts +264 -264
  62. package/src/pages/admin-roles/index.ts +9 -9
  63. package/src/pages/security/EnhancedSecurityPage.tsx +9 -9
  64. package/src/routes/account/index.ts +31 -31
  65. package/src/routes/account/masked-info.ts +36 -36
  66. package/src/routes/account/send-code.ts +39 -39
  67. package/src/routes/account/verify-email.ts +40 -40
  68. package/src/routes/account/verify-sms.ts +40 -40
  69. package/src/routes/auth/index.ts +22 -22
  70. package/src/routes/auth/refresh.ts +48 -48
  71. package/src/routes/auth/session.ts +166 -166
  72. package/src/routes/index.ts +17 -17
  73. package/src/routes/session/index.ts +7 -7
  74. package/src/routes/session/refresh-viability.ts +17 -17
  75. package/src/server/auth.ts +373 -373
  76. package/src/server/decode-session.ts +202 -202
  77. package/src/services/signalrActivityService.ts +258 -258
  78. package/src/theme/ThemeProvider.tsx +39 -39
  79. package/src/theme/default.ts +33 -33
  80. package/src/theme/index.ts +31 -31
  81. package/src/theme/types.ts +69 -69
  82. package/src/theme/useTheme.ts +57 -57
  83. package/src/theme/utils.ts +40 -40
  84. package/src/types/api.ts +12 -12
  85. package/src/types/auth.d.ts +23 -23
  86. package/src/types/auth.ts +22 -22
  87. package/src/types/logging.ts +11 -11
  88. package/src/types/recovery.ts +54 -54
  89. package/src/utils/api.ts +353 -353
  90. package/src/utils/circuitBreaker.ts +40 -40
  91. package/src/utils/error-message.ts +108 -108
  92. package/src/utils/layout/reservedSpace.ts +124 -124
@@ -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
  }
@@ -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
+ }