@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.
Files changed (68) 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 +15 -2
  12. package/dist/auth/session-cookie-clear.d.ts +7 -0
  13. package/dist/auth/session-cookie-clear.js +24 -0
  14. package/dist/auth/session-reset-link.d.ts +43 -0
  15. package/dist/auth/session-reset-link.js +144 -0
  16. package/dist/components/auth/CredentialSignInForm.d.ts +33 -0
  17. package/dist/components/auth/CredentialSignInForm.js +134 -0
  18. package/dist/lib/authorize-resume.d.ts +87 -0
  19. package/dist/lib/authorize-resume.js +190 -0
  20. package/dist/lib/bearer-fetch.d.ts +17 -0
  21. package/dist/lib/bearer-fetch.js +32 -0
  22. package/dist/lib/code-step-copy.d.ts +53 -0
  23. package/dist/lib/code-step-copy.js +73 -0
  24. package/dist/lib/credential-sign-in-client.d.ts +59 -0
  25. package/dist/lib/credential-sign-in-client.js +89 -0
  26. package/dist/lib/device-id.d.ts +37 -0
  27. package/dist/lib/device-id.js +70 -0
  28. package/dist/lib/lock-window.d.ts +29 -0
  29. package/dist/lib/lock-window.js +53 -0
  30. package/dist/lib/login-error-message.d.ts +18 -0
  31. package/dist/lib/login-error-message.js +47 -0
  32. package/dist/lib/twofa-rejection.d.ts +20 -0
  33. package/dist/lib/twofa-rejection.js +73 -0
  34. package/dist/middleware/create-middleware.d.ts +25 -1
  35. package/dist/middleware/create-middleware.js +75 -27
  36. package/dist/pages/login/page.js +11 -37
  37. package/dist/routes/auth/credential-login-email-code.d.ts +6 -0
  38. package/dist/routes/auth/credential-login-email-code.js +10 -0
  39. package/dist/routes/auth/credential-login.d.ts +6 -0
  40. package/dist/routes/auth/credential-login.js +10 -0
  41. package/dist/routes/auth/session-reset.d.ts +21 -0
  42. package/dist/routes/auth/session-reset.js +40 -0
  43. package/dist/routes/oauth/resume.d.ts +11 -0
  44. package/dist/routes/oauth/resume.js +16 -0
  45. package/package.json +1102 -1042
  46. package/src/api-handlers/auth/credential-login-email-code.ts +92 -0
  47. package/src/api-handlers/auth/credential-login.ts +948 -0
  48. package/src/api-handlers/oauth/resume.ts +182 -0
  49. package/src/auth/better-auth.ts +81 -5
  50. package/src/auth/idp-oauth.ts +310 -0
  51. package/src/auth/safe-callback.ts +16 -2
  52. package/src/auth/session-cookie-clear.ts +30 -0
  53. package/src/auth/session-reset-link.ts +159 -0
  54. package/src/components/auth/CredentialSignInForm.tsx +240 -0
  55. package/src/lib/authorize-resume.ts +187 -0
  56. package/src/lib/bearer-fetch.ts +31 -0
  57. package/src/lib/code-step-copy.ts +83 -0
  58. package/src/lib/credential-sign-in-client.ts +101 -0
  59. package/src/lib/device-id.ts +67 -0
  60. package/src/lib/lock-window.ts +49 -0
  61. package/src/lib/login-error-message.ts +41 -0
  62. package/src/lib/twofa-rejection.ts +91 -0
  63. package/src/middleware/create-middleware.ts +124 -30
  64. package/src/pages/login/page.tsx +20 -34
  65. package/src/routes/auth/credential-login-email-code.ts +6 -0
  66. package/src/routes/auth/credential-login.ts +6 -0
  67. package/src/routes/auth/session-reset.ts +37 -0
  68. package/src/routes/oauth/resume.ts +11 -0
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NO_CODE_REQUEST = exports.MSG_EMAIL_CODE_FAILED = exports.MSG_UNEXPECTED = exports.MSG_CANNOT_SIGN_IN = exports.MSG_RATE_LIMITED = exports.CREDENTIAL_EMAIL_CODE_URL = exports.CREDENTIAL_LOGIN_URL = void 0;
4
+ exports.isEmailShaped = isEmailShaped;
5
+ exports.validateCredentials = validateCredentials;
6
+ exports.credentialSignIn = credentialSignIn;
7
+ exports.requestEmailCode = requestEmailCode;
8
+ /**
9
+ * PAY-2302 cut 1b: the BROWSER side of the package's credential sign-in, as plain functions so it is testable without a DOM.
10
+ *
11
+ * It talks to the routes the app mounts from this package:
12
+ * POST /api/auth/admin-login routes/auth/credential-login { email, password, code? }
13
+ * POST /api/auth/admin-login/email-code routes/auth/credential-login-email-code (no body: the browser names no address and no client)
14
+ *
15
+ * The result is a closed union so the form cannot invent a state the door never answered. The logic mirrors the portal's
16
+ * AdminLoginCard.submitLogin (VibeID-Customer-Portal 3d654917) and keeps its rules:
17
+ * - 429 is relayed as the door's own sentence; the form never states a window the door did not send.
18
+ * - `requiresTwoFactor` moves to the code step and keeps the door's answer (sentVia / codeRequested) so the step names the
19
+ * lane that was actually fired (PAY-1576).
20
+ * - anything else not `success: true` is an error carrying the door's message, and `offerEmailCode` only when the door set it
21
+ * literally true (PAY-2284).
22
+ */
23
+ const code_step_copy_1 = require("./code-step-copy");
24
+ Object.defineProperty(exports, "NO_CODE_REQUEST", { enumerable: true, get: function () { return code_step_copy_1.NO_CODE_REQUEST; } });
25
+ exports.CREDENTIAL_LOGIN_URL = '/api/auth/admin-login';
26
+ exports.CREDENTIAL_EMAIL_CODE_URL = '/api/auth/admin-login/email-code';
27
+ exports.MSG_RATE_LIMITED = 'Too many attempts. Please try again later.';
28
+ exports.MSG_CANNOT_SIGN_IN = 'Could not sign in. Check your details and try again.';
29
+ exports.MSG_UNEXPECTED = 'Something went wrong signing you in. Please try again.';
30
+ const EMAIL_SHAPE = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
31
+ function isEmailShaped(v) {
32
+ return EMAIL_SHAPE.test(v);
33
+ }
34
+ /** Field-level checks before anything is sent. Returns the errors, or null when the input may be submitted. */
35
+ function validateCredentials(email, password) {
36
+ const errors = {};
37
+ const trimmed = email.trim();
38
+ if (!trimmed)
39
+ errors.email = 'Enter your email address.';
40
+ else if (!isEmailShaped(trimmed))
41
+ errors.email = 'Enter a valid email address.';
42
+ if (!password)
43
+ errors.password = 'Enter your password.';
44
+ return errors.email || errors.password ? errors : null;
45
+ }
46
+ function asString(v) {
47
+ return typeof v === 'string' && v ? v : undefined;
48
+ }
49
+ /** One call to the credential door. `code` is the 2FA code on the second turn; email and password are resubmitted with it. */
50
+ async function credentialSignIn(args, fetchImpl = (input, init) => fetch(input, init)) {
51
+ try {
52
+ const res = await fetchImpl(exports.CREDENTIAL_LOGIN_URL, {
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json' },
55
+ body: JSON.stringify({ email: args.email, password: args.password, code: args.code }),
56
+ });
57
+ const body = await res.json().catch(() => null);
58
+ if (res.status === 429)
59
+ return { kind: 'rate_limited', message: asString(body?.error) ?? exports.MSG_RATE_LIMITED };
60
+ if (body?.requiresTwoFactor)
61
+ return { kind: 'two_factor', codeRequest: (0, code_step_copy_1.readCodeRequest)(body) };
62
+ if (!res.ok || body?.success !== true) {
63
+ return { kind: 'error', message: asString(body?.error) ?? exports.MSG_CANNOT_SIGN_IN, offerEmailCode: body?.offerEmailCode === true };
64
+ }
65
+ return { kind: 'success' };
66
+ }
67
+ catch {
68
+ return { kind: 'error', message: exports.MSG_UNEXPECTED, offerEmailCode: false };
69
+ }
70
+ }
71
+ exports.MSG_EMAIL_CODE_FAILED = 'We could not ask for an email code just now. Try again shortly.';
72
+ /** "Email me a code instead": asks the door to email a code. `requested` means asked, never arrived. */
73
+ async function requestEmailCode(fetchImpl = (input, init) => fetch(input, init)) {
74
+ try {
75
+ const res = await fetchImpl(exports.CREDENTIAL_EMAIL_CODE_URL, { method: 'POST', credentials: 'include' });
76
+ const body = await res.json().catch(() => null);
77
+ if (res.ok && body?.success === true) {
78
+ return {
79
+ kind: 'requested',
80
+ codeRequest: (0, code_step_copy_1.readCodeRequest)(body),
81
+ devCode: typeof body?.devVerificationCode === 'string' && body.devVerificationCode ? body.devVerificationCode : null,
82
+ };
83
+ }
84
+ return { kind: 'error', message: asString(body?.error) ?? exports.MSG_EMAIL_CODE_FAILED };
85
+ }
86
+ catch {
87
+ return { kind: 'error', message: exports.MSG_EMAIL_CODE_FAILED };
88
+ }
89
+ }
@@ -0,0 +1,37 @@
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
+ export declare const DEVICE_ID_HEADER = "X-Device-Id";
24
+ export declare const DEVICE_ID_PATTERN: RegExp;
25
+ /** True for a well-formed device id. Used on BOTH sides of the wire. */
26
+ export declare function isValidDeviceId(value: string | null | undefined): value is string;
27
+ /**
28
+ * The stable per-browser device id, minted once and persisted.
29
+ *
30
+ * Browser-only. Persistence is best-effort: private windows, disabled site
31
+ * data and storage-quota failures all throw on access, so every read and
32
+ * write is guarded. A browser that cannot persist still gets a VALID id for
33
+ * this call — it simply looks like a new device each time, which is the
34
+ * honest answer for a client that refuses to be remembered, and is still
35
+ * strictly better than every user sharing one identity.
36
+ */
37
+ export declare function getDeviceId(): string;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * Per-browser device identity — card 240566 (QAPert flag 2 on the 9c7a815 review).
4
+ *
5
+ * BEFORE: /api/auth/admin-login forwarded ONE hardcoded device-id cookie —
6
+ * `payez-PayEz-6c8201c35c1b44c9b2e823b36b95a718` — for every caller on the
7
+ * PUBLIC /sign-in password path. To the IDP's rate limiter and device
8
+ * fingerprinting, every portal user was literally the same device. Two
9
+ * consequences, both measured-by-inspection rather than hypothetical:
10
+ * 1. SHARED-FATE LOCKOUT — one attacker's failed attempts consume the
11
+ * throttle budget for every legitimate user at once.
12
+ * 2. Per-device risk signals are meaningless: "new device" and "trusted
13
+ * device" cannot distinguish anybody from anybody.
14
+ *
15
+ * The id is a routing/telemetry key, NOT a credential — the IDP must never
16
+ * grant anything on the strength of it, and nothing here assumes otherwise.
17
+ * It is client-supplied and therefore client-forgeable; that is inherent to
18
+ * device-id throttling and is why it supplements, never replaces, the
19
+ * identifier- and IP-scoped limits on the IDP side.
20
+ *
21
+ * Shape is fixed by what the IDP already accepts from
22
+ * createLoginHandler: `payez-PayEz-<32 lowercase hex>`.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.DEVICE_ID_PATTERN = exports.DEVICE_ID_HEADER = void 0;
26
+ exports.isValidDeviceId = isValidDeviceId;
27
+ exports.getDeviceId = getDeviceId;
28
+ exports.DEVICE_ID_HEADER = 'X-Device-Id';
29
+ exports.DEVICE_ID_PATTERN = /^payez-PayEz-[0-9a-f]{32}$/;
30
+ const STORAGE_KEY = 'payez.device-id';
31
+ /** True for a well-formed device id. Used on BOTH sides of the wire. */
32
+ function isValidDeviceId(value) {
33
+ return typeof value === 'string' && exports.DEVICE_ID_PATTERN.test(value);
34
+ }
35
+ function mint() {
36
+ const bytes = new Uint8Array(16);
37
+ crypto.getRandomValues(bytes);
38
+ const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
39
+ return `payez-PayEz-${hex}`;
40
+ }
41
+ /**
42
+ * The stable per-browser device id, minted once and persisted.
43
+ *
44
+ * Browser-only. Persistence is best-effort: private windows, disabled site
45
+ * data and storage-quota failures all throw on access, so every read and
46
+ * write is guarded. A browser that cannot persist still gets a VALID id for
47
+ * this call — it simply looks like a new device each time, which is the
48
+ * honest answer for a client that refuses to be remembered, and is still
49
+ * strictly better than every user sharing one identity.
50
+ */
51
+ function getDeviceId() {
52
+ if (typeof window === 'undefined')
53
+ return mint();
54
+ try {
55
+ const existing = window.localStorage.getItem(STORAGE_KEY);
56
+ if (isValidDeviceId(existing))
57
+ return existing;
58
+ }
59
+ catch {
60
+ return mint();
61
+ }
62
+ const minted = mint();
63
+ try {
64
+ window.localStorage.setItem(STORAGE_KEY, minted);
65
+ }
66
+ catch {
67
+ /* not persistable — the minted id is still returned and used for this call */
68
+ }
69
+ return minted;
70
+ }
@@ -0,0 +1,29 @@
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
+ /** A positive whole number of seconds from the BFF body, or undefined. Anything else - a string, 0, NaN - is dropped. */
18
+ export declare function lockSecondsFromBody(value: unknown): number | undefined;
19
+ /** A Retry-After header as whole seconds. ONE implementation: the package's lib/retry-after (the portal copy was the same rule). */
20
+ export { parseRetryAfterSeconds } from './retry-after';
21
+ /**
22
+ * The window in words, rounded UP so the user is never told a shorter wait than the IdP enforces:
23
+ * 900 -> "15 minutes", 61 -> "2 minutes", 60 -> "1 minute", 45 -> "45 seconds", 7200 -> "2 hours".
24
+ */
25
+ export declare function formatLockWindow(seconds: number | undefined): string | undefined;
26
+ /** The sentence for a lock whose window was NOT sent. It says even a correct code is refused, and states no number. */
27
+ export declare const LOCKED_NO_WINDOW = "Too many incorrect codes. Verification is locked for now - even a correct code is refused until the lock ends. Wait before entering another code.";
28
+ /** The locked sentence: the IdP's real window when it sent one, otherwise LOCKED_NO_WINDOW. */
29
+ export declare function lockedSentence(seconds?: number): string;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ /**
3
+ * PAY-1608: a 2FA lock's window, stated as the IdP enforces it. Never a hard-coded "15 minutes".
4
+ *
5
+ * Core answers every 2FA lock with 429 code "locked" plus Retry-After: MfaController.SecondFactorLocked sends the
6
+ * full lockout (900), and VerifyTotp sends what is LEFT of the lock. The portal used to hard-code "locked for 15
7
+ * minutes" in three places (verify-code-copy.ts, twofa-rejection.ts, and the next-mvp BFF), which was true only
8
+ * while every lock was exactly 15 minutes and the user had just tripped it.
9
+ *
10
+ * The window arrives in one of two ways:
11
+ * - Door A (verify-code): next-mvp >= 4.5.2 relays it in the BFF body as `retryAfterSeconds` (a number).
12
+ * - Door B (admin-login): this route reads the IdP's Retry-After header itself.
13
+ * With no window, the sentence states NO number rather than a guessed one.
14
+ *
15
+ * Dependency-free on purpose: the verify-code page (client) and the admin-login route (server) both use it, and
16
+ * the chain gate executes it directly.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.LOCKED_NO_WINDOW = exports.parseRetryAfterSeconds = void 0;
20
+ exports.lockSecondsFromBody = lockSecondsFromBody;
21
+ exports.formatLockWindow = formatLockWindow;
22
+ exports.lockedSentence = lockedSentence;
23
+ /** A positive whole number of seconds from the BFF body, or undefined. Anything else - a string, 0, NaN - is dropped. */
24
+ function lockSecondsFromBody(value) {
25
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.ceil(value) : undefined;
26
+ }
27
+ /** A Retry-After header as whole seconds. ONE implementation: the package's lib/retry-after (the portal copy was the same rule). */
28
+ var retry_after_1 = require("./retry-after");
29
+ Object.defineProperty(exports, "parseRetryAfterSeconds", { enumerable: true, get: function () { return retry_after_1.parseRetryAfterSeconds; } });
30
+ /**
31
+ * The window in words, rounded UP so the user is never told a shorter wait than the IdP enforces:
32
+ * 900 -> "15 minutes", 61 -> "2 minutes", 60 -> "1 minute", 45 -> "45 seconds", 7200 -> "2 hours".
33
+ */
34
+ function formatLockWindow(seconds) {
35
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
36
+ return undefined;
37
+ const plural = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'}`;
38
+ if (seconds < 60)
39
+ return plural(Math.ceil(seconds), 'second');
40
+ const minutes = Math.ceil(seconds / 60);
41
+ if (minutes < 120)
42
+ return plural(minutes, 'minute');
43
+ return plural(Math.ceil(minutes / 60), 'hour');
44
+ }
45
+ /** The sentence for a lock whose window was NOT sent. It says even a correct code is refused, and states no number. */
46
+ exports.LOCKED_NO_WINDOW = 'Too many incorrect codes. Verification is locked for now - even a correct code is refused until the lock ends. Wait before entering another code.';
47
+ /** The locked sentence: the IdP's real window when it sent one, otherwise LOCKED_NO_WINDOW. */
48
+ function lockedSentence(seconds) {
49
+ const window = formatLockWindow(seconds);
50
+ return window
51
+ ? `Too many incorrect codes. Verification is locked for ${window} - wait before entering another code.`
52
+ : exports.LOCKED_NO_WINDOW;
53
+ }
@@ -0,0 +1,18 @@
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
+ export declare const GENERIC_LOGIN_ERROR = "We could not sign you in. Please try again.";
12
+ /**
13
+ * The sentence for `?error=<code>`, or null when nothing should be shown.
14
+ * SessionExpired is a normal event (not an error) and shows nothing; an absent/empty code shows nothing.
15
+ */
16
+ export declare function friendlyLoginError(code: string | null | undefined): string | null;
17
+ /** `?oauth_error=<provider>`: only a plain provider-like slug is echoed (capitalised); anything else is the generic sentence. */
18
+ export declare function oauthFailureMessage(provider: string | null | undefined): string | null;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ /**
3
+ * PAY-2319 (4.7.2): what the login page SAYS for an `?error=` / `?oauth_error=` code, as pure functions so a test can
4
+ * execute them (the page is a client component and effects do not run in a static render).
5
+ *
6
+ * 4.7.1 mapped these codes in an effect that called setLoginError, but the page never RENDERED loginError (it only fed the
7
+ * loading gate), so no sentence was ever shown (NightHawk's walk, 73801, W1). Now that the text is displayed, a raw code from
8
+ * the URL must NOT be echoed: `/account-auth/login?error=<anything an attacker types>` would otherwise print attacker-chosen
9
+ * text on the login page (content spoofing / phishing). Known codes get their sentence; anything else gets one generic
10
+ * sentence; nothing from the URL is ever shown verbatim.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.GENERIC_LOGIN_ERROR = void 0;
14
+ exports.friendlyLoginError = friendlyLoginError;
15
+ exports.oauthFailureMessage = oauthFailureMessage;
16
+ exports.GENERIC_LOGIN_ERROR = 'We could not sign you in. Please try again.';
17
+ const KNOWN = {
18
+ TwoFactorTimeout: 'Your verification step timed out before the code was confirmed. Please sign in again.',
19
+ AUTHORIZE_RESUME_REFUSED: 'That sign-in request could not be continued. Please sign in again.',
20
+ ServiceUnavailable: 'Authentication service is temporarily unavailable. Please try again in a few minutes.',
21
+ CredentialsSignin: 'Invalid email or password. Please try again.',
22
+ };
23
+ /**
24
+ * The sentence for `?error=<code>`, or null when nothing should be shown.
25
+ * SessionExpired is a normal event (not an error) and shows nothing; an absent/empty code shows nothing.
26
+ */
27
+ function friendlyLoginError(code) {
28
+ if (typeof code !== 'string' || code === '')
29
+ return null;
30
+ if (code === 'SessionExpired')
31
+ return null;
32
+ if (Object.prototype.hasOwnProperty.call(KNOWN, code))
33
+ return KNOWN[code];
34
+ // The old raw-JSON parse failures the middleware/proxy could bounce here:
35
+ if (code.startsWith('Unexpected token') || code.includes('not valid JSON')) {
36
+ return 'An authentication error occurred. Please try signing in again.';
37
+ }
38
+ return exports.GENERIC_LOGIN_ERROR;
39
+ }
40
+ /** `?oauth_error=<provider>`: only a plain provider-like slug is echoed (capitalised); anything else is the generic sentence. */
41
+ function oauthFailureMessage(provider) {
42
+ if (typeof provider !== 'string' || provider === '')
43
+ return null;
44
+ if (!/^[a-z][a-z0-9_-]{0,31}$/i.test(provider))
45
+ return exports.GENERIC_LOGIN_ERROR;
46
+ return `${provider.charAt(0).toUpperCase()}${provider.slice(1)} sign-in did not complete. Please try again.`;
47
+ }
@@ -0,0 +1,20 @@
1
+ export interface TwofaLaneResult {
2
+ status: number;
3
+ body: string;
4
+ /** 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). */
5
+ lane?: 'totp' | 'sms' | 'email';
6
+ /** PAY-1608: this lane's Retry-After header, as received. */
7
+ retryAfter?: string | null;
8
+ }
9
+ export interface TwofaRejection {
10
+ status: 400 | 429 | 502;
11
+ error: string;
12
+ retryAfter?: number;
13
+ /**
14
+ * PAY-2284: true when the authenticator (or text) lane failed on OUR side and the emailed-code lane has not faulted. The sign-in
15
+ * card then shows a real "Email me a code instead" action. Before this, the copy said "use another sign-in method" and the screen
16
+ * 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).
17
+ */
18
+ offerEmailCode?: true;
19
+ }
20
+ export declare function classifyTwofaRejection(lanes: TwofaLaneResult[], retryAfterHeader?: string | null): TwofaRejection;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.classifyTwofaRejection = classifyTwofaRejection;
4
+ /**
5
+ * Door B (/api/auth/admin-login) twofa verify: what to tell the user when every lane refused.
6
+ *
7
+ * Classification is by the MOST BLOCKING outcome across lanes (268121 ruling), in this order:
8
+ * 429 from the IdP, or any lane answering code `locked` -> 429 lockout (PAY-903)
9
+ * any 5xx, or a lane answering code server_error / service_unavailable (PAY-1589) -> 502 "our side, not your code"
10
+ * otherwise -> 400 wrong / expired code
11
+ *
12
+ * PAY-903: MfaController.VerifyTotp returns 400 {message, code:"locked"} for a 15-minute lockout
13
+ * (MfaTotpService ErrorCode "locked"). Status-only classification read that as "wrong code, try again" -
14
+ * coaching a locked-out user to spend attempts. The body is inspected for EVERY lane, because with lane
15
+ * order [totp, email] the last response is the email lane's and never carries the TOTP lockout.
16
+ * Disclosing the lockout here is safe: this step is post-password (the caller already proved the account).
17
+ *
18
+ * PAY-1608: the lockout states the LOCKED LANE's own Retry-After (Core sends one on every 2FA lock; VerifyTotp sends
19
+ * what is LEFT of it). It used to hard-code 15 minutes / 900 s. With no usable header, no number is stated and
20
+ * `retryAfter` is omitted rather than invented.
21
+ */
22
+ const lock_window_1 = require("./lock-window");
23
+ /** Every code the IdP body carries: flat {code}, envelope {error:{code}}, or {error:{details:{code}}}. */
24
+ function laneCodes(body) {
25
+ try {
26
+ const j = JSON.parse(body);
27
+ if (!j || typeof j !== 'object')
28
+ return [];
29
+ const err = (j.error && typeof j.error === 'object' ? j.error : null);
30
+ const details = (err?.details && typeof err.details === 'object' ? err.details : null);
31
+ return [j.code, err?.code, details?.code].filter((c) => typeof c === 'string').map((c) => c.toLowerCase());
32
+ }
33
+ catch {
34
+ return [];
35
+ }
36
+ }
37
+ function classifyTwofaRejection(lanes, retryAfterHeader) {
38
+ const lockedLane = lanes.find((l) => laneCodes(l.body).includes('locked'));
39
+ if (lockedLane) {
40
+ const secs = (0, lock_window_1.parseRetryAfterSeconds)(lockedLane.retryAfter);
41
+ return { status: 429, error: (0, lock_window_1.lockedSentence)(secs), ...(secs ? { retryAfter: secs } : {}) };
42
+ }
43
+ if (lanes.some((l) => l.status === 429)) {
44
+ const parsed = retryAfterHeader ? parseInt(retryAfterHeader, 10) : NaN;
45
+ return {
46
+ status: 429,
47
+ error: 'Too many attempts. Your code is still valid - wait before trying again.',
48
+ retryAfter: Number.isFinite(parsed) && parsed > 0 ? parsed : 60,
49
+ };
50
+ }
51
+ // PAY-1589: an IdP-side fault that arrives as 400 + code (TOTP secret cannot be decrypted -> server_error;
52
+ // replay store down -> service_unavailable). It is not the user's code and does not count toward the lockout,
53
+ // so calling it "not right" sends them round a loop that cannot succeed. Email may still work, so say so.
54
+ const faulted = (l) => laneCodes(l.body).some((c) => c === 'server_error' || c === 'service_unavailable');
55
+ if (lanes.some(faulted)) {
56
+ const emailLaneFaulted = lanes.some((l) => l.lane === 'email' && (faulted(l) || l.status >= 500));
57
+ const offer = !emailLaneFaulted && lanes.some((l) => faulted(l) && (l.lane === 'totp' || l.lane === 'sms'));
58
+ return {
59
+ status: 502,
60
+ error: offer
61
+ ? '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.'
62
+ : 'We could not check your code just now - this is a problem on our side, not with your code. Try again shortly.',
63
+ ...(offer ? { offerEmailCode: true } : {}),
64
+ };
65
+ }
66
+ if (lanes.some((l) => l.status >= 500)) {
67
+ return {
68
+ status: 502,
69
+ error: 'We could not check your code just now - this is a problem on our side, not with your code. Try again shortly.',
70
+ };
71
+ }
72
+ return { status: 400, error: 'That code is not right or has expired. Try again.' };
73
+ }
@@ -99,6 +99,19 @@ export interface MvpMiddlewareOptions {
99
99
  bypassPaths?: string[];
100
100
  /** Paths exempt from RBAC checks (auth still enforced, just no page-permission check) */
101
101
  rbacExemptPaths?: string[];
102
+ /**
103
+ * PAY-2218 - send a page's session-ending redirect through the session-reset ROUTE instead of clearing the
104
+ * cookies in the middleware response. Next strips the router's prefetch headers before middleware runs
105
+ * (15.5.x and 16.x; 16.2.x restores them only with `skipProxyUrlNormalize: true`), so a middleware clear also
106
+ * fires on a router PREFETCH and signs the user out of a page they never opened. The route sees those headers.
107
+ *
108
+ * Requires the app to mount the route: app/api/auth/session-reset/route.ts
109
+ * export { GET } from '@payez/next-mvp/routes/auth/session-reset';
110
+ * `true` uses that default path; a string names another mount point under /api/auth/ (middleware bypasses it).
111
+ * Needs BETTER_AUTH_SECRET (or NEXTAUTH_SECRET) to sign the hand-off; without one the direct clear is kept and
112
+ * an error is logged once. Default: off (the direct clear), because an unmounted route would 404 every sign-out.
113
+ */
114
+ sessionResetRoute?: boolean | string;
102
115
  /**
103
116
  * PAY-1882 step 4 - how this app treats a producer that reports the session's
104
117
  * revocation status as `'unknown'` (a Vibe read that FAILED: non-OK, timeout,
@@ -123,6 +136,17 @@ export interface MvpMiddlewareOptions {
123
136
  * is signed out for not implementing the check).
124
137
  */
125
138
  revocationFailMode?: 'closed' | 'open';
139
+ /**
140
+ * PAY-2302 cut 1c (BAPert 73585): this app has NO revocation source - for example a development environment
141
+ * provisioned without a vibe client id / HMAC key - and says so EXPLICITLY. Under it a viability answer of
142
+ * `revocationStatus: 'not_configured'` is viable, and a loud warning is logged once at startup.
143
+ *
144
+ * It relaxes ONLY 'not_configured'. 'unknown' (a revocation read that FAILED) and 'revoked' stay closed whatever
145
+ * `revocationFailMode` says, and the default (option absent) is unchanged: 'not_configured' fails closed, because
146
+ * for an app that HAS a vibe client it means a misconfiguration (BAPert 66356). Do not use this to paper over a
147
+ * misconfigured production app; remove it when the environment has a vibe client + HMAC key.
148
+ */
149
+ noRevocationSource?: boolean;
126
150
  }
127
151
  /**
128
152
  * PAY-2136 Rule A: a speculative request (router prefetch) must NEVER mutate cookies.
@@ -153,4 +177,4 @@ export declare function decideForceInvalid(data: {
153
177
  revocationStatus?: unknown;
154
178
  forceInvalid?: unknown;
155
179
  revoked?: unknown;
156
- }, revocationFailMode: 'closed' | 'open'): boolean;
180
+ }, revocationFailMode: 'closed' | 'open', noRevocationSource?: boolean): boolean;