@payez/next-mvp 4.4.5 → 4.4.6

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 (189) hide show
  1. package/README.md +10 -3
  2. package/dist/api/auth-handler.js +5 -3
  3. package/dist/api-handlers/account/change-password.js +6 -3
  4. package/dist/api-handlers/account/masked-info.js +2 -1
  5. package/dist/api-handlers/account/recovery/forward.d.ts +14 -0
  6. package/dist/api-handlers/account/recovery/forward.js +105 -0
  7. package/dist/api-handlers/account/recovery/initiate.js +4 -0
  8. package/dist/api-handlers/account/recovery/send-code.d.ts +12 -2
  9. package/dist/api-handlers/account/recovery/send-code.js +11 -84
  10. package/dist/api-handlers/account/recovery/verify-code.d.ts +11 -2
  11. package/dist/api-handlers/account/recovery/verify-code.js +10 -84
  12. package/dist/api-handlers/account/reset-password.js +24 -1
  13. package/dist/api-handlers/account/send-code.d.ts +1 -15
  14. package/dist/api-handlers/account/send-code.js +3 -6
  15. package/dist/api-handlers/account/update-phone.js +6 -1
  16. package/dist/api-handlers/account/validate-password.js +3 -1
  17. package/dist/api-handlers/account/verify-email.d.ts +1 -17
  18. package/dist/api-handlers/account/verify-email.js +4 -6
  19. package/dist/api-handlers/account/verify-sms.d.ts +1 -17
  20. package/dist/api-handlers/account/verify-sms.js +4 -6
  21. package/dist/api-handlers/admin/analytics.js +12 -4
  22. package/dist/api-handlers/admin/audit.js +12 -4
  23. package/dist/api-handlers/admin/redis-sessions.js +16 -8
  24. package/dist/api-handlers/admin/sessions.js +14 -6
  25. package/dist/api-handlers/admin/site-logs.js +39 -16
  26. package/dist/api-handlers/admin/stats.js +14 -4
  27. package/dist/api-handlers/admin/users.js +14 -6
  28. package/dist/api-handlers/admin/vibe-data.js +19 -11
  29. package/dist/api-handlers/auth/jwks.js +2 -1
  30. package/dist/api-handlers/auth/login.js +13 -4
  31. package/dist/api-handlers/auth/passkey-signin.js +6 -0
  32. package/dist/api-handlers/auth/refresh.js +38 -11
  33. package/dist/api-handlers/auth/signout.js +2 -1
  34. package/dist/api-handlers/auth/status.js +4 -1
  35. package/dist/api-handlers/auth/update-session.d.ts +25 -4
  36. package/dist/api-handlers/auth/update-session.js +38 -11
  37. package/dist/api-handlers/auth/validate.js +4 -2
  38. package/dist/api-handlers/auth/verify-code.js +3 -2
  39. package/dist/api-handlers/mfa/backup-code-verify.d.ts +1 -18
  40. package/dist/api-handlers/mfa/backup-code-verify.js +4 -6
  41. package/dist/api-handlers/mfa/backup-codes.js +2 -1
  42. package/dist/api-handlers/mfa/methods.js +2 -1
  43. package/dist/api-handlers/mfa/totp-confirm.js +2 -1
  44. package/dist/api-handlers/mfa/totp-enroll.js +2 -1
  45. package/dist/api-handlers/mfa/totp-verify.d.ts +1 -19
  46. package/dist/api-handlers/mfa/totp-verify.js +4 -6
  47. package/dist/api-handlers/passkeys/list.js +2 -1
  48. package/dist/api-handlers/passkeys/manage.js +2 -1
  49. package/dist/api-handlers/passkeys/register-options.js +2 -1
  50. package/dist/api-handlers/passkeys/register-verify.js +2 -1
  51. package/dist/api-handlers/session/refresh-viability.d.ts +4 -2
  52. package/dist/api-handlers/session/refresh-viability.js +10 -7
  53. package/dist/api-handlers/session/viability.js +4 -3
  54. package/dist/api-handlers/test/force-expire.js +5 -3
  55. package/dist/auth/auth-decision.js +2 -1
  56. package/dist/auth/better-auth.d.ts +14 -0
  57. package/dist/auth/better-auth.js +35 -49
  58. package/dist/auth/utils/idp-client.js +2 -1
  59. package/dist/components/admin/DataBrowserTab.js +4 -1
  60. package/dist/components/admin/SessionsTab.js +9 -3
  61. package/dist/components/recovery/RequestedStep.d.ts +11 -0
  62. package/dist/components/recovery/RequestedStep.js +14 -0
  63. package/dist/components/recovery/SetPasswordStep.js +10 -1
  64. package/dist/lib/app-slug.d.ts +21 -0
  65. package/dist/lib/app-slug.js +51 -0
  66. package/dist/lib/ensure-fresh-access-token.d.ts +26 -0
  67. package/dist/lib/ensure-fresh-access-token.js +105 -4
  68. package/dist/lib/idp-client-config.d.ts +20 -0
  69. package/dist/lib/idp-client-config.js +66 -45
  70. package/dist/lib/idp-fetch.js +1 -1
  71. package/dist/lib/password-rules.d.ts +22 -0
  72. package/dist/lib/password-rules.js +43 -0
  73. package/dist/lib/safe-error-response.d.ts +67 -0
  74. package/dist/lib/safe-error-response.js +130 -0
  75. package/dist/lib/session-cookie-shape.d.ts +22 -19
  76. package/dist/lib/session-cookie-shape.js +14 -18
  77. package/dist/lib/session-store.d.ts +8 -1
  78. package/dist/lib/session-store.js +170 -24
  79. package/dist/lib/startup-init.d.ts +6 -0
  80. package/dist/lib/startup-init.js +30 -4
  81. package/dist/lib/token-lifecycle.js +2 -1
  82. package/dist/lib/token-log-id.d.ts +18 -0
  83. package/dist/lib/token-log-id.js +84 -0
  84. package/dist/lib/two-factor-verify-failure.d.ts +45 -0
  85. package/dist/lib/two-factor-verify-failure.js +143 -0
  86. package/dist/middleware/create-middleware.d.ts +2 -1
  87. package/dist/middleware/create-middleware.js +43 -8
  88. package/dist/pages/recovery/page.js +14 -4
  89. package/dist/pages/test-env/JwtInspectPage.js +7 -149
  90. package/dist/pages/test-env/RefreshTokenPage.js +4 -1
  91. package/dist/pages/test-env/redact-credentials.d.ts +6 -0
  92. package/dist/pages/test-env/redact-credentials.js +101 -0
  93. package/dist/pages/verify-code/page.js +2 -1
  94. package/dist/routes/auth/logout.d.ts +2 -1
  95. package/dist/routes/auth/logout.js +4 -2
  96. package/dist/routes/auth/session.d.ts +0 -3
  97. package/dist/routes/auth/session.js +16 -10
  98. package/dist/routes/auth/viability.d.ts +3 -2
  99. package/dist/routes/auth/viability.js +11 -7
  100. package/dist/server/auth.js +10 -6
  101. package/dist/server/decode-session.js +15 -26
  102. package/dist/server/verified-session-token.d.ts +13 -0
  103. package/dist/server/verified-session-token.js +103 -0
  104. package/dist/stores/authStore.js +14 -3
  105. package/dist/types/recovery.d.ts +1 -1
  106. package/dist/utils/api.d.ts +18 -0
  107. package/dist/utils/api.js +51 -9
  108. package/dist/vibe/sessions.js +2 -1
  109. package/package.json +2 -1
  110. package/scripts/verify-release-provenance.mjs +410 -0
  111. package/src/api/auth-handler.ts +5 -3
  112. package/src/api-handlers/account/change-password.ts +6 -3
  113. package/src/api-handlers/account/masked-info.ts +2 -1
  114. package/src/api-handlers/account/recovery/forward.ts +117 -0
  115. package/src/api-handlers/account/recovery/initiate.ts +3 -0
  116. package/src/api-handlers/account/recovery/send-code.ts +13 -99
  117. package/src/api-handlers/account/recovery/verify-code.ts +12 -99
  118. package/src/api-handlers/account/reset-password.ts +30 -1
  119. package/src/api-handlers/account/send-code.ts +3 -9
  120. package/src/api-handlers/account/update-phone.ts +6 -1
  121. package/src/api-handlers/account/validate-password.ts +3 -1
  122. package/src/api-handlers/account/verify-email.ts +4 -9
  123. package/src/api-handlers/account/verify-sms.ts +4 -9
  124. package/src/api-handlers/admin/analytics.ts +13 -5
  125. package/src/api-handlers/admin/audit.ts +13 -5
  126. package/src/api-handlers/admin/redis-sessions.ts +16 -8
  127. package/src/api-handlers/admin/sessions.ts +15 -7
  128. package/src/api-handlers/admin/site-logs.ts +39 -16
  129. package/src/api-handlers/admin/stats.ts +15 -5
  130. package/src/api-handlers/admin/users.ts +15 -7
  131. package/src/api-handlers/admin/vibe-data.ts +20 -12
  132. package/src/api-handlers/auth/jwks.ts +2 -1
  133. package/src/api-handlers/auth/login.ts +13 -4
  134. package/src/api-handlers/auth/passkey-signin.ts +4 -0
  135. package/src/api-handlers/auth/refresh.ts +38 -11
  136. package/src/api-handlers/auth/signout.ts +2 -1
  137. package/src/api-handlers/auth/status.ts +4 -1
  138. package/src/api-handlers/auth/update-session.ts +45 -11
  139. package/src/api-handlers/auth/validate.ts +4 -2
  140. package/src/api-handlers/auth/verify-code.ts +3 -2
  141. package/src/api-handlers/mfa/backup-code-verify.ts +4 -9
  142. package/src/api-handlers/mfa/backup-codes.ts +2 -1
  143. package/src/api-handlers/mfa/methods.ts +2 -1
  144. package/src/api-handlers/mfa/totp-confirm.ts +2 -1
  145. package/src/api-handlers/mfa/totp-enroll.ts +2 -1
  146. package/src/api-handlers/mfa/totp-verify.ts +4 -9
  147. package/src/api-handlers/passkeys/list.ts +2 -1
  148. package/src/api-handlers/passkeys/manage.ts +2 -1
  149. package/src/api-handlers/passkeys/register-options.ts +2 -1
  150. package/src/api-handlers/passkeys/register-verify.ts +2 -1
  151. package/src/api-handlers/session/refresh-viability.ts +10 -7
  152. package/src/api-handlers/session/viability.ts +4 -3
  153. package/src/api-handlers/test/force-expire.ts +5 -3
  154. package/src/auth/auth-decision.ts +2 -1
  155. package/src/auth/better-auth.ts +37 -55
  156. package/src/auth/utils/idp-client.ts +2 -1
  157. package/src/components/admin/DataBrowserTab.tsx +4 -1
  158. package/src/components/admin/SessionsTab.tsx +10 -3
  159. package/src/components/recovery/RequestedStep.tsx +30 -0
  160. package/src/components/recovery/SetPasswordStep.tsx +24 -3
  161. package/src/hooks/useViabilitySession.ts +2 -1
  162. package/src/lib/app-slug.ts +50 -0
  163. package/src/lib/ensure-fresh-access-token.ts +133 -4
  164. package/src/lib/idp-client-config.ts +91 -45
  165. package/src/lib/idp-fetch.ts +1 -1
  166. package/src/lib/password-rules.ts +50 -0
  167. package/src/lib/safe-error-response.ts +126 -0
  168. package/src/lib/session-cookie-shape.ts +23 -22
  169. package/src/lib/session-store.ts +167 -24
  170. package/src/lib/startup-init.ts +29 -4
  171. package/src/lib/token-lifecycle.ts +2 -1
  172. package/src/lib/token-log-id.ts +69 -0
  173. package/src/lib/two-factor-verify-failure.ts +167 -0
  174. package/src/middleware/create-middleware.ts +55 -9
  175. package/src/pages/recovery/page.tsx +21 -4
  176. package/src/pages/test-env/JwtInspectPage.tsx +11 -233
  177. package/src/pages/test-env/RefreshTokenPage.tsx +9 -4
  178. package/src/pages/test-env/redact-credentials.ts +96 -0
  179. package/src/pages/verify-code/page.tsx +2 -1
  180. package/src/routes/auth/logout.ts +4 -2
  181. package/src/routes/auth/session.ts +16 -10
  182. package/src/routes/auth/viability.ts +11 -7
  183. package/src/server/auth.ts +10 -6
  184. package/src/server/decode-session.ts +16 -26
  185. package/src/server/verified-session-token.ts +103 -0
  186. package/src/stores/authStore.ts +16 -5
  187. package/src/types/recovery.ts +1 -1
  188. package/src/utils/api.ts +47 -8
  189. package/src/vibe/sessions.ts +2 -1
@@ -1,107 +1,21 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import { idpFetchJSON } from '../../../lib/idp-fetch';
3
- import { ENV_CONFIG } from '../../../config/env';
4
- import { getIDPClientConfig } from '../../../lib/idp-client-config';
5
- import { resolveClientKey } from '../../../lib/client-key';
1
+ import { NextRequest } from 'next/server';
2
+ import { forwardRecoveryCall } from './forward';
6
3
 
7
4
  /**
8
- * Account recovery — send-code
5
+ * Account recovery - send-code.
9
6
  *
10
- * WHY THIS WAS REWRITTEN (2026-08-02, swept out of QAPert defect #7)
11
- * This handler read the caller's bearer straight off the inbound request:
12
- *
13
- * const auth = req.headers.get('authorization') || '';
14
- * const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';
15
- * ... headers: { 'Authorization': `Bearer ${token}` }
16
- *
17
- * Browsers send a session COOKIE and no Authorization header, so `token` was
18
- * ALWAYS the empty string and this always called the IDP with a literal
19
- * "Bearer " and nothing after it.
20
- *
21
- * THAT IS WORSE THAN THE profile.ts VERSION OF THIS BUG, in two ways:
22
- *
23
- * 1. profile.ts at least 401'd when the header was missing. This one has no
24
- * check at all — `|| ''` swallows the absence — so it proceeds to call
25
- * upstream with an empty credential and returns the IDP's rejection as an
26
- * opaque failure. The user sees recovery "not working", not "not
27
- * authenticated", and the log shows an upstream error rather than an auth
28
- * one. The defect hides itself.
29
- * 2. It is BOTH HALVES of account recovery — send-code and verify-code — so
30
- * the entire recovery path is unreachable, not merely degraded. This is
31
- * the flow a locked-out user reaches for, i.e. it fails exactly when it is
32
- * the only thing left that could help them.
33
- *
34
- * Fixed the same way as profile.ts and masked-info.ts: idpFetchJSON resolves
35
- * the caller's token from the server-side session, so the cookie works and the
36
- * token is never handed to browser JavaScript.
7
+ * PAY-1588: the recovery session token minted by `initiate` is the caller's only credential (they are locked out; there is
8
+ * no session), so this forwards the inbound `Authorization: Bearer <token>` to the IdP and fails loud (401
9
+ * `missing_recovery_token`) when it is absent. The whole reasoning, and why the 2026-08-02 idpFetchJSON rewrite killed
10
+ * this flow, is in ./forward.ts. send-code and verify-code share that ONE forwarder so they cannot drift apart again.
37
11
  *
38
12
  * @package @payez/next-mvp
39
13
  */
40
-
41
- /**
42
- * RECOVERY CLIENT KEY — cards 268012 (S12) and 268410.
43
- *
44
- * These four proxies populated NONE of PayEzClientIdResolver's six slots, so
45
- * RequirePayEzUnAuthorized 404'd the request BEFORE the action ran and no
46
- * recovery token was ever minted. That is why S12 failed at step 1.
47
- *
48
- * NOT `ENV_CONFIG.CLIENT_ID`, which is what card 268012 originally prescribed.
49
- * That variable is the ENVIRONMENT-SPECIFIC NUMERIC id, and the IDP accepts a
50
- * numeric with NO existence check (RequirePayEzUnAuthorizedAttribute.cs:31-33)
51
- * while it VALIDATES a slug (:41-47). Hardcoding the numeric here would have
52
- * added four more sites to the 268410 family and made a stale id answer for
53
- * the WRONG TENANT on a password-reset path, silently. Slug-preferring, with
54
- * the numeric fallback logged, is the same resolver the other nine sites use.
55
- *
56
- * SERVER VALUE WINS: client_id is applied AFTER the caller's payload spread.
57
- * These are unauthenticated recovery endpoints, so a browser-supplied
58
- * client_id would be a tenant-targeting lever. The caller does not get to
59
- * choose which tenant their password reset is addressed to.
60
- */
61
- async function recoveryClientKey(): Promise<string | null> {
62
- try {
63
- const config = await getIDPClientConfig();
64
- return resolveClientKey(config, 'account/recovery/send-code').key;
65
- } catch (e) {
66
- console.error('[account/recovery/send-code] could not resolve IDP client config for client_id:', e);
67
- return null;
68
- }
69
- }
70
-
71
14
  export async function POST(req: NextRequest) {
72
- let payload: unknown = {};
73
- try {
74
- payload = await req.json();
75
- } catch {
76
- return NextResponse.json(
77
- { success: false, error: 'invalid_request', message: 'A JSON body is required' },
78
- { status: 400 }
79
- );
80
- }
81
-
82
- const clientKey = await recoveryClientKey();
83
-
84
- const result = await idpFetchJSON(
85
- req,
86
- `${ENV_CONFIG.IDP_URL}/api/Account/recovery/send-code`,
87
- {
88
- method: 'POST',
89
- headers: { 'Content-Type': 'application/json', ...(clientKey ? { 'X-Client-Id': clientKey } : {}) },
90
- body: JSON.stringify({ ...(payload as Record<string, unknown>), ...(clientKey ? { client_id: clientKey } : {}) }),
91
- }
92
- );
93
-
94
- if (!result.ok) {
95
- return NextResponse.json(
96
- {
97
- success: false,
98
- error: 'send_code_failed',
99
- message: result.json?.message || 'Upstream error',
100
- meta: { status: result.status, attemptedRefresh: result.attemptedRefresh },
101
- },
102
- { status: result.status }
103
- );
104
- }
105
-
106
- return NextResponse.json(result.json, { status: 200 });
15
+ return forwardRecoveryCall(req, {
16
+ upstreamPath: '/api/Account/recovery/send-code',
17
+ where: 'account/recovery/send-code',
18
+ failureCode: 'send_code_failed',
19
+ fallbackMessage: 'Failed to send the verification code',
20
+ });
107
21
  }
@@ -1,107 +1,20 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
- import { idpFetchJSON } from '../../../lib/idp-fetch';
3
- import { ENV_CONFIG } from '../../../config/env';
4
- import { getIDPClientConfig } from '../../../lib/idp-client-config';
5
- import { resolveClientKey } from '../../../lib/client-key';
1
+ import { NextRequest } from 'next/server';
2
+ import { forwardRecoveryCall } from './forward';
6
3
 
7
4
  /**
8
- * Account recovery — verify-code
5
+ * Account recovery - verify-code.
9
6
  *
10
- * WHY THIS WAS REWRITTEN (2026-08-02, swept out of QAPert defect #7)
11
- * This handler read the caller's bearer straight off the inbound request:
12
- *
13
- * const auth = req.headers.get('authorization') || '';
14
- * const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';
15
- * ... headers: { 'Authorization': `Bearer ${token}` }
16
- *
17
- * Browsers send a session COOKIE and no Authorization header, so `token` was
18
- * ALWAYS the empty string and this always called the IDP with a literal
19
- * "Bearer " and nothing after it.
20
- *
21
- * THAT IS WORSE THAN THE profile.ts VERSION OF THIS BUG, in two ways:
22
- *
23
- * 1. profile.ts at least 401'd when the header was missing. This one has no
24
- * check at all — `|| ''` swallows the absence — so it proceeds to call
25
- * upstream with an empty credential and returns the IDP's rejection as an
26
- * opaque failure. The user sees recovery "not working", not "not
27
- * authenticated", and the log shows an upstream error rather than an auth
28
- * one. The defect hides itself.
29
- * 2. It is BOTH HALVES of account recovery — send-code and verify-code — so
30
- * the entire recovery path is unreachable, not merely degraded. This is
31
- * the flow a locked-out user reaches for, i.e. it fails exactly when it is
32
- * the only thing left that could help them.
33
- *
34
- * Fixed the same way as profile.ts and masked-info.ts: idpFetchJSON resolves
35
- * the caller's token from the server-side session, so the cookie works and the
36
- * token is never handed to browser JavaScript.
7
+ * PAY-1588: forwards the inbound recovery `Authorization: Bearer <token>` to the IdP and fails loud (401
8
+ * `missing_recovery_token`) when it is absent. See ./forward.ts for the full reasoning; send-code and verify-code share
9
+ * that ONE forwarder so they cannot drift apart again.
37
10
  *
38
11
  * @package @payez/next-mvp
39
12
  */
40
-
41
- /**
42
- * RECOVERY CLIENT KEY — cards 268012 (S12) and 268410.
43
- *
44
- * These four proxies populated NONE of PayEzClientIdResolver's six slots, so
45
- * RequirePayEzUnAuthorized 404'd the request BEFORE the action ran and no
46
- * recovery token was ever minted. That is why S12 failed at step 1.
47
- *
48
- * NOT `ENV_CONFIG.CLIENT_ID`, which is what card 268012 originally prescribed.
49
- * That variable is the ENVIRONMENT-SPECIFIC NUMERIC id, and the IDP accepts a
50
- * numeric with NO existence check (RequirePayEzUnAuthorizedAttribute.cs:31-33)
51
- * while it VALIDATES a slug (:41-47). Hardcoding the numeric here would have
52
- * added four more sites to the 268410 family and made a stale id answer for
53
- * the WRONG TENANT on a password-reset path, silently. Slug-preferring, with
54
- * the numeric fallback logged, is the same resolver the other nine sites use.
55
- *
56
- * SERVER VALUE WINS: client_id is applied AFTER the caller's payload spread.
57
- * These are unauthenticated recovery endpoints, so a browser-supplied
58
- * client_id would be a tenant-targeting lever. The caller does not get to
59
- * choose which tenant their password reset is addressed to.
60
- */
61
- async function recoveryClientKey(): Promise<string | null> {
62
- try {
63
- const config = await getIDPClientConfig();
64
- return resolveClientKey(config, 'account/recovery/verify-code').key;
65
- } catch (e) {
66
- console.error('[account/recovery/verify-code] could not resolve IDP client config for client_id:', e);
67
- return null;
68
- }
69
- }
70
-
71
13
  export async function POST(req: NextRequest) {
72
- let payload: unknown = {};
73
- try {
74
- payload = await req.json();
75
- } catch {
76
- return NextResponse.json(
77
- { success: false, error: 'invalid_request', message: 'A JSON body is required' },
78
- { status: 400 }
79
- );
80
- }
81
-
82
- const clientKey = await recoveryClientKey();
83
-
84
- const result = await idpFetchJSON(
85
- req,
86
- `${ENV_CONFIG.IDP_URL}/api/Account/recovery/verify-code`,
87
- {
88
- method: 'POST',
89
- headers: { 'Content-Type': 'application/json', ...(clientKey ? { 'X-Client-Id': clientKey } : {}) },
90
- body: JSON.stringify({ ...(payload as Record<string, unknown>), ...(clientKey ? { client_id: clientKey } : {}) }),
91
- }
92
- );
93
-
94
- if (!result.ok) {
95
- return NextResponse.json(
96
- {
97
- success: false,
98
- error: 'verify_code_failed',
99
- message: result.json?.message || 'Upstream error',
100
- meta: { status: result.status, attemptedRefresh: result.attemptedRefresh },
101
- },
102
- { status: result.status }
103
- );
104
- }
105
-
106
- return NextResponse.json(result.json, { status: 200 });
14
+ return forwardRecoveryCall(req, {
15
+ upstreamPath: '/api/Account/recovery/verify-code',
16
+ where: 'account/recovery/verify-code',
17
+ failureCode: 'verify_code_failed',
18
+ fallbackMessage: 'Failed to verify the code',
19
+ });
107
20
  }
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { getIDPClientConfig } from '../../lib/idp-client-config';
3
3
  import { resolveClientKey } from '../../lib/client-key';
4
+ import { idpErrorEnvelope, projectPasswordPolicyRules, projectResetTokenInvalid } from '../../lib/safe-error-response';
4
5
 
5
6
  function getIdpUrl(): string {
6
7
  const url = process.env.IDP_URL;
@@ -41,7 +42,26 @@ async function recoveryClientKey(): Promise<string | null> {
41
42
  export async function POST(req: NextRequest) {
42
43
  const IDP_URL = getIdpUrl();
43
44
  try {
44
- const payload = await req.json();
45
+ const raw = await req.json().catch(() => null);
46
+ const body = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
47
+ // PAY-1588: the IdP's ResetPasswordRequest binds exactly email/token/new_password/confirm_password. The client
48
+ // used to send password_reset_token / password / password_confirmation, which bind to nothing (400 at the IdP).
49
+ // Legacy names are accepted as aliases and mapped; only the four IdP fields are forwarded (whitelist).
50
+ const str = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : undefined);
51
+ const fields = {
52
+ email: str(body.email),
53
+ token: str(body.token) ?? str(body.password_reset_token),
54
+ new_password: str(body.new_password) ?? str(body.password),
55
+ confirm_password: str(body.confirm_password) ?? str(body.password_confirmation),
56
+ };
57
+ const missing = Object.entries(fields).filter(([, v]) => v === undefined).map(([k]) => k);
58
+ if (missing.length) {
59
+ return NextResponse.json(
60
+ { success: false, error: 'invalid_request', message: 'Missing required fields: ' + missing.join(', ') },
61
+ { status: 400 },
62
+ );
63
+ }
64
+ const payload = fields;
45
65
  const clientKey = await recoveryClientKey();
46
66
  const upstream = await fetch(`${IDP_URL}/api/Account/reset-password`, {
47
67
  method: 'POST',
@@ -49,6 +69,15 @@ export async function POST(req: NextRequest) {
49
69
  body: JSON.stringify({ ...payload, ...(clientKey ? { client_id: clientKey } : {}) }),
50
70
  });
51
71
  const data = await upstream.json().catch(() => ({}));
72
+ // PAY-1438: anonymous route - on failure only the whitelisted envelope (utils/api reads `message`).
73
+ if (!upstream.ok) {
74
+ // PAY-1591: a password-policy refusal also carries the KNOWN rule codes so the page can say which rules failed.
75
+ const rules = projectPasswordPolicyRules(data);
76
+ return NextResponse.json(
77
+ { ...idpErrorEnvelope(data, 'Failed to reset password'), ...(rules !== undefined ? { password_policy: { rules } } : {}), ...(projectResetTokenInvalid(data) ? { reset_token_invalid: true } : {}) },
78
+ { status: upstream.status },
79
+ );
80
+ }
52
81
  return NextResponse.json(data, { status: upstream.status });
53
82
  } catch {
54
83
  return NextResponse.json({ success: false, error: 'reset_password_failed' }, { status: 500 });
@@ -10,6 +10,7 @@
10
10
  import { NextRequest, NextResponse } from 'next/server';
11
11
  import { idpFetchJSON } from '../../lib/idp-fetch';
12
12
  import { ENV_CONFIG } from '../../config/env';
13
+ import { twoFactorSendCodeFailure } from '../../lib/two-factor-verify-failure';
13
14
 
14
15
  export async function POST(req: NextRequest) {
15
16
  try {
@@ -44,15 +45,8 @@ export async function POST(req: NextRequest) {
44
45
  });
45
46
 
46
47
  if (!result.ok) {
47
- return NextResponse.json(
48
- {
49
- success: false,
50
- error: result.json?.message || `Failed to send ${method} code`,
51
- code: result.json?.code || 'IDP_ERROR',
52
- meta: { attemptedRefresh: result.attemptedRefresh },
53
- },
54
- { status: result.status }
55
- );
48
+ // PAY-1443: never relay the IDP's message/code - fixed sentence + stable code, status kept.
49
+ return twoFactorSendCodeFailure(result, method);
56
50
  }
57
51
 
58
52
  return NextResponse.json(
@@ -39,7 +39,12 @@ export async function POST(req: NextRequest) {
39
39
  });
40
40
 
41
41
  if (!result.ok) {
42
- console.error('[UPDATE_PHONE] IDP error:', result.status, result.json);
42
+ // PAY-1424: shape only, never the IDP body (profile endpoint - PII).
43
+ console.error('[UPDATE_PHONE] IDP error:', {
44
+ status: result.status,
45
+ bodyKeys: (result.json as any) && typeof (result.json as any) === 'object' ? Object.keys((result.json as any)) : undefined,
46
+ errorKeys: (result.json as any)?.error && typeof (result.json as any)?.error === 'object' ? Object.keys((result.json as any)?.error) : undefined,
47
+ });
43
48
  return NextResponse.json(
44
49
  {
45
50
  success: false,
@@ -79,9 +79,11 @@ export async function POST(req: NextRequest) {
79
79
  const responseData = await idpResponse.json().catch(() => ({}));
80
80
 
81
81
  if (!idpResponse.ok) {
82
+ // PAY-1424: shape only, never the envelope contents (this endpoint carries a password).
82
83
  console.error('[VALIDATE_PASSWORD] IDP error:', {
83
84
  status: idpResponse.status,
84
- response: responseData,
85
+ bodyKeys: responseData && typeof responseData === 'object' ? Object.keys(responseData) : undefined,
86
+ errorKeys: (responseData as any)?.error && typeof (responseData as any)?.error === 'object' ? Object.keys((responseData as any)?.error) : undefined,
85
87
  });
86
88
  return NextResponse.json(
87
89
  {
@@ -13,6 +13,7 @@ import { ENV_CONFIG } from '../../config/env';
13
13
  import { getTokenTestAware } from '../../lib/test-aware-get-token';
14
14
  import { transitionTo2FASession } from '../../lib/session-store';
15
15
  import { jwtDecode } from '../../lib/jwt-decode';
16
+ import { twoFactorVerifyFailure } from '../../lib/two-factor-verify-failure';
16
17
 
17
18
  export async function POST(req: NextRequest) {
18
19
  try {
@@ -39,15 +40,9 @@ export async function POST(req: NextRequest) {
39
40
  });
40
41
 
41
42
  if (!result.ok) {
42
- return NextResponse.json(
43
- {
44
- success: false,
45
- error: result.json?.message || 'Verification failed',
46
- code: result.json?.code || 'IDP_ERROR',
47
- meta: { attemptedRefresh: result.attemptedRefresh },
48
- },
49
- { status: result.status }
50
- );
43
+ // PAY-1443: never relay the IDP's error text - it arrives as a C# anonymous-object
44
+ // ToString ("{ message = ... }") on the deployed IDP. Classify it, answer a fixed sentence.
45
+ return twoFactorVerifyFailure(result, 'email');
51
46
  }
52
47
 
53
48
  // Unwrap IDP envelope
@@ -13,6 +13,7 @@ import { ENV_CONFIG } from '../../config/env';
13
13
  import { getTokenTestAware } from '../../lib/test-aware-get-token';
14
14
  import { transitionTo2FASession } from '../../lib/session-store';
15
15
  import { jwtDecode } from '../../lib/jwt-decode';
16
+ import { twoFactorVerifyFailure } from '../../lib/two-factor-verify-failure';
16
17
 
17
18
  export async function POST(req: NextRequest) {
18
19
  try {
@@ -39,15 +40,9 @@ export async function POST(req: NextRequest) {
39
40
  });
40
41
 
41
42
  if (!result.ok) {
42
- return NextResponse.json(
43
- {
44
- success: false,
45
- error: result.json?.message || 'Verification failed',
46
- code: result.json?.code || 'IDP_ERROR',
47
- meta: { attemptedRefresh: result.attemptedRefresh },
48
- },
49
- { status: result.status }
50
- );
43
+ // PAY-1443: never relay the IDP's error text - it arrives as a C# anonymous-object
44
+ // ToString ("{ message = ... }") on the deployed IDP. Classify it, answer a fixed sentence.
45
+ return twoFactorVerifyFailure(result, 'sms');
51
46
  }
52
47
 
53
48
  // Unwrap IDP envelope
@@ -13,6 +13,7 @@ import { getSession } from '../../server/auth';
13
13
  import { getStartupIDPConfig } from '../../lib/startup-init';
14
14
  import { resolveClientKey } from '../../lib/client-key';
15
15
  import { ADMIN_ROLES, hasAnyRole } from '../../lib/roles';
16
+ import { randomUUID } from 'crypto';
16
17
 
17
18
  interface VibeRequestOptions {
18
19
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
@@ -45,7 +46,10 @@ async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean;
45
46
  async function vibeServiceRequest<T = unknown>(
46
47
  endpoint: string,
47
48
  options: VibeRequestOptions
48
- ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
49
+ ): Promise<{ ok: boolean; status: number; data: T | null; error?: string; correlationId?: string }> {
50
+ // PAY-1429: `error` can reach the HTTP caller, so it never carries upstream Vibe text or
51
+ // exception text. Failures return a fixed message + correlationId; the same id is on the
52
+ // server log line, which carries status + bodyLength only (PAY-1424).
49
53
  const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
50
54
  const clientId = process.env.VIBE_CLIENT_ID;
51
55
  const signingKey = process.env.VIBE_HMAC_KEY;
@@ -90,13 +94,17 @@ async function vibeServiceRequest<T = unknown>(
90
94
  if (res.status === 204) return { ok: true, status: 204, data: null };
91
95
  if (!res.ok) {
92
96
  const errorText = await res.text();
93
- return { ok: false, status: res.status, data: null, error: errorText };
97
+ const correlationId = randomUUID();
98
+ console.error(`[admin/analytics] Vibe request failed: ${options.method} ${endpoint} - ${res.status}`, { correlationId, bodyLength: errorText.length });
99
+ return { ok: false, status: res.status, data: null, error: `Vibe request failed (HTTP ${res.status})`, correlationId };
94
100
  }
95
101
 
96
102
  const body = await res.json();
97
103
  return { ok: true, status: res.status, data: body };
98
104
  } catch (error) {
99
- return { ok: false, status: 0, data: null, error: String(error) };
105
+ const correlationId = randomUUID();
106
+ console.error(`[admin/analytics] Vibe request exception: ${options.method} ${endpoint}`, { correlationId, error });
107
+ return { ok: false, status: 0, data: null, error: 'Vibe request could not be completed', correlationId };
100
108
  }
101
109
  }
102
110
 
@@ -176,7 +184,7 @@ async function getGeoAnalytics(startDate: Date) {
176
184
  );
177
185
 
178
186
  if (!result.ok) {
179
- return NextResponse.json({ error: result.error }, { status: result.status || 500 });
187
+ return NextResponse.json({ error: result.error, code: 'UPSTREAM_ERROR', correlationId: result.correlationId }, { status: result.status || 500 });
180
188
  }
181
189
 
182
190
  const sessions = result.data?.data || result.data?.documents || [];
@@ -230,7 +238,7 @@ async function getLoginAnalytics(startDate: Date) {
230
238
  );
231
239
 
232
240
  if (!result.ok) {
233
- return NextResponse.json({ error: result.error }, { status: result.status || 500 });
241
+ return NextResponse.json({ error: result.error, code: 'UPSTREAM_ERROR', correlationId: result.correlationId }, { status: result.status || 500 });
234
242
  }
235
243
 
236
244
  const sessions = result.data?.data || result.data?.documents || [];
@@ -12,6 +12,7 @@ import { getSession } from '../../server/auth';
12
12
  import { getStartupIDPConfig } from '../../lib/startup-init';
13
13
  import { resolveClientKey } from '../../lib/client-key';
14
14
  import { ADMIN_ROLES, hasAnyRole } from '../../lib/roles';
15
+ import { randomUUID } from 'crypto';
15
16
 
16
17
  interface VibeRequestOptions {
17
18
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
@@ -44,7 +45,10 @@ async function checkAdminRole(request: NextRequest): Promise<{ isAdmin: boolean;
44
45
  async function vibeServiceRequest<T = unknown>(
45
46
  endpoint: string,
46
47
  options: VibeRequestOptions
47
- ): Promise<{ ok: boolean; status: number; data: T | null; error?: string }> {
48
+ ): Promise<{ ok: boolean; status: number; data: T | null; error?: string; correlationId?: string }> {
49
+ // PAY-1429: `error` can reach the HTTP caller, so it never carries upstream Vibe text or
50
+ // exception text. Failures return a fixed message + correlationId; the same id is on the
51
+ // server log line, which carries status + bodyLength only (PAY-1424).
48
52
  const idpUrl = process.env.NEXT_PUBLIC_IDP_URL || process.env.IDP_URL;
49
53
  const clientId = process.env.VIBE_CLIENT_ID;
50
54
  const signingKey = process.env.VIBE_HMAC_KEY;
@@ -89,13 +93,17 @@ async function vibeServiceRequest<T = unknown>(
89
93
  if (res.status === 204) return { ok: true, status: 204, data: null };
90
94
  if (!res.ok) {
91
95
  const errorText = await res.text();
92
- return { ok: false, status: res.status, data: null, error: errorText };
96
+ const correlationId = randomUUID();
97
+ console.error(`[admin/audit] Vibe request failed: ${options.method} ${endpoint} - ${res.status}`, { correlationId, bodyLength: errorText.length });
98
+ return { ok: false, status: res.status, data: null, error: `Vibe request failed (HTTP ${res.status})`, correlationId };
93
99
  }
94
100
 
95
101
  const body = await res.json();
96
102
  return { ok: true, status: res.status, data: body };
97
103
  } catch (error) {
98
- return { ok: false, status: 0, data: null, error: String(error) };
104
+ const correlationId = randomUUID();
105
+ console.error(`[admin/audit] Vibe request exception: ${options.method} ${endpoint}`, { correlationId, error });
106
+ return { ok: false, status: 0, data: null, error: 'Vibe request could not be completed', correlationId };
99
107
  }
100
108
  }
101
109
 
@@ -153,7 +161,7 @@ export function createAuditHandler(config: AdminAuditHandlerConfig) {
153
161
  );
154
162
 
155
163
  if (!result.ok) {
156
- return NextResponse.json({ error: result.error }, { status: result.status || 500 });
164
+ return NextResponse.json({ error: result.error, code: 'UPSTREAM_ERROR', correlationId: result.correlationId }, { status: result.status || 500 });
157
165
  }
158
166
 
159
167
  const rawLogs = result.data?.data || result.data?.documents || [];
@@ -190,7 +198,7 @@ export function createAuditHandler(config: AdminAuditHandlerConfig) {
190
198
  );
191
199
 
192
200
  if (!result.ok) {
193
- return NextResponse.json({ error: result.error }, { status: result.status || 500 });
201
+ return NextResponse.json({ error: result.error, code: 'UPSTREAM_ERROR', correlationId: result.correlationId }, { status: result.status || 500 });
194
202
  }
195
203
 
196
204
  const logs = result.data?.data || result.data?.documents || [];
@@ -15,6 +15,8 @@ import { NextRequest, NextResponse } from 'next/server';
15
15
  import { getSession } from '../../server/auth';
16
16
  import { getRedis } from '../../lib/redis';
17
17
  import { ADMIN_ROLES, hasAnyRole } from '../../lib/roles';
18
+ import { randomUUID } from 'crypto';
19
+ import { tokenLogId } from '../../lib/token-log-id';
18
20
 
19
21
  export interface RedisSessionsHandlerConfig {
20
22
  appSlug?: string;
@@ -93,7 +95,7 @@ export function createRedisSessionsHandler(config: RedisSessionsHandlerConfig) {
93
95
 
94
96
  sessions.push({
95
97
  id: sessionToken.substring(0, 16), // Truncated for display
96
- session_token: sessionToken.substring(0, 8) + '...', // Masked
98
+ session_token: tokenLogId(sessionToken), // Masked
97
99
  user_id: sessionData.userId,
98
100
  user_name: sessionData.name,
99
101
  user_email: sessionData.email,
@@ -129,9 +131,11 @@ export function createRedisSessionsHandler(config: RedisSessionsHandlerConfig) {
129
131
  redis_prefix: sessionPrefix,
130
132
  });
131
133
  } catch (error: any) {
132
- console.error('[admin/redis-sessions] Error:', error);
134
+ // PAY-1429: exception text (hosts, URLs, driver messages) stays server-side.
135
+ const correlationId = randomUUID();
136
+ console.error('[admin/redis-sessions] Error:', { correlationId, error });
133
137
  return NextResponse.json(
134
- { error: error.message || 'Internal error' },
138
+ { error: 'Internal error', code: 'INTERNAL_ERROR', correlationId },
135
139
  { status: 500 }
136
140
  );
137
141
  }
@@ -169,12 +173,14 @@ export function createRedisSessionsHandler(config: RedisSessionsHandlerConfig) {
169
173
  return NextResponse.json({
170
174
  success: true,
171
175
  message: 'Session revoked',
172
- session_token: sessionToken.substring(0, 8) + '...',
176
+ session_token: tokenLogId(sessionToken),
173
177
  });
174
178
  } catch (error: any) {
175
- console.error('[admin/redis-sessions] DELETE Error:', error);
179
+ // PAY-1429: exception text (hosts, URLs, driver messages) stays server-side.
180
+ const correlationId = randomUUID();
181
+ console.error('[admin/redis-sessions] DELETE Error:', { correlationId, error });
176
182
  return NextResponse.json(
177
- { error: error.message || 'Internal error' },
183
+ { error: 'Internal error', code: 'INTERNAL_ERROR', correlationId },
178
184
  { status: 500 }
179
185
  );
180
186
  }
@@ -240,9 +246,11 @@ export function createRedisSessionRevokeHandler(config: RedisSessionsHandlerConf
240
246
  message: 'Session revoked',
241
247
  });
242
248
  } catch (error: any) {
243
- console.error('[admin/redis-sessions/revoke] Error:', error);
249
+ // PAY-1429: exception text (hosts, URLs, driver messages) stays server-side.
250
+ const correlationId = randomUUID();
251
+ console.error('[admin/redis-sessions/revoke] Error:', { correlationId, error });
244
252
  return NextResponse.json(
245
- { error: error.message || 'Internal error' },
253
+ { error: 'Internal error', code: 'INTERNAL_ERROR', correlationId },
246
254
  { status: 500 }
247
255
  );
248
256
  }