Skip to content

feat(oauth): ask TanStack Source for its two-factor check before a source grant - #1649

Open
AlemTuzlak wants to merge 2 commits into
mainfrom
source-two-factor-check
Open

AlemTuzlak wants to merge 2 commits into
mainfrom
source-two-factor-check

Conversation

@AlemTuzlak

@AlemTuzlak AlemTuzlak commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

TanStack Source now supports two-factor authentication. A source grant from tanstack.com never passes Source's own second factor, so Source refuses tanstack.com MCP tokens for accounts that have two-factor sign-in on, unless introspection says the person passed Source's check for that grant. This PR adds that check to the source consent flow.

Flow

  1. On /oauth/authorize with scope source, the loader asks Source (server to server, with the existing shared introspection secret) whether this person's Source account needs the check: POST https://source.tanstack.com/auth/tanstack/two-factor/required with sub and the verified github_id. Any failure or timeout (5 s) counts as "not required", so the page works exactly as today when Source is unreachable. Source still enforces the rule on its side.
  2. When required, the primary button becomes Confirm in TanStack Source. It opens https://source.tanstack.com/auth/tanstack/two-factor, which checks the person's Source session and second factor, then returns to this authorize URL with source_check.
  3. The page verifies source_check and shows "Confirmed in TanStack Source." with the normal Authorize button. The person still clicks Authorize: the page never authorizes on its own.
  4. createAuthorizationCode verifies the assertion again on the server and stores source_two_factor_at on the code. The code exchange and each refresh rotation copy it to the new tokens, and /oauth/introspect returns source_two_factor_at when the token has one.

The assertion

source_check = <P>.<SIG>

  • P is base64url JSON {v: 1, sub, request, two_factor_at, exp}. request binds the check to one authorize request: base64url SHA-256 of client_id\nredirect_uri\ncode_challenge.
  • SIG is HMAC-SHA256 with the shared secret over tanstack-source-two-factor-check-v1.<P>.
  • Checked here: signature (timing-safe), v, sub equals the signed-in user, request matches, and exp is in the future.

source_two_factor_at, source_check, the two Source paths and the HMAC context string are a contract with TanStack Source, so please don't rename them.

Changes

  • src/auth/source-two-factor.server.ts (new): the secret lookup, now shared with handleIntrospection, the request hash, assertion verification, the required call and the check URL.
  • src/routes/oauth/authorize.tsx, src/utils/oauthClient.functions.ts: source_check in the search params, the confirm step and the checkSourceTwoFactor server function.
  • src/auth/oauthClient.server.ts: stores and copies source_two_factor_at; introspection returns it.
  • drizzle/migrations/0045_source_two_factor.sql: a nullable source_two_factor_at bigint (epoch seconds) on the three oauth_mcp_* tables, made with drizzle-kit generate.
  • tests/source-two-factor.test.ts: the request hash, a pinned interop vector (the same vector was checked against Source's signer), and the refusals for a bad signature, the wrong sub or request, an expired or malformed assertion, and the wrong version.

Checks

  • test:tsc passes, and lint:code has 0 errors (109 warnings, the same as main, none in these files). tests/source-two-factor.test.ts: 5/5 pass.
  • test:unit locally: 733 pass, 1 fail. The failure is tests/worker-boundaries.test.ts (URLPattern is not defined), which comes from running Node 22 locally instead of the .nvmrc 25.9, and has nothing to do with this change.
  • The database paths (code, tokens, introspection) have no tests here, because the repo has no OAuth DB tests. They are covered by tsc.

Source's side (both endpoints) is in TanStack Source's own repository and ships first. Until it is live, the required call fails and this PR changes nothing.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • OAuth authorization for Source resources can require confirmation through TanStack Source when two-factor verification is needed.
    • The confirmation step is preserved when signing in, and authorization proceeds after a valid confirmation.
    • Confirmation is checked against the authorization request, and invalid checks do not authorize access.
    • Two-factor verification status is retained across token exchanges and refreshes, and can be included in token introspection results.

…urce grant

For scope `source`, the authorize page asks TanStack Source whether the
person's Source account needs its two-factor check. When it does, the
primary button sends the person to Source, which returns a signed
`source_check` assertion. tanstack.com verifies it, shows "Confirmed in
TanStack Source" and the normal Authorize button, and never authorizes on
its own. The authorization code stores `source_two_factor_at`, the token
exchange and refresh rotation copy it, and introspection returns it when
set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AlemTuzlak
AlemTuzlak requested a review from a team December 4, 2026 13:47
@changeset-bot

changeset-bot Bot commented Dec 4, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 892be3c

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The OAuth authorization flow now supports Source two-factor checks. It validates checks against authorization details, stores verified timestamps on authorization codes and tokens, and returns the timestamp in Source-token introspection claims when present.

Changes: Source OAuth two-factor checks

Layer / File(s) Summary
Persist Source two-factor timestamps
src/db/schema.ts, drizzle/migrations/0045_source_two_factor.sql, drizzle/migrations/meta/_journal.json, drizzle/migrations/meta/0045_snapshot.json, harness-tests/postgres/site-baseline.sql
The authorization-code, access-token, and refresh-token schemas add nullable timestamp columns. The migration and metadata record these changes. The PostgreSQL test baseline adds the oauth_accounts table used to identify GitHub accounts.
Build and validate Source checks
src/auth/source-two-factor.server.ts, src/utils/oauthClient.functions.ts, src/auth/oauthClient.server.ts, tests/source-two-factor.test.ts
Source check helpers bind assertions to authorization details and verify signed assertions. Server functions check whether verification is required and build the check URL. Authorization-code creation validates a supplied check. Tests cover request hashes, assertion verification, and URL construction.
Integrate checks into authorization
src/routes/oauth/authorize.tsx
The route preserves the check through login redirects, checks Source scopes, and displays a confirmation action when needed. It passes the check to authorization-code creation only after confirmation.
Carry timestamps through token lifecycle
src/auth/oauthClient.server.ts, src/auth/oauth-endpoints.server.ts, tests/source-two-factor-grant.integration.test.ts, .github/workflows/pr.yml
Code exchange and refresh-token rotation copy the timestamp to new tokens. Source-token introspection emits it as source_two_factor_at when present. Bearer-token introspection obtains its secret through sourceSharedSecret(). The integration test checks timestamp propagation and rejected checks, and the workflow runs the test after migration.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant AuthorizeRoute
  participant checkSourceTwoFactor
  participant Source
  AuthorizeRoute->>checkSourceTwoFactor: Send authorization details and optional check
  checkSourceTwoFactor->>Source: POST subject and optional GitHub ID
  Source-->>checkSourceTwoFactor: Return whether a check is required
  checkSourceTwoFactor-->>AuthorizeRoute: Return confirmation result and check URL
Loading

Possibly related PRs

  • TanStack/tanstack.com#1449: Adds the resource-bound MCP OAuth grant, PKCE, rotating refresh-token, and introspection contracts extended here.

Suggested reviewers: tannerlinsley

Merge Risk: Low · up to fff37

This adds a Source two-factor check to the OAuth consent flow and carries its verified timestamp into issued tokens. No concrete defect was found, and the main remaining risk is that enforcement lives in Source. Have an auth/database reviewer sign off before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "feat(oauth): ask TanStack Source for its two-factor check before a source grant" matches the main change. The PR adds a Source two-factor check to the source OAuth consent flow. The check r…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "feat(oauth): ask TanStack Source for its two-factor check before a source grant" matches the main change. The PR adds a Source two-factor check to the source OAuth consent flow. The check runs on /oauth/authorize, the signed check is carried into authorization-code creation, and the timestamp is propagated to tokens and introspection. The title is specific and uses a conventional commit prefix. It is 79 characters, which is slightly long but still readable.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • 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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1faef675-28e8-4d4f-b1fb-cc4e4210065e
Commits

Reviewing files that changed from the base of the PR and between 892be3c and fff3796.

Files selected for processing: 3

  • .github/workflows/pr.yml
  • harness-tests/postgres/site-baseline.sql
  • tests/source-two-factor-grant.integration.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Asset Main PR merge build Change
JavaScript 19470.02 KiB 19470.98 KiB 🔴 +0.96 KiB (+0.00%)
JavaScript (gzip) 6400.88 KiB 6401.42 KiB 🔴 +0.55 KiB (+0.01%)
CSS 831.58 KiB 831.58 KiB 0.00 KiB (0.00%)
CSS (gzip) 127.22 KiB 127.22 KiB 0.00 KiB (0.00%)
Page Main (gzip) PR merge build (gzip) Change
/ 577.44 KiB 577.50 KiB 🔴 +0.06 KiB (+0.01%)
/libraries 522.00 KiB 522.05 KiB 🔴 +0.05 KiB (+0.01%)
/start/latest 547.34 KiB 547.40 KiB 🔴 +0.05 KiB (+0.01%)
/router/latest 547.65 KiB 547.70 KiB 🔴 +0.05 KiB (+0.01%)
/query/latest 546.31 KiB 546.37 KiB 🔴 +0.05 KiB (+0.01%)
/table/latest 578.90 KiB 578.95 KiB 🔴 +0.05 KiB (+0.01%)
/charts/latest 628.20 KiB 628.26 KiB 🔴 +0.05 KiB (+0.01%)
/ai/latest 573.28 KiB 573.33 KiB 🔴 +0.05 KiB (+0.01%)
Docs article 533.04 KiB 533.10 KiB 🔴 +0.05 KiB (+0.01%)
Framework docs article 533.05 KiB 533.11 KiB 🔴 +0.05 KiB (+0.01%)
/blog 526.21 KiB 526.27 KiB 🔴 +0.06 KiB (+0.01%)
/maintainers 525.33 KiB 525.38 KiB 🔴 +0.05 KiB (+0.01%)
/showcase 523.25 KiB 523.31 KiB 🔴 +0.06 KiB (+0.01%)
/chat 521.75 KiB 521.80 KiB 🔴 +0.05 KiB (+0.01%)
/chat/c/:conversationId 522.44 KiB 522.49 KiB 🔴 +0.05 KiB (+0.01%)

Page sizes sum the JS and CSS in the TanStack Start manifest for each route and its layouts. Shared files count once per page.

Compared with main at ab384b7. Gzip sizes are summed per file. Build run

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
tanstack-com fff3796 Commit Preview URL

Branch Preview URL
Dec 04 2026, 02:48 PM

@tannerlinsley

Copy link
Copy Markdown
Member

AI review notes for 892be3c: the assertion is verified again when the code is created, and the diff carries its timestamp through code exchange, refresh rotation and introspection. I haven't run this flow against Source.

The remaining verification gap is that the new tests only cover the hash, verifier and URL helper. Could you add a database-backed test that issues a source code with a valid assertion, exchanges it, rotates its refresh token and checks the introspection timestamp, plus a grant without an assertion and a rejected assertion that creates no code? Type checking won't catch a missing copy or persistence step in that chain.

Could you also link the Source-side change and its enforcement tests or deployment evidence? sourceTwoFactorRequired deliberately returns false on an outage, and code creation allows a source grant without sourceCheck, so the security boundary depends on Source rejecting those tokens when two-factor is required. That may be the intended contract, but this repo's passing checks don't verify it. Please include the behavior for an existing grant when two-factor is enabled or reset afterward.

This still needs the required auth/database reviewer before landing.

Issue a source code with a verified check, exchange it, rotate the refresh
token twice and check introspection at each step. Also cover a check for an
account with two-factor off, a grant without a check, and rejected checks
that create no code. The test runs in the chat-runtime job, on the database
built from the site baseline and every migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AlemTuzlak

Copy link
Copy Markdown
Contributor Author

Thanks, both points are addressed in fff3796.

Database-backed test. tests/source-two-factor-grant.integration.test.ts runs the real chain on Postgres: createAuthorizationCode, exchangeAuthorizationCode, refreshAccessToken (two rotations) and introspectSourceToken. It covers:

  • A verified check: source_two_factor_at is on the code, on the access token after exchange, after each rotation, and on the newest refresh token row.
  • A check for an account with two-factor off (two_factor_at: null): no claim.
  • A grant without a check: no claim after exchange and after rotation.
  • Rejected checks (wrong secret, other sub, other request, expired, v: 2, malformed): each throws invalid_source_check and no code row exists for the user.

It runs in the "Chat PostgreSQL runtime" job, on the database built from site-baseline.sql plus every migration (so it also applies 0045). The baseline gained a minimal oauth_accounts, because introspection reads the GitHub identity from it. Elsewhere the test skips without SOURCE_OAUTH_TEST_DATABASE_URL, like the other integration tests. I checked that it catches a missing copy step: removing the copy in the exchange (access or refresh insert) or in the rotation makes it fail.

Source side. It is merged and deployed: https://source.tanstack.com/@TanStack/source/pull/1413 (merge e778e48).

  • Enforcement is tanstackMcpActor in apps/web/src/server/tanstack-auth.ts. When the linked Source account has two-factor on, Source refuses a token unless introspection returns source_two_factor_at >= the second two-factor was turned on. The refusal is a 403 with no OAuth challenge. If introspection fails, Source refuses the token.
  • Tests: apps/web/test/shared-login.test.ts covers a token without the claim (403), a claim from before two-factor was turned on (refused), and a claim from the same second (accepted). apps/web/test/tanstack-two-factor-check.test.ts covers both endpoints: the secret check, account linking, the 15 minute re-check, the return URL allowlist, and the signature interop vector.
  • Production probes just now: POST /auth/tanstack/two-factor/required without the secret returns 401 {"error":"invalid_client"}. GET /auth/tanstack/two-factor with a foreign return URL returns 400.

The contract. Yes, the fail-open is intended. tanstack.com never decides whether two-factor is needed; it only carries Source's signed answer. If sourceTwoFactorRequired fails, or a client skips the check, the grant has no claim, and Source refuses that token for a two-factor account. The worst result is a refused token, never an unchecked one.

Existing grants

  • Two-factor turned on after a grant: the token has no claim (or an older one), so Source refuses it on the next MCP call. Refreshing doesn't help, because rotation copies the old value. The person reconnects and confirms in Source. This also covers every grant issued before this PR.
  • Two-factor turned off, or reset by a site admin: the account's two_factor_at is cleared, so Source needs no claim and existing tokens keep working.
  • Turned off and then on again later: the new two_factor_at is newer than any earlier claim, so those tokens are refused until the person reconnects.

Agreed it still needs the auth/database reviewer. I won't merge it.

@tannerlinsley

Copy link
Copy Markdown
Member

AI review follow-up for fff3796: thanks, the new test exercises the real issuance, exchange, two refresh rotations and introspection paths, including rejected checks creating no code. I checked the PostgreSQL job log: all 5 tests passed with 0 skipped. That addresses the database lifecycle gap I raised.

The Source contract and existing-grant behavior are now documented in your reply. I couldn't retrieve the linked Source PR through my reader, so I haven't independently verified that side or its deployment. The auth/database reviewer should check that evidence before signing off. I haven't run a live two-factor flow.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants