From 17ca49a281a5622f8ddc7a2b1bf053a233a6490d Mon Sep 17 00:00:00 2001 From: willynikes2 Date: Mon, 5 Oct 2026 00:44:17 +0000 Subject: [PATCH] feat(auth): migrate to @better-auth/mcp; fix OAuth on fresh installs better-auth 1.7 moved the MCP plugin out of core into @better-auth/mcp, an OAuth 2.1 provider built on @better-auth/oauth-provider. Move to it (better-auth, @better-auth/mcp and @better-auth/oauth-provider ~1.7.7): - Access tokens are EdDSA-signed JWTs bound to `/mcp` (or the bare origin). brainAuth verifies them locally against the server's own JWKS instead of looking up a session. - Discovery: RFC 9728 protected resource metadata, RFC 8414 metadata at both /.well-known/oauth-authorization-server and its /api/auth issuer path, OIDC config. 401s carry a WWW-Authenticate resource_metadata challenge so MCP clients can start the flow. - New /consent page; the sign-in page resumes /oauth2/authorize. Dynamic client registration stays enabled for Claude and other MCP clients; HTTPS redirect URIs are now required. Fix two install problems found along the way: - The auth tables were never created, so OAuth didn't work on a fresh install. `kb start` now creates or upgrades the schema on every start. On databases from the old plugin it moves the colliding tables and their indexes aside as legacy_* (nothing is dropped) before migrating; accounts and sessions are kept. - With public sign-up disabled there was no way to create the owner account. Add `kb auth add-user ` (masked prompt or --password-stdin). Tests: the real provider in-process (sign-up refused, wrong password, anonymous authorize, full flow + refresh, bare-origin resource, consent denied, forged/tampered tokens), an upgrade from a pre-1.7 production schema fixture, and the package smoke test now drives the full Claude connector flow over HTTP: 401 challenge, discovery, registration, sign-in, browser redirect to consent, token, then MCP initialize. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/package-smoke.mjs | 97 ++++++++++- EXTENDING.md | 24 +-- README.md | 3 +- bin/kb.js | 2 + package-lock.json | 152 +++++++++++------- package.json | 4 +- src/auth-oauth.js | 121 +++++++++++++- src/cli/auth-cli.js | 61 +++++++ src/public/consent.html | 121 ++++++++++++++ src/public/sign-in.html | 2 +- src/server.js | 72 +++++---- tests/auth-migrate.test.js | 95 +++++++++++ tests/auth-oauth.test.js | 142 ++++++---------- .../fixtures/auth-schema-better-auth-1.5.sql | 15 ++ tests/helpers/oauth-flow.js | 106 ++++++++++++ 15 files changed, 810 insertions(+), 207 deletions(-) create mode 100644 src/cli/auth-cli.js create mode 100644 src/public/consent.html create mode 100644 tests/auth-migrate.test.js create mode 100644 tests/fixtures/auth-schema-better-auth-1.5.sql create mode 100644 tests/helpers/oauth-flow.js diff --git a/.github/scripts/package-smoke.mjs b/.github/scripts/package-smoke.mjs index 9410b4f..3c455c6 100644 --- a/.github/scripts/package-smoke.mjs +++ b/.github/scripts/package-smoke.mjs @@ -5,6 +5,8 @@ // isolated HOME, so it catches missing files in package.json "files", broken // bin entries and native-module install problems that unit tests can't see. import { spawn, spawnSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { get as httpGet } from 'node:http'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -14,6 +16,7 @@ const BIN = join(process.cwd(), 'node_modules', '.bin'); const HOME = mkdtempSync(join(tmpdir(), 'kb-smoke-home-')); const PORT = 38000 + Math.floor(Math.random() * 1000); const API_KEY = 'ci-smoke-key'; +const OWNER = { email: 'owner@ci.test', password: 'ci smoke owner password' }; const env = { ...process.env, HOME, @@ -79,6 +82,92 @@ function busRoundTrip() { assert.equal(messages[0].sender, 'ci'); } +function addOwner() { + step('kb auth add-user: provision the account that approves OAuth clients'); + const add = spawnSync(join(BIN, 'kb'), ['auth', 'add-user', OWNER.email, '--password-stdin'], { env, input: `${OWNER.password}\n`, encoding: 'utf8', timeout: 30000 }); + assert.equal(add.status, 0, add.stderr); +} + +// A top-level browser navigation. fetch() always sends `sec-fetch-mode: cors`, +// which makes better-auth answer with JSON instead of the 302 a browser gets. +function navigate(url, headers = {}) { + return new Promise((resolve, reject) => { + httpGet(url, { headers: { Accept: 'text/html,application/xhtml+xml', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Dest': 'document', ...headers } }, res => { + res.resume(); + resolve({ status: res.statusCode, location: res.headers.location }); + }).on('error', reject); + }); +} + +// What the Claude web connector does: get challenged, discover, register, +// send the user through sign-in and consent, exchange the code, call MCP. +async function connectorOAuthFlow() { + const origin = `http://localhost:${PORT}`; + const mcpUrl = `${origin}/mcp`; + const json = { 'Content-Type': 'application/json', Origin: origin }; + const initialize = rpc(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'ci-smoke', version: '1.0.0' } }); + const mcpHeaders = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }; + + const challenge = await fetch(mcpUrl, { method: 'POST', headers: mcpHeaders, body: initialize }); + assert.equal(challenge.status, 401, 'unauthenticated MCP request was not rejected'); + const resourceMetadataUrl = /resource_metadata="([^"]+)"/.exec(challenge.headers.get('www-authenticate') || '')?.[1]; + assert.ok(resourceMetadataUrl, '401 from /mcp has no RFC 9728 resource_metadata challenge'); + + const resourceMeta = await (await fetch(resourceMetadataUrl)).json(); + assert.equal(resourceMeta.resource, mcpUrl, 'protected resource metadata names the wrong resource'); + const issuer = resourceMeta.authorization_servers[0]; + const asMetaRes = await fetch(`${origin}/.well-known/oauth-authorization-server${new URL(issuer).pathname}`); + assert.equal(asMetaRes.status, 200, 'RFC 8414 authorization server metadata not served'); + const meta = await asMetaRes.json(); + assert.equal(meta.issuer, issuer); + + const reg = await fetch(meta.registration_endpoint, { + method: 'POST', + headers: json, + body: JSON.stringify({ client_name: 'CI Connector', redirect_uris: ['https://client.example.test/callback'], token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'] }), + }); + assert.equal(reg.status, 201, `dynamic client registration failed: ${await reg.clone().text()}`); + const { client_id } = await reg.json(); + + const signUp = await fetch(`${origin}/api/auth/sign-up/email`, { method: 'POST', headers: json, body: JSON.stringify({ email: 'outsider@ci.test', password: 'Password123!', name: 'x' }) }); + assert.ok(signUp.status >= 400, `public sign-up is open (${signUp.status})`); + + const signIn = await fetch(`${origin}/api/auth/sign-in/email`, { method: 'POST', headers: json, body: JSON.stringify(OWNER) }); + assert.equal(signIn.status, 200, 'owner could not sign in'); + const cookie = signIn.headers.getSetCookie().map(c => c.split(';')[0]).join('; '); + + const verifier = randomBytes(32).toString('base64url'); + const query = new URLSearchParams({ + response_type: 'code', client_id, redirect_uri: 'https://client.example.test/callback', scope: 'openid profile email offline_access', + code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256', state: 'ci', resource: mcpUrl, + }); + const authz = await navigate(`${meta.authorization_endpoint}?${query}`, { Cookie: cookie }); + assert.equal(authz.status, 302, `authorize did not redirect the browser (${authz.status})`); + const consentUrl = new URL(authz.location || '', origin); + assert.equal(consentUrl.pathname, '/consent', `authorize did not lead to consent: ${consentUrl}`); + assert.equal((await fetch(consentUrl)).status, 200, 'consent page not served'); + + const consent = await fetch(`${origin}/api/auth/oauth2/consent`, { method: 'POST', headers: { ...json, Cookie: cookie }, body: JSON.stringify({ accept: true, oauth_query: consentUrl.search.slice(1) }) }); + const code = new URL((await consent.json()).url).searchParams.get('code'); + assert.ok(code, 'consent did not return an authorization code'); + + const tokenRes = await fetch(meta.token_endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: 'https://client.example.test/callback', client_id, code_verifier: verifier, resource: mcpUrl }), + }); + assert.equal(tokenRes.status, 200, `token exchange failed: ${await tokenRes.clone().text()}`); + const { access_token } = await tokenRes.json(); + const bearer = { Authorization: `Bearer ${access_token}` }; + + const mcp = await fetch(mcpUrl, { method: 'POST', headers: { ...mcpHeaders, ...bearer }, body: initialize }); + assert.equal(mcp.status, 200, `MCP initialize with the OAuth token failed (${mcp.status})`); + const body = await mcp.text(); + assert.match(body, /"serverInfo"/, 'MCP initialize returned no serverInfo'); + assert.equal((await fetch(`${origin}/api/v1/stats`, { headers: bearer })).status, 200, 'OAuth token rejected by the REST API'); + console.log(' connector flow: challenge -> discovery -> register -> sign-in -> consent -> token -> MCP initialize ok'); +} + async function waitForHealth(server, getLog) { const deadline = Date.now() + 30000; while (Date.now() < deadline) { @@ -93,7 +182,7 @@ async function waitForHealth(server, getLog) { } async function httpServer() { - step('kb start: health, API key + OAuth enforcement, OAuth discovery, ingest + search round trip'); + step('kb start: health, API key auth, MCP connector OAuth flow, ingest + search round trip'); const server = spawn(join(BIN, 'kb'), ['start'], { env, stdio: ['ignore', 'pipe', 'pipe'] }); let log = ''; server.stdout.on('data', d => { log += d; }); @@ -108,10 +197,7 @@ async function httpServer() { assert.equal((await fetch(`${base}/stats`, { headers: { 'X-API-Key': 'wrong' } })).status, 403, 'bad API key was not rejected'); assert.equal((await fetch(`${base}/stats`, { headers: { Authorization: 'Bearer not-a-real-token' } })).status, 401, 'bogus OAuth token was not rejected'); - const discovery = await fetch(`http://localhost:${PORT}/.well-known/oauth-authorization-server`); - assert.equal(discovery.status, 200, 'OAuth discovery endpoint failed'); - const metadata = await discovery.json(); - assert.ok(metadata.token_endpoint && metadata.authorization_endpoint, 'OAuth discovery metadata incomplete'); + await connectorOAuthFlow(); const ingest = await fetch(`${base}/ingest`, { method: 'POST', @@ -137,6 +223,7 @@ async function httpServer() { try { await mcpHandshake(); busRoundTrip(); + addOwner(); await httpServer(); console.log('\n✔ package smoke test passed'); } finally { diff --git a/EXTENDING.md b/EXTENDING.md index b35414c..e8e881e 100644 --- a/EXTENDING.md +++ b/EXTENDING.md @@ -154,8 +154,8 @@ Add it in `server.js` before the `brainAuth` middleware, like the `/api/v1/healt **Auth middleware chain (`brainAuth`):** 1. Check `X-API-Key` header against env vars (`KB_API_KEY_CLAUDE`, `KB_API_KEY_OPENAI`, `KB_API_KEY_GEMINI`) 2. Check `Authorization: Bearer ` against same API keys -3. Validate as OAuth token via better-auth -4. Reject with 401 +3. Verify as an OAuth access token (a JWT signed by this server, audience `/mcp` or the bare origin) +4. Reject with 401 and a `WWW-Authenticate: Bearer resource_metadata=...` challenge so MCP clients can start OAuth ### src/mcp-http.js -- HTTP MCP Transport @@ -261,7 +261,7 @@ Dashboard auth uses bcrypt password hashing with session cookies. The session st **To swap to a different auth provider:** The `authMiddleware` function is the gate. Replace `checkPassword()` with your provider's verification (LDAP, SSO, etc.) and update `loginHandler` accordingly. -**OAuth (remote access):** Configured in `src/auth-oauth.js` using better-auth with the MCP plugin. The OAuth database is separate (`auth.db`) from the main KB database. +**OAuth (remote access):** Configured in `src/auth-oauth.js` using better-auth with the `@better-auth/mcp` plugin (an OAuth 2.1 provider). The OAuth database is separate (`auth.db`) from the main KB database, and its schema is created or upgraded on every `kb start`. Public sign-up is disabled; accounts are created with `kb auth add-user`. --- @@ -416,7 +416,7 @@ The current system is single-user. To support multiple users: 1. **API keys:** Add per-user keys in `.env` (e.g., `KB_API_KEY_USER_ALICE`, `KB_API_KEY_USER_BOB`). Update `src/middleware/api-key.js` to dynamically read all `KB_API_KEY_*` vars. -2. **OAuth:** The better-auth setup in `src/auth-oauth.js` already supports multiple users. Enable email+password registration or add social providers. +2. **OAuth:** The better-auth setup in `src/auth-oauth.js` already supports multiple users: add each one with `kb auth add-user `. Do not re-enable public sign-up. Every account can approve clients with full KB access, so anyone able to register would get that access. 3. **Data isolation:** Currently all users share one database. For per-user isolation, partition by `source` or add a `user_id` column to the `documents` table. @@ -442,14 +442,20 @@ BETTER_AUTH_SECRET= BETTER_AUTH_URL=https://your-domain.com ``` -**Step 2:** The OAuth discovery endpoints are auto-configured: -- `/.well-known/oauth-authorization-server` +**Step 2:** Create the account you will sign in with. Public sign-up is disabled, so this is the only way to create one: +```bash +kb auth add-user you@example.com # prompts for a password +echo "$PASSWORD" | kb auth add-user you@example.com --password-stdin +``` + +**Step 3:** Start the server (`kb start`). It creates the OAuth tables on first run and serves discovery at: +- `/.well-known/oauth-protected-resource` and `/.well-known/oauth-protected-resource/mcp` (RFC 9728) +- `/.well-known/oauth-authorization-server` and `/.well-known/oauth-authorization-server/api/auth` (RFC 8414) - `/.well-known/openid-configuration` -- `/.well-known/oauth-protected-resource` -**Step 3:** The sign-in page at `/sign-in` handles the consent flow. Users authenticate with email+password. +**Step 4:** In Claude.ai, add a custom connector with the URL `https://your-domain.com/mcp`. Claude registers itself, sends you to `/sign-in`, then `/consent`; approve it and Claude receives a token bound to your `/mcp` resource. -**Step 4:** MCP clients discover auth via the well-known endpoints, redirect users to `/sign-in`, and receive tokens via the OAuth flow. +Upgrading from a release that used better-auth's built-in `mcp` plugin (before 1.7): the first `kb start` moves the old OAuth tables aside as `legacy_*` (nothing is deleted) and existing accounts keep working, but previously connected MCP clients have to be connected again. --- diff --git a/README.md b/README.md index 00a8e09..90b6636 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,8 @@ The loop in detail: **Security** - bcrypt password hashing with HttpOnly session cookies -- Dual auth: API keys (fast path) + OAuth Bearer tokens +- Dual auth: API keys (fast path) + OAuth 2.1 Bearer tokens (signed JWTs bound to the MCP resource) +- No self-registration: OAuth accounts are created by the operator with `kb auth add-user` - Three separate API keys for Claude, OpenAI, and Gemini - Safety review tool checks KB history before destructive actions - No external dependencies for core functionality diff --git a/bin/kb.js b/bin/kb.js index 097b4f5..9073a35 100755 --- a/bin/kb.js +++ b/bin/kb.js @@ -102,6 +102,7 @@ const commands = { }, export: () => import('../src/cli/export-cli.js').then(m => m.exportCmd(args)), restore: () => import('../src/cli/restore-cli.js').then(m => m.restoreCmd(args)), + auth: () => import('../src/cli/auth-cli.js').then(m => m.authCmd(args)), }; if (!command || !commands[command]) { @@ -128,6 +129,7 @@ Commands: capture-fix-json [vault] Capture a fix from JSON export Export vault docs to a portable bundle (--out=dir, --dry-run, --json) restore Restore from a bundle (--dry-run, --overwrite, --yes, --strict, --no-embeddings) + auth add-user Create an account that can approve OAuth/MCP clients (--password-stdin) setup Interactive setup wizard (--auto for agent mode) `); process.exit(command ? 1 : 0); diff --git a/package-lock.json b/package-lock.json index 35b7e46..9e1d60c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,12 @@ "version": "1.0.0", "dependencies": { "@anthropic-ai/sdk": "^0.39.0", + "@better-auth/mcp": "~1.7.7", + "@better-auth/oauth-provider": "~1.7.7", "@huggingface/transformers": "^4.3.0", "@modelcontextprotocol/sdk": "^1.0.0", "bcryptjs": "^2.4.3", - "better-auth": "~1.6.33", + "better-auth": "~1.7.7", "better-sqlite3": "^12.0.0", "cors": "^2.8.6", "dotenv": "^17.3.1", @@ -64,18 +66,18 @@ "license": "MIT" }, "node_modules/@better-auth/core": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.6.33.tgz", - "integrity": "sha512-DTadFTdcEad+IAmcJAEVGjD+6wtjt8BkLqmfBdRK+AeYOHaKy/gwtSlmxDuHKfsRaOmn1P8/gtEi/L5wVeEojQ==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.7.7.tgz", + "integrity": "sha512-srgFzHEjB2WWlokFz1i4BfG41sNhsA105Pukgqu6RrEh5A+LSkzf1mCHydVipkjt9l5qswtBMi7IL6ouHbZL4Q==", "license": "MIT", "dependencies": { - "@opentelemetry/semantic-conventions": "^1.39.0", + "@opentelemetry/semantic-conventions": "^1.41.1", "@standard-schema/spec": "^1.1.0", - "zod": "^4.3.6" + "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "0.4.2", - "@better-fetch/fetch": "1.3.1", + "@better-fetch/fetch": "1.3.2", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.0", "jose": "^6.1.0", @@ -89,14 +91,14 @@ } }, "node_modules/@better-auth/drizzle-adapter": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/drizzle-adapter/-/drizzle-adapter-1.6.33.tgz", - "integrity": "sha512-/BXRx0FoqoWKV3LZLWjnPJHHGvXEZro7goVzzV7K7ZPZG+PbBa+HYN+eJuXSMFb3JCwJEhW+JNLHWekzHQnTLA==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/drizzle-adapter/-/drizzle-adapter-1.7.7.tgz", + "integrity": "sha512-qon0U94PR5FQysuyGoAlGVQpIIiNg5dtDpwjE63sN/HjoRWZadZzHPcS9mn7JsJyQZK6iTNhd7LD0AaXt2f78w==", "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.6.33", + "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", - "drizzle-orm": "^0.45.2" + "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "peerDependenciesMeta": { "drizzle-orm": { @@ -105,12 +107,12 @@ } }, "node_modules/@better-auth/kysely-adapter": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/kysely-adapter/-/kysely-adapter-1.6.33.tgz", - "integrity": "sha512-CUYXGxJhx29iilmCr2jdzWBGg/Iq1XjghGlRO15N5SsR+hz8KOGob57UFMVtHEQAhN3tcdgJNllx/ZLmNCyO/A==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/kysely-adapter/-/kysely-adapter-1.7.7.tgz", + "integrity": "sha512-9FONOCgOcrQI9wJ5v1oDGIg9sT7pa9RjZZQ4fsCTudo8R87SrIGNUvUxDFTJhZvUblvFfGaIBR9Vb8LA+8bqLQ==", "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.6.33", + "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "kysely": "^0.28.17 || ^0.29.0" }, @@ -120,23 +122,38 @@ } } }, + "node_modules/@better-auth/mcp": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/mcp/-/mcp-1.7.7.tgz", + "integrity": "sha512-BZm8gHfPef7qXuEY61rBpVkBIuUOJ+dx2ese/JpHUnbw2/SteZ/UvHTIot5twE+C+dtEhqQYL2CEVkuPCBJeQg==", + "license": "MIT", + "dependencies": { + "@better-auth/oauth-provider": "^1.7.7", + "jose": "^6.1.3" + }, + "peerDependencies": { + "@better-auth/core": "^1.7.7", + "better-auth": "^1.7.7", + "better-call": "1.4.0" + } + }, "node_modules/@better-auth/memory-adapter": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/memory-adapter/-/memory-adapter-1.6.33.tgz", - "integrity": "sha512-vw8uuW+zWUd4TLNnmtlwIiUb4jcj/mAopKWohv7ojDR6Esha7ZkM6EsW8W1PVdRhAfLiHeGqh0RvNtFm5mNDjQ==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/memory-adapter/-/memory-adapter-1.7.7.tgz", + "integrity": "sha512-FqKFEe+b5tXXV0gRbyirca+qXgMpLOeJ8Wk19yykb/scQKy0WJ4k22WzEV3TTPctQV9DZhwCXPlDtQhnlOv5Gg==", "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.6.33", + "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2" } }, "node_modules/@better-auth/mongo-adapter": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/mongo-adapter/-/mongo-adapter-1.6.33.tgz", - "integrity": "sha512-JxAENypnmQbYcNboePWafLaP2egLgKQYoKPnZ8dNvaV50/h/dSlBDn1KaUrEMkJWjRXQ2rwgJzUl2yvGxQUZow==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/mongo-adapter/-/mongo-adapter-1.7.7.tgz", + "integrity": "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g==", "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.6.33", + "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, @@ -146,13 +163,30 @@ } } }, + "node_modules/@better-auth/oauth-provider": { + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/oauth-provider/-/oauth-provider-1.7.7.tgz", + "integrity": "sha512-dc4C/ZF+8qc88ebcU8kaFp8yladCtfTkuUt2zBSmYw25YCNC5BoUP9rpAkIx4nemlZ11gLtSnkEPc0sA7MwVmw==", + "license": "MIT", + "dependencies": { + "jose": "^6.2.3", + "zod": "^4.5.4" + }, + "peerDependencies": { + "@better-auth/core": "^1.7.7", + "@better-auth/utils": "0.4.2", + "@better-fetch/fetch": "1.3.2", + "better-auth": "^1.7.7", + "better-call": "1.4.0" + } + }, "node_modules/@better-auth/prisma-adapter": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/prisma-adapter/-/prisma-adapter-1.6.33.tgz", - "integrity": "sha512-wloYc35VpI7tjuWgOckB4GVX8y0Ow12ER5CfSqc55K88BefgRtR3brruZ9GhHSll+ZIxjf/0p5IGa+z8rKUR2Q==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/prisma-adapter/-/prisma-adapter-1.7.7.tgz", + "integrity": "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA==", "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.6.33", + "@better-auth/core": "^1.7.7", "@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" @@ -167,14 +201,14 @@ } }, "node_modules/@better-auth/telemetry": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.6.33.tgz", - "integrity": "sha512-k8BmE90sWIXlst84zyvCjWoXuftdujCmevlDDI86zXg81Pl+F2AZFPZFXzWkqaNmecnUjbm9bohNGCY6JonWQQ==", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.7.7.tgz", + "integrity": "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA==", "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.6.33", + "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", - "@better-fetch/fetch": "1.3.1" + "@better-fetch/fetch": "1.3.2" } }, "node_modules/@better-auth/utils": { @@ -187,9 +221,9 @@ } }, "node_modules/@better-fetch/fetch": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.3.1.tgz", - "integrity": "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.3.2.tgz", + "integrity": "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow==", "license": "MIT" }, "node_modules/@emnapi/runtime": { @@ -1345,28 +1379,28 @@ "license": "MIT" }, "node_modules/better-auth": { - "version": "1.6.33", - "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.6.33.tgz", - "integrity": "sha512-QkVKOmJw/LQ3HjIib2wx2Td0xB9EuPgw0ARYPKeFu3niN0VSBW32j4QwfewFZOQi5Hb/jOB6U+wdvtBhF7+URw==", - "license": "MIT", - "dependencies": { - "@better-auth/core": "1.6.33", - "@better-auth/drizzle-adapter": "1.6.33", - "@better-auth/kysely-adapter": "1.6.33", - "@better-auth/memory-adapter": "1.6.33", - "@better-auth/mongo-adapter": "1.6.33", - "@better-auth/prisma-adapter": "1.6.33", - "@better-auth/telemetry": "1.6.33", + "version": "1.7.7", + "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.7.7.tgz", + "integrity": "sha512-Zhgxi/c5ylmfB/sX+nwnBbsFf/j6k0L8DvL6CJXZSrXgxc5pPMC/e7j812zNd4L4B4ELmdURCPw3X8nAOUdcjw==", + "license": "MIT", + "dependencies": { + "@better-auth/core": "1.7.7", + "@better-auth/drizzle-adapter": "1.7.7", + "@better-auth/kysely-adapter": "1.7.7", + "@better-auth/memory-adapter": "1.7.7", + "@better-auth/mongo-adapter": "1.7.7", + "@better-auth/prisma-adapter": "1.7.7", + "@better-auth/telemetry": "1.7.7", "@better-auth/utils": "0.4.2", - "@better-fetch/fetch": "1.3.1", - "@noble/ciphers": "^2.1.1", - "@noble/hashes": "^2.0.1", + "@better-fetch/fetch": "1.3.2", + "@noble/ciphers": "^2.2.0", + "@noble/hashes": "^2.2.0", "better-call": "1.4.0", "defu": "^6.1.4", - "jose": "^6.1.3", + "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", - "nanostores": "^1.1.1", - "zod": "^4.3.6" + "nanostores": "^1.3.0", + "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", @@ -1374,9 +1408,8 @@ "@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", + "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", @@ -1386,7 +1419,7 @@ "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", + "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "peerDependenciesMeta": { @@ -1405,9 +1438,6 @@ "@tanstack/solid-start": { "optional": true }, - "better-sqlite3": { - "optional": true - }, "drizzle-kit": { "optional": true }, diff --git a/package.json b/package.json index 6493d25..2ca0d14 100644 --- a/package.json +++ b/package.json @@ -23,10 +23,12 @@ }, "dependencies": { "@anthropic-ai/sdk": "^0.39.0", + "@better-auth/mcp": "~1.7.7", + "@better-auth/oauth-provider": "~1.7.7", "@huggingface/transformers": "^4.3.0", "@modelcontextprotocol/sdk": "^1.0.0", "bcryptjs": "^2.4.3", - "better-auth": "~1.6.33", + "better-auth": "~1.7.7", "better-sqlite3": "^12.0.0", "cors": "^2.8.6", "dotenv": "^17.3.1", diff --git a/src/auth-oauth.js b/src/auth-oauth.js index 403b10c..09341f9 100644 --- a/src/auth-oauth.js +++ b/src/auth-oauth.js @@ -1,27 +1,134 @@ -// src/auth-oauth.js — Better Auth OAuth provider for MCP clients +// src/auth-oauth.js — Better Auth OAuth 2.1 provider for MCP clients import { betterAuth } from 'better-auth'; -import { mcp } from 'better-auth/plugins'; +import { jwt } from 'better-auth/plugins'; +import { getMigrations } from 'better-auth/db/migration'; +import { mcp } from '@better-auth/mcp'; +import { verifyJwsAccessToken } from 'better-auth/oauth2'; import Database from 'better-sqlite3'; import { join } from 'path'; -import { homedir } from 'os'; +import { KB_DIR } from './paths.js'; -const KB_DIR = join(homedir(), '.knowledge-base'); const AUTH_DB_PATH = join(KB_DIR, 'auth.db'); +export const BASE_URL = (process.env.BETTER_AUTH_URL || `http://localhost:${process.env.KB_PORT || 3838}`).replace(/\/+$/, ''); +// MCP clients connect to /mcp (or the bare origin); tokens are audience-bound to either. +export const MCP_RESOURCE = `${BASE_URL}/mcp`; +const ACCEPTED_AUDIENCES = [MCP_RESOURCE, BASE_URL]; + +const authDb = new Database(AUTH_DB_PATH); + +// better-auth stores string[] columns as TEXT on SQLite, then warns about it on +// every schema check; and it reports missing tables before migrateAuthSchema() +// (run at every start) creates them. Drop those two messages, keep the rest. +const IGNORED_AUTH_LOGS = [ + /has a different type in the database\. Expected string\[\] but got TEXT/, + /^Database schema mismatch/, +]; + export const auth = betterAuth({ - database: new Database(AUTH_DB_PATH), + logger: { + log(level, message, ...args) { + if (IGNORED_AUTH_LOGS.some(pattern => pattern.test(message))) return; + const write = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log; + write(`[Better Auth] ${message}`, ...args); + }, + }, + database: authDb, secret: process.env.BETTER_AUTH_SECRET, - baseURL: process.env.BETTER_AUTH_URL || `http://localhost:${process.env.KB_PORT || 3838}`, + baseURL: BASE_URL, basePath: '/api/auth', emailAndPassword: { enabled: true, // Any account can mint OAuth tokens with full KB access, so accounts are - // provisioned by the operator, never self-registered. + // provisioned by the operator (`kb auth add-user`), never self-registered. disableSignUp: true, }, plugins: [ + jwt(), mcp({ loginPage: '/sign-in', + consentPage: '/consent', + resource: MCP_RESOURCE, + resources: [BASE_URL], + clientRegistrationDefaultResources: [BASE_URL], + // Claude and other MCP clients register themselves (RFC 7591). A client + // alone grants nothing: the user still has to sign in and approve it. + allowDynamicClientRegistration: true, + allowUnauthenticatedClientRegistration: true, }), ], }); + +// Tables from the pre-1.7 better-auth `mcp` plugin. Their names collide with the +// new provider's tables but their columns don't, so they are kept aside, not dropped. +const LEGACY_OAUTH_TABLES = ['oauthApplication', 'oauthAccessToken', 'oauthConsent']; + +function archiveLegacyOAuthTables(db) { + const columns = table => db.prepare(`SELECT name FROM pragma_table_info(?)`).all(table).map(c => c.name); + const isLegacy = columns('oauthApplication').length > 0 || columns('oauthAccessToken').includes('accessToken'); + if (!isLegacy) return []; + + const archived = []; + db.transaction(() => { + for (const table of LEGACY_OAUTH_TABLES) { + if (columns(table).length === 0) continue; + let target = `legacy_${table}`; + for (let n = 2; columns(target).length > 0; n += 1) target = `legacy_${table}_${n}`; + db.prepare(`ALTER TABLE "${table}" RENAME TO "${target}"`).run(); + // Indexes keep their names across a table rename and would block the new + // tables' indexes; SQLite can't rename an index, so recreate it as legacy_*. + const indexes = db.prepare(`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL`).all(target); + for (const { name, sql } of indexes) { + db.prepare(`DROP INDEX "${name}"`).run(); + db.prepare(sql.replace(`"${name}"`, `"legacy_${name}"`)).run(); + } + archived.push(target); + } + })(); + return archived; +} + +/** + * Create or upgrade the auth schema. Safe to run on every start: it only adds + * what is missing. Returns the legacy tables it moved aside, if any. + */ +export async function migrateAuthSchema() { + const archived = archiveLegacyOAuthTables(authDb); + const { runMigrations } = await getMigrations(auth.options); + await runMigrations(); + return archived; +} + +/** Create an account that can sign in to approve OAuth clients. */ +export async function addUser({ email, password, name }) { + const ctx = await auth.$context; + const normalized = email.trim().toLowerCase(); + if (await ctx.internalAdapter.findUserByEmail(normalized)) { + throw new Error(`A user with email ${normalized} already exists`); + } + const { minPasswordLength = 8 } = auth.options.emailAndPassword; + if (password.length < minPasswordLength) { + throw new Error(`Password must be at least ${minPasswordLength} characters`); + } + const user = await ctx.internalAdapter.createUser({ email: normalized, name: name || normalized, emailVerified: true }); + await ctx.internalAdapter.linkAccount({ + userId: user.id, + providerId: 'credential', + accountId: user.id, + password: await ctx.password.hash(password), + }); + return user; +} + +/** Verify an OAuth access token (a JWT signed by this server). Returns its claims or null. */ +export async function verifyAccessToken(token) { + try { + const ctx = await auth.$context; + return await verifyJwsAccessToken(token, { + jwksFetch: async () => auth.api.getJwks(), + verifyOptions: { issuer: ctx.baseURL, audience: ACCEPTED_AUDIENCES }, + }); + } catch { + return null; + } +} diff --git a/src/cli/auth-cli.js b/src/cli/auth-cli.js new file mode 100644 index 0000000..34b74aa --- /dev/null +++ b/src/cli/auth-cli.js @@ -0,0 +1,61 @@ +// src/cli/auth-cli.js — manage accounts that can approve OAuth (MCP) clients +import { createInterface } from 'readline'; + +const USAGE = `Usage: kb auth add-user [--name ] [--password-stdin] + +Creates an account that can sign in and approve OAuth clients such as the +Claude web connector. Public sign-up is disabled, so this is the only way to +create one. Without --password-stdin you are prompted for the password.`; + +function readFlag(args, name) { + const index = args.indexOf(name); + return index === -1 ? undefined : args[index + 1]; +} + +async function readStdin() { + let data = ''; + for await (const chunk of process.stdin) data += chunk; + return data.replace(/\r?\n$/, ''); +} + +function promptHidden(question) { + return new Promise(resolve => { + const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true }); + rl._writeToOutput = text => { + if (text.startsWith(question)) rl.output.write(question); + }; + rl.question(question, answer => { + rl.output.write('\n'); + rl.close(); + resolve(answer); + }); + }); +} + +async function readPassword(args) { + if (args.includes('--password-stdin')) return readStdin(); + if (!process.stdin.isTTY) throw new Error('No terminal to prompt on; pipe the password with --password-stdin'); + const password = await promptHidden('Password: '); + if (password !== await promptHidden('Repeat password: ')) throw new Error('Passwords do not match'); + return password; +} + +export async function authCmd(args) { + const [subcommand, email] = args; + if (subcommand !== 'add-user' || !email || email.startsWith('--')) { + console.error(USAGE); + process.exit(1); + } + + try { + const { migrateAuthSchema, addUser } = await import('../auth-oauth.js'); + await migrateAuthSchema(); + const password = await readPassword(args); + const user = await addUser({ email, password, name: readFlag(args, '--name') }); + console.log(`Created ${user.email}. Sign in with it when an MCP client asks you to authorize.`); + process.exit(0); + } catch (err) { + console.error(`kb auth add-user: ${err.message}`); + process.exit(1); + } +} diff --git a/src/public/consent.html b/src/public/consent.html new file mode 100644 index 0000000..a6c37a2 --- /dev/null +++ b/src/public/consent.html @@ -0,0 +1,121 @@ + + + + + + Allow Access — Brain API + + + +
+

Brain API

+

Allow access to your knowledge base?

+
+ An application wants to search, read and write your knowledge base. +
+ +
+ + +
+
+ + + diff --git a/src/public/sign-in.html b/src/public/sign-in.html index f0812ee..bafde70 100644 --- a/src/public/sign-in.html +++ b/src/public/sign-in.html @@ -122,7 +122,7 @@

Brain API

const params = new URLSearchParams(window.location.search); if (params.get('response_type')) { // OAuth flow: redirect back to authorize endpoint with all params - window.location.href = '/api/auth/mcp/authorize?' + params.toString(); + window.location.href = '/api/auth/oauth2/authorize?' + params.toString(); } else { const redirectTo = params.get('redirect') || params.get('callbackURL') || '/'; window.location.href = redirectTo; diff --git a/src/server.js b/src/server.js index f69857d..d6ca106 100644 --- a/src/server.js +++ b/src/server.js @@ -12,7 +12,8 @@ import cors from 'cors'; import authRoutes from './routes/session-routes.js'; import apiRoutes from './routes/api.js'; import { toNodeHandler } from 'better-auth/node'; -import { auth } from './auth-oauth.js'; +import { oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from '@better-auth/oauth-provider'; +import { auth, migrateAuthSchema, verifyAccessToken, BASE_URL } from './auth-oauth.js'; import { createApiKeyMiddleware } from './middleware/api-key.js'; import v1Router from './routes/v1.js'; import openapiRoute from './routes/openapi.js'; @@ -40,7 +41,13 @@ export async function start() { await promptPassword(); } - // 2. Auto-ingest on first run + // 2. OAuth schema: create it on first run, upgrade it after better-auth updates + const archivedAuthTables = await migrateAuthSchema(); + if (archivedAuthTables.length) { + console.log(`OAuth schema upgraded; previous OAuth clients/tokens kept in ${archivedAuthTables.join(', ')}. Reconnect MCP clients.`); + } + + // 3. Auto-ingest on first run if (getDocumentCount() === 0) { console.log('First run — auto-ingesting existing knowledge base...'); const home = homedir(); @@ -59,7 +66,7 @@ export async function start() { } } - // 3. Express setup + // 4. Express setup const app = express(); const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -87,30 +94,33 @@ export async function start() { app.all('/api/auth/*', corsMiddleware, toNodeHandler(auth)); // --- Well-known OAuth discovery endpoints --- - // These return Web Response objects, so we convert to Express responses - const { oAuthDiscoveryMetadata, oAuthProtectedResourceMetadata } = await import('better-auth/plugins'); - const discoveryHandler = oAuthDiscoveryMetadata(auth); - const resourceHandler = oAuthProtectedResourceMetadata(auth); - - const handleOAuthDiscovery = async (req, res) => { - const url = `${process.env.BETTER_AUTH_URL || 'http://localhost:' + port}/.well-known/oauth-authorization-server`; - const webRes = await discoveryHandler(new Request(url)); - const data = await webRes.json(); - res.json(data); + // The issuer is ${BASE_URL}/api/auth, so RFC 8414 clients look for metadata at + // /.well-known//api/auth; older clients use the bare /.well-known/. + const sendWebResponse = async (webRes, res) => { + res.status(webRes.status); + webRes.headers.forEach((value, key) => res.setHeader(key, value)); + res.send(Buffer.from(await webRes.arrayBuffer())); }; - app.get('/.well-known/oauth-authorization-server', corsMiddleware, handleOAuthDiscovery); - app.get('/.well-known/openid-configuration', corsMiddleware, handleOAuthDiscovery); - app.get('/.well-known/oauth-protected-resource', corsMiddleware, async (req, res) => { - const url = `${process.env.BETTER_AUTH_URL || 'http://localhost:' + port}${req.originalUrl}`; - const webRes = await resourceHandler(new Request(url)); - const data = await webRes.json(); - res.json(data); - }); + const authServerMetadata = oauthProviderAuthServerMetadata(auth); + const openIdMetadata = oauthProviderOpenIdConfigMetadata(auth); + const metadataRoute = handler => async (req, res) => { + await sendWebResponse(await handler(new Request(`${BASE_URL}${req.originalUrl}`)), res); + }; + app.get(['/.well-known/oauth-authorization-server', '/.well-known/oauth-authorization-server/api/auth'], + corsMiddleware, metadataRoute(authServerMetadata)); + app.get(['/.well-known/openid-configuration', '/.well-known/openid-configuration/api/auth'], + corsMiddleware, metadataRoute(openIdMetadata)); + // RFC 9728 protected resource metadata, served by the mcp plugin itself. + app.get(['/.well-known/oauth-protected-resource', '/.well-known/oauth-protected-resource/mcp'], + corsMiddleware, toNodeHandler(auth)); // --- Sign-in page for OAuth consent flow --- app.get('/sign-in', (req, res) => { res.sendFile(join(__dirname, 'public', 'sign-in.html')); }); + app.get('/consent', (req, res) => { + res.sendFile(join(__dirname, 'public', 'consent.html')); + }); // Request logging for debugging app.use((req, res, next) => { @@ -152,21 +162,17 @@ export async function start() { return next(); } - // Otherwise validate as OAuth token via better-auth - try { - const session = await auth.api.getMcpSession({ - headers: req.headers, - }); - if (session) { - req.apiService = 'oauth'; - req.oauthSession = session; - return next(); - } - } catch { - // Fall through to 401 + // Otherwise validate as an OAuth access token issued by this server + const claims = await verifyAccessToken(token); + if (claims) { + req.apiService = 'oauth'; + req.oauthClaims = claims; + return next(); } } + // RFC 9728: point MCP clients at the metadata that starts the OAuth flow. + res.setHeader('WWW-Authenticate', `Bearer resource_metadata="${BASE_URL}/.well-known/oauth-protected-resource/mcp"`); return res.status(401).json({ error: 'Missing or invalid authentication. Provide X-API-Key header or OAuth Bearer token.' }); }; diff --git a/tests/auth-migrate.test.js b/tests/auth-migrate.test.js new file mode 100644 index 0000000..a335b6e --- /dev/null +++ b/tests/auth-migrate.test.js @@ -0,0 +1,95 @@ +// tests/auth-migrate.test.js — upgrading an auth.db created by the pre-1.7 +// better-auth `mcp` plugin (schema fixture taken from a production database). +import { describe, it, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import Database from 'better-sqlite3'; +import { hashPassword } from 'better-auth/crypto'; +import { createOAuthClient } from './helpers/oauth-flow.js'; + +const BASE = 'http://localhost:3838'; +const HOME = mkdtempSync(join(tmpdir(), 'kb-auth-migrate-test-')); +process.env.HOME = HOME; +process.env.BETTER_AUTH_URL = BASE; +process.env.BETTER_AUTH_SECRET = 'test-secret-0123456789abcdef0123456789abcdef'; + +const DB_PATH = join(HOME, '.knowledge-base', 'auth.db'); +const OWNER = { email: 'owner@example.test', password: 'correct horse battery staple' }; +const now = new Date().toISOString(); + +async function seedLegacyDatabase() { + mkdirSync(join(HOME, '.knowledge-base'), { recursive: true }); + const db = new Database(DB_PATH); + db.exec(readFileSync(join(import.meta.dirname, 'fixtures', 'auth-schema-better-auth-1.5.sql'), 'utf8')); + db.prepare('INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)') + .run('u1', 'Owner', OWNER.email, now, now); + db.prepare('INSERT INTO account (id, accountId, providerId, userId, password, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)') + .run('a1', 'u1', 'credential', 'u1', await hashPassword(OWNER.password), now, now); + db.prepare(`INSERT INTO oauthApplication (id, name, clientId, redirectUrls, type, disabled, userId, createdAt, updatedAt) + VALUES ('app1', 'Claude', 'legacy-client', 'https://claude.ai/api/mcp/auth_callback', 'public', 0, 'u1', ?, ?)`).run(now, now); + db.prepare(`INSERT INTO oauthAccessToken (id, accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt, clientId, userId, scopes, createdAt, updatedAt) + VALUES ('t1', 'legacy-access', 'legacy-refresh', ?, ?, 'legacy-client', 'u1', 'openid', ?, ?)`).run(now, now, now, now); + db.prepare(`INSERT INTO oauthConsent (id, clientId, userId, scopes, consentGiven, createdAt, updatedAt) + VALUES ('c1', 'legacy-client', 'u1', 'openid', 1, ?, ?)`).run(now, now); + db.close(); +} + +describe('auth schema upgrade from the pre-1.7 mcp plugin', () => { + let mod; + let archived; + + before(async () => { + await seedLegacyDatabase(); + mod = await import('../src/auth-oauth.js'); + archived = await mod.migrateAuthSchema(); + }); + + after(() => { + rmSync(HOME, { recursive: true, force: true }); + }); + + it('moves the legacy OAuth tables aside with their rows intact', () => { + assert.deepEqual(archived.sort(), ['legacy_oauthAccessToken', 'legacy_oauthApplication', 'legacy_oauthConsent']); + const db = new Database(DB_PATH, { readonly: true }); + try { + for (const table of archived) { + assert.equal(db.prepare(`SELECT count(*) AS n FROM "${table}"`).get().n, 1, `${table} lost rows`); + } + const columns = db.prepare(`SELECT name FROM pragma_table_info('oauthAccessToken')`).all().map(c => c.name); + assert.ok(columns.includes('token') && !columns.includes('accessToken'), 'oauthAccessToken was not recreated with the new schema'); + } finally { + db.close(); + } + }); + + it('gives the new tables their own indexes instead of colliding with the legacy ones', () => { + const db = new Database(DB_PATH, { readonly: true }); + try { + const indexes = db.prepare(`SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL`).all(); + const onTable = table => indexes.filter(i => i.tbl_name === table).map(i => i.name); + assert.ok(onTable('legacy_oauthAccessToken').every(name => name.startsWith('legacy_')), 'legacy indexes kept their old names'); + assert.ok(onTable('oauthAccessToken').length > 0, 'new oauthAccessToken table has no indexes'); + } finally { + db.close(); + } + }); + + it('is a no-op when run again', async () => { + assert.deepEqual(await mod.migrateAuthSchema(), []); + }); + + it('keeps existing accounts: the owner signs in and authorizes a new client', async () => { + const oauth = createOAuthClient(mod.auth, BASE); + const { res, cookie } = await oauth.signIn(OWNER.email, OWNER.password); + assert.equal(res.status, 200, 'existing account could not sign in after the upgrade'); + + const tokens = await oauth.exchange(await oauth.authorize(cookie)); + assert.ok(await mod.verifyAccessToken(tokens.access_token)); + }); + + it('does not accept tokens issued by the old plugin', async () => { + assert.equal(await mod.verifyAccessToken('legacy-access'), null); + }); +}); diff --git a/tests/auth-oauth.test.js b/tests/auth-oauth.test.js index c56700f..4e2c722 100644 --- a/tests/auth-oauth.test.js +++ b/tests/auth-oauth.test.js @@ -1,11 +1,11 @@ -// tests/auth-oauth.test.js — OAuth provider: who can get a token +// tests/auth-oauth.test.js — OAuth provider: who can get a token, and what it grants // Runs the real better-auth instance against an isolated HOME, in-process. import { describe, it, before, after } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { createHash, randomBytes } from 'node:crypto'; +import { createOAuthClient } from './helpers/oauth-flow.js'; const BASE = 'http://localhost:3838'; const HOME = mkdtempSync(join(tmpdir(), 'kb-auth-test-')); @@ -13,88 +13,19 @@ process.env.HOME = HOME; process.env.BETTER_AUTH_URL = BASE; process.env.BETTER_AUTH_SECRET = 'test-secret-0123456789abcdef0123456789abcdef'; -const b64url = buf => buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); -const JSON_HEADERS = { 'Content-Type': 'application/json', Origin: BASE }; +const OWNER = { email: 'owner@example.test', password: 'correct horse battery staple' }; let auth; -let discoveryHandler; - -function call(path, init = {}) { - return auth.handler(new Request(new URL(path, BASE), init)); -} - -async function signIn(email, password) { - const res = await call('/api/auth/sign-in/email', { - method: 'POST', - headers: JSON_HEADERS, - body: JSON.stringify({ email, password }), - }); - return { res, cookie: res.headers.getSetCookie().map(c => c.split(';')[0]).join('; ') }; -} - -// Dynamic client registration -> authorize with PKCE -> token exchange. -async function obtainAccessToken(cookie) { - const meta = await (await discoveryHandler(new Request(`${BASE}/.well-known/oauth-authorization-server`))).json(); - const redirectUri = 'http://localhost:9/callback'; - - const reg = await call(meta.registration_endpoint, { - method: 'POST', - headers: JSON_HEADERS, - body: JSON.stringify({ - client_name: 'test-client', - redirect_uris: [redirectUri], - token_endpoint_auth_method: 'none', - grant_types: ['authorization_code'], - response_types: ['code'], - }), - }); - assert.equal(reg.status, 201, 'client registration failed'); - const { client_id } = await reg.json(); - - const verifier = b64url(randomBytes(32)); - const challenge = b64url(createHash('sha256').update(verifier).digest()); - const authorizeUrl = new URL(meta.authorization_endpoint); - authorizeUrl.search = new URLSearchParams({ - response_type: 'code', - client_id, - redirect_uri: redirectUri, - code_challenge: challenge, - code_challenge_method: 'S256', - scope: 'openid profile email offline_access', - state: 'state-123', - }); - const authorize = await call(authorizeUrl, { headers: { Cookie: cookie } }); - const location = authorize.headers.get('location') || ''; - const code = new URL(location, BASE).searchParams.get('code'); - assert.ok(code, `authorize did not return a code (status ${authorize.status}, location ${location})`); - - const tokenRes = await call(meta.token_endpoint, { - method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id, code_verifier: verifier }), - }); - assert.equal(tokenRes.status, 200, 'token exchange failed'); - return (await tokenRes.json()).access_token; -} +let oauth; +let verifyAccessToken; describe('OAuth provider access', () => { before(async () => { - await import('../src/paths.js'); - ({ auth } = await import('../src/auth-oauth.js')); - const { getMigrations } = await import('better-auth/db/migration'); - await (await getMigrations(auth.options)).runMigrations(); - const { oAuthDiscoveryMetadata } = await import('better-auth/plugins'); - discoveryHandler = oAuthDiscoveryMetadata(auth); - - // Provision the operator account directly, the way an admin CLI would. - const ctx = await auth.$context; - const user = await ctx.internalAdapter.createUser({ email: 'owner@example.test', name: 'Owner', emailVerified: true }); - await ctx.internalAdapter.linkAccount({ - userId: user.id, - providerId: 'credential', - accountId: user.id, - password: await ctx.password.hash('correct horse battery staple'), - }); + const mod = await import('../src/auth-oauth.js'); + ({ auth, verifyAccessToken } = mod); + assert.deepEqual(await mod.migrateAuthSchema(), [], 'a fresh database has nothing to archive'); + await mod.addUser(OWNER); + oauth = createOAuthClient(auth, BASE); }); after(() => { @@ -102,9 +33,9 @@ describe('OAuth provider access', () => { }); it('rejects public sign-up, so outsiders cannot create an account', async () => { - const res = await call('/api/auth/sign-up/email', { + const res = await oauth.call('/api/auth/sign-up/email', { method: 'POST', - headers: JSON_HEADERS, + headers: oauth.jsonHeaders, body: JSON.stringify({ email: 'outsider@evil.test', password: 'Password123!', name: 'outsider' }), }); @@ -114,19 +45,52 @@ describe('OAuth provider access', () => { }); it('rejects a wrong password for the provisioned account', async () => { - const { res } = await signIn('owner@example.test', 'wrong password'); + const { res } = await oauth.signIn(OWNER.email, 'wrong password'); assert.ok(res.status >= 400, `sign-in with a wrong password should fail, got ${res.status}`); }); - it('lets the provisioned account complete the OAuth flow and use the token', async () => { - const { res, cookie } = await signIn('owner@example.test', 'correct horse battery staple'); + it('sends unauthenticated users to the sign-in page instead of issuing a code', async () => { + const meta = await (await oauth.call('/api/auth/.well-known/oauth-authorization-server')).json(); + const res = await oauth.call(`${meta.authorization_endpoint}?response_type=code&client_id=unknown&redirect_uri=https://x.test/cb`); + assert.ok(!new URL(res.headers.get('location') || 'http://x/', BASE).searchParams.get('code'), 'a code was issued without signing in'); + }); + + it('lets the provisioned account authorize a client and use the token', async () => { + const { res, cookie } = await oauth.signIn(OWNER.email, OWNER.password); assert.equal(res.status, 200, 'owner sign-in failed'); - const accessToken = await obtainAccessToken(cookie); - assert.ok(accessToken, 'no access token issued'); + const grant = await oauth.authorize(cookie); + const tokens = await oauth.exchange(grant); + + const claims = await verifyAccessToken(tokens.access_token); + assert.ok(claims, 'issued access token was not accepted'); + assert.ok([].concat(claims.aud).includes(`${BASE}/mcp`), 'token is not bound to the MCP resource'); + + const refreshed = await oauth.refresh(grant, tokens.refresh_token); + assert.ok(await verifyAccessToken(refreshed.access_token), 'refreshed access token was not accepted'); + }); + + it('accepts tokens for clients that connect at the bare origin', async () => { + const { cookie } = await oauth.signIn(OWNER.email, OWNER.password); + const tokens = await oauth.exchange(await oauth.authorize(cookie, { resource: BASE })); + assert.ok(await verifyAccessToken(tokens.access_token)); + }); + + it('issues no code when the user denies consent', async () => { + const { cookie } = await oauth.signIn(OWNER.email, OWNER.password); + const { redirect } = await oauth.authorize(cookie, { accept: false }); + assert.equal(redirect.searchParams.get('code'), null); + assert.equal(redirect.searchParams.get('error'), 'access_denied'); + }); + + it('rejects forged, tampered and foreign tokens', async () => { + const { cookie } = await oauth.signIn(OWNER.email, OWNER.password); + const tokens = await oauth.exchange(await oauth.authorize(cookie)); + const [header, payload, signature] = tokens.access_token.split('.'); + const forgedPayload = Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(payload, 'base64url')), sub: 'someone-else' })).toString('base64url'); - const session = await auth.api.getMcpSession({ headers: new Headers({ Authorization: `Bearer ${accessToken}` }) }); - assert.ok(session, 'issued token was not accepted'); - assert.equal((await auth.api.getMcpSession({ headers: new Headers({ Authorization: 'Bearer forged' }) })), null); + assert.equal(await verifyAccessToken('not-a-token'), null); + assert.equal(await verifyAccessToken(`${header}.${forgedPayload}.${signature}`), null, 'modified claims were accepted'); + assert.equal(await verifyAccessToken(`${header}.${payload}.${signature.slice(0, -4)}AAAA`), null, 'bad signature was accepted'); }); }); diff --git a/tests/fixtures/auth-schema-better-auth-1.5.sql b/tests/fixtures/auth-schema-better-auth-1.5.sql new file mode 100644 index 0000000..014ae6e --- /dev/null +++ b/tests/fixtures/auth-schema-better-auth-1.5.sql @@ -0,0 +1,15 @@ +CREATE TABLE IF NOT EXISTS "user" ("id" text not null primary key, "name" text not null, "email" text not null unique, "emailVerified" integer not null, "image" text, "createdAt" date not null, "updatedAt" date not null); +CREATE TABLE IF NOT EXISTS "session" ("id" text not null primary key, "expiresAt" date not null, "token" text not null unique, "createdAt" date not null, "updatedAt" date not null, "ipAddress" text, "userAgent" text, "userId" text not null references "user" ("id") on delete cascade); +CREATE TABLE IF NOT EXISTS "account" ("id" text not null primary key, "accountId" text not null, "providerId" text not null, "userId" text not null references "user" ("id") on delete cascade, "accessToken" text, "refreshToken" text, "idToken" text, "accessTokenExpiresAt" date, "refreshTokenExpiresAt" date, "scope" text, "password" text, "createdAt" date not null, "updatedAt" date not null); +CREATE TABLE IF NOT EXISTS "verification" ("id" text not null primary key, "identifier" text not null, "value" text not null, "expiresAt" date not null, "createdAt" date not null, "updatedAt" date not null); +CREATE TABLE IF NOT EXISTS "oauthApplication" ("id" text not null primary key, "name" text not null, "icon" text, "metadata" text, "clientId" text not null unique, "clientSecret" text, "redirectUrls" text not null, "type" text not null, "disabled" integer, "userId" text references "user" ("id") on delete cascade, "createdAt" date not null, "updatedAt" date not null); +CREATE TABLE IF NOT EXISTS "oauthAccessToken" ("id" text not null primary key, "accessToken" text not null unique, "refreshToken" text not null unique, "accessTokenExpiresAt" date not null, "refreshTokenExpiresAt" date not null, "clientId" text not null references "oauthApplication" ("clientId") on delete cascade, "userId" text references "user" ("id") on delete cascade, "scopes" text not null, "createdAt" date not null, "updatedAt" date not null); +CREATE TABLE IF NOT EXISTS "oauthConsent" ("id" text not null primary key, "clientId" text not null references "oauthApplication" ("clientId") on delete cascade, "userId" text not null references "user" ("id") on delete cascade, "scopes" text not null, "createdAt" date not null, "updatedAt" date not null, "consentGiven" integer not null); +CREATE INDEX "session_userId_idx" on "session" ("userId"); +CREATE INDEX "account_userId_idx" on "account" ("userId"); +CREATE INDEX "verification_identifier_idx" on "verification" ("identifier"); +CREATE INDEX "oauthApplication_userId_idx" on "oauthApplication" ("userId"); +CREATE INDEX "oauthAccessToken_clientId_idx" on "oauthAccessToken" ("clientId"); +CREATE INDEX "oauthAccessToken_userId_idx" on "oauthAccessToken" ("userId"); +CREATE INDEX "oauthConsent_clientId_idx" on "oauthConsent" ("clientId"); +CREATE INDEX "oauthConsent_userId_idx" on "oauthConsent" ("userId"); diff --git a/tests/helpers/oauth-flow.js b/tests/helpers/oauth-flow.js new file mode 100644 index 0000000..255eeef --- /dev/null +++ b/tests/helpers/oauth-flow.js @@ -0,0 +1,106 @@ +// tests/helpers/oauth-flow.js — drive the real OAuth provider in-process the way +// an MCP client (e.g. the Claude connector) does: discovery -> dynamic client +// registration -> sign in -> authorize -> consent -> token. +import assert from 'node:assert/strict'; +import { createHash, randomBytes } from 'node:crypto'; + +export const REDIRECT_URI = 'https://client.example.test/callback'; + +export function createOAuthClient(auth, baseUrl) { + const jsonHeaders = { 'Content-Type': 'application/json', Origin: baseUrl }; + const call = (path, init = {}) => auth.handler(new Request(new URL(path, baseUrl), init)); + + async function signIn(email, password) { + const res = await call('/api/auth/sign-in/email', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ email, password }), + }); + return { res, cookie: res.headers.getSetCookie().map(c => c.split(';')[0]).join('; ') }; + } + + async function metadata() { + const res = await call('/api/auth/.well-known/oauth-authorization-server'); + assert.equal(res.status, 200, 'authorization server metadata unavailable'); + return res.json(); + } + + async function register(meta) { + const res = await call(meta.registration_endpoint, { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ + client_name: 'Test MCP Client', + redirect_uris: [REDIRECT_URI], + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + }), + }); + assert.equal(res.status, 201, `client registration failed: ${await res.clone().text()}`); + return (await res.json()).client_id; + } + + /** Runs the flow up to the consent decision. Returns what the token step needs. */ + async function authorize(cookie, { resource = `${baseUrl}/mcp`, accept = true } = {}) { + const meta = await metadata(); + const clientId = await register(meta); + const verifier = randomBytes(32).toString('base64url'); + const query = new URLSearchParams({ + response_type: 'code', + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_challenge: createHash('sha256').update(verifier).digest('base64url'), + code_challenge_method: 'S256', + scope: 'openid profile email offline_access', + state: 'state-123', + }); + if (resource) query.set('resource', resource); + + const authz = await call(`${meta.authorization_endpoint}?${query}`, { headers: { Cookie: cookie } }); + const consentUrl = new URL(authz.headers.get('location') || '', baseUrl); + assert.equal(consentUrl.pathname, '/consent', `expected the consent page, got ${consentUrl}`); + + const consent = await call('/api/auth/oauth2/consent', { + method: 'POST', + headers: { ...jsonHeaders, Cookie: cookie }, + body: JSON.stringify({ accept, oauth_query: consentUrl.search.slice(1) }), + }); + const { url } = await consent.json(); + return { meta, clientId, verifier, resource, redirect: new URL(url) }; + } + + async function exchange({ meta, clientId, verifier, resource, redirect }) { + const code = redirect.searchParams.get('code'); + assert.ok(code, `no authorization code in ${redirect}`); + const body = new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: REDIRECT_URI, + client_id: clientId, + code_verifier: verifier, + }); + if (resource) body.set('resource', resource); + const res = await call(meta.token_endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }); + assert.equal(res.status, 200, `token exchange failed: ${await res.clone().text()}`); + return res.json(); + } + + async function refresh({ meta, clientId, resource }, refreshToken) { + const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: clientId }); + if (resource) body.set('resource', resource); + const res = await call(meta.token_endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body, + }); + assert.equal(res.status, 200, `refresh failed: ${await res.clone().text()}`); + return res.json(); + } + + return { call, jsonHeaders, signIn, authorize, exchange, refresh }; +}