Fix all five findings from the independent OAuth security audit

An independent model reviewed the MCP and OAuth surfaces. All five findings
were verified against the code before changing anything; none were false
positives. audit.md is kept as the record of what was reviewed.

F1 (High) - refresh reuse detection forgot the token family. Only the current
hash and one predecessor lived on the grant, and each rotation overwrote the
predecessor. A thief who rotated a stolen token twice made the victim's
original unrecognisable: replaying it returned "unknown token" instead of
revoking the family, and the thief kept working. Refresh tokens are now rows in
OAuthRefreshToken, one per generation, retained for the life of the family and
consumed by a guarded update on usedAt - which also means two concurrent uses
of the same token can no longer both succeed. This corrects a claim I made when
the OAuth server shipped: reuse detection covered one generation, not the family.

F2 (Medium) - issueAccessToken wrote scopes back onto the grant, so redeeming a
stale authorization code redefined standing consent. Token issuance is not
consent; the consent endpoint is now the only writer. Codes are additionally
bound to a grant id and epoch, with a coversScopes check behind that.

F3 (Medium) - revocation was reversible. Reconnecting a disconnected app cleared
revokedAt and left credentials that had raced the revoke usable again. Every
approval now starts a clean epoch: the counter advances and prior access tokens,
refresh tokens and unconsumed codes are destroyed. Token writes are conditional
on the epoch they validated, so a revoke that wins a race aborts them. Refresh
also now requires offline_access to still be granted.

F4 (Medium) - loopback redirect matching compared only scheme, host and path,
silently accepting a differing query, fragment or userinfo. RFC 9700 2.1 wants
exact matching apart from the RFC 8252 port exception; that is what it does now.

F5 (Low) - get_collection_stats returned bar and recipe counts under
drinks:read. Gated on the caller actually holding bar:read.

Verified with regression tests for each: the two-rotation attack now revokes the
family, concurrent refresh yields exactly one winner, a pre-narrowing code is
refused, disconnect-reconnect leaves old credentials dead, and Claude Code's
ephemeral-port callback still works while query/userinfo/fragment variants are
rejected. Existing protections re-checked - code replay, PKCE mismatch, deny,
confidential-client rejection, and the MCP tools themselves.

Note for deploy: OAuthAuthCode gains a required grantId, so existing rows must
be cleared first. They are 60-second ephemeral codes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
This commit is contained in:
JP
2026-08-09 21:05:08 +00:00
parent 5c05464269
commit 23c4e63a68
8 changed files with 511 additions and 137 deletions

205
audit.md Normal file
View File

@@ -0,0 +1,205 @@
# Security audit: MCP and OAuth 2.1 surfaces
Date: 2026-08-09
Auditor: independent model review, commissioned after the OAuth server shipped.
> **STATUS: all five findings were verified against the code and fixed.** Every
> claim below was independently confirmed before any change was made — there
> were no false positives, which is unusual for a cross-model review.
>
> The fixes and their regression tests are in the commit that follows this file.
> In short: refresh tokens now have durable per-generation lineage with an atomic
> consume (F1); consent is the only writer of grant scopes and codes are bound to
> a grant epoch (F2); every approval starts a clean epoch that destroys prior
> credentials (F3); loopback redirects match exactly apart from the port (F4);
> and bar counts are gated on `bar:read` (F5).
>
> Q1's advice was taken: lineage first, no refresh grace window for now.
> Q1 also corrected a claim made when the OAuth server shipped — reuse detection
> covered only one generation back, not the whole family. That was the single
> most valuable output of this audit.
>
> This document is kept as the record of what was reviewed. The findings below
> describe the code as it was, not as it is.
## Summary
The MCP surface has a strong overall tenant-isolation posture: all 22 tools pass through required bearer authentication and per-tool scope enforcement, their primary queries are scoped to the authenticated `userId`, foreign-key inputs are ownership-checked, and the bearer verifier checks token revocation, expiry, grant revocation, and account suspension from the database on every request. I found no cross-user row access and no unauthenticated path into an MCP tool. The OAuth implementation's main weakness is state lineage rather than basic PKCE: refresh rotation remembers only one prior hash and performs validation, access-token issuance, and rotation as separate state transitions. A thief can rotate a stolen refresh token twice so the legitimate client's later replay is no longer associated with the grant and does not revoke the attacker's token family. Fixing durable, atomic refresh-token lineage is the single most important change.
## Findings
### 1. High — Refresh-token replay detection forgets the token family
- **Severity:** High
- **Confidence:** Confirmed
- **Files:** `src/app/api/oauth/token/route.ts:152-170`, `src/app/api/oauth/token/route.ts:181-193`, `src/app/api/oauth/revoke/route.ts:28-47`, `src/lib/mcp/oauth.ts:243-255`, `prisma/schema.prisma:237-241`
Only `refreshHash` and the immediately preceding `refreshPrevHash` are retained. Every successful rotation overwrites the prior predecessor. A refresh token therefore identifies its grant for only one subsequent generation, not for the lifetime of the token family.
Concrete exploit path:
1. An attacker steals the grant's current refresh token `R0`.
2. The attacker sends `R0` to `POST /api/oauth/token` and receives `R1`; the row now stores `current=R1, previous=R0`.
3. Before the legitimate client refreshes, the attacker sends `R1` and receives `R2`; the row now stores `current=R2, previous=R1`. The only database reference to `R0` has been erased.
4. The legitimate client later sends `R0`. The query at `token/route.ts:152-159` finds no grant, returns `invalid_grant`, and never calls `revokeGrant`.
5. The attacker retains `R2` and can continue rotating it for the sliding 90-day lifetime. The event that should expose theft instead looks like an unknown token and leaves the attacker's family active.
The same loss of lineage defeats RFC 7009 revocation by token value. If the legitimate client posts the now-aged-out `R0` to `/api/oauth/revoke`, that endpoint cannot associate it with the grant, still returns its mandatory 200 response, and leaves `R2` active. Settings-based revocation by grant ID does still terminate the family.
There is also an atomicity failure in the same path. Two simultaneous requests with the same current token can both read it as current before either reaches `storeRefreshToken`. Both can issue token responses, and the last unconditional update at `oauth.ts:249-255` wins. Neither request is treated as replay. This also means the current zero-grace policy is not actually strict under concurrency.
**Specific fix:** Model refresh tokens as a lineage, for example an `OAuthRefreshToken` row per issued hash with `grantId`, generation, `usedAt`, and expiry. Retain consumed hashes until the family can no longer be used. In one database transaction, atomically change the presented current token from unused to used, create its successor, revoke/replace access tokens, and update grant activity. If the hash exists but is already consumed outside any configured grace interval, revoke the grant and all descendants. Use a guarded update/CAS, a row lock, or serializable transaction so only one non-grace exchange of a generation succeeds. An authenticated family/grant identifier inside the otherwise opaque token can make lookup efficient, but it does not remove the need to retain consumed generations.
This behavior falls short of [RFC 9700 section 4.14.2](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.14.2), which describes retaining the relationship between rotated tokens so presentation of an invalidated family member can revoke the active token.
### 2. Medium — Stale code and refresh snapshots can restore broader scope than the latest consent
- **Severity:** Medium
- **Confidence:** Confirmed
- **Files:** `src/app/oauth/authorize/page.tsx:84-91`, `src/app/oauth/authorize/page.tsx:139-160`, `src/app/api/oauth/authorize/route.ts:68-88`, `src/app/api/oauth/token/route.ts:99-126`, `src/app/api/oauth/token/route.ts:152-185`, `src/lib/mcp/oauth.ts:217-231`
Authorization codes carry a scope snapshot, but they are bound only to `(client, user)`, not to a particular grant version or consent epoch. `exchangeCode` checks only that some current grant for that pair is active, then issues the code's stored scopes. `issueAccessToken` also writes those scopes back onto the standing grant. Refresh similarly uses a grant object read before issuance and writes that snapshot back.
Concrete exploit path:
1. A malicious public client has an existing broad grant and obtains an auto-approved broad authorization code `C-old` with its own valid PKCE challenge.
2. The user disconnects it, then reconnects the same client read-only. The approval upsert reuses the same grant row, stores the narrow scopes, and clears `revokedAt`.
3. Before `C-old`'s 60-second expiry, the client exchanges it with the correct verifier.
4. `exchangeCode` finds the newly active grant, mints an access token using `C-old`'s broad scopes, and `issueAccessToken` writes those broad scopes back to the grant. The client gets more privilege than the user's latest read-only consent.
A concurrent version does not require a stale code: a refresh request can read broad `grant.scopes`, a narrower consent can be stored, and the refresh can then mint and write the stale broad snapshot. Two different authorization codes can likewise be exchanged in an order chosen by the client, with the last exchange redefining the standing grant.
No path was found that invents an unsupported scope or grants a scope the user never approved at any point. The defect is that an older approval can override the latest effective consent.
**Specific fix:** Make the consent endpoint the only writer of standing grant scopes; remove the scope update from `issueAccessToken`. Add a monotonically increasing consent/grant version and bind every authorization code to the grant ID and version that authorized it. At exchange, require the same active version and require the current grant to cover every code scope; otherwise return `invalid_grant`. Read refresh scopes and atomically rotate the token inside the same transaction so a stale pre-consent snapshot cannot be written back.
### 3. Medium — An in-flight exchange can repopulate a revoked grant and later revive a stolen credential
- **Severity:** Medium
- **Confidence:** Confirmed
- **Files:** `src/app/api/oauth/token/route.ts:99-135`, `src/app/api/oauth/token/route.ts:146-193`, `src/lib/mcp/oauth.ts:212-275`, `src/app/api/oauth/authorize/route.ts:68-74`, `src/lib/mcp/auth.ts:58-66`
Grant validation, access-token issuance, refresh-token storage, and grant revocation are separate transactions. Neither `issueAccessToken` nor `storeRefreshToken` conditionally requires `revokedAt` to remain null. Re-consent then clears only `revokedAt` and changes scopes; it does not clear refresh state or invalidate access tokens that may have been created after the revocation transaction scanned them.
Concrete exploit path:
1. A malicious client or refresh-token thief starts a valid refresh request and passes the active-grant checks.
2. The user disconnects the client. `revokeGrant` marks the grant revoked, clears the two stored refresh hashes, and revokes access tokens visible to that transaction.
3. The already in-flight request resumes. It can create an unrevoked access-token row and/or unconditionally write its newly returned refresh hash onto the now-revoked grant.
4. While `revokedAt` remains set, `verifyMcpToken` correctly rejects the access token and refresh rejects the grant. There is no immediate bypass; this check was traced and is why the finding is not rated High.
5. If the user later reconnects the same client, the approval upsert sets `revokedAt: null` without resetting those raced credentials. The attacker's refresh token becomes usable again for up to 90 days; a raced access token also becomes usable if its one-hour lifetime has not elapsed.
There is a related non-racing state inconsistency. If a grant already has a refresh token and a later authorization code omits `offline_access`, `exchangeCode` skips `storeRefreshToken` but does not clear the existing refresh hashes. The grant scopes can therefore say that offline access is absent while the old refresh token remains accepted. The refresh handler never checks for `offline_access` and returns another refresh token on every successful use. Thus a previously issued refresh credential can continue persistent access after the standing scope array no longer contains the permission that authorized it.
**Specific fix:** Serialize refresh/code issuance against revocation on the grant row and make the active-grant predicate part of the write, not an earlier read. A revoke should advance a grant epoch. Every token/code write should be conditional on the epoch it read, so it fails if revocation won the race. Re-consenting a revoked grant should atomically start a clean epoch: clear all refresh-token state and revoke/delete every old access token before setting the grant active. Also clear refresh state whenever the effective grant drops `offline_access`, and reject refresh grants whose current scope array lacks it. Creating a new grant row is viable if codes are bound to its exact ID/version.
### 4. Medium — Loopback redirect matching ignores every component except scheme, host, and path
- **Severity:** Medium
- **Confidence:** Suspected
- **Files:** `src/lib/mcp/oauth.ts:137-152`, `src/lib/mcp/authorize-request.ts:65-81`
For loopback redirects, `redirectUriMatches` intentionally ignores the port, but it also ignores the query string, fragment, username, and password. A requested loopback URI can therefore differ from its registered value in security-relevant components and still become the actual redirect target.
Concrete conditional exploit path: suppose a legitimate native client's registered loopback callback uses a query parameter to select or forward the post-callback destination. An attacker starts authorization with that legitimate public `client_id`, an attacker-controlled PKCE challenge, and the same loopback scheme/host/path but changes the query to an attacker destination. The server accepts it. If the victim has a covering standing grant, authorization is automatic; otherwise the legitimate client name is shown. A callback handler that forwards the altered query and authorization response can deliver the code to the attacker, who knows the verifier and exchanges it for the victim's token.
The comparison defect is confirmed, but exploitability is marked **Suspected** because the database was deliberately not queried and the external clients' loopback callback behavior is not in this repository. I could not establish that a currently registered callback forwards attacker-controlled query data.
**Specific fix:** For a supported loopback URI, compare the complete registered and requested URI after removing only the port. Query, fragment, path, userinfo, scheme, and host must otherwise match exactly; reject a requested fragment even if the registered URI has none. Apply the same rule at authorization and token exchange. [RFC 9700 section 2.1](https://www.rfc-editor.org/rfc/rfc9700.html#section-2.1) requires exact redirect matching except for the native-loopback port exception and identifies authorization-code leakage as the consequence of loose matching.
### 5. Low — `drinks:read` discloses bar and recipe counts
- **Severity:** Low
- **Confidence:** Confirmed
- **Files:** `src/lib/mcp/tools/drinks.ts:368-400`, `src/lib/mcp/tools/drinks.ts:417-436`, `src/lib/mcp/oauth.ts:27-32`
`get_collection_stats` requires only `drinks:read`, but queries and returns the number of non-empty bar items and saved recipes. The advertised scope descriptions put bar inventory and recipes behind `bar:read`.
Concrete exploit path: a client requests and receives only `drinks:read`, then calls `get_collection_stats`. It receives `barItemCount`, `recipeCount`, and the corresponding text despite the user never granting `bar:read`. This is same-user metadata rather than row contents, so the impact is Low.
**Specific fix:** Remove the bar/recipe counts from this tool, return them only when `caller.scopes` includes `bar:read`, or require both `drinks:read` and `bar:read` for the entire tool. If more cross-axis tools are expected, extend `ToolSpec` to accept an array of required scopes rather than relying on ad hoc checks.
## Material negative results
- **No cross-tenant MCP access found.** All 22 tools are registered through `defineTool`; all 22 declare a scope. Reads use `caller.userId`, creates set it server-side, and updates/deletes first resolve ownership. `rate_drink` verifies the supplied drink belongs to the caller, and `save_recipe` does the same for `sourceDrinkId`.
- **No unauthenticated MCP operation found.** `withMcpAuth` is configured with `required: true`; the verifier accepts only the MCP token shape; no route calls `auth()` as a fallback; cookies cannot authenticate `/api/mcp`. `OPTIONS` exposes no data or state change.
- **Revocation, expiry, and suspension are checked live.** `verifyMcpToken` checks the token row, access-token expiry, OAuth grant revocation, and the joined user's current status on every request. There is no token cache. Finding 3 requires a later re-consent because the live grant check correctly blocks the raced token while the grant remains revoked.
- **PKCE and same-code concurrency are sound.** S256 is mandatory, verifier syntax is constrained, comparison is timing-safe, and the guarded code consume permits only one exchange of a given code. The consume-before-validation ordering can burn a code or let a bad verifier revoke its grant, but that is availability/DoS and is outside the stated threat model.
- **Dynamic registration did not expose SSRF or client secrets.** Registration performs no outbound fetch, generates the client ID server-side, accepts only public clients, and restricts redirects to HTTPS or loopback. Untrusted client metadata is rendered as escaped text in the reviewed UI.
- **Settings management is tenant-scoped.** PAT and OAuth-grant listing/revocation use the cookie-authenticated user's ID in their reads and writes.
- **The deliberate wildcard MCP CORS policy does not combine with cookie auth.** No `Access-Control-Allow-Credentials` header or session-cookie authentication path was found.
## Q1. Should refresh-token replay have a grace window?
Zero grace is security-correct but operationally harsh; it is not required to be zero by the OAuth security BCP. [RFC 9700 section 4.14.2](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.14.2) requires public clients to use sender-constrained refresh tokens or rotation with retained family relationships and describes family revocation when an invalidated token reveals reuse. It does not prescribe a grace duration.
Mature implementations expose both choices. [Auth0 offers a configurable rotation overlap](https://dev.auth0.com/docs/secure/tokens/refresh-tokens/configure-refresh-token-rotation): its default leeway is disabled, but a configured window allows only the immediately previous generation and older generations still trigger family invalidation. [Okta defaults to a 30-second grace period configurable from 0 to 60 seconds](https://developer.okta.com/docs/guides/refresh-tokens/main/#grace-period-for-token-rotation), explicitly to handle a lost response or poor network.
For this app, the present zero-grace behavior is defensible if forced reauthorization after a lost response is acceptable. A short 510 second grace window would be a reasonable reliability choice, limited to the immediately preceding generation; any older generation or a replay outside the window should revoke the family. Do **not** add grace to the current implementation first. Finding 1 means old generations are forgotten, and simultaneous current-token requests are not atomically resolved. Implement durable lineage and atomic rotation, then choose grace. For robust retry semantics, either retain enough protected successor state to return the same result idempotently or use generation-aware rotation that cannot let late responses overwrite newer client state.
One correction to the question's premise: the implementation does not revoke the grant whenever a previous token is “ever” presented. It recognizes only the immediately preceding hash until the next successful rotation overwrites it.
## Q2. Can a token receive more scope than the user consented to?
**Normal, non-racing path:** no problem found. `validateAuthorizeRequest` parses the requested scopes; explicit approval writes the same array to both grant and code; auto-approval requires `coversScopes(existing.scopes, requested)` and puts only the requested subset on the code; access-token creation removes only the `offline_access` marker. Unsupported scopes are never written to an access token.
**Across consent changes and concurrency:** yes, a token can exceed the user's latest effective consent, as detailed in Finding 2. A broad code from an older consent can be exchanged after the same grant row is revoked and reactivated with narrow scopes. A refresh that read broad scopes before the consent change can also issue and write those scopes afterward. The code/refresh never creates a scope the user did not historically approve, but it can override a later narrowing or revoke-and-reconsent decision. The root causes are the absence of a consent epoch and `issueAccessToken` treating token issuance as authority to rewrite standing consent.
Two concurrent exchanges of different valid codes can both succeed and whichever token issuance writes last determines the grant's stored scopes. That does not by itself invent scope, but it makes request ordering—not the latest consent action—the final authority.
`offline_access` has a separate persistence defect rather than an access-token-scope escalation: removing it from the effective grant does not clear a previously issued refresh token, and refresh does not require the marker. That path is covered in Finding 3.
## Q3. Is consume-before-grant/PKCE safe, and what happens under concurrency?
The exact ordering is:
| Stage | Code behavior | Security/concurrency result |
|---|---|---|
| 1 | Hash lookup loads the code plus client and user snapshot (`token/route.ts:65-71`). | No lock is held; expiry is not accepted here. |
| 2 | `updateMany` sets `consumedAt` only where it is null and `expiresAt` is still in the future (`:74-87`). | For the **same code**, exactly one concurrent request gets `count=1`; all others fail. Expiry between lookup and consume also fails closed. |
| 3 | Client ID and redirect are checked (`:90-97`). | A wrong request burns the code but gets no token. This is availability, not token theft. |
| 4 | The current grant is loaded by `(client row ID, user ID)` and must be active (`:99-105`). | A missing or already-revoked grant fails. The code is already consumed. |
| 5 | PKCE is verified (`:107-116`). | A mismatch cannot mint a token and revokes the current grant. The code remains consumed. |
| 6 | The user snapshot's status is checked (`:118-120`). | A suspended account gets no token; MCP also rechecks live status on use. |
| 7 | `issueAccessToken` revokes visible access tokens, creates one, and updates grant scopes/activity in a transaction (`oauth.ts:212-233`). | The transaction does not condition on the grant still being active or on a grant version. A concurrent revoke can win without preventing this row from being created, although live grant verification blocks it while revoked. |
| 8 | If requested, the first refresh token is stored in a separate write (`token/route.ts:129-134`). | A revoke can interleave before this write; re-consent can later revive the raced state (Finding 3). |
Direct answers:
- **Can a code outlive its grant?** Yes in the logical authorization sense. `OAuthAuthCode` has foreign keys to client and user, not to `OAuthGrant`, and soft revocation does not consume/delete codes. A code cannot exchange while the grant is revoked, but if the same `(client,user)` row is reactivated before the code's 60-second expiry, the old code becomes usable again. It can carry stale scopes (Finding 2).
- **Can a revoked grant be resurrected?** `exchangeCode` and `issueAccessToken` do not directly clear `revokedAt`, and `verifyMcpToken` checks the grant, so a concurrent exchange does not immediately bypass a grant that stays revoked. The approval upsert intentionally reactivates the row. Because that reactivation has no epoch/reset, it can also reactivate pre-revocation codes or credentials written by an in-flight request (Findings 2 and 3).
- **Can two concurrent exchanges both succeed?** Two exchanges of the **same authorization code cannot both succeed** because of the guarded consume. Two different valid codes for the same grant can both succeed. Two concurrent refresh requests using the same current refresh token can also both succeed because validation and rotation are not one guarded transaction (Finding 1).
Consume-before-PKCE is therefore not the source of a duplicate same-code mint. Its security cost is code burning and grant revocation on a bad verifier; under the stated exclusion of DoS, that ordering is acceptable. The material problems are the missing grant/consent version and the non-atomic writes after the consume.
## Coverage
| Requested file | Coverage | Result |
|---|---|---|
| `src/lib/mcp/oauth.ts` | Fully reviewed | Findings 14; PKCE primitive itself clean. |
| `src/app/api/oauth/token/route.ts` | Fully reviewed | Findings 13; same-code consume is concurrency-safe. |
| `src/lib/mcp/authorize-request.ts` | Fully reviewed | Fatal-before-redirect validation order is sound; Finding 4 inherits the loopback matcher. |
| `src/app/oauth/authorize/page.tsx` | Fully reviewed | Auto-approve correctly uses `coversScopes`; stale-consent issue is Finding 2. |
| `src/app/api/oauth/authorize/route.ts` | Fully reviewed | Cookie auth and request revalidation are present; Findings 23 concern grant reuse/versioning. |
| `src/lib/mcp/auth.ts` | Fully reviewed | Per-request token, expiry, grant, and user-status checks are sound. |
| `src/app/api/mcp/route.ts` | Fully reviewed | Bearer auth is required; no cookie fallback; CORS decision is safe under current wiring. |
| `src/app/api/oauth/register/route.ts` | Fully reviewed | No SSRF or secret storage found; redirect registration restrictions present. |
| `src/lib/mcp/tools/bar.ts` | Fully reviewed | No IDOR or scope bypass found. |
| `src/lib/mcp/tools/chatgpt.ts` | Fully reviewed | No IDOR or scope bypass found. |
| `src/lib/mcp/tools/drinks.ts` | Fully reviewed | No IDOR; Finding 5 is a cross-scope count disclosure. |
| `src/lib/mcp/tools/meta.ts` | Fully reviewed | No IDOR or scope bypass found. |
| `src/lib/mcp/tools/recipes.ts` | Fully reviewed | `sourceDrinkId` ownership is checked; no IDOR found. |
| `src/lib/mcp/tools/wishlist.ts` | Fully reviewed | No IDOR or scope bypass found. |
| `src/lib/mcp/context.ts` | Fully reviewed | Missing auth fails closed; scope check is exact. |
| `src/lib/mcp/define.ts` | Fully reviewed | Every tool goes through auth/scope/error plumbing. |
| `src/lib/mcp/schemas.ts` | Fully reviewed | Image URL omitted; IDs and write schemas traced to validators. |
| `src/lib/auth.ts` | Fully reviewed | `/oauth/authorize` is not public; JWT revalidates active user. |
| `prisma/schema.prisma` | Fully reviewed | OAuth uniqueness/cascades and all related user-owned relationships traced. |
| `src/app/api/settings/mcp-tokens/route.ts` | Fully reviewed | User-scoped listing/creation; no token secret stored. |
| `src/app/api/settings/mcp-tokens/[id]/route.ts` | Fully reviewed | Guarded user-scoped revocation. |
| `src/app/api/settings/mcp-grants/route.ts` | Fully reviewed | User-scoped listing. |
| `src/app/api/settings/mcp-grants/[id]/route.ts` | Fully reviewed | User-scoped lookup before grant revocation. |
Supporting paths fully reviewed: `src/app/api/oauth/revoke/route.ts`, all three OAuth/protected-resource discovery routes under `src/app/.well-known`, `src/middleware.ts`, `src/lib/authz.ts`, `src/components/oauth/consent-form.tsx`, `src/lib/validators.ts`, `src/lib/mcp/{config,tokens,server,audit}.ts`, and the relevant `mcp-handler` authentication wrapper. Relevant ownership invariants were cross-checked in the existing ratings and recipes API routes. The `mcp-handler` package as a whole and unrelated application features were not audited.
Validation: `./node_modules/.bin/tsc --noEmit --incremental false` completed successfully. The application was not run, and no database or service was contacted.

View File

@@ -208,6 +208,12 @@ model OAuthAuthCode {
codeHash String @unique codeHash String @unique
clientId String clientId String
userId String userId String
/// The grant, and the epoch of that grant, this code was authorized against.
/// Without both, a code is bound only to (client, user): one minted under a
/// broad consent stays redeemable after the user narrows or revokes and
/// re-grants, carrying the old scopes with it.
grantId String
grantEpoch Int @default(0)
/// Exactly what was sent to /oauth/authorize - re-checked at the token endpoint /// Exactly what was sent to /oauth/authorize - re-checked at the token endpoint
redirectUri String redirectUri String
/// RFC 8707 audience binding /// RFC 8707 audience binding
@@ -221,8 +227,10 @@ model OAuthAuthCode {
client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade) client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
grant OAuthGrant @relation(fields: [grantId], references: [id], onDelete: Cascade)
@@index([userId]) @@index([userId])
@@index([grantId])
@@index([expiresAt]) @@index([expiresAt])
} }
@@ -232,13 +240,15 @@ model OAuthGrant {
id String @id @default(cuid()) id String @id @default(cuid())
clientId String clientId String
userId String userId String
/// Written ONLY by the consent endpoint. Token issuance must never rewrite
/// standing consent - doing so let a stale authorization code redefine what
/// the user had most recently agreed to.
scopes String[] scopes String[]
refreshHash String? @unique /// Bumped every time consent is re-granted after a revocation. Codes and
/// One generation back. A hit here means a rotated token was replayed, which /// refresh tokens carry the epoch they were issued under, so anything minted
/// is a theft signal - revoke the whole grant rather than issuing again. /// before a revoke is dead even if the grant row is later reactivated.
refreshPrevHash String? epoch Int @default(0)
refreshExpiresAt DateTime?
revokedAt DateTime? revokedAt DateTime?
lastUsedAt DateTime? lastUsedAt DateTime?
@@ -248,11 +258,40 @@ model OAuthGrant {
client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade) client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessTokens McpAccessToken[] accessTokens McpAccessToken[]
authCodes OAuthAuthCode[]
refreshTokens OAuthRefreshToken[]
@@unique([clientId, userId]) @@unique([clientId, userId])
@@index([userId]) @@index([userId])
} }
/// One row per issued refresh token, retained after use.
///
/// The previous design kept only the current hash and one predecessor on the
/// grant, so each rotation erased the generation before last. A thief who
/// rotated a stolen token twice made the victim's original token unrecognisable:
/// replaying it returned "unknown token" instead of revoking the family, and the
/// thief kept working. Keeping every generation is what makes reuse detectable
/// for the life of the family (RFC 9700 4.14.2).
///
/// Consumed with a guarded update on usedAt, so two concurrent uses of the same
/// token cannot both succeed.
model OAuthRefreshToken {
id String @id @default(cuid())
grantId String
tokenHash String @unique
generation Int @default(0)
/// Set the moment it is redeemed. A second presentation is reuse.
usedAt DateTime?
expiresAt DateTime
createdAt DateTime @default(now())
grant OAuthGrant @relation(fields: [grantId], references: [id], onDelete: Cascade)
@@index([grantId])
@@index([expiresAt])
}
model Account { model Account {
id String @id @default(cuid()) id String @id @default(cuid())
userId String userId String

View File

@@ -65,21 +65,39 @@ export async function POST(request: Request) {
}) })
} }
// One standing grant per (client, user). Re-approving widens the scopes and const { code, hash } = generateAuthCode()
// clears a previous revocation rather than piling up rows.
const grant = await prisma.oAuthGrant.upsert({ // One standing grant per (client, user), but every explicit approval starts a
// CLEAN EPOCH: the epoch counter advances and everything issued under the
// previous one is destroyed.
//
// Without this, reusing the row made a revocation reversible. Disconnecting an
// app then reconnecting it cleared revokedAt and left any credential that had
// raced the revoke - or any code minted under the older, broader consent -
// live again. Consent is also the only place standing scopes are written; the
// token endpoint no longer rewrites them.
const grant = await prisma.$transaction(async (tx) => {
const g = await tx.oAuthGrant.upsert({
where: { clientId_userId: { clientId: client.id, userId } }, where: { clientId_userId: { clientId: client.id, userId } },
update: { scopes: params.scopes, revokedAt: null }, update: { scopes: params.scopes, revokedAt: null, epoch: { increment: 1 } },
create: { clientId: client.id, userId, scopes: params.scopes }, create: { clientId: client.id, userId, scopes: params.scopes },
select: { id: true }, select: { id: true, epoch: true },
}) })
const { code, hash } = generateAuthCode() await tx.mcpAccessToken.updateMany({
await prisma.oAuthAuthCode.create({ where: { grantId: g.id, revokedAt: null },
data: { revokedAt: new Date() },
})
await tx.oAuthRefreshToken.deleteMany({ where: { grantId: g.id } })
await tx.oAuthAuthCode.deleteMany({ where: { grantId: g.id, consumedAt: null } })
await tx.oAuthAuthCode.create({
data: { data: {
codeHash: hash, codeHash: hash,
clientId: client.id, clientId: client.id,
userId, userId,
grantId: g.id,
grantEpoch: g.epoch,
redirectUri: params.redirectUri, redirectUri: params.redirectUri,
resource: params.resource, resource: params.resource,
scopes: params.scopes, scopes: params.scopes,
@@ -89,6 +107,9 @@ export async function POST(request: Request) {
}, },
}) })
return g
})
console.log( console.log(
`[oauth] granted user=${userId} client=${client.clientId} scopes=${params.scopes.join(",")} grant=${grant.id}` `[oauth] granted user=${userId} client=${client.clientId} scopes=${params.scopes.join(",")} grant=${grant.id}`
) )

View File

@@ -29,13 +29,15 @@ export async function POST(request: Request) {
try { try {
// A refresh token identifies the whole grant, so revoking it ends the // A refresh token identifies the whole grant, so revoking it ends the
// connection outright. // connection outright. Every generation is retained, so this works for any
const grant = await prisma.oAuthGrant.findFirst({ // member of the family - previously only the newest two were recognised,
where: { OR: [{ refreshHash: hash }, { refreshPrevHash: hash }] }, // which meant revoking an older token silently did nothing.
select: { id: true }, const refresh = await prisma.oAuthRefreshToken.findUnique({
where: { tokenHash: hash },
select: { grantId: true },
}) })
if (grant) { if (refresh) {
await revokeGrant(grant.id) await revokeGrant(refresh.grantId)
return ok return ok
} }

View File

@@ -1,14 +1,16 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma" import { prisma } from "@/lib/prisma"
import { import {
GrantStateError,
OFFLINE_ACCESS, OFFLINE_ACCESS,
generateRefreshToken, consumeRefreshToken,
coversScopes,
issueAccessToken, issueAccessToken,
issueRefreshToken,
oauthError, oauthError,
redirectUriMatches, redirectUriMatches,
revokeGrant, revokeGrant,
sha256, sha256,
storeRefreshToken,
verifyPkce, verifyPkce,
} from "@/lib/mcp/oauth" } from "@/lib/mcp/oauth"
@@ -40,8 +42,16 @@ export async function POST(request: Request) {
const form = await readForm(request) const form = await readForm(request)
const grantType = form.get("grant_type") const grantType = form.get("grant_type")
if (grantType === "authorization_code") return exchangeCode(form) try {
if (grantType === "refresh_token") return refresh(form) if (grantType === "authorization_code") return await exchangeCode(form)
if (grantType === "refresh_token") return await refresh(form)
} catch (error) {
// Raised when a revoke or a fresh consent won a race against this request.
if (error instanceof GrantStateError) {
return oauthError("invalid_grant", error.message)
}
throw error
}
return oauthError( return oauthError(
"unsupported_grant_type", "unsupported_grant_type",
@@ -96,13 +106,27 @@ async function exchangeCode(form: URLSearchParams) {
return oauthError("invalid_grant", "redirect_uri does not match the authorization request.") return oauthError("invalid_grant", "redirect_uri does not match the authorization request.")
} }
// Resolved by the code's own grantId, not by (client, user). Those can point
// at the same row across a revoke-and-re-consent, which is how a code minted
// under an old, broader consent used to stay redeemable afterwards.
const grant = await prisma.oAuthGrant.findUnique({ const grant = await prisma.oAuthGrant.findUnique({
where: { clientId_userId: { clientId: row.client.id, userId: row.userId } }, where: { id: row.grantId },
select: { id: true, revokedAt: true }, select: { id: true, epoch: true, scopes: true, revokedAt: true },
}) })
if (!grant || grant.revokedAt) { if (!grant || grant.revokedAt) {
return oauthError("invalid_grant", "This authorization is no longer valid.") return oauthError("invalid_grant", "This authorization is no longer valid.")
} }
if (grant.epoch !== row.grantEpoch) {
return oauthError(
"invalid_grant",
"Consent has changed since this code was issued. Start the authorization again."
)
}
// Defence in depth behind the epoch check: never issue more than the standing
// consent currently allows, whatever the code happens to carry.
if (!coversScopes(grant.scopes, row.scopes)) {
return oauthError("invalid_grant", "This code requests more than the current consent allows.")
}
if (!verifyPkce(verifier, row.codeChallenge)) { if (!verifyPkce(verifier, row.codeChallenge)) {
// A verifier that does not match means whoever is holding this code is // A verifier that does not match means whoever is holding this code is
@@ -119,23 +143,15 @@ async function exchangeCode(form: URLSearchParams) {
return oauthError("invalid_grant", "This account is not active.") return oauthError("invalid_grant", "This account is not active.")
} }
const tokens = await issueAccessToken( const tokens = await issueAccessToken(grant, row.userId, row.scopes, row.client.clientName)
grant.id,
row.userId,
row.scopes,
row.client.clientName
)
// A refresh token only exists if offline_access was actually granted.
let refreshToken: string | undefined let refreshToken: string | undefined
if (row.scopes.includes(OFFLINE_ACCESS)) { if (row.scopes.includes(OFFLINE_ACCESS)) {
const minted = generateRefreshToken() refreshToken = await issueRefreshToken(grant, 0)
await storeRefreshToken(grant.id, minted.hash, null)
refreshToken = minted.token
} }
console.log( console.log(
`[oauth] token issued user=${row.userId} client=${row.client.clientId} grant=${grant.id}` `[oauth] token issued user=${row.userId} client=${row.client.clientId} grant=${grant.id} epoch=${grant.epoch}`
) )
return NextResponse.json( return NextResponse.json(
{ ...tokens, ...(refreshToken ? { refresh_token: refreshToken } : {}) }, { ...tokens, ...(refreshToken ? { refresh_token: refreshToken } : {}) },
@@ -147,53 +163,55 @@ async function refresh(form: URLSearchParams) {
const token = form.get("refresh_token") const token = form.get("refresh_token")
if (!token) return oauthError("invalid_request", "refresh_token is required.") if (!token) return oauthError("invalid_request", "refresh_token is required.")
const hash = sha256(token) const outcome = await consumeRefreshToken(sha256(token))
const grant = await prisma.oAuthGrant.findFirst({ if (outcome.kind === "unknown") {
where: { OR: [{ refreshHash: hash }, { refreshPrevHash: hash }] }, return oauthError("invalid_grant", "Unknown refresh token.")
include: { }
if (outcome.kind === "expired") {
return oauthError("invalid_grant", "This refresh token has expired.")
}
if (outcome.kind === "reuse") {
// Every generation is retained, so this fires for any member of the family,
// not just the one immediately previous. Reuse means either theft or a
// client that cannot hold state; both warrant ending the family.
await revokeGrant(outcome.grantId)
console.warn(`[oauth] refresh token reuse on grant=${outcome.grantId}; family revoked`)
return oauthError("invalid_grant", "This refresh token has already been used.")
}
const grant = await prisma.oAuthGrant.findUnique({
where: { id: outcome.grantId },
select: {
id: true,
epoch: true,
scopes: true,
revokedAt: true,
userId: true,
client: { select: { clientId: true, clientName: true } }, client: { select: { clientId: true, clientName: true } },
user: { select: { status: true } }, user: { select: { status: true } },
}, },
}) })
if (!grant) return oauthError("invalid_grant", "Unknown refresh token.") if (!grant || grant.revokedAt) {
return oauthError("invalid_grant", "This authorization was revoked.")
// Presenting the previous generation means the current one was rotated out
// from under this caller - either a replay of a stolen token or a client
// holding a stale copy. Either way the safe move is to end the grant and make
// everyone re-authorize.
if (grant.refreshPrevHash === hash && grant.refreshHash !== hash) {
await revokeGrant(grant.id)
console.warn(
`[oauth] refresh token replay for client=${grant.client.clientId} user=${grant.userId}; grant revoked`
)
return oauthError("invalid_grant", "This refresh token has already been used.")
} }
// A grant whose standing consent no longer includes offline_access must not
if (grant.revokedAt) return oauthError("invalid_grant", "This authorization was revoked.") // keep minting refresh tokens off a credential issued when it did.
if (grant.refreshExpiresAt && grant.refreshExpiresAt <= new Date()) { if (!grant.scopes.includes(OFFLINE_ACCESS)) {
return oauthError("invalid_grant", "This refresh token has expired.") await revokeGrant(grant.id)
return oauthError("invalid_grant", "Offline access is no longer granted.")
} }
if (grant.user.status !== "ACTIVE") { if (grant.user.status !== "ACTIVE") {
return oauthError("invalid_grant", "This account is not active.") return oauthError("invalid_grant", "This account is not active.")
} }
const tokens = await issueAccessToken( const tokens = await issueAccessToken(
grant.id, grant,
grant.userId, grant.userId,
grant.scopes, grant.scopes,
grant.client.clientName grant.client.clientName
) )
const next = await issueRefreshToken(grant, outcome.generation + 1)
// Rotate. OAuth 2.1 requires it for public clients, and keeping the old hash return NextResponse.json({ ...tokens, refresh_token: next }, { headers: NO_STORE })
// in refreshPrevHash is what makes the replay check above possible. Done
// after the access token is minted so a failure there leaves the caller's
// existing refresh token still usable.
const next = generateRefreshToken()
await storeRefreshToken(grant.id, next.hash, hash)
return NextResponse.json(
{ ...tokens, refresh_token: next.token },
{ headers: NO_STORE }
)
} }

View File

@@ -83,11 +83,13 @@ export default async function AuthorizePage({
// round of clicking Allow. // round of clicking Allow.
const existing = await prisma.oAuthGrant.findUnique({ const existing = await prisma.oAuthGrant.findUnique({
where: { clientId_userId: { clientId: client.id, userId } }, where: { clientId_userId: { clientId: client.id, userId } },
select: { id: true, scopes: true, revokedAt: true }, select: { id: true, epoch: true, scopes: true, revokedAt: true },
}) })
if (existing && !existing.revokedAt && coversScopes(existing.scopes, params.scopes)) { if (existing && !existing.revokedAt && coversScopes(existing.scopes, params.scopes)) {
const code = await createAuthCode(client.id, userId, params) // Auto-approval changes no state: same grant, same epoch, narrower-or-equal
// scopes. Only an explicit approval advances the epoch.
const code = await createAuthCode(client.id, userId, existing, params)
redirect(buildRedirect(params.redirectUri, { code, state: params.state })) redirect(buildRedirect(params.redirectUri, { code, state: params.state }))
} }
@@ -139,6 +141,7 @@ export default async function AuthorizePage({
async function createAuthCode( async function createAuthCode(
clientRowId: string, clientRowId: string,
userId: string, userId: string,
grant: { id: string; epoch: number },
params: { params: {
redirectUri: string redirectUri: string
scopes: string[] scopes: string[]
@@ -152,6 +155,11 @@ async function createAuthCode(
codeHash: hash, codeHash: hash,
clientId: clientRowId, clientId: clientRowId,
userId, userId,
// Bound to the grant AND its epoch, so the code dies the moment consent
// is revoked or re-granted rather than outliving the decision that
// authorized it.
grantId: grant.id,
grantEpoch: grant.epoch,
redirectUri: params.redirectUri, redirectUri: params.redirectUri,
resource: params.resource, resource: params.resource,
scopes: params.scopes, scopes: params.scopes,

View File

@@ -126,13 +126,18 @@ export function isRegisterableRedirectUri(value: string): boolean {
/** /**
* Matching a redirect at authorize time. * Matching a redirect at authorize time.
* *
* Exact string equality, except for loopback addresses where the port is * Exact string equality, except for loopback addresses where the PORT ALONE is
* ignored. This is the single most common cause of a silently broken native * ignored. Claude Code registers http://localhost/callback and then redirects to
* client: Claude Code registers http://localhost/callback and * an ephemeral port such as http://localhost:51234/callback, so exact matching
* http://127.0.0.1/callback, then redirects to an ephemeral port such as * would reject every native client. RFC 8252 section 7.3 requires the port to be
* http://localhost:51234/callback. RFC 8252 section 7.3 requires the port to be
* ignored for the IP-literal form; the same is applied to localhost so Claude * ignored for the IP-literal form; the same is applied to localhost so Claude
* Code works at all. * Code works at all.
*
* Everything else must match exactly. An earlier version compared only scheme,
* host and path, which silently accepted a request that differed in query,
* fragment or userinfo - and a callback that forwards its query is then a route
* for delivering the authorization code somewhere the client never registered.
* RFC 9700 section 2.1 requires exact matching apart from the loopback port.
*/ */
export function redirectUriMatches(registered: string, requested: string): boolean { export function redirectUriMatches(registered: string, requested: string): boolean {
if (registered === requested) return true if (registered === requested) return true
@@ -145,11 +150,19 @@ export function redirectUriMatches(registered: string, requested: string): boole
return false return false
} }
if (!isLoopback(a) || !isLoopback(b)) return false if (!isLoopback(a) || !isLoopback(b)) return false
return (
a.protocol === b.protocol && // A fragment is never legal on a redirect URI (RFC 6749 3.1.2).
a.hostname === b.hostname && if (a.hash || b.hash) return false
a.pathname === b.pathname // Credentials in a redirect target are a spoofing aid and never needed here.
) if (a.username || a.password || b.username || b.password) return false
// Normalise away only the port, then require the rest to be identical.
const strip = (u: URL) => {
const c = new URL(u.toString())
c.port = ""
return c.toString()
}
return strip(a) === strip(b)
} }
export function findMatchingRedirectUri( export function findMatchingRedirectUri(
@@ -187,22 +200,31 @@ export interface IssuedTokens {
refresh_token?: string refresh_token?: string
} }
/** Thrown when a grant was revoked or re-consented while a request was in flight. */
export class GrantStateError extends Error {
constructor(message = "This authorization is no longer valid.") {
super(message)
this.name = "GrantStateError"
}
}
/** /**
* Mints an access token against a grant. * Mints an access token against a grant.
* *
* Refresh tokens are deliberately NOT handled here. The two call sites need * Two things this deliberately does NOT do:
* different behaviour - the code exchange creates the first one, a refresh
* rotates the existing one and has to record the previous hash for replay
* detection - and doing it in here once meant the rotation was silently
* overwritten and the token handed back matched nothing on file.
* *
* The access token is an ordinary McpAccessToken row with source "oauth", the * - It does not write scopes back to the grant. Token issuance is not consent,
* same shape a hand-minted one has, so verifyMcpToken needs no OAuth awareness. * and treating it as such let a stale authorization code redefine what the
* Previously outstanding tokens on the grant are revoked, so a refresh replaces * user had most recently agreed to. The consent endpoint is the only writer.
* rather than accumulates. * - It does not touch refresh tokens. Those have their own lineage.
*
* The whole write is conditional on the grant still being active AT THE EPOCH
* the caller validated. A revoke racing this call makes the guarded update
* affect zero rows and the transaction aborts, rather than leaving a live token
* hanging off a revoked grant to be resurrected by a later re-consent.
*/ */
export async function issueAccessToken( export async function issueAccessToken(
grantId: string, grant: { id: string; epoch: number },
userId: string, userId: string,
scopes: string[], scopes: string[],
clientName: string clientName: string
@@ -210,8 +232,14 @@ export async function issueAccessToken(
const access = generateMcpToken() const access = generateMcpToken()
await prisma.$transaction(async (tx) => { await prisma.$transaction(async (tx) => {
const { count } = await tx.oAuthGrant.updateMany({
where: { id: grant.id, epoch: grant.epoch, revokedAt: null },
data: { lastUsedAt: new Date() },
})
if (count !== 1) throw new GrantStateError()
await tx.mcpAccessToken.updateMany({ await tx.mcpAccessToken.updateMany({
where: { grantId, revokedAt: null }, where: { grantId: grant.id, revokedAt: null },
data: { revokedAt: new Date() }, data: { revokedAt: new Date() },
}) })
await tx.mcpAccessToken.create({ await tx.mcpAccessToken.create({
@@ -222,14 +250,10 @@ export async function issueAccessToken(
name: clientName, name: clientName,
scopes: accessScopes(scopes), scopes: accessScopes(scopes),
source: "oauth", source: "oauth",
grantId, grantId: grant.id,
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS), expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
}, },
}) })
await tx.oAuthGrant.update({
where: { id: grantId },
data: { scopes, lastUsedAt: new Date() },
})
}) })
return { return {
@@ -240,23 +264,70 @@ export async function issueAccessToken(
} }
} }
/** Stores a freshly minted refresh token on the grant, keeping the old hash for replay detection. */ /**
export async function storeRefreshToken( * Mints the next refresh token in a family, guarded on the grant's epoch for the
grantId: string, * same reason as above.
hash: string, */
previousHash: string | null export async function issueRefreshToken(
): Promise<void> { grant: { id: string; epoch: number },
await prisma.oAuthGrant.update({ generation: number
where: { id: grantId }, ): Promise<string> {
const { token, hash } = generateRefreshToken()
await prisma.$transaction(async (tx) => {
const active = await tx.oAuthGrant.count({
where: { id: grant.id, epoch: grant.epoch, revokedAt: null },
})
if (active !== 1) throw new GrantStateError()
await tx.oAuthRefreshToken.create({
data: { data: {
refreshHash: hash, grantId: grant.id,
refreshPrevHash: previousHash, tokenHash: hash,
refreshExpiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS), generation,
expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
}, },
}) })
})
return token
} }
/** Kills a grant and every access token it issued. */ export type RefreshConsumption =
| { kind: "unknown" }
| { kind: "expired" }
| { kind: "reuse"; grantId: string }
| { kind: "ok"; grantId: string; generation: number }
/**
* Redeems a refresh token exactly once.
*
* Every generation is retained, so a token from any point in the family's life
* is still recognisable as reuse - which is the whole point. The guarded update
* on `usedAt` means two concurrent presentations of the same token cannot both
* win: the loser is reported as reuse, which is indistinguishable from theft and
* treated the same way.
*/
export async function consumeRefreshToken(hash: string): Promise<RefreshConsumption> {
const row = await prisma.oAuthRefreshToken.findUnique({
where: { tokenHash: hash },
select: { id: true, grantId: true, generation: true, usedAt: true, expiresAt: true },
})
if (!row) return { kind: "unknown" }
if (row.usedAt) return { kind: "reuse", grantId: row.grantId }
if (row.expiresAt <= new Date()) return { kind: "expired" }
const { count } = await prisma.oAuthRefreshToken.updateMany({
where: { id: row.id, usedAt: null },
data: { usedAt: new Date() },
})
if (count !== 1) return { kind: "reuse", grantId: row.grantId }
return { kind: "ok", grantId: row.grantId, generation: row.generation }
}
/** Kills a grant, every access token it issued, and its whole refresh family. */
export async function revokeGrant(grantId: string): Promise<void> { export async function revokeGrant(grantId: string): Promise<void> {
const now = new Date() const now = new Date()
await prisma.$transaction([ await prisma.$transaction([
@@ -264,13 +335,13 @@ export async function revokeGrant(grantId: string): Promise<void> {
where: { grantId, revokedAt: null }, where: { grantId, revokedAt: null },
data: { revokedAt: now }, data: { revokedAt: now },
}), }),
prisma.oAuthRefreshToken.deleteMany({ where: { grantId } }),
// Outstanding codes die too, so one minted before the revoke cannot be
// redeemed against a later re-consent.
prisma.oAuthAuthCode.deleteMany({ where: { grantId, consumedAt: null } }),
prisma.oAuthGrant.update({ prisma.oAuthGrant.update({
where: { id: grantId }, where: { id: grantId },
data: { data: { revokedAt: now },
revokedAt: now,
refreshHash: null,
refreshPrevHash: null,
},
}), }),
]) ])
} }

View File

@@ -371,7 +371,7 @@ export function registerDrinkTools(server: McpServer): void {
name: "get_collection_stats", name: "get_collection_stats",
title: "Collection summary", title: "Collection summary",
description: description:
"Counts and averages across the whole collection: drinks by type, rating activity, top rated drinks, bar size and recipe count. Prefer this over several list calls when the question is about the collection as a whole.", "Counts and averages across the whole collection: drinks by type, rating activity and top rated drinks, plus bar size and recipe count when the connection also has bar access. Prefer this over several list calls when the question is about the collection as a whole.",
inputSchema: emptySchema, inputSchema: emptySchema,
scope: "drinks:read", scope: "drinks:read",
readOnly: true, readOnly: true,
@@ -379,6 +379,11 @@ export function registerDrinkTools(server: McpServer): void {
async (_args, caller) => { async (_args, caller) => {
const userId = caller.userId const userId = caller.userId
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
// This tool sits behind drinks:read, but two of its numbers describe the
// bar. Returning them regardless leaked across the scope boundary the
// consent screen promises, so they are gated on the caller actually
// holding bar:read rather than on which tool happened to be called.
const canReadBar = caller.scopes.includes("bar:read")
const [byType, drinkCount, ratingAgg, recentRatings, barCount, recipeCount, top] = const [byType, drinkCount, ratingAgg, recentRatings, barCount, recipeCount, top] =
await Promise.all([ await Promise.all([
@@ -396,8 +401,12 @@ export function registerDrinkTools(server: McpServer): void {
prisma.rating.count({ prisma.rating.count({
where: { userId, createdAt: { gte: thirtyDaysAgo } }, where: { userId, createdAt: { gte: thirtyDaysAgo } },
}), }),
prisma.barItem.count({ where: { userId, quantity: { not: "EMPTY" } } }), canReadBar
prisma.recipe.count({ where: { userId } }), ? prisma.barItem.count({ where: { userId, quantity: { not: "EMPTY" } } })
: Promise.resolve(null),
canReadBar
? prisma.recipe.count({ where: { userId } })
: Promise.resolve(null),
prisma.rating.findMany({ prisma.rating.findMany({
where: { userId }, where: { userId },
orderBy: [{ score: "desc" }, { createdAt: "desc" }], orderBy: [{ score: "desc" }, { createdAt: "desc" }],
@@ -419,7 +428,9 @@ export function registerDrinkTools(server: McpServer): void {
typeLines || " (none)", typeLines || " (none)",
`${ratingAgg._count._all} ratings, average ${avg ? avg.toFixed(2) : "n/a"}`, `${ratingAgg._count._all} ratings, average ${avg ? avg.toFixed(2) : "n/a"}`,
`${recentRatings} ratings in the last 30 days`, `${recentRatings} ratings in the last 30 days`,
`${barCount} bottles in the bar, ${recipeCount} saved recipes`, canReadBar
? `${barCount} bottles in the bar, ${recipeCount} saved recipes`
: "",
top.length ? "top rated:" : "", top.length ? "top rated:" : "",
topLines, topLines,
] ]
@@ -432,8 +443,7 @@ export function registerDrinkTools(server: McpServer): void {
ratingCount: ratingAgg._count._all, ratingCount: ratingAgg._count._all,
averageScore: avg, averageScore: avg,
ratingsLast30Days: recentRatings, ratingsLast30Days: recentRatings,
barItemCount: barCount, ...(canReadBar ? { barItemCount: barCount, recipeCount } : {}),
recipeCount,
topRated: top.map((r) => ({ topRated: top.map((r) => ({
drinkName: r.drink.name, drinkName: r.drink.name,
type: r.drink.type, type: r.drink.type,