@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,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;
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AUTHORIZE_RESUME_ROUTE = void 0;
4
+ exports.isIdpAuthorizeUrl = isIdpAuthorizeUrl;
5
+ exports.idpAuthorizeRedirect = idpAuthorizeRedirect;
6
+ exports.authorizeResumeHref = authorizeResumeHref;
7
+ exports.buildServerAuthorizeRequest = buildServerAuthorizeRequest;
8
+ exports.relayRegisteredCallback = relayRegisteredCallback;
9
+ exports.isSameSiteResume = isSameSiteResume;
10
+ exports.hasOAuthStateCookie = hasOAuthStateCookie;
11
+ /**
12
+ * PAY-2302 cut 2: moved VERBATIM (logic unchanged) from VibeID-Customer-Portal src/lib/auth/authorize-resume.ts.
13
+ * PAY-1500 (portal half of PAY-1479): resume the IdP OAuth authorize request after 2FA.
14
+ *
15
+ * The IdP sends an OAuth principal who still owes 2FA to the portal's /account-auth/verify-code with
16
+ * ?next_step=enroll_mfa|mfa_verify&callbackUrl=<absolute IdP authorize URL>&return_url=<same>
17
+ * (OAuthController.Authorize; hotfix-2 66ca7a8eb routes BOTH cases to verify-code, /account/security is gone). safeCallbackPath rightly refuses that absolute URL,
18
+ * so after 2FA the user used to land on the default page and sign-in never finished.
19
+ *
20
+ * This is NOT a relaxation of safeCallbackPath. The browser is sent to the portal's own
21
+ * /api/oauth/resume, which checks return_url SERVER-SIDE against IDP_URL (origin + the authorize path)
22
+ * and only then redirects. Anything else is refused. IDP_URL never reaches the client.
23
+ */
24
+ exports.AUTHORIZE_RESUME_ROUTE = '/api/oauth/resume';
25
+ const AUTHORIZE_PATH = '/api/oauth/authorize';
26
+ /** True only for `<IDP_URL origin>/api/oauth/authorize` (path case-insensitive, as ASP.NET routes). */
27
+ function isIdpAuthorizeUrl(candidate, idpBaseUrl) {
28
+ if (typeof candidate !== 'string' || candidate === '')
29
+ return false;
30
+ try {
31
+ const u = new URL(candidate);
32
+ const idp = new URL(idpBaseUrl);
33
+ return (u.protocol === 'https:' || u.protocol === 'http:') && u.origin === idp.origin && u.pathname.toLowerCase() === AUTHORIZE_PATH;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ /**
40
+ * Server side: the redirect target, REBUILT from trusted parts - IDP_URL's origin and the authorize path
41
+ * are ours; only the query string comes from the request. Null unless isIdpAuthorizeUrl holds.
42
+ */
43
+ function idpAuthorizeRedirect(candidate, idpBaseUrl) {
44
+ if (!isIdpAuthorizeUrl(candidate, idpBaseUrl))
45
+ return null;
46
+ const query = new URL(candidate).search;
47
+ return `${new URL(idpBaseUrl).origin}/api/OAuth/authorize${query}`;
48
+ }
49
+ /**
50
+ * Client side: the SAME-ORIGIN portal path that resumes authorize, or null when the IdP did not ask for one.
51
+ * Callers still pass the result through safeCallbackPath before navigating.
52
+ *
53
+ * WHY THE ASTERISK IS RE-ENCODED (PAY-1547, measured by NextPert 59939, completeness measured here).
54
+ * One consumer of this value is `authClient.signIn.social({ callbackURL })`, which POSTs to better-auth
55
+ * and is validated by its own originCheckMiddleware BEFORE anything redirects. For a relative path that
56
+ * check is decided entirely by one regex (better-auth 1.5.6, auth/trusted-origins.mjs:16 - the
57
+ * `allowRelativePaths` branch, and api/middlewares/origin-check.mjs:51 passes
58
+ * `allowRelativePaths: label !== 'origin'`, so it IS that branch for a callbackURL):
59
+ *
60
+ * /^\/(?!\/|\\|%2f|%5c)[\w\-.\+\/@]*(?:\?[\w\-.\+\/=&%@]*)?$/
61
+ *
62
+ * A character this helper emits RAW and that charset rejects is a hard 403 INVALID_CALLBACK_URL on the
63
+ * Google button - not a silent fallback. Measured exhaustively over printable ASCII by diffing what
64
+ * `URLSearchParams` leaves raw against that charset: the raw set is alphanumerics plus `* - . _`, and
65
+ * *** `*` IS THE ONLY REJECTED MEMBER *** (`%` is permitted, which is why every other special character
66
+ * survives - URLSearchParams already percent-encoded it).
67
+ *
68
+ * `*` is reachable because `state` and `scope` are chosen by the OAuth CLIENT, not by us, so we cannot
69
+ * decline to emit it. `%2A` is the same character to every parser: re-reading this query string returns
70
+ * the byte-identical `return_url` (asserted in test/authorize-resume.test.cjs), so this is an encoding
71
+ * change and NOT a value change. It is applied here, at the ONE computation, rather than at the sinks -
72
+ * the two `window.location.href` sinks are browser navigations that touch no library and for which this
73
+ * is a behavioural no-op, so there is no reason to make them each carry it.
74
+ */
75
+ function authorizeResumeHref(returnUrl) {
76
+ if (typeof returnUrl !== 'string' || returnUrl === '')
77
+ return null;
78
+ const query = new URLSearchParams({ return_url: returnUrl }).toString().replace(/\*/g, '%2A');
79
+ return `${exports.AUTHORIZE_RESUME_ROUTE}?${query}`;
80
+ }
81
+ const CHALLENGE_RE = /^[A-Za-z0-9_-]{43,128}$/;
82
+ const STATE_RE = /^[A-Za-z0-9._~-]{1,256}$/;
83
+ const SCOPE_RE = /^[A-Za-z0-9:._ -]{1,200}$/;
84
+ /**
85
+ * Build the authorize URL to call, or null (refuse). Origin, path, response_type, client_id and redirect_uri are OURS; from
86
+ * return_url only code_challenge (+ method, S256 only), state and scope are taken, each charset/length validated. A return_url for
87
+ * another client or another redirect_uri is refused (no "someone else's client"). Unknown extra parameters are NOT forwarded.
88
+ */
89
+ function buildServerAuthorizeRequest(returnUrl, p) {
90
+ if (!isIdpAuthorizeUrl(returnUrl, p.idpBaseUrl) || !p.clientId || !p.redirectUri)
91
+ return null;
92
+ const q = new URL(returnUrl).searchParams;
93
+ const once = (name) => {
94
+ const all = q.getAll(name);
95
+ return all.length === 1 ? all[0] : all.length === 0 ? null : '\u0000'; // a repeated parameter is ambiguous: refused below
96
+ };
97
+ const responseType = once('response_type');
98
+ if (responseType !== null && responseType !== 'code')
99
+ return null;
100
+ if (once('client_id') !== p.clientId)
101
+ return null;
102
+ if (once('redirect_uri') !== p.redirectUri)
103
+ return null;
104
+ const challenge = once('code_challenge');
105
+ const method = once('code_challenge_method');
106
+ const state = once('state');
107
+ const scope = once('scope');
108
+ if (challenge === null || !CHALLENGE_RE.test(challenge))
109
+ return null;
110
+ if (method !== 'S256')
111
+ return null;
112
+ if (state === null || !STATE_RE.test(state))
113
+ return null;
114
+ if (scope !== null && !SCOPE_RE.test(scope))
115
+ return null;
116
+ const out = new URLSearchParams();
117
+ out.set('response_type', 'code');
118
+ out.set('client_id', p.clientId);
119
+ out.set('redirect_uri', p.redirectUri);
120
+ if (scope !== null)
121
+ out.set('scope', scope);
122
+ out.set('state', state);
123
+ out.set('code_challenge', challenge);
124
+ out.set('code_challenge_method', 'S256');
125
+ return { url: `${new URL(p.idpBaseUrl).origin}${AUTHORIZE_PATH}?${out.toString()}`, state };
126
+ }
127
+ /**
128
+ * The IdP's answer to the server-side authorize call. Returns the RELATIVE path+query to send the browser to, or null (refuse).
129
+ * Only a redirect whose Location is EXACTLY the registered redirect_uri (origin + path), with a code and the state we sent and no
130
+ * error, qualifies. The relayed value is REBUILT from the validated code and state, never copied from the Location.
131
+ */
132
+ function relayRegisteredCallback(status, location, redirectUri, sentState) {
133
+ if (status < 300 || status > 399 || typeof location !== 'string' || location === '')
134
+ return null;
135
+ let loc;
136
+ let reg;
137
+ try {
138
+ reg = new URL(redirectUri);
139
+ loc = new URL(location, reg.origin);
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ if (loc.origin !== reg.origin || loc.pathname !== reg.pathname)
145
+ return null;
146
+ if (loc.searchParams.has('error'))
147
+ return null;
148
+ const codes = loc.searchParams.getAll('code');
149
+ const states = loc.searchParams.getAll('state');
150
+ if (codes.length !== 1 || !/^[A-Za-z0-9._~+/=-]{8,512}$/.test(codes[0]))
151
+ return null;
152
+ if (states.length !== 1 || states[0] !== sentState)
153
+ return null;
154
+ return `${reg.pathname}?${new URLSearchParams({ code: codes[0], state: sentState }).toString()}`;
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
+ function isSameSiteResume(headers, appOrigin) {
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)
165
+ return sfs === 'same-origin' || sfs === 'none';
166
+ const referer = headers.get('referer');
167
+ if (!referer)
168
+ return false;
169
+ try {
170
+ return new URL(referer).origin === appOrigin;
171
+ }
172
+ catch {
173
+ return false;
174
+ }
175
+ }
176
+ /**
177
+ * Binds the resume to a browser that STARTED this app's OAuth flow: better-auth (storeStateStrategy 'cookie') sets an
178
+ * `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
179
+ * its presence is checked; the state MATCH is enforced by better-auth's callback, which fails closed. A crafted link opened in a
180
+ * browser that never began the flow has no such cookie and is refused here, before the user's token is used.
181
+ */
182
+ function hasOAuthStateCookie(cookieHeader) {
183
+ if (typeof cookieHeader !== 'string')
184
+ return false;
185
+ return cookieHeader.split(';').some((part) => {
186
+ const i = part.indexOf('=');
187
+ const name = (i < 0 ? part : part.slice(0, i)).trim();
188
+ return /(^|[._-])oauth_state$/.test(name) && i >= 0 && part.slice(i + 1).trim() !== '';
189
+ });
190
+ }
@@ -0,0 +1,17 @@
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 declare const REDIRECT_REFUSED_CODE = "IDP_UNREACHABLE";
16
+ export declare function isRedirectResponse(res: Response): boolean;
17
+ export declare function bearerFetch(input: string | URL, init?: RequestInit): Promise<Response>;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDIRECT_REFUSED_CODE = void 0;
4
+ exports.isRedirectResponse = isRedirectResponse;
5
+ exports.bearerFetch = bearerFetch;
6
+ /**
7
+ * PAY-1777 item 5 (QAPert-NightHawk, PR 663 G4 thread 4395; coverage widened per BAPert 64034): THE way a server-side call
8
+ * that carries a user's (or a provisional) bearer token talks to the identity service.
9
+ *
10
+ * A bearer must never follow a redirect. Modern fetch drops Authorization on a CROSS-origin hop, but a same-origin hop - or
11
+ * an older runtime - does not, and we do not rely on that. So:
12
+ * - the request is always sent with redirect: 'manual' (set AFTER the caller's init, so no caller can switch it back);
13
+ * - any 3xx, or an opaque redirect, is never followed and never relayed: the caller receives a synthetic
14
+ * 502 { success:false, error:{ code:'IDP_UNREACHABLE' } } Response instead, which every existing non-2xx branch at the
15
+ * call sites already handles. Every other response is returned untouched.
16
+ *
17
+ * Moved from VibeID-Customer-Portal (src/lib/idp/bearer-fetch.ts) into the package by PAY-2302; the portal's gate
18
+ * (testing/qa/idp-bearer-no-redirect-gate.js) keeps inventorying its own Authorization-bearing fetches.
19
+ */
20
+ exports.REDIRECT_REFUSED_CODE = 'IDP_UNREACHABLE';
21
+ function isRedirectResponse(res) {
22
+ return res.type === 'opaqueredirect' || (res.status >= 300 && res.status < 400);
23
+ }
24
+ async function bearerFetch(input, init = {}) {
25
+ const res = await fetch(input, { ...init, redirect: 'manual' });
26
+ if (!isRedirectResponse(res))
27
+ return res;
28
+ return new Response(JSON.stringify({
29
+ success: false,
30
+ error: { code: exports.REDIRECT_REFUSED_CODE, message: 'The identity service answered with a redirect; the call was not followed' },
31
+ }), { status: 502, headers: { 'Content-Type': 'application/json' } });
32
+ }
@@ -0,0 +1,53 @@
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
+ export type CodeSentVia = 'sms' | 'email' | null;
24
+ export interface CodeRequest {
25
+ /** The door asked for a code to be sent (`codeRequested`, or the older alias `emailSent`). */
26
+ codeRequested: boolean;
27
+ /** Which lane the door actually fired, or null when nothing was sent (a TOTP holder). */
28
+ sentVia: CodeSentVia;
29
+ /**
30
+ * PAY-2314 (4.7.1): present and false ONLY when the door said which factors it accepts (acceptedFactors) and TOTP is not
31
+ * among them. Absent means "the door did not say" (an older door) and keeps the historic authenticator sentence.
32
+ */
33
+ acceptsAuthenticator?: false;
34
+ }
35
+ /** Nothing sent, nothing to say beyond the authenticator. What a card starts with. */
36
+ export declare const NO_CODE_REQUEST: CodeRequest;
37
+ /**
38
+ * Read the door's answer. Total: any shape (null, a string, an array, junk fields) yields a
39
+ * CodeRequest and never throws, so a malformed body degrades to the authenticator-only sentence
40
+ * rather than to a crash or to a claim the door never made.
41
+ */
42
+ export declare function readCodeRequest(body: unknown): CodeRequest;
43
+ /**
44
+ * The sentence, split around the email so a card can render the address however it likes
45
+ * (SignInCard wraps it in <strong>; AdminLoginCard passes a plain-string subtitle).
46
+ * `before + email + after` is the whole sentence.
47
+ */
48
+ export declare function codeStepParts(r: CodeRequest): {
49
+ before: string;
50
+ after: string;
51
+ };
52
+ /** The sentence as one plain string, for a card whose subtitle prop is a string. */
53
+ export declare function codeStepInstruction(email: string, r: CodeRequest): string;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ /**
3
+ * PAY-1576 - the 2FA "enter your code" step, described ONCE.
4
+ *
5
+ * WHY THIS FILE EXISTS. Two cards render the same step for the same door
6
+ * (POST /api/auth/admin-login, the package's routes/auth/credential-login, answers `requiresTwoFactor` with `sentVia` /
7
+ * `codeRequested` / `emailSent`):
8
+ * - SignInCard.tsx (fixed in 267479 to name every lane the box accepts)
9
+ * - AdminLoginCard.tsx (NOT fixed: it said "from your authenticator app" for every user and
10
+ * discarded the door's answer, so an email-code user was sent to a
11
+ * factor they do not have; live allowed2FAMethods=[emailcode,totp])
12
+ * 267479 reached only one of the twins. A comment cannot stop that recurring; a shared helper can,
13
+ * because there is then only one place the sentence is built and a static gate
14
+ * (testing/qa/code-step-copy-gate.js) fails if either card builds its own.
15
+ *
16
+ * THE COPY RULES (carried over verbatim from 267479 / 267561, not re-decided here):
17
+ * - Name BOTH lanes and RANK NEITHER: the screen does not know which factor the user holds.
18
+ * - The non-authenticator clause is gated on the door's answer, so we never mention a code nobody
19
+ * asked for.
20
+ * - `codeRequested` means "a code was requested", NOT "a code arrived" (twofa/email/send returns
21
+ * 200 even when the SMTP send threw), so the copy says "the code we emailed you" and never
22
+ * "check your inbox" / "it has arrived".
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.NO_CODE_REQUEST = void 0;
26
+ exports.readCodeRequest = readCodeRequest;
27
+ exports.codeStepParts = codeStepParts;
28
+ exports.codeStepInstruction = codeStepInstruction;
29
+ /** Nothing sent, nothing to say beyond the authenticator. What a card starts with. */
30
+ exports.NO_CODE_REQUEST = { codeRequested: false, sentVia: null };
31
+ /**
32
+ * Read the door's answer. Total: any shape (null, a string, an array, junk fields) yields a
33
+ * CodeRequest and never throws, so a malformed body degrades to the authenticator-only sentence
34
+ * rather than to a crash or to a claim the door never made.
35
+ */
36
+ function readCodeRequest(body) {
37
+ const b = body && typeof body === 'object' ? body : {};
38
+ const sentVia = b.sentVia === 'sms' || b.sentVia === 'email' ? b.sentVia : null;
39
+ const accepted = Array.isArray(b.acceptedFactors) ? b.acceptedFactors : null;
40
+ const base = { codeRequested: b.codeRequested === true || b.emailSent === true, sentVia };
41
+ return accepted !== null && !accepted.includes('totp') ? { ...base, acceptsAuthenticator: false } : base;
42
+ }
43
+ /** The lane clause that follows the authenticator, or '' when the door sent nothing. */
44
+ function laneClause(r) {
45
+ if (!r.codeRequested)
46
+ return '';
47
+ if (r.sentVia === 'sms')
48
+ return ', or the code we texted you';
49
+ if (r.sentVia === 'email')
50
+ return ', or the code we emailed you';
51
+ return ', or the code we sent you';
52
+ }
53
+ /**
54
+ * The sentence, split around the email so a card can render the address however it likes
55
+ * (SignInCard wraps it in <strong>; AdminLoginCard passes a plain-string subtitle).
56
+ * `before + email + after` is the whole sentence.
57
+ */
58
+ function codeStepParts(r) {
59
+ if (r.acceptsAuthenticator === false) {
60
+ // 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.
61
+ const how = r.sentVia === 'sms' ? 'texted' : r.sentVia === 'email' ? 'emailed' : 'sent';
62
+ return { before: 'Enter your 6-digit code to finish signing in as ', after: ` — the code we ${how} you.` };
63
+ }
64
+ return {
65
+ before: 'Enter your 6-digit code to finish signing in as ',
66
+ after: ` — from your authenticator app${laneClause(r)}.`,
67
+ };
68
+ }
69
+ /** The sentence as one plain string, for a card whose subtitle prop is a string. */
70
+ function codeStepInstruction(email, r) {
71
+ const { before, after } = codeStepParts(r);
72
+ return `${before}${email}${after}`;
73
+ }
@@ -0,0 +1,59 @@
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, type CodeRequest } from './code-step-copy';
17
+ export declare const CREDENTIAL_LOGIN_URL = "/api/auth/admin-login";
18
+ export declare const CREDENTIAL_EMAIL_CODE_URL = "/api/auth/admin-login/email-code";
19
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
20
+ export type CredentialSignInResult = {
21
+ kind: 'success';
22
+ } | {
23
+ kind: 'two_factor';
24
+ codeRequest: CodeRequest;
25
+ } | {
26
+ kind: 'rate_limited';
27
+ message: string;
28
+ } | {
29
+ kind: 'error';
30
+ message: string;
31
+ offerEmailCode: boolean;
32
+ };
33
+ export declare const MSG_RATE_LIMITED = "Too many attempts. Please try again later.";
34
+ export declare const MSG_CANNOT_SIGN_IN = "Could not sign in. Check your details and try again.";
35
+ export declare const MSG_UNEXPECTED = "Something went wrong signing you in. Please try again.";
36
+ export declare function isEmailShaped(v: string): boolean;
37
+ /** Field-level checks before anything is sent. Returns the errors, or null when the input may be submitted. */
38
+ export declare function validateCredentials(email: string, password: string): {
39
+ email?: string;
40
+ password?: string;
41
+ } | null;
42
+ /** One call to the credential door. `code` is the 2FA code on the second turn; email and password are resubmitted with it. */
43
+ export declare function credentialSignIn(args: {
44
+ email: string;
45
+ password: string;
46
+ code?: string;
47
+ }, fetchImpl?: FetchLike): Promise<CredentialSignInResult>;
48
+ export type EmailCodeResult = {
49
+ kind: 'requested';
50
+ codeRequest: CodeRequest;
51
+ devCode: string | null;
52
+ } | {
53
+ kind: 'error';
54
+ message: string;
55
+ };
56
+ export declare const MSG_EMAIL_CODE_FAILED = "We could not ask for an email code just now. Try again shortly.";
57
+ /** "Email me a code instead": asks the door to email a code. `requested` means asked, never arrived. */
58
+ export declare function requestEmailCode(fetchImpl?: FetchLike): Promise<EmailCodeResult>;
59
+ export { NO_CODE_REQUEST };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NO_CODE_REQUEST = exports.MSG_EMAIL_CODE_FAILED = exports.MSG_UNEXPECTED = exports.MSG_CANNOT_SIGN_IN = exports.MSG_RATE_LIMITED = exports.CREDENTIAL_EMAIL_CODE_URL = exports.CREDENTIAL_LOGIN_URL = void 0;
4
+ exports.isEmailShaped = isEmailShaped;
5
+ exports.validateCredentials = validateCredentials;
6
+ exports.credentialSignIn = credentialSignIn;
7
+ exports.requestEmailCode = requestEmailCode;
8
+ /**
9
+ * PAY-2302 cut 1b: the BROWSER side of the package's credential sign-in, as plain functions so it is testable without a DOM.
10
+ *
11
+ * It talks to the routes the app mounts from this package:
12
+ * POST /api/auth/admin-login routes/auth/credential-login { email, password, code? }
13
+ * POST /api/auth/admin-login/email-code routes/auth/credential-login-email-code (no body: the browser names no address and no client)
14
+ *
15
+ * The result is a closed union so the form cannot invent a state the door never answered. The logic mirrors the portal's
16
+ * AdminLoginCard.submitLogin (VibeID-Customer-Portal 3d654917) and keeps its rules:
17
+ * - 429 is relayed as the door's own sentence; the form never states a window the door did not send.
18
+ * - `requiresTwoFactor` moves to the code step and keeps the door's answer (sentVia / codeRequested) so the step names the
19
+ * lane that was actually fired (PAY-1576).
20
+ * - anything else not `success: true` is an error carrying the door's message, and `offerEmailCode` only when the door set it
21
+ * literally true (PAY-2284).
22
+ */
23
+ const code_step_copy_1 = require("./code-step-copy");
24
+ Object.defineProperty(exports, "NO_CODE_REQUEST", { enumerable: true, get: function () { return code_step_copy_1.NO_CODE_REQUEST; } });
25
+ exports.CREDENTIAL_LOGIN_URL = '/api/auth/admin-login';
26
+ exports.CREDENTIAL_EMAIL_CODE_URL = '/api/auth/admin-login/email-code';
27
+ exports.MSG_RATE_LIMITED = 'Too many attempts. Please try again later.';
28
+ exports.MSG_CANNOT_SIGN_IN = 'Could not sign in. Check your details and try again.';
29
+ exports.MSG_UNEXPECTED = 'Something went wrong signing you in. Please try again.';
30
+ const EMAIL_SHAPE = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
31
+ function isEmailShaped(v) {
32
+ return EMAIL_SHAPE.test(v);
33
+ }
34
+ /** Field-level checks before anything is sent. Returns the errors, or null when the input may be submitted. */
35
+ function validateCredentials(email, password) {
36
+ const errors = {};
37
+ const trimmed = email.trim();
38
+ if (!trimmed)
39
+ errors.email = 'Enter your email address.';
40
+ else if (!isEmailShaped(trimmed))
41
+ errors.email = 'Enter a valid email address.';
42
+ if (!password)
43
+ errors.password = 'Enter your password.';
44
+ return errors.email || errors.password ? errors : null;
45
+ }
46
+ function asString(v) {
47
+ return typeof v === 'string' && v ? v : undefined;
48
+ }
49
+ /** One call to the credential door. `code` is the 2FA code on the second turn; email and password are resubmitted with it. */
50
+ async function credentialSignIn(args, fetchImpl = (input, init) => fetch(input, init)) {
51
+ try {
52
+ const res = await fetchImpl(exports.CREDENTIAL_LOGIN_URL, {
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json' },
55
+ body: JSON.stringify({ email: args.email, password: args.password, code: args.code }),
56
+ });
57
+ const body = await res.json().catch(() => null);
58
+ if (res.status === 429)
59
+ return { kind: 'rate_limited', message: asString(body?.error) ?? exports.MSG_RATE_LIMITED };
60
+ if (body?.requiresTwoFactor)
61
+ return { kind: 'two_factor', codeRequest: (0, code_step_copy_1.readCodeRequest)(body) };
62
+ if (!res.ok || body?.success !== true) {
63
+ return { kind: 'error', message: asString(body?.error) ?? exports.MSG_CANNOT_SIGN_IN, offerEmailCode: body?.offerEmailCode === true };
64
+ }
65
+ return { kind: 'success' };
66
+ }
67
+ catch {
68
+ return { kind: 'error', message: exports.MSG_UNEXPECTED, offerEmailCode: false };
69
+ }
70
+ }
71
+ exports.MSG_EMAIL_CODE_FAILED = 'We could not ask for an email code just now. Try again shortly.';
72
+ /** "Email me a code instead": asks the door to email a code. `requested` means asked, never arrived. */
73
+ async function requestEmailCode(fetchImpl = (input, init) => fetch(input, init)) {
74
+ try {
75
+ const res = await fetchImpl(exports.CREDENTIAL_EMAIL_CODE_URL, { method: 'POST', credentials: 'include' });
76
+ const body = await res.json().catch(() => null);
77
+ if (res.ok && body?.success === true) {
78
+ return {
79
+ kind: 'requested',
80
+ codeRequest: (0, code_step_copy_1.readCodeRequest)(body),
81
+ devCode: typeof body?.devVerificationCode === 'string' && body.devVerificationCode ? body.devVerificationCode : null,
82
+ };
83
+ }
84
+ return { kind: 'error', message: asString(body?.error) ?? exports.MSG_EMAIL_CODE_FAILED };
85
+ }
86
+ catch {
87
+ return { kind: 'error', message: exports.MSG_EMAIL_CODE_FAILED };
88
+ }
89
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Per-browser device identity — card 240566 (QAPert flag 2 on the 9c7a815 review).
3
+ *
4
+ * BEFORE: /api/auth/admin-login forwarded ONE hardcoded device-id cookie —
5
+ * `payez-PayEz-6c8201c35c1b44c9b2e823b36b95a718` — for every caller on the
6
+ * PUBLIC /sign-in password path. To the IDP's rate limiter and device
7
+ * fingerprinting, every portal user was literally the same device. Two
8
+ * consequences, both measured-by-inspection rather than hypothetical:
9
+ * 1. SHARED-FATE LOCKOUT — one attacker's failed attempts consume the
10
+ * throttle budget for every legitimate user at once.
11
+ * 2. Per-device risk signals are meaningless: "new device" and "trusted
12
+ * device" cannot distinguish anybody from anybody.
13
+ *
14
+ * The id is a routing/telemetry key, NOT a credential — the IDP must never
15
+ * grant anything on the strength of it, and nothing here assumes otherwise.
16
+ * It is client-supplied and therefore client-forgeable; that is inherent to
17
+ * device-id throttling and is why it supplements, never replaces, the
18
+ * identifier- and IP-scoped limits on the IDP side.
19
+ *
20
+ * Shape is fixed by what the IDP already accepts from
21
+ * createLoginHandler: `payez-PayEz-<32 lowercase hex>`.
22
+ */
23
+ export declare const DEVICE_ID_HEADER = "X-Device-Id";
24
+ export declare const DEVICE_ID_PATTERN: RegExp;
25
+ /** True for a well-formed device id. Used on BOTH sides of the wire. */
26
+ export declare function isValidDeviceId(value: string | null | undefined): value is string;
27
+ /**
28
+ * The stable per-browser device id, minted once and persisted.
29
+ *
30
+ * Browser-only. Persistence is best-effort: private windows, disabled site
31
+ * data and storage-quota failures all throw on access, so every read and
32
+ * write is guarded. A browser that cannot persist still gets a VALID id for
33
+ * this call — it simply looks like a new device each time, which is the
34
+ * honest answer for a client that refuses to be remembered, and is still
35
+ * strictly better than every user sharing one identity.
36
+ */
37
+ export declare function getDeviceId(): string;