stack/apps/backend/src/lib
Mantra a132dd23f9
fix: refresh-token P2025 race with concurrent sign-out (#1372)
## Summary
- Fixes Sentry
[STACK-BACKEND-146](https://stackframe-pw.sentry.io/issues/7377768662/):
`PrismaClientKnownRequestError` P2025 on
`projectUserRefreshToken.update()` during token refresh.
- Root cause: `generateAccessTokenFromRefreshTokenIfValid`
(`apps/backend/src/lib/tokens.tsx`) reads the refresh-token row
upstream, then issues `.update(...)` on it (and on `projectUser`) inside
a `Promise.all`. If a concurrent sign-out (`DELETE
/auth/sessions/current`), session revoke, password change, or user
deletion removes the row between the read and the update, Prisma throws
P2025 and the refresh endpoint 500s.

## Changes
- `apps/backend/src/lib/tokens.tsx` — swap the two `.update(...)`s for
`.updateMany(...)` so a missing row is a no-op, then re-check the
refresh token still exists; return `null` if it doesn't. The refresh
route already maps `null` -> `KnownErrors.RefreshTokenNotFoundOrExpired`
(401), which is the correct user-facing behavior for a just-revoked
session.
- `apps/backend/src/oauth/model.tsx` — in `generateAccessToken`, replace
the "ultra-rare race condition" `throwErr` fallback with `throw new
KnownErrors.RefreshTokenNotFoundOrExpired()` so concurrent sign-out
during an OAuth `refresh_token` grant returns a clean 401 instead of
500.
-
`apps/e2e/tests/backend/endpoints/api/v1/auth/sessions/current/refresh-race.test.ts`
— new regression test that fires `POST /auth/sessions/current/refresh`
and `DELETE /auth/sessions/current` concurrently with the same refresh
token. Before the fix it 500s on the first iteration; after, it passes
in ~12s.

## Test plan
- [x] New regression test passes locally.
- [x] Existing `auth/sessions/**` + `auth/oauth/token.test.ts` still
pass (27 tests, 3 todo, 0 failed).
- [ ] CI green.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Refresh flows now detect a revoked or removed refresh token during
concurrent operations and stop cleanly, preventing issuance of an access
token from stale data.
* A specific refresh-token-not-found/expired error is returned instead
of a generic failure when refresh cannot proceed.

* **Tests**
* Added E2E tests exercising concurrent refresh vs sign-out to prevent
race-condition crashes and validate safe handling of competing requests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-04-24 18:44:39 +00:00
..
ai ai proxy fix (#1343) 2026-04-19 22:57:38 -07:00
bulldozer Make Bulldozer SQL statements deterministic 2026-04-18 16:43:26 -07:00
payments Make Bulldozer SQL statements deterministic 2026-04-18 16:43:26 -07:00
cache.tsx Upgrade Prisma to v7 (#1064) 2025-12-26 08:13:34 -08:00
cel-evaluator.ts Turnstile integration for fraud protection (#1239) 2026-03-20 21:26:45 +00:00
clickhouse-errors.ts Ask AI Huge Response (#1328) 2026-04-13 15:12:07 -07:00
clickhouse.tsx Increase Clickhouse request timeout 2026-04-18 21:46:10 -07:00
config.tsx Local emulator base (#1233) 2026-03-10 15:15:06 -07:00
contact-channel.tsx External db sync (#1036) 2026-02-05 12:04:31 -08:00
dev-perf-stats.tsx Fix dev-perf-stats 2026-02-04 13:59:31 -08:00
dev-request-stats.tsx Fix dev stats accuracy 2025-12-29 17:15:08 +01:00
email-delivery-stats.tsx [Refactor][Feat][Fix] Rework Email Section With New Sent Page, Better Drafts Page, and Settings Page (#1221) 2026-03-11 12:01:36 -07:00
email-drafts.tsx fix types 2025-12-26 18:11:37 +01:00
email-queue-step.test.tsx fix(email-queue): recover stuck sending without duplicate retry (#1356) 2026-04-24 11:00:46 -07:00
email-queue-step.tsx fix(email-queue): recover stuck sending without duplicate retry (#1356) 2026-04-24 11:00:46 -07:00
email-rendering.test.tsx [Refactor][Feat][Fix] Rework Email Section With New Sent Page, Better Drafts Page, and Settings Page (#1221) 2026-03-11 12:01:36 -07:00
email-rendering.tsx Emails redesign (#1076) 2026-02-16 14:57:17 -08:00
email-template-rewrite.ts Custom dashboards and unified ai no playground (#1243) 2026-03-13 20:24:40 +00:00
emailable.tsx Add more error messages for 249 Emailable errors 2026-04-09 11:06:27 -07:00
emails-low-level.tsx [Refactor] Make all SMTP 4yz Errors Retryable (#1293) 2026-04-07 16:20:39 +00:00
emails.tsx Backend fallback (cloud run) (#1306) 2026-04-11 00:57:37 +00:00
end-users.tsx Backend fallback (cloud run) (#1306) 2026-04-11 00:57:37 +00:00
events.tsx Backend fallback (cloud run) (#1306) 2026-04-11 00:57:37 +00:00
external-db-sync-metadata.ts [Refactor] Improve CI Run Times by Reducing Test Flakiness and Speeding up Test Suite (#1166) 2026-02-10 19:43:10 -08:00
external-db-sync-queue.ts Clickhouse sync fixing (#1198) 2026-02-16 11:30:38 -08:00
external-db-sync.ts clickhouse new syncs and verify-data (#1304) 2026-04-08 14:43:22 -07:00
featurebase.tsx Replace Web3Forms with internal feedback emails (#1244) 2026-03-23 17:07:37 -07:00
images.tsx Project logo upload (#817) 2025-08-19 04:45:16 +02:00
internal-api-keys.tsx "Require publishable client key" toggle (#1158) 2026-02-19 10:23:16 -08:00
internal-feedback-emails.tsx dev tool indicator (#1272) 2026-04-13 17:43:03 -07:00
js-execution.tsx local emulator security and features fixes (#1247) 2026-04-14 15:36:24 -07:00
local-emulator.test.ts make config typesafe (#1254) 2026-04-06 18:31:55 +00:00
local-emulator.ts make config typesafe (#1254) 2026-04-06 18:31:55 +00:00
managed-email-domains.tsx Managed email provider (#1222) 2026-03-09 20:23:11 -07:00
managed-email-onboarding.tsx Managed email provider (#1222) 2026-03-09 20:23:11 -07:00
metrics-activity-split.ts Overview revamp (#1238) 2026-04-15 09:36:00 -07:00
notification-categories.ts Email outbox backend (#1030) 2025-12-12 10:26:38 -08:00
oauth.tsx Turnstile integration for fraud protection (#1239) 2026-03-20 21:26:45 +00:00
openapi.tsx chore(backend): align OpenAPI output with Mintlify and mirror specs to docs-mintlify. 2026-04-08 17:12:27 -05:00
payments.test.tsx Payments bulldozer txn rework (#1315) 2026-04-17 22:11:21 +00:00
payments.tsx Payments bulldozer txn rework (#1315) 2026-04-17 22:11:21 +00:00
permissions.tsx clickhouse new syncs and verify-data (#1304) 2026-04-08 14:43:22 -07:00
preview-mode.ts stack auth preview mode (#1307) 2026-04-08 16:57:42 -07:00
product-versions.tsx [Fix] [Refactor] Implement Base Settings for Stack-Auth Plans and Move Metadata from Stripe Webhook Event to Table (#1214) 2026-02-23 22:09:27 -08:00
projects.tsx Add onboarding status to Project model and implement related database… (#1246) 2026-03-13 12:00:40 -07:00
redirect-urls.test.tsx [Fix] [Feat] Update OAuth Sign-In and Get Token Functions to Work (#1130) 2026-01-28 02:17:27 +00:00
redirect-urls.tsx [Fix] [Feat] Update OAuth Sign-In and Get Token Functions to Work (#1130) 2026-01-28 02:17:27 +00:00
request-checks.tsx Upgrade Prisma to v7 (#1064) 2025-12-26 08:13:34 -08:00
risk-scores.tsx rework weights for same name signups (#1298) 2026-04-12 23:30:55 +00:00
seed-dummy-data.ts Fast-start local emulator via RAM snapshot + live secret rotation (#1340) 2026-04-20 14:24:49 -07:00
session-replays.tsx Analytics event tracking (#1208) 2026-02-17 18:33:01 -08:00
sign-up-context.ts Turnstile integration for fraud protection (#1239) 2026-03-20 21:26:45 +00:00
sign-up-heuristics.tsx Turnstile integration for fraud protection (#1239) 2026-03-20 21:26:45 +00:00
sign-up-rules.ts Backend fallback (cloud run) (#1306) 2026-04-11 00:57:37 +00:00
stripe-proxy.tsx one time payments (#865) 2025-09-12 17:14:09 -07:00
stripe.tsx Payments bulldozer txn rework (#1315) 2026-04-17 22:11:21 +00:00
telegram.tsx payment email templates (#1106) 2026-01-20 18:45:01 -08:00
tenancies.tsx Make most queries readonly 2026-01-02 04:25:05 +01:00
tokens.tsx fix: refresh-token P2025 race with concurrent sign-out (#1372) 2026-04-24 18:44:39 +00:00
turnstile.tsx Turnstile integration for fraud protection (#1239) 2026-03-20 21:26:45 +00:00
types.tsx Upgrade Prisma to v7 (#1064) 2025-12-26 08:13:34 -08:00
upstash.tsx local emulator security and features fixes (#1247) 2026-04-14 15:36:24 -07:00
users.tsx Enhance error handling and logging in Emailable response validation (#1292) 2026-04-01 09:21:43 -07:00
webhooks.tsx stack auth preview mode (#1307) 2026-04-08 16:57:42 -07:00