bookstack-mcp 4.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -144,6 +144,17 @@ When binding to `0.0.0.0` (e.g. inside a container reachable from other services
144
144
 
145
145
  Restart LibreChat after config changes.
146
146
 
147
+ ### Remote hosting & Claude Connector (Docker + Entra OAuth)
148
+
149
+ A container image is published to `ghcr.io/ttpears/bookstack-mcp` (released `:X.Y.Z`/`:latest`,
150
+ plus per-PR preview tags `:branch-<slug>`). The server can run as a public **Claude Connector**
151
+ gated by Microsoft 365 / Entra ID login — users sign in, no API key or client credential to
152
+ paste; write tools are unlocked per session by an Entra app role.
153
+
154
+ See **[docs/SETUP.md](docs/SETUP.md)** for the full runbook: Entra app registration steps,
155
+ the environment-variable reference, internal LibreChat deployment, and the public OAuth
156
+ connector setup.
157
+
147
158
  ### Claude Code (CLI)
148
159
 
149
160
  The recommended path is the `ttpears/claude-plugins` marketplace, which ships this repo's plugin manifest (`.claude-plugin/plugin.json`):
package/dist/index.js CHANGED
@@ -10,6 +10,8 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
10
10
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
11
11
  import { z } from "zod";
12
12
  import { BookStackClient } from "./bookstack-client.js";
13
+ import { registerPrompts } from "./prompts.js";
14
+ import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
13
15
  const PKG_VERSION = (() => {
14
16
  try {
15
17
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
@@ -45,6 +47,7 @@ function buildServer(config) {
45
47
  });
46
48
  registerTools(server, client, config);
47
49
  registerResources(server, client);
50
+ registerPrompts(server);
48
51
  return server;
49
52
  }
50
53
  function registerResources(server, client) {
@@ -768,7 +771,7 @@ function registerTools(server, client, config) {
768
771
  }
769
772
  }
770
773
  async function startStdio(config) {
771
- const server = buildServer(config);
774
+ const server = buildServer(config.read);
772
775
  const transport = new StdioServerTransport();
773
776
  await server.connect(transport);
774
777
  console.error("BookStack MCP server running on stdio");
@@ -799,6 +802,8 @@ async function startHttp(config) {
799
802
  return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
800
803
  };
801
804
  const transports = {};
805
+ // Per-session auth binding (OAuth mode only): subject + resolved write status, fixed at init.
806
+ const sessionAuth = {};
802
807
  const readJsonBody = (req) => new Promise((resolve, reject) => {
803
808
  const chunks = [];
804
809
  req.on("data", (c) => chunks.push(c));
@@ -826,10 +831,24 @@ async function startHttp(config) {
826
831
  sendJson(res, 421, { error: "Misdirected Request", message: hostError });
827
832
  return;
828
833
  }
834
+ // OAuth proxy surface (discovery metadata, DCR, authorize/callback/token).
835
+ if (config.oauth && (await handleOAuthRoutes(req, res, config.oauth))) {
836
+ return;
837
+ }
829
838
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
830
839
  const pathname = url.pathname;
831
840
  // Streamable HTTP endpoint (recommended)
832
841
  if (pathname === mcpPath) {
842
+ // Enforce the bearer and resolve the caller's authorization when OAuth is enabled.
843
+ let auth = null;
844
+ if (config.oauth) {
845
+ const result = await validateBearer(req, config.oauth);
846
+ if (!result.ok) {
847
+ sendUnauthorized(res, config.oauth);
848
+ return;
849
+ }
850
+ auth = { sub: result.sub, isWriter: !!result.isWriter };
851
+ }
833
852
  const sessionId = req.headers["mcp-session-id"];
834
853
  let transport;
835
854
  let parsedBody;
@@ -837,21 +856,38 @@ async function startHttp(config) {
837
856
  parsedBody = await readJsonBody(req);
838
857
  }
839
858
  if (sessionId && transports[sessionId]) {
859
+ // Reject a valid token belonging to a different subject than the session was bound to.
860
+ if (config.oauth && sessionAuth[sessionId] && auth?.sub !== sessionAuth[sessionId].sub) {
861
+ sendJson(res, 403, {
862
+ jsonrpc: "2.0",
863
+ error: { code: -32003, message: "Forbidden: token does not match session" },
864
+ id: null
865
+ });
866
+ return;
867
+ }
840
868
  transport = transports[sessionId];
841
869
  }
842
870
  else if (!sessionId && req.method === "POST" && isInitializeRequest(parsedBody)) {
871
+ // Choose the per-session credential: writers (with a write token configured) get the
872
+ // write token and write tools; everyone else gets the read-only token.
873
+ const useWrite = !!(auth?.isWriter && config.write);
874
+ const sessionConfig = useWrite ? config.write : config.read;
843
875
  transport = new StreamableHTTPServerTransport({
844
876
  sessionIdGenerator: () => randomUUID(),
845
877
  onsessioninitialized: (sid) => {
846
878
  transports[sid] = transport;
879
+ if (config.oauth && auth)
880
+ sessionAuth[sid] = auth;
847
881
  }
848
882
  });
849
883
  transport.onclose = () => {
850
884
  const sid = transport.sessionId;
851
885
  if (sid && transports[sid])
852
886
  delete transports[sid];
887
+ if (sid && sessionAuth[sid])
888
+ delete sessionAuth[sid];
853
889
  };
854
- const server = buildServer(config);
890
+ const server = buildServer(sessionConfig);
855
891
  await server.connect(transport);
856
892
  }
857
893
  else {
@@ -905,17 +941,47 @@ async function startHttp(config) {
905
941
  process.on("SIGTERM", shutdown);
906
942
  }
907
943
  async function main() {
908
- const config = {
909
- baseUrl: getRequiredEnvVar('BOOKSTACK_BASE_URL'),
944
+ const baseUrl = getRequiredEnvVar('BOOKSTACK_BASE_URL');
945
+ const insecureSkipTlsVerify = process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true';
946
+ const envEnableWrite = process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true';
947
+ const oauth = loadOAuthConfig(process.env);
948
+ // Initialize the OAuth broker-state store (Redis when REDIS_URL is set) before
949
+ // the server handles any request, so DCR clients / pending flows / codes persist.
950
+ if (oauth) {
951
+ await initOAuthStore(process.env, oauth.serverUrl);
952
+ }
953
+ // The read-only credential is required. In OAuth mode it always runs read-only (write is
954
+ // reserved for role-bearing sessions on the separate write token); otherwise the legacy
955
+ // BOOKSTACK_ENABLE_WRITE flag governs it.
956
+ const read = {
957
+ baseUrl,
910
958
  tokenId: getRequiredEnvVar('BOOKSTACK_TOKEN_ID'),
911
959
  tokenSecret: getRequiredEnvVar('BOOKSTACK_TOKEN_SECRET'),
912
- enableWrite: process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true',
913
- insecureSkipTlsVerify: process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true'
960
+ enableWrite: oauth ? false : envEnableWrite,
961
+ insecureSkipTlsVerify
914
962
  };
963
+ // The write credential is optional and only used by the OAuth proxy for sessions whose
964
+ // token carries the configured app role.
965
+ const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
966
+ const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
967
+ const write = (writeTokenId && writeTokenSecret)
968
+ ? { baseUrl, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true, insecureSkipTlsVerify }
969
+ : null;
970
+ const config = { read, write, oauth };
915
971
  console.error('Initializing BookStack MCP Server...');
916
- console.error(`BookStack URL: ${config.baseUrl}`);
917
- console.error(`Write operations: ${config.enableWrite ? 'ENABLED' : 'DISABLED'}`);
918
- if (config.insecureSkipTlsVerify) {
972
+ console.error(`BookStack URL: ${baseUrl}`);
973
+ if (oauth) {
974
+ console.error(`Auth: Entra OAuth proxy ENABLED (tenant ${oauth.tenantId})`);
975
+ console.error(` Public URL: ${oauth.serverUrl}`);
976
+ console.error(` Write role: ${oauth.writeRole}`);
977
+ if (!write) {
978
+ console.error(' WARNING: no BOOKSTACK_WRITE_TOKEN_ID/SECRET set — all sessions are read-only regardless of role.');
979
+ }
980
+ }
981
+ else {
982
+ console.error(`Auth: none (token-only mode); Write operations: ${read.enableWrite ? 'ENABLED' : 'DISABLED'}`);
983
+ }
984
+ if (insecureSkipTlsVerify) {
919
985
  console.error('WARNING: TLS certificate verification is DISABLED (BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=true). Connections to BookStack are vulnerable to MITM attacks. Use only with trusted self-signed certs on a trusted network.');
920
986
  }
921
987
  const transportMode = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();
@@ -0,0 +1,379 @@
1
+ // Entra (Microsoft 365) OAuth proxy for remote MCP / Claude Connectors.
2
+ //
3
+ // Modeled on zereight/gitlab-mcp's GITLAB_MCP_OAUTH mode: the MCP server hosts the
4
+ // OAuth surface Claude expects (discovery metadata + Dynamic Client Registration +
5
+ // authorize/token) and brokers the real login upstream to Entra ID. Claude self-registers
6
+ // (DCR is handled locally — Entra never sees it), logs the user in against the tenant, and
7
+ // receives the Entra access token, which the MCP server validates statelessly per request.
8
+ //
9
+ // This module is deliberately BookStack-agnostic so it can be reused across the MCP fleet.
10
+ // The only app-specific glue (mapping the `roles` claim to which credential/tool set to use)
11
+ // lives in the caller.
12
+ import { randomUUID, createHash, randomBytes } from "node:crypto";
13
+ import { createRemoteJWKSet, jwtVerify } from "jose";
14
+ import { InMemoryKvStore, createStore } from "./kv-store.js";
15
+ // Load config from env. Returns null when OAuth proxy mode is disabled.
16
+ export function loadOAuthConfig(env) {
17
+ if (env.MCP_OAUTH_ENABLE?.toLowerCase() !== "true")
18
+ return null;
19
+ const missing = [];
20
+ const req = (name) => {
21
+ const v = env[name];
22
+ if (!v)
23
+ missing.push(name);
24
+ return v ?? "";
25
+ };
26
+ const serverUrl = req("MCP_SERVER_URL").replace(/\/+$/, "");
27
+ const tenantId = req("OAUTH_TENANT_ID");
28
+ const clientId = req("OAUTH_CLIENT_ID");
29
+ const clientSecret = req("OAUTH_CLIENT_SECRET");
30
+ if (missing.length) {
31
+ console.error(`Error: MCP_OAUTH_ENABLE=true but missing required vars: ${missing.join(", ")}`);
32
+ process.exit(1);
33
+ }
34
+ const audience = env.OAUTH_AUDIENCE || `api://${clientId}`;
35
+ const scopes = env.OAUTH_SCOPES || `openid profile offline_access ${audience}/.default`;
36
+ const writeRole = env.OAUTH_WRITE_ROLE || "Writer";
37
+ const trustProxy = env.MCP_TRUST_PROXY?.toLowerCase() === "true";
38
+ const base = `https://login.microsoftonline.com/${tenantId}`;
39
+ return {
40
+ serverUrl,
41
+ tenantId,
42
+ clientId,
43
+ clientSecret,
44
+ audience,
45
+ scopes,
46
+ writeRole,
47
+ trustProxy,
48
+ authorizeEndpoint: `${base}/oauth2/v2.0/authorize`,
49
+ tokenEndpoint: `${base}/oauth2/v2.0/token`,
50
+ issuers: [
51
+ `${base}/v2.0`,
52
+ `https://sts.windows.net/${tenantId}/`,
53
+ ],
54
+ jwksUri: `${base}/discovery/v2.0/keys`,
55
+ };
56
+ }
57
+ const TTL_CLIENT = 1000 * 60 * 60 * 24 * 30; // 30d
58
+ const TTL_PENDING = 1000 * 60 * 10; // 10m
59
+ const TTL_CODE = 1000 * 60 * 5; // 5m
60
+ // Default to in-memory; initOAuthStore() upgrades to Redis when REDIS_URL is set.
61
+ // Keys: client:<id>, pending:<state>, code:<code>. TTL handled by the store.
62
+ let store = new InMemoryKvStore();
63
+ /**
64
+ * Initialize the broker-state store from the environment. With REDIS_URL set,
65
+ * broker state (DCR clients, pending flows, issued codes) persists across
66
+ * redeploys and can be shared by multiple replicas. Call once at startup; keys
67
+ * are namespaced by issuer host so co-tenant MCPs can share one Redis.
68
+ */
69
+ export async function initOAuthStore(env, serverUrl) {
70
+ let host = "default";
71
+ try {
72
+ host = new URL(serverUrl).host;
73
+ }
74
+ catch {
75
+ /* keep default */
76
+ }
77
+ const prefix = `${env.REDIS_KEY_PREFIX || "bookstack-mcp"}:${host}`;
78
+ store = await createStore(env.REDIS_URL, prefix);
79
+ }
80
+ // ---- HTTP helpers ----
81
+ function sendJson(res, status, body) {
82
+ res.writeHead(status, {
83
+ "Content-Type": "application/json",
84
+ "Cache-Control": "no-store",
85
+ });
86
+ res.end(JSON.stringify(body));
87
+ }
88
+ function readBody(req) {
89
+ return new Promise((resolve, reject) => {
90
+ const chunks = [];
91
+ req.on("data", (c) => chunks.push(c));
92
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
93
+ req.on("error", reject);
94
+ });
95
+ }
96
+ function parseForm(raw) {
97
+ const out = {};
98
+ for (const [k, v] of new URLSearchParams(raw))
99
+ out[k] = v;
100
+ return out;
101
+ }
102
+ function s256(verifier) {
103
+ return createHash("sha256").update(verifier).digest("base64url");
104
+ }
105
+ // ---- JWKS / token validation ----
106
+ let jwks = null;
107
+ function getJwks(cfg) {
108
+ if (!jwks)
109
+ jwks = createRemoteJWKSet(new URL(cfg.jwksUri));
110
+ return jwks;
111
+ }
112
+ function audienceMatches(cfg, aud) {
113
+ const accepted = new Set([cfg.audience, cfg.clientId, `api://${cfg.clientId}`]);
114
+ if (typeof aud === "string")
115
+ return accepted.has(aud);
116
+ if (Array.isArray(aud))
117
+ return aud.some((a) => accepted.has(a));
118
+ return false;
119
+ }
120
+ export async function validateBearer(req, cfg) {
121
+ const header = req.headers["authorization"];
122
+ if (!header || Array.isArray(header) || !header.startsWith("Bearer ")) {
123
+ return { ok: false, error: "missing bearer token" };
124
+ }
125
+ const token = header.slice("Bearer ".length).trim();
126
+ try {
127
+ const { payload } = await jwtVerify(token, getJwks(cfg), {
128
+ issuer: cfg.issuers,
129
+ });
130
+ if (!audienceMatches(cfg, payload.aud)) {
131
+ return { ok: false, error: "audience mismatch" };
132
+ }
133
+ const roles = Array.isArray(payload.roles)
134
+ ? payload.roles
135
+ : [];
136
+ return {
137
+ ok: true,
138
+ sub: typeof payload.sub === "string" ? payload.sub : undefined,
139
+ roles,
140
+ isWriter: roles.includes(cfg.writeRole),
141
+ };
142
+ }
143
+ catch (err) {
144
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
145
+ }
146
+ }
147
+ // Emit the 401 that bootstraps Claude's OAuth discovery (RFC 9728).
148
+ export function sendUnauthorized(res, cfg) {
149
+ res.writeHead(401, {
150
+ "Content-Type": "application/json",
151
+ "WWW-Authenticate": `Bearer resource_metadata="${cfg.serverUrl}/.well-known/oauth-protected-resource"`,
152
+ });
153
+ res.end(JSON.stringify({
154
+ jsonrpc: "2.0",
155
+ error: { code: -32001, message: "Unauthorized: authentication required" },
156
+ id: null,
157
+ }));
158
+ }
159
+ // ---- OAuth route handling ----
160
+ // Returns true if this request was an OAuth endpoint (handled here), false otherwise.
161
+ export async function handleOAuthRoutes(req, res, cfg) {
162
+ const url = new URL(req.url ?? "/", cfg.serverUrl);
163
+ const path = url.pathname;
164
+ if (["/register", "/authorize", "/callback", "/token"].includes(path)) {
165
+ console.error(`[oauth] ${req.method} ${path}` +
166
+ (path === "/callback"
167
+ ? ` error=${url.searchParams.get("error") ?? ""} code=${url.searchParams.get("code") ? "yes" : "no"} state=${url.searchParams.get("state") ? "yes" : "no"}`
168
+ : ""));
169
+ }
170
+ // RFC 9728 — Protected Resource Metadata
171
+ if (path === "/.well-known/oauth-protected-resource") {
172
+ sendJson(res, 200, {
173
+ resource: cfg.serverUrl,
174
+ authorization_servers: [cfg.serverUrl],
175
+ bearer_methods_supported: ["header"],
176
+ scopes_supported: cfg.scopes.split(/\s+/).filter(Boolean),
177
+ });
178
+ return true;
179
+ }
180
+ // RFC 8414 — Authorization Server Metadata (we ARE the AS, proxying to Entra)
181
+ if (path === "/.well-known/oauth-authorization-server") {
182
+ sendJson(res, 200, {
183
+ issuer: cfg.serverUrl,
184
+ authorization_endpoint: `${cfg.serverUrl}/authorize`,
185
+ token_endpoint: `${cfg.serverUrl}/token`,
186
+ registration_endpoint: `${cfg.serverUrl}/register`,
187
+ response_types_supported: ["code"],
188
+ grant_types_supported: ["authorization_code", "refresh_token"],
189
+ code_challenge_methods_supported: ["S256"],
190
+ token_endpoint_auth_methods_supported: ["none"],
191
+ scopes_supported: cfg.scopes.split(/\s+/).filter(Boolean),
192
+ });
193
+ return true;
194
+ }
195
+ // RFC 7591 — Dynamic Client Registration (handled locally)
196
+ if (path === "/register" && req.method === "POST") {
197
+ let meta = {};
198
+ try {
199
+ meta = JSON.parse((await readBody(req)) || "{}");
200
+ }
201
+ catch {
202
+ sendJson(res, 400, { error: "invalid_client_metadata" });
203
+ return true;
204
+ }
205
+ const redirectUris = Array.isArray(meta.redirect_uris)
206
+ ? meta.redirect_uris
207
+ : [];
208
+ if (redirectUris.length === 0) {
209
+ sendJson(res, 400, {
210
+ error: "invalid_redirect_uri",
211
+ error_description: "redirect_uris is required",
212
+ });
213
+ return true;
214
+ }
215
+ const clientId = `mcp-${randomUUID()}`;
216
+ await store.set(`client:${clientId}`, { clientId, redirectUris }, TTL_CLIENT);
217
+ sendJson(res, 201, {
218
+ client_id: clientId,
219
+ redirect_uris: redirectUris,
220
+ token_endpoint_auth_method: "none",
221
+ grant_types: ["authorization_code", "refresh_token"],
222
+ response_types: ["code"],
223
+ });
224
+ return true;
225
+ }
226
+ // Authorization endpoint — redirect the browser up to Entra.
227
+ if (path === "/authorize" && req.method === "GET") {
228
+ const q = url.searchParams;
229
+ const clientId = q.get("client_id") ?? "";
230
+ const redirectUri = q.get("redirect_uri") ?? "";
231
+ const clientState = q.get("state") ?? "";
232
+ const codeChallenge = q.get("code_challenge") ?? "";
233
+ const method = q.get("code_challenge_method") ?? "";
234
+ const client = await store.get(`client:${clientId}`);
235
+ if (!client) {
236
+ sendJson(res, 400, { error: "invalid_client" });
237
+ return true;
238
+ }
239
+ if (!client.redirectUris.includes(redirectUri)) {
240
+ sendJson(res, 400, { error: "invalid_request", error_description: "redirect_uri mismatch" });
241
+ return true;
242
+ }
243
+ if (method !== "S256" || !codeChallenge) {
244
+ sendJson(res, 400, { error: "invalid_request", error_description: "PKCE S256 required" });
245
+ return true;
246
+ }
247
+ const upstreamState = randomBytes(24).toString("base64url");
248
+ await store.set(`pending:${upstreamState}`, {
249
+ clientId,
250
+ clientRedirectUri: redirectUri,
251
+ clientState,
252
+ codeChallenge,
253
+ }, TTL_PENDING);
254
+ const up = new URL(cfg.authorizeEndpoint);
255
+ up.searchParams.set("client_id", cfg.clientId);
256
+ up.searchParams.set("response_type", "code");
257
+ up.searchParams.set("redirect_uri", `${cfg.serverUrl}/callback`);
258
+ up.searchParams.set("response_mode", "query");
259
+ up.searchParams.set("scope", cfg.scopes);
260
+ up.searchParams.set("state", upstreamState);
261
+ res.writeHead(302, { Location: up.toString() });
262
+ res.end();
263
+ return true;
264
+ }
265
+ // Callback from Entra — exchange code upstream, then hand our own code to the client.
266
+ if (path === "/callback" && req.method === "GET") {
267
+ const q = url.searchParams;
268
+ const upstreamState = q.get("state") ?? "";
269
+ const code = q.get("code") ?? "";
270
+ const err = q.get("error");
271
+ const p = await store.get(`pending:${upstreamState}`);
272
+ if (!p) {
273
+ sendJson(res, 400, { error: "invalid_state" });
274
+ return true;
275
+ }
276
+ await store.del(`pending:${upstreamState}`);
277
+ if (err || !code) {
278
+ const dest = new URL(p.clientRedirectUri);
279
+ dest.searchParams.set("error", err || "invalid_request");
280
+ if (p.clientState)
281
+ dest.searchParams.set("state", p.clientState);
282
+ res.writeHead(302, { Location: dest.toString() });
283
+ res.end();
284
+ return true;
285
+ }
286
+ // Confidential-client code exchange with Entra.
287
+ const tokenRes = await fetch(cfg.tokenEndpoint, {
288
+ method: "POST",
289
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
290
+ body: new URLSearchParams({
291
+ client_id: cfg.clientId,
292
+ client_secret: cfg.clientSecret,
293
+ grant_type: "authorization_code",
294
+ code,
295
+ redirect_uri: `${cfg.serverUrl}/callback`,
296
+ scope: cfg.scopes,
297
+ }),
298
+ });
299
+ const rawTok = await tokenRes.text();
300
+ let tokenJson = null;
301
+ try {
302
+ tokenJson = JSON.parse(rawTok);
303
+ }
304
+ catch { /* non-JSON */ }
305
+ if (!tokenRes.ok || !tokenJson || !tokenJson.access_token) {
306
+ console.error(`[oauth] /callback Entra token exchange FAILED: status=${tokenRes.status} body=${rawTok.slice(0, 600)}`);
307
+ const dest = new URL(p.clientRedirectUri);
308
+ dest.searchParams.set("error", "server_error");
309
+ if (p.clientState)
310
+ dest.searchParams.set("state", p.clientState);
311
+ res.writeHead(302, { Location: dest.toString() });
312
+ res.end();
313
+ return true;
314
+ }
315
+ console.error("[oauth] /callback Entra token exchange OK; issuing client code");
316
+ const ourCode = randomBytes(32).toString("base64url");
317
+ await store.set(`code:${ourCode}`, {
318
+ clientId: p.clientId,
319
+ clientRedirectUri: p.clientRedirectUri,
320
+ codeChallenge: p.codeChallenge,
321
+ tokenResponse: tokenJson,
322
+ }, TTL_CODE);
323
+ const dest = new URL(p.clientRedirectUri);
324
+ dest.searchParams.set("code", ourCode);
325
+ if (p.clientState)
326
+ dest.searchParams.set("state", p.clientState);
327
+ res.writeHead(302, { Location: dest.toString() });
328
+ res.end();
329
+ return true;
330
+ }
331
+ // Token endpoint — code exchange (verify PKCE) and refresh pass-through.
332
+ if (path === "/token" && req.method === "POST") {
333
+ const form = parseForm(await readBody(req));
334
+ const grant = form["grant_type"];
335
+ if (grant === "authorization_code") {
336
+ const issued = await store.get(`code:${form["code"] ?? ""}`);
337
+ if (!issued) {
338
+ console.error("[oauth] /token authorization_code: invalid_grant (code not found/expired)");
339
+ sendJson(res, 400, { error: "invalid_grant" });
340
+ return true;
341
+ }
342
+ await store.del(`code:${form["code"]}`);
343
+ const verifier = form["code_verifier"] ?? "";
344
+ if (!verifier || s256(verifier) !== issued.codeChallenge) {
345
+ console.error(`[oauth] /token authorization_code: PKCE FAILED (verifier=${verifier ? "present" : "missing"})`);
346
+ sendJson(res, 400, { error: "invalid_grant", error_description: "PKCE verification failed" });
347
+ return true;
348
+ }
349
+ if (form["client_id"] && form["client_id"] !== issued.clientId) {
350
+ console.error(`[oauth] /token authorization_code: client mismatch (got=${form["client_id"]} want=${issued.clientId})`);
351
+ sendJson(res, 400, { error: "invalid_client" });
352
+ return true;
353
+ }
354
+ console.error("[oauth] /token authorization_code: OK (returning Entra token to client)");
355
+ sendJson(res, 200, issued.tokenResponse);
356
+ return true;
357
+ }
358
+ if (grant === "refresh_token") {
359
+ // Proxy the refresh straight to Entra (confidential client).
360
+ const refreshRes = await fetch(cfg.tokenEndpoint, {
361
+ method: "POST",
362
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
363
+ body: new URLSearchParams({
364
+ client_id: cfg.clientId,
365
+ client_secret: cfg.clientSecret,
366
+ grant_type: "refresh_token",
367
+ refresh_token: form["refresh_token"] ?? "",
368
+ scope: cfg.scopes,
369
+ }),
370
+ });
371
+ const refreshJson = await refreshRes.json().catch(() => null);
372
+ sendJson(res, refreshRes.ok ? 200 : 400, refreshJson ?? { error: "invalid_grant" });
373
+ return true;
374
+ }
375
+ sendJson(res, 400, { error: "unsupported_grant_type" });
376
+ return true;
377
+ }
378
+ return false;
379
+ }
@@ -0,0 +1,79 @@
1
+ // Minimal async key/value store with per-key TTL for the OAuth proxy's broker
2
+ // state (DCR clients, pending flows, issued codes). Redis-backed when REDIS_URL
3
+ // is set — so state survives redeploys and can run more than one replica —
4
+ // otherwise in-process memory. Mirrors the store in ttpears/gitlab-mcp.
5
+ const SWEEP_INTERVAL_MS = 5 * 60 * 1000;
6
+ /** In-process store with lazy expiry on read plus a periodic sweep. */
7
+ export class InMemoryKvStore {
8
+ prefix;
9
+ map = new Map();
10
+ sweep;
11
+ constructor(prefix = "bookstack-mcp:") {
12
+ this.prefix = prefix;
13
+ this.sweep = setInterval(() => {
14
+ const now = Date.now();
15
+ for (const [k, v] of this.map)
16
+ if (v.expiresAt < now)
17
+ this.map.delete(k);
18
+ }, SWEEP_INTERVAL_MS);
19
+ this.sweep.unref?.();
20
+ }
21
+ async get(key) {
22
+ const entry = this.map.get(this.prefix + key);
23
+ if (!entry)
24
+ return undefined;
25
+ if (entry.expiresAt < Date.now()) {
26
+ this.map.delete(this.prefix + key);
27
+ return undefined;
28
+ }
29
+ return entry.value;
30
+ }
31
+ async set(key, value, ttlMs) {
32
+ this.map.set(this.prefix + key, { value, expiresAt: Date.now() + ttlMs });
33
+ }
34
+ async del(key) {
35
+ this.map.delete(this.prefix + key);
36
+ }
37
+ dispose() {
38
+ if (this.sweep)
39
+ clearInterval(this.sweep);
40
+ }
41
+ }
42
+ /** Redis-backed store. TTL enforced by Redis (PX); no sweep needed. */
43
+ export class RedisKvStore {
44
+ client;
45
+ prefix;
46
+ constructor(client, prefix) {
47
+ this.client = client;
48
+ this.prefix = prefix;
49
+ }
50
+ async get(key) {
51
+ const raw = await this.client.get(this.prefix + key);
52
+ return raw == null ? undefined : JSON.parse(raw);
53
+ }
54
+ async set(key, value, ttlMs) {
55
+ await this.client.set(this.prefix + key, JSON.stringify(value), "PX", Math.max(1, Math.floor(ttlMs)));
56
+ }
57
+ async del(key) {
58
+ await this.client.del(this.prefix + key);
59
+ }
60
+ dispose() {
61
+ void this.client.quit();
62
+ }
63
+ }
64
+ /**
65
+ * Build the store. Redis when `redisUrl` is set (ioredis loaded lazily so
66
+ * non-Redis deployments don't pay for it); otherwise in-memory. `keyPrefix`
67
+ * should include the issuer host so co-tenant MCPs sharing one Redis don't
68
+ * collide while replicas of the same issuer DO share state.
69
+ */
70
+ export async function createStore(redisUrl, keyPrefix) {
71
+ const prefix = keyPrefix.endsWith(":") ? keyPrefix : `${keyPrefix}:`;
72
+ if (redisUrl) {
73
+ const mod = await import("ioredis");
74
+ const Redis = mod.default || mod;
75
+ const client = new Redis(redisUrl, { maxRetriesPerRequest: 2, lazyConnect: false });
76
+ return new RedisKvStore(client, prefix);
77
+ }
78
+ return new InMemoryKvStore(prefix);
79
+ }
@@ -0,0 +1,51 @@
1
+ // MCP prompts for BookStack — one-click actions surfaced in Claude's connector menu
2
+ // (and any prompts-capable MCP client). Content-oriented and read-only: each prompt just
3
+ // returns a templated instruction that drives the existing read tools. No per-user
4
+ // identity is assumed (the connector uses a shared service token).
5
+ import { z } from "zod";
6
+ // Small helper: a prompt handler returns a single user message.
7
+ function userMessage(text) {
8
+ return { messages: [{ role: "user", content: { type: "text", text } }] };
9
+ }
10
+ export function registerPrompts(server) {
11
+ server.registerPrompt("answer_from_wiki", {
12
+ title: "Answer from the wiki",
13
+ description: "Answer a question using the BookStack wiki, with citations and links.",
14
+ argsSchema: {
15
+ question: z.string().describe("The question to answer from the wiki")
16
+ }
17
+ }, async ({ question }) => userMessage(`Answer this question using the BookStack wiki: "${question}".\n\n` +
18
+ `Use search_content to find the most relevant pages, read the top matches with ` +
19
+ `get_page, then answer concisely. Cite each source by page name with its URL. ` +
20
+ `If the wiki has nothing relevant, say so rather than guessing.`));
21
+ server.registerPrompt("find_pages", {
22
+ title: "Find pages about a topic",
23
+ description: "List BookStack pages matching a topic, with previews and links.",
24
+ argsSchema: {
25
+ topic: z.string().describe("Topic or keywords to search for")
26
+ }
27
+ }, async ({ topic }) => userMessage(`Find BookStack pages about "${topic}" using search_content (and search_pages if ` +
28
+ `helpful). Return a ranked list — for each result give the page name, a one-line ` +
29
+ `preview, and its URL. Do not read full page contents unless I ask.`));
30
+ server.registerPrompt("summarize_book", {
31
+ title: "Summarize a book",
32
+ description: "Produce a structured summary of a BookStack book with section links.",
33
+ argsSchema: {
34
+ book: z.string().describe("Book name or numeric id")
35
+ }
36
+ }, async ({ book }) => userMessage(`Summarize the BookStack book "${book}".\n\n` +
37
+ `If that is a name rather than a numeric id, first find it with search_content ` +
38
+ `using {type:book}. Then use get_book and get_pages to read its chapters and pages, ` +
39
+ `and produce a structured summary (overview, then key points per chapter/section). ` +
40
+ `Include a link to the book and to the sections you reference.`));
41
+ server.registerPrompt("recent_changes", {
42
+ title: "What changed recently",
43
+ description: "Summarize recently created or updated wiki content.",
44
+ argsSchema: {
45
+ days: z.string().optional().describe("How many days back to look (default 30)")
46
+ }
47
+ }, async ({ days }) => userMessage(`Summarize what changed in the BookStack wiki in the last ${days || "30"} days using ` +
48
+ `get_recent_changes. Group the changes by book (and note the type — page, chapter, ` +
49
+ `book), and include a link to each changed item. Highlight anything that looks ` +
50
+ `significant.`));
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "4.0.0",
3
+ "version": "5.1.0",
4
4
  "description": "MCP server for BookStack wiki — search, read, create, and manage documentation via AI assistants",
5
5
  "type": "module",
6
6
  "bin": {
@@ -42,6 +42,8 @@
42
42
  "dependencies": {
43
43
  "@modelcontextprotocol/sdk": "^1.25.3",
44
44
  "axios": "^1.6.0",
45
+ "ioredis": "^5.11.1",
46
+ "jose": "^6.2.3",
45
47
  "zod": "^3.25.76"
46
48
  },
47
49
  "devDependencies": {