From 71c746e308c40453045deeac9f7fdab9ee111eab Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:58:11 +0000 Subject: [PATCH 1/5] Migrate MCP OAuth to Better Auth 1.7 with credential reset Co-Authored-By: Cameron Pak --- .changeset/steady-agent-authentication.md | 5 + bun.lock | 46 ++- docs/adr/0026-agent-native-mcp-server.md | 50 ++- docs/adr/0061-cli-mcp-compatibility.md | 12 +- docs/mcp.md | 14 +- migrations/0023_better_auth_1_7.sql | 160 ++++++++++ package.json | 6 +- scripts/mint-mcp-token.ts | 58 ++-- worker/account-deletion.test.ts | 9 +- worker/account-deletion.ts | 16 +- worker/auth-real.test.ts | 26 +- worker/auth.ts | 231 +------------- worker/capture-real.test.ts | 346 ++++++++++++++------- worker/index.ts | 42 ++- worker/mcp-migration.test.ts | 57 ++++ worker/mcp-oauth.ts | 59 +++- worker/mcp-provider.ts | 351 ++++++++++++++++++++++ worker/membership.test.ts | 11 +- 18 files changed, 1069 insertions(+), 430 deletions(-) create mode 100644 .changeset/steady-agent-authentication.md create mode 100644 migrations/0023_better_auth_1_7.sql create mode 100644 worker/mcp-migration.test.ts create mode 100644 worker/mcp-provider.ts diff --git a/.changeset/steady-agent-authentication.md b/.changeset/steady-agent-authentication.md new file mode 100644 index 00000000..8a72fa37 --- /dev/null +++ b/.changeset/steady-agent-authentication.md @@ -0,0 +1,5 @@ +--- +"dotflowy": patch +--- + +Keeps Dotflowy's authentication infrastructure up to date. Connected AI agents may need to reconnect once. diff --git a/bun.lock b/bun.lock index 25ac60ec..0d478c29 100644 --- a/bun.lock +++ b/bun.lock @@ -6,7 +6,9 @@ "name": "dotflowy", "dependencies": { "@base-ui/react": "^1.8.0", - "@better-auth/stripe": "~1.6.35", + "@better-auth/mcp": "~1.7.26", + "@better-auth/oauth-provider": "~1.7.26", + "@better-auth/stripe": "~1.7.26", "@floating-ui/react-dom": "^2.1.9", "@fontsource-variable/geist": "^5.3.0", "@fontsource-variable/geist-mono": "^5.3.0", @@ -29,7 +31,7 @@ "@tanstack/react-start": "^1.169.3", "@tanstack/react-virtual": "^3.14.13", "@xstate/react": "7.0.0-alpha.1", - "better-auth": "~1.6.35", + "better-auth": "~1.7.26", "chrono-node": "^2.10.1", "class-variance-authority": "^0.7.1", "cmdk": "^1.1.1", @@ -166,23 +168,27 @@ "@better-auth/core": ["@better-auth/core@1.7.26", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "@opentelemetry/api": "^1.9.0", "better-call": "~1.4.5", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-k9tECegh1/MZmAQ9tD+4fjF2zYCzMcy0Xhu3nASp8bj48NrK1E0yV2BAeWnprMVRqh62ka07xc0MZuqmvlXNDQ=="], - "@better-auth/drizzle-adapter": ["@better-auth/drizzle-adapter@1.6.35", "", { "peerDependencies": { "@better-auth/core": "^1.6.35", "@better-auth/utils": "0.4.2", "drizzle-orm": "^0.45.2" }, "optionalPeers": ["drizzle-orm"] }, "sha512-sCSppi7kSlbaaRxjcPN3Xxd/prl9VnZRWDUZ/uZXG1V9w77pZGElHVJxZD2NE03iXu2KzYw0w1Rikod10P74kw=="], + "@better-auth/drizzle-adapter": ["@better-auth/drizzle-adapter@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-3OOQPZkAFVo63jbjkQTVjM7SyNbKxmM5sb9BKflaJOT+ld6mxM6yItm5NMKNd1xn/wA4X/+kAmT/KjFL0mRW/Q=="], - "@better-auth/kysely-adapter": ["@better-auth/kysely-adapter@1.6.35", "", { "peerDependencies": { "@better-auth/core": "^1.6.35", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-/4g8fKS7ZWa3fx+5vx7OnEwOvM7w4F9tAFRjIHc4tj0pbx4aWPqkEe+it+zIcTldlPirJQyv8Wr+rLpxUamd+g=="], + "@better-auth/kysely-adapter": ["@better-auth/kysely-adapter@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-8kImf5aRi5cFC3fYO7fqszSAUC5vU8ya7yHxuCovTJNz7ow4pItRshU319aEPBdgABRFU53kI0v+SE5NI8UJtQ=="], - "@better-auth/memory-adapter": ["@better-auth/memory-adapter@1.6.35", "", { "peerDependencies": { "@better-auth/core": "^1.6.35", "@better-auth/utils": "0.4.2" } }, "sha512-/L3L4xBVUySPofL6p9zrNRDGsjn4h+jTRrPkXxQJ836NtpUAhJttppXFmrTQTfMuMhE8I0wsGLEXf+HBLXi5ug=="], + "@better-auth/mcp": ["@better-auth/mcp@1.7.26", "", { "dependencies": { "@better-auth/oauth-provider": "^1.7.26", "jose": "^6.1.3" }, "peerDependencies": { "@better-auth/core": "^1.7.26", "better-auth": "^1.7.26", "better-call": "~1.4.5" } }, "sha512-SlueBNN1Aqi2amwfc8/qlMzjCCqh9w08coeRdpzn1b/huL/1hwmdShFn2bwffJLY5eckpGVrnoYgnBB6/sfYUA=="], - "@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.6.35", "", { "peerDependencies": { "@better-auth/core": "^1.6.35", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-W4r0Oe8NmfADItoB76ZDPYeCrQ5Fq1+1xmHB74s7BWgwKuFoa6cu/dkGmqx+UYAC4TpaHx+591P/Kw83XQAdww=="], + "@better-auth/memory-adapter": ["@better-auth/memory-adapter@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0" } }, "sha512-ttV2Q06uoJBJzp9J8zYwYwMY60jvlhziumyqUZ1gJKltvsOasbGfoGPYThypyydTVu8iApP9O4xI9jYXJ08syg=="], - "@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.6.35", "", { "peerDependencies": { "@better-auth/core": "^1.6.35", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-wvQr06lNx14WKrbYiP6fWIXcRKpMzmOjnCGfmz+AeB+/hb5dj270Urx639Rybf6dhwRamKEoZupZiOYOmVhEYw=="], + "@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-mGVJ0UIL1hjrp5aCuv4hFinZhpB7vvpu1c/fSa40Ktk4GugXcXguVwHI4hiDqGCttslTz0LOa5gqT+BfzgdJWw=="], - "@better-auth/stripe": ["@better-auth/stripe@1.6.35", "", { "dependencies": { "defu": "^6.1.5", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/core": "^1.6.35", "better-auth": "^1.6.35", "better-call": "1.4.0", "stripe": "^18 || ^19 || ^20 || ^21 || ^22" } }, "sha512-Rd3o9iRtXFudNugSo34N6rCFECR51yzNvLhhl+Ev94zF64mu6X2yLs/HTrwKgDYIBN3zbGb9TQyB6TRb3P6RwQ=="], + "@better-auth/oauth-provider": ["@better-auth/oauth-provider@1.7.26", "", { "dependencies": { "jose": "^6.2.3", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "better-auth": "^1.7.26", "better-call": "~1.4.5" } }, "sha512-wzeIJ2Yogsd8HN5QLm3avpEubJmwo/hg00qZf6c7Ivu/doJlg0PENJOxgK2oRdjbl787i9GOKp1pAzTCQpMGDg=="], - "@better-auth/telemetry": ["@better-auth/telemetry@1.6.35", "", { "peerDependencies": { "@better-auth/core": "^1.6.35", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1" } }, "sha512-a0oSxf2OlNnFu8jRvn8ruNLh8tsX3xw11mpn4mKIMATPxHcgmrRF2xBQIIb/NDRsd+fBXWO7Nv5y6Wk9sQKKOQ=="], + "@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-rXc6dI6HBhD4uXh1gMJU0ScQjojt3wIS4+DziIm/j8ujoTBEG96hFVN0vFVIq/D7SnimXIsPu5rqJ7GYSDbDtw=="], - "@better-auth/utils": ["@better-auth/utils@0.4.2", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A=="], + "@better-auth/stripe": ["@better-auth/stripe@1.7.26", "", { "dependencies": { "defu": "^6.1.5", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.26", "better-auth": "^1.7.26", "better-call": "~1.4.5", "stripe": "^18 || ^19 || ^20 || ^21 || ^22 || ^23" } }, "sha512-5T70tMAW5dNAjWo58561VBvLBVCwm8TI7MYsIGjhFu18Ho19I1l9ZGXLu0TM8oy113hCIyC7bsJQwwNrq5chaA=="], - "@better-fetch/fetch": ["@better-fetch/fetch@1.3.1", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="], + "@better-auth/telemetry": ["@better-auth/telemetry@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3" } }, "sha512-XSxQWg+guJ4X9KrcsdJCUPcXk/GaKxPNSXrhuDRhoWhk3ommioRB2Y6/to6ROy1fGP8JtXqRN4ZPiyKZnfy4Sw=="], + + "@better-auth/utils": ["@better-auth/utils@0.5.1", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-WETqw5vQ52uQ/xwWR4E8rTgT6fDEr/wnS+otDNkBCa/69281FCF32OKDdQUcahMCnjsvqXBNiEvAQHFB0EVRRg=="], + + "@better-fetch/fetch": ["@better-fetch/fetch@1.3.3", "", {}, "sha512-U6SlDt/GUWtK2JAxS/NhdoYTEim+EL1G5byz2TUj83KjLZBUpYzb5SmX0aXaCnbGkAjFKnV/o/0+cyXMbEcqqg=="], "@changesets/apply-release-plan": ["@changesets/apply-release-plan@8.1.1", "", { "dependencies": { "@changesets/config": "^4.0.1", "@changesets/format": "^0.1.2", "@changesets/git": "^4.0.1", "@changesets/should-skip-package": "^1.0.0", "@changesets/types": "^7.0.0", "import-meta-resolve": "^4.2.0", "jsonc-parser": "^3.3.1", "semver": "^7.8.1" } }, "sha512-nk2Hbq3M9NeHMdaIRBDvawKrQJzXB9sGyBUE5yWnIKtvdcNCPj75zBekJYr0gTT2ecJH3eFeTrc8eisPImcv0Q=="], @@ -424,8 +430,6 @@ "@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.45.0", "", {}, "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw=="], - "@oxc-project/types": ["@oxc-project/types@0.149.0", "", {}, "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA=="], "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.68.0", "", { "os": "android", "cpu": "arm" }, "sha512-dhfYPbzv/h9JgHjNkl2R6sOjUfxDyLGOZVb3g8/ScaTNwwJcYgmHh8kcYFDUhinuy1QAoANCWUvw1jlk+z6gAg=="], @@ -848,9 +852,9 @@ "baseline-browser-mapping": ["baseline-browser-mapping@2.11.38", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-rMgy5YW7x28SMfXHLlVZDBqlWzYZ0x2rVR/6FWrNBF0chjigARK1H6nM0hKA1Um3kPOlkQFVtjJs00d2N1ezuw=="], - "better-auth": ["better-auth@1.6.35", "", { "dependencies": { "@better-auth/core": "1.6.35", "@better-auth/drizzle-adapter": "1.6.35", "@better-auth/kysely-adapter": "1.6.35", "@better-auth/memory-adapter": "1.6.35", "@better-auth/mongo-adapter": "1.6.35", "@better-auth/prisma-adapter": "1.6.35", "@better-auth/telemetry": "1.6.35", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.4.0", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": "^0.45.2", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-AjESIE4zF586CtXeSXnmOGuq2FLjhgWbwpdOmsKlKeVsNXTd6p6lN+q0pFmRFiVLI4q9AtVVQgZg9rgSKDlpRQ=="], + "better-auth": ["better-auth@1.7.26", "", { "dependencies": { "@better-auth/core": "1.7.26", "@better-auth/drizzle-adapter": "1.7.26", "@better-auth/kysely-adapter": "1.7.26", "@better-auth/memory-adapter": "1.7.26", "@better-auth/mongo-adapter": "1.7.26", "@better-auth/prisma-adapter": "1.7.26", "@better-auth/telemetry": "1.7.26", "@better-auth/utils": "0.5.1", "@better-fetch/fetch": "1.3.3", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.6", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0 || ^3.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-8TLA60CxEnhcmGceHIFlheonqrFFcVJ1Yfr3gOJEet3xyMfN6qAVN0N1GRcpe0g9KNzqhe1EM2smbk9DCylaAA=="], - "better-call": ["better-call@1.4.0", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-bBKOT4vv1kZLDgxVePdilk/Jwkn+dtRRsmi3DzHcDP+WnswyVl6dR59l2HEeP/0cB+bDoopASAesWDPIdd/zZA=="], + "better-call": ["better-call@1.4.6", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-tJ3lkMFeQProwiuZiQApwgVmYmBfXM4sAP7HxMsnAFtl4NWZhamG+RGoMNgHwGYkmcB+3eWyo3vgt4sWUUSdQA=="], "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], @@ -1450,10 +1454,6 @@ "@babel/preset-typescript/@babel/helper-validator-option": ["@babel/helper-validator-option@7.29.7", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="], - "@better-auth/core/@better-fetch/fetch": ["@better-fetch/fetch@1.3.3", "", {}, "sha512-U6SlDt/GUWtK2JAxS/NhdoYTEim+EL1G5byz2TUj83KjLZBUpYzb5SmX0aXaCnbGkAjFKnV/o/0+cyXMbEcqqg=="], - - "@better-auth/core/better-call": ["better-call@1.4.6", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-tJ3lkMFeQProwiuZiQApwgVmYmBfXM4sAP7HxMsnAFtl4NWZhamG+RGoMNgHwGYkmcB+3eWyo3vgt4sWUUSdQA=="], - "@cspotcode/source-map-support/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], "@dotenvx/dotenvx/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], @@ -1534,12 +1534,6 @@ "babel-plugin-react-compiler/@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="], - "better-auth/@better-auth/core": ["@better-auth/core@1.6.35", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.39.0", "@standard-schema/spec": "^1.1.0", "zod": "^4.3.6" }, "peerDependencies": { "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.0", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-yp+MIXG3bd9D4iUxMO8PWgj7h1aiOzKogma/QzBNZLlT3nalsxAZiyJQ1LsQa8QMQlZoU9r5dloJd4uQUnUvZA=="], - - "better-call/@better-auth/utils": ["@better-auth/utils@0.5.1", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-WETqw5vQ52uQ/xwWR4E8rTgT6fDEr/wnS+otDNkBCa/69281FCF32OKDdQUcahMCnjsvqXBNiEvAQHFB0EVRRg=="], - - "better-call/@better-fetch/fetch": ["@better-fetch/fetch@1.3.3", "", {}, "sha512-U6SlDt/GUWtK2JAxS/NhdoYTEim+EL1G5byz2TUj83KjLZBUpYzb5SmX0aXaCnbGkAjFKnV/o/0+cyXMbEcqqg=="], - "cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], "dot-prop/is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], @@ -1680,8 +1674,6 @@ "@babel/helper-skip-transparent-expression-wrappers/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], - "@better-auth/core/better-call/@better-auth/utils": ["@better-auth/utils@0.5.1", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-WETqw5vQ52uQ/xwWR4E8rTgT6fDEr/wnS+otDNkBCa/69281FCF32OKDdQUcahMCnjsvqXBNiEvAQHFB0EVRRg=="], - "@dotenvx/dotenvx/execa/get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], "@dotenvx/dotenvx/execa/human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], diff --git a/docs/adr/0026-agent-native-mcp-server.md b/docs/adr/0026-agent-native-mcp-server.md index a8439b14..b1efc24c 100644 --- a/docs/adr/0026-agent-native-mcp-server.md +++ b/docs/adr/0026-agent-native-mcp-server.md @@ -83,7 +83,7 @@ personal API keys can also authenticate MCP, with server-enforced read-only or read/write permissions. OAuth discovery and browser-session separation remain. The paragraph below records the original OAuth-only decision. -**OAuth: Better Auth's `mcp` plugin, not API keys, not the session cookie.** MCP clients speak OAuth +**Historical OAuth design (superseded by the 1.7 amendment below): Better Auth's `mcp` plugin, not API keys, not the session cookie.** MCP clients speak OAuth 2.1 (PKCE + dynamic client registration + RFC 9728 discovery), and Better Auth — already the identity layer ([ADR 0011](./0011-the-auth-gate.md)) — ships all of it as the `mcp` plugin: authorization/token/ registration endpoints under `/api/auth/mcp/*`, tokens in D1 (migration `0004`), `getMcpSession` for @@ -188,3 +188,51 @@ the daily path when a `date` is given, so for them it is validated and ignored.) - The tool registry is compile-time static, like the plugin registry ([ADR 0001](./0001-plugin-architecture.md)): adding a tool = one entry in `worker/mcp-tools.ts` (schema + handler), and `tools/list` derives itself. + +## Better Auth 1.7 migration + +The authorization server now uses `@better-auth/mcp`, built on +`@better-auth/oauth-provider`, with opaque SHA-256-hashed tokens. Migration +`0023_better_auth_1_7.sql` follows the vendor reset path: remove old OAuth +verification state, drop the three legacy OAuth tables, and create the 1.7 +client, resource, consent, access-token and refresh-token models. Existing agent +registrations and credentials are intentionally invalidated; agents reconnect +once. Users, browser sessions, API keys and outline routing are unaffected. + +Both `/mcp` and `/api/mcp` remain public MCP URLs. Root and path-aware +`/.well-known/oauth-protected-resource` documents remain available, as does +`/.well-known/oauth-authorization-server` (including issuer-path discovery). +The issuer is now the provider's `/api/auth`; protected-resource metadata +advertises that issuer. Discovery retains the public `/api/auth/mcp/authorize`, +`/token`, and `/register` aliases, which dispatch internally to 1.7's +`/oauth2/*`. Resource requests for the origin or either MCP URL normalize to +`/mcp`; unrelated resources are rejected. PKCE remains mandatory. +The provider's active-token validator checks stored expiry/revocation and the +MCP audience; proof-bound tokens are not accepted as unbound Bearer tokens. +The resulting stable user id still passes through `resolveUserId`. + +Explicit consent remains account-bound and required on every authorization. +The compatibility boundary keeps a short-lived, single-use opaque consent code +in D1, bound to the server session's user and the provider-signed OAuth query. +The browser never submits arbitrary redirects, scopes or a raw signed query to +approve access. Approval forwards the saved query to the official provider, +then tags the issued authorization code with the current revocation generation. + +D1 has no interactive transactions for provider rotation. Rotation uses the +provider's conditional one-time update, with `refreshTokenReuseInterval: 0`: +replaying a rotated refresh token invalidates the user's client family, not +just the old credential. An `mcpGrant` generation and refresh-deletion trigger +mitigate the provider's documented family-invalidation/rotation insertion window. +Disconnect increments the generation and deletes access tokens, refresh tokens, +consents and pending codes in one D1 batch. Token issuance snapshots the +generation and checks it after insertion; a stale candidate pair is deleted +before a response is returned. Refresh also invalidates the prior access token. +The same check prevents an approval or code exchange from restoring a revoked +grant. Account deletion removes both token models, consent, client-resource +links, owned clients, grant generations and pending OAuth verification state. +This is a D1-specific mitigation, not an interactive transaction across provider +operations. Tests inject revocation during approval, exchange and rotation; +they do not exhaust all multi-worker interleavings. Revisit this boundary when +the provider supports atomic family invalidation. +An already-authorized MCP request may finish when revocation races its execution; +revocation cannot undo work already accepted by the outline DO. diff --git a/docs/adr/0061-cli-mcp-compatibility.md b/docs/adr/0061-cli-mcp-compatibility.md index 6a8060e0..6bad70dc 100644 --- a/docs/adr/0061-cli-mcp-compatibility.md +++ b/docs/adr/0061-cli-mcp-compatibility.md @@ -60,5 +60,13 @@ choose `login --insecure-storage` to use an unencrypted, user-only credential fi Diagnostics never print credentials. OS credential storage reduces accidental exposure; it does not guarantee protection from malware running as the user. -Logout removes local credentials only. The current OAuth provider has no MCP -revocation endpoint, so the CLI does not claim to revoke server tokens. +Logout removes local credentials only; it does not call the provider's revocation +endpoint or claim to revoke server tokens. Users can disconnect clients in +Dotflowy's Connections settings. The Better Auth 1.7 reset in ADR 0026 requires +existing OAuth agents (including the CLI) to sign in once again; the MCP URLs, +PKCE flow, and discovery URLs remain compatible. + +The provider infers native client registration for exact loopback HTTP callbacks +when `application_type` is omitted, preserving the published CLI's registration. +It still rejects HTTP callbacks on non-loopback hosts and validates explicit +web/native application types with the vendor's redirect rules. diff --git a/docs/mcp.md b/docs/mcp.md index 1c1433d2..968bfc8e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -43,6 +43,11 @@ in Settings → Plugins does not disable explicit MCP or CLI daily operations. ## OAuth consent and revocation +Connected AI agents may need to reconnect once as Dotflowy updates its +authentication infrastructure to Better Auth 1.7. Existing OAuth credentials +are reset; personal API keys and browser sessions are unaffected. Use the same +MCP URL and sign in again (CLI: `dotflowy login`). + Every new OAuth authorization requires explicit approval in Dotflowy, even if the client omits `prompt=consent`. The consent page shows the authenticated account, registered client name, callback hostname, full-outline read/write @@ -60,10 +65,11 @@ the connector in the AI app alone may not revoke its tokens. Root and `/mcp`-suffixed protected-resource discovery both identify the full `https:///mcp` URL. The retained `/api/mcp` alias has its own -path-aware discovery document. Existing bearer tokens and API keys remain valid -without retroactive consent. New authorization uses S256 PKCE and explicit consent; -successful refresh consumes the previous refresh grant. A client must save the -new token pair, not retry the old refresh token. +path-aware discovery document. API keys remain valid across the 1.7 upgrade; +OAuth agents reconnect once. New authorization uses S256 PKCE and explicit consent; +successful refresh consumes the previous refresh grant and invalidates the prior +access token. A client must save the new pair: replaying the old refresh token +revokes the client's refresh family for that user. ## Tool annotations diff --git a/migrations/0023_better_auth_1_7.sql b/migrations/0023_better_auth_1_7.sql new file mode 100644 index 00000000..cb5a3e5d --- /dev/null +++ b/migrations/0023_better_auth_1_7.sql @@ -0,0 +1,160 @@ +-- Better Auth 1.7 MCP reset: existing agents reconnect once (ADR 0026). +-- No identity/session changes. Do not retain plaintext legacy credentials. +DELETE FROM verification WHERE json_valid(value) AND json_type(value, '$.clientId') IS NOT NULL; +DROP TABLE oauthAccessToken; +DROP TABLE oauthConsent; +DROP TABLE oauthApplication; + +CREATE TABLE "oauthClient" ( + "id" text NOT NULL PRIMARY KEY, + "clientId" text NOT NULL UNIQUE, + "clientSecret" text, + "clientDiscoveryId" text, + "disabled" integer DEFAULT 0, + "skipConsent" integer, + "enableEndSession" integer, + "subjectType" text, + "scopes" text CHECK ("scopes" IS NULL OR json_valid("scopes")), + "clientCredentialsScopes" text DEFAULT '[]' CHECK ("clientCredentialsScopes" IS NULL OR json_valid("clientCredentialsScopes")), + "userId" text REFERENCES "user" ("id") ON DELETE CASCADE, + "createdAt" date, + "updatedAt" date, + "name" text, + "uri" text, + "icon" text, + "contacts" text CHECK ("contacts" IS NULL OR json_valid("contacts")), + "tos" text, + "policy" text, + "softwareId" text, + "softwareVersion" text, + "softwareStatement" text, + "redirectUris" text NOT NULL CHECK ("redirectUris" IS NULL OR json_valid("redirectUris")), + "postLogoutRedirectUris" text CHECK ("postLogoutRedirectUris" IS NULL OR json_valid("postLogoutRedirectUris")), + "backchannelLogoutUri" text, + "backchannelLogoutSessionRequired" integer, + "tokenEndpointAuthMethod" text, + "applicationType" text, + "jwks" text, + "jwksUri" text, + "grantTypes" text CHECK ("grantTypes" IS NULL OR json_valid("grantTypes")), + "responseTypes" text CHECK ("responseTypes" IS NULL OR json_valid("responseTypes")), + "requirePKCE" integer, + "dpopBoundAccessTokens" integer DEFAULT 0, + "referenceId" text, + "metadata" text CHECK ("metadata" IS NULL OR json_valid("metadata")) +); +CREATE INDEX "oauthClient_userId_idx" ON "oauthClient" ("userId"); + +CREATE TABLE "oauthResource" ( + "id" text NOT NULL PRIMARY KEY, + "identifier" text NOT NULL UNIQUE, + "name" text NOT NULL, + "accessTokenTtl" integer, + "refreshTokenTtl" integer, + "signingAlgorithm" text, + "signingKeyId" text, + "allowedScopes" text CHECK ("allowedScopes" IS NULL OR json_valid("allowedScopes")), + "customClaims" text CHECK ("customClaims" IS NULL OR json_valid("customClaims")), + "dpopBoundAccessTokensRequired" integer DEFAULT 0, + "disabled" integer DEFAULT 0, + "createdAt" date, + "updatedAt" date, + "policyVersion" integer DEFAULT 1, + "metadata" text CHECK ("metadata" IS NULL OR json_valid("metadata")) +); + + +CREATE TABLE "oauthClientResource" ( + "id" text NOT NULL PRIMARY KEY, + "clientId" text NOT NULL REFERENCES "oauthClient" ("clientId") ON DELETE CASCADE, + "resourceId" text NOT NULL REFERENCES "oauthResource" ("identifier") ON DELETE CASCADE, + "metadata" text CHECK ("metadata" IS NULL OR json_valid("metadata")), + "createdAt" date +); +CREATE INDEX "oauthClientResource_clientId_idx" ON "oauthClientResource" ("clientId"); +CREATE INDEX "oauthClientResource_resourceId_idx" ON "oauthClientResource" ("resourceId"); + +CREATE TABLE "oauthRefreshToken" ( + "id" text NOT NULL PRIMARY KEY, + "token" text NOT NULL UNIQUE, + "clientId" text NOT NULL REFERENCES "oauthClient" ("clientId") ON DELETE CASCADE, + "sessionId" text REFERENCES "session" ("id") ON DELETE SET NULL, + "userId" text NOT NULL REFERENCES "user" ("id") ON DELETE CASCADE, + "referenceId" text, + "authorizationCodeId" text, + "resources" text CHECK ("resources" IS NULL OR json_valid("resources")), + "requestedUserInfoClaims" text CHECK ("requestedUserInfoClaims" IS NULL OR json_valid("requestedUserInfoClaims")), + "expiresAt" date NOT NULL, + "createdAt" date NOT NULL, + "revoked" date, + "rotatedAt" date, + "rotationReplayResponse" text, + "rotationReplayExpiresAt" date, + "authTime" date, + "confirmation" text CHECK ("confirmation" IS NULL OR json_valid("confirmation")), + "scopes" text NOT NULL CHECK ("scopes" IS NULL OR json_valid("scopes")) +); +CREATE INDEX "oauthRefreshToken_clientId_idx" ON "oauthRefreshToken" ("clientId"); +CREATE INDEX "oauthRefreshToken_sessionId_idx" ON "oauthRefreshToken" ("sessionId"); +CREATE INDEX "oauthRefreshToken_userId_idx" ON "oauthRefreshToken" ("userId"); +CREATE INDEX "oauthRefreshToken_authorizationCodeId_idx" ON "oauthRefreshToken" ("authorizationCodeId"); + +CREATE TABLE "oauthAccessToken" ( + "id" text NOT NULL PRIMARY KEY, + "token" text NOT NULL UNIQUE, + "clientId" text NOT NULL REFERENCES "oauthClient" ("clientId") ON DELETE CASCADE, + "sessionId" text REFERENCES "session" ("id") ON DELETE SET NULL, + "userId" text REFERENCES "user" ("id") ON DELETE CASCADE, + "referenceId" text, + "authorizationCodeId" text, + "resources" text CHECK ("resources" IS NULL OR json_valid("resources")), + "requestedUserInfoClaims" text CHECK ("requestedUserInfoClaims" IS NULL OR json_valid("requestedUserInfoClaims")), + "refreshId" text REFERENCES "oauthRefreshToken" ("id") ON DELETE CASCADE, + "expiresAt" date NOT NULL, + "createdAt" date NOT NULL, + "revoked" date, + "confirmation" text CHECK ("confirmation" IS NULL OR json_valid("confirmation")), + "scopes" text NOT NULL CHECK ("scopes" IS NULL OR json_valid("scopes")) +); +CREATE INDEX "oauthAccessToken_clientId_idx" ON "oauthAccessToken" ("clientId"); +CREATE INDEX "oauthAccessToken_sessionId_idx" ON "oauthAccessToken" ("sessionId"); +CREATE INDEX "oauthAccessToken_userId_idx" ON "oauthAccessToken" ("userId"); +CREATE INDEX "oauthAccessToken_authorizationCodeId_idx" ON "oauthAccessToken" ("authorizationCodeId"); +CREATE INDEX "oauthAccessToken_refreshId_idx" ON "oauthAccessToken" ("refreshId"); + +CREATE TABLE "oauthConsent" ( + "id" text NOT NULL PRIMARY KEY, + "clientId" text NOT NULL REFERENCES "oauthClient" ("clientId") ON DELETE CASCADE, + "userId" text REFERENCES "user" ("id") ON DELETE CASCADE, + "referenceId" text, + "resources" text CHECK ("resources" IS NULL OR json_valid("resources")), + "requestedUserInfoClaims" text CHECK ("requestedUserInfoClaims" IS NULL OR json_valid("requestedUserInfoClaims")), + "scopes" text NOT NULL CHECK ("scopes" IS NULL OR json_valid("scopes")), + "createdAt" date NOT NULL, + "updatedAt" date NOT NULL +); +CREATE INDEX "oauthConsent_clientId_idx" ON "oauthConsent" ("clientId"); +CREATE INDEX "oauthConsent_userId_idx" ON "oauthConsent" ("userId"); + +CREATE TABLE "oauthClientAssertion" ( + "id" text NOT NULL PRIMARY KEY, + "expiresAt" date NOT NULL +); + + +-- Revocation generations survive token deletion. A rotation that was already +-- in flight must not recreate a family after disconnect or replay cleanup. +CREATE TABLE mcpGrant ( + userId text NOT NULL REFERENCES "user" (id) ON DELETE CASCADE, + clientId text NOT NULL REFERENCES oauthClient (clientId) ON DELETE CASCADE, + epoch integer NOT NULL DEFAULT 0, + PRIMARY KEY (userId, clientId) +); + +CREATE TRIGGER oauthRefreshToken_deleted AFTER DELETE ON oauthRefreshToken BEGIN + INSERT INTO mcpGrant (userId, clientId, epoch) + SELECT OLD.userId, OLD.clientId, 1 + WHERE EXISTS (SELECT 1 FROM "user" WHERE id = OLD.userId) + AND EXISTS (SELECT 1 FROM oauthClient WHERE clientId = OLD.clientId) + ON CONFLICT(userId, clientId) DO UPDATE SET epoch = epoch + 1; +END; diff --git a/package.json b/package.json index 97689067..de68e223 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,9 @@ }, "dependencies": { "@base-ui/react": "^1.8.0", - "@better-auth/stripe": "~1.6.35", + "@better-auth/mcp": "~1.7.26", + "@better-auth/oauth-provider": "~1.7.26", + "@better-auth/stripe": "~1.7.26", "@floating-ui/react-dom": "^2.1.9", "@fontsource-variable/geist": "^5.3.0", "@fontsource-variable/geist-mono": "^5.3.0", @@ -83,7 +85,7 @@ "@tanstack/react-start": "^1.169.3", "@tanstack/react-virtual": "^3.14.13", "@xstate/react": "7.0.0-alpha.1", - "better-auth": "~1.6.35", + "better-auth": "~1.7.26", "chrono-node": "^2.10.1", "class-variance-authority": "^0.7.1", "cmdk": "^1.1.1", diff --git a/scripts/mint-mcp-token.ts b/scripts/mint-mcp-token.ts index 9c91c186..f7d012c7 100644 --- a/scripts/mint-mcp-token.ts +++ b/scripts/mint-mcp-token.ts @@ -9,8 +9,10 @@ * MCP tool calls also require a paid plan locally — run `bun run comp:dev-plan` * once per D1 reset before exercising writes. * - * Requires `bun run dev` / `bun run dev:api` and `bun run seed:user`. + * Requires `bun run cf:dev` and `bun run seed:user`. */ +import { Schema } from "effect"; + const API = "http://localhost:8787"; const AUTH = `${API}/api/auth`; const EMAIL = "dev@dotflowy.local"; @@ -19,15 +21,19 @@ const ORIGIN = "http://localhost:8787"; /** Loopback redirect the authorize step can target without a listener. */ const REDIRECT_URI = "http://127.0.0.1:8765/callback"; -type SignInBody = { user?: { id?: string; email?: string } }; -type RegisterBody = { client_id?: string; error?: string }; -type TokenBody = { - access_token?: string; - token_type?: string; - expires_in?: number; - error?: string; - error_description?: string; -}; +const SignInBody = Schema.Struct({ + user: Schema.Struct({ id: Schema.String }), +}); +const RegisterBody = Schema.Struct({ + client_id: Schema.optionalKey(Schema.String), + error: Schema.optionalKey(Schema.String), +}); +const TokenBody = Schema.Struct({ + access_token: Schema.optionalKey(Schema.String), + expires_in: Schema.optionalKey(Schema.Number), + error: Schema.optionalKey(Schema.String), + error_description: Schema.optionalKey(Schema.String), +}); function randomVerifier(): string { const bytes = crypto.getRandomValues(new Uint8Array(32)); @@ -68,7 +74,7 @@ async function signIn(): Promise<{ cookie: string; userId: string }> { `sign-in failed (${res.status}): ${text}. Run \`bun run seed:user\` first.`, ); } - const body = (await res.json()) as SignInBody; + const body = Schema.decodeUnknownSync(SignInBody)(await res.json()); const userId = body.user?.id; if (!userId) throw new Error("sign-in succeeded but user id missing"); return { cookie: sessionCookie(res), userId }; @@ -90,7 +96,7 @@ async function registerClient(cookie: string): Promise { response_types: ["code"], }), }); - const body = (await res.json()) as RegisterBody; + const body = Schema.decodeUnknownSync(RegisterBody)(await res.json()); if (!res.ok || !body.client_id) { throw new Error( `client registration failed (${res.status}): ${JSON.stringify(body)}`, @@ -122,16 +128,26 @@ async function authorizeCode( `authorize failed (status ${res.status}, location ${location ?? "none"})`, ); } - const code = new URL(location).searchParams.get("code"); + const pending = new URL(location, API).searchParams.get("consent_code"); + if (!pending) throw new Error("authorize redirect missing consent request"); + const consent = await fetch(`${AUTH}/oauth2/consent`, { + method: "POST", + headers: { cookie, origin: ORIGIN, "content-type": "application/json" }, + body: JSON.stringify({ consent_code: pending, accept: true }), + }); + const approved = Schema.decodeUnknownSync( + Schema.Struct({ + redirectURI: Schema.optionalKey(Schema.String), + }), + )(await consent.json()); + if (!consent.ok || !approved.redirectURI) + throw new Error(`consent failed (${consent.status})`); + const code = new URL(approved.redirectURI).searchParams.get("code"); if (!code) throw new Error(`authorize redirect missing code: ${location}`); return code; } -async function exchangeToken( - clientId: string, - code: string, - verifier: string, -): Promise { +async function exchangeToken(clientId: string, code: string, verifier: string) { const body = new URLSearchParams({ grant_type: "authorization_code", code, @@ -147,7 +163,7 @@ async function exchangeToken( }, body, }); - const json = (await res.json()) as TokenBody; + const json = Schema.decodeUnknownSync(TokenBody)(await res.json()); if (!res.ok || !json.access_token) { throw new Error( `token exchange failed (${res.status}): ${JSON.stringify(json)}`, @@ -160,7 +176,9 @@ async function main(): Promise { try { await fetch(`${API}/api/auth/ok`); } catch { - console.error(`Worker not reachable at ${API}. Run \`bun run dev\` first.`); + console.error( + `Worker not reachable at ${API}. Run \`bun run cf:dev\` first.`, + ); process.exit(1); } diff --git a/worker/account-deletion.test.ts b/worker/account-deletion.test.ts index a3d9cac7..8540ad45 100644 --- a/worker/account-deletion.test.ts +++ b/worker/account-deletion.test.ts @@ -117,7 +117,14 @@ describe("deleteResidualUserRows", () => { expect(bySql("DELETE FROM capture_key")!.args).toEqual(["user-abc"]); expect(bySql("oauthAccessToken")!.args).toEqual(["user-abc"]); expect(bySql("oauthConsent")!.args).toEqual(["user-abc"]); - expect(bySql("oauthApplication")!.args).toEqual(["user-abc"]); + for (const table of [ + "oauthRefreshToken", + "oauthClientResource", + "oauthClient", + "mcpGrant", + "verification", + ]) + expect(bySql(table)!.args).toEqual(["user-abc"]); expect(bySql("DELETE FROM waitlist")!.args).toEqual(["user@example.com"]); expect(bySql("DELETE FROM invites")!.args).toEqual(["user@example.com"]); expect(bySql("subscription")).toBeUndefined(); diff --git a/worker/account-deletion.ts b/worker/account-deletion.ts index 0bd6189b..c4e76e92 100644 --- a/worker/account-deletion.ts +++ b/worker/account-deletion.ts @@ -158,7 +158,7 @@ export async function cancelActiveSubscriptions( * row is already gone (cleared in beforeDelete's Stripe step — it's the * entitlement record, too load-bearing for a best-effort sweep). What's left: * - * - the mcp OAuth tables (migration 0004) DO declare `ON DELETE CASCADE`, so + * - the MCP OAuth tables (migration 0023) DO declare `ON DELETE CASCADE`, so * they may already be gone; deleting them by `userId` is idempotent and makes * cleanup correct whether or not D1 enforced the cascade. * - the `waitlist` row (migration 0005) and the `invites` row (migration 0007) @@ -182,8 +182,20 @@ export function deleteResidualUserRows( return db.batch([ db.prepare("DELETE FROM capture_key WHERE userId = ?").bind(userId), db.prepare("DELETE FROM oauthAccessToken WHERE userId = ?").bind(userId), + db.prepare("DELETE FROM oauthRefreshToken WHERE userId = ?").bind(userId), db.prepare("DELETE FROM oauthConsent WHERE userId = ?").bind(userId), - db.prepare("DELETE FROM oauthApplication WHERE userId = ?").bind(userId), + db + .prepare( + "DELETE FROM oauthClientResource WHERE clientId IN (SELECT clientId FROM oauthClient WHERE userId = ?)", + ) + .bind(userId), + db.prepare("DELETE FROM oauthClient WHERE userId = ?").bind(userId), + db.prepare("DELETE FROM mcpGrant WHERE userId = ?").bind(userId), + db + .prepare( + "DELETE FROM verification WHERE json_valid(value) AND json_extract(value, '$.userId') = ?", + ) + .bind(userId), db.prepare("DELETE FROM waitlist WHERE email = ?").bind(normalized), db.prepare("DELETE FROM invites WHERE email = ?").bind(normalized), ]); diff --git a/worker/auth-real.test.ts b/worker/auth-real.test.ts index 12dda583..c72899b4 100644 --- a/worker/auth-real.test.ts +++ b/worker/auth-real.test.ts @@ -27,7 +27,7 @@ beforeAll(async () => { const mode = request.headers.get("x-fixture-signup-mode"); return createAuth({ ...env, EMAIL: { async send(message) { mail.set(message.to, message.text); return { messageId: "fixture-only" }; } }, - SIGNUP_OPEN: mode === "open" ? "true" : mode === "malformed" ? "TRUE" : undefined }, "http://fixture", ctx).handler(request); + SIGNUP_OPEN: mode === "open" ? "true" : mode === "malformed" ? "TRUE" : undefined }, "http://localhost", ctx).handler(request); } };`, resolveDir: process.cwd(), loader: "ts", @@ -64,7 +64,10 @@ beforeAll(async () => { type: "text" as const, value: "disposable-google-auth-test-secret", }, - BETTER_AUTH_URL: { type: "text" as const, value: "http://fixture" }, + BETTER_AUTH_URL: { + type: "text" as const, + value: "http://localhost", + }, GOOGLE_CLIENT_ID: { type: "text" as const, value: "fixture-client", @@ -122,6 +125,7 @@ beforeAll(async () => { for (const file of [ "0003_create_auth.sql", "0004_create_oauth.sql", + "0023_better_auth_1_7.sql", "0005_create_waitlist.sql", "0006_create_stripe.sql", "0007_create_invites.sql", @@ -144,12 +148,12 @@ async function request( cookie?: string, ) { const headers = new ProviderHeaders({ - origin: "http://fixture", + origin: "http://localhost", "content-type": "application/json", "x-fixture-signup-mode": mode, }); if (cookie) headers.set("cookie", cookie); - return mf.dispatchFetch(`http://fixture/api/auth${path}`, { + return mf.dispatchFetch(`http://localhost/api/auth${path}`, { method: body === undefined ? "GET" : "POST", headers, body: body === undefined ? undefined : JSON.stringify(body), @@ -167,8 +171,8 @@ function cookies(response: Pick) { async function google(mode: string, email: string, requestSignUp = false) { const start = await request(mode, "/sign-in/social", { provider: "google", - callbackURL: "http://fixture/", - errorCallbackURL: "http://fixture/", + callbackURL: "http://localhost/", + errorCallbackURL: "http://localhost/", requestSignUp, }); expect(start.status, await start.clone().text()).toBe(200); @@ -211,11 +215,11 @@ test("gift verification returns to redemption without signing in or allowing an expect(signup.status).toBe(200); expect(await session("open", signup)).toBeNull(); const mail = await mf.dispatchFetch( - `http://fixture/__fixture/email?to=${encodeURIComponent(email)}`, + `http://localhost/__fixture/email?to=${encodeURIComponent(email)}`, ); const text = Schema.decodeUnknownSync(Schema.String)(await mail.json()); const link = text.match( - /http:\/\/fixture\/api\/auth\/verify-email\?[^\s]+/, + /http:\/\/localhost\/api\/auth\/verify-email\?[^\s]+/, )?.[0]; expect(link).toBeDefined(); expect(new URL(link!).searchParams.get("callbackURL")).toBe("/redeem"); @@ -241,13 +245,13 @@ test("open Google signup creates a verified account and later sign-ins reuse it const email = "new-google@auth.test"; const created = await google("open", email); expect(created.status).toBe(302); - expect(created.headers.get("location")).toBe("http://fixture/"); + expect(created.headers.get("location")).toBe("http://localhost/"); const first = await session("open", created); expect(first?.user).toMatchObject({ email, emailVerified: true }); expect(first?.user.id).toBeTruthy(); const again = await google("invite", email); - expect(again.headers.get("location")).toBe("http://fixture/"); + expect(again.headers.get("location")).toBe("http://localhost/"); expect((await session("invite", again))?.user.id).toBe(first!.user.id); const db = await mf.getD1Database("DB"); expect( @@ -345,7 +349,7 @@ test("Google links only verified matching password accounts, preserving their id const result = await google("invite", email); if (verified) { - expect(result.headers.get("location")).toBe("http://fixture/"); + expect(result.headers.get("location")).toBe("http://localhost/"); expect((await session("invite", result))?.user.id).toBe(user.id); const passwordLogin = await request("invite", "/sign-in/email", { email, diff --git a/worker/auth.ts b/worker/auth.ts index 459fbbd0..d3014a1f 100644 --- a/worker/auth.ts +++ b/worker/auth.ts @@ -14,13 +14,8 @@ import { stripe } from "@better-auth/stripe"; import { betterAuth } from "better-auth"; -import { - APIError, - createAuthMiddleware, - getSessionFromCtx, -} from "better-auth/api"; -import { generateRandomString } from "better-auth/crypto"; -import { captcha, mcp } from "better-auth/plugins"; +import { APIError, createAuthMiddleware } from "better-auth/api"; +import { captcha } from "better-auth/plugins"; import { Effect, Schema } from "effect"; import Stripe from "stripe"; @@ -40,7 +35,7 @@ import { normalizeEmail, } from "./identity"; import { isRedeemableInvite, redeemInvite } from "./invites"; -import { readMcpConsent } from "./mcp-oauth"; +import { mcpProvider } from "./mcp-provider"; import { recordWelcome } from "./membership"; import { FOUNDING_SEAT_LIMIT, countFoundingSeats } from "./plan"; import { @@ -379,149 +374,6 @@ export function createAuth( // email-bound code, so this is belt-and-braces. hooks: { before: createAuthMiddleware(async (ctx) => { - if (ctx.path === "/mcp/authorize" || ctx.path === "/mcp/token") { - const resource = - ctx.path === "/mcp/authorize" - ? ctx.query?.resource - : ctx.body?.resource; - // Both URLs address the same outline service. Keep omitted and old - // origin-only indicators working, but reject unrelated audiences. - if ( - resource !== undefined && - baseURL && - ![ - new URL(baseURL).origin, - `${new URL(baseURL).origin}/mcp`, - `${new URL(baseURL).origin}/api/mcp`, - ].includes(resource) - ) { - throw new APIError("BAD_REQUEST", { - error: "invalid_target", - error_description: "Unknown MCP resource", - }); - } - } - if ( - ctx.path === "/mcp/token" && - ctx.body?.grant_type === "refresh_token" && - !isString(ctx.body.refresh_token) - ) - throw new APIError("BAD_REQUEST", { - error: "invalid_request", - error_description: "Refresh token must be a string", - }); - if ( - ctx.path === "/mcp/token" && - ctx.body?.grant_type === "authorization_code" - ) { - if (!isString(ctx.body.code)) - throw new APIError("BAD_REQUEST", { - error: "invalid_request", - error_description: "Authorization code must be a string", - }); - const verification = - await ctx.context.internalAdapter.findVerificationValue( - ctx.body.code, - ); - if (verification) { - const value = Schema.decodeUnknownResult( - Schema.fromJsonString( - Schema.Struct({ requireConsent: Schema.Boolean }), - ), - )(verification.value); - if (value._tag === "Success" && value.success.requireConsent) { - throw new APIError("UNAUTHORIZED", { - error: "invalid_grant", - error_description: "User consent is required", - }); - } - } - } - if (ctx.path === "/mcp/authorize") { - // Consent is our policy, not an optional client prompt. This also - // persists into the provider's signed login-resume cookie. - return { context: { query: { ...ctx.query, prompt: "consent" } } }; - } - if (ctx.path === "/oauth2/consent") { - if (!Schema.is(Schema.Boolean)(ctx.body?.accept)) - throw new APIError("BAD_REQUEST", { - message: "Consent decision must be a boolean", - }); - const session = await getSessionFromCtx(ctx); - const code = - ctx.body?.consent_code || - (await ctx.getSignedCookie( - "oidc_consent_prompt", - ctx.context.secret, - )); - const consent = - session && isString(code) - ? await readMcpConsent(env.DB, session.user.id, code) - : null; - if (!session || !consent) - throw new APIError("FORBIDDEN", { - message: - "Invalid or expired consent request. Reconnect from your app.", - }); - ctx.setCookie("oidc_consent_prompt", "", { path: "/", maxAge: 0 }); - if (!ctx.body.accept) { - await ctx.context.internalAdapter.deleteVerificationByIdentifier( - code, - ); - const redirectURI = new URL(consent.redirectURI); - redirectURI.searchParams.set("error", "access_denied"); - if (consent.state) - redirectURI.searchParams.set("state", consent.state); - return ctx.json({ redirectURI: redirectURI.toString() }); - } - const authorizationCode = generateRandomString( - 32, - "a-z", - "A-Z", - "0-9", - ); - const now = new Date().toISOString(); - // The provider's separate update/create ignores deleted pending state. - // Keep approval conditional and atomic with respect to revocation. - const [, savedConsent] = await env.DB.batch([ - env.DB.prepare(`UPDATE verification SET identifier = ?, - value = json_set(value, '$.requireConsent', json('false')), - expiresAt = ?, updatedAt = ? - WHERE identifier = ? AND expiresAt > ? AND json_valid(value) - AND json_extract(value, '$.requireConsent') = 1 - AND json_extract(value, '$.userId') = ? - AND json_extract(value, '$.clientId') = ?`).bind( - authorizationCode, - new Date(Date.now() + 600_000).toISOString(), - now, - code, - now, - session.user.id, - consent.clientId, - ), - env.DB.prepare(`INSERT INTO oauthConsent - (id, clientId, userId, scopes, consentGiven, createdAt, updatedAt) - SELECT ?, ?, ?, ?, 1, ?, ? FROM verification WHERE identifier = ?`).bind( - crypto.randomUUID(), - consent.clientId, - session.user.id, - consent.scope.join(" "), - now, - now, - authorizationCode, - ), - ]); - if (savedConsent.meta.changes !== 1) - throw new APIError("FORBIDDEN", { - message: - "Connection request was revoked. Reconnect from your app.", - }); - const redirectURI = new URL(consent.redirectURI); - redirectURI.searchParams.set("code", authorizationCode); - if (consent.state) - redirectURI.searchParams.set("state", consent.state); - return ctx.json({ redirectURI: redirectURI.toString() }); - } if (ctx.path !== "/sign-up/email") return; // Open signup: no invite required (Turnstile already gated this request // in the captcha plugin's onRequest). Accept and let the after-hook @@ -550,65 +402,6 @@ export function createAuth( }); }), after: createAuthMiddleware(async (ctx) => { - if ( - ctx.path === "/mcp/token" && - ctx.body?.grant_type === "authorization_code" && - !(ctx.context.returned instanceof APIError) - ) { - const returned = Schema.decodeUnknownResult( - Schema.Struct({ access_token: Schema.String }), - )(ctx.context.returned); - if (returned._tag === "Success") { - // A revocation may run after the provider consumes the code but - // before it saves the token. Do not let that exchange restore access. - const revoked = await env.DB.prepare( - `DELETE FROM oauthAccessToken WHERE accessToken = ? AND NOT EXISTS ( - SELECT 1 FROM oauthConsent c WHERE c.clientId = oauthAccessToken.clientId - AND c.userId = oauthAccessToken.userId AND c.consentGiven = 1 - )`, - ) - .bind(returned.success.access_token) - .run(); - if (revoked.meta.changes !== 0) - throw new APIError("UNAUTHORIZED", { - error: "invalid_grant", - error_description: - "App access was revoked. Reconnect to allow access again.", - }); - } - return; - } - if ( - ctx.path === "/mcp/token" && - ctx.body?.grant_type === "refresh_token" && - !(ctx.context.returned instanceof APIError) - ) { - const returned = Schema.decodeUnknownResult( - Schema.Struct({ access_token: Schema.String }), - )(ctx.context.returned); - // Better Auth 1.6 issues a new pair but retains the old refresh grant. - // Delete it atomically; only one concurrent refresh can win. If it - // was revoked or already consumed, remove this candidate pair too. - if (returned._tag === "Success") { - const consumed = await env.DB.prepare( - "DELETE FROM oauthAccessToken WHERE refreshToken = ?", - ) - .bind(ctx.body.refresh_token) - .run(); - if (consumed.meta.changes !== 1) { - await env.DB.prepare( - "DELETE FROM oauthAccessToken WHERE accessToken = ?", - ) - .bind(returned.success.access_token) - .run(); - throw new APIError("UNAUTHORIZED", { - error: "invalid_grant", - error_description: "Refresh token was revoked or already used", - }); - } - } - return; - } if ( ctx.path === "/change-password" && !(ctx.context.returned instanceof APIError) @@ -649,13 +442,7 @@ export function createAuth( // stripe-node v22 ships workerd export conditions, so `new Stripe(key)` // auto-selects the fetch HTTP client + SubtleCrypto webhook verification. // - // OAuth 2.1 authorization server for the MCP endpoint (/mcp): PKCE - // authorization-code flow with dynamic client registration, tokens in D1 - // (migration 0004). The SPA's AuthScreen doubles as the login page — the - // authorize endpoint stashes the OAuth query in a signed cookie, sends the - // signed-out user to `/`, and resumes the flow after sign-in (the plugin's - // after-hook plus AuthScreen's explicit authorize-redirect fallback). - // See docs/adr/0026-agent-native-mcp-server.md. + // OAuth provider and the compatibility boundary: ADR 0026. plugins: [ // Cloudflare Turnstile (#293), registered ONLY when the secret is set — // the optional-secrets pattern (Google/Stripe): no key locally or on a @@ -676,15 +463,7 @@ export function createAuth( }), ] : []), - mcp({ - loginPage: "/", - resource: baseURL ? `${new URL(baseURL).origin}/mcp` : undefined, - oidcConfig: { - loginPage: "/", - consentPage: "/mcp-consent", - requirePKCE: true, - }, - }), + mcpProvider(`${new URL(baseURL ?? "http://localhost:8787").origin}/mcp`), stripe({ stripeClient: new Stripe( env.STRIPE_SECRET_KEY ?? "sk_test_placeholder", diff --git a/worker/capture-real.test.ts b/worker/capture-real.test.ts index 328d43cb..284b2c05 100644 --- a/worker/capture-real.test.ts +++ b/worker/capture-real.test.ts @@ -1,5 +1,6 @@ import { hashPassword } from "better-auth/crypto"; import { afterAll, beforeAll, expect, test } from "bun:test"; +import { Schema } from "effect"; import { build } from "esbuild"; import { Miniflare, Response as FixtureResponse } from "miniflare"; import { createHash, createHmac, randomUUID } from "node:crypto"; @@ -61,7 +62,7 @@ async function fixture( } async function fixtureResponse(path: string, input: FixtureInput) { - const response = await mf.dispatchFetch(`http://fixture/fixture/${path}`, { + const response = await mf.dispatchFetch(`http://localhost/fixture/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(input), @@ -73,7 +74,7 @@ async function fixtureResponse(path: string, input: FixtureInput) { async function api(path: string, key: string, body?: typeof CaptureBody.Type) { const headers = new Headers({ authorization: `Bearer ${key}` }); if (body !== undefined) headers.set("content-type", "application/json"); - const response = await mf.dispatchFetch(`http://fixture${path}`, { + const response = await mf.dispatchFetch(`http://localhost${path}`, { method: body === undefined ? "GET" : "POST", headers: Object.fromEntries(headers), body: body === undefined ? undefined : JSON.stringify(body), @@ -182,7 +183,7 @@ beforeAll(async () => { type: "text", value: "disposable-capture-test-secret-not-for-production", }, - BETTER_AUTH_URL: { type: "text", value: "http://fixture" }, + BETTER_AUTH_URL: { type: "text", value: "http://localhost" }, STRIPE_SECRET_KEY: { type: "text", value: "sk_test_disposable_membership_fixture", @@ -401,6 +402,7 @@ beforeAll(async () => { "0020_feedback_replies.sql", "0021_pro_trial_checkout.sql", "0022_pro_rewards.sql", + "0023_better_auth_1_7.sql", ]) { const sql = await readFile(`migrations/${migration}`, "utf8"); await db.exec(sql.replace(/--[^\n]*/g, "").replaceAll("\n", " ")); @@ -428,12 +430,12 @@ test("membership gates theme writes, keeps the launch exception narrow, and scop .bind(email, id) .run(); const response = await mf.dispatchFetch( - "http://fixture/api/auth/sign-in/email", + "http://localhost/api/auth/sign-in/email", { method: "POST", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", }, body: JSON.stringify({ email, password }), }, @@ -691,7 +693,7 @@ test("only a signed paid checkout queues a welcome, and webhook retries cannot r }, }); const send = (body: string, secret = webhookSecret) => - mf.dispatchFetch("http://fixture/api/auth/stripe/webhook", { + mf.dispatchFetch("http://localhost/api/auth/stripe/webhook", { method: "POST", headers: { "content-type": "application/json", @@ -773,11 +775,11 @@ test("standalone codes bind atomically to their first redeemer, track private hi async function login(id: string = randomUUID()) { await fixture("seed", { userId: id, password: hash }); const response = await mf.dispatchFetch( - `http://fixture/api/auth/sign-in/email`, + `http://localhost/api/auth/sign-in/email`, { method: "POST", headers: { - origin: "http://fixture", + origin: "http://localhost", "content-type": "application/json", }, body: JSON.stringify({ email: `${id}@capture.test`, password }), @@ -1076,7 +1078,7 @@ test("standalone codes bind atomically to their first redeemer, track private hi successUrl: "/settings", cancelUrl: "/settings", }, - "http://fixture", + "http://localhost", ); expect(checkout.status, await checkout.clone().text()).toBe(200); const giftCheckout = [...trialCheckouts.values()].find( @@ -1162,7 +1164,7 @@ test("standalone codes bind atomically to their first redeemer, track private hi successUrl: "/settings", cancelUrl: "/settings", }, - "http://fixture", + "http://localhost", ) ).status, ).toBe(200); @@ -1630,10 +1632,13 @@ test("cardless trial setup is explicit, serialized, replayable and follows verif const password = "trial-fixture-password"; await fixture("seed", { userId, password: await hashPassword(password) }); const login = await mf.dispatchFetch( - "http://fixture/api/auth/sign-in/email", + "http://localhost/api/auth/sign-in/email", { method: "POST", - headers: { "content-type": "application/json", origin: "http://fixture" }, + headers: { + "content-type": "application/json", + origin: "http://localhost", + }, body: JSON.stringify({ email: `${userId}@capture.test`, password }), }, ); @@ -1706,7 +1711,7 @@ test("cardless trial setup is explicit, serialized, replayable and follows verif successUrl: "/settings?checkout=success", cancelUrl: "/settings?checkout=canceled", }, - "http://fixture", + "http://localhost", ); // A live unused trial reservation excludes ordinary checkout as well as the // opposite direction below. Expired and consumed reservations do not. @@ -1765,7 +1770,7 @@ test("cardless trial setup is explicit, serialized, replayable and follows verif ).toBe(403); expect( ( - await mf.dispatchFetch(`http://fixture${path}`, { + await mf.dispatchFetch(`http://localhost${path}`, { method: "POST", body: JSON.stringify({ consent: true }), }) @@ -1900,7 +1905,7 @@ test("cardless trial setup is explicit, serialized, replayable and follows verif created: now, data: { object }, }); - return mf.dispatchFetch("http://fixture/api/auth/stripe/webhook", { + return mf.dispatchFetch("http://localhost/api/auth/stripe/webhook", { method: "POST", headers: { "content-type": "application/json", @@ -1932,7 +1937,7 @@ test("cardless trial setup is explicit, serialized, replayable and follows verif }); const key = await fixture("key", { userId, permission: "read" }); const mcp = () => - mf.dispatchFetch("http://fixture/mcp", { + mf.dispatchFetch("http://localhost/mcp", { method: "POST", headers: { authorization: `Bearer ${key.key}`, @@ -2032,10 +2037,13 @@ test("retained shards stay inert until authenticated account erasure, without af const email = `${randomUUID()}@capture.test`; const password = "disposable-test-password-1"; const signup = await mf.dispatchFetch( - "http://fixture/api/auth/sign-up/email", + "http://localhost/api/auth/sign-up/email", { method: "POST", - headers: { "content-type": "application/json", origin: "http://fixture" }, + headers: { + "content-type": "application/json", + origin: "http://localhost", + }, body: JSON.stringify({ name: "Deletion test", email, password }), }, ); @@ -2052,10 +2060,13 @@ test("retained shards stay inert until authenticated account erasure, without af .bind(userId) .run(); const signin = await mf.dispatchFetch( - "http://fixture/api/auth/sign-in/email", + "http://localhost/api/auth/sign-in/email", { method: "POST", - headers: { "content-type": "application/json", origin: "http://fixture" }, + headers: { + "content-type": "application/json", + origin: "http://localhost", + }, body: JSON.stringify({ email, password }), }, ); @@ -2093,8 +2104,11 @@ test("retained shards stay inert until authenticated account erasure, without af } const namespace = await mf.getDurableObjectNamespace("SHARD"); expect( - (await namespace.get(namespace.idFromName(userId)).fetch("http://fixture/")) - .status, + ( + await namespace + .get(namespace.idFromName(userId)) + .fetch("http://localhost/") + ).status, ).toBe(404); await mf.unsafeEvictDurableObject("capture-test", "ShardDO", { name: userId, @@ -2104,12 +2118,12 @@ test("retained shards stay inert until authenticated account erasure, without af ]); const refused = await mf.dispatchFetch( - "http://fixture/api/auth/delete-user", + "http://localhost/api/auth/delete-user", { method: "POST", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", cookie, }, body: JSON.stringify({ password: "wrong password" }), @@ -2120,12 +2134,12 @@ test("retained shards stay inert until authenticated account erasure, without af { value: "retain me" }, ]); const deleted = await mf.dispatchFetch( - "http://fixture/api/auth/delete-user", + "http://localhost/api/auth/delete-user", { method: "POST", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", cookie, }, body: JSON.stringify({ password }), @@ -2181,7 +2195,7 @@ test("persisted cutover receipts still prevent replacing a recovered outline", a "completed-cutover", ); const response = await mf.dispatchFetch( - "http://fixture/fixture/restore-snapshot", + "http://localhost/fixture/restore-snapshot", { method: "POST", headers: { "content-type": "application/json" }, @@ -2209,10 +2223,13 @@ test("HTTP PATCH rejects an invalid batch without partial writes, then clears nu throw new Error(`fixture capture failed: ${capture.error}`); const { nodeId } = capture.receipt; const signin = await mf.dispatchFetch( - "http://fixture/api/auth/sign-in/email", + "http://localhost/api/auth/sign-in/email", { method: "POST", - headers: { "content-type": "application/json", origin: "http://fixture" }, + headers: { + "content-type": "application/json", + origin: "http://localhost", + }, body: JSON.stringify({ email: `${userId}@capture.test`, password }), }, ); @@ -2222,11 +2239,11 @@ test("HTTP PATCH rejects an invalid batch without partial writes, then clears nu .map((value) => value.split(";")[0]) .join("; "); const patch = (updates: unknown[]) => - mf.dispatchFetch("http://fixture/api/nodes", { + mf.dispatchFetch("http://localhost/api/nodes", { method: "PATCH", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", cookie, }, body: JSON.stringify({ updates }), @@ -2282,12 +2299,12 @@ test("feedback widget config requires the pinned real session, not email, admin for (const userId of ["feedback-owner", "feedback-other"]) { await fixture("seed", { userId, password: await hashPassword(password) }); const signin = await mf.dispatchFetch( - "http://fixture/api/auth/sign-in/email", + "http://localhost/api/auth/sign-in/email", { method: "POST", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", }, body: JSON.stringify({ email: `${userId}@capture.test`, password }), }, @@ -2302,13 +2319,13 @@ test("feedback widget config requires the pinned real session, not email, admin } const request = (cookie = "", method = "GET") => mf.dispatchFetch( - "http://fixture/api/feedback-widget?userId=feedback-owner", + "http://localhost/api/feedback-widget?userId=feedback-owner", { method, headers: { cookie, "x-user-id": "feedback-owner", - origin: "http://fixture", + origin: "http://localhost", }, }, ); @@ -2328,15 +2345,18 @@ test("feedback widget config requires the pinned real session, not email, admin const wrongMethod = await request(cookies[0], "POST"); expect(wrongMethod.status).toBe(405); expect(wrongMethod.headers.get("allow")).toBe("GET"); - const signedOut = await mf.dispatchFetch("http://fixture/api/auth/sign-out", { - method: "POST", - headers: { - cookie: cookies[0], - origin: "http://fixture", - "content-type": "application/json", + const signedOut = await mf.dispatchFetch( + "http://localhost/api/auth/sign-out", + { + method: "POST", + headers: { + cookie: cookies[0], + origin: "http://localhost", + "content-type": "application/json", + }, + body: "{}", }, - body: "{}", - }); + ); expect(signedOut.status).toBe(200); expect((await request(cookies[0])).status).toBe(404); }); @@ -2866,10 +2886,10 @@ test("real password change and reset revoke keys; sign-out does not", async () = const auth = (path: string, body: AuthBody, cookie?: string) => { const headers = new Headers({ "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", }); if (cookie) headers.set("cookie", cookie); - return mf.dispatchFetch(`http://fixture/api/auth/${path}`, { + return mf.dispatchFetch(`http://localhost/api/auth/${path}`, { method: "POST", headers: Object.fromEntries(headers), body: JSON.stringify(body), @@ -2899,11 +2919,11 @@ test("real password change and reset revoke keys; sign-out does not", async () = .map((value) => value.split(";")[0]) .join("; "); const beforeCreation = Date.now(); - const created = await mf.dispatchFetch("http://fixture/api/keys", { + const created = await mf.dispatchFetch("http://localhost/api/keys", { method: "POST", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", cookie, }, // Omitting expiry exercises the canonical route's secure default. @@ -2917,7 +2937,7 @@ test("real password change and reset revoke keys; sign-out does not", async () = beforeCreation + 30 * 86400000, ); expect(first.entry.expiresAt).toBeLessThanOrEqual(Date.now() + 30 * 86400000); - const handshake = await mf.dispatchFetch("http://fixture/mcp", { + const handshake = await mf.dispatchFetch("http://localhost/mcp", { method: "POST", headers: { "content-type": "application/json", @@ -2936,9 +2956,9 @@ test("real password change and reset revoke keys; sign-out does not", async () = const rotate = ( body: RotationRequest, path = "/api/keys", - origin = "http://fixture", + origin = "http://localhost", ) => - mf.dispatchFetch(`http://fixture${path}`, { + mf.dispatchFetch(`http://localhost${path}`, { method: "PATCH", headers: { "content-type": "application/json", origin, cookie }, body: JSON.stringify(body), @@ -2995,11 +3015,11 @@ test("real password change and reset revoke keys; sign-out does not", async () = authorization: `Bearer ${rotated.key}`, }), ).toEqual({ authenticated: true }); - const deniedRotation = await mf.dispatchFetch("http://fixture/api/keys", { + const deniedRotation = await mf.dispatchFetch("http://localhost/api/keys", { method: "PATCH", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", authorization: `Bearer ${rotated.key}`, }, body: JSON.stringify({ id: rotated.entry.id }), @@ -3021,7 +3041,7 @@ test("real password change and reset revoke keys; sign-out does not", async () = authorization: `Bearer ${first.key}`, }), ).toEqual({ authenticated: true }); - const listing = await mf.dispatchFetch("http://fixture/api/keys", { + const listing = await mf.dispatchFetch("http://localhost/api/keys", { headers: { cookie }, }); expect(listing.status).toBe(200); @@ -3065,7 +3085,7 @@ test("real password change and reset revoke keys; sign-out does not", async () = ).toEqual({ authenticated: true }); const requested = await auth("request-password-reset", { email, - redirectTo: "http://fixture/reset-password", + redirectTo: "http://localhost/reset-password", }); expect(requested.status, await requested.clone().text()).toBe(200); const token = await db @@ -3160,7 +3180,7 @@ test("invalid capture input creates no nodes; key management enforces origin and test("OAuth discovery, explicit account-bound consent, refresh rotation and isolated revocation", async () => { const db = await mf.getD1Database("DB"); - const origin = "http://fixture"; + const origin = "http://localhost"; for (const path of ["/mcp", "/api/mcp"]) { const denied = await mf.dispatchFetch(`${origin}${path}`, { method: "POST", @@ -3171,7 +3191,7 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol .match(/resource_metadata="([^"]+)"/)![1]!; expect(await (await mf.dispatchFetch(metadataUrl)).json()).toMatchObject({ resource: `${origin}${path}`, - authorization_servers: [origin], + authorization_servers: [`${origin}/api/auth`], }); } expect( @@ -3179,6 +3199,23 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol await mf.dispatchFetch(`${origin}/.well-known/oauth-protected-resource`) ).json(), ).toMatchObject({ resource: `${origin}/mcp` }); + expect( + ( + await mf.dispatchFetch( + `${origin}/.well-known/oauth-protected-resource/mcp`, + { method: "HEAD" }, + ) + ).status, + ).toBe(200); + const discovery = await ( + await mf.dispatchFetch(`${origin}/.well-known/oauth-authorization-server`) + ).json(); + expect(discovery).toMatchObject({ + issuer: `${origin}/api/auth`, + authorization_endpoint: `${origin}/api/auth/mcp/authorize`, + token_endpoint: `${origin}/api/auth/mcp/token`, + registration_endpoint: `${origin}/api/auth/mcp/register`, + }); const cookies: [string, string] = ["", ""]; const users = []; for (let i = 0; i < 2; i++) { @@ -3210,9 +3247,28 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol client_name: "Local OAuth reviewer", redirect_uris: ["https://client.example/callback?existing=1"], token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], }), }); expect(register.status).toBe(201); + for (const [redirect, status] of [ + ["http://127.0.0.1:8765/callback", 201], + ["http://untrusted.example/callback", 400], + ] as const) { + const native = await mf.dispatchFetch(`${origin}/api/auth/mcp/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + client_name: "Loopback CLI", + redirect_uris: [redirect], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + }), + }); + expect(native.status).toBe(status); + if (native.ok) + expect(await native.json()).toMatchObject({ application_type: "native" }); + } // SAFETY: This successful DCR response is produced by the real provider; its client id is used in the exercised authorization flow. const client = (await register.json()) as { client_id: string }; const verifier = "disposable-oauth-verifier-012345678901234567890123456789"; @@ -3257,6 +3313,7 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol const location = new URL(response.headers.get("location")!, origin); expect(location.pathname).toBe("/mcp-consent"); expect(location.searchParams.has("code")).toBe(false); + expect(location.searchParams.get("consent_code")).toBeTruthy(); return location.searchParams.get("consent_code")!; }; const decide = ( @@ -3361,6 +3418,17 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol }; }; const first = await issue(); + const stored = await db + .prepare("SELECT token FROM oauthAccessToken WHERE token = ?") + .bind(createHash("sha256").update(first.access_token).digest("base64url")) + .first(); + expect(stored).not.toBeNull(); + expect( + await db + .prepare("SELECT token FROM oauthAccessToken WHERE token = ?") + .bind(first.access_token) + .first(), + ).toBeNull(); const unapproved = await authorize(); for (const credentials of [ { @@ -3408,7 +3476,7 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol }) ).status, ).not.toBe(200); - expect((await mcp(current.access_token)).status).toBe(200); + expect((await mcp(current.access_token)).status).toBe(401); const racing = await issue(); const competitors = await Promise.all( [0, 1].map(() => @@ -3421,6 +3489,57 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol expect( competitors.filter((response) => response.status === 200), ).toHaveLength(1); + expect((await mcp(racing.access_token)).status).toBe(401); + await tokenRequest({ + grant_type: "refresh_token", + refresh_token: racing.refresh_token, + }); + for (const response of competitors) { + if (response.ok) { + const pair = Schema.decodeUnknownSync( + Schema.Struct({ + access_token: Schema.String, + refresh_token: Schema.String, + }), + )(await response.json()); + expect((await mcp(pair.access_token)).status).toBe(401); + expect( + ( + await tokenRequest({ + grant_type: "refresh_token", + refresh_token: pair.refresh_token, + }) + ).status, + ).not.toBe(200); + } + } + const interruptedRotation = await issue(); + await db + .prepare(`CREATE TRIGGER revoke_during_rotation BEFORE INSERT ON oauthRefreshToken + WHEN NEW.userId = '${users[0]}' AND NEW.clientId = '${client.client_id}' BEGIN + DELETE FROM oauthAccessToken WHERE userId = NEW.userId AND clientId = NEW.clientId; + DELETE FROM oauthRefreshToken WHERE userId = NEW.userId AND clientId = NEW.clientId; + DELETE FROM oauthConsent WHERE userId = NEW.userId AND clientId = NEW.clientId; + END`) + .run(); + try { + const interrupted = await tokenRequest({ + grant_type: "refresh_token", + refresh_token: interruptedRotation.refresh_token, + }); + expect(interrupted.status).not.toBe(200); + expect( + await db + .prepare( + "SELECT id FROM oauthRefreshToken WHERE userId = ? AND clientId = ?", + ) + .bind(users[0], client.client_id) + .all(), + ).toMatchObject({ results: [] }); + } finally { + await db.exec("DROP TRIGGER revoke_during_rotation"); + } + await issue(); const inFlight = await authorize(); const workerOrigin = (await mf.ready).origin; const revoke = (cookie: string, requestOrigin = workerOrigin) => @@ -3442,6 +3561,19 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol }); const revoked = await revoke(cookies[0]); expect(revoked.status, await revoked.text()).toBe(200); + expect( + ( + await mf.dispatchFetch(`${origin}/api/mcp-connections`, { + method: "DELETE", + headers: { + cookie: cookies[0], + origin: workerOrigin, + "content-type": "application/json", + }, + body: JSON.stringify({ clientId: "unknown-client" }), + }) + ).status, + ).toBe(200); expect((await mcp(current.access_token)).status).toBe(401); expect( ( @@ -3460,48 +3592,26 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol }) ).status, ).toBe(401); - // Legacy credentials still work and refresh without retroactive consent. - await db - .prepare( - "INSERT INTO oauthAccessToken (id,accessToken,refreshToken,accessTokenExpiresAt,refreshTokenExpiresAt,clientId,userId,scopes,createdAt,updatedAt) VALUES (?,?,?,?,?,?,?,?,?,?)", - ) - .bind( - randomUUID(), - "legacy-oauth-fixture", - "legacy-refresh-fixture", - Date.now() + 60000, - Date.now() + 60000, - client.client_id, - users[0], - "openid offline_access", - Date.now(), - Date.now(), - ) - .run(); - expect((await mcp("legacy-oauth-fixture")).status).toBe(200); - const legacyRefreshed = await tokenRequest({ - grant_type: "refresh_token", - refresh_token: "legacy-refresh-fixture", - }); - expect(legacyRefreshed.status).toBe(200); - // SAFETY: The provider's successful refresh response is exercised as an MCP bearer below. - const legacyCurrent = (await legacyRefreshed.json()) as { - access_token: string; - }; - expect((await mcp(legacyCurrent.access_token)).status).toBe(200); + // The 1.7 reset intentionally invalidates old credentials; agents reconnect. expect((await mcp("legacy-oauth-fixture")).status).toBe(401); - expect((await revoke(cookies[0])).status).toBe(200); - expect((await mcp(legacyCurrent.access_token)).status).toBe(401); + expect( + ( + await tokenRequest({ + grant_type: "refresh_token", + refresh_token: "legacy-refresh-fixture", + }) + ).status, + ).not.toBe(200); // Revoke after the approval reads pending state but before its write. The // provider must not restore consent after that pending state is deleted. const staleConsent = await authorize(); await db - .prepare(`CREATE TRIGGER revoke_during_approval BEFORE UPDATE ON verification + .prepare(`CREATE TRIGGER revoke_during_approval BEFORE DELETE ON verification WHEN OLD.identifier = '${staleConsent}' BEGIN DELETE FROM oauthAccessToken WHERE userId = json_extract(OLD.value, '$.userId') AND clientId = json_extract(OLD.value, '$.clientId'); DELETE FROM oauthConsent WHERE userId = json_extract(OLD.value, '$.userId') AND clientId = json_extract(OLD.value, '$.clientId'); - DELETE FROM verification WHERE identifier = OLD.identifier; + UPDATE mcpGrant SET epoch = epoch + 1 WHERE userId = json_extract(OLD.value, '$.userId') AND clientId = json_extract(OLD.value, '$.clientId'); END`) .run(); try { @@ -3554,19 +3664,21 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol headers: { cookie: cookies[1] }, }); await db - .prepare( - "UPDATE oauthAccessToken SET accessTokenExpiresAt = ? WHERE accessToken = ?", + .prepare("UPDATE oauthAccessToken SET expiresAt = ? WHERE token = ?") + .bind( + "2000-01-01T00:00:00.000Z", + createHash("sha256").update(otherUser.access_token).digest("base64url"), ) - .bind("2000-01-01T00:00:00.000Z", otherUser.access_token) .run(); expect(await (await otherConnections()).json()).toEqual({ connections: [{ clientId: client.client_id, name: "Local OAuth reviewer" }], }); await db - .prepare( - "UPDATE oauthAccessToken SET refreshTokenExpiresAt = ? WHERE accessToken = ?", + .prepare("UPDATE oauthRefreshToken SET expiresAt = ? WHERE token = ?") + .bind( + "2000-01-01T00:00:00.000Z", + createHash("sha256").update(otherUser.refresh_token).digest("base64url"), ) - .bind("2000-01-01T00:00:00.000Z", otherUser.access_token) .run(); expect(await (await otherConnections()).json()).toEqual({ connections: [] }); }); @@ -3586,7 +3698,7 @@ test("API keys enforce MCP permissions, plan gates, capture scope, and live revo params: { name?: string; arguments?: Record } = {}, path = "/mcp", ) => { - const response = await mf.dispatchFetch(`http://fixture${path}`, { + const response = await mf.dispatchFetch(`http://localhost${path}`, { method: "POST", headers: { authorization: `Bearer ${key}`, @@ -3726,10 +3838,13 @@ test("share target: launch hands text over without saving; Add to Today is sessi const userId = `share-${randomUUID()}`; await fixture("seed", { userId, password: await hashPassword(password) }); const signin = await mf.dispatchFetch( - "http://fixture/api/auth/sign-in/email", + "http://localhost/api/auth/sign-in/email", { method: "POST", - headers: { "content-type": "application/json", origin: "http://fixture" }, + headers: { + "content-type": "application/json", + origin: "http://localhost", + }, body: JSON.stringify({ email: `${userId}@capture.test`, password }), }, ); @@ -3746,11 +3861,11 @@ test("share target: launch hands text over without saving; Add to Today is sessi headers: Record, form = new FormData(), ) => { - const encoded = new Request("http://fixture/share", { + const encoded = new Request("http://localhost/share", { method: "POST", body: form, }); - return mf.dispatchFetch("http://fixture/share", { + return mf.dispatchFetch("http://localhost/share", { method: "POST", headers: { cookie, @@ -3778,7 +3893,7 @@ test("share target: launch hands text over without saving; Add to Today is sessi ( await launch({ "sec-fetch-site": "same-origin", - origin: "http://fixture", + origin: "http://localhost", }) ).headers.get("location"), ).toBe("/share#"); @@ -3812,7 +3927,7 @@ test("share target: launch hands text over without saving; Add to Today is sessi headers: Record, body: typeof CaptureBody.Type, ) => - mf.dispatchFetch("http://fixture/api/share", { + mf.dispatchFetch("http://localhost/api/share", { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), @@ -3826,21 +3941,24 @@ test("share target: launch hands text over without saving; Add to Today is sessi expect( ( await add( - { authorization: `Bearer ${key}`, origin: "http://fixture" }, + { authorization: `Bearer ${key}`, origin: "http://localhost" }, payload, ) ).status, ).toBe(401); expect((await api("/api/capture", "", payload)).response.status).toBe(401); - const cookieOnCapture = await mf.dispatchFetch("http://fixture/api/capture", { - method: "POST", - headers: { - cookie, - origin: "http://fixture", - "content-type": "application/json", + const cookieOnCapture = await mf.dispatchFetch( + "http://localhost/api/capture", + { + method: "POST", + headers: { + cookie, + origin: "http://localhost", + "content-type": "application/json", + }, + body: JSON.stringify(payload), }, - body: JSON.stringify(payload), - }); + ); expect(cookieOnCapture.status).toBe(401); // The session still needs this server's Origin. const foreign = await add({ cookie, origin: "https://evil.test" }, payload); @@ -3849,7 +3967,7 @@ test("share target: launch hands text over without saving; Add to Today is sessi (await fixture("inspect", { userId })).snapshot.nodes, ).toEqual([]); - const saved = await add({ cookie, origin: "http://fixture" }, payload); + const saved = await add({ cookie, origin: "http://localhost" }, payload); expect(saved.status).toBe(200); // SAFETY: a 200 from /api/share is the capture receipt (worker/capture.ts). const receipt = (await saved.json()) as CaptureReceipt & { @@ -3860,7 +3978,7 @@ test("share target: launch hands text over without saving; Add to Today is sessi date: "2026-11-13", replayed: false, }); - const replay = await add({ cookie, origin: "http://fixture" }, payload); + const replay = await add({ cookie, origin: "http://localhost" }, payload); expect(await replay.json()).toEqual({ ...receipt, replayed: true }); const { snapshot } = await fixture("inspect", { userId }); const task = snapshot.nodes.find((node) => node.id === receipt.nodeId)!; diff --git a/worker/index.ts b/worker/index.ts index 90d2f3c3..016d965a 100644 --- a/worker/index.ts +++ b/worker/index.ts @@ -25,8 +25,12 @@ * unambiguous 500s without collapsing known validation errors into the same bucket. */ +import { + oauthProviderAuthServerMetadata, + type AuthServerMetadata, + type ResourceServerMetadata, +} from "@better-auth/oauth-provider"; import * as Sentry from "@sentry/cloudflare"; -import { oAuthDiscoveryMetadata } from "better-auth/plugins"; import { Data, Effect, Schema } from "effect"; import type { KvClaim, WeekStartMigrationResult } from "./outline-do"; @@ -74,6 +78,7 @@ import { } from "./invites"; import { handleMcp, mcpCorsPreflight } from "./mcp"; import { handleMcpConnections, readMcpConsent } from "./mcp-oauth"; +import { handleMcpAuthRequest } from "./mcp-provider"; import { acknowledgeWelcome, canSaveTheme, readMembership } from "./membership"; import { legacyNumberedNode } from "./numbered-compat"; import { UserOutlineDO as BaseUserOutlineDO } from "./outline-do"; @@ -901,7 +906,9 @@ function handleApiRequest( // Better Auth owns everything under /api/auth/* (sign-up/in/out, session, // and — via the mcp plugin — the OAuth authorize/token/register endpoints). if (url.pathname.startsWith("/api/auth/")) { - return yield* Effect.promise(() => auth.handler(request)); + return yield* Effect.promise(() => + handleMcpAuthRequest(auth, request, env.DB), + ); } // Public signup config (#293): the SPA reads whether signup is OPEN (hide @@ -1548,7 +1555,20 @@ const handler = { // Keep the root discovery URL for existing connectors, plus path-aware // documents whose resource exactly matches the canonical endpoint or alias. if (url.pathname.startsWith("/.well-known/oauth-authorization-server")) { - return oAuthDiscoveryMetadata(createAuth(env, url.origin))(request); + const response = await oauthProviderAuthServerMetadata( + createAuth(env, url.origin), + )(request); + const metadata = await response.json(); + const origin = new URL(env.BETTER_AUTH_URL ?? url.origin).origin; + return Response.json( + { + ...metadata, + authorization_endpoint: `${origin}/api/auth/mcp/authorize`, + token_endpoint: `${origin}/api/auth/mcp/token`, + registration_endpoint: `${origin}/api/auth/mcp/register`, + }, + { headers: response.headers }, + ); } if (url.pathname.startsWith("/.well-known/oauth-protected-resource")) { const suffix = url.pathname.slice( @@ -1556,10 +1576,18 @@ const handler = { ); if (!["", "/mcp", "/api/mcp"].includes(suffix)) return new Response(null, { status: 404 }); - const metadata = await createAuth( - env, - url.origin, - ).api.getMCPProtectedResource({ request, asResponse: false }); + if (!["GET", "HEAD"].includes(request.method)) + return new Response(null, { + status: 405, + headers: { allow: "GET, HEAD" }, + }); + const response = await createAuth(env, url.origin).handler( + new Request(new URL("/.well-known/oauth-protected-resource", url), { + method: "GET", + headers: request.headers, + }), + ); + const metadata = await response.json(); return Response.json( { ...metadata, diff --git a/worker/mcp-migration.test.ts b/worker/mcp-migration.test.ts new file mode 100644 index 00000000..83cd7b18 --- /dev/null +++ b/worker/mcp-migration.test.ts @@ -0,0 +1,57 @@ +import { Database } from "bun:sqlite"; +import { expect, test } from "bun:test"; +import { readFile } from "node:fs/promises"; + +test("the 1.7 reset invalidates legacy OAuth credentials but preserves identity and non-OAuth verification", async () => { + const db = new Database(":memory:"); + try { + db.exec("PRAGMA foreign_keys = ON"); + for (const name of ["0003_create_auth.sql", "0004_create_oauth.sql"]) + db.exec(await readFile(`migrations/${name}`, "utf8")); + db.exec(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt) VALUES ('owner', 'Owner', 'owner@example.com', 1, '2026-01-01', '2026-01-01'); + INSERT INTO oauthApplication (id, name, clientId, redirectUrls, type, createdAt, updatedAt) VALUES ('app', 'App', 'old-client', 'https://client.example/callback', 'public', '2026-01-01', '2026-01-01'); + INSERT INTO oauthAccessToken (id, accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt, clientId, userId, scopes, createdAt, updatedAt) VALUES ('token', 'plaintext-access', 'plaintext-refresh', '2030-01-01', '2030-01-01', 'old-client', 'owner', 'openid', '2026-01-01', '2026-01-01'); + INSERT INTO session (id, expiresAt, token, createdAt, updatedAt, userId) VALUES ('session', '2030-01-01', 'browser-session', '2026-01-01', '2026-01-01', 'owner'); + INSERT INTO verification (id, identifier, value, expiresAt, createdAt, updatedAt) VALUES ('pending', 'consent-code', '{"clientId":"old-client","userId":"owner"}', '2030-01-01', '2026-01-01', '2026-01-01'), ('email', 'email-verification', 'owner', '2030-01-01', '2026-01-01', '2026-01-01');`); + db.exec(await readFile("migrations/0023_better_auth_1_7.sql", "utf8")); + expect(db.query("SELECT id FROM user").all()).toEqual([{ id: "owner" }]); + expect(db.query("SELECT token FROM session").all()).toEqual([ + { token: "browser-session" }, + ]); + expect(db.query("SELECT id FROM verification").all()).toEqual([ + { id: "email" }, + ]); + expect( + db + .query("SELECT name FROM sqlite_master WHERE name = 'oauthApplication'") + .all(), + ).toEqual([]); + for (const table of [ + "oauthClient", + "oauthAccessToken", + "oauthRefreshToken", + "oauthConsent", + "oauthResource", + "oauthClientResource", + "oauthClientAssertion", + "mcpGrant", + ]) + expect(db.query(`SELECT * FROM ${table}`).all()).toEqual([]); + expect(db.query("PRAGMA foreign_key_check").all()).toEqual([]); + db.exec(`INSERT INTO oauthClient (id, clientId, redirectUris, userId) VALUES ('client', 'new-client', '["https://client.example/callback"]', 'owner'); + INSERT INTO oauthRefreshToken (id, token, clientId, userId, expiresAt, createdAt, scopes) VALUES ('refresh', 'hash-refresh', 'new-client', 'owner', '2030-01-01', '2026-01-01', '["offline_access"]'); + INSERT INTO oauthAccessToken (id, token, clientId, userId, refreshId, expiresAt, createdAt, scopes) VALUES ('access', 'hash-access', 'new-client', 'owner', 'refresh', '2030-01-01', '2026-01-01', '["offline_access"]'); + DELETE FROM user WHERE id = 'owner';`); + for (const table of [ + "oauthClient", + "oauthRefreshToken", + "oauthAccessToken", + "mcpGrant", + "session", + ]) + expect(db.query(`SELECT * FROM ${table}`).all()).toEqual([]); + expect(db.query("PRAGMA foreign_key_check").all()).toEqual([]); + } finally { + db.close(); + } +}); diff --git a/worker/mcp-oauth.ts b/worker/mcp-oauth.ts index 2a8179d0..c56b3a12 100644 --- a/worker/mcp-oauth.ts +++ b/worker/mcp-oauth.ts @@ -1,6 +1,24 @@ /// import { Effect, Schema } from "effect"; +export async function grantEpoch( + db: D1Database, + userId: string, + clientId: string, +) { + await db + .prepare( + "INSERT INTO mcpGrant (userId, clientId, epoch) VALUES (?, ?, 0) ON CONFLICT DO NOTHING", + ) + .bind(userId, clientId) + .run(); + const row = await db + .prepare("SELECT epoch FROM mcpGrant WHERE userId = ? AND clientId = ?") + .bind(userId, clientId) + .first<{ epoch: number }>(); + return row?.epoch ?? -1; +} + const ConsentValue = Schema.Struct({ userId: Schema.String, clientId: Schema.String, @@ -8,6 +26,8 @@ const ConsentValue = Schema.Struct({ requireConsent: Schema.Boolean, scope: Schema.Array(Schema.String), state: Schema.optionalKey(Schema.NullOr(Schema.String)), + oauthQuery: Schema.String, + epoch: Schema.Number, }); /** Read provider-owned state, never client-supplied names, scopes or redirects. */ @@ -31,11 +51,19 @@ export async function readMcpConsent( if (!value.requireConsent || value.userId !== userId) return null; const client = await db .prepare( - "SELECT name, redirectUrls FROM oauthApplication WHERE clientId = ? AND (disabled IS NULL OR disabled = 0)", + "SELECT name, redirectUris FROM oauthClient WHERE clientId = ? AND (disabled IS NULL OR disabled = 0)", ) .bind(value.clientId) - .first<{ name: string; redirectUrls: string }>(); - if (!client || !client.redirectUrls.split(",").includes(value.redirectURI)) + .first<{ name: string; redirectUris: string }>(); + if (!client) return null; + const redirects = Schema.decodeUnknownResult( + Schema.fromJsonString(Schema.Array(Schema.String)), + )(client.redirectUris); + if ( + redirects._tag === "Failure" || + !redirects.success.includes(value.redirectURI) || + value.epoch !== (await grantEpoch(db, userId, value.clientId)) + ) return null; return { ...value, name: client.name }; } @@ -58,12 +86,17 @@ export function handleMcpConnections( const clients = yield* Effect.promise(() => db .prepare(` - SELECT DISTINCT a.clientId, a.name FROM oauthApplication a - INNER JOIN oauthAccessToken t ON t.clientId = a.clientId - WHERE t.userId = ? AND (t.accessTokenExpiresAt > ? OR t.refreshTokenExpiresAt > ?) + SELECT DISTINCT a.clientId, a.name FROM oauthClient a + WHERE EXISTS (SELECT 1 FROM oauthAccessToken t WHERE t.clientId = a.clientId AND t.userId = ? AND t.expiresAt > ? AND t.revoked IS NULL) + OR EXISTS (SELECT 1 FROM oauthRefreshToken r WHERE r.clientId = a.clientId AND r.userId = ? AND r.expiresAt > ? AND r.revoked IS NULL) ORDER BY a.name, a.clientId `) - .bind(userId, new Date().toISOString(), new Date().toISOString()) + .bind( + userId, + new Date().toISOString(), + userId, + new Date().toISOString(), + ) .all<{ clientId: string; name: string }>(), ); return reply({ connections: clients.results }); @@ -84,17 +117,27 @@ export function handleMcpConnections( // registration or other users. Pending codes must not resurrect access. yield* Effect.promise(() => db.batch([ + db + .prepare( + "INSERT INTO mcpGrant (userId, clientId, epoch) SELECT ?, ?, 1 WHERE EXISTS (SELECT 1 FROM oauthClient WHERE clientId = ?) ON CONFLICT(userId, clientId) DO UPDATE SET epoch = epoch + 1", + ) + .bind(userId, clientId, clientId), db .prepare( "DELETE FROM oauthAccessToken WHERE userId = ? AND clientId = ?", ) .bind(userId, clientId), + db + .prepare( + "DELETE FROM oauthRefreshToken WHERE userId = ? AND clientId = ?", + ) + .bind(userId, clientId), db .prepare("DELETE FROM oauthConsent WHERE userId = ? AND clientId = ?") .bind(userId, clientId), db .prepare( - `DELETE FROM verification WHERE json_valid(value) AND json_extract(value, '$.userId') = ? AND json_extract(value, '$.clientId') = ?`, + `DELETE FROM verification WHERE json_valid(value) AND json_extract(value, '$.userId') = ? AND COALESCE(json_extract(value, '$.clientId'), json_extract(value, '$.query.client_id')) = ?`, ) .bind(userId, clientId), ]), diff --git a/worker/mcp-provider.ts b/worker/mcp-provider.ts new file mode 100644 index 00000000..0d7cfd0b --- /dev/null +++ b/worker/mcp-provider.ts @@ -0,0 +1,351 @@ +/// +import { mcp } from "@better-auth/mcp"; +import { + getOAuthProviderApi, + verifyOAuthQueryParams, +} from "@better-auth/oauth-provider"; +import { createAuthEndpoint, isAPIError } from "better-auth/api"; +import { Schema } from "effect"; + +import type { Auth } from "./auth"; + +import { grantEpoch, readMcpConsent } from "./mcp-oauth"; + +export async function hashOAuthToken(token: string) { + const bytes = new Uint8Array( + await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)), + ); + return btoa(String.fromCharCode(...bytes)) + .replaceAll("+", "-") + .replaceAll("/", "_") + .replace(/=+$/, ""); +} + +export function mcpProvider(resource: string) { + const options = { + resource, + loginPage: "/", + consentPage: "/mcp-consent", + disableJwtPlugin: true, + refreshTokenReuseInterval: 0, + allowDynamicClientRegistration: true, + allowUnauthenticatedClientRegistration: true, + clientRegistrationDefaultApplicationType: "infer", + grantTypes: ["authorization_code", "refresh_token"], + scopes: ["openid", "profile", "email", "offline_access"], + clientRegistrationDefaultScopes: [ + "openid", + "profile", + "email", + "offline_access", + ], + storeTokens: { hash: hashOAuthToken }, + } satisfies Parameters[0]; + const provider = mcp(options); + return { + ...provider, + endpoints: { + ...provider.endpoints, + getMcpSession: createAuthEndpoint( + "/mcp/get-session", + { method: "GET" }, + async (ctx) => { + const match = ctx.headers + ?.get("authorization") + ?.match(/^Bearer ([^\s]+)$/i); + if (!match) return null; + try { + const payload = await getOAuthProviderApi( + ctx, + options, + ).requireActiveAccessToken(match[1]!); + const audiences = Array.isArray(payload.aud) + ? payload.aud + : [payload.aud]; + if (!payload.sub || payload.cnf || !audiences.includes(resource)) + return null; + return { userId: payload.sub }; + } catch (error) { + if (isAPIError(error) && error.statusCode === 401) return null; + throw error; + } + }, + ), + }, + }; +} + +const oauthError = (error: string, status = 401) => + Response.json( + { error }, + { status, headers: { "cache-control": "no-store" } }, + ); +const ConsentBody = Schema.Struct({ + consent_code: Schema.String, + accept: Schema.Boolean, +}); +const ProviderRedirect = Schema.Struct({ url: Schema.String }); +const TokenResponse = Schema.Struct({ + access_token: Schema.String, + refresh_token: Schema.optionalKey(Schema.String), +}); +const CodeValue = Schema.Struct({ + userId: Schema.String, + query: Schema.Struct({ client_id: Schema.String }), + mcpEpoch: Schema.Number, +}); + +/** The provider owns OAuth; this boundary preserves public paths and D1 revocation ordering. */ +export async function handleMcpAuthRequest( + auth: Auth, + request: Request, + db: D1Database, +) { + const url = new URL(request.url); + url.pathname = url.pathname.replace( + /^\/api\/auth\/mcp\/(authorize|token|register)$/, + "/api/auth/oauth2/$1", + ); + const path = url.pathname; + if (!path.startsWith("/api/auth/oauth2/")) return auth.handler(request); + const session = () => auth.api.getSession({ headers: request.headers }); + const context = await auth.$context; + const secret = context.secret; + const resource = `${new URL(context.baseURL).origin}/mcp`; + const normalizeResources = (params: URLSearchParams) => { + const accepted = [ + new URL(resource).origin, + resource, + `${new URL(resource).origin}/api/mcp`, + ]; + if (params.getAll("resource").some((value) => !accepted.includes(value))) + return false; + params.set("resource", resource); + return true; + }; + if (path === "/api/auth/oauth2/authorize") { + if (!normalizeResources(url.searchParams)) + return oauthError("invalid_target", 400); + url.searchParams.set("prompt", "consent"); + const response = await auth.handler(new Request(url, request)); + const location = response.headers.get("location"); + if (!location) return response; + const target = new URL(location, resource); + if ( + target.pathname !== "/mcp-consent" || + target.origin !== new URL(resource).origin + ) + return response; + const identity = await session(); + if ( + !identity || + !(await verifyOAuthQueryParams(target.search.slice(1), secret)) + ) + return oauthError("invalid_request"); + const clientId = target.searchParams.get("client_id"); + const redirectURI = target.searchParams.get("redirect_uri"); + if (!clientId || !redirectURI) return oauthError("invalid_request"); + const code = crypto.randomUUID(); + const now = new Date().toISOString(); + const value = { + userId: identity.user.id, + clientId, + redirectURI, + requireConsent: true, + scope: (target.searchParams.get("scope") ?? "") + .split(" ") + .filter(Boolean), + state: target.searchParams.get("state"), + oauthQuery: target.search.slice(1), + epoch: await grantEpoch(db, identity.user.id, clientId), + }; + await db + .prepare( + "INSERT INTO verification (id, identifier, value, expiresAt, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind( + crypto.randomUUID(), + code, + JSON.stringify(value), + new Date(Date.now() + 600_000).toISOString(), + now, + now, + ) + .run(); + target.search = new URLSearchParams({ consent_code: code }).toString(); + const headers = new Headers(response.headers); + headers.set("location", target.toString()); + headers.set("cache-control", "no-store"); + return new Response(null, { status: response.status, headers }); + } + if (path === "/api/auth/oauth2/consent") { + if ( + request.method !== "POST" || + request.headers.get("origin") !== new URL(resource).origin + ) + return oauthError("invalid_origin", 403); + const body = Schema.decodeUnknownResult(ConsentBody)( + await request.json().catch(() => null), + ); + const identity = await session(); + if (body._tag === "Failure" || !identity) + return oauthError("invalid_request", 403); + const consent = await readMcpConsent( + db, + identity.user.id, + body.success.consent_code, + ); + if (!consent) return oauthError("invalid_request", 403); + const consumed = await db + .prepare( + "DELETE FROM verification WHERE identifier = ? AND json_extract(value, '$.userId') = ? RETURNING id", + ) + .bind(body.success.consent_code, identity.user.id) + .first(); + if (!consumed) return oauthError("invalid_request", 403); + const response = await auth.handler( + new Request(url, { + method: "POST", + headers: request.headers, + body: JSON.stringify({ + accept: body.success.accept, + oauth_query: consent.oauthQuery, + }), + }), + ); + if (!response.ok) return response; + const redirect = Schema.decodeUnknownResult(ProviderRedirect)( + await response.json(), + ); + if (redirect._tag === "Failure") return oauthError("invalid_request"); + const target = new URL(redirect.success.url, url); + const code = target.searchParams.get("code"); + const identifier = code ? await hashOAuthToken(code) : ""; + const currentEpoch = await grantEpoch( + db, + identity.user.id, + consent.clientId, + ); + const updated = + code && currentEpoch === consent.epoch + ? await db + .prepare( + "UPDATE verification SET value = json_set(value, '$.mcpEpoch', ?) WHERE identifier = ? AND EXISTS (SELECT 1 FROM mcpGrant WHERE userId = ? AND clientId = ? AND epoch = ?)", + ) + .bind( + consent.epoch, + identifier, + identity.user.id, + consent.clientId, + consent.epoch, + ) + .run() + : null; + if (body.success.accept && (!code || updated?.meta.changes !== 1)) { + await db.batch([ + db + .prepare("DELETE FROM verification WHERE identifier = ?") + .bind(identifier), + db + .prepare("DELETE FROM oauthConsent WHERE userId = ? AND clientId = ?") + .bind(identity.user.id, consent.clientId), + ]); + return oauthError("invalid_grant", 403); + } + return Response.json( + { redirectURI: target.toString() }, + { headers: { "cache-control": "no-store" } }, + ); + } + if (path === "/api/auth/oauth2/token" && request.method === "POST") { + if ( + !request.headers + .get("content-type") + ?.startsWith("application/x-www-form-urlencoded") + ) + return oauthError("invalid_request", 400); + const params = new URLSearchParams(await request.text()); + if (!normalizeResources(params)) return oauthError("invalid_target", 400); + const isRefresh = params.get("grant_type") === "refresh_token"; + const credential = params.get(isRefresh ? "refresh_token" : "code"); + if (!credential) return oauthError("invalid_grant"); + let userId: string; + let clientId: string; + let epoch: number; + let refreshId: string | null = null; + if (isRefresh) { + const row = await db + .prepare( + "SELECT id, userId, clientId FROM oauthRefreshToken WHERE token = ?", + ) + .bind(await hashOAuthToken(credential)) + .first<{ id: string; userId: string; clientId: string }>(); + if (!row) return oauthError("invalid_grant"); + ({ userId, clientId } = row); + refreshId = row.id; + epoch = await grantEpoch(db, userId, clientId); + } else { + const row = await db + .prepare("SELECT value FROM verification WHERE identifier = ?") + .bind(await hashOAuthToken(credential)) + .first<{ value: string }>(); + const parsed = Schema.decodeUnknownResult( + Schema.fromJsonString(CodeValue), + )(row?.value); + if (parsed._tag === "Failure") { + if (!row) + await auth.handler( + new Request(url, { + method: "POST", + headers: request.headers, + body: params.toString(), + }), + ); + return oauthError("invalid_grant"); + } + userId = parsed.success.userId; + clientId = parsed.success.query.client_id; + epoch = parsed.success.mcpEpoch; + } + const response = await auth.handler( + new Request(url, { + method: "POST", + headers: request.headers, + body: params.toString(), + }), + ); + if (!response.ok) return response; + const parsed = Schema.decodeUnknownResult(TokenResponse)( + await response.clone().json(), + ); + if (parsed._tag === "Failure") return oauthError("invalid_grant"); + const accessHash = await hashOAuthToken(parsed.success.access_token); + const refreshHash = parsed.success.refresh_token + ? await hashOAuthToken(parsed.success.refresh_token) + : ""; + if (refreshId) + await db + .prepare("DELETE FROM oauthAccessToken WHERE refreshId = ?") + .bind(refreshId) + .run(); + const valid = await db + .prepare(`SELECT 1 FROM mcpGrant g WHERE g.userId = ? AND g.clientId = ? AND g.epoch = ? + AND EXISTS (SELECT 1 FROM oauthConsent c WHERE c.userId = g.userId AND c.clientId = g.clientId) + AND (? IS NULL OR EXISTS (SELECT 1 FROM oauthRefreshToken WHERE id = ? AND revoked IS NOT NULL))`) + .bind(userId, clientId, epoch, refreshId, refreshId) + .first(); + if (!valid) { + await db.batch([ + db + .prepare("DELETE FROM oauthAccessToken WHERE token = ?") + .bind(accessHash), + db + .prepare("DELETE FROM oauthRefreshToken WHERE token = ?") + .bind(refreshHash), + ]); + return oauthError("invalid_grant"); + } + return response; + } + return auth.handler(new Request(url, request)); +} diff --git a/worker/membership.test.ts b/worker/membership.test.ts index ab008815..eedc0b40 100644 --- a/worker/membership.test.ts +++ b/worker/membership.test.ts @@ -66,7 +66,7 @@ beforeAll(async () => { type: "text", value: "disposable-membership-test-secret", }, - BETTER_AUTH_URL: { type: "text", value: "http://fixture" }, + BETTER_AUTH_URL: { type: "text", value: "http://localhost" }, SIGNUP_OPEN: { type: "text", value: "true" }, }, }, @@ -77,6 +77,7 @@ beforeAll(async () => { for (const migration of [ "0003_create_auth.sql", "0004_create_oauth.sql", + "0023_better_auth_1_7.sql", "0006_create_stripe.sql", "0017_membership_welcome.sql", "0021_pro_trial_checkout.sql", @@ -95,11 +96,11 @@ afterAll(async () => { test("membership reads retain typed storage failures, GET sanitizes them to 503, and projection defects remain 500", async () => { const authRequest = (action: string) => - mf.dispatchFetch(`http://fixture/api/auth/${action}/email`, { + mf.dispatchFetch(`http://localhost/api/auth/${action}/email`, { method: "POST", headers: { "content-type": "application/json", - origin: "http://fixture", + origin: "http://localhost", }, body: JSON.stringify({ name: "Member", @@ -118,7 +119,7 @@ test("membership reads retain typed storage failures, GET sanitizes them to 503, .join("; "); expect(cookie).not.toBe(""); const membership = (query?: string, mode = "throw") => - mf.dispatchFetch("http://fixture/api/membership", { + mf.dispatchFetch("http://localhost/api/membership", { headers: query ? { cookie, "x-fail-query": query, "x-fail-mode": mode } : { cookie }, @@ -146,7 +147,7 @@ test("membership reads retain typed storage failures, GET sanitizes them to 503, ]) { for (const mode of ["throw", "reject"]) { const typed = await mf.dispatchFetch( - "http://fixture/__membership-result", + "http://localhost/__membership-result", { headers: { "x-fail-query": query, "x-fail-mode": mode }, }, From 5114c09cd93a5d6952f0c4ed27640c2b7c849e0c Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:08:00 +0000 Subject: [PATCH 2/5] Keep local Worker auth origins on localhost Co-Authored-By: Cameron Pak --- .dev.vars.example | 12 +----- CONTRIBUTING.md | 19 +++++----- docs/adr/0026-agent-native-mcp-server.md | 7 ++++ package.json | 2 +- scripts/cf-dev.ts | 15 +++++++- worker/auth-real.test.ts | 28 ++++++++++++++ worker/cf-dev.test.ts | 48 ++++++++++++++++++++++++ 7 files changed, 109 insertions(+), 22 deletions(-) create mode 100644 worker/cf-dev.test.ts diff --git a/.dev.vars.example b/.dev.vars.example index 2f7d1536..eaf85b32 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -35,18 +35,10 @@ INVITE_CODES=dev-invite # STRIPE_WEBHOOK_SECRET=whsec_replace-me # Optional: pin the OAuth issuer the MCP discovery metadata advertises (ADR -# 0026). Needed to test the MCP OAuth flow against `wrangler dev` — without it -# the dev proxy's custom-domain simulation makes the inferred origin the prod -# domain. In prod set the real origin via BETTER_AUTH_URL. +# 0026). cf:dev and dev:api already infer localhost without an override. In prod +# set the real HTTPS origin via BETTER_AUTH_URL. # BETTER_AUTH_URL=http://localhost:8787 -# Optional companion to the above: the same custom-domain simulation also -# rewrites the request Origin header to the prod domain, so Better Auth's CSRF -# check rejects local sign-in unless that origin is trusted. Set this to make -# the OAuth login flow work under `wrangler dev`. Local-only; in prod the origin -# IS the prod domain and is already trusted via BETTER_AUTH_URL. -# BETTER_AUTH_TRUSTED_ORIGINS=http://app.dotflowy.com,https://app.dotflowy.com - # Optional: Google OAuth client for "Sign in with Google" (Google Cloud console # -> Credentials -> OAuth client ID, type "Web application"). Local redirect # URI: http://localhost:3000/api/auth/callback/google. Unset = the provider diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a2ac6eb..3c3ff5bf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -161,20 +161,19 @@ approved owner-only exception; Amp enablement and deployment remain separate. ### Testing the MCP OAuth flow locally -The MCP endpoint (`/mcp`) is OAuth-gated, and testing it against `wrangler dev` -has one gotcha: the dev proxy simulates the production custom domain, so it -rewrites both the inferred issuer **and** the request `Origin` to -`app.dotflowy.com`. Two local-only vars in `.dev.vars` make the flow work (both -are documented in `.dev.vars.example`): +The MCP endpoint (`/mcp`) is OAuth-gated. `bun run cf:dev` and `bun run dev:api` +keep Wrangler's upstream URL and request `Origin` on localhost, so auth and +discovery work without a `BETTER_AUTH_URL` override. When invoking Wrangler +directly, use the same local routing flags: ```sh -BETTER_AUTH_URL=http://localhost:8787 -BETTER_AUTH_TRUSTED_ORIGINS=http://app.dotflowy.com,https://app.dotflowy.com +bunx wrangler dev --port 8787 --local-upstream localhost:8787 --upstream-protocol http ``` -Without the first, discovery points MCP clients at the prod domain; without the -second, Better Auth's CSRF check rejects local sign-in with `403 Invalid origin`. -Neither is needed in prod (there the origin genuinely _is_ the prod domain). See +Without these flags, Wrangler simulates the production custom domain over HTTP, +which the MCP provider correctly rejects. Pinning only `BETTER_AUTH_URL` leaves +the rewritten `Origin` mismatched and can fail the CSRF check. Production still +requires HTTPS; do not broaden trusted origins to work around local routing. See [ADR 0026](./docs/adr/0026-agent-native-mcp-server.md). ### Testing Stripe billing locally diff --git a/docs/adr/0026-agent-native-mcp-server.md b/docs/adr/0026-agent-native-mcp-server.md index b1efc24c..ceda8814 100644 --- a/docs/adr/0026-agent-native-mcp-server.md +++ b/docs/adr/0026-agent-native-mcp-server.md @@ -211,6 +211,13 @@ The provider's active-token validator checks stored expiry/revocation and the MCP audience; proof-bound tokens are not accepted as unbound Bearer tokens. The resulting stable user id still passes through `resolveUserId`. +Local `cf:dev` and `dev:api` explicitly use Wrangler's localhost HTTP upstream, +so both the inferred issuer and browser Origin stay local. The 1.7 MCP provider +rejects HTTP custom-domain resources at construction; the legacy plugin did not. +Pinning only the auth base URL cannot fix a separately rewritten Origin. Keep +production HTTPS validation and CSRF checks unchanged rather than trusting the +simulated production origin locally. + Explicit consent remains account-bound and required on every authorization. The compatibility boundary keeps a short-lived, single-use opaque consent code in D1, bound to the server session's user and the provider-signed OAuth query. diff --git a/package.json b/package.json index de68e223..a6656e34 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "bootstrap": "bun scripts/bootstrap.ts", "dev": "bun scripts/dev.ts", "dev:web": "vite dev", - "dev:api": "wrangler dev --port 8787", + "dev:api": "wrangler dev --port 8787 --local-upstream localhost:8787 --upstream-protocol http", "build": "bun scripts/heavy-lane.ts vite build", "build:cli": "bun scripts/heavy-lane.ts bun run --cwd cli build", "typecheck:cli": "bun scripts/heavy-lane.ts bun run --cwd cli typecheck", diff --git a/scripts/cf-dev.ts b/scripts/cf-dev.ts index 91150214..69f818a4 100644 --- a/scripts/cf-dev.ts +++ b/scripts/cf-dev.ts @@ -61,9 +61,22 @@ if (!ok) { // 2. wrangler dev (Worker + per-user DO + serves dist/client live). log("starting wrangler dev on :8787"); +// Keep URL and Origin local instead of simulating the production custom domain. // `--var SENTRY_DSN:` blanks the committed DSN so the local Worker stays silent. const wrangler = Bun.spawn( - ["bunx", "wrangler", "dev", "--port", "8787", "--var", "SENTRY_DSN:"], + [ + "bunx", + "wrangler", + "dev", + "--port", + "8787", + "--local-upstream", + "localhost:8787", + "--upstream-protocol", + "http", + "--var", + "SENTRY_DSN:", + ], { cwd: ROOT, stdio: ["inherit", "inherit", "inherit"], diff --git a/worker/auth-real.test.ts b/worker/auth-real.test.ts index c72899b4..147da898 100644 --- a/worker/auth-real.test.ts +++ b/worker/auth-real.test.ts @@ -24,6 +24,14 @@ beforeAll(async () => { const url = new URL(request.url); if (url.pathname === "/__fixture/email") return Response.json(mail.get(url.searchParams.get("to")) ?? null); + if (url.pathname === "/__fixture/unpinned-auth") { + try { + return createAuth({ ...env, BETTER_AUTH_URL: undefined }, request.headers.get("x-fixture-upstream") ?? url.origin, ctx) + .handler(new Request(new URL("/api/auth/get-session", url), request)); + } catch (error) { + return Response.json({ error: error.message }, { status: 400 }); + } + } const mode = request.headers.get("x-fixture-signup-mode"); return createAuth({ ...env, EMAIL: { async send(message) { mail.set(message.to, message.text); return { messageId: "fixture-only" }; } }, @@ -141,6 +149,26 @@ afterAll(async () => { if (directory) await rm(directory, { recursive: true, force: true }); }); +test("unpinned auth accepts local upstream and HTTPS deployments, not HTTP custom domains", async () => { + for (const origin of ["http://localhost:8787", "https://app.dotflowy.com"]) { + const response = await mf.dispatchFetch( + "http://localhost/__fixture/unpinned-auth", + { headers: { "x-fixture-upstream": origin } }, + ); + expect(response.status).toBe(200); + expect(await response.json()).toBeNull(); + } + const insecure = await mf.dispatchFetch( + "http://localhost/__fixture/unpinned-auth", + { headers: { "x-fixture-upstream": "http://app.dotflowy.com" } }, + ); + expect(insecure.status).toBe(400); + expect(await insecure.json()).toEqual({ + error: + "MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs", + }); +}); + async function request( mode: string, path: string, diff --git a/worker/cf-dev.test.ts b/worker/cf-dev.test.ts new file mode 100644 index 00000000..c3dd4da1 --- /dev/null +++ b/worker/cf-dev.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { delimiter, join } from "node:path"; + +test("local launchers keep Wrangler URL and Origin on localhost", async () => { + const directory = await mkdtemp(join(tmpdir(), "dotflowy-cf-dev-")); + try { + for (const command of ["bun", "bunx"]) + await writeFile( + join(directory, command), + `#!${process.execPath}\nconsole.log(JSON.stringify(process.argv.slice(2)));\n`, + { mode: 0o755 }, + ); + const proc = Bun.spawn([process.execPath, "scripts/cf-dev.ts"], { + env: { + ...process.env, + PATH: `${directory}${delimiter}${process.env.PATH}`, + }, + stdout: "pipe", + stderr: "pipe", + }); + const output = await new Response(proc.stdout).text(); + expect(await proc.exited, await new Response(proc.stderr).text()).toBe(0); + const commands = output + .split("\n") + .filter((line) => line.startsWith('["')) + .map((line) => JSON.parse(line)); + expect(commands).toContainEqual([ + "wrangler", + "dev", + "--port", + "8787", + "--local-upstream", + "localhost:8787", + "--upstream-protocol", + "http", + "--var", + "SENTRY_DSN:", + ]); + const manifest = await Bun.file("package.json").json(); + expect(manifest.scripts["dev:api"]).toBe( + "wrangler dev --port 8787 --local-upstream localhost:8787 --upstream-protocol http", + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); From f235de2d97ee53bc1f14762cee6438c3f35d7243 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:30:32 +0000 Subject: [PATCH 3/5] Clarify one-time OAuth reconnect instructions Co-Authored-By: Cameron Pak --- .changeset/steady-agent-authentication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/steady-agent-authentication.md b/.changeset/steady-agent-authentication.md index 8a72fa37..4a3bca36 100644 --- a/.changeset/steady-agent-authentication.md +++ b/.changeset/steady-agent-authentication.md @@ -2,4 +2,4 @@ "dotflowy": patch --- -Keeps Dotflowy's authentication infrastructure up to date. Connected AI agents may need to reconnect once. +Please sign in again once to your Dotflowy OAuth connections: reconnect MCP connectors in AI apps such as Claude, ChatGPT, and Cursor, and run `dotflowy login` for the Dotflowy CLI. Your outlines, browser sessions, and API keys are unchanged. From 4f82fefb861b691990dacc1bc2bc3eac66f883c6 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:36:55 +0000 Subject: [PATCH 4/5] Explain how to reconnect on MCP authentication failures Co-Authored-By: Cameron Pak --- docs/adr/0026-agent-native-mcp-server.md | 7 ++++ docs/mcp.md | 8 +++++ worker/capture-real.test.ts | 45 ++++++++++++++++++------ worker/index.ts | 23 +++++++----- 4 files changed, 64 insertions(+), 19 deletions(-) diff --git a/docs/adr/0026-agent-native-mcp-server.md b/docs/adr/0026-agent-native-mcp-server.md index ceda8814..f4b04a7f 100644 --- a/docs/adr/0026-agent-native-mcp-server.md +++ b/docs/adr/0026-agent-native-mcp-server.md @@ -211,6 +211,13 @@ The provider's active-token validator checks stored expiry/revocation and the MCP audience; proof-bound tokens are not accepted as unbound Bearer tokens. The resulting stable user id still passes through `resolveUserId`. +Missing or invalid MCP credentials return HTTP 401 with the existing +`WWW-Authenticate` resource-metadata challenge and CORS headers. The JSON body +contains `error: "unauthorized"` and a uniform `error_description` directing +users to reconnect in their AI app's connector settings or run `dotflowy login`. +It does not identify reset tokens or return a JSON-RPC success. Clients may +ignore the description; discovery and reauthorization still use the challenge. + Local `cf:dev` and `dev:api` explicitly use Wrangler's localhost HTTP upstream, so both the inferred issuer and browser Origin stay local. The 1.7 MCP provider rejects HTTP custom-domain resources at construction; the legacy plugin did not. diff --git a/docs/mcp.md b/docs/mcp.md index 968bfc8e..41f95e89 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -48,6 +48,14 @@ authentication infrastructure to Better Auth 1.7. Existing OAuth credentials are reset; personal API keys and browser sessions are unaffected. Use the same MCP URL and sign in again (CLI: `dotflowy login`). +Missing or invalid credentials on `/mcp` and `/api/mcp` return HTTP 401 with +`error: "unauthorized"` and an `error_description` explaining how to reconnect +in your AI app's connector settings or run `dotflowy login`. The same message +is used for every invalid credential. The `WWW-Authenticate` protected-resource +metadata challenge and CORS headers remain available for OAuth discovery. +This is an HTTP authentication error, not a JSON-RPC response; whether an AI +app displays the description or starts reauthorization depends on the client. + Every new OAuth authorization requires explicit approval in Dotflowy, even if the client omits `prompt=consent`. The consent page shows the authenticated account, registered client name, callback hostname, full-outline read/write diff --git a/worker/capture-real.test.ts b/worker/capture-real.test.ts index 284b2c05..4fdd9d08 100644 --- a/worker/capture-real.test.ts +++ b/worker/capture-real.test.ts @@ -3182,17 +3182,40 @@ test("OAuth discovery, explicit account-bound consent, refresh rotation and isol const db = await mf.getD1Database("DB"); const origin = "http://localhost"; for (const path of ["/mcp", "/api/mcp"]) { - const denied = await mf.dispatchFetch(`${origin}${path}`, { - method: "POST", - }); - expect(denied.status).toBe(401); - const metadataUrl = denied.headers - .get("www-authenticate")! - .match(/resource_metadata="([^"]+)"/)![1]!; - expect(await (await mf.dispatchFetch(metadataUrl)).json()).toMatchObject({ - resource: `${origin}${path}`, - authorization_servers: [`${origin}/api/auth`], - }); + for (const authorization of [ + undefined, + "Bearer invalid-oauth-token", + "Bearer dfk_invalid", + ]) { + const denied = await mf.dispatchFetch(`${origin}${path}`, { + method: "POST", + headers: authorization ? { authorization } : {}, + }); + expect(denied.status).toBe(401); + expect(await denied.json()).toEqual({ + error: "unauthorized", + error_description: + "Your Dotflowy connection needs to be reconnected. Sign in again from your AI app's connector settings, or run `dotflowy login` for the CLI.", + }); + expect(denied.headers.get("content-type")).toBe("application/json"); + expect(denied.headers.get("access-control-allow-origin")).toBe("*"); + expect(denied.headers.get("access-control-expose-headers")).toBe( + "WWW-Authenticate", + ); + const metadataUrl = denied.headers + .get("www-authenticate")! + .match(/resource_metadata="([^"]+)"/)![1]!; + expect(new URL(metadataUrl).pathname).toBe( + `/.well-known/oauth-protected-resource${path}`, + ); + expect(denied.headers.get("www-authenticate")).toBe( + `Bearer resource_metadata="${metadataUrl}"`, + ); + expect(await (await mf.dispatchFetch(metadataUrl)).json()).toMatchObject({ + resource: `${origin}${path}`, + authorization_servers: [`${origin}/api/auth`], + }); + } } expect( await ( diff --git a/worker/index.ts b/worker/index.ts index 016d965a..d75516cd 100644 --- a/worker/index.ts +++ b/worker/index.ts @@ -1173,15 +1173,22 @@ function handleApiRequest( if (!token?.userId) { // RFC 9728: point the client at the protected-resource metadata so it // can discover the authorization server and start the OAuth flow. - return new Response(JSON.stringify({ error: "unauthorized" }), { - status: 401, - headers: { - "content-type": "application/json", - "www-authenticate": `Bearer resource_metadata="${url.origin}/.well-known/oauth-protected-resource${url.pathname}"`, - "access-control-allow-origin": "*", - "access-control-expose-headers": "WWW-Authenticate", + return new Response( + JSON.stringify({ + error: "unauthorized", + error_description: + "Your Dotflowy connection needs to be reconnected. Sign in again from your AI app's connector settings, or run `dotflowy login` for the CLI.", + }), + { + status: 401, + headers: { + "content-type": "application/json", + "www-authenticate": `Bearer resource_metadata="${url.origin}/.well-known/oauth-protected-resource${url.pathname}"`, + "access-control-allow-origin": "*", + "access-control-expose-headers": "WWW-Authenticate", + }, }, - }); + ); } // MCP (agent access) is a paid capability (#152/#170). Resolve the plan // from the token's `userId` — the Better Auth id the subscription table is From 28cf640f280b7ea7a2aaa4eff723245866cfe739 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:40:04 +0000 Subject: [PATCH 5/5] Add dry-run-first admin reconnect email workflow Co-Authored-By: Cameron Pak --- CONTRIBUTING.md | 29 ++++ docs/adr/0026-agent-native-mcp-server.md | 11 ++ scripts/reconnect-notice.ts | 160 +++++++++++++++++ worker/capture-real.test.ts | 44 +++++ worker/index.ts | 24 +++ worker/reconnect-notice.test.ts | 212 +++++++++++++++++++++++ worker/reconnect-notice.ts | 61 +++++++ 7 files changed, 541 insertions(+) create mode 100644 scripts/reconnect-notice.ts create mode 100644 worker/reconnect-notice.test.ts create mode 100644 worker/reconnect-notice.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c3ff5bf..0f035490 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -270,6 +270,35 @@ current gift. An operator-comped user is a hand-inserted active row with no Stri Keep the founding seat cap in `getCheckoutSessionParams` at checkout-creation time. Webhooks and `subscription.list()` resolve plans from that same list. +## One-time reconnect notice (operators) + +After deploying the Better Auth 1.7 update, use the approved private CSV with an +`email` column (other columns and quoted CSV fields are supported). Keep it outside +the repository. The script uses the same `DOTFLOWY_SESSION_COOKIE` or +`DOTFLOWY_ADMIN_EMAIL` + `DOTFLOWY_ADMIN_PASSWORD` authentication as `scripts/announce.ts`. +The account must be on the admin allowlist. + +```sh +bun scripts/reconnect-notice.ts /home/ubuntu/private/reconnect-cohort.csv --api https://app.dotflowy.com --dry-run +bun scripts/reconnect-notice.ts /home/ubuntu/private/reconnect-cohort.csv --api https://app.dotflowy.com --send +``` + +The default is dry-run; only explicit `--send` can send. Review the dry-run copy +and recipient count first. The route accepts 1–50 email entries and normalizes +and deduplicates them. Results are masked and numbered in CSV order after +deduplication. No recipient addresses are logged by this flow. Missing email +bindings return `simulated` without logging the message. Sends are sequential +and awaited so the response contains each recipient's accepted/failed/simulated +outcome; using `ctx.waitUntil` alone would return before those outcomes exist. +`accepted` means provider acceptance, not inbox delivery. + +There is no database tracking or automatic retry. Save the results privately. +For failures, prepare a new CSV containing **only failed recipients** and run +dry-run then send on that file; never resend the original successful batch. +If a response is lost, outcomes are unknown: investigate before retrying to +avoid duplicate mail. The endpoint never reads the old OAuth tables and does +not reuse waitlist notification flags. No notice is sent by deployment itself. + ## Testing A test earns its place by catching a regression nothing cheaper would catch. diff --git a/docs/adr/0026-agent-native-mcp-server.md b/docs/adr/0026-agent-native-mcp-server.md index f4b04a7f..d23979b9 100644 --- a/docs/adr/0026-agent-native-mcp-server.md +++ b/docs/adr/0026-agent-native-mcp-server.md @@ -199,6 +199,17 @@ client, resource, consent, access-token and refresh-token models. Existing agent registrations and credentials are intentionally invalidated; agents reconnect once. Users, browser sessions, API keys and outline routing are unaffected. +The one-time reconnect email is an explicit operator action via +`scripts/reconnect-notice.ts` and admin-only `POST /api/admin/reconnect-notice` +(non-admins get 404). A private CSV supplies recipients because migration 0023 +removes the legacy source tables. The route validates 1–50 emails, deduplicates, +defaults to dry-run, and uses the approved fixed copy through `worker/email.ts`. +Sequential sends are awaited to return per-recipient outcomes rather than +detached with `ctx.waitUntil`. Neither path logs addresses; dry-run never sends. +There is no database tracking or automatic retry: operators retry only failures +from a new CSV and investigate unknown outcomes before resending. Deployment +never triggers this email. See the operator steps in CONTRIBUTING.md. + Both `/mcp` and `/api/mcp` remain public MCP URLs. Root and path-aware `/.well-known/oauth-protected-resource` documents remain available, as does `/.well-known/oauth-authorization-server` (including issuer-path discovery). diff --git a/scripts/reconnect-notice.ts b/scripts/reconnect-notice.ts new file mode 100644 index 00000000..3a83b5a9 --- /dev/null +++ b/scripts/reconnect-notice.ts @@ -0,0 +1,160 @@ +import { Schema } from "effect"; +import { readFile } from "node:fs/promises"; + +import { ReconnectNoticeBody } from "../worker/reconnect-notice"; +import { resolveAdminCookie } from "./admin-session"; + +export function parseRecipientCsv(csv: string): string[] { + const rows: string[][] = []; + let row: string[] = []; + let value = ""; + let quoted = false; + let closed = false; + const source = csv.replace(/^\uFEFF/, ""); + for (let i = 0; i < source.length; i++) { + const c = source[i]!; + if (quoted) { + if (c === '"' && source[i + 1] === '"') { + value += '"'; + i++; + } else if (c === '"') { + quoted = false; + closed = true; + } else value += c; + } else if (c === "," || c === "\n" || c === "\r") { + row.push(value); + value = ""; + closed = false; + if (c !== ",") { + if (c === "\r" && source[i + 1] === "\n") i++; + if (row.some((cell) => cell.trim())) rows.push(row); + row = []; + } + } else if (c === '"' && value === "" && !closed) quoted = true; + else if (closed || c === '"') throw new Error("Invalid CSV quoting."); + else value += c; + } + if (quoted) throw new Error("Unclosed CSV quote."); + row.push(value); + if (row.some((cell) => cell.trim())) rows.push(row); + const headers = rows.shift()?.map((cell) => cell.trim().toLowerCase()) ?? []; + const column = headers.indexOf("email"); + if (column < 0 || headers.lastIndexOf("email") !== column) + throw new Error("CSV needs one email column."); + const recipients = rows.map((cells) => { + if (cells.length !== headers.length) + throw new Error("CSV row width does not match header."); + return cells[column]!.trim().toLowerCase(); + }); + const decoded = Schema.decodeUnknownSync(ReconnectNoticeBody)({ + recipients, + dryRun: true, + }); + return [...new Set(decoded.recipients)]; +} + +export function reconnectArgs(argv: string[]) { + let api = process.env.DOTFLOWY_API ?? "https://app.dotflowy.com"; + let csv: string | undefined; + let send = false; + let dryRun = false; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]!; + if (arg === "--send") send = true; + else if (arg === "--dry-run") dryRun = true; + else if (arg === "--api") { + const next = argv[++i]; + if (!next || next.startsWith("--")) throw new Error("--api needs a URL."); + api = next; + } else if (arg.startsWith("--") || csv) + throw new Error("Unexpected argument."); + else csv = arg; + } + if (!csv || (send && dryRun)) + throw new Error( + "Pass a CSV path and either --dry-run (default) or --send.", + ); + const url = new URL(api); + if ( + url.username || + url.password || + url.search || + url.hash || + url.pathname !== "/" + ) + throw new Error("API must be an origin URL."); + if ( + url.protocol !== "https:" && + !( + url.protocol === "http:" && + ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) + ) + ) + throw new Error("API must use HTTPS except on loopback."); + return { api: url.origin, csv, dryRun: !send }; +} + +export function maskRecipient(email: string): string { + const [local, domain = ""] = email.split("@"); + return `${local?.slice(0, 1) ?? ""}***@${domain.slice(0, 1)}***`; +} + +const NoticeResponse = Schema.Struct({ + dryRun: Schema.Boolean, + results: Schema.Array( + Schema.Struct({ + email: Schema.String, + status: Schema.Literals(["accepted", "failed", "simulated"]), + }), + ), + message: Schema.optional( + Schema.Struct({ + subject: Schema.String, + text: Schema.String, + html: Schema.String, + }), + ), +}); + +async function main() { + const args = reconnectArgs(process.argv.slice(2)); + const recipients = parseRecipientCsv(await readFile(args.csv, "utf8")); + const cookie = await resolveAdminCookie(args.api); + const response = await fetch(`${args.api}/api/admin/reconnect-notice`, { + method: "POST", + headers: { "content-type": "application/json", cookie }, + body: JSON.stringify({ recipients, dryRun: args.dryRun }), + }); + if (!response.ok) throw new Error("Reconnect notice request failed."); + const result = Schema.decodeUnknownSync(NoticeResponse)( + await response.json(), + ); + if ( + result.dryRun !== args.dryRun || + result.results.length !== recipients.length || + result.results.some((entry, index) => entry.email !== recipients[index]) + ) + throw new Error("Unexpected response."); + console.log( + result.dryRun + ? "DRY RUN: no emails sent." + : "Send results (acceptance is not inbox delivery):", + ); + for (const [index, entry] of result.results.entries()) + console.log(`${index + 1}. ${maskRecipient(entry.email)}: ${entry.status}`); + if (result.message) console.log(JSON.stringify(result.message, null, 2)); + if ( + !args.dryRun && + result.results.some((entry) => entry.status !== "accepted") + ) + process.exitCode = 1; +} + +if (import.meta.main) { + main().catch(() => { + console.error( + "Reconnect notice failed. Check arguments, CSV, admin authentication, and server status. No automatic retry; inspect outcomes before resending.", + ); + process.exitCode = 1; + }); +} diff --git a/worker/capture-real.test.ts b/worker/capture-real.test.ts index 4fdd9d08..c96de464 100644 --- a/worker/capture-real.test.ts +++ b/worker/capture-real.test.ts @@ -621,6 +621,50 @@ test("membership gates theme writes, keeps the launch exception narrow, and scop expect((await request(freeCookie, "/api/admin/feedback")).status).toBe(404); // The admin capability comes from the session and agrees with enforcement. const adminCookie = await signIn("capabilities-admin"); + type ReconnectFixtureBody = { + recipients?: string[]; + dryRun?: boolean | string; + }; + const reconnect = ( + cookie: string, + body: ReconnectFixtureBody, + method = "POST", + ) => + mf.dispatchFetch(`${origin}/api/admin/reconnect-notice`, { + method, + headers: { cookie, "content-type": "application/json", origin }, + body: method === "POST" ? JSON.stringify(body) : undefined, + }); + for (const cookie of ["", freeCookie]) { + expect((await reconnect(cookie, {})).status).toBe(404); + expect((await reconnect(cookie, {}, "GET")).status).toBe(404); + } + expect((await reconnect(adminCookie, {}, "GET")).status).toBe(405); + for (const body of [ + {}, + { recipients: [] }, + { recipients: ["invalid"] }, + { + recipients: Array.from( + { length: 51 }, + (_, i) => `recipient${i}@example.test`, + ), + }, + { recipients: ["recipient@example.test"], dryRun: "false" }, + ]) + expect((await reconnect(adminCookie, body)).status).toBe(400); + const preview = await reconnect(adminCookie, { + recipients: ["Recipient@example.test", "recipient@example.test"], + dryRun: true, + }); + expect(preview.status).toBe(200); + expect(await preview.json()).toMatchObject({ + dryRun: true, + results: [{ email: "recipient@example.test", status: "simulated" }], + message: { + subject: "A quick sign-in refresh for your Dotflowy connections", + }, + }); expect((await request("", "/api/account-capabilities")).status).toBe(401); for (const [cookie, admin] of [ [freeCookie, false], diff --git a/worker/index.ts b/worker/index.ts index d75516cd..68dc77bd 100644 --- a/worker/index.ts +++ b/worker/index.ts @@ -85,6 +85,7 @@ import { UserOutlineDO as BaseUserOutlineDO } from "./outline-do"; import { FREE_NODE_LIMIT, getPlan, nodeLimitForPlan } from "./plan"; import { handleRewards } from "./pro-reward"; import { trialCheckout } from "./pro-trial"; +import { ReconnectNoticeBody, runReconnectNotice } from "./reconnect-notice"; import { resolveRestorePoint } from "./restore"; import { workerSentryOptions } from "./sentry"; import { isHttpUrlString, rateLimitedTitleE, unfurlTitleE } from "./unfurl"; @@ -993,6 +994,29 @@ function handleApiRequest( ); } + if (url.pathname === "/api/admin/reconnect-notice") { + const session = yield* Effect.promise(() => + auth.api.getSession({ headers: request.headers }), + ); + if (!isAdminSession(session, env)) { + return yield* Effect.fail(new RouteNotFound({ path: url.pathname })); + } + if (request.method !== "POST") { + return json({ error: "method not allowed" }, 405); + } + if ( + request.headers.get("content-type")?.split(";")[0]?.trim() !== + "application/json" || + (request.headers.get("origin") && + request.headers.get("origin") !== url.origin) + ) { + return json({ error: "invalid origin or content type" }, 403); + } + const body = yield* decodeBody(request, ReconnectNoticeBody); + // Await the sequential batch so the operator receives every send outcome. + return json(yield* Effect.promise(() => runReconnectNotice(env, body))); + } + // Admin-only: email the launch "Dotflowy is open" blast to the waitlist // (#294). Same 404-not-401 admin gate + method order as /api/admin/invite — // the surface shouldn't advertise itself. Driven by scripts/announce.ts. diff --git a/worker/reconnect-notice.test.ts b/worker/reconnect-notice.test.ts new file mode 100644 index 00000000..fa756b09 --- /dev/null +++ b/worker/reconnect-notice.test.ts @@ -0,0 +1,212 @@ +import { expect, test } from "bun:test"; +import { Schema } from "effect"; +import { createHash } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import type { EmailEnv } from "./email"; + +import { + maskRecipient, + parseRecipientCsv, + reconnectArgs, +} from "../scripts/reconnect-notice"; +import { + ReconnectNoticeBody, + reconnectNoticeEmail, + runReconnectNotice, +} from "./reconnect-notice"; + +test("reconnect notices preview without sending, then send sequentially with the approved copy and report failures", async () => { + // Digests of the approved draft, including its signature and whitespace. + for (const [key, digest] of [ + [ + "subject", + "1d377f4fd6fe7fedcdadff507d3812fc205e391b6bf4062e5dd2b8d910f7dad1", + ], + [ + "text", + "a992fc78881594f8c0b561aa26ad01d6856884fb5179740567249549c8e380c6", + ], + [ + "html", + "b6c9ec8ec490e541359b474281ddb604a442f37b57ad9a35987fff9f6583d647", + ], + ] as const) + expect( + createHash("sha256").update(reconnectNoticeEmail[key]).digest("hex"), + ).toBe(digest); + const calls: unknown[] = []; + let inFlight = 0; + const env: EmailEnv = { + EMAIL: { + async send(message) { + expect(inFlight++).toBe(0); + calls.push(message); + await Promise.resolve(); + inFlight--; + if (calls.length === 2) throw new Error("private provider failure"); + return { messageId: "mock-message" }; + }, + }, + }; + const recipients = [ + " First@example.test ", + "first@example.test", + "second@example.test", + "third@example.test", + ]; + for (const body of [{ recipients }, { recipients, dryRun: true }]) { + const preview = await runReconnectNotice(env, body); + expect(preview.dryRun).toBe(true); + expect(preview.message).toEqual(reconnectNoticeEmail); + expect(preview.results).toEqual([ + { email: "first@example.test", status: "simulated" }, + { email: "second@example.test", status: "simulated" }, + { email: "third@example.test", status: "simulated" }, + ]); + expect(calls).toHaveLength(0); + } + const sent = await runReconnectNotice(env, { recipients, dryRun: false }); + expect(sent.results.map((r) => r.status)).toEqual([ + "accepted", + "failed", + "accepted", + ]); + expect(sent.message).toBeUndefined(); + expect(calls).toEqual( + ["first@example.test", "second@example.test", "third@example.test"].map( + (to) => ({ + from: "Dotflowy ", + replyTo: undefined, + to, + ...reconnectNoticeEmail, + }), + ), + ); + expect( + ( + await runReconnectNotice( + {}, + { recipients: ["first@example.test"], dryRun: false }, + ) + ).results, + ).toEqual([{ email: "first@example.test", status: "simulated" }]); +}); + +test("CSV and command parsing fail closed before any network access", () => { + expect( + parseRecipientCsv( + '\uFEFFuser_id,email,client_names\r\n1,"First@Example.test","Claude, Cursor"\r\n2,first@example.test,CLI\r\n3,second@example.test,"A ""quoted"" client"\r\n', + ), + ).toEqual(["first@example.test", "second@example.test"]); + expect(reconnectArgs(["cohort.csv"]).dryRun).toBe(true); + expect(reconnectArgs(["cohort.csv", "--dry-run"]).dryRun).toBe(true); + expect(reconnectArgs(["cohort.csv", "--send"]).dryRun).toBe(false); + expect(maskRecipient("first@example.test")).toBe("f***@e***"); + for (const csv of [ + "", + "email\n", + "name\nx", + "email,email\na@b.test,a@b.test", + 'email\n"unclosed', + "email\ninvalid", + "email\na@b.test,extra", + 'email\n"a@b.test"junk', + ]) + expect(() => parseRecipientCsv(csv)).toThrow(); + for (const args of [ + [], + ["cohort.csv", "--send", "--dry-run"], + ["cohort.csv", "--unknown"], + ["cohort.csv", "--api"], + ["cohort.csv", "--api", "http://example.test"], + ["cohort.csv", "--api", "https://example.test/path"], + ]) + expect(() => reconnectArgs(args)).toThrow(); + for (const body of [ + { recipients: [] }, + { recipients: ["bad"] }, + { recipients: Array(51).fill("a@b.test") }, + { recipients: ["a@b.test"], dryRun: "false" }, + ]) + expect(() => Schema.decodeUnknownSync(ReconnectNoticeBody)(body)).toThrow(); +}); + +test("operator script defaults to preview and masks batch outcomes against a loopback-only stub", async () => { + const directory = await mkdtemp(join(tmpdir(), "reconnect-script-")); + const csv = join(directory, "cohort.csv"); + await Bun.write(csv, "email\nfirst@example.test\nsecond@example.test\n"); + const requests: unknown[] = []; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + expect(new URL(request.url).pathname).toBe("/api/admin/reconnect-notice"); + expect(request.headers.get("cookie")).toBe("mock-session=local"); + const body = Schema.decodeUnknownSync(ReconnectNoticeBody)( + await request.json(), + ); + requests.push(body); + return Response.json({ + dryRun: body.dryRun, + results: body.recipients.map((email, index) => ({ + email, + status: body.dryRun + ? "simulated" + : index === 0 + ? "accepted" + : "failed", + })), + message: body.dryRun ? reconnectNoticeEmail : undefined, + }); + }, + }); + try { + for (const send of [false, true]) { + const child = Bun.spawn( + [ + process.execPath, + "scripts/reconnect-notice.ts", + csv, + "--api", + server.url.origin, + ...(send ? ["--send"] : []), + ], + { + env: { + ...process.env, + DOTFLOWY_SESSION_COOKIE: "mock-session=local", + }, + stdout: "pipe", + stderr: "pipe", + }, + ); + const [output, errors, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + expect(code).toBe(send ? 1 : 0); + expect(errors).toBe(""); + expect(output).not.toContain("first@example.test"); + expect(output).not.toContain("second@example.test"); + expect(output).toContain( + send ? "f***@e***: accepted" : "DRY RUN: no emails sent.", + ); + expect(output).toContain( + send ? "s***@e***: failed" : "s***@e***: simulated", + ); + } + expect(requests).toEqual( + [true, false].map((dryRun) => ({ + recipients: ["first@example.test", "second@example.test"], + dryRun, + })), + ); + } finally { + await server.stop(true); + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/worker/reconnect-notice.ts b/worker/reconnect-notice.ts new file mode 100644 index 00000000..7da35659 --- /dev/null +++ b/worker/reconnect-notice.ts @@ -0,0 +1,61 @@ +import { Schema } from "effect"; + +import { sendEmail, type EmailEnv } from "./email"; +import { isPlausibleEmail, normalizeEmail } from "./identity"; + +export const ReconnectNoticeBody = Schema.Struct({ + recipients: Schema.Array( + Schema.String.check( + Schema.makeFilter((value) => isPlausibleEmail(normalizeEmail(value))), + ), + ).check(Schema.isMinLength(1), Schema.isMaxLength(50)), + dryRun: Schema.optional(Schema.Boolean), +}); + +export const reconnectNoticeEmail = { + subject: "A quick sign-in refresh for your Dotflowy connections", + text: `Hi there, + +We've updated Dotflowy's sign-in system to help keep your connections secure. Your connected AI apps and the Dotflowy CLI need you to sign in again just once. + +- AI apps such as Claude, ChatGPT, and Cursor: reconnect Dotflowy in the app's connector settings, then sign in and approve the connection again. +- Dotflowy CLI: run \`dotflowy login\` and follow the sign-in steps in your browser. + +Your outlines, browser sessions, and API keys are unchanged. If you connect using an API key, there's nothing you need to do. + +Thanks for using Dotflowy! +— Cam Pak, creator of Dotflowy`, + html: `

Hi there,

+

We've updated Dotflowy's sign-in system to help keep your connections secure. Your connected AI apps and the Dotflowy CLI need you to sign in again just once.

+
    +
  • AI apps such as Claude, ChatGPT, and Cursor: reconnect Dotflowy in the app's connector settings, then sign in and approve the connection again.
  • +
  • Dotflowy CLI: run dotflowy login and follow the sign-in steps in your browser.
  • +
+

Your outlines, browser sessions, and API keys are unchanged. If you connect using an API key, there's nothing you need to do.

+

Thanks for using Dotflowy!
— Cam Pak, creator of Dotflowy

`, +}; + +export async function runReconnectNotice( + env: EmailEnv, + body: typeof ReconnectNoticeBody.Type, +) { + const recipients = [...new Set(body.recipients.map(normalizeEmail))]; + const dryRun = body.dryRun ?? true; + const results: { + email: string; + status: "accepted" | "failed" | "simulated"; + }[] = []; + for (const email of recipients) { + // Avoid the email seam's local fallback, which logs recipient addresses. + const outcome = + dryRun || !env.EMAIL + ? { status: "simulated" as const } + : await sendEmail(env, { to: email, ...reconnectNoticeEmail }); + results.push({ email, status: outcome.status }); + } + return { + dryRun, + results, + message: dryRun ? reconnectNoticeEmail : undefined, + }; +}