@payez/next-mvp 4.5.7 → 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.
Files changed (59) hide show
  1. package/dist/api-handlers/auth/credential-login-email-code.d.ts +24 -0
  2. package/dist/api-handlers/auth/credential-login-email-code.js +83 -0
  3. package/dist/api-handlers/auth/credential-login.d.ts +41 -0
  4. package/dist/api-handlers/auth/credential-login.js +858 -0
  5. package/dist/api-handlers/oauth/resume.d.ts +16 -0
  6. package/dist/api-handlers/oauth/resume.js +207 -0
  7. package/dist/auth/better-auth.d.ts +14 -2
  8. package/dist/auth/better-auth.js +59 -34
  9. package/dist/auth/idp-oauth.d.ts +106 -0
  10. package/dist/auth/idp-oauth.js +280 -0
  11. package/dist/auth/safe-callback.js +10 -2
  12. package/dist/components/auth/CredentialSignInForm.d.ts +33 -0
  13. package/dist/components/auth/CredentialSignInForm.js +134 -0
  14. package/dist/lib/authorize-resume.d.ts +87 -0
  15. package/dist/lib/authorize-resume.js +190 -0
  16. package/dist/lib/bearer-fetch.d.ts +17 -0
  17. package/dist/lib/bearer-fetch.js +32 -0
  18. package/dist/lib/code-step-copy.d.ts +53 -0
  19. package/dist/lib/code-step-copy.js +73 -0
  20. package/dist/lib/credential-sign-in-client.d.ts +59 -0
  21. package/dist/lib/credential-sign-in-client.js +89 -0
  22. package/dist/lib/device-id.d.ts +37 -0
  23. package/dist/lib/device-id.js +70 -0
  24. package/dist/lib/lock-window.d.ts +29 -0
  25. package/dist/lib/lock-window.js +53 -0
  26. package/dist/lib/login-error-message.d.ts +18 -0
  27. package/dist/lib/login-error-message.js +47 -0
  28. package/dist/lib/twofa-rejection.d.ts +20 -0
  29. package/dist/lib/twofa-rejection.js +73 -0
  30. package/dist/middleware/create-middleware.d.ts +12 -1
  31. package/dist/middleware/create-middleware.js +19 -5
  32. package/dist/pages/login/page.js +11 -37
  33. package/dist/routes/auth/credential-login-email-code.d.ts +6 -0
  34. package/dist/routes/auth/credential-login-email-code.js +10 -0
  35. package/dist/routes/auth/credential-login.d.ts +6 -0
  36. package/dist/routes/auth/credential-login.js +10 -0
  37. package/dist/routes/oauth/resume.d.ts +11 -0
  38. package/dist/routes/oauth/resume.js +16 -0
  39. package/package.json +1102 -1047
  40. package/src/api-handlers/auth/credential-login-email-code.ts +92 -0
  41. package/src/api-handlers/auth/credential-login.ts +948 -0
  42. package/src/api-handlers/oauth/resume.ts +182 -0
  43. package/src/auth/better-auth.ts +81 -5
  44. package/src/auth/idp-oauth.ts +310 -0
  45. package/src/auth/safe-callback.ts +11 -2
  46. package/src/components/auth/CredentialSignInForm.tsx +240 -0
  47. package/src/lib/authorize-resume.ts +187 -0
  48. package/src/lib/bearer-fetch.ts +31 -0
  49. package/src/lib/code-step-copy.ts +83 -0
  50. package/src/lib/credential-sign-in-client.ts +101 -0
  51. package/src/lib/device-id.ts +67 -0
  52. package/src/lib/lock-window.ts +49 -0
  53. package/src/lib/login-error-message.ts +41 -0
  54. package/src/lib/twofa-rejection.ts +91 -0
  55. package/src/middleware/create-middleware.ts +35 -4
  56. package/src/pages/login/page.tsx +20 -34
  57. package/src/routes/auth/credential-login-email-code.ts +6 -0
  58. package/src/routes/auth/credential-login.ts +6 -0
  59. package/src/routes/oauth/resume.ts +11 -0
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Per-browser device identity — card 240566 (QAPert flag 2 on the 9c7a815 review).
3
+ *
4
+ * BEFORE: /api/auth/admin-login forwarded ONE hardcoded device-id cookie —
5
+ * `payez-PayEz-6c8201c35c1b44c9b2e823b36b95a718` — for every caller on the
6
+ * PUBLIC /sign-in password path. To the IDP's rate limiter and device
7
+ * fingerprinting, every portal user was literally the same device. Two
8
+ * consequences, both measured-by-inspection rather than hypothetical:
9
+ * 1. SHARED-FATE LOCKOUT — one attacker's failed attempts consume the
10
+ * throttle budget for every legitimate user at once.
11
+ * 2. Per-device risk signals are meaningless: "new device" and "trusted
12
+ * device" cannot distinguish anybody from anybody.
13
+ *
14
+ * The id is a routing/telemetry key, NOT a credential — the IDP must never
15
+ * grant anything on the strength of it, and nothing here assumes otherwise.
16
+ * It is client-supplied and therefore client-forgeable; that is inherent to
17
+ * device-id throttling and is why it supplements, never replaces, the
18
+ * identifier- and IP-scoped limits on the IDP side.
19
+ *
20
+ * Shape is fixed by what the IDP already accepts from
21
+ * createLoginHandler: `payez-PayEz-<32 lowercase hex>`.
22
+ */
23
+
24
+ export const DEVICE_ID_HEADER = 'X-Device-Id';
25
+ export const DEVICE_ID_PATTERN = /^payez-PayEz-[0-9a-f]{32}$/;
26
+ const STORAGE_KEY = 'payez.device-id';
27
+
28
+ /** True for a well-formed device id. Used on BOTH sides of the wire. */
29
+ export function isValidDeviceId(value: string | null | undefined): value is string {
30
+ return typeof value === 'string' && DEVICE_ID_PATTERN.test(value);
31
+ }
32
+
33
+ function mint(): string {
34
+ const bytes = new Uint8Array(16);
35
+ crypto.getRandomValues(bytes);
36
+ const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
37
+ return `payez-PayEz-${hex}`;
38
+ }
39
+
40
+ /**
41
+ * The stable per-browser device id, minted once and persisted.
42
+ *
43
+ * Browser-only. Persistence is best-effort: private windows, disabled site
44
+ * data and storage-quota failures all throw on access, so every read and
45
+ * write is guarded. A browser that cannot persist still gets a VALID id for
46
+ * this call — it simply looks like a new device each time, which is the
47
+ * honest answer for a client that refuses to be remembered, and is still
48
+ * strictly better than every user sharing one identity.
49
+ */
50
+ export function getDeviceId(): string {
51
+ if (typeof window === 'undefined') return mint();
52
+
53
+ try {
54
+ const existing = window.localStorage.getItem(STORAGE_KEY);
55
+ if (isValidDeviceId(existing)) return existing;
56
+ } catch {
57
+ return mint();
58
+ }
59
+
60
+ const minted = mint();
61
+ try {
62
+ window.localStorage.setItem(STORAGE_KEY, minted);
63
+ } catch {
64
+ /* not persistable — the minted id is still returned and used for this call */
65
+ }
66
+ return minted;
67
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * PAY-1608: a 2FA lock's window, stated as the IdP enforces it. Never a hard-coded "15 minutes".
3
+ *
4
+ * Core answers every 2FA lock with 429 code "locked" plus Retry-After: MfaController.SecondFactorLocked sends the
5
+ * full lockout (900), and VerifyTotp sends what is LEFT of the lock. The portal used to hard-code "locked for 15
6
+ * minutes" in three places (verify-code-copy.ts, twofa-rejection.ts, and the next-mvp BFF), which was true only
7
+ * while every lock was exactly 15 minutes and the user had just tripped it.
8
+ *
9
+ * The window arrives in one of two ways:
10
+ * - Door A (verify-code): next-mvp >= 4.5.2 relays it in the BFF body as `retryAfterSeconds` (a number).
11
+ * - Door B (admin-login): this route reads the IdP's Retry-After header itself.
12
+ * With no window, the sentence states NO number rather than a guessed one.
13
+ *
14
+ * Dependency-free on purpose: the verify-code page (client) and the admin-login route (server) both use it, and
15
+ * the chain gate executes it directly.
16
+ */
17
+
18
+ /** A positive whole number of seconds from the BFF body, or undefined. Anything else - a string, 0, NaN - is dropped. */
19
+ export function lockSecondsFromBody(value: unknown): number | undefined {
20
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.ceil(value) : undefined;
21
+ }
22
+
23
+ /** A Retry-After header as whole seconds. ONE implementation: the package's lib/retry-after (the portal copy was the same rule). */
24
+ export { parseRetryAfterSeconds } from './retry-after';
25
+
26
+ /**
27
+ * The window in words, rounded UP so the user is never told a shorter wait than the IdP enforces:
28
+ * 900 -> "15 minutes", 61 -> "2 minutes", 60 -> "1 minute", 45 -> "45 seconds", 7200 -> "2 hours".
29
+ */
30
+ export function formatLockWindow(seconds: number | undefined): string | undefined {
31
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) return undefined;
32
+ const plural = (n: number, unit: string) => `${n} ${unit}${n === 1 ? '' : 's'}`;
33
+ if (seconds < 60) return plural(Math.ceil(seconds), 'second');
34
+ const minutes = Math.ceil(seconds / 60);
35
+ if (minutes < 120) return plural(minutes, 'minute');
36
+ return plural(Math.ceil(minutes / 60), 'hour');
37
+ }
38
+
39
+ /** The sentence for a lock whose window was NOT sent. It says even a correct code is refused, and states no number. */
40
+ export const LOCKED_NO_WINDOW =
41
+ 'Too many incorrect codes. Verification is locked for now - even a correct code is refused until the lock ends. Wait before entering another code.';
42
+
43
+ /** The locked sentence: the IdP's real window when it sent one, otherwise LOCKED_NO_WINDOW. */
44
+ export function lockedSentence(seconds?: number): string {
45
+ const window = formatLockWindow(seconds);
46
+ return window
47
+ ? `Too many incorrect codes. Verification is locked for ${window} - wait before entering another code.`
48
+ : LOCKED_NO_WINDOW;
49
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * PAY-2319 (4.7.2): what the login page SAYS for an `?error=` / `?oauth_error=` code, as pure functions so a test can
3
+ * execute them (the page is a client component and effects do not run in a static render).
4
+ *
5
+ * 4.7.1 mapped these codes in an effect that called setLoginError, but the page never RENDERED loginError (it only fed the
6
+ * loading gate), so no sentence was ever shown (NightHawk's walk, 73801, W1). Now that the text is displayed, a raw code from
7
+ * the URL must NOT be echoed: `/account-auth/login?error=<anything an attacker types>` would otherwise print attacker-chosen
8
+ * text on the login page (content spoofing / phishing). Known codes get their sentence; anything else gets one generic
9
+ * sentence; nothing from the URL is ever shown verbatim.
10
+ */
11
+
12
+ export const GENERIC_LOGIN_ERROR = 'We could not sign you in. Please try again.';
13
+
14
+ const KNOWN: Record<string, string> = {
15
+ TwoFactorTimeout: 'Your verification step timed out before the code was confirmed. Please sign in again.',
16
+ AUTHORIZE_RESUME_REFUSED: 'That sign-in request could not be continued. Please sign in again.',
17
+ ServiceUnavailable: 'Authentication service is temporarily unavailable. Please try again in a few minutes.',
18
+ CredentialsSignin: 'Invalid email or password. Please try again.',
19
+ };
20
+
21
+ /**
22
+ * The sentence for `?error=<code>`, or null when nothing should be shown.
23
+ * SessionExpired is a normal event (not an error) and shows nothing; an absent/empty code shows nothing.
24
+ */
25
+ export function friendlyLoginError(code: string | null | undefined): string | null {
26
+ if (typeof code !== 'string' || code === '') return null;
27
+ if (code === 'SessionExpired') return null;
28
+ if (Object.prototype.hasOwnProperty.call(KNOWN, code)) return KNOWN[code];
29
+ // The old raw-JSON parse failures the middleware/proxy could bounce here:
30
+ if (code.startsWith('Unexpected token') || code.includes('not valid JSON')) {
31
+ return 'An authentication error occurred. Please try signing in again.';
32
+ }
33
+ return GENERIC_LOGIN_ERROR;
34
+ }
35
+
36
+ /** `?oauth_error=<provider>`: only a plain provider-like slug is echoed (capitalised); anything else is the generic sentence. */
37
+ export function oauthFailureMessage(provider: string | null | undefined): string | null {
38
+ if (typeof provider !== 'string' || provider === '') return null;
39
+ if (!/^[a-z][a-z0-9_-]{0,31}$/i.test(provider)) return GENERIC_LOGIN_ERROR;
40
+ return `${provider.charAt(0).toUpperCase()}${provider.slice(1)} sign-in did not complete. Please try again.`;
41
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Door B (/api/auth/admin-login) twofa verify: what to tell the user when every lane refused.
3
+ *
4
+ * Classification is by the MOST BLOCKING outcome across lanes (268121 ruling), in this order:
5
+ * 429 from the IdP, or any lane answering code `locked` -> 429 lockout (PAY-903)
6
+ * any 5xx, or a lane answering code server_error / service_unavailable (PAY-1589) -> 502 "our side, not your code"
7
+ * otherwise -> 400 wrong / expired code
8
+ *
9
+ * PAY-903: MfaController.VerifyTotp returns 400 {message, code:"locked"} for a 15-minute lockout
10
+ * (MfaTotpService ErrorCode "locked"). Status-only classification read that as "wrong code, try again" -
11
+ * coaching a locked-out user to spend attempts. The body is inspected for EVERY lane, because with lane
12
+ * order [totp, email] the last response is the email lane's and never carries the TOTP lockout.
13
+ * Disclosing the lockout here is safe: this step is post-password (the caller already proved the account).
14
+ *
15
+ * PAY-1608: the lockout states the LOCKED LANE's own Retry-After (Core sends one on every 2FA lock; VerifyTotp sends
16
+ * what is LEFT of it). It used to hard-code 15 minutes / 900 s. With no usable header, no number is stated and
17
+ * `retryAfter` is omitted rather than invented.
18
+ */
19
+ import { lockedSentence, parseRetryAfterSeconds } from './lock-window';
20
+
21
+ export interface TwofaLaneResult {
22
+ status: number;
23
+ body: string;
24
+ /** PAY-2284: which lane this answer came from, so a fault in the TOTP/SMS lane can offer the email lane (never offered when the EMAIL lane is the one that faulted). */
25
+ lane?: 'totp' | 'sms' | 'email';
26
+ /** PAY-1608: this lane's Retry-After header, as received. */
27
+ retryAfter?: string | null;
28
+ }
29
+
30
+ export interface TwofaRejection {
31
+ status: 400 | 429 | 502;
32
+ error: string;
33
+ retryAfter?: number;
34
+ /**
35
+ * PAY-2284: true when the authenticator (or text) lane failed on OUR side and the emailed-code lane has not faulted. The sign-in
36
+ * card then shows a real "Email me a code instead" action. Before this, the copy said "use another sign-in method" and the screen
37
+ * offered none, and a TOTP holder - for whom the door sends NOTHING at sign-in - was stuck (Jon, 12 Oct, dev-93 key version 57).
38
+ */
39
+ offerEmailCode?: true;
40
+ }
41
+
42
+ /** Every code the IdP body carries: flat {code}, envelope {error:{code}}, or {error:{details:{code}}}. */
43
+ function laneCodes(body: string): string[] {
44
+ try {
45
+ const j = JSON.parse(body) as Record<string, unknown> | null;
46
+ if (!j || typeof j !== 'object') return [];
47
+ const err = (j.error && typeof j.error === 'object' ? j.error : null) as Record<string, unknown> | null;
48
+ const details = (err?.details && typeof err.details === 'object' ? err.details : null) as Record<string, unknown> | null;
49
+ return [j.code, err?.code, details?.code].filter((c): c is string => typeof c === 'string').map((c) => c.toLowerCase());
50
+ } catch {
51
+ return [];
52
+ }
53
+ }
54
+
55
+ export function classifyTwofaRejection(lanes: TwofaLaneResult[], retryAfterHeader?: string | null): TwofaRejection {
56
+ const lockedLane = lanes.find((l) => laneCodes(l.body).includes('locked'));
57
+ if (lockedLane) {
58
+ const secs = parseRetryAfterSeconds(lockedLane.retryAfter);
59
+ return { status: 429, error: lockedSentence(secs), ...(secs ? { retryAfter: secs } : {}) };
60
+ }
61
+ if (lanes.some((l) => l.status === 429)) {
62
+ const parsed = retryAfterHeader ? parseInt(retryAfterHeader, 10) : NaN;
63
+ return {
64
+ status: 429,
65
+ error: 'Too many attempts. Your code is still valid - wait before trying again.',
66
+ retryAfter: Number.isFinite(parsed) && parsed > 0 ? parsed : 60,
67
+ };
68
+ }
69
+ // PAY-1589: an IdP-side fault that arrives as 400 + code (TOTP secret cannot be decrypted -> server_error;
70
+ // replay store down -> service_unavailable). It is not the user's code and does not count toward the lockout,
71
+ // so calling it "not right" sends them round a loop that cannot succeed. Email may still work, so say so.
72
+ const faulted = (l: TwofaLaneResult) => laneCodes(l.body).some((c) => c === 'server_error' || c === 'service_unavailable');
73
+ if (lanes.some(faulted)) {
74
+ const emailLaneFaulted = lanes.some((l) => l.lane === 'email' && (faulted(l) || l.status >= 500));
75
+ const offer = !emailLaneFaulted && lanes.some((l) => faulted(l) && (l.lane === 'totp' || l.lane === 'sms'));
76
+ return {
77
+ status: 502,
78
+ error: offer
79
+ ? 'We could not check your code just now - this is a problem on our side, not with your code. You can have us email you a code instead.'
80
+ : 'We could not check your code just now - this is a problem on our side, not with your code. Try again shortly.',
81
+ ...(offer ? { offerEmailCode: true as const } : {}),
82
+ };
83
+ }
84
+ if (lanes.some((l) => l.status >= 500)) {
85
+ return {
86
+ status: 502,
87
+ error: 'We could not check your code just now - this is a problem on our side, not with your code. Try again shortly.',
88
+ };
89
+ }
90
+ return { status: 400, error: 'That code is not right or has expired. Try again.' };
91
+ }
@@ -158,6 +158,18 @@ export interface MvpMiddlewareOptions {
158
158
  * is signed out for not implementing the check).
159
159
  */
160
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;
161
173
  }
162
174
 
163
175
  // =============================================================================
@@ -195,8 +207,13 @@ const defaultLogger: MiddlewareLogger = {
195
207
  const LOGIN_PAGE = '/account-auth/login';
196
208
  const VERIFY_CODE_PAGE = '/account-auth/verify-code';
197
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
+
198
215
  function isLoginPage(pathname: string): boolean {
199
- return pathname === LOGIN_PAGE;
216
+ return pathname === LOGIN_PAGE || pathname === LOGIN_ALIAS;
200
217
  }
201
218
 
202
219
  /**
@@ -542,6 +559,15 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
542
559
  const rbacExemptPaths = options.rbacExemptPaths || [];
543
560
  // PAY-1882 step 4: default 'closed' (Jon's option A / BAPert 66316).
544
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
+ }
545
571
  const sessionResetRoute =
546
572
  options.sessionResetRoute === true ? DEFAULT_SESSION_RESET_ROUTE
547
573
  : typeof options.sessionResetRoute === 'string' && options.sessionResetRoute ? options.sessionResetRoute
@@ -604,7 +630,8 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
604
630
  request,
605
631
  viabilityEndpoint,
606
632
  log,
607
- revocationFailMode
633
+ revocationFailMode,
634
+ noRevocationSource
608
635
  );
609
636
 
610
637
  // --- Stale session (cookie exists but session doesn't): OBSERVE ONLY, DO NOT DECIDE ---
@@ -687,11 +714,14 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
687
714
  export function decideForceInvalid(
688
715
  data: { revocationStatus?: unknown; forceInvalid?: unknown; revoked?: unknown },
689
716
  revocationFailMode: 'closed' | 'open',
717
+ noRevocationSource: boolean = false,
690
718
  ): boolean {
691
719
  const status = data.revocationStatus;
692
720
  if (typeof status === 'string') {
693
721
  if (status === 'revoked') return true;
694
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;
695
725
  // S1 (NightHawk 66409): ANY other string - 'unknown', 'not_configured', a
696
726
  // typo like 'Revoked', 'error', or '' - is treated as 'unknown' (fail mode
697
727
  // applies), NEVER as 'active'. Returning false here would let the first
@@ -720,7 +750,8 @@ async function checkViability(
720
750
  request: NextRequest,
721
751
  endpoint: string,
722
752
  log: MiddlewareLogger,
723
- revocationFailMode: 'closed' | 'open'
753
+ revocationFailMode: 'closed' | 'open',
754
+ noRevocationSource: boolean = false
724
755
  ): Promise<{
725
756
  sessionStatus: SessionStatus;
726
757
  sessionPointer: SessionPointer;
@@ -798,7 +829,7 @@ async function checkViability(
798
829
  // revocations status, decide from it + failMode and ignore the folded
799
830
  // booleans for unknown/not_configured. The booleans are read ONLY when
800
831
  // revocationStatus is ABSENT (idealresume.online's older boolean route).
801
- sessionStatus.forceInvalid = decideForceInvalid(data, revocationFailMode);
832
+ sessionStatus.forceInvalid = decideForceInvalid(data, revocationFailMode, noRevocationSource);
802
833
  // PAY-2216: a STALE session - the cookie resolved to a token, but no store holds the session - used to set
803
834
  // pointer.exists=false, so makeAuthDecision took no_session (login, cookie NOT cleared) and its stale_session
804
835
  // arm (clearCookies) was unreachable: a dead cookie lingered and re-ran viability on every request.
@@ -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
- const [loginError, setLoginError] = useState<string | null>(null);
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
- // Surface OAuth failures the Better Auth mount bounced back here.
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 (oauthError) {
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 && !loginError && (loading || (status === 'loading' && !session))) {
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,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';