@payez/next-mvp 4.4.4 → 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 +33 -13
  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 +65 -14
  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 +35 -10
  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 +90 -14
  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
@@ -21,6 +21,7 @@ import {
21
21
  getCallbackUrlCookieName,
22
22
  getJwtCookieName
23
23
  } from '../../lib/app-slug';
24
+ import { tokenLogId } from '../../lib/token-log-id';
24
25
 
25
26
  // JWT decode helper - simple base64 decode without verification
26
27
  function jwtDecode(token: string): any {
@@ -152,7 +153,7 @@ export function createSignoutHandler() {
152
153
  try {
153
154
  await deleteSessionEverywhere(redisSessionToken);
154
155
  console.info('[SIGNOUT] Redis session cleanup successful', {
155
- sessionToken: redisSessionToken.substring(0, 8) + '...'
156
+ sessionToken: tokenLogId(redisSessionToken)
156
157
  });
157
158
  } catch (sessionError) {
158
159
  // Log error but don't fail the signout process
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { getSession } from '../../server/auth';
3
3
  import { getSession as getRedisSession } from '../../lib/session-store';
4
+ import { logExceptionWithCorrelation } from '../../lib/safe-error-response';
4
5
 
5
6
  export async function GET(req: NextRequest) {
6
7
  try {
@@ -15,6 +16,8 @@ export async function GET(req: NextRequest) {
15
16
  }
16
17
  return NextResponse.json({ success: true, userId: betterAuthSession?.user?.id || (sessionModel as any).userId || null });
17
18
  } catch (err) {
18
- return NextResponse.json({ success: false, error: err instanceof Error ? err.message : 'Unknown error' }, { status: 500 });
19
+ // PAY-1438: this catch wraps both session reads (Better Auth + Redis), before any auth decision.
20
+ const correlationId = logExceptionWithCorrelation('[AUTH_STATUS] Error reading session:', err);
21
+ return NextResponse.json({ success: false, error: 'Failed to read session status', code: 'INTERNAL_ERROR', correlationId }, { status: 500 });
19
22
  }
20
23
  }
@@ -1,11 +1,28 @@
1
1
  /**
2
2
  * Authentication Update Session API Handler
3
3
  *
4
- * Handles session updates, particularly for 2FA status changes.
5
- * This handler is designed to be imported and used by Next.js applications
6
- * using the @payez/next-mvp package.
4
+ * *** THIS HANDLER DOES NOT PERSIST ANYTHING. IT IS AN ECHO. ***
7
5
  *
8
- * @version 2.0
6
+ * It authenticates the caller, reads `twoFactorSessionVerified` from the REQUEST
7
+ * BODY, and echoes that caller-asserted value straight back. There is no redis
8
+ * write, no cookie write, no JWT mint and no session-store call anywhere in this
9
+ * module - the only `.set(` calls are the security headers below. The 2FA state
10
+ * does NOT survive the request.
11
+ *
12
+ * Do not wire this expecting it to record a second factor. It is kept because
13
+ * live callers POST to it on the 2FA completion path and a 404/501 would break
14
+ * that flow; it is deliberately inert, NOT a session writer. Callers can detect
15
+ * this programmatically via `persisted: false` in the response.
16
+ *
17
+ * Card 391621 measured the consequence: because nothing is stored, downstream
18
+ * 2FA gates read no verified state and FAIL CLOSED. That is why this is an
19
+ * honesty/diagnosability defect rather than an auth bypass - but a future
20
+ * consumer that trusts `success: true` here would be trusting nothing.
21
+ *
22
+ * If you need to actually record 2FA completion, write to the session store
23
+ * (see `../../server/session-store`); do not extend this handler in place.
24
+ *
25
+ * @version 2.1
9
26
  * @requires Authentication (authenticated endpoint)
10
27
  */
11
28
 
@@ -36,11 +53,22 @@ interface UpdateSessionResponse {
36
53
  success: boolean;
37
54
  twoFactorSessionVerified: boolean;
38
55
  twoFactorMethod?: string;
56
+ /**
57
+ * ALWAYS `false`. This handler stores nothing, so the echoed
58
+ * `twoFactorSessionVerified` above reflects the REQUEST BODY and not any
59
+ * recorded state. Present so a consumer can detect the no-op without having
60
+ * to read this file. Additive: no pre-existing field changed meaning.
61
+ */
62
+ persisted: false;
39
63
  }
40
64
 
41
65
  /**
42
66
  * Creates an update-session handler for Next.js API routes.
43
67
  *
68
+ * *** NO-OP: this handler PERSISTS NOTHING. *** It requires a valid session,
69
+ * then echoes the caller-asserted `twoFactorSessionVerified` back with
70
+ * `persisted: false`. See the module header before wiring it.
71
+ *
44
72
  * Better Auth resolves its session from cookies, so this handler takes no
45
73
  * configuration. Use the default `POST` export below for typical usage.
46
74
  *
@@ -75,22 +103,28 @@ export function createUpdateSessionHandler() {
75
103
  ));
76
104
  }
77
105
 
78
- // Update the session with 2FA challenge completion status
79
- const updatedSession = {
106
+ // NOT a session update. This object is local, is never written anywhere,
107
+ // and is discarded when the request ends. Named for what it is so the
108
+ // next reader cannot mistake it for persisted state.
109
+ const echoedRequest = {
80
110
  twoFactorSessionVerified: !!twoFactorSessionVerified,
81
111
  twoFactorMethod: twoFactorMethod || (session as any).twoFactorMethod
82
112
  };
83
113
 
84
- console.info('[UPDATE-SESSION] Session updated successfully', {
114
+ // Previously logged "Session updated successfully", which asserted a write
115
+ // that never happened and made the no-op invisible in production logs.
116
+ console.warn('[UPDATE-SESSION] NO-OP: nothing persisted; echoing caller-asserted 2FA state', {
85
117
  userId: session.user?.id,
86
- twoFactorSessionVerified: updatedSession.twoFactorSessionVerified,
87
- twoFactorMethod: updatedSession.twoFactorMethod
118
+ twoFactorSessionVerified: echoedRequest.twoFactorSessionVerified,
119
+ twoFactorMethod: echoedRequest.twoFactorMethod,
120
+ persisted: false
88
121
  });
89
122
 
90
123
  const responseData: UpdateSessionResponse = {
91
124
  success: true,
92
- twoFactorSessionVerified: updatedSession.twoFactorSessionVerified as boolean,
93
- twoFactorMethod: updatedSession.twoFactorMethod as string | undefined
125
+ twoFactorSessionVerified: echoedRequest.twoFactorSessionVerified as boolean,
126
+ twoFactorMethod: echoedRequest.twoFactorMethod as string | undefined,
127
+ persisted: false
94
128
  };
95
129
 
96
130
  return addSecurityHeaders(NextResponse.json(responseData));
@@ -3,6 +3,7 @@ import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG, API_ENDPOINTS } from '../../config/env';
4
4
  import { getTokenTestAware } from '../../lib/test-aware-get-token';
5
5
  import { getSession } from '../../lib/session-store';
6
+ import { logExceptionWithCorrelation, projectIdpError } from '../../lib/safe-error-response';
6
7
 
7
8
  /**
8
9
  * Validates current access token with the IDP and returns normalized info.
@@ -33,12 +34,13 @@ export async function GET(req: NextRequest) {
33
34
  const result = await idpFetchJSON(req, url, { method: 'GET', headers: { Authorization: `Bearer ${bearer}` } });
34
35
 
35
36
  if (!result.ok) {
36
- return NextResponse.json({ success: false, error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status }, data: result.json }, { status: result.status });
37
+ return NextResponse.json({ success: false, error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) } }, { status: result.status });
37
38
  }
38
39
 
39
40
  // Passthrough normalized
40
41
  return NextResponse.json(result.json ?? { success: true }, { status: 200 });
41
42
  } catch (e: any) {
42
- return NextResponse.json({ success: false, error: { code: 'INTERNAL_SERVER_ERROR', message: e?.message || 'validate error' } }, { status: 500 });
43
+ const correlationId = logExceptionWithCorrelation('[AUTH_VALIDATE] Error:', e);
44
+ return NextResponse.json({ success: false, error: { code: 'INTERNAL_SERVER_ERROR', message: 'validate error', correlationId } }, { status: 500 });
43
45
  }
44
46
  }
@@ -12,6 +12,7 @@
12
12
  import { NextRequest, NextResponse } from 'next/server';
13
13
  import { getSession } from '../../server/auth';
14
14
  import { updateTokens, mark2FAComplete } from '../../lib/session-store';
15
+ import { tokenLogId } from '../../lib/token-log-id';
15
16
 
16
17
  interface VerifyCodeRequest {
17
18
  accessToken: string;
@@ -64,7 +65,7 @@ export function createVerifyCodeHandler() {
64
65
  }
65
66
 
66
67
  console.info('[VERIFY-CODE] Updating session with new tokens after 2FA', {
67
- sessionToken: sessionToken.substring(0, 8) + '...',
68
+ sessionToken: tokenLogId(sessionToken),
68
69
  userId: betterAuthSession?.user?.id,
69
70
  hasAccessToken: !!accessToken,
70
71
  hasRefreshToken: !!refreshToken,
@@ -88,7 +89,7 @@ export function createVerifyCodeHandler() {
88
89
  await mark2FAComplete(sessionToken, accessToken);
89
90
 
90
91
  console.info('[VERIFY-CODE] 2FA completion successful', {
91
- sessionToken: sessionToken.substring(0, 8) + '...',
92
+ sessionToken: tokenLogId(sessionToken),
92
93
  userId: betterAuthSession?.user?.id
93
94
  });
94
95
 
@@ -59,6 +59,7 @@ import { ENV_CONFIG } from '../../config/env';
59
59
  import { getTokenTestAware } from '../../lib/test-aware-get-token';
60
60
  import { transitionTo2FASession } from '../../lib/session-store';
61
61
  import { jwtDecode } from '../../lib/jwt-decode';
62
+ import { twoFactorVerifyFailure } from '../../lib/two-factor-verify-failure';
62
63
 
63
64
  export async function POST(req: NextRequest) {
64
65
  try {
@@ -87,15 +88,9 @@ export async function POST(req: NextRequest) {
87
88
  );
88
89
 
89
90
  if (!result.ok) {
90
- return NextResponse.json(
91
- {
92
- success: false,
93
- error: result.json?.message || 'Verification failed',
94
- code: result.json?.code || 'IDP_ERROR',
95
- meta: { attemptedRefresh: result.attemptedRefresh },
96
- },
97
- { status: result.status }
98
- );
91
+ // PAY-1443: never relay the IDP's error text - it arrives as a C# anonymous-object
92
+ // ToString ("{ message = ... }") on the deployed IDP. Classify it, answer a fixed sentence.
93
+ return twoFactorVerifyFailure(result, 'backup_code');
99
94
  }
100
95
 
101
96
  const unwrappedData = result.json?.data || result.json;
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * Generate MFA backup codes (POST /api/Account/mfa/backup-codes, user JWT).
@@ -25,7 +26,7 @@ export async function POST(req: NextRequest) {
25
26
  {
26
27
  success: false,
27
28
  message: 'Upstream error',
28
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
29
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
29
30
  meta: { attemptedRefresh: result.attemptedRefresh },
30
31
  },
31
32
  { status: result.status },
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * MFA methods (GET list / DELETE one, /api/Account/mfa/methods[/{id}],
@@ -13,7 +14,7 @@ function upstreamError(result: { status: number; json: unknown; attemptedRefresh
13
14
  {
14
15
  success: false,
15
16
  message: 'Upstream error',
16
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
17
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
17
18
  meta: { attemptedRefresh: result.attemptedRefresh },
18
19
  },
19
20
  { status: result.status },
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * Confirm TOTP enrolment with the first authenticator code
@@ -26,7 +27,7 @@ export async function POST(req: NextRequest) {
26
27
  {
27
28
  success: false,
28
29
  message: 'Upstream error',
29
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
30
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
30
31
  meta: { attemptedRefresh: result.attemptedRefresh },
31
32
  },
32
33
  { status: result.status },
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * Begin TOTP enrolment (POST /api/Account/mfa/totp/enroll, user JWT).
@@ -26,7 +27,7 @@ export async function POST(req: NextRequest) {
26
27
  {
27
28
  success: false,
28
29
  message: 'Upstream error',
29
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
30
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
30
31
  meta: { attemptedRefresh: result.attemptedRefresh },
31
32
  },
32
33
  { status: result.status },
@@ -34,6 +34,7 @@ import { ENV_CONFIG } from '../../config/env';
34
34
  import { getTokenTestAware } from '../../lib/test-aware-get-token';
35
35
  import { transitionTo2FASession } from '../../lib/session-store';
36
36
  import { jwtDecode } from '../../lib/jwt-decode';
37
+ import { twoFactorVerifyFailure } from '../../lib/two-factor-verify-failure';
37
38
 
38
39
  export async function POST(req: NextRequest) {
39
40
  try {
@@ -64,15 +65,9 @@ export async function POST(req: NextRequest) {
64
65
  );
65
66
 
66
67
  if (!result.ok) {
67
- return NextResponse.json(
68
- {
69
- success: false,
70
- error: result.json?.message || 'Verification failed',
71
- code: result.json?.code || 'IDP_ERROR',
72
- meta: { attemptedRefresh: result.attemptedRefresh },
73
- },
74
- { status: result.status }
75
- );
68
+ // PAY-1443: never relay the IDP's error text - it arrives as a C# anonymous-object
69
+ // ToString ("{ message = ... }") on the deployed IDP. Classify it, answer a fixed sentence.
70
+ return twoFactorVerifyFailure(result, 'totp');
76
71
  }
77
72
 
78
73
  // Unwrap IDP envelope { success, data }
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * List the signed-in user's passkeys (GET /api/Passkeys, user JWT).
@@ -15,7 +16,7 @@ export async function GET(req: NextRequest) {
15
16
  {
16
17
  success: false,
17
18
  message: 'Upstream error',
18
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
19
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
19
20
  meta: { attemptedRefresh: result.attemptedRefresh },
20
21
  },
21
22
  { status: result.status },
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * Manage ONE passkey (PATCH rename / DELETE revoke, /api/Passkeys/{id},
@@ -13,7 +14,7 @@ function upstreamError(result: { status: number; json: unknown; attemptedRefresh
13
14
  {
14
15
  success: false,
15
16
  message: 'Upstream error',
16
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
17
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
17
18
  meta: { attemptedRefresh: result.attemptedRefresh },
18
19
  },
19
20
  { status: result.status },
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * Begin the passkey REGISTRATION ceremony (POST /api/Passkeys/register/options,
@@ -26,7 +27,7 @@ export async function POST(req: NextRequest) {
26
27
  {
27
28
  success: false,
28
29
  message: 'Upstream error',
29
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
30
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
30
31
  meta: { attemptedRefresh: result.attemptedRefresh },
31
32
  },
32
33
  { status: result.status },
@@ -1,6 +1,7 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { idpFetchJSON } from '../../lib/idp-fetch';
3
3
  import { ENV_CONFIG } from '../../config/env';
4
+ import { projectIdpError } from '../../lib/safe-error-response';
4
5
 
5
6
  /**
6
7
  * Finish the passkey REGISTRATION ceremony (POST /api/Passkeys/register/verify,
@@ -25,7 +26,7 @@ export async function POST(req: NextRequest) {
25
26
  {
26
27
  success: false,
27
28
  message: 'Upstream error',
28
- error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: result.json },
29
+ error: { code: 'UPSTREAM_SERVICE_ERROR', status: result.status, details: projectIdpError(result.json) },
29
30
  meta: { attemptedRefresh: result.attemptedRefresh },
30
31
  },
31
32
  { status: result.status },
@@ -3,6 +3,7 @@ import { getSession, isRefreshInProgress } from '../../lib/session-store';
3
3
  import { checkRefreshViability } from '../../lib/refresh-token-validator';
4
4
  import { getTokenTestAware } from '../../lib/test-aware-get-token';
5
5
  import { logger } from '../../config/logger';
6
+ import { tokenLogId } from '../../lib/token-log-id';
6
7
 
7
8
  export async function GET(req: NextRequest) {
8
9
  try {
@@ -14,23 +15,25 @@ export async function GET(req: NextRequest) {
14
15
  finalSessionToken = (token?.sessionToken || token?.redisSessionId) as string;
15
16
  }
16
17
  if (!finalSessionToken) {
17
- return NextResponse.json({ canRefresh: false, reason: 'not_logged_in', sessionToken: null }, { status: 200 });
18
+ return NextResponse.json({ canRefresh: false, reason: 'not_logged_in', sessionTokenId: null }, { status: 200 });
18
19
  }
19
20
  const refreshInProgress = await isRefreshInProgress(finalSessionToken);
20
21
  if (refreshInProgress) {
21
22
  // Still need to get session data for twoFactorComplete even when refresh is in progress
22
23
  const sessionData = await getSession(finalSessionToken);
23
- logger.info('[REFRESH-VIABILITY] Refresh already in progress, telling middleware to wait', { sessionToken: finalSessionToken.substring(0, 8) + '...' });
24
- return NextResponse.json({ canRefresh: true, reason: 'refresh_in_progress', refreshInProgress: true, sessionToken: finalSessionToken, twoFactorComplete: sessionData?.mfaVerified ?? false }, { status: 200 });
24
+ logger.info('[REFRESH-VIABILITY] Refresh already in progress, telling middleware to wait', { sessionToken: tokenLogId(finalSessionToken) });
25
+ return NextResponse.json({ canRefresh: true, reason: 'refresh_in_progress', refreshInProgress: true, sessionTokenId: tokenLogId(finalSessionToken), twoFactorComplete: sessionData?.mfaVerified ?? false }, { status: 200 });
25
26
  }
26
27
  const sessionData = await getSession(finalSessionToken);
27
28
  if (!sessionData) {
28
- return NextResponse.json({ canRefresh: false, reason: 'session_not_found', sessionToken: finalSessionToken }, { status: 200 });
29
+ return NextResponse.json({ canRefresh: false, reason: 'session_not_found', sessionTokenId: tokenLogId(finalSessionToken) }, { status: 200 });
29
30
  }
30
31
  const viabilityCheck = checkRefreshViability(sessionData);
31
- return NextResponse.json({ canRefresh: viabilityCheck.canRefresh, reason: viabilityCheck.reason, timeRemaining: viabilityCheck.timeRemaining, expiresAt: viabilityCheck.expiresAt, accessTokenExpired: viabilityCheck.accessTokenExpired, accessTokenTimeRemaining: viabilityCheck.accessTokenTimeRemaining, sessionToken: finalSessionToken, twoFactorComplete: sessionData.mfaVerified ?? false, userId: sessionData.userId, refreshInProgress: false });
32
+ return NextResponse.json({ canRefresh: viabilityCheck.canRefresh, reason: viabilityCheck.reason, timeRemaining: viabilityCheck.timeRemaining, expiresAt: viabilityCheck.expiresAt, accessTokenExpired: viabilityCheck.accessTokenExpired, accessTokenTimeRemaining: viabilityCheck.accessTokenTimeRemaining, sessionTokenId: tokenLogId(finalSessionToken), twoFactorComplete: sessionData.mfaVerified ?? false, userId: sessionData.userId, refreshInProgress: false });
32
33
  } catch (error) {
33
- logger.error('[REFRESH-VIABILITY] Error checking refresh viability', { error: error instanceof Error ? error.message : String(error) });
34
- return NextResponse.json({ canRefresh: false, reason: 'check_error', error: error instanceof Error ? error.message : String(error) }, { status: 500 });
34
+ const correlationId = globalThis.crypto.randomUUID();
35
+ logger.error('[REFRESH-VIABILITY] Error checking refresh viability', { correlationId, error: error instanceof Error ? error.message : String(error) });
36
+ // PAY-1438: the exception text stays in the log above; the caller gets the id.
37
+ return NextResponse.json({ canRefresh: false, reason: 'check_error', error: 'Failed to check refresh viability', code: 'INTERNAL_ERROR', correlationId }, { status: 500 });
35
38
  }
36
39
  }
@@ -9,6 +9,7 @@ import { getSession as getRedisSession, getBetterAuthSession } from '../../lib/s
9
9
  import { getSession } from '../../server/auth';
10
10
  import { isInitializationFailed, ensureInitialized } from '../../lib/startup-init';
11
11
  import { getIDPClientConfig } from '../../lib/idp-client-config';
12
+ import { tokenLogId } from '../../lib/token-log-id';
12
13
 
13
14
  export async function GET(req: NextRequest) {
14
15
  try {
@@ -123,7 +124,7 @@ export async function GET(req: NextRequest) {
123
124
  const effectiveTwoFactorComplete = sessionMfaComplete && !mfaExpired;
124
125
 
125
126
  console.log('[VIABILITY] Session 2FA check:', {
126
- sessionToken: sessionToken.substring(0, 8) + '...',
127
+ sessionToken: tokenLogId(sessionToken),
127
128
  mfaVerified: sessionData.mfaVerified,
128
129
  twoFactorComplete: (sessionData as any).twoFactorComplete,
129
130
  sessionMfaComplete,
@@ -141,7 +142,7 @@ export async function GET(req: NextRequest) {
141
142
 
142
143
  const response = {
143
144
  authenticated: true,
144
- sessionToken, // Include token for middleware tracking
145
+ sessionTokenId: tokenLogId(sessionToken), // PAY-1481: correlation id for middleware tracking, never the token
145
146
  // 2FA fields - critical for middleware redirect logic
146
147
  requires2FA, // From cached client config (client-wide setting)
147
148
  twoFactorComplete: effectiveTwoFactorComplete, // From session, BUT respects MFA TTL
@@ -176,7 +177,7 @@ export async function GET(req: NextRequest) {
176
177
  console.warn('[VIABILITY] Stale cookie detected - session not in Redis');
177
178
  return NextResponse.json({
178
179
  authenticated: false,
179
- sessionToken // Include token to enable stale cookie detection
180
+ sessionTokenId: sessionToken ? tokenLogId(sessionToken) : null // PAY-1481: presence + correlation for stale cookie detection
180
181
  });
181
182
  }
182
183
 
@@ -1,6 +1,8 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
2
  import { getSession as getBetterAuthSession } from '../../server/auth';
3
3
  import { getSession, updateSession } from '../../lib/session-store';
4
+ import { logExceptionWithCorrelation } from '../../lib/safe-error-response';
5
+ import { tokenLogId } from '../../lib/token-log-id';
4
6
 
5
7
  /**
6
8
  * ⚠️ DESTRUCTIVE TEST-ONLY HANDLER — DO NOT MOUNT IN PRODUCTION. ⚠️
@@ -146,7 +148,7 @@ export const POST = async (req: NextRequest) => {
146
148
  await updateSession(sessionToken, { idpAccessTokenExpires: forced });
147
149
 
148
150
  console.log('[TEST_EXPIRE] Forced access token expiry for session', {
149
- sessionToken: sessionToken.substring(0, 8) + '...',
151
+ sessionToken: tokenLogId(sessionToken),
150
152
  previous: prev ? new Date(prev).toISOString() : null,
151
153
  newExpiry: new Date(forced).toISOString()
152
154
  });
@@ -159,7 +161,7 @@ export const POST = async (req: NextRequest) => {
159
161
  newExpiryIso: new Date(forced).toISOString()
160
162
  });
161
163
  } catch (e) {
162
- console.error('[TEST_EXPIRE] Error:', e);
163
- return NextResponse.json({ success: false, error: e instanceof Error ? e.message : String(e) }, { status: 500 });
164
+ const correlationId = logExceptionWithCorrelation('[TEST_EXPIRE] Error:', e);
165
+ return NextResponse.json({ success: false, error: 'Failed to force expiry', code: 'INTERNAL_ERROR', correlationId }, { status: 500 });
164
166
  }
165
167
  };
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { safeCallbackPath } from './safe-callback';
9
+ import { tokenLogId } from '../lib/token-log-id';
9
10
 
10
11
  // Input types for the decision engine
11
12
  export interface AuthContext {
@@ -140,7 +141,7 @@ export function makeAuthDecision(context: AuthContext): AuthAction {
140
141
  pathname,
141
142
  isLoginPage,
142
143
  sessionExists: sessionStatus.exists,
143
- sessionToken: sessionPointer.sessionToken?.substring(0, 8) + '...'
144
+ sessionToken: tokenLogId(sessionPointer.sessionToken)
144
145
  });
145
146
 
146
147
  // Already on the 2FA page
@@ -21,9 +21,11 @@ import { resolveClientKey } from '../lib/client-key';
21
21
  import { genericOAuth } from 'better-auth/plugins/generic-oauth';
22
22
  import type { IDPClientConfig } from '../lib/idp-client-config';
23
23
  import { getIDPClientConfig } from '../lib/idp-client-config';
24
- import { getAppSlug } from '../lib/app-slug';
24
+ import { getAppSlug, assertAppSlugMatchesIdp } from '../lib/app-slug';
25
25
  import { getRedis } from '../lib/redis';
26
+ import { createSingleFlight, type SingleFlight } from '../lib/single-flight';
26
27
  import { SESSION_TTL } from '../lib/session-store';
28
+ import { tokenLogId } from '../lib/token-log-id';
27
29
 
28
30
  /**
29
31
  * 185121: short sha256 fingerprint for secrets/tokens in log lines — enough
@@ -518,6 +520,7 @@ export function createBetterAuthInstance(
518
520
  idpConfig: IDPClientConfig,
519
521
  opts: CreateBetterAuthInstanceOptions = {}
520
522
  ) {
523
+ assertAppSlugMatchesIdp(idpConfig.clientSlug);
521
524
  const appSlug = idpConfig.clientSlug || getAppSlug();
522
525
 
523
526
  // 185121 line 1: name the secret this instance PINNED, as a hash, never the
@@ -867,6 +870,9 @@ interface BetterAuthModuleState {
867
870
  cachedInstance: any;
868
871
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
869
872
  initPromise: Promise<any> | null;
873
+ // PAY-642: the init attempt, single-flighted so a REJECTED attempt clears itself (see getBetterAuthInstance).
874
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
875
+ initFlight?: SingleFlight<any>;
870
876
  configuredOpts: CreateBetterAuthInstanceOptions;
871
877
  }
872
878
 
@@ -902,19 +908,36 @@ export function configureBetterAuth(opts: CreateBetterAuthInstanceOptions): void
902
908
  state.configuredOpts = opts;
903
909
  }
904
910
 
911
+ /**
912
+ * PAY-642 (card 338215): the init attempt no longer LATCHES A FAILURE.
913
+ *
914
+ * This used to be `state.initPromise ??= getIDPClientConfig(true).then(...)` with no .catch and no reset. One
915
+ * auth request against a cold process while the IdP was unreachable stored a rejected promise, and every later
916
+ * caller replayed it until the process restarted, even after the IdP recovered. This funnel backs every
917
+ * /api/auth/* route, the login GET handler and withAuth. server/auth.ts getAuthInstance() already used
918
+ * createSingleFlight for this exact bug; this sibling funnel was missed.
919
+ *
920
+ * Now the attempt runs through the same helper: concurrent callers share one attempt, a failure still rejects
921
+ * for every caller of THAT attempt (loud), the next call starts a fresh attempt, and a success is cached in
922
+ * state.cachedInstance as before. The flight lives on the globalThis state for the same reason the instance
923
+ * does (duplicated route chunks must share one init).
924
+ */
905
925
  export async function getBetterAuthInstance() {
906
926
  if (state.cachedInstance) return state.cachedInstance;
907
927
 
908
- if (!state.initPromise) {
909
- state.initPromise = getIDPClientConfig(true).then(config => {
928
+ state.initFlight ??= createSingleFlight(() =>
929
+ getIDPClientConfig(true).then(config => {
910
930
  const instance = createBetterAuthInstance(config, state.configuredOpts);
911
931
  state.cachedInstance = instance;
912
932
  console.log('[BETTER_AUTH] Instance created for', config.clientSlug || config.clientId);
913
933
  return instance;
914
- });
915
- }
934
+ })
935
+ );
916
936
 
917
- return state.initPromise;
937
+ const attempt = state.initFlight.get();
938
+ // Kept for callers that inspect it; it always points at the CURRENT attempt, never a settled failure.
939
+ state.initPromise = attempt;
940
+ return attempt;
918
941
  }
919
942
 
920
943
  /**
@@ -961,7 +984,7 @@ export async function exchangeOAuthForIdpTokens(
961
984
  // Read the BA session from Redis
962
985
  const baRaw = await getRedis().get(baKey).catch(() => null);
963
986
  if (!baRaw) {
964
- console.warn('[BETTER_AUTH] exchangeOAuthForIdpTokens: session not found in Redis for token', sessionToken.substring(0, 10));
987
+ console.warn('[BETTER_AUTH] exchangeOAuthForIdpTokens: session not found in Redis for token', tokenLogId(sessionToken));
965
988
  return false;
966
989
  }
967
990
 
@@ -1038,7 +1061,9 @@ export async function exchangeOAuthForIdpTokens(
1038
1061
  });
1039
1062
 
1040
1063
  const oauthResText = await oauthRes.text();
1041
- console.log('[BETTER_AUTH] IDP oauth-callback response:', oauthRes.status, oauthResText.substring(0, 500));
1064
+ // PAY-1427 (QAPert, PR 154 thread 326): this printed the first 500 chars of the oauth-callback TOKEN
1065
+ // envelope on EVERY successful OAuth login (it runs before the !ok check). Status + length only.
1066
+ console.log('[BETTER_AUTH] IDP oauth-callback response:', { status: oauthRes.status, bodyLength: oauthResText.length });
1042
1067
 
1043
1068
  if (!oauthRes.ok) {
1044
1069
  console.error('[BETTER_AUTH] IDP oauth-callback failed:', oauthRes.status);
@@ -1276,7 +1301,7 @@ export async function storeIdpTokensInSession(
1276
1301
  // conjured here would carry no Better Auth cookie, so it would be
1277
1302
  // unreachable by the browser and invisible to every other consumer —
1278
1303
  // failing as "silently signed out" rather than as an error.
1279
- console.warn('[BETTER_AUTH] storeIdpTokensInSession: no BA session for token', sessionToken.substring(0, 10));
1304
+ console.warn('[BETTER_AUTH] storeIdpTokensInSession: no BA session for token', tokenLogId(sessionToken));
1280
1305
  return false;
1281
1306
  }
1282
1307
 
@@ -1399,7 +1424,7 @@ export function createAuthGetHandler(loginPath: string = '/account-auth/login')
1399
1424
 
1400
1425
  const session = await auth.api.getSession({ headers });
1401
1426
  if (session?.session?.token) {
1402
- console.log('[BETTER_AUTH] Got session token from callback:', session.session.token.substring(0, 10), '| email:', session.user?.email);
1427
+ console.log('[BETTER_AUTH] Got session token from callback:', tokenLogId(session.session.token), '| email:', session.user?.email);
1403
1428
  await exchangeOAuthForIdpTokens(session.session.token);
1404
1429
  } else {
1405
1430
  console.warn('[BETTER_AUTH] Could not get session after OAuth callback');
@@ -215,7 +215,8 @@ export async function idpRefreshToken(
215
215
 
216
216
  if (!response.ok) {
217
217
  const errorText = await response.text().catch(() => 'Unknown error');
218
- console.error('[IDP_CLIENT] Token refresh failed:', response.status, errorText);
218
+ // PAY-1427: never the raw upstream body (the refresh.ts:528 twin PR 139 fixed). Status + length only.
219
+ console.error('[IDP_CLIENT] Token refresh failed:', { status: response.status, bodyLength: errorText.length });
219
220
  return {
220
221
  success: false,
221
222
  error: {
@@ -214,7 +214,10 @@ export function DataBrowserTab({
214
214
 
215
215
  if (!response.ok) {
216
216
  const errData = await response.json().catch(() => ({}));
217
- throw new Error(errData.error?.message || 'Delete failed');
217
+ // PAY-1425: the handler returns a fixed message plus a correlationId (never upstream
218
+ // text). Surface the id so an admin can quote it to an operator.
219
+ const ref = errData.error?.correlationId ? ` (ref ${errData.error.correlationId})` : '';
220
+ throw new Error(`${errData.error?.message || 'Delete failed'}${ref}`);
218
221
  }
219
222
 
220
223
  setSuccess(`Record ${id} deleted`);