Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 92 additions & 5 deletions .github/scripts/package-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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,
Expand Down Expand Up @@ -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) {
Expand All @@ -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; });
Expand All @@ -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',
Expand All @@ -137,6 +223,7 @@ async function httpServer() {
try {
await mcpHandshake();
busRoundTrip();
addOwner();
await httpServer();
console.log('\n✔ package smoke test passed');
} finally {
Expand Down
24 changes: 15 additions & 9 deletions EXTENDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <token>` 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 `<BETTER_AUTH_URL>/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

Expand Down Expand Up @@ -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`.

---

Expand Down Expand Up @@ -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 <email>`. 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.

Expand All @@ -442,14 +442,20 @@ BETTER_AUTH_SECRET=<random-64-char-string>
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.

---

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions bin/kb.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]) {
Expand All @@ -128,6 +129,7 @@ Commands:
capture-fix-json <payload.json> [vault] Capture a fix from JSON
export Export vault docs to a portable bundle (--out=dir, --dry-run, --json)
restore <bundle> Restore from a bundle (--dry-run, --overwrite, --yes, --strict, --no-embeddings)
auth add-user <email> Create an account that can approve OAuth/MCP clients (--password-stdin)
setup Interactive setup wizard (--auto for agent mode)
`);
process.exit(command ? 1 : 0);
Expand Down
Loading
Loading