@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
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-1576 - the 2FA "enter your code" step, described ONCE.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS FILE EXISTS. Two cards render the same step for the same door
|
|
5
|
+
* (POST /api/auth/admin-login, the package's routes/auth/credential-login, answers `requiresTwoFactor` with `sentVia` /
|
|
6
|
+
* `codeRequested` / `emailSent`):
|
|
7
|
+
* - SignInCard.tsx (fixed in 267479 to name every lane the box accepts)
|
|
8
|
+
* - AdminLoginCard.tsx (NOT fixed: it said "from your authenticator app" for every user and
|
|
9
|
+
* discarded the door's answer, so an email-code user was sent to a
|
|
10
|
+
* factor they do not have; live allowed2FAMethods=[emailcode,totp])
|
|
11
|
+
* 267479 reached only one of the twins. A comment cannot stop that recurring; a shared helper can,
|
|
12
|
+
* because there is then only one place the sentence is built and a static gate
|
|
13
|
+
* (testing/qa/code-step-copy-gate.js) fails if either card builds its own.
|
|
14
|
+
*
|
|
15
|
+
* THE COPY RULES (carried over verbatim from 267479 / 267561, not re-decided here):
|
|
16
|
+
* - Name BOTH lanes and RANK NEITHER: the screen does not know which factor the user holds.
|
|
17
|
+
* - The non-authenticator clause is gated on the door's answer, so we never mention a code nobody
|
|
18
|
+
* asked for.
|
|
19
|
+
* - `codeRequested` means "a code was requested", NOT "a code arrived" (twofa/email/send returns
|
|
20
|
+
* 200 even when the SMTP send threw), so the copy says "the code we emailed you" and never
|
|
21
|
+
* "check your inbox" / "it has arrived".
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export type CodeSentVia = 'sms' | 'email' | null;
|
|
25
|
+
|
|
26
|
+
export interface CodeRequest {
|
|
27
|
+
/** The door asked for a code to be sent (`codeRequested`, or the older alias `emailSent`). */
|
|
28
|
+
codeRequested: boolean;
|
|
29
|
+
/** Which lane the door actually fired, or null when nothing was sent (a TOTP holder). */
|
|
30
|
+
sentVia: CodeSentVia;
|
|
31
|
+
/**
|
|
32
|
+
* PAY-2314 (4.7.1): present and false ONLY when the door said which factors it accepts (acceptedFactors) and TOTP is not
|
|
33
|
+
* among them. Absent means "the door did not say" (an older door) and keeps the historic authenticator sentence.
|
|
34
|
+
*/
|
|
35
|
+
acceptsAuthenticator?: false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Nothing sent, nothing to say beyond the authenticator. What a card starts with. */
|
|
39
|
+
export const NO_CODE_REQUEST: CodeRequest = { codeRequested: false, sentVia: null };
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Read the door's answer. Total: any shape (null, a string, an array, junk fields) yields a
|
|
43
|
+
* CodeRequest and never throws, so a malformed body degrades to the authenticator-only sentence
|
|
44
|
+
* rather than to a crash or to a claim the door never made.
|
|
45
|
+
*/
|
|
46
|
+
export function readCodeRequest(body: unknown): CodeRequest {
|
|
47
|
+
const b = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};
|
|
48
|
+
const sentVia: CodeSentVia = b.sentVia === 'sms' || b.sentVia === 'email' ? b.sentVia : null;
|
|
49
|
+
const accepted = Array.isArray(b.acceptedFactors) ? (b.acceptedFactors as unknown[]) : null;
|
|
50
|
+
const base: CodeRequest = { codeRequested: b.codeRequested === true || b.emailSent === true, sentVia };
|
|
51
|
+
return accepted !== null && !accepted.includes('totp') ? { ...base, acceptsAuthenticator: false } : base;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The lane clause that follows the authenticator, or '' when the door sent nothing. */
|
|
55
|
+
function laneClause(r: CodeRequest): string {
|
|
56
|
+
if (!r.codeRequested) return '';
|
|
57
|
+
if (r.sentVia === 'sms') return ', or the code we texted you';
|
|
58
|
+
if (r.sentVia === 'email') return ', or the code we emailed you';
|
|
59
|
+
return ', or the code we sent you';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The sentence, split around the email so a card can render the address however it likes
|
|
64
|
+
* (SignInCard wraps it in <strong>; AdminLoginCard passes a plain-string subtitle).
|
|
65
|
+
* `before + email + after` is the whole sentence.
|
|
66
|
+
*/
|
|
67
|
+
export function codeStepParts(r: CodeRequest): { before: string; after: string } {
|
|
68
|
+
if (r.acceptsAuthenticator === false) {
|
|
69
|
+
// PAY-2314: the door told us TOTP is not an accepted factor for this user - never send them to an authenticator they do not have.
|
|
70
|
+
const how = r.sentVia === 'sms' ? 'texted' : r.sentVia === 'email' ? 'emailed' : 'sent';
|
|
71
|
+
return { before: 'Enter your 6-digit code to finish signing in as ', after: ` — the code we ${how} you.` };
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
before: 'Enter your 6-digit code to finish signing in as ',
|
|
75
|
+
after: ` — from your authenticator app${laneClause(r)}.`,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The sentence as one plain string, for a card whose subtitle prop is a string. */
|
|
80
|
+
export function codeStepInstruction(email: string, r: CodeRequest): string {
|
|
81
|
+
const { before, after } = codeStepParts(r);
|
|
82
|
+
return `${before}${email}${after}`;
|
|
83
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PAY-2302 cut 1b: the BROWSER side of the package's credential sign-in, as plain functions so it is testable without a DOM.
|
|
3
|
+
*
|
|
4
|
+
* It talks to the routes the app mounts from this package:
|
|
5
|
+
* POST /api/auth/admin-login routes/auth/credential-login { email, password, code? }
|
|
6
|
+
* POST /api/auth/admin-login/email-code routes/auth/credential-login-email-code (no body: the browser names no address and no client)
|
|
7
|
+
*
|
|
8
|
+
* The result is a closed union so the form cannot invent a state the door never answered. The logic mirrors the portal's
|
|
9
|
+
* AdminLoginCard.submitLogin (VibeID-Customer-Portal 3d654917) and keeps its rules:
|
|
10
|
+
* - 429 is relayed as the door's own sentence; the form never states a window the door did not send.
|
|
11
|
+
* - `requiresTwoFactor` moves to the code step and keeps the door's answer (sentVia / codeRequested) so the step names the
|
|
12
|
+
* lane that was actually fired (PAY-1576).
|
|
13
|
+
* - anything else not `success: true` is an error carrying the door's message, and `offerEmailCode` only when the door set it
|
|
14
|
+
* literally true (PAY-2284).
|
|
15
|
+
*/
|
|
16
|
+
import { NO_CODE_REQUEST, readCodeRequest, type CodeRequest } from './code-step-copy';
|
|
17
|
+
|
|
18
|
+
export const CREDENTIAL_LOGIN_URL = '/api/auth/admin-login';
|
|
19
|
+
export const CREDENTIAL_EMAIL_CODE_URL = '/api/auth/admin-login/email-code';
|
|
20
|
+
|
|
21
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
22
|
+
|
|
23
|
+
export type CredentialSignInResult =
|
|
24
|
+
| { kind: 'success' }
|
|
25
|
+
| { kind: 'two_factor'; codeRequest: CodeRequest }
|
|
26
|
+
| { kind: 'rate_limited'; message: string }
|
|
27
|
+
| { kind: 'error'; message: string; offerEmailCode: boolean };
|
|
28
|
+
|
|
29
|
+
export const MSG_RATE_LIMITED = 'Too many attempts. Please try again later.';
|
|
30
|
+
export const MSG_CANNOT_SIGN_IN = 'Could not sign in. Check your details and try again.';
|
|
31
|
+
export const MSG_UNEXPECTED = 'Something went wrong signing you in. Please try again.';
|
|
32
|
+
|
|
33
|
+
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])?)*$/;
|
|
34
|
+
|
|
35
|
+
export function isEmailShaped(v: string): boolean {
|
|
36
|
+
return EMAIL_SHAPE.test(v);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Field-level checks before anything is sent. Returns the errors, or null when the input may be submitted. */
|
|
40
|
+
export function validateCredentials(email: string, password: string): { email?: string; password?: string } | null {
|
|
41
|
+
const errors: { email?: string; password?: string } = {};
|
|
42
|
+
const trimmed = email.trim();
|
|
43
|
+
if (!trimmed) errors.email = 'Enter your email address.';
|
|
44
|
+
else if (!isEmailShaped(trimmed)) errors.email = 'Enter a valid email address.';
|
|
45
|
+
if (!password) errors.password = 'Enter your password.';
|
|
46
|
+
return errors.email || errors.password ? errors : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function asString(v: unknown): string | undefined {
|
|
50
|
+
return typeof v === 'string' && v ? v : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One call to the credential door. `code` is the 2FA code on the second turn; email and password are resubmitted with it. */
|
|
54
|
+
export async function credentialSignIn(
|
|
55
|
+
args: { email: string; password: string; code?: string },
|
|
56
|
+
fetchImpl: FetchLike = (input, init) => fetch(input, init),
|
|
57
|
+
): Promise<CredentialSignInResult> {
|
|
58
|
+
try {
|
|
59
|
+
const res = await fetchImpl(CREDENTIAL_LOGIN_URL, {
|
|
60
|
+
method: 'POST',
|
|
61
|
+
headers: { 'Content-Type': 'application/json' },
|
|
62
|
+
body: JSON.stringify({ email: args.email, password: args.password, code: args.code }),
|
|
63
|
+
});
|
|
64
|
+
const body: any = await res.json().catch(() => null);
|
|
65
|
+
|
|
66
|
+
if (res.status === 429) return { kind: 'rate_limited', message: asString(body?.error) ?? MSG_RATE_LIMITED };
|
|
67
|
+
if (body?.requiresTwoFactor) return { kind: 'two_factor', codeRequest: readCodeRequest(body) };
|
|
68
|
+
if (!res.ok || body?.success !== true) {
|
|
69
|
+
return { kind: 'error', message: asString(body?.error) ?? MSG_CANNOT_SIGN_IN, offerEmailCode: body?.offerEmailCode === true };
|
|
70
|
+
}
|
|
71
|
+
return { kind: 'success' };
|
|
72
|
+
} catch {
|
|
73
|
+
return { kind: 'error', message: MSG_UNEXPECTED, offerEmailCode: false };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type EmailCodeResult =
|
|
78
|
+
| { kind: 'requested'; codeRequest: CodeRequest; devCode: string | null }
|
|
79
|
+
| { kind: 'error'; message: string };
|
|
80
|
+
|
|
81
|
+
export const MSG_EMAIL_CODE_FAILED = 'We could not ask for an email code just now. Try again shortly.';
|
|
82
|
+
|
|
83
|
+
/** "Email me a code instead": asks the door to email a code. `requested` means asked, never arrived. */
|
|
84
|
+
export async function requestEmailCode(fetchImpl: FetchLike = (input, init) => fetch(input, init)): Promise<EmailCodeResult> {
|
|
85
|
+
try {
|
|
86
|
+
const res = await fetchImpl(CREDENTIAL_EMAIL_CODE_URL, { method: 'POST', credentials: 'include' });
|
|
87
|
+
const body: any = await res.json().catch(() => null);
|
|
88
|
+
if (res.ok && body?.success === true) {
|
|
89
|
+
return {
|
|
90
|
+
kind: 'requested',
|
|
91
|
+
codeRequest: readCodeRequest(body),
|
|
92
|
+
devCode: typeof body?.devVerificationCode === 'string' && body.devVerificationCode ? body.devVerificationCode : null,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return { kind: 'error', message: asString(body?.error) ?? MSG_EMAIL_CODE_FAILED };
|
|
96
|
+
} catch {
|
|
97
|
+
return { kind: 'error', message: MSG_EMAIL_CODE_FAILED };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export { NO_CODE_REQUEST };
|
|
@@ -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
|
+
}
|