@payez/next-mvp 4.5.7 → 4.7.10

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 +10 -2
  12. package/dist/client/AuthContext.d.ts +2 -0
  13. package/dist/client/AuthContext.js +14 -1
  14. package/dist/components/auth/CredentialSignInForm.d.ts +33 -0
  15. package/dist/components/auth/CredentialSignInForm.js +134 -0
  16. package/dist/components/auth/ModeAwareLoginPage.js +4 -1
  17. package/dist/components/auth/ModeAwareSignupPage.js +7 -22
  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 +12 -1
  35. package/dist/middleware/create-middleware.js +19 -5
  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/oauth/resume.d.ts +11 -0
  42. package/dist/routes/oauth/resume.js +16 -0
  43. package/dist/types/auth.d.ts +6 -0
  44. package/package.json +1102 -1047
  45. package/src/api-handlers/auth/credential-login-email-code.ts +92 -0
  46. package/src/api-handlers/auth/credential-login.ts +948 -0
  47. package/src/api-handlers/oauth/resume.ts +182 -0
  48. package/src/auth/better-auth.ts +81 -5
  49. package/src/auth/idp-oauth.ts +310 -0
  50. package/src/auth/safe-callback.ts +11 -2
  51. package/src/client/AuthContext.tsx +14 -1
  52. package/src/components/auth/CredentialSignInForm.tsx +240 -0
  53. package/src/components/auth/ModeAwareLoginPage.tsx +21 -1
  54. package/src/components/auth/ModeAwareSignupPage.tsx +38 -108
  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 +35 -4
  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/oauth/resume.ts +11 -0
  68. package/src/types/auth.ts +6 -0
@@ -0,0 +1,187 @@
1
+ /**
2
+ * PAY-2302 cut 2: moved VERBATIM (logic unchanged) from VibeID-Customer-Portal src/lib/auth/authorize-resume.ts.
3
+ * PAY-1500 (portal half of PAY-1479): resume the IdP OAuth authorize request after 2FA.
4
+ *
5
+ * The IdP sends an OAuth principal who still owes 2FA to the portal's /account-auth/verify-code with
6
+ * ?next_step=enroll_mfa|mfa_verify&callbackUrl=<absolute IdP authorize URL>&return_url=<same>
7
+ * (OAuthController.Authorize; hotfix-2 66ca7a8eb routes BOTH cases to verify-code, /account/security is gone). safeCallbackPath rightly refuses that absolute URL,
8
+ * so after 2FA the user used to land on the default page and sign-in never finished.
9
+ *
10
+ * This is NOT a relaxation of safeCallbackPath. The browser is sent to the portal's own
11
+ * /api/oauth/resume, which checks return_url SERVER-SIDE against IDP_URL (origin + the authorize path)
12
+ * and only then redirects. Anything else is refused. IDP_URL never reaches the client.
13
+ */
14
+ export const AUTHORIZE_RESUME_ROUTE = '/api/oauth/resume';
15
+ const AUTHORIZE_PATH = '/api/oauth/authorize';
16
+
17
+ /** True only for `<IDP_URL origin>/api/oauth/authorize` (path case-insensitive, as ASP.NET routes). */
18
+ export function isIdpAuthorizeUrl(candidate: string | null | undefined, idpBaseUrl: string): boolean {
19
+ if (typeof candidate !== 'string' || candidate === '') return false;
20
+ try {
21
+ const u = new URL(candidate);
22
+ const idp = new URL(idpBaseUrl);
23
+ return (u.protocol === 'https:' || u.protocol === 'http:') && u.origin === idp.origin && u.pathname.toLowerCase() === AUTHORIZE_PATH;
24
+ } catch {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Server side: the redirect target, REBUILT from trusted parts - IDP_URL's origin and the authorize path
31
+ * are ours; only the query string comes from the request. Null unless isIdpAuthorizeUrl holds.
32
+ */
33
+ export function idpAuthorizeRedirect(candidate: string | null | undefined, idpBaseUrl: string): string | null {
34
+ if (!isIdpAuthorizeUrl(candidate, idpBaseUrl)) return null;
35
+ const query = new URL(candidate as string).search;
36
+ return `${new URL(idpBaseUrl).origin}/api/OAuth/authorize${query}`;
37
+ }
38
+
39
+ /**
40
+ * Client side: the SAME-ORIGIN portal path that resumes authorize, or null when the IdP did not ask for one.
41
+ * Callers still pass the result through safeCallbackPath before navigating.
42
+ *
43
+ * WHY THE ASTERISK IS RE-ENCODED (PAY-1547, measured by NextPert 59939, completeness measured here).
44
+ * One consumer of this value is `authClient.signIn.social({ callbackURL })`, which POSTs to better-auth
45
+ * and is validated by its own originCheckMiddleware BEFORE anything redirects. For a relative path that
46
+ * check is decided entirely by one regex (better-auth 1.5.6, auth/trusted-origins.mjs:16 - the
47
+ * `allowRelativePaths` branch, and api/middlewares/origin-check.mjs:51 passes
48
+ * `allowRelativePaths: label !== 'origin'`, so it IS that branch for a callbackURL):
49
+ *
50
+ * /^\/(?!\/|\\|%2f|%5c)[\w\-.\+\/@]*(?:\?[\w\-.\+\/=&%@]*)?$/
51
+ *
52
+ * A character this helper emits RAW and that charset rejects is a hard 403 INVALID_CALLBACK_URL on the
53
+ * Google button - not a silent fallback. Measured exhaustively over printable ASCII by diffing what
54
+ * `URLSearchParams` leaves raw against that charset: the raw set is alphanumerics plus `* - . _`, and
55
+ * *** `*` IS THE ONLY REJECTED MEMBER *** (`%` is permitted, which is why every other special character
56
+ * survives - URLSearchParams already percent-encoded it).
57
+ *
58
+ * `*` is reachable because `state` and `scope` are chosen by the OAuth CLIENT, not by us, so we cannot
59
+ * decline to emit it. `%2A` is the same character to every parser: re-reading this query string returns
60
+ * the byte-identical `return_url` (asserted in test/authorize-resume.test.cjs), so this is an encoding
61
+ * change and NOT a value change. It is applied here, at the ONE computation, rather than at the sinks -
62
+ * the two `window.location.href` sinks are browser navigations that touch no library and for which this
63
+ * is a behavioural no-op, so there is no reason to make them each carry it.
64
+ */
65
+ export function authorizeResumeHref(returnUrl: string | null | undefined): string | null {
66
+ if (typeof returnUrl !== 'string' || returnUrl === '') return null;
67
+ const query = new URLSearchParams({ return_url: returnUrl }).toString().replace(/\*/g, '%2A');
68
+ return `${AUTHORIZE_RESUME_ROUTE}?${query}`;
69
+ }
70
+
71
+ // ───────────────────────── 4.7.5 (PAY-2305): the authorize call is made SERVER-SIDE ─────────────────────────
72
+ //
73
+ // WHY: Core's /api/oauth/authorize identifies a user ONLY from an `Authorization: Bearer` header (JwtMiddleware reads no cookie,
74
+ // and a browser navigation cannot send a header), so the 4.7.0-4.7.4 behaviour - 302 the BROWSER to authorize - could never
75
+ // produce a code for anyone. The resume route now calls authorize itself with the signed-in user's IdP access token and relays
76
+ // only the verified outcome. These helpers are the pure, testable parts.
77
+
78
+ export interface ServerAuthorizeParams {
79
+ idpBaseUrl: string;
80
+ /** This app's IdP client slug (CLIENT_ID). The request's client_id must equal it. */
81
+ clientId: string;
82
+ /** The app's REGISTERED redirect_uri, e.g. http://localhost:3000/api/auth/callback. The request's redirect_uri must equal it exactly. */
83
+ redirectUri: string;
84
+ }
85
+
86
+ export interface ServerAuthorizeRequest {
87
+ /** Built from constants + validated pieces only. This is what gets fetched. */
88
+ url: string;
89
+ state: string;
90
+ }
91
+
92
+ const CHALLENGE_RE = /^[A-Za-z0-9_-]{43,128}$/;
93
+ const STATE_RE = /^[A-Za-z0-9._~-]{1,256}$/;
94
+ const SCOPE_RE = /^[A-Za-z0-9:._ -]{1,200}$/;
95
+
96
+ /**
97
+ * Build the authorize URL to call, or null (refuse). Origin, path, response_type, client_id and redirect_uri are OURS; from
98
+ * return_url only code_challenge (+ method, S256 only), state and scope are taken, each charset/length validated. A return_url for
99
+ * another client or another redirect_uri is refused (no "someone else's client"). Unknown extra parameters are NOT forwarded.
100
+ */
101
+ export function buildServerAuthorizeRequest(returnUrl: string | null | undefined, p: ServerAuthorizeParams): ServerAuthorizeRequest | null {
102
+ if (!isIdpAuthorizeUrl(returnUrl, p.idpBaseUrl) || !p.clientId || !p.redirectUri) return null;
103
+ const q = new URL(returnUrl as string).searchParams;
104
+ const once = (name: string): string | null => {
105
+ const all = q.getAll(name);
106
+ return all.length === 1 ? all[0] : all.length === 0 ? null : '\u0000'; // a repeated parameter is ambiguous: refused below
107
+ };
108
+ const responseType = once('response_type');
109
+ if (responseType !== null && responseType !== 'code') return null;
110
+ if (once('client_id') !== p.clientId) return null;
111
+ if (once('redirect_uri') !== p.redirectUri) return null;
112
+ const challenge = once('code_challenge');
113
+ const method = once('code_challenge_method');
114
+ const state = once('state');
115
+ const scope = once('scope');
116
+ if (challenge === null || !CHALLENGE_RE.test(challenge)) return null;
117
+ if (method !== 'S256') return null;
118
+ if (state === null || !STATE_RE.test(state)) return null;
119
+ if (scope !== null && !SCOPE_RE.test(scope)) return null;
120
+
121
+ const out = new URLSearchParams();
122
+ out.set('response_type', 'code');
123
+ out.set('client_id', p.clientId);
124
+ out.set('redirect_uri', p.redirectUri);
125
+ if (scope !== null) out.set('scope', scope);
126
+ out.set('state', state);
127
+ out.set('code_challenge', challenge);
128
+ out.set('code_challenge_method', 'S256');
129
+ return { url: `${new URL(p.idpBaseUrl).origin}${AUTHORIZE_PATH}?${out.toString()}`, state };
130
+ }
131
+
132
+ /**
133
+ * The IdP's answer to the server-side authorize call. Returns the RELATIVE path+query to send the browser to, or null (refuse).
134
+ * Only a redirect whose Location is EXACTLY the registered redirect_uri (origin + path), with a code and the state we sent and no
135
+ * error, qualifies. The relayed value is REBUILT from the validated code and state, never copied from the Location.
136
+ */
137
+ export function relayRegisteredCallback(status: number, location: string | null | undefined, redirectUri: string, sentState: string): string | null {
138
+ if (status < 300 || status > 399 || typeof location !== 'string' || location === '') return null;
139
+ let loc: URL;
140
+ let reg: URL;
141
+ try {
142
+ reg = new URL(redirectUri);
143
+ loc = new URL(location, reg.origin);
144
+ } catch {
145
+ return null;
146
+ }
147
+ if (loc.origin !== reg.origin || loc.pathname !== reg.pathname) return null;
148
+ if (loc.searchParams.has('error')) return null;
149
+ const codes = loc.searchParams.getAll('code');
150
+ const states = loc.searchParams.getAll('state');
151
+ if (codes.length !== 1 || !/^[A-Za-z0-9._~+/=-]{8,512}$/.test(codes[0])) return null;
152
+ if (states.length !== 1 || states[0] !== sentState) return null;
153
+ return `${reg.pathname}?${new URLSearchParams({ code: codes[0], state: sentState }).toString()}`;
154
+ }
155
+
156
+ /**
157
+ * The resume must be a same-site navigation. Sec-Fetch-Site decides when the browser sends it; otherwise Referer must be this
158
+ * app's own origin; with neither it is refused (a crafted cross-site link must not make the victim's browser trigger authorize
159
+ * with the victim's token).
160
+ */
161
+ export function isSameSiteResume(headers: { get(name: string): string | null }, appOrigin: string): boolean {
162
+ const sfs = headers.get('sec-fetch-site');
163
+ // same-origin or none only: a sibling subdomain ('same-site') is not this app.
164
+ if (sfs !== null) return sfs === 'same-origin' || sfs === 'none';
165
+ const referer = headers.get('referer');
166
+ if (!referer) return false;
167
+ try {
168
+ return new URL(referer).origin === appOrigin;
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Binds the resume to a browser that STARTED this app's OAuth flow: better-auth (storeStateStrategy 'cookie') sets an
176
+ * `oauth_state` cookie (Max-Age 600; name may carry a `__Secure-` and an app prefix) when sign-in begins. Its value is sealed, so only
177
+ * its presence is checked; the state MATCH is enforced by better-auth's callback, which fails closed. A crafted link opened in a
178
+ * browser that never began the flow has no such cookie and is refused here, before the user's token is used.
179
+ */
180
+ export function hasOAuthStateCookie(cookieHeader: string | null | undefined): boolean {
181
+ if (typeof cookieHeader !== 'string') return false;
182
+ return cookieHeader.split(';').some((part) => {
183
+ const i = part.indexOf('=');
184
+ const name = (i < 0 ? part : part.slice(0, i)).trim();
185
+ return /(^|[._-])oauth_state$/.test(name) && i >= 0 && part.slice(i + 1).trim() !== '';
186
+ });
187
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * PAY-1777 item 5 (QAPert-NightHawk, PR 663 G4 thread 4395; coverage widened per BAPert 64034): THE way a server-side call
3
+ * that carries a user's (or a provisional) bearer token talks to the identity service.
4
+ *
5
+ * A bearer must never follow a redirect. Modern fetch drops Authorization on a CROSS-origin hop, but a same-origin hop - or
6
+ * an older runtime - does not, and we do not rely on that. So:
7
+ * - the request is always sent with redirect: 'manual' (set AFTER the caller's init, so no caller can switch it back);
8
+ * - any 3xx, or an opaque redirect, is never followed and never relayed: the caller receives a synthetic
9
+ * 502 { success:false, error:{ code:'IDP_UNREACHABLE' } } Response instead, which every existing non-2xx branch at the
10
+ * call sites already handles. Every other response is returned untouched.
11
+ *
12
+ * Moved from VibeID-Customer-Portal (src/lib/idp/bearer-fetch.ts) into the package by PAY-2302; the portal's gate
13
+ * (testing/qa/idp-bearer-no-redirect-gate.js) keeps inventorying its own Authorization-bearing fetches.
14
+ */
15
+ export const REDIRECT_REFUSED_CODE = 'IDP_UNREACHABLE';
16
+
17
+ export function isRedirectResponse(res: Response): boolean {
18
+ return res.type === 'opaqueredirect' || (res.status >= 300 && res.status < 400);
19
+ }
20
+
21
+ export async function bearerFetch(input: string | URL, init: RequestInit = {}): Promise<Response> {
22
+ const res = await fetch(input, { ...init, redirect: 'manual' });
23
+ if (!isRedirectResponse(res)) return res;
24
+ return new Response(
25
+ JSON.stringify({
26
+ success: false,
27
+ error: { code: REDIRECT_REFUSED_CODE, message: 'The identity service answered with a redirect; the call was not followed' },
28
+ }),
29
+ { status: 502, headers: { 'Content-Type': 'application/json' } },
30
+ );
31
+ }
@@ -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
+ }