Connect your users' KnowledgeBases

OAuth 2 authorization code with PKCE. Your user picks the record and the exact details your app may read. You read only those, and they can narrow or revoke access from Connected Apps at any time.

Set up

  1. Register an app with your exact redirect address (https, or http on localhost), then create a client secret. It's shown once.
  2. Ask only for the permissions you need. Users can untick any of them.
  3. Keep the secret and tokens on your server. Public clients (no secret) are only for assistants that register themselves through MCP.
kb:readRead approved knowledge. See the approved items in the knowledgebases you choose.
kb:searchSearch approved knowledge. Search those items.
kb:answerAsk questions. Get answers written from those items, with sources.
changes:readGet notified of updates. Find out when you publish a new version.

The flow

import { createHash, randomBytes } from "node:crypto";

// 1. Send the user to the permission screen.
const verifier = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
const state = randomBytes(16).toString("base64url");
session.set({ verifier, state });
redirect(`https://knowledgebase.org/oauth/authorize?` + new URLSearchParams({
  response_type: "code",
  client_id: process.env.KB_CLIENT_ID,
  redirect_uri: "https://yourapp.example/kb/callback",
  scope: "kb:read kb:search kb:answer changes:read",
  state,
  code_challenge: challenge,
  code_challenge_method: "S256",
}));

// 2. Callback: check state, exchange the code (server side, with your secret).
const basic = Buffer.from(`${process.env.KB_CLIENT_ID}:${process.env.KB_CLIENT_SECRET}`).toString("base64");
const tokens = await fetch("https://knowledgebase.org/oauth/token", {
  method: "POST",
  headers: { Authorization: `Basic ${basic}`, "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: "https://yourapp.example/kb/callback", code_verifier: session.verifier }),
}).then((r) => r.json()); // { access_token, refresh_token, expires_in: 3600, scope }

// 3. Read what the user granted.
const auth = { Authorization: `Bearer ${tokens.access_token}` };
const { data } = await fetch("https://knowledgebase.org/v1/knowledge-bases", { headers: auth }).then((r) => r.json());
const fields = await fetch(`https://knowledgebase.org/v1/knowledge-bases/${data[0].slug}/fields`, { headers: auth }).then((r) => r.json());

// 4. Disconnect from your side when the user asks.
await fetch("https://knowledgebase.org/oauth/revoke", { method: "POST", headers: { Authorization: `Basic ${basic}` }, body: new URLSearchParams({ token: tokens.refresh_token }) });
GET/oauth/authorizeThe permission screen. response_type=code, client_id, redirect_uri, scope, state, code_challenge (S256).
POST/oauth/tokenauthorization_code (with code_verifier) or refresh_token. HTTP Basic client authentication.
POST/oauth/revokeRevoke your own access or refresh token (RFC 7009).

What the user decides

Which KnowledgeBase

Only records they own. A company's linked locations or products are separate choices.

Which details

"Only the details I choose" (the default) or "Everything, including details I approve later". Responses say scope: "selected" or "full".

What you may do

Read, search, ask, and get notified of updates. Never write, publish or export.

For how long

30 days, 90 days, a year, or until they disconnect. Expired grants refuse the next refresh.

Active grants show on their Connected Apps page with exactly what each app can read and which version it last read. Narrowing applies to tokens you already hold.

Stay current, and clean up

Verify a webhook signature

import { createHmac, timingSafeEqual } from "node:crypto";

// header: Knowledgebase-Signature: t=1764000000,v1=<hex>[,v1=<hex during secret rotation>]
export function verify(rawBody, header, secret) {
  const parts = header.split(",").map((p) => p.split("="));
  const t = Number(parts.find(([k]) => k === "t")?.[1]);
  if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false; // reject old deliveries
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  return parts.some(([k, v]) => k === "v1" && v.length === expected.length * 2 && timingSafeEqual(Buffer.from(v, "hex"), expected));
}

Run the demo

examples/connect-demo in the repository is a complete app on its own origin: connect, token exchange, granted fields, a cited answer, the change feed, and deleting its cache when disconnected.

KB_URL=https://knowledgebase.org CLIENT_ID=kbapp_... CLIENT_SECRET=kbsec_... node examples/connect-demo/server.mjs
# then open http://localhost:4400 (register http://localhost:4400/callback as the redirect)