Compare commits

..

8 Commits

Author SHA1 Message Date
JP
7ff3f68b2c Add a backlog, consolidating deferred work that was only in commit messages
Several decisions had been consciously postponed - the Docker purge date, the
unencrypted dumps, the unestablished Docker-in-LXC cause - but they lived in
commit messages and chat, which is the same as nowhere.

Each entry records what would trigger picking it up, so none of it has to be
re-derived. Starts with the MCP tool-consolidation question: the answer is that
merging CRUD into one tool would cost the annotations, the scope boundary, the
schema clarity and the audit trail, and the useful rule is to merge only when
it is the same gesture with a different parameter.

Nothing here is urgent; that is the point of writing it down rather than doing it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-10 01:22:05 +00:00
JP
a8c959bfab Add a saved recipe to the collection or the wishlist so it can be rated
A recipe was previously a dead end: you could save one and see whether your bar
could make it, but there was no way to record that you had actually drunk it.

Promoting links rather than converts. A drink is created and Recipe.sourceDrinkId
is set to point at it, so the recipe survives and then renders on that drink's
page through the relation the drink detail view already reads. The wishlist path
creates a "try later" entry tagged source=recipe and leaves the recipe alone.

Both are idempotent. Promoting an already-linked recipe returns the existing
drink with a 200 rather than creating a second one, because pressing the button
twice is a double click and not a request for a duplicate. Creation and linking
happen in one transaction - a drink that existed but was not linked back would
show no recipe and would be promoted again on the next attempt.

The logic lives in src/lib/recipe-promotion.ts and is shared by the REST route
and the MCP tool, so the ownership check, the idempotency rule and the generated
description cannot drift apart.

Adding to drinks navigates straight to the rating page: being able to rate it is
the entire point, and an unrated cocktail is easy to lose in a list of 88. There
is no Toaster mounted in this app, so the wishlist path reports inline instead.

One MCP tool with a target parameter rather than two, since the tool list is
already at the point where selection quality suffers - 23 now. Gated on
drinks:write, not bar:write: it changes the collection, not the bar.

Verified: promote to drink then rate it, idempotency on both targets, the
recipe stays linked and undeleted, invalid target, unknown recipe, unauthenticated
access, read-only tokens, and that another user's recipe is refused identically
on both the REST route and the tool without confirming the row exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 21:30:40 +00:00
JP
23c4e63a68 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
2026-08-09 21:05:08 +00:00
JP
5c05464269 Retract the unprivileged-LXC claim in the Docker post-mortem
/proc/self/uid_map reads 0 0 4294967295 - an identity mapping - so this
container is privileged. The AppArmor and sysctl failures were real and
reproduced, but "because unprivileged" was never the diagnosis, and leaving it
in the doc invites someone to build on a false premise.

Says what is actually known and marks the root cause as unestablished rather
than substituting a fresh guess.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 19:24:03 +00:00
JP
1710e6147b Document the off-site backup leg now that it exists
Nightly backups now copy to TrueNAS over SSH rather than living only on the
LXC they are protecting. Chose scp over the existing NFS share deliberately:
a mount that goes stale writes into the local mountpoint instead, silently
filling the LXC disk while every run reports success. No mount, no such class
of failure - and the backup script already spoke scp, so nothing changed but
two Environment lines.

Set as a systemd drop-in so re-installing the service cannot quietly return to
local-only backups.

Recorded the failure mode that cost time here: sshd refuses authorized_keys
when the user's home directory is group- or world-writable, which TrueNAS
datasets often are. The key is offered and silently rejected, which looks
exactly like a key that was never added.

Verified end to end rather than assumed: the copy lands, the dump passes
gzip -t, contains 25 CREATE TABLE statements including the new MCP and OAuth
tables, and the MinIO tarball reads back with 194 entries.

Still open: the dumps are unencrypted, and TrueNAS is on the same site.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 19:20:16 +00:00
JP
82680d9430 Correct stale deploy docs and document the new env knobs
deploy/README.md described a rewrites() block that no longer exists, and told
the reader to verify the image bucket's anonymous-download policy was set -
which is precisely the exposure that was closed. Following it would have
re-opened every stored image to the public internet.

Replaced with what is actually true: /minio-images is a session-gated route
handler with per-user key-prefix ownership, the bucket must have no anonymous
policy, and MinIO must stay bound to loopback. Also noted that the suggested
`mc anonymous get` check does not work on this host - the alias has no
credentials and returns Access Denied either way - and gave an external curl
that actually tells you something.

The same stale rationale sat in deploy.sh's build comment. Building without the
env file is still right, just for a different reason: nothing needs baking in.

Added the MCP and OAuth journal greps, an unauthenticated discovery check, and
a note that a 307 there means /.well-known fell out of PUBLIC_ROUTES. Documented
in .env.example that NEXTAUTH_URL must be the exact public origin with no
trailing slash, since it is now the OAuth issuer and MCP resource identifier,
plus the MCP_CHATGPT_TOOLS opt-out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 19:04:42 +00:00
JP
e77f605c9c Add OAuth 2.1 server so claude.ai and ChatGPT can connect natively
Phase A needed a token pasted into a header, which Anthropic documents as an
org-admin-scoped beta on claude.ai and is undocumented on ChatGPT. This makes
the app its own authorization server so both connect through their normal
"add a connector" flow, with a per-user consent screen.

The whole thing funnels into the existing verifyMcpToken: an issued access
token is an ordinary McpAccessToken row with source "oauth", so the resource
server gained no OAuth awareness and Phase A's verification path is unchanged.

Notes on the parts that fail quietly if got wrong:

- scopes_supported is published in the protected resource metadata. When a 401
  challenge carries no explicit scope Claude requests exactly what is
  advertised there, so omitting it silently makes every connection read-only.
- Loopback redirect URIs match with the port ignored. Claude Code registers
  http://localhost/callback and then redirects to an ephemeral port; exact
  matching would reject every native client. RFC 8252 7.3 requires this.
- CIMD is deliberately not advertised. Claude only selects it when the metadata
  carries client_id_metadata_document_supported, and supporting it would mean
  fetching a client-supplied URL server-side from a host that also reaches
  MinIO, Postgres and the gateway on the LAN. DCR costs nothing by comparison.
- The consent page validates client_id and redirect_uri before it will redirect
  anywhere, because an unvalidated redirect_uri is an open redirect.
- Authorization codes are consumed by one guarded updateMany, so a replay under
  concurrency cannot mint a second token. A PKCE mismatch burns the whole grant
  rather than just the code.
- Refresh tokens rotate and keep the previous hash; presenting it revokes the
  grant, since that is either theft or a client that cannot be trusted to hold
  state.

Also fixes the login page, which hardcoded callbackUrl and so dropped anyone
sent to sign in for the consent screen onto /dashboard instead. Same-origin
destinations only, absolute or relative - the middleware writes absolute.

"/.well-known" joins PUBLIC_ROUTES. It is a prefix match, so nothing else
should be served from there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 05:33:48 +00:00
JP
4fd339dabc Add MCP server so Claude and ChatGPT can read and write drink data
Exposes the collection over the Model Context Protocol at /api/mcp, with 22
tools covering drinks, ratings, bar inventory, recipes, wishlist and taste
preferences, plus search/fetch aliases for ChatGPT's deep-research mode.

Authentication is a bearer token, the app's first header-borne credential -
every other route derives identity from the NextAuth cookie, which a machine
client cannot present. /api/mcp sits under the middleware's /api exclusion so
it can answer a JSON 401 with an RFC 9728 WWW-Authenticate challenge instead
of an HTML redirect to /login.

Tokens are stored as a SHA-256 hash rather than plaintext like Invite.token
and PasswordReset.token. Those are single-use and short-lived; this one is
long-lived and grants read/write over a whole collection, and the nightly
pg_dump keeps 14 days of history. Not encrypt(), which is reversible AES and
right only for outbound keys we must replay; not bcrypt, which cannot be
indexed and would turn verification into a table scan per request.

verifyMcpToken joins User.status on every call, mirroring the jwt callback, so
suspending a member kills their MCP access immediately rather than leaving the
token as a documented way to outlive suspension. It fails closed on a database
error, deliberately unlike the jwt callback, which keeps the session because a
throw there would sign out every user at once.

No tool reaches the Switchboard gateway. Claude and ChatGPT are language
models already, so they can reason over a bar inventory without the app paying
to do it a second time, and a remote client looping a vision call is not a
failure mode worth having. Account deletion, restore, gateway keys, admin
routes and shared-list creation are excluded too.

The OAuth models ship now but are unused; the token endpoint will write the
same McpAccessToken rows, so adding it later touches no verification code.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 04:29:54 +00:00
49 changed files with 5123 additions and 36 deletions

View File

@@ -5,6 +5,9 @@ POSTGRES_PASSWORD="YOUR_PASSWORD"
POSTGRES_DB="drinktracker"
# NextAuth
# Must be the exact public origin, with NO trailing slash. Beyond login redirects
# it is the OAuth `issuer` and the MCP `resource` identifier, and connectors
# compare both byte-for-byte - a mismatch fails discovery with no useful error.
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="generate-with: openssl rand -base64 32"
AUTH_TRUST_HOST="true" # Set to true when behind a reverse proxy
@@ -25,3 +28,9 @@ ENCRYPTION_KEY="generate-with: openssl rand -hex 32"
# OpenAI-compatible router that picks the best model per request. LAN-only, plain HTTP.
# Each user adds their own gateway API key in Settings; this is only the endpoint.
SWITCHBOARD_BASE_URL="http://192.168.2.11:8787/v1"
# MCP server (optional)
# The `search` and `fetch` tools exist only for ChatGPT's deep-research mode.
# Their generic names can muddy tool selection when several connectors are
# attached at once, so set this to 0 on a Claude-only deployment to drop them.
# MCP_CHATGPT_TOOLS="0"

116
BACKLOG.md Normal file
View File

@@ -0,0 +1,116 @@
# Backlog
Things deliberately deferred, with enough context to pick them up cold. Not a
wish list — everything here has been considered and consciously postponed, and
each entry says what would trigger doing it.
Last reviewed: 2026-08-10
---
## Consolidating MCP tools
**Trigger: the model starts picking the wrong tool, or `tools/list` overhead becomes measurable.**
There are 23 tools. The often-quoted ceiling of ~20 is a rule of thumb, not a
threshold, and mis-selection is caused by tools that resemble each other far more
than by raw count — these are mostly distinct. It has been working well in
practice, so this is not currently a problem.
The question that prompted this: could one `modify_drink` take an `action` of
create/update/delete and replace three tools? Technically yes, but it is the
wrong merge:
- **Annotations stop meaning anything.** A tool that *can* delete has to be
marked `destructiveHint`, so a client that confirms destructive actions would
start prompting when you add a drink — or you mark it false and lose the
prompt when it matters.
- **Scope enforcement gets coarser.** Reads need `drinks:read` and writes need
`drinks:write`. A merged tool must demand the union (a read-only token loses
read access) or branch internally, at which point the declared scope no longer
describes the tool and the consent screen misleads.
- **The schema gets harder for the model.** `id` is required for update/delete
and meaningless for create. That is a discriminated union, which converts to
`anyOf` — exactly the shape models fill in wrong.
- **The audit trail gets vaguer.** `McpAuditLog` records the tool name;
`delete_drink` says what happened, `modify_drink` does not.
The rule worth keeping: **merge when it is the same gesture with a different
parameter; keep separate when the intent or the risk differs.** `upsert_bar_item`
("I bought gin" / "I finished the gin") and `promote_recipe` (drink vs wishlist)
are good merges. CRUD is not.
Cheaper levers if the count ever needs to come down:
1. `MCP_CHATGPT_TOOLS=0` drops the `search`/`fetch` aliases: 23 → 21, free if
ChatGPT is unused.
2. Remove low-value tools rather than merging good ones. `update_rating` is the
weakest — a drink can simply be re-rated.
3. Sharpen descriptions. Selection failures are usually a description problem.
Worth measuring the real `tools/list` payload cost before spending effort here.
---
## Refresh-token grace window
**Trigger: a client is forced to re-authorize after a dropped network response.**
Reuse of any refresh generation currently revokes the whole family, with no
grace. That is correct against theft but harsh on a client whose response was
lost in transit — it replays legitimately and destroys its own grant.
The audit's advice was to build durable lineage first and only then consider
grace. Lineage now exists (`OAuthRefreshToken`, one row per generation, atomic
consume), so this is a safe change to make if it ever bites. Auth0 disables
leeway by default; Okta defaults to 30 seconds, configurable to 60. A 510
second window limited to the immediately preceding generation would be
reasonable — anything older must still revoke the family.
---
## Encrypt backup dumps
**Trigger: backups leave the LAN, for any reason.**
`pg_dump` output goes to TrueNAS unencrypted and contains every user's data plus
bcrypt password hashes. Defensible on a NAS you control on your own network;
not defensible in cloud storage, a friend's NAS, or off-site replication.
`gpg` or `age` before the `scp` in `/usr/local/bin/drinktracker-backup` is a
couple of lines. Much easier to add before there is history to re-encrypt.
Related: the off-site copy is in the same building, so it survives losing the
LXC or the Proxmox host but not fire or theft.
---
## Purge the retained Docker artifacts
**Trigger: 2026-09-07.**
Docker is installed but disabled on the LXC; old containers and volumes were
kept as a rollback path after the move to native systemd. Nothing has needed
them. Remove after that date.
---
## Establish why Docker actually failed in this LXC
**Trigger: only if Docker is ever wanted on this host again.**
`deploy/README.md` originally blamed unprivileged-LXC nesting. That is wrong —
`/proc/self/uid_map` reads `0 0 4294967295`, an identity mapping, so the
container is privileged. The AppArmor and `ip_unprivileged_port_start` failures
were real and reproduced, but the cause was never established. The doc now says
so rather than substituting a fresh guess.
---
## Rotate the TrueNAS account password
**Trigger: do it whenever convenient.**
`getent passwd` run as root on TrueNAS prints the SHA-512 hash, and one ended up
in a session transcript. Salted and not trivially reversible, but crackable
offline against a weak password.

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

@@ -26,9 +26,13 @@ The app runs **natively under systemd — there is no Docker on this host.**
**`drinktracker.tenseconddelay.net` resolves to the reverse proxy (192.168.2.172), not the container.** `NEXTAUTH_URL` points at the public name, so resolving it and SSHing there fails in a way that looks like a rejected key but is simply a different machine.
**`next.config.mjs` evaluates `rewrites()` at BUILD time.** The `/minio-images/:path*` destination is baked into `routes-manifest.json` as `http://localhost:9000/drink-images/:path*`. Changing `MINIO_ENDPOINT` in the env file appears to work and does nothing — images break only after the *next* rebuild, so the change and the breakage are separated in time. MinIO must stay on `localhost:9000` serving `drink-images`.
**Images are served by an authenticated route, not a rewrite.** `next.config.mjs` has no `rewrites()` block at all. `/minio-images/:path*` is a route handler (`src/app/minio-images/[...key]/route.ts`) that requires a session, rejects `..` in the key, and enforces per-user ownership by key prefix (`<userId>/` or `scans/<userId>/`). It reads `MINIO_ENDPOINT` at request time, so changing it takes effect on restart with no rebuild.
**The image proxy is an unauthenticated GET.** Next rewrites don't sign requests, so the bucket's anonymous-download policy is load-bearing. Verify with `mc anonymous get local/drink-images` → must say `download`.
> This replaced an unauthenticated rewrite that, combined with an anonymous-download bucket policy, exposed every stored image to the public internet. **The bucket must not have an anonymous policy, and MinIO must stay bound to loopback** (`127.0.0.1:9000`, verify with `ss -lntp | grep 9000`). `mc anonymous get local/drink-images` is not a usable check here — the `local` alias on this host has no working credentials and returns `Access Denied` regardless. Check from outside instead: `curl -si https://drinktracker.tenseconddelay.net/minio-images?list-type=2` must **not** return a `200` with an XML key listing.
**Never use `next/image` for stored images.** The optimizer fetches them server-side without the session cookie, so every image would 401. All renders are plain `<img>`, and there is deliberately no `images.remotePatterns` config.
**`NEXTAUTH_URL` must exactly equal the public origin, with no trailing slash.** Beyond login redirects it now drives the OAuth `issuer` and the MCP `resource` identifier, both of which clients compare byte-for-byte. A mismatch does not error — connectors just fail to complete with an unhelpful "couldn't reach the server".
**`prisma db push`, not `migrate deploy`.** Production has no `_prisma_migrations` table, so `migrate deploy` would try to apply the init migration against populated tables and fail. `--accept-data-loss` means removing a field from `schema.prisma` **drops the column and its data** — the deploy script dumps first for this reason.
@@ -36,13 +40,15 @@ The app runs **natively under systemd — there is no Docker on this host.**
Build happens in `/opt/drinktracker/repo` and is assembled **out-of-place** into `releases/<sha>`, so the ~3 minute build runs while the current release keeps serving. Only the symlink swap and `systemctl restart` cause downtime, about 3 seconds. Rollback is the same swap in reverse and needs no rebuild.
The build deliberately does **not** source the env file same as the Dockerfile — because of the build-time rewrite baking described above.
The build deliberately does **not** source the env file, same as the Dockerfile. Nothing in this app needs configuration baked into the bundle: `NEXTAUTH_URL`, `MINIO_ENDPOINT` and the rest are read at request time by dynamic routes, so the build stays identical regardless of which host it runs on. (This originally guarded against a `rewrites()` block that baked a MinIO URL into `routes-manifest.json`; that block is gone, but building without secrets is still the right default.)
## Docker still works, just not here
`Dockerfile` and `docker-compose.prod.yml` are maintained for running this app elsewhere (a VPS). `docker compose build && docker compose up -d` works on any normal Docker host.
It does **not** work on this LXC, which is why the app runs natively. Two independent problems, both from unprivileged-LXC nesting:
It does **not** work on this LXC, which is why the app runs natively. Two independent problems, both from running a container runtime nested inside an LXC:
> An earlier version of this note blamed *unprivileged*-LXC nesting. That is wrong: `/proc/self/uid_map` reads `0 0 4294967295`, an identity mapping, so **this container is privileged**. The two failures below were reproduced and are real; the root cause was never actually established, so don't treat "because unprivileged" as a diagnosis if you revisit this.
1. AppArmor — the container can't load the `docker-default` profile (`apparmor_parser: Access denied`), so any container without `--security-opt apparmor=unconfined` fails.
2. runc can't set `net.ipv4.ip_unprivileged_port_start`, so containers only work with `--network host`.
@@ -56,16 +62,59 @@ ssh -i ~/.ssh/drinktracker_ed25519 drinkadmin@192.168.2.169
systemctl is-active postgresql@16-main minio drinktracker
sudo journalctl -u drinktracker -n 50
sudo journalctl -u drinktracker | grep '\[switchboard\]' # AI routing + cost per call
sudo journalctl -u drinktracker | grep '\[mcp\]' # one line per MCP tool call
sudo journalctl -u drinktracker | grep '\[oauth\]' # connector grants and token issuance
readlink /opt/drinktracker/current # which release is live
```
Each AI call logs one `[switchboard] feature=… model=… cost=… latency_ms=…` line. `FAILOVER` warnings are expected — the gateway's `:batch` model variants currently fail on every request and fall back. `CONTEXT OVERFLOW` is worth investigating.
MCP tool calls log `[mcp] user=… tool=… ok=… ms=…`, and the same events are rows in `McpAuditLog` (arguments are deliberately never recorded). `[oauth]` lines cover consent grants and token issuance; a `PKCE mismatch` or `refresh token replay` warning there means a grant was revoked defensively and is worth looking at.
Discovery can be checked without credentials:
```bash
curl -s https://drinktracker.tenseconddelay.net/.well-known/oauth-protected-resource | jq
curl -si https://drinktracker.tenseconddelay.net/api/mcp -X POST \
-H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2026-07-28' -H 'Mcp-Method: tools/list' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}'
```
The second must return **401** with a `WWW-Authenticate: Bearer … resource_metadata="…"` header. A `307` there means `/.well-known` fell out of `PUBLIC_ROUTES` in `src/lib/auth.ts` and discovery is broken.
## Backups
`drinktracker-backup.timer` runs nightly at 03:25: `pg_dump` + a tar of `/var/lib/minio/data` + a copy of the env file, into `/var/backups/drinktracker`, retained 14 days (~1 GB).
**TODO — the chain has no off-site leg.** `/usr/local/bin/drinktracker-backup` supports `OFFSITE_DEST` (an scp target) and `OFFSITE_KEY`; set them via `Environment=` in `drinktracker-backup.service`. Until then everything lives on one LXC on one Proxmox host, and the nightly job prints a warning saying so.
Each run also copies the dump and the MinIO tarball off-site to TrueNAS:
| | |
|---|---|
| Destination | `jpscott84@192.168.2.196:/mnt/Beefcake/backup/drinktracker` (dataset `Beefcake/backup`) |
| Transport | `scp` over SSH — **not** NFS, so there is no mount to go stale and silently swallow a night's backup into the LXC's own disk |
| Key | `/root/.ssh/drinktracker_backup_ed25519`, a dedicated backup-only keypair |
| Config | `Environment=` lines in `/etc/systemd/system/drinktracker-backup.service.d/offsite.conf` |
Set as a **drop-in** rather than an edit to the unit, so re-installing the service cannot silently drop the off-site leg and return to local-only backups.
A successful run logs `offsite copy ok -> …`. If it ever logs `NOTE: OFFSITE_DEST unset` again, the drop-in has gone missing. A failed copy logs `WARNING: offsite copy FAILED` and **keeps the local copy** — the job still exits 0, so watch the log rather than the exit status.
```bash
sudo systemctl start drinktracker-backup.service # run it now
sudo journalctl -u drinktracker-backup -n 20 # look for "offsite copy ok"
```
Verify what landed is actually restorable, not merely present:
```bash
sudo ssh -i /root/.ssh/drinktracker_backup_ed25519 jpscott84@192.168.2.196 \
'ls -lh /mnt/Beefcake/backup/drinktracker && gzip -t /mnt/Beefcake/backup/drinktracker/pg-*.sql.gz && echo OK'
```
**Two gaps that remain.** The dumps are **unencrypted** and contain every user's data plus bcrypt password hashes — acceptable writing to a NAS on the same LAN, but encrypt before this ever leaves the network. And TrueNAS is in the same building, so this survives losing the LXC or the Proxmox host, not fire or theft.
> If SSH key auth to TrueNAS ever breaks: sshd refuses `authorized_keys` when the user's **home directory** is group- or world-writable, which TrueNAS datasets often are by default. `/mnt/local/jpscott84` must not be `777`. The symptom is indistinguishable from a missing key — the key is offered and silently rejected — so check `journalctl -u ssh | grep 'bad ownership'` on the NAS first.
Restore:

View File

@@ -109,9 +109,10 @@ git -C "$APP_DIR/repo" log --oneline -1
cd "$APP_DIR/repo"
export npm_config_cache="$APP_DIR/.npm" NODE_OPTIONS=--max-old-space-size=3072
# Built WITHOUT the env file, deliberately - same as the Dockerfile. next.config.mjs
# evaluates rewrites() at build time, so sourcing the env here would bake a different
# /minio-images destination into routes-manifest.json.
# Built WITHOUT the env file, deliberately - same as the Dockerfile. Every setting
# this app reads (NEXTAUTH_URL, MINIO_ENDPOINT, ...) is read at request time by a
# dynamic route, so nothing needs baking in and the bundle stays host-independent.
# Keep it that way: a build that depends on secrets stops being reproducible.
npm ci --prefer-offline --no-audit --fund=false
npx prisma generate
npm run build

78
package-lock.json generated
View File

@@ -10,6 +10,7 @@
"dependencies": {
"@auth/prisma-adapter": "^2.11.1",
"@aws-sdk/client-s3": "^3.1000.0",
"@modelcontextprotocol/server": "^2.0.0",
"@prisma/client": "^6.19.2",
"@tanstack/react-query": "^5.90.21",
"@types/bcryptjs": "^2.4.6",
@@ -18,6 +19,7 @@
"clsx": "^2.1.1",
"html5-qrcode": "^2.3.8",
"lucide-react": "^0.575.0",
"mcp-handler": "^2.1.0",
"next": "14.2.35",
"next-auth": "^5.0.0-beta.25",
"openai": "^6.25.0",
@@ -1607,6 +1609,31 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@modelcontextprotocol/core": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz",
"integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==",
"license": "MIT",
"dependencies": {
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@modelcontextprotocol/server": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz",
"integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/core": "2.0.0",
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
@@ -6125,6 +6152,57 @@
"node": ">= 0.4"
}
},
"node_modules/mcp-handler": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/mcp-handler/-/mcp-handler-2.1.0.tgz",
"integrity": "sha512-mhnUpkgWrXMwwhdbJ5Uq43uUV23Emxfq3fRfsFwt8Kjc35cGUiKuYeX9wjwnvsdTiKsmjXnQ4tO4awWa3ZM4LQ==",
"license": "Apache-2.0",
"dependencies": {
"chalk": "^5.3.0",
"commander": "^11.1.0"
},
"bin": {
"create-mcp-route": "dist/cli/index.js",
"mcp-adapter": "dist/cli/index.js",
"mcp-handler": "dist/cli/index.js"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@modelcontextprotocol/server": "^2.0.0",
"next": ">=13.0.0"
},
"peerDependenciesMeta": {
"@modelcontextprotocol/server": {
"optional": false
},
"next": {
"optional": true
}
}
},
"node_modules/mcp-handler/node_modules/chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
"integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
"license": "MIT",
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/mcp-handler/node_modules/commander": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz",
"integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==",
"license": "MIT",
"engines": {
"node": ">=16"
}
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",

View File

@@ -11,6 +11,7 @@
"dependencies": {
"@auth/prisma-adapter": "^2.11.1",
"@aws-sdk/client-s3": "^3.1000.0",
"@modelcontextprotocol/server": "^2.0.0",
"@prisma/client": "^6.19.2",
"@tanstack/react-query": "^5.90.21",
"@types/bcryptjs": "^2.4.6",
@@ -19,6 +20,7 @@
"clsx": "^2.1.1",
"html5-qrcode": "^2.3.8",
"lucide-react": "^0.575.0",
"mcp-handler": "^2.1.0",
"next": "14.2.35",
"next-auth": "^5.0.0-beta.25",
"openai": "^6.25.0",

View File

@@ -58,6 +58,11 @@ model User {
invitesCreated Invite[] @relation("InviteCreator")
redemption InviteRedemption?
passwordResets PasswordReset[]
mcpTokens McpAccessToken[]
mcpAuditLogs McpAuditLog[]
oauthAuthCodes OAuthAuthCode[]
oauthGrants OAuthGrant[]
}
// ─── Invites ─────────────────────────────────────────────────────
@@ -111,6 +116,182 @@ model PasswordReset {
@@index([userId])
}
// ─── MCP access ──────────────────────────────────────────────────
// The app's first header-borne credential. Every other route derives identity
// from the NextAuth JWT cookie, which a machine client (claude.ai, ChatGPT,
// Claude Code) cannot present.
/// Bearer token for the MCP endpoint. Two producers, one table: a token minted
/// by hand in Settings (source "pat") and one issued by the OAuth token endpoint
/// (source "oauth") are the same row shape, so verification has a single path.
///
/// Stored as a SHA-256 hash, unlike Invite.token and PasswordReset.token which
/// are plaintext. Those are single-use and short-lived; this one is long-lived
/// and grants full read/write over a user's whole collection, and the nightly
/// pg_dump keeps 14 days of history.
model McpAccessToken {
id String @id @default(cuid())
userId String
/// sha256 hex of the raw secret - never the secret itself
tokenHash String @unique
/// First 8 chars of the secret, so the UI can tell two tokens apart
prefix String
/// User-supplied label, or the OAuth client name
name String?
scopes String[]
/// "pat" | "oauth"
source String @default("pat")
/// Set only for OAuth-issued tokens; revoking the grant revokes these with it
grantId String?
lastUsedAt DateTime?
expiresAt DateTime?
revokedAt DateTime?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
grant OAuthGrant? @relation(fields: [grantId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([grantId])
@@index([expiresAt])
}
/// One row per MCP tool call. Modelled on AiCall: the arguments are deliberately
/// not recorded - they carry free-text tasting notes and could carry anything.
model McpAuditLog {
id String @id @default(cuid())
userId String
tokenId String?
tool String
ok Boolean
errorCode String?
/// Row the call created, updated or deleted
recordId String?
durationMs Int?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, createdAt])
@@index([createdAt])
}
/// A client registered through RFC 7591 dynamic registration. Not user-owned -
/// registrations are global, and a user's access is revoked by cascading their
/// OAuthGrant instead.
model OAuthClient {
id String @id @default(cuid())
clientId String @unique
clientName String
redirectUris String[]
grantTypes String[] @default(["authorization_code", "refresh_token"])
responseTypes String[] @default(["code"])
/// Public clients only - this server stores no client secrets
tokenEndpointAuthMethod String @default("none")
scope String?
clientUri String?
logoUri String?
softwareId String?
createdAt DateTime @default(now())
lastUsedAt DateTime?
authCodes OAuthAuthCode[]
grants OAuthGrant[]
@@index([createdAt])
}
/// Authorization code, hashed and single-use. Consumed with a guarded updateMany
/// so a replayed code cannot mint a second token.
model OAuthAuthCode {
id String @id @default(cuid())
codeHash String @unique
clientId 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
redirectUri String
/// RFC 8707 audience binding
resource String?
scopes String[]
codeChallenge String
codeChallengeMethod String @default("S256")
expiresAt DateTime
consumedAt DateTime?
createdAt DateTime @default(now())
client OAuthClient @relation(fields: [clientId], 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([grantId])
@@index([expiresAt])
}
/// A user's standing consent for one client. Holds the refresh token, since
/// rotation replaces it while the grant itself persists.
model OAuthGrant {
id String @id @default(cuid())
clientId 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[]
/// Bumped every time consent is re-granted after a revocation. Codes and
/// refresh tokens carry the epoch they were issued under, so anything minted
/// before a revoke is dead even if the grant row is later reactivated.
epoch Int @default(0)
revokedAt DateTime?
lastUsedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessTokens McpAccessToken[]
authCodes OAuthAuthCode[]
refreshTokens OAuthRefreshToken[]
@@unique([clientId, 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 {
id String @id @default(cuid())
userId String

View File

@@ -1,7 +1,8 @@
"use client"
import { useState } from "react"
import { Suspense, useState } from "react"
import { signIn } from "next-auth/react"
import { useSearchParams } from "next/navigation"
import Link from "next/link"
import { Beer, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
@@ -9,7 +10,49 @@ import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
/**
* Only same-origin destinations are honoured. Without this check the
* `?callbackUrl=` parameter - which anyone can put in a link - would make the
* login page an open redirect onto an attacker's site, wearing our domain.
*
* Both forms have to be accepted. A relative path is what /oauth/authorize
* builds, while the middleware's own redirect writes an absolute URL, and
* rejecting that one would quietly drop people on /dashboard instead of the
* consent screen they were sent to sign in for.
*
* A leading `//` is rejected because `//evil.com` is protocol-relative, which
* the browser resolves as absolute.
*/
function safeCallbackUrl(value: string | null): string {
if (!value) return "/dashboard"
if (value.startsWith("/")) {
return value.startsWith("//") ? "/dashboard" : value
}
try {
const target = new URL(value)
if (target.origin === window.location.origin) {
return `${target.pathname}${target.search}${target.hash}`
}
} catch {
// Not a URL at all.
}
return "/dashboard"
}
export default function LoginPage() {
// useSearchParams needs a Suspense boundary; this page prerenders statically.
return (
<Suspense fallback={null}>
<LoginForm />
</Suspense>
)
}
function LoginForm() {
const searchParams = useSearchParams()
const callbackUrl = safeCallbackUrl(searchParams.get("callbackUrl"))
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [error, setError] = useState("")
@@ -24,7 +67,7 @@ export default function LoginPage() {
const result = await signIn("credentials", {
email,
password,
callbackUrl: "/dashboard",
callbackUrl,
redirect: false,
})

View File

@@ -0,0 +1,65 @@
import { NextResponse } from "next/server"
import { mcpBaseUrl } from "@/lib/mcp/config"
import { SUPPORTED_SCOPES } from "@/lib/mcp/oauth"
/**
* RFC 8414 authorization server metadata.
*
* `issuer` must equal the base URL this document was discovered at, so it is
* derived from the same NEXTAUTH_URL everything else uses rather than hardcoded.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
function metadata() {
const base = mcpBaseUrl()
return {
issuer: base,
authorization_endpoint: `${base}/oauth/authorize`,
token_endpoint: `${base}/api/oauth/token`,
registration_endpoint: `${base}/api/oauth/register`,
revocation_endpoint: `${base}/api/oauth/revoke`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
// Claude always sends a PKCE challenge and checks that S256 is advertised
// before starting the flow. `plain` is not accepted.
code_challenge_methods_supported: ["S256"],
// Public clients only. No client secret is ever issued or stored, so there
// is none to leak from this deployment.
token_endpoint_auth_methods_supported: ["none"],
revocation_endpoint_auth_methods_supported: ["none"],
scopes_supported: SUPPORTED_SCOPES,
service_documentation: `${base}/settings`,
//
// Deliberately absent: client_id_metadata_document_supported.
//
// Claude picks CIMD only when this document advertises BOTH that flag and
// "none" in token_endpoint_auth_methods_supported; omitting it makes both
// Claude and ChatGPT fall back to dynamic registration cleanly. CIMD would
// mean fetching a client-supplied URL server-side, from a host that also
// reaches MinIO on 127.0.0.1:9000, Postgres on 5432 and the Switchboard
// gateway on the LAN. That is an SSRF pivot in exchange for nothing here;
// registration is a POST to our own endpoint with no outbound traffic.
}
}
const CORS = {
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=3600",
}
export function GET(): NextResponse {
return NextResponse.json(metadata(), { headers: CORS })
}
export function OPTIONS(): Response {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Access-Control-Max-Age": "86400",
},
})
}

View File

@@ -0,0 +1,15 @@
/**
* RFC 9728 path-inserted form of the protected resource metadata.
*
* For a resource at https://host/api/mcp, a client probes
* /.well-known/oauth-protected-resource/api/mcp before falling back to the bare
* /.well-known/oauth-protected-resource. Both are served so discovery works
* whichever a given client tries, and whether or not it read the
* WWW-Authenticate challenge that names the URL explicitly.
*/
export { GET, OPTIONS } from "../../route"
// Declared literally rather than re-exported: Next reads these statically and
// cannot follow a re-export.
export const runtime = "nodejs"
export const dynamic = "force-dynamic"

View File

@@ -0,0 +1,62 @@
import { NextResponse } from "next/server"
import { generateProtectedResourceMetadata } from "mcp-handler"
import { mcpBaseUrl, mcpResourceUrl } from "@/lib/mcp/config"
import { SUPPORTED_SCOPES } from "@/lib/mcp/oauth"
/**
* RFC 9728 protected resource metadata - how a client discovers where to
* authenticate for /api/mcp.
*
* Two constraints worth stating, because breaking either fails silently as
* "couldn't reach the MCP server":
*
* - `resource` must match the URL the user typed into their client exactly,
* which is why both it and the issuer come from NEXTAUTH_URL rather than the
* request. See src/lib/mcp/config.ts.
* - Claude reads only the FIRST entry of authorization_servers and does not
* fall back to later ones, so there is exactly one.
*
* This path sits outside /api, so it is caught by the middleware matcher and
* needs "/.well-known" in PUBLIC_ROUTES - otherwise it answers with an HTML
* redirect to /login and discovery never starts.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
/**
* `scopes_supported` is not decoration. When a client's 401 challenge carries no
* explicit scope, Claude requests exactly the scopes advertised here - so
* omitting it makes every connection fall back to the read-only default and the
* user is left wondering why the assistant cannot add a drink. The consent
* screen is what actually gates the write scopes.
*/
export function GET(): Response {
const metadata = generateProtectedResourceMetadata({
authServerUrls: [mcpBaseUrl()],
resourceUrl: mcpResourceUrl(),
additionalMetadata: {
scopes_supported: SUPPORTED_SCOPES,
resource_name: "DrinkTracker",
bearer_methods_supported: ["header"],
},
})
return NextResponse.json(metadata, {
headers: {
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=3600",
},
})
}
export function OPTIONS(): Response {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Access-Control-Max-Age": "86400",
},
})
}

109
src/app/api/mcp/route.ts Normal file
View File

@@ -0,0 +1,109 @@
import { createHash } from "crypto"
import { createMcpHandler, withMcpAuth } from "mcp-handler"
import { rateLimit } from "@/lib/rate-limit"
import { verifyMcpToken } from "@/lib/mcp/auth"
import {
MCP_SERVER_NAME,
MCP_SERVER_VERSION,
mcpBaseUrl,
} from "@/lib/mcp/config"
import { registerTools } from "@/lib/mcp/server"
/**
* The MCP endpoint.
*
* Lives under /api deliberately: the middleware matcher in src/middleware.ts
* excludes /api precisely because `authorized` answers with an HTML redirect to
* /login, and an MCP client needs a JSON 401 with a WWW-Authenticate challenge.
* Authentication here is a bearer token, never the session cookie.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource"
const baseHandler = createMcpHandler(registerTools, {
serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },
verboseLogs: process.env.NODE_ENV !== "production",
})
const authedHandler = withMcpAuth(baseHandler, verifyMcpToken, {
required: true,
resourceMetadataPath: RESOURCE_METADATA_PATH,
// Pinned rather than derived from proxy headers. See src/lib/mcp/config.ts -
// the app binds 0.0.0.0:3000 behind a reverse proxy, so a request-derived
// origin sends clients to an unreachable metadata URL.
resourceUrl: mcpBaseUrl(),
})
/**
* A wildcard origin is safe here only because this endpoint authenticates with an
* Authorization header and never a cookie. Do not add Access-Control-Allow-
* Credentials, and do not add session-cookie auth as a fallback: either one turns
* this into a CSRF hole that any website could drive on a logged-in user's behalf.
*/
const CORS_HEADERS: Record<string, string> = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers":
"Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID",
"Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate",
"Access-Control-Max-Age": "86400",
}
function withCors(response: Response): Response {
for (const [key, value] of Object.entries(CORS_HEADERS)) {
response.headers.set(key, value)
}
return response
}
/**
* Throttled on a hash of the presented credential, so it works before any
* database lookup and a malformed token cannot be used to probe for free.
*
* Deliberately not enforced inside verifyMcpToken: returning undefined there
* produces a 401, which tells the client to go and re-authenticate - the wrong
* answer to "slow down", and one that would send Claude around the OAuth loop
* repeatedly. Note src/lib/rate-limit.ts is a module-scope Map: per process and
* reset by every deploy. Correct for the single systemd process this runs as;
* under multiple workers the effective limit becomes N times looser.
*/
function throttle(request: Request): Response | null {
const bearer = request.headers
.get("authorization")
?.replace(/^Bearer\s+/i, "")
.trim()
const key = bearer
? `mcp:${createHash("sha256").update(bearer).digest("hex").slice(0, 16)}`
: "mcp:anonymous"
const { success } = rateLimit(key, 120, 60_000)
if (success) return null
return withCors(
new Response(
JSON.stringify({ error: "Too many requests. Please slow down." }),
{
status: 429,
headers: { "content-type": "application/json", "retry-after": "60" },
}
)
)
}
async function handle(request: Request): Promise<Response> {
const throttled = throttle(request)
if (throttled) return throttled
return withCors(await authedHandler(request))
}
export const GET = handle
export const POST = handle
export const DELETE = handle
export function OPTIONS(): Response {
return withCors(new Response(null, { status: 204 }))
}

View File

@@ -0,0 +1,123 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import {
buildRedirect,
validateAuthorizeRequest,
} from "@/lib/mcp/authorize-request"
import { AUTH_CODE_TTL_MS, generateAuthCode } from "@/lib/mcp/oauth"
/**
* The user's decision on the consent screen.
*
* Everything is re-validated from the query string rather than trusted from the
* request body: the body is just a carrier for the original parameters, and
* treating any of it as already-checked would let a crafted POST mint a code for
* a client and redirect the page never approved.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
const bodySchema = z.object({
decision: z.enum(["allow", "deny"]),
search: z.string().max(4096),
})
export async function POST(request: Request) {
const session = await requireUser()
if (session instanceof NextResponse) return session
const parsed = bodySchema.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return NextResponse.json({ error: "invalid_request" }, { status: 400 })
}
const search = new URLSearchParams(parsed.data.search)
const validation = await validateAuthorizeRequest(search)
if (validation.kind === "fatal") {
return NextResponse.json(
{ error: "invalid_request", error_description: validation.message },
{ status: 400 }
)
}
if (validation.kind === "redirectable") {
return NextResponse.json({
redirectTo: buildRedirect(validation.redirectUri, {
error: validation.error,
error_description: validation.description,
state: validation.state,
}),
})
}
const { params, client } = validation
const userId = session.user.id
if (parsed.data.decision === "deny") {
return NextResponse.json({
redirectTo: buildRedirect(params.redirectUri, {
error: "access_denied",
error_description: "The user declined the request.",
state: params.state,
}),
})
}
const { code, hash } = generateAuthCode()
// 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 } },
update: { scopes: params.scopes, revokedAt: null, epoch: { increment: 1 } },
create: { clientId: client.id, userId, scopes: params.scopes },
select: { id: true, epoch: true },
})
await tx.mcpAccessToken.updateMany({
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: {
codeHash: hash,
clientId: client.id,
userId,
grantId: g.id,
grantEpoch: g.epoch,
redirectUri: params.redirectUri,
resource: params.resource,
scopes: params.scopes,
codeChallenge: params.codeChallenge,
codeChallengeMethod: "S256",
expiresAt: new Date(Date.now() + AUTH_CODE_TTL_MS),
},
})
return g
})
console.log(
`[oauth] granted user=${userId} client=${client.clientId} scopes=${params.scopes.join(",")} grant=${grant.id}`
)
return NextResponse.json({
redirectTo: buildRedirect(params.redirectUri, {
code,
state: params.state,
}),
})
}

View File

@@ -0,0 +1,142 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { prisma } from "@/lib/prisma"
import { rateLimit } from "@/lib/rate-limit"
import {
generateClientId,
isRegisterableRedirectUri,
oauthError,
} from "@/lib/mcp/oauth"
/**
* RFC 7591 dynamic client registration.
*
* Unauthenticated by specification, which makes it the one endpoint on this
* deployment that a stranger can create rows through. Hence the rate limit, the
* global cap, and the pruning of registrations that never went on to be used.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
/** Beyond this many registrations in a day, something is wrong. */
const DAILY_REGISTRATION_CAP = 500
const PRUNE_AFTER_MS = 7 * 24 * 60 * 60 * 1000
const registerSchema = z.object({
client_name: z.string().min(1).max(200).optional(),
redirect_uris: z.array(z.string().min(1)).min(1).max(10),
grant_types: z.array(z.string()).optional(),
response_types: z.array(z.string()).optional(),
token_endpoint_auth_method: z.string().optional(),
scope: z.string().max(500).optional(),
client_uri: z.string().max(2048).optional(),
logo_uri: z.string().max(2048).optional(),
software_id: z.string().max(200).optional(),
})
export async function POST(request: Request) {
const forwarded = request.headers.get("x-forwarded-for")
const hops = forwarded?.split(",").map((h) => h.trim()).filter(Boolean) ?? []
// Last hop, not first: everything before it is client-supplied and can be
// forged for a fresh bucket. Same reasoning as the register route.
const ip = hops.length > 0 ? hops[hops.length - 1] : "unknown"
const rl = rateLimit(`dcr:${ip}`, 5, 60 * 60 * 1000)
if (!rl.success) {
return oauthError(
"temporarily_unavailable",
"Too many registration attempts.",
429
)
}
const body = await request.json().catch(() => null)
if (!body) return oauthError("invalid_client_metadata", "Body must be JSON.")
const parsed = registerSchema.safeParse(body)
if (!parsed.success) {
return oauthError("invalid_client_metadata", parsed.error.issues[0]?.message)
}
const data = parsed.data
// Public clients only. Accepting a confidential client would mean storing a
// secret this server has no need for and no way to protect better than the
// PKCE it already requires.
const authMethod = data.token_endpoint_auth_method ?? "none"
if (authMethod !== "none") {
return oauthError(
"invalid_client_metadata",
"This server issues public clients only; token_endpoint_auth_method must be \"none\"."
)
}
const bad = data.redirect_uris.filter((u) => !isRegisterableRedirectUri(u))
if (bad.length) {
return oauthError(
"invalid_redirect_uri",
`Redirect URIs must be https or a loopback address, with no fragment: ${bad.join(", ")}`
)
}
const since = new Date(Date.now() - 24 * 60 * 60 * 1000)
const recent = await prisma.oAuthClient.count({
where: { createdAt: { gte: since } },
})
if (recent >= DAILY_REGISTRATION_CAP) {
return oauthError(
"temporarily_unavailable",
"Registration is temporarily closed.",
503
)
}
const clientId = generateClientId()
const client = await prisma.oAuthClient.create({
data: {
clientId,
clientName: data.client_name ?? "Unnamed client",
redirectUris: data.redirect_uris,
grantTypes: data.grant_types ?? ["authorization_code", "refresh_token"],
responseTypes: data.response_types ?? ["code"],
tokenEndpointAuthMethod: "none",
scope: data.scope ?? null,
clientUri: data.client_uri ?? null,
logoUri: data.logo_uri ?? null,
softwareId: data.software_id ?? null,
},
})
pruneUnusedClients()
return NextResponse.json(
{
client_id: client.clientId,
client_id_issued_at: Math.floor(client.createdAt.getTime() / 1000),
client_name: client.clientName,
redirect_uris: client.redirectUris,
grant_types: client.grantTypes,
response_types: client.responseTypes,
token_endpoint_auth_method: "none",
...(client.scope ? { scope: client.scope } : {}),
},
{ status: 201, headers: { "Cache-Control": "no-store" } }
)
}
/**
* Registrations that never led to a grant are abandoned handshakes. Cleared
* opportunistically rather than on a schedule, because there is no scheduler.
*/
function pruneUnusedClients(): void {
prisma.oAuthClient
.deleteMany({
where: {
createdAt: { lt: new Date(Date.now() - PRUNE_AFTER_MS) },
grants: { none: {} },
},
})
.then(({ count }) => {
if (count > 0) console.log(`[oauth] pruned ${count} unused client(s)`)
})
.catch((error) => console.warn("[oauth] client prune failed:", error))
}

View File

@@ -0,0 +1,58 @@
import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { revokeGrant, sha256 } from "@/lib/mcp/oauth"
/**
* RFC 7009 token revocation.
*
* Always answers 200, even for a token that does not exist. That is the spec's
* requirement and it is also what stops this endpoint from becoming an oracle
* for guessing valid tokens.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
export async function POST(request: Request) {
const contentType = request.headers.get("content-type") ?? ""
const form = contentType.includes("application/json")
? new URLSearchParams(
Object.entries((await request.json().catch(() => ({}))) as Record<string, unknown>)
.map(([k, v]) => [k, String(v)])
)
: new URLSearchParams(await request.text())
const token = form.get("token")
const ok = NextResponse.json({}, { headers: { "Cache-Control": "no-store" } })
if (!token) return ok
const hash = sha256(token)
try {
// A refresh token identifies the whole grant, so revoking it ends the
// connection outright. Every generation is retained, so this works for any
// member of the family - previously only the newest two were recognised,
// which meant revoking an older token silently did nothing.
const refresh = await prisma.oAuthRefreshToken.findUnique({
where: { tokenHash: hash },
select: { grantId: true },
})
if (refresh) {
await revokeGrant(refresh.grantId)
return ok
}
// An access token revokes only itself; the client can still refresh. That
// matches RFC 7009's guidance that revoking an access token need not
// invalidate the refresh token.
await prisma.mcpAccessToken.updateMany({
where: { tokenHash: hash, revokedAt: null },
data: { revokedAt: new Date() },
})
} catch (error) {
// Still a 200 - the caller's intent was for the token to stop working, and
// reporting an internal failure here tells them nothing useful.
console.error("[oauth] revoke failed:", error)
}
return ok
}

View File

@@ -0,0 +1,217 @@
import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import {
GrantStateError,
OFFLINE_ACCESS,
consumeRefreshToken,
coversScopes,
issueAccessToken,
issueRefreshToken,
oauthError,
redirectUriMatches,
revokeGrant,
sha256,
verifyPkce,
} from "@/lib/mcp/oauth"
/**
* RFC 6749 token endpoint.
*
* Bodies arrive as application/x-www-form-urlencoded - required by the spec and
* what Claude sends for both the initial exchange and every refresh. JSON is
* accepted as well, since some clients send it and there is no reason to be
* strict about it.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
const NO_STORE = { "Cache-Control": "no-store", Pragma: "no-cache" }
async function readForm(request: Request): Promise<URLSearchParams> {
const contentType = request.headers.get("content-type") ?? ""
if (contentType.includes("application/json")) {
const body = await request.json().catch(() => ({}))
return new URLSearchParams(
Object.entries(body as Record<string, unknown>).map(([k, v]) => [k, String(v)])
)
}
return new URLSearchParams(await request.text())
}
export async function POST(request: Request) {
const form = await readForm(request)
const grantType = form.get("grant_type")
try {
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(
"unsupported_grant_type",
"Supported grant types are authorization_code and refresh_token."
)
}
async function exchangeCode(form: URLSearchParams) {
const code = form.get("code")
const clientId = form.get("client_id")
const redirectUri = form.get("redirect_uri")
const verifier = form.get("code_verifier")
if (!code || !clientId || !redirectUri || !verifier) {
return oauthError(
"invalid_request",
"code, client_id, redirect_uri and code_verifier are all required."
)
}
const row = await prisma.oAuthAuthCode.findUnique({
where: { codeHash: sha256(code) },
include: {
client: { select: { id: true, clientId: true, clientName: true } },
user: { select: { id: true, status: true } },
},
})
if (!row) return oauthError("invalid_grant", "Unknown or expired code.")
// Consume before verifying anything else. One guarded statement, one row
// lock: whoever wins gets count 1 and everyone else gets 0, so a replayed
// code cannot mint a second token even under concurrency. A code that fails
// verification below stays consumed, which is the intent - it has been seen.
const { count } = await prisma.oAuthAuthCode.updateMany({
where: {
codeHash: row.codeHash,
consumedAt: null,
expiresAt: { gt: new Date() },
},
data: { consumedAt: new Date() },
})
if (count !== 1) {
return oauthError("invalid_grant", "This code has already been used or has expired.")
}
if (row.client.clientId !== clientId) {
return oauthError("invalid_grant", "This code was issued to a different client.")
}
// Exact match against what was recorded at authorize time, not a fresh
// registration lookup - the pairing is what is being verified.
if (!redirectUriMatches(row.redirectUri, redirectUri)) {
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({
where: { id: row.grantId },
select: { id: true, epoch: true, scopes: true, revokedAt: true },
})
if (!grant || grant.revokedAt) {
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)) {
// A verifier that does not match means whoever is holding this code is
// probably not who the code was issued to. Burn the whole grant, not just
// the code.
await revokeGrant(grant.id)
console.warn(
`[oauth] PKCE mismatch for client=${row.client.clientId} user=${row.userId}; grant revoked`
)
return oauthError("invalid_grant", "PKCE verification failed.")
}
if (row.user.status !== "ACTIVE") {
return oauthError("invalid_grant", "This account is not active.")
}
const tokens = await issueAccessToken(grant, row.userId, row.scopes, row.client.clientName)
let refreshToken: string | undefined
if (row.scopes.includes(OFFLINE_ACCESS)) {
refreshToken = await issueRefreshToken(grant, 0)
}
console.log(
`[oauth] token issued user=${row.userId} client=${row.client.clientId} grant=${grant.id} epoch=${grant.epoch}`
)
return NextResponse.json(
{ ...tokens, ...(refreshToken ? { refresh_token: refreshToken } : {}) },
{ headers: NO_STORE }
)
}
async function refresh(form: URLSearchParams) {
const token = form.get("refresh_token")
if (!token) return oauthError("invalid_request", "refresh_token is required.")
const outcome = await consumeRefreshToken(sha256(token))
if (outcome.kind === "unknown") {
return oauthError("invalid_grant", "Unknown refresh token.")
}
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 } },
user: { select: { status: true } },
},
})
if (!grant || grant.revokedAt) {
return oauthError("invalid_grant", "This authorization was revoked.")
}
// A grant whose standing consent no longer includes offline_access must not
// keep minting refresh tokens off a credential issued when it did.
if (!grant.scopes.includes(OFFLINE_ACCESS)) {
await revokeGrant(grant.id)
return oauthError("invalid_grant", "Offline access is no longer granted.")
}
if (grant.user.status !== "ACTIVE") {
return oauthError("invalid_grant", "This account is not active.")
}
const tokens = await issueAccessToken(
grant,
grant.userId,
grant.scopes,
grant.client.clientName
)
const next = await issueRefreshToken(grant, outcome.generation + 1)
return NextResponse.json({ ...tokens, refresh_token: next }, { headers: NO_STORE })
}

View File

@@ -0,0 +1,53 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { requireUser } from "@/lib/authz"
import { promoteRecipe } from "@/lib/recipe-promotion"
/**
* Promote a saved recipe into the collection so it can be rated, or onto the
* wishlist to try later.
*
* All the logic lives in src/lib/recipe-promotion.ts, shared with the MCP tool.
*/
const bodySchema = z.object({
target: z.enum(["drink", "wishlist"]),
})
export async function POST(
request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireUser()
if (session instanceof NextResponse) return session
const parsed = bodySchema.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return NextResponse.json(
{ error: "target must be \"drink\" or \"wishlist\"" },
{ status: 400 }
)
}
const result = await promoteRecipe(
session.user.id,
params.id,
parsed.data.target
)
if (result.kind === "not_found") {
return NextResponse.json({ error: "Not found" }, { status: 404 })
}
if (result.kind === "drink") {
return NextResponse.json(
{ target: "drink", drink: result.drink, existing: result.existing },
// 200 rather than 201 when it was already linked - nothing was created.
{ status: result.existing ? 200 : 201 }
)
}
return NextResponse.json(
{ target: "wishlist", item: result.item, existing: result.existing },
{ status: result.existing ? 200 : 201 }
)
}

View File

@@ -18,7 +18,9 @@ export async function GET() {
orderBy: { createdAt: "desc" },
include: {
sourceDrink: {
select: { name: true, type: true },
// id included so the UI can link straight to the drink (and its
// rating page) for a recipe that has already been promoted.
select: { id: true, name: true, type: true },
},
},
}),

View File

@@ -0,0 +1,27 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { revokeGrant } from "@/lib/mcp/oauth"
/**
* Disconnect an app. Cascades to every access token the grant issued, so the
* connection dies on the next request rather than at the end of the current
* access token's hour.
*/
export async function DELETE(
_request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireUser()
if (session instanceof NextResponse) return session
// Scoped to the caller, 404 rather than 403 - the convention across the API.
const grant = await prisma.oAuthGrant.findFirst({
where: { id: params.id, userId: session.user.id, revokedAt: null },
select: { id: true },
})
if (!grant) return NextResponse.json({ error: "Not found" }, { status: 404 })
await revokeGrant(grant.id)
return NextResponse.json({ success: true })
}

View File

@@ -0,0 +1,32 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
/** Apps the user has connected through OAuth, for the Settings list. */
export async function GET() {
const session = await requireUser()
if (session instanceof NextResponse) return session
const grants = await prisma.oAuthGrant.findMany({
where: { userId: session.user.id, revokedAt: null },
orderBy: { createdAt: "desc" },
select: {
id: true,
scopes: true,
createdAt: true,
lastUsedAt: true,
client: { select: { clientName: true, clientUri: true } },
},
})
return NextResponse.json({
grants: grants.map((g) => ({
id: g.id,
clientName: g.client.clientName,
clientUri: g.client.clientUri,
scopes: g.scopes,
createdAt: g.createdAt,
lastUsedAt: g.lastUsedAt,
})),
})
}

View File

@@ -0,0 +1,29 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
/**
* Revoke a token. Soft, so the row survives for the audit trail; verifyMcpToken
* checks revokedAt on every request with no cache anywhere, so it takes effect
* on the next call.
*/
export async function DELETE(
_request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireUser()
if (session instanceof NextResponse) return session
// Scoped to the caller, resolving to 404 rather than 403 - the convention
// across the rest of the API.
const { count } = await prisma.mcpAccessToken.updateMany({
where: { id: params.id, userId: session.user.id, revokedAt: null },
data: { revokedAt: new Date() },
})
if (count === 0) {
return NextResponse.json({ error: "Not found" }, { status: 404 })
}
return NextResponse.json({ success: true })
}

View File

@@ -0,0 +1,107 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { generateMcpToken } from "@/lib/mcp/tokens"
import { MCP_ALL_SCOPES, MCP_READ_SCOPES, mcpResourceUrl } from "@/lib/mcp/config"
/**
* MCP access tokens.
*
* requireUser, not requireOwner: a token only ever reaches its own user's rows,
* so a member connecting their own Claude or ChatGPT is no more privileged than
* them logging into the web app.
*/
/** Enough to cover a laptop, a phone, a desktop client and some spares. */
const MAX_LIVE_TOKENS = 10
const createSchema = z.object({
name: z.string().min(1).max(100).optional(),
access: z.enum(["read", "read-write"]).default("read"),
expiresInDays: z.union([z.literal(90), z.literal(365), z.null()]).default(90),
})
export async function GET() {
const session = await requireUser()
if (session instanceof NextResponse) return session
const tokens = await prisma.mcpAccessToken.findMany({
where: { userId: session.user.id, source: "pat", revokedAt: null },
orderBy: { createdAt: "desc" },
// The secret is not selectable because it is not stored - only its hash is.
// This is the deliberate difference from /api/settings/api-keys, which
// decrypts and masks on read.
select: {
id: true,
name: true,
prefix: true,
scopes: true,
lastUsedAt: true,
expiresAt: true,
createdAt: true,
},
})
return NextResponse.json({
tokens,
serverUrl: mcpResourceUrl(),
})
}
export async function POST(request: Request) {
const session = await requireUser()
if (session instanceof NextResponse) return session
const body = await request.json().catch(() => null)
const parsed = createSchema.safeParse(body ?? {})
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid input", details: parsed.error.flatten() },
{ status: 400 }
)
}
const live = await prisma.mcpAccessToken.count({
where: { userId: session.user.id, source: "pat", revokedAt: null },
})
if (live >= MAX_LIVE_TOKENS) {
return NextResponse.json(
{
error: `You already have ${MAX_LIVE_TOKENS} active tokens. Revoke one before creating another.`,
},
{ status: 400 }
)
}
const { name, access, expiresInDays } = parsed.data
const { raw, hash, prefix } = generateMcpToken()
const token = await prisma.mcpAccessToken.create({
data: {
userId: session.user.id,
tokenHash: hash,
prefix,
name: name ?? null,
scopes: access === "read-write" ? MCP_ALL_SCOPES : MCP_READ_SCOPES,
source: "pat",
expiresAt: expiresInDays
? new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000)
: null,
},
select: {
id: true,
name: true,
prefix: true,
scopes: true,
expiresAt: true,
createdAt: true,
},
})
// The only time the secret ever leaves this process.
return NextResponse.json(
{ token: { ...token, secret: raw }, serverUrl: mcpResourceUrl() },
{ status: 201 }
)
}

View File

@@ -0,0 +1,191 @@
import { redirect } from "next/navigation"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { Beer, ShieldCheck } from "lucide-react"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { ConsentForm } from "@/components/oauth/consent-form"
import {
buildRedirect,
validateAuthorizeRequest,
} from "@/lib/mcp/authorize-request"
import {
AUTH_CODE_TTL_MS,
SCOPE_DESCRIPTIONS,
coversScopes,
generateAuthCode,
} from "@/lib/mcp/oauth"
/**
* The consent screen.
*
* Not in PUBLIC_ROUTES, so the middleware bounces an unauthenticated visitor to
* /login for us - and now that login honours ?callbackUrl they come straight
* back here afterwards. The explicit session check below is for the callbackUrl
* construction, not for access control.
*
* Deliberately outside the (app) route group: this is a credential prompt, and
* it should not be wrapped in the sidebar and bottom nav of the signed-in app.
*/
export const dynamic = "force-dynamic"
type SearchParams = Record<string, string | string[] | undefined>
function toParams(searchParams: SearchParams): URLSearchParams {
const params = new URLSearchParams()
for (const [key, value] of Object.entries(searchParams)) {
if (typeof value === "string") params.set(key, value)
else if (Array.isArray(value) && value[0]) params.set(key, value[0])
}
return params
}
export default async function AuthorizePage({
searchParams,
}: {
searchParams: SearchParams
}) {
const search = toParams(searchParams)
const validation = await validateAuthorizeRequest(search)
if (validation.kind === "fatal") {
return <ErrorCard title="This link isn't valid" detail={validation.message} />
}
if (validation.kind === "redirectable") {
redirect(
buildRedirect(validation.redirectUri, {
error: validation.error,
error_description: validation.description,
state: validation.state,
})
)
}
const { params, client } = validation
const session = await auth()
if (!session?.user?.id) {
redirect(`/login?callbackUrl=${encodeURIComponent(`/oauth/authorize?${search}`)}`)
}
// A session already implies an ACTIVE user - the jwt callback in lib/auth.ts
// returns null for anyone suspended or deleted, which clears the cookie.
const userId = session.user.id
// Already approved for these scopes? Skip the screen. This is what makes a
// re-connection after an expired refresh token silent rather than another
// round of clicking Allow.
const existing = await prisma.oAuthGrant.findUnique({
where: { clientId_userId: { clientId: client.id, userId } },
select: { id: true, epoch: true, scopes: true, revokedAt: true },
})
if (existing && !existing.revokedAt && coversScopes(existing.scopes, params.scopes)) {
// 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 }))
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="flex justify-center mb-4">
<Beer className="h-10 w-10 text-primary" />
</div>
<CardTitle className="text-xl">
Connect {client.clientName} to DrinkTracker?
</CardTitle>
<CardDescription>
Signed in as {session.user.email ?? session.user.name}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-2">
<p className="text-sm font-medium">It will be able to:</p>
<ul className="space-y-1.5">
{params.scopes.map((scope) => (
<li key={scope} className="flex gap-2 text-sm text-muted-foreground">
<ShieldCheck className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
<span>{SCOPE_DESCRIPTIONS[scope] ?? scope}</span>
</li>
))}
</ul>
</div>
{client.clientUri && (
<p className="text-xs text-muted-foreground break-all">
{client.clientUri}
</p>
)}
<p className="text-xs text-muted-foreground">
It will be sent back to <code className="break-all">{params.redirectUri}</code>.
You can disconnect it any time from Settings.
</p>
<ConsentForm search={search.toString()} />
</CardContent>
</Card>
</div>
)
}
async function createAuthCode(
clientRowId: string,
userId: string,
grant: { id: string; epoch: number },
params: {
redirectUri: string
scopes: string[]
codeChallenge: string
resource: string | null
}
): Promise<string> {
const { code, hash } = generateAuthCode()
await prisma.oAuthAuthCode.create({
data: {
codeHash: hash,
clientId: clientRowId,
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,
resource: params.resource,
scopes: params.scopes,
codeChallenge: params.codeChallenge,
codeChallengeMethod: "S256",
expiresAt: new Date(Date.now() + AUTH_CODE_TTL_MS),
},
})
return code
}
function ErrorCard({ title, detail }: { title: string; detail: string }) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<CardTitle className="text-xl">{title}</CardTitle>
<CardDescription>{detail}</CardDescription>
</CardHeader>
<CardContent>
<p className="text-center text-sm text-muted-foreground">
Nothing was connected. Try starting the connection again from the app
you were using.
</p>
</CardContent>
</Card>
</div>
)
}

View File

@@ -1,6 +1,7 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
@@ -13,6 +14,8 @@ import {
Trash2,
GlassWater,
Loader2,
Star,
Clock,
} from "lucide-react"
import { cn } from "@/lib/utils"
import type { RecipeIngredient } from "@/hooks/use-bartender"
@@ -26,15 +29,20 @@ export interface RecipeCardData {
glassware?: string | null
notes?: string | null
missingCount?: number
sourceDrink?: { name: string; type: string } | null
sourceDrink?: { id: string; name: string; type: string } | null
}
export type PromoteTarget = "drink" | "wishlist"
interface RecipeCardProps {
recipe: RecipeCardData
onSave?: (recipe: RecipeCardData) => void
onDelete?: (id: string) => void
onPromote?: (id: string, target: PromoteTarget) => void
isSaving?: boolean
isDeleting?: boolean
/** Which promotion is in flight for this card, if any. */
promoting?: PromoteTarget | null
saved?: boolean
}
@@ -42,8 +50,10 @@ export function RecipeCard({
recipe,
onSave,
onDelete,
onPromote,
isSaving,
isDeleting,
promoting,
saved,
}: RecipeCardProps) {
const [expanded, setExpanded] = useState(false)
@@ -189,6 +199,64 @@ export function RecipeCard({
<p className="text-sm text-muted-foreground">{recipe.notes}</p>
</div>
)}
{/*
A recipe is instructions; a drink is the thing you have an opinion
about. Promoting links the two rather than converting, so the recipe
stays here and also shows on the drink's page.
*/}
{saved && recipe.id && onPromote && (
<div className="flex flex-wrap gap-2 border-t pt-3">
{recipe.sourceDrink ? (
<Button asChild variant="secondary" size="sm">
<Link href={`/rate/${recipe.sourceDrink.id}`}>
<Star className="mr-1.5 h-4 w-4" />
Rate this
</Link>
</Button>
) : (
<Button
variant="secondary"
size="sm"
disabled={!!promoting}
onClick={() => onPromote(recipe.id!, "drink")}
>
{promoting === "drink" ? (
<Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
) : (
<GlassWater className="mr-1.5 h-4 w-4" />
)}
Add to my drinks
</Button>
)}
<Button
variant="outline"
size="sm"
disabled={!!promoting}
onClick={() => onPromote(recipe.id!, "wishlist")}
>
{promoting === "wishlist" ? (
<Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
) : (
<Clock className="mr-1.5 h-4 w-4" />
)}
Try later
</Button>
</div>
)}
{recipe.sourceDrink && (
<p className="text-xs text-muted-foreground">
In your drinks as{" "}
<Link
href={`/drinks/${recipe.sourceDrink.id}`}
className="text-primary underline-offset-4 hover:underline"
>
{recipe.sourceDrink.name}
</Link>
</p>
)}
</CardContent>
</Card>
)

View File

@@ -1,15 +1,27 @@
"use client"
import { Skeleton } from "@/components/ui/skeleton"
import { RecipeCard } from "./recipe-card"
import { useRecipes, useDeleteRecipe } from "@/hooks/use-bartender"
import { BookOpen } from "lucide-react"
import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { Skeleton } from "@/components/ui/skeleton"
import { RecipeCard, type PromoteTarget } from "./recipe-card"
import {
useRecipes,
useDeleteRecipe,
usePromoteRecipe,
} from "@/hooks/use-bartender"
import { BookOpen } from "lucide-react"
export function SavedRecipesTab() {
const router = useRouter()
const { data, isLoading, error } = useRecipes()
const deleteRecipe = useDeleteRecipe()
const promoteRecipe = usePromoteRecipe()
const [deletingId, setDeletingId] = useState<string | null>(null)
const [promoting, setPromoting] = useState<{ id: string; target: PromoteTarget } | null>(null)
// There is no Toaster mounted in this app, so feedback is inline.
const [notice, setNotice] = useState<string | null>(null)
const [promoteError, setPromoteError] = useState<string | null>(null)
const recipes = data?.recipes || []
@@ -23,6 +35,36 @@ export function SavedRecipesTab() {
})
}
function handlePromote(id: string, target: PromoteTarget) {
setNotice(null)
setPromoteError(null)
setPromoting({ id, target })
promoteRecipe.mutate(
{ id, target },
{
onSuccess: (result) => {
if (result.target === "drink" && result.drink) {
// Straight to the rating page - being able to rate it is the whole
// point of adding it, and the drink is otherwise unrated and easy
// to lose track of.
router.push(`/rate/${result.drink.id}`)
return
}
setNotice(
result.existing
? `${result.item?.name} is already on your wishlist.`
: `Added ${result.item?.name} to your wishlist.`
)
},
onError: (err: Error) => {
setPromoteError(err.message || "Could not add that. Please try again.")
},
onSettled: () => setPromoting(null),
}
)
}
if (isLoading) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
@@ -58,6 +100,24 @@ export function SavedRecipesTab() {
}
return (
<div className="space-y-4">
{notice && (
<div className="rounded-md bg-primary/10 p-3 text-sm">
{notice}{" "}
<Link
href="/wishlist"
className="text-primary underline-offset-4 hover:underline"
>
View wishlist
</Link>
</div>
)}
{promoteError && (
<div className="rounded-md bg-destructive/10 p-3">
<p className="text-sm text-destructive">{promoteError}</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{recipes.map((recipe) => (
<RecipeCard
@@ -73,10 +133,13 @@ export function SavedRecipesTab() {
sourceDrink: recipe.sourceDrink,
}}
onDelete={handleDelete}
onPromote={handlePromote}
isDeleting={deletingId === recipe.id}
promoting={promoting?.id === recipe.id ? promoting.target : null}
saved
/>
))}
</div>
</div>
)
}

View File

@@ -0,0 +1,71 @@
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Loader2 } from "lucide-react"
/**
* Approve or deny.
*
* The endpoint answers with JSON containing the URL to go to, and the browser
* navigates itself, rather than the POST replying with a 302 to claude.ai. The
* CSP sets `form-action 'self'`, and browsers have historically disagreed about
* whether that also constrains the redirect a form submission lands on. A
* client-side navigation sidesteps the question and gives somewhere to show an
* error if the request fails.
*/
export function ConsentForm({ search }: { search: string }) {
const [busy, setBusy] = useState<"allow" | "deny" | null>(null)
const [error, setError] = useState("")
async function decide(decision: "allow" | "deny") {
setBusy(decision)
setError("")
try {
const res = await fetch("/api/oauth/authorize", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ decision, search }),
})
const body = await res.json()
if (!res.ok || !body.redirectTo) {
setError(body.error_description ?? body.error ?? "Something went wrong.")
setBusy(null)
return
}
window.location.assign(body.redirectTo)
} catch {
setError("Could not reach the server. Please try again.")
setBusy(null)
}
}
return (
<div className="space-y-3">
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
)}
<div className="flex gap-3">
<Button
variant="outline"
className="flex-1"
disabled={busy !== null}
onClick={() => decide("deny")}
>
{busy === "deny" && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Deny
</Button>
<Button
className="flex-1"
disabled={busy !== null}
onClick={() => decide("allow")}
>
{busy === "allow" && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Allow
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,394 @@
"use client"
import { useState } from "react"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Select, SelectOption } from "@/components/ui/select"
import { Separator } from "@/components/ui/separator"
import { Check, Copy, Loader2, Plug, Trash2 } from "lucide-react"
interface McpToken {
id: string
name: string | null
prefix: string
scopes: string[]
lastUsedAt: string | null
expiresAt: string | null
createdAt: string
}
interface TokensResponse {
tokens: McpToken[]
serverUrl: string
}
interface CreatedToken extends McpToken {
secret: string
}
interface McpGrant {
id: string
clientName: string
clientUri: string | null
scopes: string[]
createdAt: string
lastUsedAt: string | null
}
const ACCESS_OPTIONS = [
{ value: "read", label: "Read only" },
{ value: "read-write", label: "Read and write" },
]
const EXPIRY_OPTIONS = [
{ value: "90", label: "90 days" },
{ value: "365", label: "1 year" },
{ value: "never", label: "Never" },
]
/**
* Connecting an AI assistant to this account.
*
* Not gated on ownership, unlike the AI Gateway card: a token only ever reaches
* its own user's rows, and it spends nothing.
*/
export function McpTokensCard() {
const queryClient = useQueryClient()
const [name, setName] = useState("")
const [access, setAccess] = useState("read")
const [expiry, setExpiry] = useState("90")
const [created, setCreated] = useState<CreatedToken | null>(null)
const [copied, setCopied] = useState<string | null>(null)
const { data, isLoading } = useQuery<TokensResponse>({
queryKey: ["mcp-tokens"],
queryFn: async () => {
const res = await fetch("/api/settings/mcp-tokens")
if (!res.ok) throw new Error("Failed to load tokens")
return res.json()
},
})
const create = useMutation({
mutationFn: async () => {
const res = await fetch("/api/settings/mcp-tokens", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
name: name.trim() || undefined,
access,
expiresInDays: expiry === "never" ? null : Number(expiry),
}),
})
const body = await res.json()
if (!res.ok) throw new Error(body.error ?? "Failed to create token")
return body as { token: CreatedToken; serverUrl: string }
},
onSuccess: (body) => {
setCreated(body.token)
setName("")
queryClient.invalidateQueries({ queryKey: ["mcp-tokens"] })
},
})
const revoke = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/settings/mcp-tokens/${id}`, {
method: "DELETE",
})
if (!res.ok) throw new Error("Failed to revoke token")
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["mcp-tokens"] })
},
})
// Apps connected through OAuth rather than a pasted token: claude.ai and
// ChatGPT arrive this way.
const { data: grantData } = useQuery<{ grants: McpGrant[] }>({
queryKey: ["mcp-grants"],
queryFn: async () => {
const res = await fetch("/api/settings/mcp-grants")
if (!res.ok) throw new Error("Failed to load connected apps")
return res.json()
},
})
const disconnect = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/settings/mcp-grants/${id}`, {
method: "DELETE",
})
if (!res.ok) throw new Error("Failed to disconnect")
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["mcp-grants"] })
queryClient.invalidateQueries({ queryKey: ["mcp-tokens"] })
},
})
const serverUrl = data?.serverUrl ?? ""
async function copy(key: string, value: string) {
await navigator.clipboard.writeText(value)
setCopied(key)
setTimeout(() => setCopied(null), 2000)
}
const connectCommand = created
? `claude mcp add --transport http drinktracker ${serverUrl} --header "Authorization: Bearer ${created.secret}" -s user`
: ""
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Plug className="h-5 w-5" />
AI assistant access
</CardTitle>
<CardDescription>
Connect Claude or ChatGPT to this account so it can read and update your
drinks, bar and recipes. Each token reaches only your own data.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{created && (
<div className="rounded-lg border border-amber-500/50 bg-amber-500/5 p-4 space-y-3">
<div className="flex items-start justify-between gap-2">
<div>
<p className="font-medium">Your new token</p>
<p className="text-sm text-muted-foreground">
Copy it now. It is stored only as a hash, so it cannot be shown
again.
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => setCreated(null)}
aria-label="Dismiss"
>
Done
</Button>
</div>
<div className="flex gap-2">
<code className="flex-1 overflow-x-auto rounded bg-muted px-3 py-2 text-xs">
{created.secret}
</code>
<Button
variant="outline"
size="sm"
onClick={() => copy("secret", created.secret)}
>
{copied === "secret" ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
<div className="space-y-1">
<p className="text-sm font-medium">Connect Claude Code</p>
<div className="flex gap-2">
<code className="flex-1 overflow-x-auto whitespace-pre rounded bg-muted px-3 py-2 text-xs">
{connectCommand}
</code>
<Button
variant="outline"
size="sm"
onClick={() => copy("cmd", connectCommand)}
>
{copied === "cmd" ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
</div>
)}
{!!grantData?.grants.length && (
<div className="space-y-2">
<p className="text-sm font-medium">Connected apps</p>
{grantData.grants.map((grant) => (
<div
key={grant.id}
className="flex items-center justify-between gap-3 rounded-lg border p-3"
>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{grant.clientName}</span>
<Badge variant="secondary">
{grant.scopes.some((s) => s.endsWith(":write"))
? "read/write"
: "read only"}
</Badge>
</div>
<p className="mt-1 text-xs text-muted-foreground">
Connected {new Date(grant.createdAt).toLocaleDateString()}
{grant.lastUsedAt
? ` · last used ${new Date(grant.lastUsedAt).toLocaleDateString()}`
: ""}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => disconnect.mutate(grant.id)}
disabled={disconnect.isPending}
>
<Trash2 className="mr-1 h-4 w-4" />
Disconnect
</Button>
</div>
))}
<Separator className="!mt-4" />
</div>
)}
<p className="text-sm font-medium">
Access tokens
<span className="ml-2 font-normal text-muted-foreground">
for clients you configure by hand, such as Claude Code
</span>
</p>
<div className="grid gap-3 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="mcp-name">Name</Label>
<Input
id="mcp-name"
placeholder="Laptop"
value={name}
maxLength={100}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="mcp-access">Access</Label>
<Select
id="mcp-access"
value={access}
onChange={(e) => setAccess(e.target.value)}
>
{ACCESS_OPTIONS.map((o) => (
<SelectOption key={o.value} value={o.value}>
{o.label}
</SelectOption>
))}
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="mcp-expiry">Expires</Label>
<Select
id="mcp-expiry"
value={expiry}
onChange={(e) => setExpiry(e.target.value)}
>
{EXPIRY_OPTIONS.map((o) => (
<SelectOption key={o.value} value={o.value}>
{o.label}
</SelectOption>
))}
</Select>
</div>
</div>
<div className="flex items-center gap-3">
<Button onClick={() => create.mutate()} disabled={create.isPending}>
{create.isPending && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Create token
</Button>
{create.isError && (
<p className="text-sm text-destructive">
{(create.error as Error).message}
</p>
)}
</div>
<div className="space-y-2">
{isLoading && (
<p className="text-sm text-muted-foreground">Loading</p>
)}
{!isLoading && !data?.tokens.length && (
<p className="text-sm text-muted-foreground">
No tokens yet. Create one to connect an assistant.
</p>
)}
{data?.tokens.map((token) => (
<div
key={token.id}
className="flex items-center justify-between gap-3 rounded-lg border p-3"
>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">
{token.name ?? "Unnamed token"}
</span>
<code className="text-xs text-muted-foreground">
dtk_{token.prefix}
</code>
<Badge variant="secondary">
{token.scopes.some((s) => s.endsWith(":write"))
? "read/write"
: "read only"}
</Badge>
<ExpiryBadge expiresAt={token.expiresAt} />
</div>
<p className="mt-1 text-xs text-muted-foreground">
{token.lastUsedAt
? `Last used ${new Date(token.lastUsedAt).toLocaleDateString()}`
: "Never used"}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => revoke.mutate(token.id)}
disabled={revoke.isPending}
>
<Trash2 className="mr-1 h-4 w-4" />
Revoke
</Button>
</div>
))}
</div>
{serverUrl && (
<p className="text-xs text-muted-foreground">
Server URL: <code>{serverUrl}</code>
</p>
)}
</CardContent>
</Card>
)
}
function ExpiryBadge({ expiresAt }: { expiresAt: string | null }) {
if (!expiresAt) return <Badge variant="outline">no expiry</Badge>
const days = Math.ceil(
(new Date(expiresAt).getTime() - Date.now()) / (24 * 60 * 60 * 1000)
)
if (days <= 0) return <Badge variant="destructive">expired</Badge>
// Flagged early enough to rotate before a client starts failing.
if (days <= 14) return <Badge variant="destructive">{days}d left</Badge>
return <Badge variant="outline">{days}d left</Badge>
}

View File

@@ -11,6 +11,7 @@ import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { Key, Trash2, Check, Loader2, Shield, Sliders } from "lucide-react"
import { BackupRestore } from "@/components/settings/backup-restore"
import { McpTokensCard } from "@/components/settings/mcp-tokens-card"
import { DeleteAccountCard } from "@/components/settings/delete-account-card"
interface ApiKeyInfo {
@@ -140,6 +141,10 @@ export function SettingsClient({ isOwner }: { isOwner: boolean }) {
</CardContent>
</Card>
{/* Available to every member: an MCP token only ever reaches its own
user's rows, and unlike the gateway key it spends nothing. */}
<McpTokensCard />
{/* Backup & Restore Section */}
<BackupRestore />

View File

@@ -21,7 +21,7 @@ export interface Recipe {
notes: string | null
createdAt: string
updatedAt: string
sourceDrink?: { name: string; type: string } | null
sourceDrink?: { id: string; name: string; type: string } | null
}
export interface SuggestedCocktail {
@@ -100,3 +100,41 @@ export function useDeleteRecipe() {
},
})
}
export interface PromotionResponse {
target: "drink" | "wishlist"
drink?: { id: string; name: string }
item?: { id: string; name: string }
/** True when it was already there - nothing new was created. */
existing: boolean
}
/**
* Adds a saved recipe to the collection (so it can be rated) or to the wishlist.
* The recipe itself is kept either way; promoting to a drink links the two.
*/
export function usePromoteRecipe() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({
id,
target,
}: {
id: string
target: "drink" | "wishlist"
}): Promise<PromotionResponse> =>
fetchWithError(`/api/recipes/${id}/promote`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ target }),
}),
onSuccess: (_data, variables) => {
// The recipe list carries the sourceDrink link, so it goes stale too.
queryClient.invalidateQueries({ queryKey: ["recipes"] })
queryClient.invalidateQueries({
queryKey: [variables.target === "drink" ? "drinks" : "wishlist"],
})
},
})
}

View File

@@ -16,6 +16,17 @@ const PUBLIC_ROUTES = [
"/invite",
"/reset",
"/share",
// OAuth discovery documents for the MCP server. These have to be readable
// without a session - an MCP client fetches them before it has any
// credential, and `authorized` would otherwise answer with an HTML redirect
// to /login, which the client cannot parse and reports as "couldn't reach
// the server". Being a prefix match, this makes any future /.well-known/*
// route public too, so put nothing there that isn't meant to be.
//
// Note /oauth/authorize is deliberately NOT here: the consent screen must
// sit behind the session, and the redirect to /login is exactly what should
// happen when a client sends an unauthenticated user to it.
"/.well-known",
]
// Email and password only. Google and GitHub were configured but never had

46
src/lib/mcp/audit.ts Normal file
View File

@@ -0,0 +1,46 @@
import { prisma } from "@/lib/prisma"
/**
* One row per MCP tool call, modelled on AiCall - same shape, same reason. Once a
* long-lived credential can write to someone's collection, "what did that token
* actually do" needs to be a query rather than a journald grep.
*
* The arguments are deliberately not recorded. They carry free-text tasting notes
* and could carry anything a user typed; the tool name plus the affected row id is
* enough to reconstruct what happened without turning the audit log into a second
* copy of the data it is auditing.
*/
export interface McpCallLog {
userId: string
tokenId?: string | null
tool: string
ok: boolean
errorCode?: string | null
recordId?: string | null
durationMs?: number | null
}
export function logMcpCall(entry: McpCallLog): void {
// Matches the existing [switchboard] convention, which deploy.sh already greps
// for when checking a release.
const status = entry.ok ? "ok" : `err=${entry.errorCode ?? "unknown"}`
console.log(
`[mcp] user=${entry.userId} tool=${entry.tool} ${status} ms=${entry.durationMs ?? "?"}`
)
// Fire and forget: an audit write must never fail the call it is auditing.
prisma.mcpAuditLog
.create({
data: {
userId: entry.userId,
tokenId: entry.tokenId ?? null,
tool: entry.tool,
ok: entry.ok,
errorCode: entry.errorCode ?? null,
recordId: entry.recordId ?? null,
durationMs: entry.durationMs ?? null,
},
})
.catch((error) => console.warn("[mcp] audit write failed:", error))
}

99
src/lib/mcp/auth.ts Normal file
View File

@@ -0,0 +1,99 @@
import type { AuthInfo } from "@modelcontextprotocol/server"
import { prisma } from "@/lib/prisma"
import { hashMcpToken, looksLikeMcpToken } from "@/lib/mcp/tokens"
/**
* The single place an MCP bearer token becomes a user.
*
* Both token sources land here: one minted by hand in Settings (source "pat") and
* one issued by the OAuth token endpoint (source "oauth") are the same row, so
* adding OAuth does not add a second verification path to keep in sync.
*/
/** Don't write lastUsedAt more often than this. */
const TOUCH_INTERVAL_MS = 5 * 60 * 1000
export interface McpCaller {
userId: string
tokenId: string
scopes: string[]
role: "OWNER" | "MEMBER"
}
export async function verifyMcpToken(
_request: Request,
bearerToken?: string
): Promise<AuthInfo | undefined> {
// Cheap shape check first - no query for a malformed header.
if (!looksLikeMcpToken(bearerToken)) return undefined
let row
try {
row = await prisma.mcpAccessToken.findUnique({
where: { tokenHash: hashMcpToken(bearerToken) },
select: {
id: true,
userId: true,
scopes: true,
source: true,
grantId: true,
expiresAt: true,
revokedAt: true,
lastUsedAt: true,
// Joined rather than queried separately: this is what makes suspension
// take effect immediately, and it is a foreign key so it costs nothing.
user: { select: { status: true, role: true } },
grant: { select: { revokedAt: true } },
},
})
} catch (error) {
// Fail closed. This is a deliberate divergence from the jwt callback in
// src/lib/auth.ts, which swallows database errors and keeps the session
// because a throw there signs out every user at once. Here the blast radius
// of a 401 is one client retrying, so there is nothing to protect against.
console.error("[mcp] token lookup failed:", error)
return undefined
}
if (!row) return undefined
if (row.revokedAt) return undefined
if (row.expiresAt && row.expiresAt.getTime() <= Date.now()) return undefined
// An OAuth token dies with the grant that issued it.
if (row.grant?.revokedAt) return undefined
// Mirrors src/lib/auth.ts, where the jwt callback returns null for a suspended
// user. Without this an MCP token would be a documented way to outlive a
// suspension - the only control an owner has over a member.
if (row.user.status !== "ACTIVE") return undefined
touchLastUsed(row.id, row.lastUsedAt)
return {
token: bearerToken,
clientId: row.source === "oauth" ? `oauth:${row.grantId}` : `pat:${row.id}`,
scopes: row.scopes,
// AuthInfo wants seconds since epoch, not a Date.
expiresAt: row.expiresAt
? Math.floor(row.expiresAt.getTime() / 1000)
: undefined,
extra: {
userId: row.userId,
tokenId: row.id,
grantId: row.grantId,
source: row.source,
role: row.user.role,
},
}
}
/**
* Fire and forget, and throttled. Awaiting a write on every tool call would add a
* round trip to every request to record something only ever read by a human
* glancing at the token list.
*/
function touchLastUsed(id: string, lastUsedAt: Date | null): void {
if (lastUsedAt && Date.now() - lastUsedAt.getTime() < TOUCH_INTERVAL_MS) return
prisma.mcpAccessToken
.update({ where: { id }, data: { lastUsedAt: new Date() } })
.catch((error) => console.warn("[mcp] lastUsedAt update failed:", error))
}

View File

@@ -0,0 +1,139 @@
import { prisma } from "@/lib/prisma"
import { mcpResourceUrl } from "@/lib/mcp/config"
import { findMatchingRedirectUri, parseScopes } from "@/lib/mcp/oauth"
/**
* Validation for an /oauth/authorize request, shared by the consent page and the
* approve endpoint so the two cannot drift.
*
* Order matters and is the whole point of the two-stage result below. Until the
* client and its redirect URI are known good there is nowhere safe to send an
* error, because an unvalidated redirect_uri is an open redirect. Only after
* both check out do errors become redirects, as RFC 6749 requires.
*/
export interface AuthorizeParams {
clientId: string
redirectUri: string
state: string | null
scopes: string[]
codeChallenge: string
resource: string | null
}
export interface ResolvedClient {
id: string
clientId: string
clientName: string
clientUri: string | null
}
export type AuthorizeValidation =
/** Nothing may be redirected. Render this on our own page. */
| { kind: "fatal"; message: string }
/** Client and redirect are trustworthy; report this back to the client. */
| {
kind: "redirectable"
error: string
description: string
redirectUri: string
state: string | null
}
| { kind: "ok"; params: AuthorizeParams; client: ResolvedClient }
export async function validateAuthorizeRequest(
search: URLSearchParams
): Promise<AuthorizeValidation> {
const clientId = search.get("client_id")
const redirectUri = search.get("redirect_uri")
if (!clientId) return { kind: "fatal", message: "Missing client_id." }
if (!redirectUri) return { kind: "fatal", message: "Missing redirect_uri." }
const client = await prisma.oAuthClient.findUnique({
where: { clientId },
select: {
id: true,
clientId: true,
clientName: true,
clientUri: true,
redirectUris: true,
},
})
if (!client) return { kind: "fatal", message: "Unknown client_id." }
// Port-agnostic for loopback, exact otherwise. Returns the registered form.
const matched = findMatchingRedirectUri(client.redirectUris, redirectUri)
if (!matched) {
return {
kind: "fatal",
message: "The redirect_uri does not match any registered for this client.",
}
}
// From here on the redirect target is trusted, so problems go back to it.
const state = search.get("state")
const fail = (error: string, description: string): AuthorizeValidation => ({
kind: "redirectable",
error,
description,
redirectUri,
state,
})
if (search.get("response_type") !== "code") {
return fail("unsupported_response_type", "Only response_type=code is supported.")
}
const codeChallenge = search.get("code_challenge")
if (!codeChallenge) {
return fail("invalid_request", "PKCE is required: code_challenge is missing.")
}
const method = search.get("code_challenge_method")
if (method !== "S256") {
return fail(
"invalid_request",
"code_challenge_method must be S256; plain is not accepted."
)
}
// RFC 8707. If a client names an audience it must be this MCP server, or a
// token minted here could be replayed somewhere it was never meant for.
const resource = search.get("resource")
if (resource && resource.replace(/\/$/, "") !== mcpResourceUrl()) {
return fail(
"invalid_target",
`Unknown resource. This server issues tokens for ${mcpResourceUrl()}.`
)
}
return {
kind: "ok",
params: {
clientId,
redirectUri,
state,
scopes: parseScopes(search.get("scope")),
codeChallenge,
resource: resource ?? null,
},
client: {
id: client.id,
clientId: client.clientId,
clientName: client.clientName,
clientUri: client.clientUri,
},
}
}
/** Builds the URL to send the user back to, preserving `state`. */
export function buildRedirect(
redirectUri: string,
params: Record<string, string | null>
): string {
const url = new URL(redirectUri)
for (const [key, value] of Object.entries(params)) {
if (value !== null) url.searchParams.set(key, value)
}
return url.toString()
}

61
src/lib/mcp/config.ts Normal file
View File

@@ -0,0 +1,61 @@
/**
* Static configuration for the MCP server.
*
* The origin is read from NEXTAUTH_URL rather than derived from the incoming
* request. `publicOrigin()` in src/lib/origin.ts explains why for links; here it
* matters more. RFC 9728 requires the `resource` field of the protected resource
* metadata to match the URL the user typed into their client byte for byte, and
* RFC 8414 requires the OAuth `issuer` to equal the origin it was discovered at.
* Deriving either from X-Forwarded-* means a proxy misconfiguration shows up as a
* silent connector failure with no useful error, so it is pinned to config instead.
*/
export const MCP_SERVER_NAME = "drinktracker"
export const MCP_SERVER_VERSION = "1.0.0"
/** Path the MCP endpoint is mounted at. Clients are given the full URL. */
export const MCP_PATH = "/api/mcp"
/**
* Scopes. Two axes, read and write, over two halves of the data:
*
* drinks:* the collection and journal - drinks, ratings, wishlist, preferences
* bar:* the inventory and what can be made from it - bar items, recipes
*
* Kept deliberately coarse. A consent screen listing eight scopes is a consent
* screen nobody reads.
*/
export const MCP_SCOPES = [
"drinks:read",
"drinks:write",
"bar:read",
"bar:write",
] as const
export type McpScope = (typeof MCP_SCOPES)[number]
/** Everything a read-only connection gets. The default when minting a token. */
export const MCP_READ_SCOPES: McpScope[] = ["drinks:read", "bar:read"]
/** Full access. */
export const MCP_ALL_SCOPES: McpScope[] = [...MCP_SCOPES]
export function isMcpScope(value: string): value is McpScope {
return (MCP_SCOPES as readonly string[]).includes(value)
}
/** Public origin, no trailing slash. */
export function mcpBaseUrl(): string {
const configured = process.env.NEXTAUTH_URL
if (configured) return configured.replace(/\/$/, "")
// Only reachable in local development, where NEXTAUTH_URL is usually unset.
return "http://localhost:3000"
}
/**
* The resource identifier for this MCP server, which is also the URL a user
* pastes into claude.ai. Must match their input exactly.
*/
export function mcpResourceUrl(): string {
return `${mcpBaseUrl()}${MCP_PATH}`
}

55
src/lib/mcp/context.ts Normal file
View File

@@ -0,0 +1,55 @@
import type { AuthInfo } from "@modelcontextprotocol/server"
import type { McpCaller } from "@/lib/mcp/auth"
import type { McpScope } from "@/lib/mcp/config"
/**
* Pulling the authenticated user out of a tool callback.
*
* In SDK v2 the verified token is at `ctx.http.authInfo` (it was `extra.authInfo`
* in v1). The context type is wide, so this narrows it in one place rather than
* casting in seventeen tool handlers.
*/
/** Thrown by the helpers below; surfaces to the client as an error tool result. */
export class McpToolError extends Error {
readonly code: string
constructor(message: string, code = "forbidden") {
super(message)
this.name = "McpToolError"
this.code = code
}
}
interface MaybeHttpContext {
http?: { authInfo?: AuthInfo }
}
export function requireMcpUser(ctx: unknown): McpCaller {
const authInfo = (ctx as MaybeHttpContext | undefined)?.http?.authInfo
const extra = authInfo?.extra
const userId = extra?.userId
const tokenId = extra?.tokenId
if (typeof userId !== "string" || typeof tokenId !== "string") {
// Unreachable in practice - withMcpAuth runs with `required: true`, so an
// unauthenticated request never reaches a tool. Kept so a future misuse of
// the handler fails loudly rather than reading someone else's rows.
throw new McpToolError("Not authenticated.", "unauthorized")
}
return {
userId,
tokenId,
scopes: authInfo?.scopes ?? [],
role: extra?.role === "OWNER" ? "OWNER" : "MEMBER",
}
}
export function requireScope(caller: McpCaller, scope: McpScope): void {
if (caller.scopes.includes(scope)) return
throw new McpToolError(
`This connection does not have the "${scope}" permission. Reconnect with a read-write token to do that.`,
"insufficient_scope"
)
}

118
src/lib/mcp/define.ts Normal file
View File

@@ -0,0 +1,118 @@
import type { CallToolResult, McpServer } from "@modelcontextprotocol/server"
import type { z } from "zod"
import type { McpCaller } from "@/lib/mcp/auth"
import type { McpScope } from "@/lib/mcp/config"
import { McpToolError, requireMcpUser, requireScope } from "@/lib/mcp/context"
import { logMcpCall } from "@/lib/mcp/audit"
import { fail } from "@/lib/mcp/render"
/**
* Registers a tool with the auth, scope, error and audit handling every tool
* needs, so seventeen handlers can be seventeen queries instead of seventeen
* copies of the same six lines.
*
* Handlers return either a CallToolResult or a `{ result, recordId }` pair - the
* recordId is what the audit row records as the row touched.
*/
export interface ToolSpec<S extends z.ZodTypeAny> {
name: string
title: string
description: string
inputSchema: S
/** Required scope. Omit only for tools that need no permission at all. */
scope?: McpScope
/** True for tools that never write. Surfaces as an MCP annotation. */
readOnly?: boolean
/** True for tools that delete data. */
destructive?: boolean
}
export interface ToolOutcome {
result: CallToolResult
recordId?: string | null
}
export type ToolHandler<S extends z.ZodTypeAny> = (
args: z.infer<S>,
caller: McpCaller
) => Promise<CallToolResult | ToolOutcome>
/**
* CallToolResult carries an index signature, so `"result" in outcome` does not
* narrow. Probe for the nested content array instead.
*/
function isToolOutcome(value: CallToolResult | ToolOutcome): value is ToolOutcome {
const nested = (value as ToolOutcome).result
return !!nested && typeof nested === "object" && Array.isArray(nested.content)
}
export function defineTool<S extends z.ZodTypeAny>(
server: McpServer,
spec: ToolSpec<S>,
handler: ToolHandler<S>
): void {
server.registerTool(
spec.name,
{
title: spec.title,
description: spec.description,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
inputSchema: spec.inputSchema as any,
annotations: {
readOnlyHint: spec.readOnly ?? false,
destructiveHint: spec.destructive ?? false,
},
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(async (args: any, ctx: unknown) => {
const started = Date.now()
let caller: McpCaller | undefined
try {
caller = requireMcpUser(ctx)
if (spec.scope) requireScope(caller, spec.scope)
const outcome = await handler(args as z.infer<S>, caller)
const normalised: ToolOutcome = isToolOutcome(outcome)
? outcome
: { result: outcome }
logMcpCall({
userId: caller.userId,
tokenId: caller.tokenId,
tool: spec.name,
ok: !normalised.result.isError,
recordId: normalised.recordId,
durationMs: Date.now() - started,
})
return normalised.result
} catch (error) {
// A throw inside a handler becomes an error tool result, not an HTTP
// status. That is the right shape mid-call: the connection is fine, this
// one operation is not, and the model can read the reason and adapt.
const isExpected = error instanceof McpToolError
if (!isExpected) console.error(`[mcp] ${spec.name} failed:`, error)
if (caller) {
logMcpCall({
userId: caller.userId,
tokenId: caller.tokenId,
tool: spec.name,
ok: false,
errorCode: isExpected ? error.code : "internal_error",
durationMs: Date.now() - started,
})
}
return fail(
isExpected
? error.message
: "Something went wrong handling that request."
)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any
)
}

347
src/lib/mcp/oauth.ts Normal file
View File

@@ -0,0 +1,347 @@
import { createHash, randomBytes, timingSafeEqual } from "crypto"
import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { generateMcpToken } from "@/lib/mcp/tokens"
import { MCP_SCOPES, type McpScope } from "@/lib/mcp/config"
/**
* OAuth 2.1 authorization server primitives.
*
* This app is both the authorization server and the resource server, and it
* serves public clients only - no client secrets are stored anywhere, so there
* is nothing here to leak. Clients authenticate at the token endpoint with PKCE,
* which Claude always sends with S256.
*/
/** Access tokens are short; the refresh token is what carries the session. */
export const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000
export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
/** Long enough for a redirect and a token call, short enough to be useless if leaked. */
export const AUTH_CODE_TTL_MS = 60 * 1000
export const OFFLINE_ACCESS = "offline_access"
/** Advertised in discovery metadata and offered on the consent screen. */
export const SUPPORTED_SCOPES: string[] = [...MCP_SCOPES, OFFLINE_ACCESS]
export const SCOPE_DESCRIPTIONS: Record<string, string> = {
"drinks:read": "See your drinks, ratings, wishlist and taste preferences",
"drinks:write": "Add, edit and delete drinks, ratings and wishlist entries",
"bar:read": "See your bar inventory and saved recipes",
"bar:write": "Add, edit and delete bar items and recipes",
[OFFLINE_ACCESS]: "Stay connected without asking you to sign in again",
}
// ─── Opaque secrets ──────────────────────────────────────────────
export function sha256(value: string): string {
return createHash("sha256").update(value).digest("hex")
}
export function generateAuthCode(): { code: string; hash: string } {
const code = randomBytes(32).toString("base64url")
return { code, hash: sha256(code) }
}
export function generateRefreshToken(): { token: string; hash: string } {
const token = randomBytes(32).toString("base64url")
return { token, hash: sha256(token) }
}
export function generateClientId(): string {
return `dtc_${randomBytes(16).toString("hex")}`
}
// ─── Scopes ──────────────────────────────────────────────────────
/**
* Narrow a requested scope string to what this server actually grants. Unknown
* scopes are dropped rather than rejected: an unrecognised scope is not an error
* per RFC 6749, and rejecting would break clients that request extras.
*/
export function parseScopes(requested: string | null | undefined): string[] {
const asked = (requested ?? "").split(/\s+/).filter(Boolean)
const granted = asked.filter((s) => SUPPORTED_SCOPES.includes(s))
// Default to read-only when nothing usable was asked for.
if (granted.filter((s) => s !== OFFLINE_ACCESS).length === 0) {
return ["drinks:read", "bar:read", ...granted.filter((s) => s === OFFLINE_ACCESS)]
}
return granted
}
/** The scopes actually stored on an access token: everything except the marker. */
export function accessScopes(scopes: string[]): McpScope[] {
return scopes.filter((s): s is McpScope =>
(MCP_SCOPES as readonly string[]).includes(s)
)
}
export function coversScopes(granted: string[], requested: string[]): boolean {
return requested.every((s) => granted.includes(s))
}
// ─── PKCE ────────────────────────────────────────────────────────
/** RFC 7636 unreserved set, 43-128 characters. */
const VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/
export function verifyPkce(verifier: string, challenge: string): boolean {
if (!VERIFIER_RE.test(verifier)) return false
const computed = createHash("sha256").update(verifier).digest("base64url")
const a = Buffer.from(computed)
const b = Buffer.from(challenge)
// Length check first: timingSafeEqual throws on a mismatch rather than
// returning false.
if (a.length !== b.length) return false
return timingSafeEqual(a, b)
}
// ─── Redirect URIs ───────────────────────────────────────────────
function isLoopback(url: URL): boolean {
return (
url.protocol === "http:" &&
(url.hostname === "localhost" ||
url.hostname === "127.0.0.1" ||
url.hostname === "[::1]" ||
url.hostname === "::1")
)
}
/**
* A redirect URI is acceptable at registration if it is https, or an RFC 8252
* loopback address. Fragments are forbidden by RFC 6749.
*/
export function isRegisterableRedirectUri(value: string): boolean {
let url: URL
try {
url = new URL(value)
} catch {
return false
}
if (url.hash) return false
return url.protocol === "https:" || isLoopback(url)
}
/**
* Matching a redirect at authorize time.
*
* Exact string equality, except for loopback addresses where the PORT ALONE is
* ignored. Claude Code registers http://localhost/callback and then redirects to
* an ephemeral port such as http://localhost:51234/callback, so exact matching
* would reject every native client. RFC 8252 section 7.3 requires the port to be
* ignored for the IP-literal form; the same is applied to localhost so Claude
* 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 {
if (registered === requested) return true
let a: URL, b: URL
try {
a = new URL(registered)
b = new URL(requested)
} catch {
return false
}
if (!isLoopback(a) || !isLoopback(b)) return false
// A fragment is never legal on a redirect URI (RFC 6749 3.1.2).
if (a.hash || b.hash) return false
// 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(
registered: string[],
requested: string
): string | null {
return registered.find((uri) => redirectUriMatches(uri, requested)) ?? null
}
// ─── Errors ──────────────────────────────────────────────────────
/**
* RFC 6749 error body. `invalid_grant` in particular is load-bearing: Claude
* keys off exactly that code to decide a refresh token is dead and it should
* restart the whole flow. Any other code leaves the connection stuck.
*/
export function oauthError(
error: string,
description?: string,
status = 400
): NextResponse {
return NextResponse.json(
{ error, ...(description ? { error_description: description } : {}) },
{ status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } }
)
}
// ─── Token issuance ──────────────────────────────────────────────
export interface IssuedTokens {
access_token: string
token_type: "Bearer"
expires_in: number
scope: 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.
*
* Two things this deliberately does NOT do:
*
* - It does not write scopes back to the grant. Token issuance is not consent,
* and treating it as such let a stale authorization code redefine what the
* user had most recently agreed to. The consent endpoint is the only writer.
* - 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(
grant: { id: string; epoch: number },
userId: string,
scopes: string[],
clientName: string
): Promise<IssuedTokens> {
const access = generateMcpToken()
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({
where: { grantId: grant.id, revokedAt: null },
data: { revokedAt: new Date() },
})
await tx.mcpAccessToken.create({
data: {
userId,
tokenHash: access.hash,
prefix: access.prefix,
name: clientName,
scopes: accessScopes(scopes),
source: "oauth",
grantId: grant.id,
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
},
})
})
return {
access_token: access.raw,
token_type: "Bearer",
expires_in: Math.floor(ACCESS_TOKEN_TTL_MS / 1000),
scope: scopes.join(" "),
}
}
/**
* Mints the next refresh token in a family, guarded on the grant's epoch for the
* same reason as above.
*/
export async function issueRefreshToken(
grant: { id: string; epoch: number },
generation: number
): 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: {
grantId: grant.id,
tokenHash: hash,
generation,
expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
},
})
})
return token
}
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> {
const now = new Date()
await prisma.$transaction([
prisma.mcpAccessToken.updateMany({
where: { grantId, revokedAt: null },
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({
where: { id: grantId },
data: { revokedAt: now },
}),
])
}

160
src/lib/mcp/render.ts Normal file
View File

@@ -0,0 +1,160 @@
import type { CallToolResult } from "@modelcontextprotocol/server"
/**
* Shaping tool output.
*
* Every result carries both `content` text and `structuredContent`. The text is
* what Claude actually reads; structuredContent is there for clients that parse
* it. No `outputSchema` is declared anywhere - declaring one makes
* structuredContent mandatory per spec and adds schema bloat to every tools/list,
* whereas returning it undeclared is allowed.
*
* Text is compact lines, never a JSON dump. The id comes first on every line so
* the model can quote it straight into the next call - every write tool takes one.
*/
/**
* claude.ai accepts about 150,000 characters per tool result. This budget is far
* lower on purpose: the model pays for every character on every subsequent turn,
* so a result worth truncating is a result worth paginating.
*/
export const MAX_TOOL_TEXT = 40_000
/** Hard ceiling on any list tool's page size. The REST API allows 100. */
export const MAX_PAGE_SIZE = 50
export const DEFAULT_PAGE_SIZE = 20
export function truncateToolText(text: string, limit = MAX_TOOL_TEXT): string {
if (text.length <= limit) return text
const cut = text.slice(0, limit)
// Don't strand a half-written line - the model may try to parse it as an id.
const lastBreak = cut.lastIndexOf("\n")
const body = lastBreak > limit * 0.8 ? cut.slice(0, lastBreak) : cut
return `${body}\n… output truncated. Narrow the search or request the next page.`
}
export function ok(
text: string,
structuredContent?: Record<string, unknown>
): CallToolResult {
return {
content: [{ type: "text", text: truncateToolText(text) }],
...(structuredContent ? { structuredContent } : {}),
}
}
export function fail(message: string): CallToolResult {
return { content: [{ type: "text", text: message }], isError: true }
}
/**
* The trailer models follow reliably. Always emitted by list tools, even on a
* single page, so "is there more" never needs a second call to answer.
*/
export function paginationTrailer(
page: number,
pageSize: number,
total: number
): string {
const totalPages = Math.max(1, Math.ceil(total / pageSize))
if (total === 0) return "no matches"
const more =
page < totalPages ? ` · pass page=${page + 1} for more` : " · end of results"
return `page ${page} of ${totalPages} · ${total} total${more}`
}
/** Joins non-empty parts with a separator, dropping blanks. */
function join(parts: (string | null | undefined)[], sep = " · "): string {
return parts.filter((p): p is string => !!p && p.length > 0).join(sep)
}
export function formatAbv(abv: number | null | undefined): string | null {
return typeof abv === "number" ? `${abv.toFixed(1)}%` : null
}
export function formatDrinkLine(d: {
id: string
name: string
type: string
subType?: string | null
brewery?: string | null
region?: string | null
abv?: number | null
avgRating?: number | null
ratingCount?: number
}): string {
const kind = d.subType ? `${d.type} / ${d.subType}` : d.type
const rating =
d.avgRating != null && d.ratingCount
? `${d.avgRating.toFixed(1)} (${d.ratingCount})`
: "unrated"
return `[${d.id}] ${d.name}${join([
kind,
d.brewery,
d.region,
formatAbv(d.abv),
rating,
])}`
}
export function formatBarItemLine(b: {
id: string
name: string
category: string
quantity: string
notes?: string | null
}): string {
return `[${b.id}] ${b.name}${join([b.category, b.quantity, b.notes])}`
}
export function formatRatingLine(r: {
id: string
score: number
wouldReorder: boolean
location?: string | null
notes?: string | null
createdAt: Date
drink?: { name: string } | null
}): string {
const when = r.createdAt.toISOString().slice(0, 10)
return `[${r.id}] ${r.drink?.name ?? "?"}${join([
`${r.score}`,
when,
r.location,
r.wouldReorder ? "would reorder" : null,
r.notes,
])}`
}
export function formatRecipeLine(r: {
id: string
title: string
missingCount: number
ingredients: { name: string; available: boolean }[]
glassware?: string | null
}): string {
const status =
r.missingCount === 0
? "can make now"
: `missing ${r.missingCount}: ${r.ingredients
.filter((i) => !i.available)
.map((i) => i.name)
.join(", ")}`
return `[${r.id}] ${r.title}${join([
`${r.ingredients.length} ingredients`,
status,
r.glassware,
])}`
}
export function formatWishlistLine(w: {
id: string
name: string
type: string
subType?: string | null
brewery?: string | null
notes?: string | null
}): string {
const kind = w.subType ? `${w.type} / ${w.subType}` : w.type
return `[${w.id}] ${w.name}${join([kind, w.brewery, w.notes])}`
}

161
src/lib/mcp/schemas.ts Normal file
View File

@@ -0,0 +1,161 @@
import { z } from "zod"
import {
barItemCreateSchema,
drinkCreateSchema,
drinkUpdateSchema,
ratingCreateSchema,
ratingUpdateSchema,
recipeCreateSchema,
wishlistCreateSchema,
} from "@/lib/validators"
import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from "@/lib/mcp/render"
/**
* Tool input schemas.
*
* Derived from src/lib/validators.ts wherever one exists, so an MCP write and a
* write from the web app cannot drift apart in what they accept. SDK v2 takes a
* full Standard Schema (a `z.object(...)`), not a raw shape, and this project is
* already on zod 4 - so these drop straight in as `inputSchema`.
*
* `imageUrl` is omitted from every one of them. The image route is session-cookie
* gated with per-user key prefixes, so a bearer holder cannot fetch the bytes
* anyway, and a model has no way to produce a valid /minio-images/ path. Letting
* it write arbitrary URLs into a field the app renders in <img> would be stored
* content risk for no benefit.
*/
const DRINK_TYPES = ["BEER", "WINE", "COCKTAIL", "SPIRIT", "OTHER"] as const
const idField = z.string().min(1).describe("The id from a previous list result")
const pageFields = {
page: z.number().int().min(1).default(1).describe("1-based page number"),
limit: z
.number()
.int()
.min(1)
.max(MAX_PAGE_SIZE)
.default(DEFAULT_PAGE_SIZE)
.describe(`Results per page (max ${MAX_PAGE_SIZE})`),
}
// ─── Drinks ──────────────────────────────────────────────────────
export const listDrinksSchema = z.object({
search: z
.string()
.max(200)
.optional()
.describe("Matches name, brewery, sub-type or region, case-insensitively"),
type: z.enum(DRINK_TYPES).optional().describe("Filter to one kind of drink"),
sort: z
.enum(["recent", "name", "rating"])
.default("recent")
.describe("Order of results"),
...pageFields,
})
export const getDrinkSchema = z.object({ id: idField })
export const createDrinkSchema = drinkCreateSchema.omit({ imageUrl: true })
export const updateDrinkSchema = drinkUpdateSchema
.omit({ imageUrl: true })
.extend({ id: idField })
export const deleteDrinkSchema = z.object({ id: idField })
// ─── Ratings ─────────────────────────────────────────────────────
export const listRatingsSchema = z.object({
drinkId: z.string().optional().describe("Only ratings for this drink"),
sort: z.enum(["recent", "score-high", "score-low"]).default("recent"),
...pageFields,
})
export const rateDrinkSchema = ratingCreateSchema
export const updateRatingSchema = ratingUpdateSchema.extend({ id: idField })
// ─── Bar ─────────────────────────────────────────────────────────
export const listBarItemsSchema = z.object({
category: z
.enum(["SPIRITS", "LIQUEURS", "MIXERS", "BITTERS", "GARNISHES", "TOOLS"])
.optional(),
includeEmpty: z
.boolean()
.default(true)
.describe("Set false to hide bottles marked EMPTY"),
})
/**
* One tool for add and update. "I bought gin" and "I finished the gin" are the
* same gesture to a model, and forcing it to choose between two tools it cannot
* distinguish without a prior lookup just costs a round trip.
*/
export const upsertBarItemSchema = barItemCreateSchema
.omit({ imageUrl: true })
.extend({
id: z
.string()
.optional()
.describe("Omit to add a new bottle; pass an existing id to update it"),
})
export const deleteBarItemSchema = z.object({ id: idField })
// ─── Recipes ─────────────────────────────────────────────────────
export const listRecipesSchema = z.object({
makeableOnly: z
.boolean()
.default(false)
.describe("Only recipes where every ingredient is currently in the bar"),
search: z.string().max(200).optional().describe("Matches the recipe title"),
})
export const saveRecipeSchema = recipeCreateSchema
export const deleteRecipeSchema = z.object({ id: idField })
/**
* One tool with a target rather than two tools. The tool list is already at the
* point where selection quality starts to suffer, and "add it to my drinks" and
* "add it to try later" are the same gesture with a different destination.
*/
export const promoteRecipeSchema = z.object({
id: idField,
target: z
.enum(["drink", "wishlist"])
.describe(
"\"drink\" adds it to the collection so it can be rated; \"wishlist\" notes it to try later"
),
})
// ─── Wishlist ────────────────────────────────────────────────────
export const listWishlistSchema = z.object({})
// `source` is set by the server to "mcp" so wishlist entries added this way are
// attributable, the same way the scan and ai_search paths tag their own.
export const addWishlistItemSchema = wishlistCreateSchema.omit({ source: true })
export const removeWishlistItemSchema = z.object({ id: idField })
export const promoteWishlistItemSchema = z.object({ id: idField })
// ─── Meta ────────────────────────────────────────────────────────
export const emptySchema = z.object({})
// ─── ChatGPT deep-research compatibility ─────────────────────────
export const chatgptSearchSchema = z.object({
query: z.string().min(1).max(200),
})
export const chatgptFetchSchema = z.object({
id: idField,
})

38
src/lib/mcp/server.ts Normal file
View File

@@ -0,0 +1,38 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { registerBarTools } from "@/lib/mcp/tools/bar"
import { registerChatGptTools } from "@/lib/mcp/tools/chatgpt"
import { registerDrinkTools } from "@/lib/mcp/tools/drinks"
import { registerMetaTools } from "@/lib/mcp/tools/meta"
import { registerRecipeTools } from "@/lib/mcp/tools/recipes"
import { registerWishlistTools } from "@/lib/mcp/tools/wishlist"
/**
* Builds the tool surface.
*
* Deliberately excluded: everything that reaches the Switchboard gateway (menu
* scanning, bartender suggestions, recommendations, AI search, photo identify,
* barcode lookup). Claude and ChatGPT are language models already - they can
* reason about a bar inventory without the app paying to do it a second time,
* and a remote client looping an expensive vision call is not a failure mode
* worth having. Also excluded: account deletion, backup restore, gateway key
* management, everything under /api/admin, and shared-list creation, which mints
* a public internet URL and should stay a deliberate human act.
*
* A note on scopes: createMcpHandler's initializer runs without a request, so a
* stateless handler cannot vary the registered tool list per token. Every tool is
* always listed; a write tool called with a read-only token returns an error
* result. Slightly wasteful in listing tokens, but honest about what exists.
*/
export function registerTools(server: McpServer): void {
registerDrinkTools(server)
registerBarTools(server)
registerRecipeTools(server)
registerWishlistTools(server)
registerMetaTools(server)
// Only ChatGPT's deep-research mode needs these, and their generic names cost
// tool-selection clarity elsewhere. Set MCP_CHATGPT_TOOLS=0 to drop them.
if (process.env.MCP_CHATGPT_TOOLS !== "0") {
registerChatGptTools(server)
}
}

50
src/lib/mcp/tokens.ts Normal file
View File

@@ -0,0 +1,50 @@
import { createHash, randomBytes } from "crypto"
/**
* MCP bearer tokens.
*
* Stored as a SHA-256 hash, unlike Invite.token and PasswordReset.token which are
* plaintext. Those are single-use and short-lived and the worst case is one
* unwanted signup; this one is long-lived and grants read/write over a user's
* whole collection, and the nightly pg_dump keeps 14 days of history.
*
* SHA-256 rather than bcrypt: the secret is already 256 bits of CSPRNG output, so
* there is nothing to slow an attacker down, and a bcrypt column cannot be indexed
* - verification would become a full table scan on every single MCP request.
* Not `encrypt()` from src/lib/encryption.ts either: that is reversible AES, which
* is right for an outbound key you must replay to a gateway and wrong for an
* inbound credential you only ever compare.
*/
export const MCP_TOKEN_PREFIX = "dtk_"
/** 32 random bytes as base64url is always 43 characters. */
const TOKEN_RE = /^dtk_[A-Za-z0-9_-]{43}$/
export interface GeneratedToken {
/** The full secret. Shown to the user once and never stored. */
raw: string
/** SHA-256 hex of `raw`. This is what goes in the database. */
hash: string
/** First 8 characters of the random part, so the UI can tell two tokens apart. */
prefix: string
}
export function generateMcpToken(): GeneratedToken {
const secret = randomBytes(32).toString("base64url")
const raw = `${MCP_TOKEN_PREFIX}${secret}`
return { raw, hash: hashMcpToken(raw), prefix: secret.slice(0, 8) }
}
export function hashMcpToken(raw: string): string {
return createHash("sha256").update(raw).digest("hex")
}
/**
* Shape check before any database round trip, the same guard `isValidInviteToken`
* applies in src/lib/invites.ts. A garbage Authorization header - a stale cookie,
* a scanner, a client sending the wrong credential - should cost zero queries.
*/
export function looksLikeMcpToken(raw: string | undefined | null): raw is string {
return typeof raw === "string" && TOKEN_RE.test(raw)
}

118
src/lib/mcp/tools/bar.ts Normal file
View File

@@ -0,0 +1,118 @@
import type { McpServer } from "@modelcontextprotocol/server"
import type { Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
import { defineTool } from "@/lib/mcp/define"
import { McpToolError } from "@/lib/mcp/context"
import {
deleteBarItemSchema,
listBarItemsSchema,
upsertBarItemSchema,
} from "@/lib/mcp/schemas"
import { formatBarItemLine, ok } from "@/lib/mcp/render"
/** Bar inventory - the bottles on hand, which is what recipe availability is computed from. */
export function registerBarTools(server: McpServer): void {
defineTool(
server,
{
name: "list_bar_items",
title: "List bar inventory",
description:
"Everything in the user's home bar, grouped by category, with how much is left of each. Use this to answer what they have on hand; use list_recipes when the question is what they can make.",
inputSchema: listBarItemsSchema,
scope: "bar:read",
readOnly: true,
},
async ({ category, includeEmpty }, caller) => {
const where: Prisma.BarItemWhereInput = { userId: caller.userId }
if (category) where.category = category
if (!includeEmpty) where.quantity = { not: "EMPTY" }
const items = await prisma.barItem.findMany({
where,
orderBy: [{ category: "asc" }, { name: "asc" }],
})
const text = items.length
? [...items.map(formatBarItemLine), `${items.length} items`].join("\n")
: "The bar is empty."
return ok(text, {
items: items.map((i) => ({
id: i.id,
name: i.name,
category: i.category,
quantity: i.quantity,
notes: i.notes,
hasImage: !!i.imageUrl,
})),
total: items.length,
})
}
)
defineTool(
server,
{
name: "upsert_bar_item",
title: "Add or update a bottle",
description:
"Add a bottle to the bar, or update one that is already there. Omit id to add; pass the id from list_bar_items to update. Set quantity to EMPTY when something runs out rather than deleting it.",
inputSchema: upsertBarItemSchema,
scope: "bar:write",
},
async ({ id, ...fields }, caller) => {
if (id) {
const existing = await prisma.barItem.findFirst({
where: { id, userId: caller.userId },
select: { id: true },
})
if (!existing)
throw new McpToolError("No bar item with that id.", "not_found")
const item = await prisma.barItem.update({ where: { id }, data: fields })
return {
result: ok(`Updated ${formatBarItemLine(item)}`, { id: item.id }),
recordId: item.id,
}
}
const item = await prisma.barItem.create({
data: { ...fields, userId: caller.userId },
})
return {
result: ok(`Added ${formatBarItemLine(item)}`, { id: item.id }),
recordId: item.id,
}
}
)
defineTool(
server,
{
name: "delete_bar_item",
title: "Remove a bottle",
description:
"Permanently remove a bottle from the bar. To record that something ran out but is usually stocked, set its quantity to EMPTY with upsert_bar_item instead.",
inputSchema: deleteBarItemSchema,
scope: "bar:write",
destructive: true,
},
async ({ id }, caller) => {
const item = await prisma.barItem.findFirst({
where: { id, userId: caller.userId },
select: { id: true, name: true, imageUrl: true },
})
if (!item) throw new McpToolError("No bar item with that id.", "not_found")
await prisma.barItem.delete({ where: { id } })
await deleteImagesByUrl([item.imageUrl])
return {
result: ok(`Removed ${item.name} from the bar.`, { id: item.id }),
recordId: item.id,
}
}
)
}

View File

@@ -0,0 +1,130 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { prisma } from "@/lib/prisma"
import { defineTool } from "@/lib/mcp/define"
import { McpToolError } from "@/lib/mcp/context"
import { chatgptFetchSchema, chatgptSearchSchema } from "@/lib/mcp/schemas"
import { mcpBaseUrl } from "@/lib/mcp/config"
import { ok } from "@/lib/mcp/render"
/**
* ChatGPT deep-research compatibility.
*
* That mode requires two tools named exactly `search` and `fetch` returning a
* specific shape. They are not needed for ordinary connectors, and their generic
* names can muddy tool selection when several connectors are attached at once -
* hence the aggressively specific descriptions, and the MCP_CHATGPT_TOOLS escape
* hatch in server.ts for a claude.ai-only deployment.
*/
export function registerChatGptTools(server: McpServer): void {
defineTool(
server,
{
name: "search",
title: "Search the drink collection",
description:
"Search THIS USER'S TRACKED DRINK COLLECTION in DrinkTracker - beers, wines, spirits and cocktails they have personally logged, plus their bar inventory and saved recipes. Not a web search. Returns ids for the fetch tool.",
inputSchema: chatgptSearchSchema,
scope: "drinks:read",
readOnly: true,
},
async ({ query }, caller) => {
const drinks = await prisma.drink.findMany({
where: {
userId: caller.userId,
OR: [
{ name: { contains: query, mode: "insensitive" } },
{ brewery: { contains: query, mode: "insensitive" } },
{ subType: { contains: query, mode: "insensitive" } },
{ region: { contains: query, mode: "insensitive" } },
],
},
take: 20,
orderBy: { createdAt: "desc" },
include: { ratings: { select: { score: true } } },
})
const results = drinks.map((d) => {
const scores = d.ratings.map((r) => r.score)
const avg = scores.length
? (scores.reduce((s, n) => s + n, 0) / scores.length).toFixed(1)
: null
return {
id: d.id,
title: d.name,
url: `${mcpBaseUrl()}/drinks/${d.id}`,
text: [
d.type,
d.subType,
d.brewery,
d.region,
typeof d.abv === "number" ? `${d.abv}% ABV` : null,
avg ? `rated ${avg}/5` : "unrated",
d.description,
]
.filter(Boolean)
.join(" · "),
}
})
return ok(
results.length
? results.map((r) => `[${r.id}] ${r.title}${r.text}`).join("\n")
: "No matching drinks.",
{ results }
)
}
)
defineTool(
server,
{
name: "fetch",
title: "Fetch a drink record",
description:
"Retrieve the full DrinkTracker record for one drink by the id returned from the search tool, including every rating the user left for it.",
inputSchema: chatgptFetchSchema,
scope: "drinks:read",
readOnly: true,
},
async ({ id }, caller) => {
const drink = await prisma.drink.findFirst({
where: { id, userId: caller.userId },
include: { ratings: { orderBy: { createdAt: "desc" } } },
})
if (!drink) throw new McpToolError("No drink with that id.", "not_found")
const body = [
`${drink.name} (${drink.type}${drink.subType ? ` / ${drink.subType}` : ""})`,
drink.brewery ? `Producer: ${drink.brewery}` : null,
drink.region ? `Region: ${drink.region}` : null,
typeof drink.abv === "number" ? `ABV: ${drink.abv}%` : null,
drink.description,
drink.ratings.length
? `Ratings:\n${drink.ratings
.map(
(r) =>
`- ${r.score}/5 on ${r.createdAt.toISOString().slice(0, 10)}${
r.location ? ` at ${r.location}` : ""
}${r.notes ? `: ${r.notes}` : ""}`
)
.join("\n")}`
: "No ratings recorded.",
]
.filter(Boolean)
.join("\n")
return ok(body, {
id: drink.id,
title: drink.name,
text: body,
url: `${mcpBaseUrl()}/drinks/${drink.id}`,
metadata: {
type: drink.type,
brewery: drink.brewery,
abv: drink.abv,
ratingCount: drink.ratings.length,
},
})
}
)
}

455
src/lib/mcp/tools/drinks.ts Normal file
View File

@@ -0,0 +1,455 @@
import type { McpServer } from "@modelcontextprotocol/server"
import type { Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
import { deleteImagesByUrl } from "@/lib/images"
import { defineTool } from "@/lib/mcp/define"
import { McpToolError } from "@/lib/mcp/context"
import {
createDrinkSchema,
deleteDrinkSchema,
emptySchema,
getDrinkSchema,
listDrinksSchema,
listRatingsSchema,
rateDrinkSchema,
updateDrinkSchema,
updateRatingSchema,
} from "@/lib/mcp/schemas"
import {
formatDrinkLine,
formatRatingLine,
ok,
paginationTrailer,
} from "@/lib/mcp/render"
/**
* Drinks and ratings - the collection and the journal.
*
* Ownership is always `findFirst({ id, userId })` resolving to "not found",
* rather than the 404/403 split some REST routes use. A 403 confirms that a row
* exists and belongs to someone else, which is information this surface has no
* reason to hand out.
*/
export function registerDrinkTools(server: McpServer): void {
defineTool(
server,
{
name: "list_drinks",
title: "List drinks",
description:
"Search and page through the connected user's tracked drinks, each with its average rating. Use this to answer questions about what they have tried. Returns ids usable with get_drink, update_drink, rate_drink and delete_drink.",
inputSchema: listDrinksSchema,
scope: "drinks:read",
readOnly: true,
},
async ({ search, type, sort, page, limit }, caller) => {
const where: Prisma.DrinkWhereInput = { userId: caller.userId }
if (search) {
where.OR = [
{ name: { contains: search, mode: "insensitive" } },
{ brewery: { contains: search, mode: "insensitive" } },
{ subType: { contains: search, mode: "insensitive" } },
{ region: { contains: search, mode: "insensitive" } },
]
}
if (type) where.type = type
let orderBy: Prisma.DrinkOrderByWithRelationInput = { createdAt: "desc" }
if (sort === "name") orderBy = { name: "asc" }
else if (sort === "rating") orderBy = { ratings: { _count: "desc" } }
const [drinks, total] = await Promise.all([
prisma.drink.findMany({
where,
include: { ratings: { select: { score: true } } },
orderBy,
skip: (page - 1) * limit,
take: limit,
}),
prisma.drink.count({ where }),
])
const rows = drinks.map((d) => {
const scores = d.ratings.map((r) => r.score)
return {
id: d.id,
name: d.name,
type: d.type,
subType: d.subType,
brewery: d.brewery,
region: d.region,
abv: d.abv,
hasImage: !!d.imageUrl,
avgRating: scores.length
? scores.reduce((sum, s) => sum + s, 0) / scores.length
: null,
ratingCount: scores.length,
}
})
// Prisma orders by rating count, not average, so the average sort is
// finished in memory - same as GET /api/drinks.
if (sort === "rating") {
rows.sort((a, b) => {
if (a.avgRating === null && b.avgRating === null) return 0
if (a.avgRating === null) return 1
if (b.avgRating === null) return -1
return b.avgRating - a.avgRating
})
}
const text = [
...rows.map(formatDrinkLine),
paginationTrailer(page, limit, total),
].join("\n")
return ok(text, { drinks: rows, page, limit, total })
}
)
defineTool(
server,
{
name: "get_drink",
title: "Get a drink",
description:
"Full detail for one drink including its description and every rating the user has left for it. Prefer list_drinks when looking across the collection.",
inputSchema: getDrinkSchema,
scope: "drinks:read",
readOnly: true,
},
async ({ id }, caller) => {
const drink = await prisma.drink.findFirst({
where: { id, userId: caller.userId },
include: { ratings: { orderBy: { createdAt: "desc" } } },
})
if (!drink) throw new McpToolError("No drink with that id.", "not_found")
const scores = drink.ratings.map((r) => r.score)
const avgRating = scores.length
? scores.reduce((sum, s) => sum + s, 0) / scores.length
: null
const header = formatDrinkLine({ ...drink, avgRating, ratingCount: scores.length })
const lines = [header]
if (drink.description) lines.push(`description: ${drink.description}`)
if (drink.imageUrl) lines.push("has a photo (not retrievable over MCP)")
if (drink.ratings.length) {
lines.push("ratings:")
lines.push(
...drink.ratings.map((r) => ` ${formatRatingLine({ ...r, drink })}`)
)
} else {
lines.push("no ratings yet")
}
return ok(lines.join("\n"), {
drink: {
id: drink.id,
name: drink.name,
type: drink.type,
subType: drink.subType,
brewery: drink.brewery,
region: drink.region,
abv: drink.abv,
description: drink.description,
hasImage: !!drink.imageUrl,
avgRating,
ratingCount: scores.length,
ratings: drink.ratings.map((r) => ({
id: r.id,
score: r.score,
notes: r.notes,
wouldReorder: r.wouldReorder,
location: r.location,
createdAt: r.createdAt.toISOString(),
})),
},
})
}
)
defineTool(
server,
{
name: "create_drink",
title: "Add a drink",
description:
"Add a drink to the user's collection. Use rate_drink afterwards to record what they thought of it.",
inputSchema: createDrinkSchema,
scope: "drinks:write",
},
async (input, caller) => {
const drink = await prisma.drink.create({
data: { ...input, userId: caller.userId },
})
return {
result: ok(`Added ${formatDrinkLine(drink)}`, { id: drink.id }),
recordId: drink.id,
}
}
)
defineTool(
server,
{
name: "update_drink",
title: "Update a drink",
description:
"Change fields on an existing drink. Only the fields you pass are modified.",
inputSchema: updateDrinkSchema,
scope: "drinks:write",
},
async ({ id, ...changes }, caller) => {
const existing = await prisma.drink.findFirst({
where: { id, userId: caller.userId },
select: { id: true },
})
if (!existing) throw new McpToolError("No drink with that id.", "not_found")
const drink = await prisma.drink.update({ where: { id }, data: changes })
return {
result: ok(`Updated ${formatDrinkLine(drink)}`, { id: drink.id }),
recordId: drink.id,
}
}
)
defineTool(
server,
{
name: "delete_drink",
title: "Delete a drink",
description:
"Permanently remove a drink and every rating attached to it. This cannot be undone.",
inputSchema: deleteDrinkSchema,
scope: "drinks:write",
destructive: true,
},
async ({ id }, caller) => {
const drink = await prisma.drink.findFirst({
where: { id, userId: caller.userId },
select: { id: true, name: true, imageUrl: true },
})
if (!drink) throw new McpToolError("No drink with that id.", "not_found")
await prisma.drink.delete({ where: { id } })
// Best effort and after the row is gone, matching DELETE /api/drinks/[id].
await deleteImagesByUrl([drink.imageUrl])
return {
result: ok(`Deleted ${drink.name}.`, { id: drink.id }),
recordId: drink.id,
}
}
)
defineTool(
server,
{
name: "list_ratings",
title: "List ratings",
description:
"The user's ratings, most recent first by default. Pass drinkId to see the history for one drink.",
inputSchema: listRatingsSchema,
scope: "drinks:read",
readOnly: true,
},
async ({ drinkId, sort, page, limit }, caller) => {
const where: Prisma.RatingWhereInput = { userId: caller.userId }
if (drinkId) where.drinkId = drinkId
const orderBy: Prisma.RatingOrderByWithRelationInput =
sort === "score-high"
? { score: "desc" }
: sort === "score-low"
? { score: "asc" }
: { createdAt: "desc" }
const [ratings, total] = await Promise.all([
prisma.rating.findMany({
where,
orderBy,
skip: (page - 1) * limit,
take: limit,
include: { drink: { select: { name: true } } },
}),
prisma.rating.count({ where }),
])
const text = [
...ratings.map(formatRatingLine),
paginationTrailer(page, limit, total),
].join("\n")
return ok(text, {
ratings: ratings.map((r) => ({
id: r.id,
drinkId: r.drinkId,
drinkName: r.drink.name,
score: r.score,
notes: r.notes,
wouldReorder: r.wouldReorder,
location: r.location,
createdAt: r.createdAt.toISOString(),
})),
page,
limit,
total,
})
}
)
defineTool(
server,
{
name: "rate_drink",
title: "Rate a drink",
description:
"Record a 1-5 star rating for a drink the user already has, optionally with tasting notes and where they had it.",
inputSchema: rateDrinkSchema,
scope: "drinks:write",
},
async (input, caller) => {
// The drink id arrives from the model. Without this the rating would be
// written against someone else's drink - the same check POST /api/ratings
// performs for the web app.
const drink = await prisma.drink.findFirst({
where: { id: input.drinkId, userId: caller.userId },
select: { id: true, name: true },
})
if (!drink) throw new McpToolError("No drink with that id.", "not_found")
const rating = await prisma.rating.create({
data: { ...input, userId: caller.userId },
})
return {
result: ok(`Rated ${drink.name} ${rating.score}/5.`, { id: rating.id }),
recordId: rating.id,
}
}
)
defineTool(
server,
{
name: "update_rating",
title: "Update a rating",
description:
"Change the score, notes, location or would-reorder flag on an existing rating.",
inputSchema: updateRatingSchema,
scope: "drinks:write",
},
async ({ id, ...changes }, caller) => {
const existing = await prisma.rating.findFirst({
where: { id, userId: caller.userId },
select: { id: true },
})
if (!existing) throw new McpToolError("No rating with that id.", "not_found")
const rating = await prisma.rating.update({
where: { id },
data: changes,
include: { drink: { select: { name: true } } },
})
return {
result: ok(
`Updated the rating for ${rating.drink.name} (now ${rating.score}/5).`,
{ id: rating.id }
),
recordId: rating.id,
}
}
)
defineTool(
server,
{
name: "get_collection_stats",
title: "Collection summary",
description:
"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,
scope: "drinks:read",
readOnly: true,
},
async (_args, caller) => {
const userId = caller.userId
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] =
await Promise.all([
prisma.drink.groupBy({
by: ["type"],
where: { userId },
_count: { _all: true },
}),
prisma.drink.count({ where: { userId } }),
prisma.rating.aggregate({
where: { userId },
_avg: { score: true },
_count: { _all: true },
}),
prisma.rating.count({
where: { userId, createdAt: { gte: thirtyDaysAgo } },
}),
canReadBar
? prisma.barItem.count({ where: { userId, quantity: { not: "EMPTY" } } })
: Promise.resolve(null),
canReadBar
? prisma.recipe.count({ where: { userId } })
: Promise.resolve(null),
prisma.rating.findMany({
where: { userId },
orderBy: [{ score: "desc" }, { createdAt: "desc" }],
take: 5,
include: { drink: { select: { name: true, type: true } } },
}),
])
const typeLines = byType
.map((t) => ` ${t.type}: ${t._count._all}`)
.join("\n")
const avg = ratingAgg._avg.score
const topLines = top
.map((r) => `${r.score} ${r.drink.name} (${r.drink.type})`)
.join("\n")
const text = [
`${drinkCount} drinks tracked`,
typeLines || " (none)",
`${ratingAgg._count._all} ratings, average ${avg ? avg.toFixed(2) : "n/a"}`,
`${recentRatings} ratings in the last 30 days`,
canReadBar
? `${barCount} bottles in the bar, ${recipeCount} saved recipes`
: "",
top.length ? "top rated:" : "",
topLines,
]
.filter(Boolean)
.join("\n")
return ok(text, {
drinkCount,
byType: Object.fromEntries(byType.map((t) => [t.type, t._count._all])),
ratingCount: ratingAgg._count._all,
averageScore: avg,
ratingsLast30Days: recentRatings,
...(canReadBar ? { barItemCount: barCount, recipeCount } : {}),
topRated: top.map((r) => ({
drinkName: r.drink.name,
type: r.drink.type,
score: r.score,
})),
})
}
)
}

73
src/lib/mcp/tools/meta.ts Normal file
View File

@@ -0,0 +1,73 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { prisma } from "@/lib/prisma"
import { defineTool } from "@/lib/mcp/define"
import { emptySchema } from "@/lib/mcp/schemas"
import { ok } from "@/lib/mcp/render"
/**
* Taste context.
*
* Read-only on purpose. The flavour profile is generated by the app's own AI
* pipeline, and MCP deliberately exposes no tool that spends gateway budget -
* a remote client can read the profile, but cannot make the app pay to
* regenerate it.
*/
export function registerMetaTools(server: McpServer): void {
defineTool(
server,
{
name: "get_preferences",
title: "Get taste preferences",
description:
"The user's stated style preferences and ABV range, plus the flavour profile the app generated from their ratings. Read this before recommending anything so suggestions match their actual taste.",
inputSchema: emptySchema,
scope: "drinks:read",
readOnly: true,
},
async (_args, caller) => {
const [prefs, profile, ratingCount] = await Promise.all([
prisma.userPreference.findUnique({ where: { userId: caller.userId } }),
prisma.flavorProfile.findUnique({ where: { userId: caller.userId } }),
prisma.rating.count({ where: { userId: caller.userId } }),
])
const lines: string[] = []
if (prefs?.preferredStyles.length)
lines.push(`prefers: ${prefs.preferredStyles.join(", ")}`)
if (prefs?.avoidedStyles.length)
lines.push(`avoids: ${prefs.avoidedStyles.join(", ")}`)
if (prefs?.minAbv != null || prefs?.maxAbv != null) {
lines.push(
`abv range: ${prefs.minAbv ?? "any"} to ${prefs.maxAbv ?? "any"}`
)
}
if (profile) {
const stale = profile.ratingCount < ratingCount
lines.push("")
lines.push(
`flavour profile (generated from ${profile.ratingCount} ratings${
stale ? `, now ${ratingCount} - somewhat out of date` : ""
}):`
)
lines.push(profile.profileText)
} else {
lines.push("")
lines.push(
`No flavour profile yet - the app generates one from rating history (${ratingCount} ratings so far).`
)
}
return ok(lines.join("\n") || "No preferences set.", {
preferredStyles: prefs?.preferredStyles ?? [],
avoidedStyles: prefs?.avoidedStyles ?? [],
minAbv: prefs?.minAbv ?? null,
maxAbv: prefs?.maxAbv ?? null,
flavorProfile: profile?.profileText ?? null,
flavorProfileRatingCount: profile?.ratingCount ?? null,
currentRatingCount: ratingCount,
})
}
)
}

View File

@@ -0,0 +1,203 @@
import type { McpServer } from "@modelcontextprotocol/server"
import type { Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
import {
fuzzyMatchIngredients,
recalculateMissingCount,
} from "@/lib/ingredient-matcher"
import { defineTool } from "@/lib/mcp/define"
import { McpToolError } from "@/lib/mcp/context"
import {
deleteRecipeSchema,
listRecipesSchema,
promoteRecipeSchema,
saveRecipeSchema,
} from "@/lib/mcp/schemas"
import { promoteRecipe } from "@/lib/recipe-promotion"
import { formatRecipeLine, ok } from "@/lib/mcp/render"
type StoredIngredient = { name: string; amount: string; available: boolean }
/**
* Saved recipes, with availability recomputed against the live bar on every read
* - the same thing GET /api/recipes does. The stored `available` flag is a
* snapshot from whenever the recipe was saved, so trusting it would answer "what
* can I make" with what was true weeks ago.
*/
export function registerRecipeTools(server: McpServer): void {
defineTool(
server,
{
name: "list_recipes",
title: "List recipes",
description:
"The user's saved cocktail recipes, with ingredient availability recomputed live against their current bar inventory. Set makeableOnly to true to answer what they can make right now. Prefer this over list_bar_items when the question is about drinks rather than bottles.",
inputSchema: listRecipesSchema,
scope: "bar:read",
readOnly: true,
},
async ({ makeableOnly, search }, caller) => {
const where: Prisma.RecipeWhereInput = { userId: caller.userId }
if (search) where.title = { contains: search, mode: "insensitive" }
const [recipes, barItems] = await Promise.all([
prisma.recipe.findMany({
where,
orderBy: { createdAt: "desc" },
include: { sourceDrink: { select: { name: true } } },
}),
prisma.barItem.findMany({
where: { userId: caller.userId, quantity: { not: "EMPTY" } },
select: { name: true },
}),
])
const processed = recipes.map((recipe) => {
const stored = Array.isArray(recipe.ingredients)
? (recipe.ingredients as unknown as StoredIngredient[])
: []
const ingredients = barItems.length
? fuzzyMatchIngredients(stored, barItems)
: stored
return {
id: recipe.id,
title: recipe.title,
ingredients,
missingCount: recalculateMissingCount(ingredients),
steps: Array.isArray(recipe.steps) ? (recipe.steps as string[]) : [],
garnish: recipe.garnish,
glassware: recipe.glassware,
notes: recipe.notes,
sourceDrinkName: recipe.sourceDrink?.name ?? null,
}
})
const visible = makeableOnly
? processed.filter((r) => r.missingCount === 0)
: processed
const text = visible.length
? [
...visible.map(formatRecipeLine),
`${visible.length} of ${processed.length} recipes${
makeableOnly ? " can be made right now" : ""
}`,
].join("\n")
: makeableOnly
? "Nothing can be made from the current bar inventory."
: "No saved recipes."
return ok(text, { recipes: visible, total: processed.length })
}
)
defineTool(
server,
{
name: "save_recipe",
title: "Save a recipe",
description:
"Save a cocktail recipe. Mark each ingredient available true or false as best you can; availability is recomputed against the live bar whenever the recipe is read, so a wrong guess here is self-correcting.",
inputSchema: saveRecipeSchema,
scope: "bar:write",
},
async (input, caller) => {
// sourceDrinkId is a foreign key onto Drink supplied by the caller. Without
// this check a recipe could be attached to someone else's drink, where it
// would render on their page and they could not remove it.
if (input.sourceDrinkId) {
const ownsDrink = await prisma.drink.findFirst({
where: { id: input.sourceDrinkId, userId: caller.userId },
select: { id: true },
})
if (!ownsDrink)
throw new McpToolError("No drink with that id.", "not_found")
}
const recipe = await prisma.recipe.create({
data: {
userId: caller.userId,
title: input.title,
ingredients: input.ingredients as unknown as Prisma.InputJsonValue,
steps: input.steps as unknown as Prisma.InputJsonValue,
garnish: input.garnish || null,
glassware: input.glassware || null,
sourceDrinkId: input.sourceDrinkId || null,
notes: input.notes || null,
},
})
return {
result: ok(`Saved recipe "${recipe.title}".`, { id: recipe.id }),
recordId: recipe.id,
}
}
)
defineTool(
server,
{
name: "promote_recipe",
title: "Add a recipe to drinks or the wishlist",
description:
"Turn a saved recipe into something the user can rate. target=\"drink\" adds it to their collection and links the recipe to it, so the recipe then shows on that drink's page; target=\"wishlist\" notes it to try later. The recipe is kept either way. Safe to call twice - if it is already there, the existing entry is returned rather than a duplicate created.",
inputSchema: promoteRecipeSchema,
// Creating a drink or wishlist entry is a change to the collection, not
// to the bar, so this is gated on drinks:write despite acting on a recipe.
scope: "drinks:write",
},
async ({ id, target }, caller) => {
const result = await promoteRecipe(caller.userId, id, target)
if (result.kind === "not_found") {
throw new McpToolError("No recipe with that id.", "not_found")
}
if (result.kind === "drink") {
const verb = result.existing ? "was already in" : "added to"
return {
result: ok(
`[${result.drink.id}] ${result.drink.name} ${verb} the collection. Use rate_drink with this id to record what they thought.`,
{ target: "drink", id: result.drink.id, existing: result.existing }
),
recordId: result.drink.id,
}
}
const verb = result.existing ? "was already on" : "added to"
return {
result: ok(`[${result.item.id}] ${result.item.name} ${verb} the wishlist.`, {
target: "wishlist",
id: result.item.id,
existing: result.existing,
}),
recordId: result.item.id,
}
}
)
defineTool(
server,
{
name: "delete_recipe",
title: "Delete a recipe",
description: "Permanently remove a saved recipe.",
inputSchema: deleteRecipeSchema,
scope: "bar:write",
destructive: true,
},
async ({ id }, caller) => {
const recipe = await prisma.recipe.findFirst({
where: { id, userId: caller.userId },
select: { id: true, title: true },
})
if (!recipe) throw new McpToolError("No recipe with that id.", "not_found")
await prisma.recipe.delete({ where: { id } })
return {
result: ok(`Deleted recipe "${recipe.title}".`, { id: recipe.id }),
recordId: recipe.id,
}
}
)
}

View File

@@ -0,0 +1,146 @@
import type { McpServer } from "@modelcontextprotocol/server"
import { prisma } from "@/lib/prisma"
import { defineTool } from "@/lib/mcp/define"
import { McpToolError } from "@/lib/mcp/context"
import {
addWishlistItemSchema,
listWishlistSchema,
promoteWishlistItemSchema,
removeWishlistItemSchema,
} from "@/lib/mcp/schemas"
import { formatWishlistLine, ok } from "@/lib/mcp/render"
/** Things the user wants to try but has not yet. */
export function registerWishlistTools(server: McpServer): void {
defineTool(
server,
{
name: "list_wishlist",
title: "List wishlist",
description:
"Drinks the user wants to try but has not tracked yet. Use promote_wishlist_item once they have actually had one.",
inputSchema: listWishlistSchema,
scope: "drinks:read",
readOnly: true,
},
async (_args, caller) => {
const items = await prisma.wishlistItem.findMany({
where: { userId: caller.userId },
orderBy: { createdAt: "desc" },
})
const text = items.length
? [...items.map(formatWishlistLine), `${items.length} items`].join("\n")
: "The wishlist is empty."
return ok(text, {
items: items.map((i) => ({
id: i.id,
name: i.name,
type: i.type,
subType: i.subType,
brewery: i.brewery,
abv: i.abv,
notes: i.notes,
source: i.source,
})),
total: items.length,
})
}
)
defineTool(
server,
{
name: "add_wishlist_item",
title: "Add to wishlist",
description:
"Note a drink the user wants to try later. Use create_drink instead if they have already had it.",
inputSchema: addWishlistItemSchema,
scope: "drinks:write",
},
async (input, caller) => {
const item = await prisma.wishlistItem.create({
// source is set here rather than accepted from the caller, so entries
// added this way stay attributable the way scan and ai_search ones are.
data: { ...input, source: "mcp", userId: caller.userId },
})
return {
result: ok(`Added ${item.name} to the wishlist.`, { id: item.id }),
recordId: item.id,
}
}
)
defineTool(
server,
{
name: "remove_wishlist_item",
title: "Remove from wishlist",
description:
"Drop a wishlist entry without tracking it. To move it into the collection instead, use promote_wishlist_item.",
inputSchema: removeWishlistItemSchema,
scope: "drinks:write",
destructive: true,
},
async ({ id }, caller) => {
const item = await prisma.wishlistItem.findFirst({
where: { id, userId: caller.userId },
select: { id: true, name: true },
})
if (!item)
throw new McpToolError("No wishlist item with that id.", "not_found")
await prisma.wishlistItem.delete({ where: { id } })
return {
result: ok(`Removed ${item.name} from the wishlist.`, { id: item.id }),
recordId: item.id,
}
}
)
defineTool(
server,
{
name: "promote_wishlist_item",
title: "Move a wishlist item into the collection",
description:
"Turn a wishlist entry into a tracked drink once the user has actually tried it, removing it from the wishlist. Follow with rate_drink to record what they thought.",
inputSchema: promoteWishlistItemSchema,
scope: "drinks:write",
},
async ({ id }, caller) => {
const item = await prisma.wishlistItem.findFirst({
where: { id, userId: caller.userId },
})
if (!item)
throw new McpToolError("No wishlist item with that id.", "not_found")
// One transaction so a failure cannot leave the entry on both lists, or
// on neither.
const drink = await prisma.$transaction(async (tx) => {
const created = await tx.drink.create({
data: {
userId: caller.userId,
name: item.name,
type: item.type,
subType: item.subType,
brewery: item.brewery,
abv: item.abv,
description: item.description,
},
})
await tx.wishlistItem.delete({ where: { id: item.id } })
return created
})
return {
result: ok(
`Moved ${drink.name} from the wishlist into the collection.`,
{ id: drink.id }
),
recordId: drink.id,
}
}
)
}

122
src/lib/recipe-promotion.ts Normal file
View File

@@ -0,0 +1,122 @@
import type { Drink, WishlistItem } from "@prisma/client"
import { prisma } from "@/lib/prisma"
/**
* Turning a saved recipe into something rateable.
*
* A recipe is instructions; a Drink is the thing you form an opinion about. The
* two are related but not the same, so promoting **links** them via
* Recipe.sourceDrinkId rather than converting one into the other - the recipe
* survives, and it then renders on the drink's page through the relation the
* drink detail view already reads.
*
* This is deliberately shared between the REST route and the MCP tool. The
* ownership check, the idempotency rule and the generated description all have
* to be identical, and the wishlist promote route is a standing example of that
* logic existing in exactly one place and being copied by nobody.
*/
export type PromotionTarget = "drink" | "wishlist"
export type PromotionResult =
| { kind: "not_found" }
/** `existing` is true when the recipe was already linked - nothing was created. */
| { kind: "drink"; drink: Drink; existing: boolean }
| { kind: "wishlist"; item: WishlistItem; existing: boolean }
interface StoredIngredient {
name: string
amount: string
available: boolean
}
function ingredientsOf(value: unknown): StoredIngredient[] {
return Array.isArray(value) ? (value as StoredIngredient[]) : []
}
/**
* A short human description, since a Drink has no ingredients of its own and a
* bare title would tell the user nothing on the drinks list a month from now.
*/
export function describeRecipe(recipe: {
ingredients: unknown
garnish: string | null
glassware: string | null
notes: string | null
}): string {
const names = ingredientsOf(recipe.ingredients).map((i) => i.name).filter(Boolean)
const parts = [
names.length ? `Made with ${names.join(", ")}.` : null,
recipe.glassware ? `Served in a ${recipe.glassware}.` : null,
recipe.garnish ? `Garnish: ${recipe.garnish}.` : null,
recipe.notes,
].filter(Boolean) as string[]
// description is capped at 2000 by drinkCreateSchema.
return parts.join(" ").slice(0, 2000)
}
export async function promoteRecipe(
userId: string,
recipeId: string,
target: PromotionTarget
): Promise<PromotionResult> {
const recipe = await prisma.recipe.findFirst({
where: { id: recipeId, userId },
})
if (!recipe) return { kind: "not_found" }
const description = describeRecipe(recipe)
if (target === "drink") {
// Already linked? Hand back the existing drink rather than creating a second
// one - promoting twice is a double click, not a request for a duplicate.
if (recipe.sourceDrinkId) {
const linked = await prisma.drink.findFirst({
where: { id: recipe.sourceDrinkId, userId },
})
if (linked) return { kind: "drink", drink: linked, existing: true }
}
// One transaction: a drink that exists but is not linked back would show no
// recipe on its page and would be promoted again on the next attempt.
const drink = await prisma.$transaction(async (tx) => {
const created = await tx.drink.create({
data: {
userId,
name: recipe.title,
type: "COCKTAIL",
description: description || null,
},
})
await tx.recipe.update({
where: { id: recipe.id },
data: { sourceDrinkId: created.id },
})
return created
})
return { kind: "drink", drink, existing: false }
}
// Wishlist. The recipe is untouched - "try later" is a note to self, not a
// change to the recipe itself.
const duplicate = await prisma.wishlistItem.findFirst({
where: { userId, source: "recipe", name: { equals: recipe.title, mode: "insensitive" } },
})
if (duplicate) return { kind: "wishlist", item: duplicate, existing: true }
const item = await prisma.wishlistItem.create({
data: {
userId,
name: recipe.title,
type: "COCKTAIL",
description: description || null,
notes: recipe.notes,
source: "recipe",
},
})
return { kind: "wishlist", item, existing: false }
}