Skip to content

feat(auth): store PKCE verifiers in per-flow slots to survive overlapping flows - #2569

Merged
mandarini merged 4 commits into
masterfrom
fix/pkce-verifier-per-flow-slots
Jul 28, 2026
Merged

mandarini merged 4 commits into
masterfrom
fix/pkce-verifier-per-flow-slots

Conversation

@mandarini

@mandarini mandarini commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Stores each PKCE code verifier in its own bounded storage slot (${storageKey}-flow-<flowId>-code-verifier, ring of 5) instead of a single fixed key, so overlapping OAuth or password recovery flows no longer overwrite each other's verifier. signInWithOAuth and linkIdentity return the flowId, exchangeCodeForSession accepts it as an optional selector, and enabling experimental.appendPkceFlowIdToRedirects appends a reserved sb_flow_id param to redirectTo that round-trips through the auth server so browser callbacks pick the right verifier automatically. When a flow id is present but its verifier is gone, the exchange fails fast instead of submitting another flow's verifier, which would consume the single-use auth code.

The redirect param is opt-in because the auth server matches redirect URLs against the allow list including the query string. Slot keys end in -code-verifier so @supabase/ssr's server adapter persists them immediately (no ssr change needed) and contain no dot to avoid its chunked cookie naming (<key>.<number>). Sign-out and session teardown clear all pending slots; the legacy fixed key is still written and read as a fallback, so single-flow callers and older SDK versions are unaffected.

Closes #2557

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 47a8d4a1-571c-4fd1-84f8-9e766bf8093d

📥 Commits

Reviewing files that changed from the base of the PR and between 873ce53 and 73030ee.

📒 Files selected for processing (3)
  • packages/core/auth-js/src/GoTrueClient.ts
  • packages/core/auth-js/src/lib/types.ts
  • packages/core/auth-js/test/GoTrueClient.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/auth-js/src/lib/types.ts
  • packages/core/auth-js/src/GoTrueClient.ts

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Supports multiple concurrent PKCE flows with distinct verifier storage, bounded by a configurable maximum.
    • Adds optional sb_flow_id correlation to PKCE redirects and propagates flowId through OAuth/auth responses.
    • exchangeCodeForSession now accepts an optional flow identifier for accurate callback handling.
  • Bug Fixes
    • Tightens PKCE callback detection and URL parameter handling; improves flow-scoped verifier cleanup on success and error (including sign-out teardown).
  • Tests
    • Added browser and unit test coverage for overlapping flows, redirect/flow-id behavior, recovery, SSR-like storage, eviction, and cleanup.

Walkthrough

PKCE flows now receive unique flow IDs and store verifiers in bounded per-flow slots while retaining legacy compatibility. Redirect URLs can include sb_flow_id through an experimental flag. Code exchange accepts explicit or callback-derived flow IDs, retrieves the matching verifier, and cleans up only that flow. OAuth responses expose the flow ID, sign-out clears all pending verifiers, and tests cover browser, concurrent, recovery, bounded-storage, and SSR-like scenarios.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Storage
  participant AuthServer
  Client->>Storage: store verifier for flowId
  Client->>AuthServer: start OAuth with redirect containing flowId
  AuthServer-->>Client: callback with code and flowId
  Client->>Storage: retrieve verifier for flowId
  Client->>AuthServer: exchange code and verifier
  Client->>Storage: remove consumed flow
Loading

Assessment against linked issues

Objective Addressed Explanation
Preserve distinct verifier pairs for overlapping PKCE starts and exchange each callback with its own verifier [#2557] ✅
Prevent one callback’s cleanup from removing another pending verifier [#2557] ✅
Retain compatibility when no flow ID is available [#2557] ✅

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the auth-js Related to the auth-js library. label Jul 28, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@supabase/auth-js

npm i https://pkg.pr.new/@supabase/auth-js@2569

@supabase/functions-js

npm i https://pkg.pr.new/@supabase/functions-js@2569

@supabase/postgrest-js

npm i https://pkg.pr.new/@supabase/postgrest-js@2569

@supabase/realtime-js

npm i https://pkg.pr.new/@supabase/realtime-js@2569

@supabase/storage-js

npm i https://pkg.pr.new/@supabase/storage-js@2569

@supabase/supabase-js

npm i https://pkg.pr.new/@supabase/supabase-js@2569

commit: 73030ee

@mandarini mandarini self-assigned this Jul 28, 2026
@coveralls

coveralls commented Jul 28, 2026 •

Copy link
Copy Markdown

Coverage Status

Coverage is 73.391% — fix/pkce-verifier-per-flow-slots into master. No base build found for master.

@mandarini mandarini changed the title fix(auth): store PKCE verifiers in per-flow slots to survive overlapping flows feat(auth): store PKCE verifiers in per-flow slots to survive overlapping flows Jul 28, 2026
@mandarini
mandarini marked this pull request as ready for review July 28, 2026 13:11
@mandarini
mandarini requested review from a team as code owners July 28, 2026 13:11
@mandarini
mandarini merged commit 97b58eb into master Jul 28, 2026
31 checks passed
@mandarini
mandarini deleted the fix/pkce-verifier-per-flow-slots branch July 28, 2026 15:36
mandarini added a commit to supabase/ssr that referenced this pull request Jul 28, 2026
This PR updates `@supabase/supabase-js` to v2.111.0.

**Source**: supabase-js-stable-release

---

## Test update included

supabase-js 2.111.0
([supabase/supabase-js#2569](supabase/supabase-js#2569))
stores PKCE verifiers in per-flow slots, so a flow start now writes
three storage keys instead of one: the per-flow slot, the flow index,
and the legacy fixed `-code-verifier` key. Our server storage adapter
flushes each of these immediately (by design — slot keys deliberately
end in `-code-verifier`), so `setAll` now fires 3 times per flow start
instead of 1.

The PKCE verifier test asserted that internal flush count and
snapshotted the exact cookies, so we updated it: expect 3 `setAll`
calls, normalize the random flow id in slot cookie names, and regenerate
the snapshots. Test-only change — no source changes needed, the adapter
was already prepared in #275.

**Why this isn't a breaking change in supabase-js:** the writes are
purely additive — the legacy key is still written with the same format,
and `exchangeCodeForSession` without a flow id reads it exactly as
before. The new slot-only lookup only kicks in when a flow id is
explicitly passed or the opt-in
`experimental.appendPkceFlowIdToRedirects` flag is enabled.

---

## Release Notes

## v2.111.0

## 2.111.0 (2026-07-28)

### 🚀 Features

- **auth:** store PKCE verifiers in per-flow slots to survive
overlapping flows
([#2569](supabase/supabase-js#2569))

### ❤️ Thank You

- Katerina Skroumpelou @mandarini

This PR was created automatically.

---------

Co-authored-by: supabase-workflow-trigger[bot] <266661614+supabase-workflow-trigger[bot]@users.noreply.github.com>
Co-authored-by: Katerina Skroumpelou <[email protected]>
mandarini pushed a commit to supabase/supabase that referenced this pull request Aug 11, 2026
This PR updates @supabase/*-js libraries to version 2.112.3.

**Source**: manual

**Changes**:
- Updated @supabase/supabase-js to 2.112.3
- Updated @supabase/auth-js to 2.112.3
- Updated @supabase/realtime-js to 2.112.3
- Updated @supabase/postgest-js to 2.112.3
- Refreshed pnpm-lock.yaml

---

## Release Notes

## v2.112.3

## 2.112.3 (2026-08-11)

### 🩹 Fixes

- **supabase:** add trace context headers to canonical CORS allow-list
([#2603](supabase/supabase-js#2603))
- **supabase:** improve trace propagation sampling and diagnostics
([#2604](supabase/supabase-js#2604))

### ❤️ Thank You

- Katerina Skroumpelou @mandarini
## v2.112.2

## 2.112.2 (2026-08-06)

### 🩹 Fixes

- **realtime:** prevent duplicate on bindings
([#2594](supabase/supabase-js#2594))
- **realtime:** clear stale join payload on sign-out
([#2597](supabase/supabase-js#2597))

### ❤️ Thank You

- Filipe Cabaço @filipecabaco
- Vaibhav @7ttp
## v2.112.1

## 2.112.1 (2026-08-05)

### 🩹 Fixes

- **auth:** preserve 5xx error message
([#2587](supabase/supabase-js#2587))
- **realtime:** ensure setAuth doesn't disable token refresh
([#2592](supabase/supabase-js#2592))

### ❤️ Thank You

- Eduardo Gurgel
- Vaibhav @7ttp
## v2.112.0

## 2.112.0 (2026-08-03)

### 🚀 Features

- **supabase:** move OpenTelemetry tracing to opt-in /tracing subpath
([#2583](supabase/supabase-js#2583))

### 🩹 Fixes

- **auth:** accept uppercase UUIDs in validateUUID
([#2467](supabase/supabase-js#2467))
- **postgrest:** honour throwOnError when maybeSingle finds multiple
rows ([#2580](supabase/supabase-js#2580))
- **storage:** resolve createSignedUrls return type mismatch
([#2474](supabase/supabase-js#2474))
- **storage:** expose service error code on StorageApiError
([#2537](supabase/supabase-js#2537))
- **supabase:** forward db retry option
([#2571](supabase/supabase-js#2571))

### ❤️ Thank You

- Anubhav Anand @i-anubhav-anand
- Gourab Singha @gourabsingha1
- Juhef @juheff
- Katerina Skroumpelou @mandarini
- Thribhuvan
- Vaibhav @7ttp
- Zuhef Ahmed @Zuhef
## v2.111.0

## 2.111.0 (2026-07-28)

### 🚀 Features

- **auth:** store PKCE verifiers in per-flow slots to survive
overlapping flows
([#2569](supabase/supabase-js#2569))

### ❤️ Thank You

- Katerina Skroumpelou @mandarini

This PR was created automatically.

Co-authored-by: supabase-workflow-trigger[bot] <266661614+supabase-workflow-trigger[bot]@users.noreply.github.com>
spydon added a commit to supabase/supabase-flutter that referenced this pull request Aug 19, 2026
#1662)

## Summary

Each PKCE flow now keeps its code verifier in a slot of its own instead
of a single fixed key that a later flow silently overwrote. Starting an
OAuth sign-in while a password recovery was still pending used to break
whichever of the two completed second.

**Outcome:** implemented

Closes #1648, SDK-1429.

## What changed

- **Per-flow verifier slots**
(`packages/supabase_auth/lib/src/pkce_verifier_store.dart`, new).
Verifiers are stored under
`supabase.auth.token-flow-<flowId>-code-verifier`. At most five are
kept, oldest evicted first, tracked in an index entry because
`AuthAsyncStorage` cannot enumerate keys. Flow ids are validated against
a fixed shape both when they are read and when they are stored, since
they can arrive from a callback URL and a slot written under an id the
index cannot validate could never be evicted again. Marked `@internal`.
- **`OAuthResponse.flowId`** returns the id of the flow that
`getOAuthSignInUrl` or `getLinkIdentityUrl` started, `null` on the
implicit flow.
- **`exchangeCodeForSession(authCode, {String? flowId})`** picks that
flow's verifier. A given flow id is looked up in its slot only,
deliberately without falling back to the most recent verifier:
submitting a mismatched verifier would spend the single-use auth code. A
malformed flow id fails immediately with a message naming it, rather
than surfacing later as a missing verifier, which would point at storage
instead of the callback URL. Without a flow id the most recently started
flow's verifier is used, so existing callers behave exactly as before.
- **`getSessionFromUrl`** reads the reserved `sb_flow_id` query
parameter off the callback URL, which is how `supabase_flutter` handles
auth deep links, so the right verifier is picked without the app
threading anything itself.
- **`appendPkceFlowIdToRedirects`** on `AuthClient`, `AuthClientOptions`
and `FlutterAuthClientOptions` appends `sb_flow_id` to the redirect URL
of `signUp`, `signInWithOtp`, `getSSOSignInUrl`, `resend`, `updateUser`,
`resetPasswordForEmail` and the OAuth authorize URL. It is the only way
to tell concurrent email OTP, password recovery and email change flows
apart, since those hand back no flow id. Opt-in and defaulting to false,
because the auth server matches redirect URLs against the allow list
including the query string, so an entry without a wildcard stops
matching once the parameter is appended.
- **Sign-out** clears every pending verifier rather than just the one
fixed key, and `sb_flow_id` is stripped from the browser URL after a
successful exchange on web.

The legacy `supabase.auth.token-code-verifier` key is still written and
read as a fallback, so nothing on the existing API breaks. Exchanging
through that fallback now also clears the slot the verifier came from,
so a spent verifier cannot be reached again through its own flow id and
dead entries do not eat into the five concurrent slots.

## Notes for reviewers

- No breaking changes. Every new parameter is optional and defaults to
the previous behavior.
- One behavior change to be aware of: `getSessionFromUrl` now reads
`sb_flow_id`, so a callback URL that already carries that reserved name
with a value outside the generated shape will fail the exchange rather
than silently using the most recent verifier.
- `appendPKCEFlowIdToRedirect` also strips the reserved parameter from
the fragment, not just the query, because `getSessionFromUrl` folds the
fragment into the query parameters and a stale copy parsed after the
appended one would win.

## Deviation from the reference

The issue text says `signInWithOtp`, `signInWithSSO`, `resend`,
`updateUser` and `resetPasswordForEmail` also return a flow id. The
reference implementation only adds it to the OAuth response, so this
matches supabase-js as merged rather than as described.

## Reference

supabase-js PR supabase/supabase-js#2569, commit
97b58eb428556d768ae982c511fa10c4b7b8119f.

## Compliance matrix

`auth.sign_in.exchange_code_for_session` stays `implemented`, with
`AuthClient.appendPkceFlowIdToRedirects`,
`AuthClientOptions.appendPkceFlowIdToRedirects` and
`OAuthResponse.flowId` registered under it.

## Tests

43 new tests in `packages/supabase_auth/test/pkce_flow_test.dart`
covering the slot ring and its eviction, the index tolerating malformed
contents, flow id validation on both read and write, redirect parameter
construction including fragments and names that only share the reserved
prefix, and client level behavior: two overlapping flows keeping
separate verifiers, exchanging with and without a flow id, unknown and
malformed flow ids failing fast, `getSessionFromUrl` picking the flow
off the URL, and sign-out clearing everything.

Full `supabase_auth` (523), `supabase` (142) and `supabase_flutter` (76)
suites pass locally against the local Supabase stack.
grdsdev added a commit to supabase/sdk that referenced this pull request Aug 20, 2026
## Summary
- Adds `auth.sign_in.pkce_flow_id` to `capabilities/auth.yaml`: a
per-flow, bounded (ring of 5) PKCE verifier storage keyed by a generated
flow id, with an optional flow id selector on exchange-code-for-session.
- Adds `specs/auth/pkce_flow_id.md` describing the behavior, fail-fast
error contract, and scope boundary (the reference implementation's
opt-in redirect-param propagation is called out as not required for
baseline parity).

## Why
Validated against the merged `supabase-js` PR
[supabase/supabase-js#2569](supabase/supabase-js#2569):
starting two PKCE flows concurrently (two OAuth sign-ins, or an OAuth
flow started while a password-recovery flow is pending) used to silently
overwrite the earlier flow's verifier. This spec is a prerequisite for
[SDK-1395](https://linear.app/supabase/issue/SDK-1395) (supabase-swift
parity implementation).

## Test plan
- [x] `npm run validate` passes locally in `scripts/capability-matrix`
- [ ] CODEOWNERS review
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth-js Related to the auth-js library.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

auth: overlapping PKCE flows overwrite each other's code verifier

3 participants