Skip to content

test(auth): pin oauth refresh-token reuse detection and document its limits - #1490

Merged
prisis merged 8 commits into
alphafrom
fix/oauth-refresh-reuse
Nov 5, 2026
Merged

prisis merged 8 commits into
alphafrom
fix/oauth-refresh-reuse

Conversation

@prisis

@prisis prisis commented Nov 5, 2026

Copy link
Copy Markdown
Member

Summary

A regression test for OAuth refresh-token reuse detection, plus docs on where it stops. Void added reuse detection in voidzero-dev/void#631. Lunora gets it from better-auth's oauthProvider (1.7.16): replaying a rotated refresh token revokes the token family for that client and user. Nothing tested that until now.

  • Test (oauth-refresh-reuse.behaviour.test.ts). It runs the real flow over HTTP: sign-up and sign-in, client registration, PKCE authorization code, refresh, then a replay. It runs against both better-auth's memory adapter and Lunora's SQL store. It checks that:
    • the replay is refused with invalid_grant;
    • the newer refresh token and the access tokens die;
    • the same user's grant to another client survives, and so does another user's grant to the same client;
    • inside the retry window the same tokens come back, and a replay after the window revokes the family;
    • expiry slides with each refresh, and an expired token is refused without revoking the family.
  • Proof the test catches breakage. I patched better-auth in node_modules five ways (dropping the clientId filter, dropping the userId filter, no revocation on replay, revocation on expiry, the wrong error code). Each patch made the matching tests fail on both backends, and the original file was restored, with its checksum verified.
  • Docs (packages/auth/docs/plugins.mdx). They state the limits:
    • Only access tokens tied to a refresh token are revoked.
    • JWT access tokens (a resource is requested and disableJwtPlugin is unset) stay valid until they expire. Under mcp() that is the normal case, so use a short accessTokenExpiresIn.
    • A replay inside refreshTokenReuseInterval (default 0, or 30s under mcp()) gets live tokens back and is not detected.
    • Upstream's two-step family delete is not atomic.
  • Test helper. The memory-adapter table setup moved into __tests__/helpers/memory-tables.ts, which createMemoryAuth now also uses.

No production code changes.

Test plan

  • @lunora/auth: eslint, lint:types, tests 603/603
  • Prettier on the docs
  • Ran the upstream mutations above; each was seen failing the right tests

Checklist

  • Commit messages follow Conventional Commits
  • Added or updated tests covering the change
  • Updated docs (packages/auth/docs/plugins.mdx)

🤖 Generated with Claude Code

prisis and others added 7 commits November 5, 2026 01:34
Drive oauthProvider's real token endpoint through authorization_code ->
refresh -> replay and assert better-auth's reuse detection (RFC 9700
§4.14.2): replaying a rotated refresh token is refused and revokes every
refresh and opaque access token that user holds for that client, including
sibling grants, while another user's grant survives. Also pins the
refreshTokenReuseInterval retry window and the sliding refreshTokenExpiresIn.

Runs over better-auth's memory adapter and Lunora's SQL store, since
rotation relies on incrementOne with a revoked-is-null guard and family
revocation on deleteMany with an `in` filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Explain what a replayed rotated refresh token does under oauthProvider: the
(client, user) family is revoked, JWT access tokens outlive it, expiry slides
with each rotation, and refreshTokenReuseInterval defaults to 0 so a lost
response retry also revokes. Note the non-atomic revocation upstream tracks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replay of a rotated refresh token after refreshTokenReuseInterval has
elapsed must still revoke the family; assert it with an injected clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mcp() is oauthProvider underneath with refreshTokenReuseInterval defaulting
to 30 seconds; say so and clarify which token the replay revokes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
createMemoryAuth seeded its memoryAdapter store inline, and the refresh-reuse suite copied
that loop. memoryTables builds the store from the resolved options so both can share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- pin that a replay leaves the same user's grant to another client alive
- pin that an expired refresh token does not revoke its family
- assert the replaying user's family is revoked in the other-user case
- assert invalid_grant on every refused refresh, not just a 400
- treat a failed introspection as an error, never as "revoked"
- register the client and sign in through the typed API and HTTP, dropping
  the hand-typed ProviderAuth and its cast; reuse signInAndCookie and
  memoryTables; hoist the pure helpers to module scope

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only access tokens issued with a refresh token are revoked; JWT access tokens depend on
disableJwtPlugin; a replay inside refreshTokenReuseInterval gets the rotation's tokens and
revokes nothing; and mcp() binds tokens to its resource, so its access tokens are JWTs that
outlive revocation, on top of its 30 s default window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters: 4

  • packages/auth/__tests__/helpers/memory-auth.ts is excluded by !**/__tests__/** and included by packages/**
  • packages/auth/__tests__/helpers/memory-tables.ts is excluded by !**/__tests__/** and included by packages/**
  • packages/auth/__tests__/oauth-refresh-reuse.behaviour.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/auth/docs/plugins.mdx is excluded by !**/docs/** and included by packages/**

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Test OAuth refresh-token reuse and document its limits

🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Test refresh-token replay, family revocation, retry windows, and sliding expiry across memory and
 SQL backends.
• Document which tokens survive revocation and the security trade-offs of OAuth and MCP defaults.
• Share resolved memory-adapter table setup between authentication test helpers.
Diagram

graph TD
  T["HTTP regression suite"] --> O["OAuth token endpoint"] --> B["Memory or SQL"] --> D{"Token status"}
  D -->|fresh| R["Rotate token"]
  D -->|retry window| W["Return same tokens"]
  D -->|used replay| F["Revoke token family"] --> E["invalid_grant"]
  D -->|expired| E
Loading
High-Level Assessment

Keep the endpoint-level, dual-backend tests: they cover upstream provider behavior and Lunora's adapter contract without duplicating OAuth logic in production. Narrower mocked tests would be cheaper but would not verify the rotation and family-deletion behavior this PR aims to pin.

Files changed (4) +449 / -20

Refactor (1) +5 / -20
memory-auth.tsUse shared memory-table setup +5/-20

Use shared memory-table setup

• Replaces inline creation of resolved better-auth tables with the shared memoryTables helper while retaining a fresh in-memory auth instance.

packages/auth/tests/helpers/memory-auth.ts

Tests (2) +384 / -0
memory-tables.tsExtract resolved plugin table initialization +17/-0

Extract resolved plugin table initialization

• Adds a helper that creates empty memory-adapter tables from resolved auth options, including tables required by enabled plugins.

packages/auth/tests/helpers/memory-tables.ts

oauth-refresh-reuse.behaviour.test.tsPin OAuth refresh-token reuse behavior on two backends +367/-0

Pin OAuth refresh-token reuse behavior on two backends

• Adds real HTTP authorization-code, refresh, replay, and introspection tests against the memory adapter and Lunora SQL store. Checks client-user family boundaries, linked token revocation, retry-window behavior, sliding expiry, and rejection of expired tokens without family revocation.

packages/auth/tests/oauth-refresh-reuse.behaviour.test.ts

Documentation (1) +60 / -0
plugins.mdxExplain refresh-token rotation and revocation limits +60/-0

Explain refresh-token rotation and revocation limits

• Documents provider family scope, opaque versus JWT access-token behavior, sliding expiry, and retry-window trade-offs. Calls out MCP defaults and the upstream non-atomic revocation sequence.

packages/auth/docs/plugins.mdx

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can turn these tips off under Display > Comment parts

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@github-actions github-actions Bot added the vouch:trusted PR author is a collaborator, a bot or on the VOUCHED list. label Nov 5, 2026
@netlify

netlify Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit b6979b3
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6aebd7a8911c71f0acdd5f95
😎 Deploy Preview https://deploy-preview-1490--lunorash.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added package: auth size:M Size of the change, tests and generated files excluded. labels Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@codspeed

codspeed Bot commented Nov 5, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 3 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 3 untouched benchmarks
⏩ 396 skipped benchmarks1


Comparing fix/oauth-refresh-reuse (a641b83) with alpha (a92d85c)2

Open in CodSpeed

Footnotes

  1. 396 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on alpha (788ba73) during the generation of this report, so a92d85c was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@prisis
prisis merged commit 9d0fedc into alpha Nov 5, 2026
10 of 11 checks passed
@prisis
prisis deleted the fix/oauth-refresh-reuse branch November 5, 2026 01:11
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.46%. Comparing base (2d7eb96) to head (b6979b3).
⚠️ Report is 5 commits behind head on alpha.

Additional details and impacted files
@@             Coverage Diff             @@
##            alpha    #1490       +/-   ##
===========================================
+ Coverage   83.97%   88.46%    +4.48%     
===========================================
  Files        2089      248     -1841     
  Lines      126052    15958   -110094     
  Branches    32259     4503    -27756     
===========================================
- Hits       105855    14117    -91738     
+ Misses      19447     1711    -17736     
+ Partials      750      130      -620     

see 1842 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch was previously deployed

1 inactive deployment
benchmarks — b6979b32 Deployed Nov 5, 2026 by prisis via Benchmarks #7077
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🟠 Medium blast radius package: auth size:M Size of the change, tests and generated files excluded. vouch:trusted PR author is a collaborator, a bot or on the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants