@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,34 +1,34 @@
1
- export type MinimalSession = {
2
- user?: {
3
- id?: string | null;
4
- email?: string | null;
5
- } | null;
6
- accessToken?: string | null;
7
- expires?: string;
8
- [k: string]: any;
9
- };
10
-
11
- // AppSession is used by authStore - alias to MinimalSession for compatibility
12
- export type AppSession = MinimalSession;
13
-
14
- /**
15
- * Strict session validation for client-side guards.
16
- * A session is considered valid when:
17
- * - a user object exists with non-empty id and email
18
- * - an accessToken string exists
19
- */
20
- export function isValidSession(session: MinimalSession | null | undefined): boolean {
21
- if (!session) return false;
22
- const u = session.user as any;
23
- const hasUser = !!u && typeof u.id === 'string' && u.id.length > 0 && typeof u.email === 'string' && u.email.length > 0;
24
- const hasAccessToken = typeof session.accessToken === 'string' && session.accessToken.length > 0;
25
- return hasUser && hasAccessToken;
26
- }
27
-
28
- /**
29
- * Sanitize session data - returns null if session is invalid
30
- */
31
- export function sanitizeSession(session: MinimalSession | null | undefined): MinimalSession | null {
32
- if (!isValidSession(session)) return null;
33
- return session as MinimalSession;
34
- }
1
+ export type MinimalSession = {
2
+ user?: {
3
+ id?: string | null;
4
+ email?: string | null;
5
+ } | null;
6
+ accessToken?: string | null;
7
+ expires?: string;
8
+ [k: string]: any;
9
+ };
10
+
11
+ // AppSession is used by authStore - alias to MinimalSession for compatibility
12
+ export type AppSession = MinimalSession;
13
+
14
+ /**
15
+ * Strict session validation for client-side guards.
16
+ * A session is considered valid when:
17
+ * - a user object exists with non-empty id and email
18
+ * - an accessToken string exists
19
+ */
20
+ export function isValidSession(session: MinimalSession | null | undefined): boolean {
21
+ if (!session) return false;
22
+ const u = session.user as any;
23
+ const hasUser = !!u && typeof u.id === 'string' && u.id.length > 0 && typeof u.email === 'string' && u.email.length > 0;
24
+ const hasAccessToken = typeof session.accessToken === 'string' && session.accessToken.length > 0;
25
+ return hasUser && hasAccessToken;
26
+ }
27
+
28
+ /**
29
+ * Sanitize session data - returns null if session is invalid
30
+ */
31
+ export function sanitizeSession(session: MinimalSession | null | undefined): MinimalSession | null {
32
+ if (!isValidSession(session)) return null;
33
+ return session as MinimalSession;
34
+ }
@@ -1,251 +1,251 @@
1
- /**
2
- * Startup Initialization for MVP
3
- *
4
- * This module ensures that critical initialization tasks are completed
5
- * before the application serves requests.
6
- *
7
- * Uses unified IDP client config for:
8
- * - BETTER_AUTH_SECRET (the Better Auth signing secret)
9
- * - OAuth provider configuration
10
- * - Auth settings (2FA, session timeouts, etc.)
11
- */
12
-
13
- import 'server-only';
14
- import { getIDPClientConfig, clearConfigRedisCache, type IDPClientConfig } from './idp-client-config';
15
-
16
- let initializationStarted = false;
17
- let initializationComplete = false;
18
- let initializationFailed = false;
19
- let initializationPromise: Promise<void> | null = null;
20
- let lastInitError: Error | null = null;
21
-
22
- // Cached IDP config for access after initialization
23
- let cachedIDPConfig: IDPClientConfig | null = null;
24
-
25
- // Startup backoff to prevent pod restart storms from hammering IDP
26
- let lastStartupAttemptTime = 0;
27
- const STARTUP_BACKOFF_MS = 30000; // 30 seconds between startup attempts after failure
28
-
29
- /**
30
- * Initialize the application startup sequence (async)
31
- * Handles async initialization like fetching secrets from IDP
32
- */
33
- export async function ensureInitialized(): Promise<void> {
34
- // If already initialized, return immediately
35
- if (initializationComplete) {
36
- return;
37
- }
38
-
39
- // If initialization is in progress, wait for it
40
- if (initializationPromise) {
41
- return initializationPromise;
42
- }
43
-
44
- // Prevent hammering IDP on rapid pod restarts
45
- const now = Date.now();
46
- if (initializationFailed && (now - lastStartupAttemptTime) < STARTUP_BACKOFF_MS) {
47
- const remainingMs = STARTUP_BACKOFF_MS - (now - lastStartupAttemptTime);
48
- console.warn('[STARTUP] In backoff period after previous failure, skipping IDP call', {
49
- remainingMs: Math.round(remainingMs),
50
- lastError: lastInitError?.message
51
- });
52
- // Re-throw last error so callers know we're still in failed state
53
- throw lastInitError || new Error('Initialization in backoff period');
54
- }
55
-
56
- // Track this attempt time
57
- lastStartupAttemptTime = now;
58
-
59
- // Mark as started
60
- initializationStarted = true;
61
-
62
- // Start initialization
63
- initializationPromise = performInitialization();
64
- await initializationPromise;
65
- }
66
-
67
- /**
68
- * Synchronously log startup status
69
- * Can be called before async initialization is complete
70
- */
71
- export function logStartupStatus(): void {
72
- if (!initializationStarted) {
73
- console.log('\n');
74
- console.log('╔══════════════════════════════════════════════════════════════╗');
75
- console.log('║ 🚀 PayEz Next MVP - Starting Up ║');
76
- console.log('║ ║');
77
- console.log('║ Async initialization in progress... ║');
78
- console.log('║ - Resolving BETTER_AUTH_SECRET from IDP ║');
79
- console.log('║ - Verifying environment configuration ║');
80
- console.log('║ ║');
81
- console.log('║ Check logs below for detailed initialization status: ║');
82
- console.log('╚══════════════════════════════════════════════════════════════╝');
83
- console.log('');
84
- } else if (initializationComplete) {
85
- console.log('\n');
86
- console.log('╔══════════════════════════════════════════════════════════════╗');
87
- console.log('║ ✨ PayEz Next MVP Ready for Requests ✨ ║');
88
- console.log('╚══════════════════════════════════════════════════════════════╝');
89
- console.log('');
90
- } else if (lastInitError) {
91
- console.log('\n');
92
- console.log('╔══════════════════════════════════════════════════════════════╗');
93
- console.log('║ ⚠️ Startup error detected - initialization may still retry ║');
94
- console.log('╚══════════════════════════════════════════════════════════════╝');
95
- console.log('');
96
- }
97
- }
98
-
99
- async function performInitialization(): Promise<void> {
100
- console.log('\n');
101
- console.log('╔══════════════════════════════════════════════════════════════╗');
102
- console.log('║ PayEz Next MVP - Async Startup ║');
103
- console.log('╚══════════════════════════════════════════════════════════════╝');
104
- console.log('');
105
-
106
- try {
107
- // Step 1: Fetch full client config from IDP (includes secret, providers, settings)
108
- console.log('[STARTUP] Step 1/2: Fetching client config from IDP...');
109
-
110
- // Clear any stale Redis cache so startup always gets fresh IDP data
111
- await clearConfigRedisCache();
112
-
113
- try {
114
- const config = await getIDPClientConfig(true);
115
- cachedIDPConfig = config;
116
-
117
- console.log('[STARTUP] Client config loaded successfully');
118
- console.log('[STARTUP] - Client ID:', config.clientId);
119
- console.log('[STARTUP] - Client Slug:', config.clientSlug);
120
- console.log('[STARTUP] - Secret length:', config.authSecret?.length || 0, 'chars');
121
- console.log('[STARTUP] - OAuth Providers:', config.oauthProviders?.filter(p => p.enabled).map(p => p.provider).join(', ') || 'none');
122
- console.log('[STARTUP] - Require 2FA:', config.authSettings?.require2FA);
123
- console.log('[STARTUP] - Cache TTL:', config.configCacheTtlSeconds, 'seconds');
124
- console.log('[STARTUP] - Base Client URL:', config.baseClientUrl || '(not set)');
125
-
126
- // Set BETTER_AUTH_SECRET from IDP response if not already set.
127
- // Also mirror to legacy NEXTAUTH_SECRET during the rename transition
128
- // so any consumer code still reading the old name keeps working.
129
- if (config.authSecret && !process.env.BETTER_AUTH_SECRET) {
130
- process.env.BETTER_AUTH_SECRET = config.authSecret;
131
- console.log('[STARTUP] Set BETTER_AUTH_SECRET from IDP config');
132
- }
133
- if (config.authSecret && !process.env.NEXTAUTH_SECRET) {
134
- process.env.NEXTAUTH_SECRET = config.authSecret;
135
- }
136
- } catch (error) {
137
- const errorMsg = error instanceof Error ? error.message : String(error);
138
- console.error('[STARTUP] IDP config fetch failed:', errorMsg);
139
-
140
- // No fallback available — IDP config is the only source for the auth secret
141
- console.error('[STARTUP] No fallback available for auth secret resolution');
142
- }
143
-
144
- // Step 2: Verify BETTER_AUTH_SECRET is available - FAIL FAST if not
145
- console.log('[STARTUP] Step 2/2: Verifying BETTER_AUTH_SECRET...');
146
-
147
- const secret = process.env.BETTER_AUTH_SECRET || process.env.NEXTAUTH_SECRET;
148
- if (!secret || secret.trim() === '') {
149
- console.error('');
150
- console.error('╔══════════════════════════════════════════════════════════════╗');
151
- console.error('║ ❌ FATAL: BETTER_AUTH_SECRET NOT AVAILABLE ║');
152
- console.error('║ ║');
153
- console.error('║ The app cannot start without a valid auth signing secret. ║');
154
- console.error('║ This should be fetched from IDP at startup. ║');
155
- console.error('║ ║');
156
- console.error('║ Possible causes: ║');
157
- console.error('║ • IDP is not running or unreachable ║');
158
- console.error('║ • CLIENT_ID is not registered in IDP ║');
159
- console.error('║ • IDP_URL is incorrect ║');
160
- console.error('║ • Network connectivity issue ║');
161
- console.error('╚══════════════════════════════════════════════════════════════╝');
162
- console.error('');
163
- throw new Error('FATAL: BETTER_AUTH_SECRET not available - cannot start without valid secret from IDP');
164
- }
165
-
166
- console.log('[STARTUP] BETTER_AUTH_SECRET verified (' + secret.length + ' chars)');
167
-
168
- // Step 3: Validate cookie name consistency
169
- // This catches bugs where getJwtCookieName() returns a different name than
170
- // what auth-options.ts configures, which causes sessions to fail in production
171
- const { validateCookieNameConsistency, getSessionCookieName } = await import('./app-slug');
172
- validateCookieNameConsistency();
173
- console.log('[STARTUP] Cookie name consistency validated:', getSessionCookieName());
174
-
175
- // All done
176
- console.log('');
177
- console.log('╔══════════════════════════════════════════════════════════════╗');
178
- console.log('║ PayEz Next MVP Ready for Requests ║');
179
- console.log('╚══════════════════════════════════════════════════════════════╝');
180
- console.log('');
181
-
182
- initializationComplete = true;
183
- initializationFailed = false;
184
- lastInitError = null;
185
- } catch (error) {
186
- lastInitError = error instanceof Error ? error : new Error(String(error));
187
- initializationFailed = true;
188
-
189
- const errorMsg = lastInitError.message || 'Unknown error';
190
- const isConnectionError = errorMsg.includes('fetch failed') || errorMsg.includes('ECONNREFUSED');
191
- const idpUrl = (process.env.IDP_URL || 'NOT SET').padEnd(46);
192
- const clientId = (process.env.CLIENT_ID || 'NOT SET').padEnd(43);
193
-
194
- const connectionLine = isConnectionError
195
- ? '║ 🔌 CONNECTION REFUSED - IDP appears to be down ║\n║ ║\n'
196
- : '';
197
-
198
- console.error(`
199
- ╔══════════════════════════════════════════════════════════════╗
200
- ║ ❌ FATAL: BETTER_AUTH_SECRET NOT AVAILABLE ║
201
- ║ ║
202
- ║ The app cannot start without a valid auth signing secret. ║
203
- ║ This should be fetched from IDP at startup. ║
204
- ║ ║
205
- ${connectionLine}║ Possible causes: ║
206
- ║ • IDP is not running or unreachable ║
207
- ║ • CLIENT_ID is not registered in IDP ║
208
- ║ • IDP_URL is incorrect ║
209
- ║ • Network connectivity issue ║
210
- ║ ║
211
- ║ Current config: ║
212
- ║ • IDP_URL: ${idpUrl}║
213
- ║ • CLIENT_ID: ${clientId}║
214
- ╚══════════════════════════════════════════════════════════════╝
215
-
216
- [STARTUP] Error: ${errorMsg}
217
- `);
218
-
219
- // Re-throw so callers know initialization failed
220
- throw lastInitError;
221
- }
222
- }
223
-
224
- /**
225
- * Get the cached IDP config after initialization.
226
- * Returns null if not yet initialized.
227
- */
228
- export function getStartupIDPConfig(): IDPClientConfig | null {
229
- return cachedIDPConfig;
230
- }
231
-
232
- /**
233
- * Check if initialization failed (auth signing secret couldn't be retrieved)
234
- */
235
- export function isInitializationFailed(): boolean {
236
- return initializationFailed;
237
- }
238
-
239
- /**
240
- * Get the last initialization error
241
- */
242
- export function getInitializationError(): Error | null {
243
- return lastInitError;
244
- }
245
-
246
- /**
247
- * Check if the app is ready to handle auth requests
248
- */
249
- export function isAppReady(): boolean {
250
- return initializationComplete && !initializationFailed;
251
- }
1
+ /**
2
+ * Startup Initialization for MVP
3
+ *
4
+ * This module ensures that critical initialization tasks are completed
5
+ * before the application serves requests.
6
+ *
7
+ * Uses unified IDP client config for:
8
+ * - BETTER_AUTH_SECRET (the Better Auth signing secret)
9
+ * - OAuth provider configuration
10
+ * - Auth settings (2FA, session timeouts, etc.)
11
+ */
12
+
13
+ import 'server-only';
14
+ import { getIDPClientConfig, clearConfigRedisCache, type IDPClientConfig } from './idp-client-config';
15
+
16
+ let initializationStarted = false;
17
+ let initializationComplete = false;
18
+ let initializationFailed = false;
19
+ let initializationPromise: Promise<void> | null = null;
20
+ let lastInitError: Error | null = null;
21
+
22
+ // Cached IDP config for access after initialization
23
+ let cachedIDPConfig: IDPClientConfig | null = null;
24
+
25
+ // Startup backoff to prevent pod restart storms from hammering IDP
26
+ let lastStartupAttemptTime = 0;
27
+ const STARTUP_BACKOFF_MS = 30000; // 30 seconds between startup attempts after failure
28
+
29
+ /**
30
+ * Initialize the application startup sequence (async)
31
+ * Handles async initialization like fetching secrets from IDP
32
+ */
33
+ export async function ensureInitialized(): Promise<void> {
34
+ // If already initialized, return immediately
35
+ if (initializationComplete) {
36
+ return;
37
+ }
38
+
39
+ // If initialization is in progress, wait for it
40
+ if (initializationPromise) {
41
+ return initializationPromise;
42
+ }
43
+
44
+ // Prevent hammering IDP on rapid pod restarts
45
+ const now = Date.now();
46
+ if (initializationFailed && (now - lastStartupAttemptTime) < STARTUP_BACKOFF_MS) {
47
+ const remainingMs = STARTUP_BACKOFF_MS - (now - lastStartupAttemptTime);
48
+ console.warn('[STARTUP] In backoff period after previous failure, skipping IDP call', {
49
+ remainingMs: Math.round(remainingMs),
50
+ lastError: lastInitError?.message
51
+ });
52
+ // Re-throw last error so callers know we're still in failed state
53
+ throw lastInitError || new Error('Initialization in backoff period');
54
+ }
55
+
56
+ // Track this attempt time
57
+ lastStartupAttemptTime = now;
58
+
59
+ // Mark as started
60
+ initializationStarted = true;
61
+
62
+ // Start initialization
63
+ initializationPromise = performInitialization();
64
+ await initializationPromise;
65
+ }
66
+
67
+ /**
68
+ * Synchronously log startup status
69
+ * Can be called before async initialization is complete
70
+ */
71
+ export function logStartupStatus(): void {
72
+ if (!initializationStarted) {
73
+ console.log('\n');
74
+ console.log('╔══════════════════════════════════════════════════════════════╗');
75
+ console.log('║ 🚀 PayEz Next MVP - Starting Up ║');
76
+ console.log('║ ║');
77
+ console.log('║ Async initialization in progress... ║');
78
+ console.log('║ - Resolving BETTER_AUTH_SECRET from IDP ║');
79
+ console.log('║ - Verifying environment configuration ║');
80
+ console.log('║ ║');
81
+ console.log('║ Check logs below for detailed initialization status: ║');
82
+ console.log('╚══════════════════════════════════════════════════════════════╝');
83
+ console.log('');
84
+ } else if (initializationComplete) {
85
+ console.log('\n');
86
+ console.log('╔══════════════════════════════════════════════════════════════╗');
87
+ console.log('║ ✨ PayEz Next MVP Ready for Requests ✨ ║');
88
+ console.log('╚══════════════════════════════════════════════════════════════╝');
89
+ console.log('');
90
+ } else if (lastInitError) {
91
+ console.log('\n');
92
+ console.log('╔══════════════════════════════════════════════════════════════╗');
93
+ console.log('║ ⚠️ Startup error detected - initialization may still retry ║');
94
+ console.log('╚══════════════════════════════════════════════════════════════╝');
95
+ console.log('');
96
+ }
97
+ }
98
+
99
+ async function performInitialization(): Promise<void> {
100
+ console.log('\n');
101
+ console.log('╔══════════════════════════════════════════════════════════════╗');
102
+ console.log('║ PayEz Next MVP - Async Startup ║');
103
+ console.log('╚══════════════════════════════════════════════════════════════╝');
104
+ console.log('');
105
+
106
+ try {
107
+ // Step 1: Fetch full client config from IDP (includes secret, providers, settings)
108
+ console.log('[STARTUP] Step 1/2: Fetching client config from IDP...');
109
+
110
+ // Clear any stale Redis cache so startup always gets fresh IDP data
111
+ await clearConfigRedisCache();
112
+
113
+ try {
114
+ const config = await getIDPClientConfig(true);
115
+ cachedIDPConfig = config;
116
+
117
+ console.log('[STARTUP] Client config loaded successfully');
118
+ console.log('[STARTUP] - Client ID:', config.clientId);
119
+ console.log('[STARTUP] - Client Slug:', config.clientSlug);
120
+ console.log('[STARTUP] - Secret length:', config.authSecret?.length || 0, 'chars');
121
+ console.log('[STARTUP] - OAuth Providers:', config.oauthProviders?.filter(p => p.enabled).map(p => p.provider).join(', ') || 'none');
122
+ console.log('[STARTUP] - Require 2FA:', config.authSettings?.require2FA);
123
+ console.log('[STARTUP] - Cache TTL:', config.configCacheTtlSeconds, 'seconds');
124
+ console.log('[STARTUP] - Base Client URL:', config.baseClientUrl || '(not set)');
125
+
126
+ // Set BETTER_AUTH_SECRET from IDP response if not already set.
127
+ // Also mirror to legacy NEXTAUTH_SECRET during the rename transition
128
+ // so any consumer code still reading the old name keeps working.
129
+ if (config.authSecret && !process.env.BETTER_AUTH_SECRET) {
130
+ process.env.BETTER_AUTH_SECRET = config.authSecret;
131
+ console.log('[STARTUP] Set BETTER_AUTH_SECRET from IDP config');
132
+ }
133
+ if (config.authSecret && !process.env.NEXTAUTH_SECRET) {
134
+ process.env.NEXTAUTH_SECRET = config.authSecret;
135
+ }
136
+ } catch (error) {
137
+ const errorMsg = error instanceof Error ? error.message : String(error);
138
+ console.error('[STARTUP] IDP config fetch failed:', errorMsg);
139
+
140
+ // No fallback available — IDP config is the only source for the auth secret
141
+ console.error('[STARTUP] No fallback available for auth secret resolution');
142
+ }
143
+
144
+ // Step 2: Verify BETTER_AUTH_SECRET is available - FAIL FAST if not
145
+ console.log('[STARTUP] Step 2/2: Verifying BETTER_AUTH_SECRET...');
146
+
147
+ const secret = process.env.BETTER_AUTH_SECRET || process.env.NEXTAUTH_SECRET;
148
+ if (!secret || secret.trim() === '') {
149
+ console.error('');
150
+ console.error('╔══════════════════════════════════════════════════════════════╗');
151
+ console.error('║ ❌ FATAL: BETTER_AUTH_SECRET NOT AVAILABLE ║');
152
+ console.error('║ ║');
153
+ console.error('║ The app cannot start without a valid auth signing secret. ║');
154
+ console.error('║ This should be fetched from IDP at startup. ║');
155
+ console.error('║ ║');
156
+ console.error('║ Possible causes: ║');
157
+ console.error('║ • IDP is not running or unreachable ║');
158
+ console.error('║ • CLIENT_ID is not registered in IDP ║');
159
+ console.error('║ • IDP_URL is incorrect ║');
160
+ console.error('║ • Network connectivity issue ║');
161
+ console.error('╚══════════════════════════════════════════════════════════════╝');
162
+ console.error('');
163
+ throw new Error('FATAL: BETTER_AUTH_SECRET not available - cannot start without valid secret from IDP');
164
+ }
165
+
166
+ console.log('[STARTUP] BETTER_AUTH_SECRET verified (' + secret.length + ' chars)');
167
+
168
+ // Step 3: Validate cookie name consistency
169
+ // This catches bugs where getJwtCookieName() returns a different name than
170
+ // what auth-options.ts configures, which causes sessions to fail in production
171
+ const { validateCookieNameConsistency, getSessionCookieName } = await import('./app-slug');
172
+ validateCookieNameConsistency();
173
+ console.log('[STARTUP] Cookie name consistency validated:', getSessionCookieName());
174
+
175
+ // All done
176
+ console.log('');
177
+ console.log('╔══════════════════════════════════════════════════════════════╗');
178
+ console.log('║ PayEz Next MVP Ready for Requests ║');
179
+ console.log('╚══════════════════════════════════════════════════════════════╝');
180
+ console.log('');
181
+
182
+ initializationComplete = true;
183
+ initializationFailed = false;
184
+ lastInitError = null;
185
+ } catch (error) {
186
+ lastInitError = error instanceof Error ? error : new Error(String(error));
187
+ initializationFailed = true;
188
+
189
+ const errorMsg = lastInitError.message || 'Unknown error';
190
+ const isConnectionError = errorMsg.includes('fetch failed') || errorMsg.includes('ECONNREFUSED');
191
+ const idpUrl = (process.env.IDP_URL || 'NOT SET').padEnd(46);
192
+ const clientId = (process.env.CLIENT_ID || 'NOT SET').padEnd(43);
193
+
194
+ const connectionLine = isConnectionError
195
+ ? '║ 🔌 CONNECTION REFUSED - IDP appears to be down ║\n║ ║\n'
196
+ : '';
197
+
198
+ console.error(`
199
+ ╔══════════════════════════════════════════════════════════════╗
200
+ ║ ❌ FATAL: BETTER_AUTH_SECRET NOT AVAILABLE ║
201
+ ║ ║
202
+ ║ The app cannot start without a valid auth signing secret. ║
203
+ ║ This should be fetched from IDP at startup. ║
204
+ ║ ║
205
+ ${connectionLine}║ Possible causes: ║
206
+ ║ • IDP is not running or unreachable ║
207
+ ║ • CLIENT_ID is not registered in IDP ║
208
+ ║ • IDP_URL is incorrect ║
209
+ ║ • Network connectivity issue ║
210
+ ║ ║
211
+ ║ Current config: ║
212
+ ║ • IDP_URL: ${idpUrl}║
213
+ ║ • CLIENT_ID: ${clientId}║
214
+ ╚══════════════════════════════════════════════════════════════╝
215
+
216
+ [STARTUP] Error: ${errorMsg}
217
+ `);
218
+
219
+ // Re-throw so callers know initialization failed
220
+ throw lastInitError;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Get the cached IDP config after initialization.
226
+ * Returns null if not yet initialized.
227
+ */
228
+ export function getStartupIDPConfig(): IDPClientConfig | null {
229
+ return cachedIDPConfig;
230
+ }
231
+
232
+ /**
233
+ * Check if initialization failed (auth signing secret couldn't be retrieved)
234
+ */
235
+ export function isInitializationFailed(): boolean {
236
+ return initializationFailed;
237
+ }
238
+
239
+ /**
240
+ * Get the last initialization error
241
+ */
242
+ export function getInitializationError(): Error | null {
243
+ return lastInitError;
244
+ }
245
+
246
+ /**
247
+ * Check if the app is ready to handle auth requests
248
+ */
249
+ export function isAppReady(): boolean {
250
+ return initializationComplete && !initializationFailed;
251
+ }