@payez/next-mvp 4.5.7 → 4.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/api-handlers/auth/credential-login-email-code.d.ts +24 -0
  2. package/dist/api-handlers/auth/credential-login-email-code.js +83 -0
  3. package/dist/api-handlers/auth/credential-login.d.ts +41 -0
  4. package/dist/api-handlers/auth/credential-login.js +858 -0
  5. package/dist/api-handlers/oauth/resume.d.ts +16 -0
  6. package/dist/api-handlers/oauth/resume.js +207 -0
  7. package/dist/auth/better-auth.d.ts +14 -2
  8. package/dist/auth/better-auth.js +59 -34
  9. package/dist/auth/idp-oauth.d.ts +106 -0
  10. package/dist/auth/idp-oauth.js +280 -0
  11. package/dist/auth/safe-callback.js +10 -2
  12. package/dist/components/auth/CredentialSignInForm.d.ts +33 -0
  13. package/dist/components/auth/CredentialSignInForm.js +134 -0
  14. package/dist/lib/authorize-resume.d.ts +87 -0
  15. package/dist/lib/authorize-resume.js +190 -0
  16. package/dist/lib/bearer-fetch.d.ts +17 -0
  17. package/dist/lib/bearer-fetch.js +32 -0
  18. package/dist/lib/code-step-copy.d.ts +53 -0
  19. package/dist/lib/code-step-copy.js +73 -0
  20. package/dist/lib/credential-sign-in-client.d.ts +59 -0
  21. package/dist/lib/credential-sign-in-client.js +89 -0
  22. package/dist/lib/device-id.d.ts +37 -0
  23. package/dist/lib/device-id.js +70 -0
  24. package/dist/lib/lock-window.d.ts +29 -0
  25. package/dist/lib/lock-window.js +53 -0
  26. package/dist/lib/login-error-message.d.ts +18 -0
  27. package/dist/lib/login-error-message.js +47 -0
  28. package/dist/lib/twofa-rejection.d.ts +20 -0
  29. package/dist/lib/twofa-rejection.js +73 -0
  30. package/dist/middleware/create-middleware.d.ts +12 -1
  31. package/dist/middleware/create-middleware.js +19 -5
  32. package/dist/pages/login/page.js +11 -37
  33. package/dist/routes/auth/credential-login-email-code.d.ts +6 -0
  34. package/dist/routes/auth/credential-login-email-code.js +10 -0
  35. package/dist/routes/auth/credential-login.d.ts +6 -0
  36. package/dist/routes/auth/credential-login.js +10 -0
  37. package/dist/routes/oauth/resume.d.ts +11 -0
  38. package/dist/routes/oauth/resume.js +16 -0
  39. package/package.json +1102 -1047
  40. package/src/api-handlers/auth/credential-login-email-code.ts +92 -0
  41. package/src/api-handlers/auth/credential-login.ts +948 -0
  42. package/src/api-handlers/oauth/resume.ts +182 -0
  43. package/src/auth/better-auth.ts +81 -5
  44. package/src/auth/idp-oauth.ts +310 -0
  45. package/src/auth/safe-callback.ts +11 -2
  46. package/src/components/auth/CredentialSignInForm.tsx +240 -0
  47. package/src/lib/authorize-resume.ts +187 -0
  48. package/src/lib/bearer-fetch.ts +31 -0
  49. package/src/lib/code-step-copy.ts +83 -0
  50. package/src/lib/credential-sign-in-client.ts +101 -0
  51. package/src/lib/device-id.ts +67 -0
  52. package/src/lib/lock-window.ts +49 -0
  53. package/src/lib/login-error-message.ts +41 -0
  54. package/src/lib/twofa-rejection.ts +91 -0
  55. package/src/middleware/create-middleware.ts +35 -4
  56. package/src/pages/login/page.tsx +20 -34
  57. package/src/routes/auth/credential-login-email-code.ts +6 -0
  58. package/src/routes/auth/credential-login.ts +6 -0
  59. package/src/routes/oauth/resume.ts +11 -0
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLOCK_TOLERANCE_SECONDS = void 0;
4
+ exports.resolveIdpRedirectUri = resolveIdpRedirectUri;
5
+ exports.amrIncludesMfa = amrIncludesMfa;
6
+ exports.isAddressShaped = isAddressShaped;
7
+ exports.resolveEmail = resolveEmail;
8
+ exports.createIdpOAuthHooks = createIdpOAuthHooks;
9
+ /**
10
+ * PAY-2305 (next-mvp 4.7.4): the two hooks that let better-auth's genericOAuth talk to THIS IdP.
11
+ *
12
+ * WHY THEY EXIST (source read, PayEz-Core master d53f192af, BAPert 74014):
13
+ * - POST /api/oauth/token takes a JSON body (snake_case), not better-auth's default form body, and answers with the
14
+ * Core response envelope { success, data: { access_token, refresh_token, token_type, expires_in, user } }.
15
+ * better-auth's default exchange reads top-level fields and would find nothing.
16
+ * - There is NO id_token and NO userinfo endpoint (deliberate, PAY-1585). The only proof of who signed in is the
17
+ * access token itself: an RS-family bearer JWT (RS512 on dev-93's JWKS, measured) signed by the IdP bearer key (jwks_uri in discovery) with sub, email,
18
+ * roles, amr, token_type.
19
+ *
20
+ * TRUST RULE: a claim is read ONLY from a token whose signature, issuer, expiry and token_type were verified here.
21
+ * Never base64-decode and believe. Only RSA signatures are accepted (the RS and PS families; the JWKS key's own declared alg is binding), so a token
22
+ * re-signed with HS256 using the public key as the secret, or alg none, is refused. The `aud` of an IdP bearer is the IdP's public constant, not this client, so it is not a
23
+ * binding; the binding to THIS client is the authorization code + PKCE verifier + exact redirect_uri that Core checks.
24
+ *
25
+ * The redirect_uri sent here MUST be byte-identical at the authorize step and the token step (Core compares it
26
+ * Ordinal at the token step) and equal to the registered {site_url}/api/auth/callback (Core compares it exactly,
27
+ * case-insensitively, at the authorize step). Both come from ONE value: the `redirectURI` of the provider config.
28
+ */
29
+ const jose_1 = require("jose");
30
+ const DISCOVERY_TTL_MS = 10 * 60 * 1000;
31
+ const HTTP_TIMEOUT_MS = 10_000;
32
+ /** The URI sent at authorize AND token time. Explicit env wins; else the registered {app}/api/auth/callback form. */
33
+ function resolveIdpRedirectUri(appBaseUrl, env = process.env) {
34
+ const explicit = env.IDP_OAUTH_REDIRECT_URI?.trim();
35
+ if (explicit)
36
+ return explicit;
37
+ return appBaseUrl.replace(/\/+$/, '') + '/api/auth/callback';
38
+ }
39
+ /** amr arrives as an array, a JSON-array string, or a delimited string (Core's own reader accepts all three). */
40
+ function amrIncludesMfa(amr) {
41
+ let values = [];
42
+ if (Array.isArray(amr))
43
+ values = amr;
44
+ else if (typeof amr === 'string') {
45
+ const t = amr.trim();
46
+ if (t.startsWith('[')) {
47
+ try {
48
+ const parsed = JSON.parse(t);
49
+ if (Array.isArray(parsed))
50
+ values = parsed;
51
+ }
52
+ catch {
53
+ values = [];
54
+ }
55
+ }
56
+ else {
57
+ values = t.split(/[\s,]+/);
58
+ }
59
+ }
60
+ return values.some((v) => typeof v === 'string' && v.trim().toLowerCase() === 'mfa');
61
+ }
62
+ /** Max skew accepted on nbf/exp/iat when verifying the IdP access token. */
63
+ exports.CLOCK_TOLERANCE_SECONDS = 30;
64
+ /**
65
+ * Address shape, a POSITIVE character rule (PAY-2337, Scout 74285): the local part may contain only [A-Za-z0-9] and . _ % + - ' ; the domain only
66
+ * [A-Za-z0-9-] labels joined by dots; one @, <= 254 total, local <= 64, no leading/trailing/double dot in the local part, a dotted domain.
67
+ * Everything else is NOT an address, and in particular a MASK: Core masks data.user.email on purpose (MaskedEmailJsonConverter), today with '*',
68
+ * tomorrow maybe a bullet, an ellipsis or an 'x' run; a blacklist of one glyph would pass the next mask. Not a deliverability check.
69
+ */
70
+ function isAddressShaped(v) {
71
+ if (typeof v !== 'string' || v.length === 0 || v.length > 254)
72
+ return false;
73
+ if (!/^[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+$/.test(v))
74
+ return false;
75
+ const [local, domain] = v.split('@');
76
+ if (local.length > 64 || local.startsWith('.') || local.endsWith('.') || local.includes('..'))
77
+ return false;
78
+ return /^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(domain) && !domain.startsWith('-') && !domain.endsWith('-');
79
+ }
80
+ /**
81
+ * The account address (BAPert 74193 / 74196, 4.7.8). Core's code-flow access token has NO email claim; its sub and ws-identity name claim are
82
+ * both user.UserName, which is a LOGIN, not the mailbox: it may be address-shaped and still differ from the account's Email (4.7.7 vetoed on that
83
+ * and refused every such sign-in, NightHawk 74189). Sources: the token RESPONSE's data.user.email (token endpoint, TLS) and/or the signed token's
84
+ * own email claim; if both are present they must be equal. sub / the name claim are NEITHER a source NOR a veto. Not trimmed. Returns '' on any doubt.
85
+ */
86
+ function resolveEmail(payload, responseEmail) {
87
+ // NOT trimmed: padding or a trailing newline is a malformed address (refused by the shape check), never silently repaired.
88
+ const raw = (v) => (typeof v === 'string' ? v : '');
89
+ const sources = [raw(payload.email), raw(responseEmail)].filter((v) => v.trim() !== '');
90
+ if (sources.length === 0 || !sources.every(isAddressShaped))
91
+ return '';
92
+ const chosen = sources[0];
93
+ const same = (a) => a.toLowerCase() === chosen.toLowerCase();
94
+ if (!sources.every(same))
95
+ return '';
96
+ return chosen;
97
+ }
98
+ function rolesOf(claim) {
99
+ if (Array.isArray(claim))
100
+ return claim.filter((r) => typeof r === 'string' && r.length > 0);
101
+ if (typeof claim === 'string' && claim.trim()) {
102
+ const t = claim.trim();
103
+ if (t.startsWith('[')) {
104
+ try {
105
+ const parsed = JSON.parse(t);
106
+ if (Array.isArray(parsed))
107
+ return parsed.filter((r) => typeof r === 'string' && r.length > 0);
108
+ }
109
+ catch {
110
+ return [];
111
+ }
112
+ }
113
+ return t.split(/[\s,]+/).filter(Boolean);
114
+ }
115
+ return [];
116
+ }
117
+ function createIdpOAuthHooks(opts) {
118
+ const fetchFn = opts.deps?.fetch ?? fetch;
119
+ const now = opts.deps?.now ?? (() => Date.now());
120
+ const getKeySet = opts.deps?.getKeySet ?? ((uri) => (0, jose_1.createRemoteJWKSet)(new URL(uri)));
121
+ let discovery = null;
122
+ const keySets = new Map();
123
+ /** access token -> data.user.email / user_name from the token response, consumed by getUserInfo for THAT token (bounded; never keyed by anything shared). */
124
+ const responseUsers = new Map();
125
+ async function loadDiscovery() {
126
+ if (discovery && now() - discovery.at < DISCOVERY_TTL_MS)
127
+ return discovery.doc;
128
+ const res = await fetchFn(opts.discoveryUrl, {
129
+ headers: { Accept: 'application/json' },
130
+ redirect: 'error',
131
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
132
+ });
133
+ if (!res.ok)
134
+ throw new Error(`IdP discovery returned ${res.status}`);
135
+ const doc = (await res.json());
136
+ if (typeof doc?.token_endpoint !== 'string' || typeof doc?.jwks_uri !== 'string' || typeof doc?.issuer !== 'string') {
137
+ throw new Error('IdP discovery document is missing token_endpoint, jwks_uri or issuer');
138
+ }
139
+ const allowed = new Set([new URL(opts.discoveryUrl).origin, ...(opts.trustedOrigins ?? []).map((o) => o.replace(/\/+$/, ''))]);
140
+ for (const field of ['token_endpoint', 'jwks_uri']) {
141
+ const origin = new URL(doc[field]).origin;
142
+ if (!allowed.has(origin))
143
+ throw new Error(`IdP discovery ${field} points at an untrusted origin (${origin})`);
144
+ }
145
+ discovery = { doc, at: now() }; // only a good document is cached
146
+ return doc;
147
+ }
148
+ /** better-auth `getToken`: JSON body, envelope unwrapped, no data.access_token => refused. */
149
+ async function getToken(data) {
150
+ const doc = await loadDiscovery();
151
+ if (!data.codeVerifier)
152
+ throw new Error('IdP token exchange refused: no PKCE code_verifier');
153
+ const res = await fetchFn(doc.token_endpoint, {
154
+ method: 'POST',
155
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
156
+ redirect: 'error',
157
+ signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
158
+ body: JSON.stringify({
159
+ grant_type: 'authorization_code',
160
+ code: data.code,
161
+ code_verifier: data.codeVerifier,
162
+ // Deliberately NOT data.redirectURI: that is better-auth's own computed callback, not the registered URI.
163
+ redirect_uri: opts.redirectURI,
164
+ client_id: opts.clientId,
165
+ }),
166
+ });
167
+ let body;
168
+ try {
169
+ body = await res.json();
170
+ }
171
+ catch {
172
+ throw new Error(`IdP token response (${res.status}) was not JSON`);
173
+ }
174
+ if (!res.ok) {
175
+ const code = body?.error?.code ?? body?.error ?? body?.code ?? 'unknown';
176
+ throw new Error(`IdP token exchange refused (${res.status}, ${typeof code === 'string' ? code : 'unknown'})`);
177
+ }
178
+ const d = body?.data;
179
+ if (!d || typeof d.access_token !== 'string' || !d.access_token) {
180
+ throw new Error('IdP token response has no data.access_token (envelope not as expected)');
181
+ }
182
+ const expiresIn = typeof d.expires_in === 'number' && d.expires_in > 0 ? d.expires_in : undefined;
183
+ const expires = expiresIn ? now() + expiresIn * 1000 : undefined;
184
+ if (d.user && typeof d.user === 'object' && typeof d.user.email === 'string') {
185
+ if (responseUsers.size >= 64)
186
+ responseUsers.delete(responseUsers.keys().next().value);
187
+ responseUsers.set(d.access_token, { email: d.user.email, userName: typeof d.user.user_name === 'string' ? d.user.user_name : '' });
188
+ }
189
+ opts.onTokens?.({
190
+ accessToken: d.access_token,
191
+ refreshToken: typeof d.refresh_token === 'string' ? d.refresh_token : undefined,
192
+ accessTokenExpires: expires,
193
+ tokenType: typeof d.token_type === 'string' ? d.token_type : undefined,
194
+ user: d.user && typeof d.user === 'object' ? d.user : undefined,
195
+ });
196
+ return {
197
+ tokenType: typeof d.token_type === 'string' ? d.token_type : 'Bearer',
198
+ accessToken: d.access_token,
199
+ refreshToken: typeof d.refresh_token === 'string' ? d.refresh_token : undefined,
200
+ accessTokenExpiresAt: expires ? new Date(expires) : undefined,
201
+ scopes: [],
202
+ };
203
+ }
204
+ /** better-auth `getUserInfo`: the user comes from the VERIFIED access token. Returns null (never a guess) on any doubt. */
205
+ async function getUserInfo(tokens) {
206
+ try {
207
+ if (!tokens?.accessToken)
208
+ return null;
209
+ const doc = await loadDiscovery();
210
+ // A token without a kid is refused: no "first key" fallback. (A kid that is not in the key set is refused by jose.)
211
+ const kid = (0, jose_1.decodeProtectedHeader)(tokens.accessToken).kid;
212
+ if (typeof kid !== 'string' || !kid)
213
+ throw new Error('token header has no kid');
214
+ const jwksUri = doc.jwks_uri;
215
+ let keys = keySets.get(jwksUri);
216
+ if (!keys) {
217
+ keys = getKeySet(jwksUri);
218
+ keySets.set(jwksUri, keys);
219
+ }
220
+ const { payload } = await (0, jose_1.jwtVerify)(tokens.accessToken, keys, {
221
+ // RSA signatures ONLY (RS256/384/512, PS256/384/512; BAPert 74117): never HS* (a token "signed" with the public key as an HMAC
222
+ // secret), never none, never ES. 4.7.4/4.7.5 pinned RS256 from a source read; the live IdP's JWKS (dev-93, kid 46) declares alg RS512
223
+ // and every real access token was refused (NightHawk 74114). Which RS alg is binding is the JWKS KEY's own declared
224
+ // `alg`: jose only offers a JWK to a token whose header alg equals that JWK's `alg`, so a token cannot choose a
225
+ // weaker/other algorithm than the published key says. A JWK with no `alg` accepts any listed RSA alg; a symmetric (oct) key is never usable for these algorithms.
226
+ algorithms: ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512'],
227
+ issuer: opts.issuer ?? doc.issuer,
228
+ currentDate: new Date(now()),
229
+ // The IdP stamps nbf = issue time with no skew and the token is verified in the same second it is minted (NightHawk 74151:
230
+ // "nbf claim timestamp check failed"). 30 s, bounded. jose applies it to exp too: a token is accepted up to 30 s after exp.
231
+ clockTolerance: exports.CLOCK_TOLERANCE_SECONDS,
232
+ });
233
+ if (payload.token_type !== 'bearer_token')
234
+ throw new Error('token_type is not bearer_token');
235
+ if (typeof payload.sub !== 'string' || !payload.sub)
236
+ throw new Error('no sub');
237
+ const hasEmailClaim = typeof payload.email === 'string' && payload.email.trim() !== '';
238
+ const responseUser = responseUsers.get(tokens.accessToken);
239
+ responseUsers.delete(tokens.accessToken);
240
+ // The response user object (UNSIGNED body) must be the TOKEN's user (Scout 74198, DotNetPert-Scout 74202): Core fills data.user.user_name and the
241
+ // signed sub from the same loaded user in one mint, so WHENEVER a response user exists (even if a signed email claim is also present), user_name MUST be present
242
+ // and equal sub (case-insensitive). A different or missing user_name means the address may belong to someone else -> refuse. Does not constrain email == sub.
243
+ if (responseUser && responseUser.userName.trim().toLowerCase() !== payload.sub.trim().toLowerCase()) {
244
+ throw new Error('token response user is missing or does not match the token subject');
245
+ }
246
+ // A MASKED / unusable response address is ABSENT (PAY-2337), not "a different address": a valid signed claim still signs in, and with no claim
247
+ // there is no source. NEVER repaired or unmasked (no prefix match against sub or the claim). Log names only the fact, no value, no length.
248
+ const responseEmailRaw = responseUser?.email ?? '';
249
+ const responseEmailUsable = isAddressShaped(responseEmailRaw);
250
+ const responseMasked = responseEmailRaw.trim() !== '' && !responseEmailUsable;
251
+ if (responseMasked)
252
+ console.warn('[BETTER_AUTH] payez-idp token response address is masked or unusable; ignored');
253
+ const email = resolveEmail(payload, responseEmailUsable ? responseEmailRaw : undefined);
254
+ if (!email) {
255
+ throw new Error(responseMasked ? 'response address is masked' : 'no usable email (needs data.user.email or an email claim, address-shaped, equal when both are present)');
256
+ }
257
+ const name = (typeof payload.name === 'string' && payload.name.trim()) ||
258
+ (typeof payload.full_name === 'string' && payload.full_name.trim()) ||
259
+ email.split('@')[0];
260
+ const claims = {
261
+ sub: payload.sub,
262
+ email,
263
+ name,
264
+ userId: typeof payload.user_id === 'string' || typeof payload.user_id === 'number' ? String(payload.user_id) : undefined,
265
+ roles: rolesOf(payload.roles),
266
+ mfaVerified: amrIncludesMfa(payload.amr),
267
+ // Only the signed token's own email CLAIM can be verified; an address that came from the token response (data.user.email) never asserts it.
268
+ emailVerified: hasEmailClaim && (payload.email_verified === true || payload.email_verified === 'true'),
269
+ };
270
+ opts.onClaims?.(claims);
271
+ return { id: claims.sub, email: claims.email, name: claims.name, emailVerified: claims.emailVerified };
272
+ }
273
+ catch (err) {
274
+ // Reason only, never the token.
275
+ console.warn('[BETTER_AUTH] payez-idp access token refused:', err instanceof Error ? err.message : String(err));
276
+ return null;
277
+ }
278
+ }
279
+ return { getToken, getUserInfo };
280
+ }
@@ -68,6 +68,14 @@ exports.resolveCallbackDestination = resolveCallbackDestination;
68
68
  exports.DEFAULT_CALLBACK = '/';
69
69
  /** The auth surface. A callback pointing back into it causes a redirect cycle. */
70
70
  const AUTH_PREFIX = '/account-auth/';
71
+ /**
72
+ * PAY-2315 (4.7.1): the middleware now treats the public /login page like /account-auth/login (a signed-in user is sent
73
+ * on), so a callback or a resolved path that is /login itself must be refused here too - otherwise /login with no
74
+ * callbackUrl would resolve its own pathname as the destination and redirect to itself forever.
75
+ */
76
+ function isAuthSurface(pathname) {
77
+ return pathname.startsWith(AUTH_PREFIX) || pathname === '/login' || pathname.startsWith('/login/');
78
+ }
71
79
  /**
72
80
  * Synthetic, unreachable base. Only ever used as the resolution origin for the
73
81
  * comparison below - never emitted, never navigated to. `.invalid` is reserved
@@ -95,7 +103,7 @@ function safeCallbackPath(raw, fallback = exports.DEFAULT_CALLBACK) {
95
103
  if (url.origin !== BASE)
96
104
  return fallback;
97
105
  // Loopbacks into the auth surface cause redirect cycles.
98
- if (url.pathname.startsWith(AUTH_PREFIX))
106
+ if (isAuthSurface(url.pathname))
99
107
  return fallback;
100
108
  // PAY-2218: `_rsc` is Next's flight cache-buster. Once skipProxyUrlNormalize lets it reach middleware it leaks
101
109
  // into return targets (`callbackUrl=/overview?_rsc=abc12`, NightHawk 72013); it is never a meaningful part of a
@@ -143,7 +151,7 @@ function safeCallbackPath(raw, fallback = exports.DEFAULT_CALLBACK) {
143
151
  }
144
152
  if (echo.origin !== BASE)
145
153
  return fallback;
146
- if (echo.pathname.startsWith(AUTH_PREFIX))
154
+ if (isAuthSurface(echo.pathname))
147
155
  return fallback;
148
156
  if (echo.pathname + echo.search + echo.hash !== candidate)
149
157
  return fallback;
@@ -0,0 +1,33 @@
1
+ import { type FetchLike } from '../../lib/credential-sign-in-client';
2
+ /**
3
+ * PAY-2302 cut 1b: the package's email + password (+ 2FA code) sign-in form.
4
+ *
5
+ * WHY IT EXISTS. The package's own Better Auth instance has no emailAndPassword, so the login page had no credential form
6
+ * (removed 2026-08-02, BAPert 17586: "restore this form together" with the backend that makes it work). This is that pair:
7
+ * the backend is routes/auth/credential-login (+ credential-login-email-code), which the app mounts at
8
+ * /api/auth/admin-login[/email-code]; this component drives it. Moved from the portal's AdminLoginCard (VibeID-Customer-Portal
9
+ * 3d654917), re-styled with the package's own TraditionalAuthSection instead of the portal's AuthCard chrome.
10
+ *
11
+ * MOUNT IT through the login page's slot, so nothing changes for a consumer that does not opt in:
12
+ * <LoginPage altAuthSlot={<CredentialSignInForm />} />
13
+ * (An app that has not mounted the two routes must NOT mount this form: it would be the dead control 17586 removed.)
14
+ *
15
+ * Two steps, the IdP's own contract (an access token with no refresh token means a second factor is outstanding):
16
+ * 'credentials' - email + password
17
+ * 'code' - the 2FA code; the door parks the provisional bearer in an httpOnly cookie, this step resubmits with the code.
18
+ *
19
+ * After success the browser goes to the callbackUrl, passed through safeCallbackPath (same-origin paths only); when the page
20
+ * carries ?return_url (an IdP authorize request) it goes to the app's /api/oauth/resume instead, which resumes that request.
21
+ */
22
+ interface Props {
23
+ /** Where to go after sign-in. Default: the page's ?callbackUrl, else /dashboard. Always passed through safeCallbackPath. */
24
+ callbackUrl?: string;
25
+ /** Test seam: the fetch used for both doors. */
26
+ fetchImpl?: FetchLike;
27
+ /** Test seam: navigation after success. */
28
+ onSignedIn?: (destination: string) => void;
29
+ showForgotPassword?: boolean;
30
+ }
31
+ export declare function resolveDestination(explicit?: string): string;
32
+ export declare function CredentialSignInForm({ callbackUrl, fetchImpl, onSignedIn, showForgotPassword }: Props): import("react/jsx-runtime").JSX.Element;
33
+ export default CredentialSignInForm;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ 'use client';
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.resolveDestination = resolveDestination;
5
+ exports.CredentialSignInForm = CredentialSignInForm;
6
+ const jsx_runtime_1 = require("react/jsx-runtime");
7
+ const react_1 = require("react");
8
+ const TraditionalAuthSection_1 = require("./TraditionalAuthSection");
9
+ const safe_callback_1 = require("../../auth/safe-callback");
10
+ const authorize_resume_1 = require("../../lib/authorize-resume");
11
+ const code_step_copy_1 = require("../../lib/code-step-copy");
12
+ const credential_sign_in_client_1 = require("../../lib/credential-sign-in-client");
13
+ const inputStyle = {
14
+ borderColor: 'var(--border-default, #e5e7eb)',
15
+ color: 'var(--text-primary, #111827)',
16
+ background: 'var(--bg-input, white)',
17
+ };
18
+ function resolveDestination(explicit) {
19
+ let raw = explicit;
20
+ let returnUrl = null;
21
+ if (typeof window !== 'undefined') {
22
+ const params = new URLSearchParams(window.location.search);
23
+ if (raw === undefined)
24
+ raw = params.get('callbackUrl') ?? undefined;
25
+ // PAY-2302 cut 2: an IdP that sent the user here mid-authorize (?return_url=<IdP authorize request>) must get the
26
+ // authorize request resumed after sign-in. The href points at the app's OWN /api/oauth/resume, which validates the
27
+ // URL against IDP_URL server-side; nothing absolute is navigated to from here, and the result is still guarded.
28
+ returnUrl = params.get('return_url');
29
+ }
30
+ return (0, safe_callback_1.safeCallbackPath)((0, authorize_resume_1.authorizeResumeHref)(returnUrl), (0, safe_callback_1.safeCallbackPath)(raw, '/dashboard'));
31
+ }
32
+ function CredentialSignInForm({ callbackUrl, fetchImpl, onSignedIn, showForgotPassword = false }) {
33
+ const [step, setStep] = (0, react_1.useState)('credentials');
34
+ const [email, setEmail] = (0, react_1.useState)('');
35
+ const [password, setPassword] = (0, react_1.useState)('');
36
+ const [code, setCode] = (0, react_1.useState)('');
37
+ const [busy, setBusy] = (0, react_1.useState)(false);
38
+ const [error, setError] = (0, react_1.useState)(null);
39
+ const [fieldError, setFieldError] = (0, react_1.useState)(null);
40
+ const [codeRequest, setCodeRequest] = (0, react_1.useState)(code_step_copy_1.NO_CODE_REQUEST);
41
+ const [offerEmailCode, setOfferEmailCode] = (0, react_1.useState)(false);
42
+ const [emailCodeMsg, setEmailCodeMsg] = (0, react_1.useState)(null);
43
+ async function submit(withCode) {
44
+ setBusy(true);
45
+ setError(null);
46
+ setOfferEmailCode(false);
47
+ try {
48
+ const r = await (0, credential_sign_in_client_1.credentialSignIn)({ email, password, code: withCode }, fetchImpl);
49
+ if (r.kind === 'success') {
50
+ const destination = resolveDestination(callbackUrl);
51
+ if (onSignedIn)
52
+ onSignedIn(destination);
53
+ else
54
+ window.location.href = destination;
55
+ return;
56
+ }
57
+ if (r.kind === 'two_factor') {
58
+ setCodeRequest(r.codeRequest);
59
+ setStep('code');
60
+ return;
61
+ }
62
+ setError(r.message);
63
+ if (r.kind === 'error')
64
+ setOfferEmailCode(r.offerEmailCode);
65
+ }
66
+ finally {
67
+ setBusy(false);
68
+ }
69
+ }
70
+ function onCredentialsSubmit(e) {
71
+ e.preventDefault();
72
+ const invalid = (0, credential_sign_in_client_1.validateCredentials)(email, password);
73
+ if (invalid) {
74
+ setFieldError(invalid.email ?? invalid.password ?? null);
75
+ return;
76
+ }
77
+ setFieldError(null);
78
+ void submit();
79
+ }
80
+ function onCodeSubmit(e) {
81
+ e.preventDefault();
82
+ const trimmed = code.trim();
83
+ if (!trimmed) {
84
+ setFieldError('Enter your authentication code.');
85
+ return;
86
+ }
87
+ setFieldError(null);
88
+ void submit(trimmed);
89
+ }
90
+ function onBack() {
91
+ setStep('credentials');
92
+ setCodeRequest(code_step_copy_1.NO_CODE_REQUEST);
93
+ setCode('');
94
+ setFieldError(null);
95
+ setError(null);
96
+ setOfferEmailCode(false);
97
+ setEmailCodeMsg(null);
98
+ }
99
+ async function askForEmailCode() {
100
+ setBusy(true);
101
+ setEmailCodeMsg(null);
102
+ try {
103
+ const r = await (0, credential_sign_in_client_1.requestEmailCode)(fetchImpl);
104
+ if (r.kind === 'requested') {
105
+ setCodeRequest(r.codeRequest);
106
+ setError(null);
107
+ setOfferEmailCode(false);
108
+ setEmailCodeMsg('We asked for a code to be emailed to you. Enter it above when it arrives.');
109
+ }
110
+ else {
111
+ setEmailCodeMsg(r.message);
112
+ }
113
+ }
114
+ finally {
115
+ setBusy(false);
116
+ }
117
+ }
118
+ const problem = fieldError ?? error;
119
+ const problemLine = problem && ((0, jsx_runtime_1.jsx)("p", { role: "alert", "data-testid": "credential-sign-in-error", className: "text-sm mt-3", style: { color: 'var(--color-error, #ef4444)' }, children: problem }));
120
+ if (step === 'code') {
121
+ return ((0, jsx_runtime_1.jsxs)("div", { "data-testid": "credential-sign-in-code-step", className: "text-left", children: [(0, jsx_runtime_1.jsx)("p", { className: "text-sm mb-4", style: { color: 'var(--text-primary, #111827)' }, children: (0, code_step_copy_1.codeStepInstruction)(email, codeRequest) }), (0, jsx_runtime_1.jsxs)("form", { onSubmit: onCodeSubmit, noValidate: true, className: "space-y-4", children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("label", { htmlFor: "credential-code", className: "block text-sm font-medium mb-2", style: { color: 'var(--text-primary, #111827)' }, children: "Authentication code" }), (0, jsx_runtime_1.jsx)("input", { id: "credential-code", name: "code", type: "text", inputMode: "numeric", autoComplete: "one-time-code", required: true, placeholder: "000000", value: code, disabled: busy, onChange: (e) => {
122
+ setCode(e.target.value);
123
+ setFieldError(null);
124
+ }, className: "w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 disabled:opacity-50", style: inputStyle })] }), (0, jsx_runtime_1.jsx)("button", { type: "submit", disabled: busy, 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", style: { background: 'var(--btn-primary-bg, #11B588)', color: 'var(--btn-primary-text, white)' }, children: busy ? 'Verifying…' : 'Verify' })] }), (0, jsx_runtime_1.jsx)("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)' }, children: "Back" }), problemLine, (offerEmailCode || emailCodeMsg) && ((0, jsx_runtime_1.jsxs)("div", { "data-testid": "email-code-offer", className: "mt-4", children: [offerEmailCode && ((0, jsx_runtime_1.jsx)("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)' }, children: "Email me a code instead" })), emailCodeMsg && ((0, jsx_runtime_1.jsx)("p", { role: "status", "data-testid": "email-code-offer-msg", className: "text-sm mt-2", style: { color: 'var(--text-primary, #111827)' }, children: emailCodeMsg }))] }))] }));
125
+ }
126
+ return ((0, jsx_runtime_1.jsxs)("div", { "data-testid": "credential-sign-in", className: "text-left", children: [(0, jsx_runtime_1.jsx)(TraditionalAuthSection_1.TraditionalAuthSection, { email: email, password: password, onEmailChange: (v) => {
127
+ setEmail(v);
128
+ setFieldError(null);
129
+ }, onPasswordChange: (v) => {
130
+ setPassword(v);
131
+ setFieldError(null);
132
+ }, onSubmit: onCredentialsSubmit, isLoading: busy, buttonText: "Sign in", showForgotPassword: showForgotPassword }), problemLine] }));
133
+ }
134
+ exports.default = CredentialSignInForm;
@@ -0,0 +1,87 @@
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 declare const AUTHORIZE_RESUME_ROUTE = "/api/oauth/resume";
15
+ /** True only for `<IDP_URL origin>/api/oauth/authorize` (path case-insensitive, as ASP.NET routes). */
16
+ export declare function isIdpAuthorizeUrl(candidate: string | null | undefined, idpBaseUrl: string): boolean;
17
+ /**
18
+ * Server side: the redirect target, REBUILT from trusted parts - IDP_URL's origin and the authorize path
19
+ * are ours; only the query string comes from the request. Null unless isIdpAuthorizeUrl holds.
20
+ */
21
+ export declare function idpAuthorizeRedirect(candidate: string | null | undefined, idpBaseUrl: string): string | null;
22
+ /**
23
+ * Client side: the SAME-ORIGIN portal path that resumes authorize, or null when the IdP did not ask for one.
24
+ * Callers still pass the result through safeCallbackPath before navigating.
25
+ *
26
+ * WHY THE ASTERISK IS RE-ENCODED (PAY-1547, measured by NextPert 59939, completeness measured here).
27
+ * One consumer of this value is `authClient.signIn.social({ callbackURL })`, which POSTs to better-auth
28
+ * and is validated by its own originCheckMiddleware BEFORE anything redirects. For a relative path that
29
+ * check is decided entirely by one regex (better-auth 1.5.6, auth/trusted-origins.mjs:16 - the
30
+ * `allowRelativePaths` branch, and api/middlewares/origin-check.mjs:51 passes
31
+ * `allowRelativePaths: label !== 'origin'`, so it IS that branch for a callbackURL):
32
+ *
33
+ * /^\/(?!\/|\\|%2f|%5c)[\w\-.\+\/@]*(?:\?[\w\-.\+\/=&%@]*)?$/
34
+ *
35
+ * A character this helper emits RAW and that charset rejects is a hard 403 INVALID_CALLBACK_URL on the
36
+ * Google button - not a silent fallback. Measured exhaustively over printable ASCII by diffing what
37
+ * `URLSearchParams` leaves raw against that charset: the raw set is alphanumerics plus `* - . _`, and
38
+ * *** `*` IS THE ONLY REJECTED MEMBER *** (`%` is permitted, which is why every other special character
39
+ * survives - URLSearchParams already percent-encoded it).
40
+ *
41
+ * `*` is reachable because `state` and `scope` are chosen by the OAuth CLIENT, not by us, so we cannot
42
+ * decline to emit it. `%2A` is the same character to every parser: re-reading this query string returns
43
+ * the byte-identical `return_url` (asserted in test/authorize-resume.test.cjs), so this is an encoding
44
+ * change and NOT a value change. It is applied here, at the ONE computation, rather than at the sinks -
45
+ * the two `window.location.href` sinks are browser navigations that touch no library and for which this
46
+ * is a behavioural no-op, so there is no reason to make them each carry it.
47
+ */
48
+ export declare function authorizeResumeHref(returnUrl: string | null | undefined): string | null;
49
+ export interface ServerAuthorizeParams {
50
+ idpBaseUrl: string;
51
+ /** This app's IdP client slug (CLIENT_ID). The request's client_id must equal it. */
52
+ clientId: string;
53
+ /** The app's REGISTERED redirect_uri, e.g. http://localhost:3000/api/auth/callback. The request's redirect_uri must equal it exactly. */
54
+ redirectUri: string;
55
+ }
56
+ export interface ServerAuthorizeRequest {
57
+ /** Built from constants + validated pieces only. This is what gets fetched. */
58
+ url: string;
59
+ state: string;
60
+ }
61
+ /**
62
+ * Build the authorize URL to call, or null (refuse). Origin, path, response_type, client_id and redirect_uri are OURS; from
63
+ * return_url only code_challenge (+ method, S256 only), state and scope are taken, each charset/length validated. A return_url for
64
+ * another client or another redirect_uri is refused (no "someone else's client"). Unknown extra parameters are NOT forwarded.
65
+ */
66
+ export declare function buildServerAuthorizeRequest(returnUrl: string | null | undefined, p: ServerAuthorizeParams): ServerAuthorizeRequest | null;
67
+ /**
68
+ * The IdP's answer to the server-side authorize call. Returns the RELATIVE path+query to send the browser to, or null (refuse).
69
+ * Only a redirect whose Location is EXACTLY the registered redirect_uri (origin + path), with a code and the state we sent and no
70
+ * error, qualifies. The relayed value is REBUILT from the validated code and state, never copied from the Location.
71
+ */
72
+ export declare function relayRegisteredCallback(status: number, location: string | null | undefined, redirectUri: string, sentState: string): string | null;
73
+ /**
74
+ * The resume must be a same-site navigation. Sec-Fetch-Site decides when the browser sends it; otherwise Referer must be this
75
+ * app's own origin; with neither it is refused (a crafted cross-site link must not make the victim's browser trigger authorize
76
+ * with the victim's token).
77
+ */
78
+ export declare function isSameSiteResume(headers: {
79
+ get(name: string): string | null;
80
+ }, appOrigin: string): boolean;
81
+ /**
82
+ * Binds the resume to a browser that STARTED this app's OAuth flow: better-auth (storeStateStrategy 'cookie') sets an
83
+ * `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
84
+ * its presence is checked; the state MATCH is enforced by better-auth's callback, which fails closed. A crafted link opened in a
85
+ * browser that never began the flow has no such cookie and is refused here, before the user's token is used.
86
+ */
87
+ export declare function hasOAuthStateCookie(cookieHeader: string | null | undefined): boolean;