@payez/next-mvp 4.0.21 → 4.0.23

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.
@@ -1,243 +1,246 @@
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
- * Now uses unified IDP client config for:
8
- * - NEXTAUTH_SECRET
9
- * - OAuth provider configuration
10
- * - Auth settings (2FA, session timeouts, etc.)
11
- */
12
-
13
- import 'server-only';
14
- import { getIDPClientConfig, 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 NEXTAUTH_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
- try {
111
- const config = await getIDPClientConfig(true);
112
- cachedIDPConfig = config;
113
-
114
- console.log('[STARTUP] Client config loaded successfully');
115
- console.log('[STARTUP] - Client ID:', config.clientId);
116
- console.log('[STARTUP] - Client Slug:', config.clientSlug);
117
- console.log('[STARTUP] - Secret length:', config.nextAuthSecret?.length || 0, 'chars');
118
- console.log('[STARTUP] - OAuth Providers:', config.oauthProviders?.filter(p => p.enabled).map(p => p.provider).join(', ') || 'none');
119
- console.log('[STARTUP] - Require 2FA:', config.authSettings?.require2FA);
120
- console.log('[STARTUP] - Cache TTL:', config.configCacheTtlSeconds, 'seconds');
121
- console.log('[STARTUP] - Base Client URL:', config.baseClientUrl || '(not set)');
122
-
123
- // Set NEXTAUTH_SECRET from IDP response if not already set
124
- if (config.nextAuthSecret && !process.env.NEXTAUTH_SECRET) {
125
- process.env.NEXTAUTH_SECRET = config.nextAuthSecret;
126
- console.log('[STARTUP] Set NEXTAUTH_SECRET from IDP config');
127
- }
128
- } catch (error) {
129
- const errorMsg = error instanceof Error ? error.message : String(error);
130
- console.error('[STARTUP] IDP config fetch failed:', errorMsg);
131
-
132
- // No fallback available IDP config is the only source for the auth secret
133
- console.error('[STARTUP] No fallback available for auth secret resolution');
134
- }
135
-
136
- // Step 2: Verify NEXTAUTH_SECRET is available - FAIL FAST if not
137
- console.log('[STARTUP] Step 2/2: Verifying NEXTAUTH_SECRET...');
138
-
139
- const secret = process.env.NEXTAUTH_SECRET;
140
- if (!secret || secret.trim() === '') {
141
- console.error('');
142
- console.error('╔══════════════════════════════════════════════════════════════╗');
143
- console.error('║ ❌ FATAL: NEXTAUTH_SECRET NOT AVAILABLE ║');
144
- console.error('║ ║');
145
- console.error('║ The app cannot start without a valid NEXTAUTH_SECRET. ║');
146
- console.error('║ This should be fetched from IDP at startup. ║');
147
- console.error('║ ║');
148
- console.error('║ Possible causes: ║');
149
- console.error('║ IDP is not running or unreachable ║');
150
- console.error('║ • CLIENT_ID is not registered in IDP ║');
151
- console.error('║ IDP_URL is incorrect ║');
152
- console.error('║ • Network connectivity issue ║');
153
- console.error('╚══════════════════════════════════════════════════════════════╝');
154
- console.error('');
155
- throw new Error('FATAL: NEXTAUTH_SECRET not available - cannot start without valid secret from IDP');
156
- }
157
-
158
- console.log('[STARTUP] NEXTAUTH_SECRET verified (' + secret.length + ' chars)');
159
-
160
- // Step 3: Validate cookie name consistency
161
- // This catches bugs where getJwtCookieName() returns a different name than
162
- // what auth-options.ts configures, which causes sessions to fail in production
163
- const { validateCookieNameConsistency, getSessionCookieName } = await import('./app-slug');
164
- validateCookieNameConsistency();
165
- console.log('[STARTUP] Cookie name consistency validated:', getSessionCookieName());
166
-
167
- // All done
168
- console.log('');
169
- console.log('╔══════════════════════════════════════════════════════════════╗');
170
- console.log('║ PayEz Next MVP Ready for Requests ║');
171
- console.log('╚══════════════════════════════════════════════════════════════╝');
172
- console.log('');
173
-
174
- initializationComplete = true;
175
- initializationFailed = false;
176
- lastInitError = null;
177
- } catch (error) {
178
- lastInitError = error instanceof Error ? error : new Error(String(error));
179
- initializationFailed = true;
180
-
181
- const errorMsg = lastInitError.message || 'Unknown error';
182
- const isConnectionError = errorMsg.includes('fetch failed') || errorMsg.includes('ECONNREFUSED');
183
- const idpUrl = (process.env.IDP_URL || 'NOT SET').padEnd(46);
184
- const clientId = (process.env.CLIENT_ID || 'NOT SET').padEnd(43);
185
-
186
- const connectionLine = isConnectionError
187
- ? '║ 🔌 CONNECTION REFUSED - IDP appears to be down ║\n║ ║\n'
188
- : '';
189
-
190
- console.error(`
191
- ╔══════════════════════════════════════════════════════════════╗
192
- ║ ❌ FATAL: NEXTAUTH_SECRET NOT AVAILABLE ║
193
- ║ ║
194
- ║ The app cannot start without a valid NEXTAUTH_SECRET. ║
195
- This should be fetched from IDP at startup.
196
- ║ ║
197
- ${connectionLine}Possible causes:
198
- IDP is not running or unreachable
199
- • CLIENT_ID is not registered in IDP
200
- IDP_URL is incorrect
201
- ║ • Network connectivity issue
202
-
203
- Current config:
204
- ║ • IDP_URL: ${idpUrl}
205
- • CLIENT_ID: ${clientId}
206
- ╚══════════════════════════════════════════════════════════════╝
207
-
208
- [STARTUP] Error: ${errorMsg}
209
- `);
210
-
211
- // Re-throw so callers know initialization failed
212
- throw lastInitError;
213
- }
214
- }
215
-
216
- /**
217
- * Get the cached IDP config after initialization.
218
- * Returns null if not yet initialized.
219
- */
220
- export function getStartupIDPConfig(): IDPClientConfig | null {
221
- return cachedIDPConfig;
222
- }
223
-
224
- /**
225
- * Check if initialization failed (NEXTAUTH_SECRET couldn't be retrieved)
226
- */
227
- export function isInitializationFailed(): boolean {
228
- return initializationFailed;
229
- }
230
-
231
- /**
232
- * Get the last initialization error
233
- */
234
- export function getInitializationError(): Error | null {
235
- return lastInitError;
236
- }
237
-
238
- /**
239
- * Check if the app is ready to handle auth requests
240
- */
241
- export function isAppReady(): boolean {
242
- return initializationComplete && !initializationFailed;
243
- }
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
+ * Now uses unified IDP client config for:
8
+ * - NEXTAUTH_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 NEXTAUTH_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.nextAuthSecret?.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 NEXTAUTH_SECRET from IDP response if not already set
127
+ if (config.nextAuthSecret && !process.env.NEXTAUTH_SECRET) {
128
+ process.env.NEXTAUTH_SECRET = config.nextAuthSecret;
129
+ console.log('[STARTUP] Set NEXTAUTH_SECRET from IDP config');
130
+ }
131
+ } catch (error) {
132
+ const errorMsg = error instanceof Error ? error.message : String(error);
133
+ console.error('[STARTUP] IDP config fetch failed:', errorMsg);
134
+
135
+ // No fallback available — IDP config is the only source for the auth secret
136
+ console.error('[STARTUP] No fallback available for auth secret resolution');
137
+ }
138
+
139
+ // Step 2: Verify NEXTAUTH_SECRET is available - FAIL FAST if not
140
+ console.log('[STARTUP] Step 2/2: Verifying NEXTAUTH_SECRET...');
141
+
142
+ const secret = process.env.NEXTAUTH_SECRET;
143
+ if (!secret || secret.trim() === '') {
144
+ console.error('');
145
+ console.error('╔══════════════════════════════════════════════════════════════╗');
146
+ console.error('║ FATAL: NEXTAUTH_SECRET NOT AVAILABLE ║');
147
+ console.error('║ ║');
148
+ console.error('║ The app cannot start without a valid NEXTAUTH_SECRET. ║');
149
+ console.error('║ This should be fetched from IDP at startup. ║');
150
+ console.error('║ ║');
151
+ console.error('║ Possible causes: ║');
152
+ console.error('║ • IDP is not running or unreachable ║');
153
+ console.error('║ • CLIENT_ID is not registered in IDP ║');
154
+ console.error('║ • IDP_URL is incorrect ║');
155
+ console.error('║ • Network connectivity issue ║');
156
+ console.error('╚══════════════════════════════════════════════════════════════╝');
157
+ console.error('');
158
+ throw new Error('FATAL: NEXTAUTH_SECRET not available - cannot start without valid secret from IDP');
159
+ }
160
+
161
+ console.log('[STARTUP] NEXTAUTH_SECRET verified (' + secret.length + ' chars)');
162
+
163
+ // Step 3: Validate cookie name consistency
164
+ // This catches bugs where getJwtCookieName() returns a different name than
165
+ // what auth-options.ts configures, which causes sessions to fail in production
166
+ const { validateCookieNameConsistency, getSessionCookieName } = await import('./app-slug');
167
+ validateCookieNameConsistency();
168
+ console.log('[STARTUP] Cookie name consistency validated:', getSessionCookieName());
169
+
170
+ // All done
171
+ console.log('');
172
+ console.log('╔══════════════════════════════════════════════════════════════╗');
173
+ console.log('║ PayEz Next MVP Ready for Requests ║');
174
+ console.log('╚══════════════════════════════════════════════════════════════╝');
175
+ console.log('');
176
+
177
+ initializationComplete = true;
178
+ initializationFailed = false;
179
+ lastInitError = null;
180
+ } catch (error) {
181
+ lastInitError = error instanceof Error ? error : new Error(String(error));
182
+ initializationFailed = true;
183
+
184
+ const errorMsg = lastInitError.message || 'Unknown error';
185
+ const isConnectionError = errorMsg.includes('fetch failed') || errorMsg.includes('ECONNREFUSED');
186
+ const idpUrl = (process.env.IDP_URL || 'NOT SET').padEnd(46);
187
+ const clientId = (process.env.CLIENT_ID || 'NOT SET').padEnd(43);
188
+
189
+ const connectionLine = isConnectionError
190
+ ? '║ 🔌 CONNECTION REFUSED - IDP appears to be down ║\n║ ║\n'
191
+ : '';
192
+
193
+ console.error(`
194
+ ╔══════════════════════════════════════════════════════════════╗
195
+ FATAL: NEXTAUTH_SECRET NOT AVAILABLE
196
+ ║ ║
197
+ The app cannot start without a valid NEXTAUTH_SECRET.
198
+ This should be fetched from IDP at startup.
199
+
200
+ ${connectionLine}Possible causes:
201
+ ║ • IDP is not running or unreachable
202
+ • CLIENT_ID is not registered in IDP
203
+ IDP_URL is incorrect
204
+ ║ • Network connectivity issue
205
+
206
+ ║ Current config: ║
207
+ ║ • IDP_URL: ${idpUrl}║
208
+ ║ • CLIENT_ID: ${clientId}
209
+ ╚══════════════════════════════════════════════════════════════╝
210
+
211
+ [STARTUP] Error: ${errorMsg}
212
+ `);
213
+
214
+ // Re-throw so callers know initialization failed
215
+ throw lastInitError;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Get the cached IDP config after initialization.
221
+ * Returns null if not yet initialized.
222
+ */
223
+ export function getStartupIDPConfig(): IDPClientConfig | null {
224
+ return cachedIDPConfig;
225
+ }
226
+
227
+ /**
228
+ * Check if initialization failed (NEXTAUTH_SECRET couldn't be retrieved)
229
+ */
230
+ export function isInitializationFailed(): boolean {
231
+ return initializationFailed;
232
+ }
233
+
234
+ /**
235
+ * Get the last initialization error
236
+ */
237
+ export function getInitializationError(): Error | null {
238
+ return lastInitError;
239
+ }
240
+
241
+ /**
242
+ * Check if the app is ready to handle auth requests
243
+ */
244
+ export function isAppReady(): boolean {
245
+ return initializationComplete && !initializationFailed;
246
+ }
@@ -14,7 +14,7 @@ export interface PublicAuthSettings {
14
14
 
15
15
  // Registration settings
16
16
  allowPublicRegistration: boolean;
17
- allowSocialLogin: boolean;
17
+ allowFederatedLogin: boolean;
18
18
 
19
19
  // Password settings
20
20
  enablePasswordReset: boolean;
@@ -42,7 +42,7 @@ export async function GET() {
42
42
 
43
43
  // Registration - default to true if not specified
44
44
  allowPublicRegistration: true, // Could come from config.authSettings in future
45
- allowSocialLogin: config.oauthProviders?.some(p => p.enabled) ?? false,
45
+ allowFederatedLogin: config.oauthProviders?.some(p => p.enabled) ?? false,
46
46
 
47
47
  // Password reset
48
48
  enablePasswordReset: true, // Could come from config.authSettings in future
@@ -65,7 +65,7 @@ export async function GET() {
65
65
  data: {
66
66
  enabledProviders: [],
67
67
  allowPublicRegistration: true,
68
- allowSocialLogin: false,
68
+ allowFederatedLogin: false,
69
69
  enablePasswordReset: true,
70
70
  require2FA: true,
71
71
  allowed2FAMethods: ['email', 'sms'],