@payez/next-mvp 4.5.6 → 4.7.9
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/auth/credential-login-email-code.d.ts +24 -0
- package/dist/api-handlers/auth/credential-login-email-code.js +83 -0
- package/dist/api-handlers/auth/credential-login.d.ts +41 -0
- package/dist/api-handlers/auth/credential-login.js +858 -0
- package/dist/api-handlers/oauth/resume.d.ts +16 -0
- package/dist/api-handlers/oauth/resume.js +207 -0
- package/dist/auth/better-auth.d.ts +14 -2
- package/dist/auth/better-auth.js +59 -34
- package/dist/auth/idp-oauth.d.ts +106 -0
- package/dist/auth/idp-oauth.js +280 -0
- package/dist/auth/safe-callback.js +15 -2
- package/dist/auth/session-cookie-clear.d.ts +7 -0
- package/dist/auth/session-cookie-clear.js +24 -0
- package/dist/auth/session-reset-link.d.ts +43 -0
- package/dist/auth/session-reset-link.js +144 -0
- package/dist/components/auth/CredentialSignInForm.d.ts +33 -0
- package/dist/components/auth/CredentialSignInForm.js +134 -0
- package/dist/lib/authorize-resume.d.ts +87 -0
- package/dist/lib/authorize-resume.js +190 -0
- package/dist/lib/bearer-fetch.d.ts +17 -0
- package/dist/lib/bearer-fetch.js +32 -0
- package/dist/lib/code-step-copy.d.ts +53 -0
- package/dist/lib/code-step-copy.js +73 -0
- package/dist/lib/credential-sign-in-client.d.ts +59 -0
- package/dist/lib/credential-sign-in-client.js +89 -0
- package/dist/lib/device-id.d.ts +37 -0
- package/dist/lib/device-id.js +70 -0
- package/dist/lib/lock-window.d.ts +29 -0
- package/dist/lib/lock-window.js +53 -0
- package/dist/lib/login-error-message.d.ts +18 -0
- package/dist/lib/login-error-message.js +47 -0
- package/dist/lib/twofa-rejection.d.ts +20 -0
- package/dist/lib/twofa-rejection.js +73 -0
- package/dist/middleware/create-middleware.d.ts +25 -1
- package/dist/middleware/create-middleware.js +75 -27
- package/dist/pages/login/page.js +11 -37
- package/dist/routes/auth/credential-login-email-code.d.ts +6 -0
- package/dist/routes/auth/credential-login-email-code.js +10 -0
- package/dist/routes/auth/credential-login.d.ts +6 -0
- package/dist/routes/auth/credential-login.js +10 -0
- package/dist/routes/auth/session-reset.d.ts +21 -0
- package/dist/routes/auth/session-reset.js +40 -0
- package/dist/routes/oauth/resume.d.ts +11 -0
- package/dist/routes/oauth/resume.js +16 -0
- package/package.json +1102 -1042
- package/src/api-handlers/auth/credential-login-email-code.ts +92 -0
- package/src/api-handlers/auth/credential-login.ts +948 -0
- package/src/api-handlers/oauth/resume.ts +182 -0
- package/src/auth/better-auth.ts +81 -5
- package/src/auth/idp-oauth.ts +310 -0
- package/src/auth/safe-callback.ts +16 -2
- package/src/auth/session-cookie-clear.ts +30 -0
- package/src/auth/session-reset-link.ts +159 -0
- package/src/components/auth/CredentialSignInForm.tsx +240 -0
- package/src/lib/authorize-resume.ts +187 -0
- package/src/lib/bearer-fetch.ts +31 -0
- package/src/lib/code-step-copy.ts +83 -0
- package/src/lib/credential-sign-in-client.ts +101 -0
- package/src/lib/device-id.ts +67 -0
- package/src/lib/lock-window.ts +49 -0
- package/src/lib/login-error-message.ts +41 -0
- package/src/lib/twofa-rejection.ts +91 -0
- package/src/middleware/create-middleware.ts +124 -30
- package/src/pages/login/page.tsx +20 -34
- package/src/routes/auth/credential-login-email-code.ts +6 -0
- package/src/routes/auth/credential-login.ts +6 -0
- package/src/routes/auth/session-reset.ts +37 -0
- package/src/routes/oauth/resume.ts +11 -0
|
@@ -24,6 +24,14 @@ import { getInternalApiUrl } from '../edge/internal-api-url';
|
|
|
24
24
|
import { getSessionCookieName, getSecureSessionCookieName } from '../lib/app-slug';
|
|
25
25
|
import { checkPagePermission, isRBACEnabled } from './rbac-check';
|
|
26
26
|
import { tokenLogId } from '../lib/token-log-id';
|
|
27
|
+
import { expireSessionCookies } from '../auth/session-cookie-clear';
|
|
28
|
+
import {
|
|
29
|
+
DEFAULT_SESSION_RESET_ROUTE,
|
|
30
|
+
boundSessionCookie,
|
|
31
|
+
normaliseResetParams,
|
|
32
|
+
resetSecret,
|
|
33
|
+
signedResetHref,
|
|
34
|
+
} from '../auth/session-reset-link';
|
|
27
35
|
|
|
28
36
|
// =============================================================================
|
|
29
37
|
// TYPES
|
|
@@ -113,6 +121,19 @@ export interface MvpMiddlewareOptions {
|
|
|
113
121
|
bypassPaths?: string[];
|
|
114
122
|
/** Paths exempt from RBAC checks (auth still enforced, just no page-permission check) */
|
|
115
123
|
rbacExemptPaths?: string[];
|
|
124
|
+
/**
|
|
125
|
+
* PAY-2218 - send a page's session-ending redirect through the session-reset ROUTE instead of clearing the
|
|
126
|
+
* cookies in the middleware response. Next strips the router's prefetch headers before middleware runs
|
|
127
|
+
* (15.5.x and 16.x; 16.2.x restores them only with `skipProxyUrlNormalize: true`), so a middleware clear also
|
|
128
|
+
* fires on a router PREFETCH and signs the user out of a page they never opened. The route sees those headers.
|
|
129
|
+
*
|
|
130
|
+
* Requires the app to mount the route: app/api/auth/session-reset/route.ts
|
|
131
|
+
* export { GET } from '@payez/next-mvp/routes/auth/session-reset';
|
|
132
|
+
* `true` uses that default path; a string names another mount point under /api/auth/ (middleware bypasses it).
|
|
133
|
+
* Needs BETTER_AUTH_SECRET (or NEXTAUTH_SECRET) to sign the hand-off; without one the direct clear is kept and
|
|
134
|
+
* an error is logged once. Default: off (the direct clear), because an unmounted route would 404 every sign-out.
|
|
135
|
+
*/
|
|
136
|
+
sessionResetRoute?: boolean | string;
|
|
116
137
|
/**
|
|
117
138
|
* PAY-1882 step 4 - how this app treats a producer that reports the session's
|
|
118
139
|
* revocation status as `'unknown'` (a Vibe read that FAILED: non-OK, timeout,
|
|
@@ -137,6 +158,18 @@ export interface MvpMiddlewareOptions {
|
|
|
137
158
|
* is signed out for not implementing the check).
|
|
138
159
|
*/
|
|
139
160
|
revocationFailMode?: 'closed' | 'open';
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* PAY-2302 cut 1c (BAPert 73585): this app has NO revocation source - for example a development environment
|
|
164
|
+
* provisioned without a vibe client id / HMAC key - and says so EXPLICITLY. Under it a viability answer of
|
|
165
|
+
* `revocationStatus: 'not_configured'` is viable, and a loud warning is logged once at startup.
|
|
166
|
+
*
|
|
167
|
+
* It relaxes ONLY 'not_configured'. 'unknown' (a revocation read that FAILED) and 'revoked' stay closed whatever
|
|
168
|
+
* `revocationFailMode` says, and the default (option absent) is unchanged: 'not_configured' fails closed, because
|
|
169
|
+
* for an app that HAS a vibe client it means a misconfiguration (BAPert 66356). Do not use this to paper over a
|
|
170
|
+
* misconfigured production app; remove it when the environment has a vibe client + HMAC key.
|
|
171
|
+
*/
|
|
172
|
+
noRevocationSource?: boolean;
|
|
140
173
|
}
|
|
141
174
|
|
|
142
175
|
// =============================================================================
|
|
@@ -174,8 +207,13 @@ const defaultLogger: MiddlewareLogger = {
|
|
|
174
207
|
const LOGIN_PAGE = '/account-auth/login';
|
|
175
208
|
const VERIFY_CODE_PAGE = '/account-auth/verify-code';
|
|
176
209
|
|
|
210
|
+
// PAY-2315 (4.7.1): /login is a public alias of the login page. It used to take the 'public: allow' arm and never reached the
|
|
211
|
+
// 'already_authenticated' redirect, so a signed-in user was shown the sign-in form. It is the login page for every arm now.
|
|
212
|
+
// (safe-callback refuses /login as a destination, so this cannot redirect to itself.)
|
|
213
|
+
const LOGIN_ALIAS = '/login';
|
|
214
|
+
|
|
177
215
|
function isLoginPage(pathname: string): boolean {
|
|
178
|
-
return pathname === LOGIN_PAGE;
|
|
216
|
+
return pathname === LOGIN_PAGE || pathname === LOGIN_ALIAS;
|
|
179
217
|
}
|
|
180
218
|
|
|
181
219
|
/**
|
|
@@ -221,26 +259,7 @@ export function isPrefetchRequest(request: NextRequest): boolean {
|
|
|
221
259
|
*/
|
|
222
260
|
function clearSessionCookies(response: NextResponse, request: NextRequest): void {
|
|
223
261
|
if (isPrefetchRequest(request)) return;
|
|
224
|
-
|
|
225
|
-
const secureCookie = getSecureSessionCookieName();
|
|
226
|
-
|
|
227
|
-
// Clear main cookies
|
|
228
|
-
response.cookies.set(sessionCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax' });
|
|
229
|
-
response.cookies.set(secureCookie, '', { path: '/', expires: new Date(0), httpOnly: true, sameSite: 'lax', secure: true });
|
|
230
|
-
|
|
231
|
-
// Clear any chunked cookies (NextAuth chunks large cookies)
|
|
232
|
-
for (const [name] of request.cookies) {
|
|
233
|
-
if (name.startsWith(`${sessionCookie}.`) || name.startsWith(`${secureCookie}.`)) {
|
|
234
|
-
const isSecure = name.startsWith('__Secure-');
|
|
235
|
-
response.cookies.set(name, '', {
|
|
236
|
-
path: '/',
|
|
237
|
-
expires: new Date(0),
|
|
238
|
-
httpOnly: true,
|
|
239
|
-
sameSite: 'lax',
|
|
240
|
-
...(isSecure && { secure: true })
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
}
|
|
262
|
+
expireSessionCookies(response, Array.from(request.cookies, ([name]) => name));
|
|
244
263
|
}
|
|
245
264
|
|
|
246
265
|
/** Create redirect response, optionally clearing cookies */
|
|
@@ -256,6 +275,35 @@ function redirectTo(
|
|
|
256
275
|
return response;
|
|
257
276
|
}
|
|
258
277
|
|
|
278
|
+
/** PAY-2218: where a page's clearing redirect goes when the app has mounted the session-reset route. */
|
|
279
|
+
interface ResetConfig {
|
|
280
|
+
route: string;
|
|
281
|
+
secret: string;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* A redirect that must also END the session. With the reset route configured, a page request is sent through it
|
|
286
|
+
* WITHOUT any Set-Cookie here: the route sees the flight headers this middleware cannot (Next strips them before
|
|
287
|
+
* middleware), answers a prefetch 204 + no-store, and clears on the real navigation. `/api/` requests and apps
|
|
288
|
+
* without the route keep the direct clear exactly as before.
|
|
289
|
+
*/
|
|
290
|
+
async function clearingRedirect(request: NextRequest, location: string, reset?: ResetConfig): Promise<NextResponse> {
|
|
291
|
+
if (!reset || request.nextUrl.pathname.startsWith('/api/')) {
|
|
292
|
+
return redirectTo(request, location, true);
|
|
293
|
+
}
|
|
294
|
+
const target = new URL(location, request.url);
|
|
295
|
+
const params = normaliseResetParams({
|
|
296
|
+
callbackUrl: target.searchParams.get('callbackUrl'),
|
|
297
|
+
reason: target.searchParams.get('reason'),
|
|
298
|
+
error: target.searchParams.get('error'),
|
|
299
|
+
});
|
|
300
|
+
// Bound to THIS request's session cookie: the route clears only when its own request carries the same one.
|
|
301
|
+
const bound = boundSessionCookie((n) => request.cookies.get(n)?.value, getSessionCookieName(), getSecureSessionCookieName());
|
|
302
|
+
const response = NextResponse.redirect(new URL(await signedResetHref(reset.route, params, reset.secret, bound), request.url));
|
|
303
|
+
response.headers.set('cache-control', 'no-store');
|
|
304
|
+
return response;
|
|
305
|
+
}
|
|
306
|
+
|
|
259
307
|
/**
|
|
260
308
|
* Terminal response for a FAILED token refresh.
|
|
261
309
|
*
|
|
@@ -274,12 +322,13 @@ function redirectTo(
|
|
|
274
322
|
* higher would intercept 'refresh_needed' and disable middleware token refresh across
|
|
275
323
|
* the whole API surface (card 340024 C1).
|
|
276
324
|
*/
|
|
277
|
-
function refreshFailureResponse(
|
|
325
|
+
async function refreshFailureResponse(
|
|
278
326
|
request: NextRequest,
|
|
279
327
|
location: string,
|
|
280
328
|
errorCode: string,
|
|
281
|
-
clearCookies = false
|
|
282
|
-
|
|
329
|
+
clearCookies = false,
|
|
330
|
+
reset?: ResetConfig
|
|
331
|
+
): Promise<NextResponse> {
|
|
283
332
|
if (request.nextUrl.pathname.startsWith('/api/')) {
|
|
284
333
|
const response = NextResponse.json({ error: errorCode }, { status: 401 });
|
|
285
334
|
if (clearCookies) {
|
|
@@ -287,7 +336,7 @@ function refreshFailureResponse(
|
|
|
287
336
|
}
|
|
288
337
|
return response;
|
|
289
338
|
}
|
|
290
|
-
return
|
|
339
|
+
return clearCookies ? clearingRedirect(request, location, reset) : redirectTo(request, location);
|
|
291
340
|
}
|
|
292
341
|
|
|
293
342
|
/**
|
|
@@ -497,6 +546,9 @@ function redirect2FA(callbackUrl: string): AuthAction {
|
|
|
497
546
|
// MIDDLEWARE FACTORY
|
|
498
547
|
// =============================================================================
|
|
499
548
|
|
|
549
|
+
/** PAY-2218: the stripped-flight-headers warning is logged once per process, not once per request. */
|
|
550
|
+
let flightHeadersStrippedWarned = false;
|
|
551
|
+
|
|
500
552
|
export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
|
|
501
553
|
// Resolve options with defaults
|
|
502
554
|
const cb = options.circuitBreaker || defaultCircuitBreaker;
|
|
@@ -507,6 +559,30 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
|
|
|
507
559
|
const rbacExemptPaths = options.rbacExemptPaths || [];
|
|
508
560
|
// PAY-1882 step 4: default 'closed' (Jon's option A / BAPert 66316).
|
|
509
561
|
const revocationFailMode = options.revocationFailMode || 'closed';
|
|
562
|
+
// PAY-2302 cut 1c: strictly `=== true`, so a truthy string in a config file cannot switch revocation off.
|
|
563
|
+
const noRevocationSource = options.noRevocationSource === true;
|
|
564
|
+
if (noRevocationSource) {
|
|
565
|
+
log.warn(
|
|
566
|
+
'[next-mvp] noRevocationSource is ON: sessions of this app CANNOT be revoked server-side (no vibe client / HMAC key). ' +
|
|
567
|
+
"revocationStatus 'not_configured' is treated as viable; 'unknown' and 'revoked' still sign the user out. " +
|
|
568
|
+
'Remove this option once the environment has a vibe client id and HMAC key.'
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
const sessionResetRoute =
|
|
572
|
+
options.sessionResetRoute === true ? DEFAULT_SESSION_RESET_ROUTE
|
|
573
|
+
: typeof options.sessionResetRoute === 'string' && options.sessionResetRoute ? options.sessionResetRoute
|
|
574
|
+
: undefined;
|
|
575
|
+
let resetSecretMissingLogged = false;
|
|
576
|
+
const resolveReset = (): ResetConfig | undefined => {
|
|
577
|
+
if (!sessionResetRoute) return undefined;
|
|
578
|
+
const secret = resetSecret();
|
|
579
|
+
if (secret) return { route: sessionResetRoute, secret };
|
|
580
|
+
if (!resetSecretMissingLogged) {
|
|
581
|
+
resetSecretMissingLogged = true;
|
|
582
|
+
log.error('sessionResetRoute is set but no BETTER_AUTH_SECRET/NEXTAUTH_SECRET is available to sign the hand-off; clearing in middleware instead', { sessionResetRoute });
|
|
583
|
+
}
|
|
584
|
+
return undefined;
|
|
585
|
+
};
|
|
510
586
|
|
|
511
587
|
return async function middleware(request: NextRequest): Promise<NextResponse> {
|
|
512
588
|
const { pathname, searchParams } = request.nextUrl;
|
|
@@ -529,6 +605,13 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
|
|
|
529
605
|
}
|
|
530
606
|
}
|
|
531
607
|
|
|
608
|
+
// PAY-2218: a router request (it carries `next-url`) that arrives WITHOUT `rsc` had its flight headers stripped
|
|
609
|
+
// by Next before middleware ran, so isPrefetchRequest() cannot see a router prefetch on this app. Say so once.
|
|
610
|
+
if (!sessionResetRoute && !flightHeadersStrippedWarned && request.headers.has('next-url') && !request.headers.has('rsc')) {
|
|
611
|
+
flightHeadersStrippedWarned = true;
|
|
612
|
+
log.warn('Next strips router prefetch headers before middleware on this app, so a session-ending redirect can fire on a prefetch. Mount @payez/next-mvp/routes/auth/session-reset and set sessionResetRoute (PAY-2218).', { pathname });
|
|
613
|
+
}
|
|
614
|
+
|
|
532
615
|
const isPublic = isUnauthenticatedRoute(pathname);
|
|
533
616
|
const isLogin = isLoginPage(pathname);
|
|
534
617
|
|
|
@@ -547,7 +630,8 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
|
|
|
547
630
|
request,
|
|
548
631
|
viabilityEndpoint,
|
|
549
632
|
log,
|
|
550
|
-
revocationFailMode
|
|
633
|
+
revocationFailMode,
|
|
634
|
+
noRevocationSource
|
|
551
635
|
);
|
|
552
636
|
|
|
553
637
|
// --- Stale session (cookie exists but session doesn't): OBSERVE ONLY, DO NOT DECIDE ---
|
|
@@ -608,6 +692,7 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
|
|
|
608
692
|
logger: log,
|
|
609
693
|
refreshEndpoint,
|
|
610
694
|
rbacExemptPaths,
|
|
695
|
+
reset: resolveReset(),
|
|
611
696
|
onRefreshSuccess: options.onRefreshSuccess,
|
|
612
697
|
onRefreshFailure: options.onRefreshFailure,
|
|
613
698
|
});
|
|
@@ -629,11 +714,14 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
|
|
|
629
714
|
export function decideForceInvalid(
|
|
630
715
|
data: { revocationStatus?: unknown; forceInvalid?: unknown; revoked?: unknown },
|
|
631
716
|
revocationFailMode: 'closed' | 'open',
|
|
717
|
+
noRevocationSource: boolean = false,
|
|
632
718
|
): boolean {
|
|
633
719
|
const status = data.revocationStatus;
|
|
634
720
|
if (typeof status === 'string') {
|
|
635
721
|
if (status === 'revoked') return true;
|
|
636
722
|
if (status === 'active') return false;
|
|
723
|
+
// PAY-2302 cut 1c: an app that declared it has no revocation source. ONLY the exact 'not_configured' string.
|
|
724
|
+
if (status === 'not_configured' && noRevocationSource === true) return false;
|
|
637
725
|
// S1 (NightHawk 66409): ANY other string - 'unknown', 'not_configured', a
|
|
638
726
|
// typo like 'Revoked', 'error', or '' - is treated as 'unknown' (fail mode
|
|
639
727
|
// applies), NEVER as 'active'. Returning false here would let the first
|
|
@@ -662,7 +750,8 @@ async function checkViability(
|
|
|
662
750
|
request: NextRequest,
|
|
663
751
|
endpoint: string,
|
|
664
752
|
log: MiddlewareLogger,
|
|
665
|
-
revocationFailMode: 'closed' | 'open'
|
|
753
|
+
revocationFailMode: 'closed' | 'open',
|
|
754
|
+
noRevocationSource: boolean = false
|
|
666
755
|
): Promise<{
|
|
667
756
|
sessionStatus: SessionStatus;
|
|
668
757
|
sessionPointer: SessionPointer;
|
|
@@ -740,7 +829,7 @@ async function checkViability(
|
|
|
740
829
|
// revocations status, decide from it + failMode and ignore the folded
|
|
741
830
|
// booleans for unknown/not_configured. The booleans are read ONLY when
|
|
742
831
|
// revocationStatus is ABSENT (idealresume.online's older boolean route).
|
|
743
|
-
sessionStatus.forceInvalid = decideForceInvalid(data, revocationFailMode);
|
|
832
|
+
sessionStatus.forceInvalid = decideForceInvalid(data, revocationFailMode, noRevocationSource);
|
|
744
833
|
// PAY-2216: a STALE session - the cookie resolved to a token, but no store holds the session - used to set
|
|
745
834
|
// pointer.exists=false, so makeAuthDecision took no_session (login, cookie NOT cleared) and its stale_session
|
|
746
835
|
// arm (clearCookies) was unreachable: a dead cookie lingered and re-ran viability on every request.
|
|
@@ -778,6 +867,8 @@ interface ExecuteOptions {
|
|
|
778
867
|
logger: MiddlewareLogger;
|
|
779
868
|
refreshEndpoint: string;
|
|
780
869
|
rbacExemptPaths: string[];
|
|
870
|
+
/** PAY-2218: set when the app mounted the session-reset route AND a signing secret exists. */
|
|
871
|
+
reset?: ResetConfig;
|
|
781
872
|
onRefreshSuccess?: () => void;
|
|
782
873
|
onRefreshFailure?: (status: number, isNetworkError: boolean) => void;
|
|
783
874
|
}
|
|
@@ -798,7 +889,9 @@ async function executeDecision(
|
|
|
798
889
|
return handleAllow(request, pathname, sessionPointer, sessionStatus, opts.rbacExemptPaths);
|
|
799
890
|
|
|
800
891
|
case 'redirect':
|
|
801
|
-
return
|
|
892
|
+
return decision.clearCookies
|
|
893
|
+
? clearingRedirect(request, decision.location, opts.reset)
|
|
894
|
+
: redirectTo(request, decision.location);
|
|
802
895
|
|
|
803
896
|
case 'service_error':
|
|
804
897
|
return serviceUnavailableResponse(request);
|
|
@@ -943,7 +1036,8 @@ async function handleRefresh(
|
|
|
943
1036
|
request,
|
|
944
1037
|
`${LOGIN_PAGE}?callbackUrl=${encodeURIComponent(safeCallback)}&error=${errorParam}`,
|
|
945
1038
|
errorParam,
|
|
946
|
-
isPermanentFailure
|
|
1039
|
+
isPermanentFailure,
|
|
1040
|
+
opts.reset
|
|
947
1041
|
);
|
|
948
1042
|
} catch (error: any) {
|
|
949
1043
|
const isNetwork = cb.isNetworkError(error);
|
package/src/pages/login/page.tsx
CHANGED
|
@@ -29,6 +29,7 @@ import { Suspense } from 'react';
|
|
|
29
29
|
import ReservedStatusBox from '../../components/reserved/ReservedStatusBox';
|
|
30
30
|
import ReservedRecoveryWarning from '../../components/reserved/ReservedRecoveryWarning';
|
|
31
31
|
import { useBranding, useColors, useLayout } from '../../theme/useTheme';
|
|
32
|
+
import { friendlyLoginError, oauthFailureMessage } from '../../lib/login-error-message';
|
|
32
33
|
|
|
33
34
|
function LoginForm({ altAuthSlot }: { altAuthSlot?: React.ReactNode }) {
|
|
34
35
|
const searchParams = useSearchParams();
|
|
@@ -117,46 +118,20 @@ function LoginForm({ altAuthSlot }: { altAuthSlot?: React.ReactNode }) {
|
|
|
117
118
|
// Atomic state management - only ONE can be true at a time
|
|
118
119
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
119
120
|
const [loginSuccess, setLoginSuccess] = useState(false);
|
|
120
|
-
|
|
121
|
+
// undefined = the user has not acted yet (show what the URL says); null/string = an explicit state set by a handler below.
|
|
122
|
+
const [loginError, setLoginError] = useState<string | null | undefined>(undefined);
|
|
121
123
|
const [loading, setLoading] = useState(false);
|
|
122
124
|
const [showRecoveryOptions, setShowRecoveryOptions] = useState(false);
|
|
123
125
|
|
|
124
126
|
// Force show form after timeout if stuck in loading
|
|
125
127
|
const [forceShowForm, setForceShowForm] = useState(false);
|
|
126
128
|
|
|
127
|
-
//
|
|
129
|
+
// PAY-2319 (4.7.2): what the URL says, derived at render (no effect) so it is shown on the FIRST paint and in a static render.
|
|
130
|
+
// 4.7.1 mapped these in effects that only set loginError, which was never rendered. Unknown codes are NOT echoed (see lib/login-error-message).
|
|
131
|
+
const urlMessage = oauthFailureMessage(oauthError) ?? friendlyLoginError(urlError);
|
|
132
|
+
const shownError: string | null = loginError !== undefined ? loginError : urlMessage;
|
|
128
133
|
useEffect(() => {
|
|
129
|
-
if (
|
|
130
|
-
const name = oauthError.charAt(0).toUpperCase() + oauthError.slice(1);
|
|
131
|
-
setLoginError(`${name} sign-in did not complete. Please try again.`);
|
|
132
|
-
}
|
|
133
|
-
}, [oauthError]);
|
|
134
|
-
|
|
135
|
-
// Handle URL errors with user-friendly messages
|
|
136
|
-
useEffect(() => {
|
|
137
|
-
if (urlError) {
|
|
138
|
-
let friendlyError: string | null = urlError;
|
|
139
|
-
|
|
140
|
-
if (urlError === 'SessionExpired') {
|
|
141
|
-
// Session expiration is normal - don't show as error
|
|
142
|
-
console.log('[LOGIN] SessionExpired detected - normal behavior');
|
|
143
|
-
friendlyError = null;
|
|
144
|
-
} else if (urlError === 'TwoFactorTimeout') {
|
|
145
|
-
// PAY-884: the sign-in expired while the verification code was outstanding. Unlike
|
|
146
|
-
// SessionExpired this is NOT silent - the user was mid-2FA and must know why they are here.
|
|
147
|
-
friendlyError = 'Your verification step timed out before the code was confirmed. Please sign in again.';
|
|
148
|
-
} else if (urlError === 'ServiceUnavailable') {
|
|
149
|
-
friendlyError = 'Authentication service is temporarily unavailable. Please try again in a few minutes.';
|
|
150
|
-
} else if (urlError.startsWith("Unexpected token")) {
|
|
151
|
-
friendlyError = 'An authentication error occurred. Please try signing in again.';
|
|
152
|
-
} else if (urlError.includes('not valid JSON')) {
|
|
153
|
-
friendlyError = 'An authentication error occurred. Please try signing in again.';
|
|
154
|
-
} else if (urlError === 'CredentialsSignin') {
|
|
155
|
-
friendlyError = 'Invalid email or password. Please try again.';
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
setLoginError(friendlyError);
|
|
159
|
-
}
|
|
134
|
+
if (urlError === 'SessionExpired') console.log('[LOGIN] SessionExpired detected - normal behavior');
|
|
160
135
|
}, [urlError]);
|
|
161
136
|
|
|
162
137
|
// Timeout to prevent infinite loading states
|
|
@@ -186,7 +161,7 @@ function LoginForm({ altAuthSlot }: { altAuthSlot?: React.ReactNode }) {
|
|
|
186
161
|
// package never configures emailAndPassword. See the note at the render site.
|
|
187
162
|
|
|
188
163
|
// Show loading spinner for initial loads
|
|
189
|
-
if (!forceShowForm && !
|
|
164
|
+
if (!forceShowForm && !shownError && (loading || (status === 'loading' && !session))) {
|
|
190
165
|
return (
|
|
191
166
|
<div className={`flex flex-col items-center justify-center min-h-screen ${colors.background}`}>
|
|
192
167
|
<svg className="animate-spin h-6 w-6" style={{ color: buttonColor }} viewBox="0 0 24 24" fill="none">
|
|
@@ -246,6 +221,17 @@ function LoginForm({ altAuthSlot }: { altAuthSlot?: React.ReactNode }) {
|
|
|
246
221
|
</p>
|
|
247
222
|
</div>
|
|
248
223
|
|
|
224
|
+
{/* PAY-2319 (4.7.2): the error sentence. 4.7.1 set loginError but never rendered it. */}
|
|
225
|
+
{shownError && (
|
|
226
|
+
<div
|
|
227
|
+
role="alert"
|
|
228
|
+
data-testid="login-error"
|
|
229
|
+
className="mb-6 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
|
230
|
+
>
|
|
231
|
+
{shownError}
|
|
232
|
+
</div>
|
|
233
|
+
)}
|
|
234
|
+
|
|
249
235
|
{/* Social sign-in — rendered ONLY from the IDP client config's
|
|
250
236
|
enabled providers (see the /api/auth/settings discovery above).
|
|
251
237
|
Above the form, divider idiom per the package's ModeAwareLoginPage. */}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2302 cut 1: ask the IdP to email a code when the authenticator lane failed on our side.
|
|
3
|
+
* The handler lives in api-handlers/auth/credential-login-email-code.ts (moved from VibeID-Customer-Portal src/app/api/auth/admin-login/email-code/route.ts). A consuming app's route file
|
|
4
|
+
* re-exports POST and writes `export const runtime = 'nodejs'` literally.
|
|
5
|
+
*/
|
|
6
|
+
export { POST } from '../../api-handlers/auth/credential-login-email-code';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2302 cut 1: password sign-in route (IdP ExternalAuth/login, session written via lib/session-store, 2FA-outstanding handling).
|
|
3
|
+
* The handler lives in api-handlers/auth/credential-login.ts (moved from VibeID-Customer-Portal src/app/api/auth/admin-login/route.ts). A consuming app's route file
|
|
4
|
+
* re-exports POST and writes `export const runtime = 'nodejs'` literally.
|
|
5
|
+
*/
|
|
6
|
+
export { POST } from '../../api-handlers/auth/credential-login';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2218 PR 2: the session-reset route. Mount it at app/api/auth/session-reset/route.ts:
|
|
3
|
+
*
|
|
4
|
+
* export { GET } from '@payez/next-mvp/routes/auth/session-reset';
|
|
5
|
+
*
|
|
6
|
+
* and turn it on with createMvpMiddleware({ sessionResetRoute: true }). The middleware then sends a page's
|
|
7
|
+
* session-ending redirect (stale session, force-invalidated, pre-2FA timeout, refresh 401/403) here instead of
|
|
8
|
+
* clearing the cookies itself. See src/auth/session-reset-link.ts for the measurements behind each rule.
|
|
9
|
+
*
|
|
10
|
+
* - Router PREFETCH (the route sees `next-router-prefetch`, which Next strips before middleware): 204 + no-store,
|
|
11
|
+
* no redirect, no Set-Cookie. A redirect here would be cached by the 15.5.x router and reused by the click, so
|
|
12
|
+
* the real navigation would never come back to clear.
|
|
13
|
+
* - Real navigation with a valid signed hand-off: expire the session cookies and 307 to the login page.
|
|
14
|
+
* - Anything unsigned, tampered, expired, or bound to a DIFFERENT session than this request's cookie: 307 to the
|
|
15
|
+
* login page and touch NO cookie (nobody can link a signed-in user here to log them out; a second use is a no-op).
|
|
16
|
+
*
|
|
17
|
+
* The login URL is always rebuilt from allowlisted parts; the route never redirects to a URL it was given.
|
|
18
|
+
*/
|
|
19
|
+
import { NextRequest, NextResponse } from 'next/server';
|
|
20
|
+
import { isPrefetchRequest } from '../../middleware/create-middleware';
|
|
21
|
+
import { expireSessionCookies } from '../../auth/session-cookie-clear';
|
|
22
|
+
import { getSessionCookieName, getSecureSessionCookieName } from '../../lib/app-slug';
|
|
23
|
+
import { boundSessionCookie, loginLocation, readResetRequest, resetSecret } from '../../auth/session-reset-link';
|
|
24
|
+
|
|
25
|
+
export const dynamic = 'force-dynamic';
|
|
26
|
+
|
|
27
|
+
export async function GET(request: NextRequest): Promise<NextResponse> {
|
|
28
|
+
if (isPrefetchRequest(request)) {
|
|
29
|
+
return new NextResponse(null, { status: 204, headers: { 'cache-control': 'no-store' } });
|
|
30
|
+
}
|
|
31
|
+
const bound = boundSessionCookie((n) => request.cookies.get(n)?.value, getSessionCookieName(), getSecureSessionCookieName());
|
|
32
|
+
const { params, signed } = await readResetRequest(request.nextUrl.searchParams, resetSecret(), bound);
|
|
33
|
+
const response = NextResponse.redirect(new URL(loginLocation(params), request.url), 307);
|
|
34
|
+
response.headers.set('cache-control', 'no-store');
|
|
35
|
+
if (signed) expireSessionCookies(response, Array.from(request.cookies, ([name]) => name));
|
|
36
|
+
return response;
|
|
37
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2302 cut 2: post-2FA OAuth authorize resume route. The handler lives in api-handlers/oauth/resume.ts
|
|
3
|
+
* (moved from VibeID-Customer-Portal src/app/api/oauth/resume/route.ts). A consuming app's route file re-exports GET
|
|
4
|
+
* and writes `export const runtime = 'nodejs'` literally.
|
|
5
|
+
*
|
|
6
|
+
* 4.7.3: `createOAuthResumeHandler({ refusalLocation })` and `DEFAULT_REFUSAL_LOCATION` are re-exported HERE because a consumer can only
|
|
7
|
+
* import what `package.json` `exports` lists, and this route module is the entry. An app whose sign-in page is not
|
|
8
|
+
* /account-auth/login (the portal uses /sign-in) writes `export const GET = createOAuthResumeHandler({ refusalLocation: '/sign-in?error=AUTHORIZE_RESUME_REFUSED' });`.
|
|
9
|
+
*/
|
|
10
|
+
export { GET, createOAuthResumeHandler, DEFAULT_REFUSAL_LOCATION } from '../../api-handlers/oauth/resume';
|
|
11
|
+
export type { OAuthResumeOptions, OAuthResumeDeps } from '../../api-handlers/oauth/resume';
|