@payez/next-mvp 4.5.7 → 4.7.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +10 -2
- 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 +12 -1
- package/dist/middleware/create-middleware.js +19 -5
- 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/oauth/resume.d.ts +11 -0
- package/dist/routes/oauth/resume.js +16 -0
- package/package.json +1102 -1047
- 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 +11 -2
- 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 +35 -4
- 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/oauth/resume.ts +11 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import React, { useState } from 'react';
|
|
4
|
+
import { TraditionalAuthSection } from './TraditionalAuthSection';
|
|
5
|
+
import { safeCallbackPath } from '../../auth/safe-callback';
|
|
6
|
+
import { authorizeResumeHref } from '../../lib/authorize-resume';
|
|
7
|
+
import { NO_CODE_REQUEST, codeStepInstruction, type CodeRequest } from '../../lib/code-step-copy';
|
|
8
|
+
import {
|
|
9
|
+
credentialSignIn,
|
|
10
|
+
requestEmailCode,
|
|
11
|
+
validateCredentials,
|
|
12
|
+
type FetchLike,
|
|
13
|
+
} from '../../lib/credential-sign-in-client';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* PAY-2302 cut 1b: the package's email + password (+ 2FA code) sign-in form.
|
|
17
|
+
*
|
|
18
|
+
* WHY IT EXISTS. The package's own Better Auth instance has no emailAndPassword, so the login page had no credential form
|
|
19
|
+
* (removed 2026-08-02, BAPert 17586: "restore this form together" with the backend that makes it work). This is that pair:
|
|
20
|
+
* the backend is routes/auth/credential-login (+ credential-login-email-code), which the app mounts at
|
|
21
|
+
* /api/auth/admin-login[/email-code]; this component drives it. Moved from the portal's AdminLoginCard (VibeID-Customer-Portal
|
|
22
|
+
* 3d654917), re-styled with the package's own TraditionalAuthSection instead of the portal's AuthCard chrome.
|
|
23
|
+
*
|
|
24
|
+
* MOUNT IT through the login page's slot, so nothing changes for a consumer that does not opt in:
|
|
25
|
+
* <LoginPage altAuthSlot={<CredentialSignInForm />} />
|
|
26
|
+
* (An app that has not mounted the two routes must NOT mount this form: it would be the dead control 17586 removed.)
|
|
27
|
+
*
|
|
28
|
+
* Two steps, the IdP's own contract (an access token with no refresh token means a second factor is outstanding):
|
|
29
|
+
* 'credentials' - email + password
|
|
30
|
+
* 'code' - the 2FA code; the door parks the provisional bearer in an httpOnly cookie, this step resubmits with the code.
|
|
31
|
+
*
|
|
32
|
+
* After success the browser goes to the callbackUrl, passed through safeCallbackPath (same-origin paths only); when the page
|
|
33
|
+
* carries ?return_url (an IdP authorize request) it goes to the app's /api/oauth/resume instead, which resumes that request.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
interface Props {
|
|
37
|
+
/** Where to go after sign-in. Default: the page's ?callbackUrl, else /dashboard. Always passed through safeCallbackPath. */
|
|
38
|
+
callbackUrl?: string;
|
|
39
|
+
/** Test seam: the fetch used for both doors. */
|
|
40
|
+
fetchImpl?: FetchLike;
|
|
41
|
+
/** Test seam: navigation after success. */
|
|
42
|
+
onSignedIn?: (destination: string) => void;
|
|
43
|
+
showForgotPassword?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const inputStyle: React.CSSProperties = {
|
|
47
|
+
borderColor: 'var(--border-default, #e5e7eb)',
|
|
48
|
+
color: 'var(--text-primary, #111827)',
|
|
49
|
+
background: 'var(--bg-input, white)',
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export function resolveDestination(explicit?: string): string {
|
|
53
|
+
let raw = explicit;
|
|
54
|
+
let returnUrl: string | null = null;
|
|
55
|
+
if (typeof window !== 'undefined') {
|
|
56
|
+
const params = new URLSearchParams(window.location.search);
|
|
57
|
+
if (raw === undefined) raw = params.get('callbackUrl') ?? undefined;
|
|
58
|
+
// PAY-2302 cut 2: an IdP that sent the user here mid-authorize (?return_url=<IdP authorize request>) must get the
|
|
59
|
+
// authorize request resumed after sign-in. The href points at the app's OWN /api/oauth/resume, which validates the
|
|
60
|
+
// URL against IDP_URL server-side; nothing absolute is navigated to from here, and the result is still guarded.
|
|
61
|
+
returnUrl = params.get('return_url');
|
|
62
|
+
}
|
|
63
|
+
return safeCallbackPath(authorizeResumeHref(returnUrl), safeCallbackPath(raw, '/dashboard'));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function CredentialSignInForm({ callbackUrl, fetchImpl, onSignedIn, showForgotPassword = false }: Props) {
|
|
67
|
+
const [step, setStep] = useState<'credentials' | 'code'>('credentials');
|
|
68
|
+
const [email, setEmail] = useState('');
|
|
69
|
+
const [password, setPassword] = useState('');
|
|
70
|
+
const [code, setCode] = useState('');
|
|
71
|
+
const [busy, setBusy] = useState(false);
|
|
72
|
+
const [error, setError] = useState<string | null>(null);
|
|
73
|
+
const [fieldError, setFieldError] = useState<string | null>(null);
|
|
74
|
+
const [codeRequest, setCodeRequest] = useState<CodeRequest>(NO_CODE_REQUEST);
|
|
75
|
+
const [offerEmailCode, setOfferEmailCode] = useState(false);
|
|
76
|
+
const [emailCodeMsg, setEmailCodeMsg] = useState<string | null>(null);
|
|
77
|
+
|
|
78
|
+
async function submit(withCode?: string) {
|
|
79
|
+
setBusy(true);
|
|
80
|
+
setError(null);
|
|
81
|
+
setOfferEmailCode(false);
|
|
82
|
+
try {
|
|
83
|
+
const r = await credentialSignIn({ email, password, code: withCode }, fetchImpl);
|
|
84
|
+
if (r.kind === 'success') {
|
|
85
|
+
const destination = resolveDestination(callbackUrl);
|
|
86
|
+
if (onSignedIn) onSignedIn(destination);
|
|
87
|
+
else window.location.href = destination;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (r.kind === 'two_factor') {
|
|
91
|
+
setCodeRequest(r.codeRequest);
|
|
92
|
+
setStep('code');
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
setError(r.message);
|
|
96
|
+
if (r.kind === 'error') setOfferEmailCode(r.offerEmailCode);
|
|
97
|
+
} finally {
|
|
98
|
+
setBusy(false);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function onCredentialsSubmit(e: React.FormEvent) {
|
|
103
|
+
e.preventDefault();
|
|
104
|
+
const invalid = validateCredentials(email, password);
|
|
105
|
+
if (invalid) {
|
|
106
|
+
setFieldError(invalid.email ?? invalid.password ?? null);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
setFieldError(null);
|
|
110
|
+
void submit();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function onCodeSubmit(e: React.FormEvent) {
|
|
114
|
+
e.preventDefault();
|
|
115
|
+
const trimmed = code.trim();
|
|
116
|
+
if (!trimmed) {
|
|
117
|
+
setFieldError('Enter your authentication code.');
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
setFieldError(null);
|
|
121
|
+
void submit(trimmed);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function onBack() {
|
|
125
|
+
setStep('credentials');
|
|
126
|
+
setCodeRequest(NO_CODE_REQUEST);
|
|
127
|
+
setCode('');
|
|
128
|
+
setFieldError(null);
|
|
129
|
+
setError(null);
|
|
130
|
+
setOfferEmailCode(false);
|
|
131
|
+
setEmailCodeMsg(null);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function askForEmailCode() {
|
|
135
|
+
setBusy(true);
|
|
136
|
+
setEmailCodeMsg(null);
|
|
137
|
+
try {
|
|
138
|
+
const r = await requestEmailCode(fetchImpl);
|
|
139
|
+
if (r.kind === 'requested') {
|
|
140
|
+
setCodeRequest(r.codeRequest);
|
|
141
|
+
setError(null);
|
|
142
|
+
setOfferEmailCode(false);
|
|
143
|
+
setEmailCodeMsg('We asked for a code to be emailed to you. Enter it above when it arrives.');
|
|
144
|
+
} else {
|
|
145
|
+
setEmailCodeMsg(r.message);
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
setBusy(false);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const problem = fieldError ?? error;
|
|
153
|
+
const problemLine = problem && (
|
|
154
|
+
<p role="alert" data-testid="credential-sign-in-error" className="text-sm mt-3" style={{ color: 'var(--color-error, #ef4444)' }}>
|
|
155
|
+
{problem}
|
|
156
|
+
</p>
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
if (step === 'code') {
|
|
160
|
+
return (
|
|
161
|
+
<div data-testid="credential-sign-in-code-step" className="text-left">
|
|
162
|
+
<p className="text-sm mb-4" style={{ color: 'var(--text-primary, #111827)' }}>{codeStepInstruction(email, codeRequest)}</p>
|
|
163
|
+
<form onSubmit={onCodeSubmit} noValidate className="space-y-4">
|
|
164
|
+
<div>
|
|
165
|
+
<label htmlFor="credential-code" className="block text-sm font-medium mb-2" style={{ color: 'var(--text-primary, #111827)' }}>
|
|
166
|
+
Authentication code
|
|
167
|
+
</label>
|
|
168
|
+
<input
|
|
169
|
+
id="credential-code"
|
|
170
|
+
name="code"
|
|
171
|
+
type="text"
|
|
172
|
+
inputMode="numeric"
|
|
173
|
+
autoComplete="one-time-code"
|
|
174
|
+
required
|
|
175
|
+
placeholder="000000"
|
|
176
|
+
value={code}
|
|
177
|
+
disabled={busy}
|
|
178
|
+
onChange={(e) => {
|
|
179
|
+
setCode(e.target.value);
|
|
180
|
+
setFieldError(null);
|
|
181
|
+
}}
|
|
182
|
+
className="w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 disabled:opacity-50"
|
|
183
|
+
style={inputStyle}
|
|
184
|
+
/>
|
|
185
|
+
</div>
|
|
186
|
+
<button
|
|
187
|
+
type="submit"
|
|
188
|
+
disabled={busy}
|
|
189
|
+
className="w-full py-3 px-4 rounded-lg font-semibold focus:outline-none focus:ring-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
|
190
|
+
style={{ background: 'var(--btn-primary-bg, #11B588)', color: 'var(--btn-primary-text, white)' }}
|
|
191
|
+
>
|
|
192
|
+
{busy ? 'Verifying…' : 'Verify'}
|
|
193
|
+
</button>
|
|
194
|
+
</form>
|
|
195
|
+
<button type="button" onClick={onBack} disabled={busy} className="text-sm underline mt-4" style={{ background: 'none', border: 'none', padding: 0, color: 'var(--text-muted, #6b7280)' }}>
|
|
196
|
+
Back
|
|
197
|
+
</button>
|
|
198
|
+
{problemLine}
|
|
199
|
+
{(offerEmailCode || emailCodeMsg) && (
|
|
200
|
+
<div data-testid="email-code-offer" className="mt-4">
|
|
201
|
+
{offerEmailCode && (
|
|
202
|
+
<button type="button" onClick={() => void askForEmailCode()} disabled={busy} className="text-sm font-semibold underline" style={{ background: 'none', border: 'none', padding: 0, color: 'var(--text-primary, #111827)' }}>
|
|
203
|
+
Email me a code instead
|
|
204
|
+
</button>
|
|
205
|
+
)}
|
|
206
|
+
{emailCodeMsg && (
|
|
207
|
+
<p role="status" data-testid="email-code-offer-msg" className="text-sm mt-2" style={{ color: 'var(--text-primary, #111827)' }}>
|
|
208
|
+
{emailCodeMsg}
|
|
209
|
+
</p>
|
|
210
|
+
)}
|
|
211
|
+
</div>
|
|
212
|
+
)}
|
|
213
|
+
</div>
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return (
|
|
218
|
+
<div data-testid="credential-sign-in" className="text-left">
|
|
219
|
+
<TraditionalAuthSection
|
|
220
|
+
email={email}
|
|
221
|
+
password={password}
|
|
222
|
+
onEmailChange={(v) => {
|
|
223
|
+
setEmail(v);
|
|
224
|
+
setFieldError(null);
|
|
225
|
+
}}
|
|
226
|
+
onPasswordChange={(v) => {
|
|
227
|
+
setPassword(v);
|
|
228
|
+
setFieldError(null);
|
|
229
|
+
}}
|
|
230
|
+
onSubmit={onCredentialsSubmit}
|
|
231
|
+
isLoading={busy}
|
|
232
|
+
buttonText="Sign in"
|
|
233
|
+
showForgotPassword={showForgotPassword}
|
|
234
|
+
/>
|
|
235
|
+
{problemLine}
|
|
236
|
+
</div>
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export default CredentialSignInForm;
|
|
@@ -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 };
|