bookstack-mcp 5.7.0 → 5.7.1

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
@@ -125,7 +125,10 @@ remain disabled unless `BOOKSTACK_ENABLE_WRITE=true` is set.
125
125
 
126
126
  The manifest supplies the project website, privacy policy, and terms of use for
127
127
  plugin directories, including HOL. The HOL Guard CI workflow scans this manifest
128
- alongside the Claude and Gemini manifests; it does not submit or publish listings.
128
+ alongside the Claude and Gemini manifests. After a passing scan on `main`, a
129
+ separate job sends an authenticated score summary to HOL so the registry can
130
+ show the result checked in CI. PR scans remain read-only. See
131
+ [HOL registry setup](docs/HOL.md) for ownership verification and reporting details.
129
132
 
130
133
  ### Claude Desktop
131
134
 
@@ -249,6 +252,16 @@ the BookStack authorization token. Deleting an image can break existing page ref
249
252
  | `MCP_HTTP_HOST` | `127.0.0.1` | Bind address. Loopback by default for safety |
250
253
  | `MCP_HTTP_ALLOWED_HOSTS` | *(loopback only)* | Comma-separated allowlist of `Host` header hostnames for DNS rebinding protection. Required when binding to a non-loopback address |
251
254
  | `MCP_HTTP_PATH` | `/mcp` | Streamable HTTP endpoint |
255
+ | `MCP_HTTP_MAX_BODY_BYTES` | `10485760` (10 MiB) | Maximum MCP JSON request size in bytes; positive integer |
256
+
257
+ OAuth registration and token request bodies are limited to 64 KiB. Body reads
258
+ must complete within 30 seconds. Oversized bodies return HTTP 413, slow bodies
259
+ return 408, and malformed MCP JSON returns 400 without echoing its contents.
260
+
261
+ OAuth sessions are bound to both the user's identity and current write role.
262
+ If that role changes, the server closes the old session and returns 404 so the
263
+ client reinitializes with the appropriate credential and tool set. OAuth pending
264
+ states and authorization codes are consumed atomically, including with Redis.
252
265
 
253
266
  When binding to `0.0.0.0` (e.g. inside a container reachable from other services), set `MCP_HTTP_ALLOWED_HOSTS` to the hostnames LibreChat will use to reach this server, e.g. `MCP_HTTP_ALLOWED_HOSTS=bookstack-mcp,bookstack-mcp.internal`.
254
267
 
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sen
14
14
  import { SessionRegistry } from "./session-registry.js";
15
15
  import { parseRequestCredentials, requestScopedClient, withRequestCredentials } from "./request-credentials.js";
16
16
  import { PublicError, logSafeError, safeError, safeUrlOrigin } from "./util/safe-errors.js";
17
+ import { HttpBodyError, readRequestBody } from "./util/http-body.js";
17
18
  const PKG_VERSION = (() => {
18
19
  try {
19
20
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
@@ -903,22 +904,22 @@ async function startHttp(config) {
903
904
  const maxSessionsParsed = maxSessionsRaw ? parseInt(maxSessionsRaw, 10) : NaN;
904
905
  const maxSessions = Number.isFinite(maxSessionsParsed) && maxSessionsParsed > 0 ? maxSessionsParsed : undefined;
905
906
  const sessions = new SessionRegistry({ idleTtlMs, maxSessions });
906
- const readJsonBody = (req) => new Promise((resolve, reject) => {
907
- const chunks = [];
908
- req.on("data", (c) => chunks.push(c));
909
- req.on("end", () => {
910
- const raw = Buffer.concat(chunks).toString("utf8");
911
- if (!raw)
912
- return resolve(undefined);
913
- try {
914
- resolve(JSON.parse(raw));
915
- }
916
- catch (e) {
917
- reject(e);
918
- }
919
- });
920
- req.on("error", reject);
921
- });
907
+ const maxBodyRaw = process.env.MCP_HTTP_MAX_BODY_BYTES;
908
+ const maxBodyBytes = maxBodyRaw === undefined ? 10 * 1024 * 1024 : Number(maxBodyRaw);
909
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) {
910
+ throw new PublicError('MCP_HTTP_MAX_BODY_BYTES must be a positive integer');
911
+ }
912
+ const readJsonBody = async (req) => {
913
+ const raw = await readRequestBody(req, { maxBytes: maxBodyBytes });
914
+ if (!raw)
915
+ return undefined;
916
+ try {
917
+ return JSON.parse(raw);
918
+ }
919
+ catch {
920
+ throw new HttpBodyError(400, 'Invalid JSON');
921
+ }
922
+ };
922
923
  const sendJson = (res, status, body) => {
923
924
  res.writeHead(status, { "Content-Type": "application/json" });
924
925
  res.end(JSON.stringify(body));
@@ -945,7 +946,7 @@ async function startHttp(config) {
945
946
  let auth = null;
946
947
  if (config.oauth) {
947
948
  const result = await validateBearer(req, config.oauth);
948
- if (!result.ok) {
949
+ if (!result.ok || !result.sub) {
949
950
  sendUnauthorized(res, config.oauth);
950
951
  return;
951
952
  }
@@ -966,12 +967,14 @@ async function startHttp(config) {
966
967
  parsedBody = await readJsonBody(req);
967
968
  }
968
969
  if (sessionId && sessions.has(sessionId)) {
969
- // Reject a valid token belonging to a different subject than the session was bound to.
970
- const boundAuth = sessions.getAuth(sessionId);
971
- if (config.oauth && boundAuth && auth?.sub !== boundAuth.sub) {
972
- sendJson(res, 403, {
970
+ const authorization = config.oauth ? sessions.validateAuth(sessionId, auth) : 'ok';
971
+ if (authorization !== 'ok') {
972
+ const changed = authorization === 'permissions_changed';
973
+ sendJson(res, changed ? 404 : 403, {
973
974
  jsonrpc: "2.0",
974
- error: { code: -32003, message: "Forbidden: token does not match session" },
975
+ error: { code: changed ? -32001 : -32003, message: changed
976
+ ? "Session permissions changed; reinitialize the session"
977
+ : "Forbidden: token does not match session" },
975
978
  id: null
976
979
  });
977
980
  return;
@@ -1048,6 +1051,16 @@ async function startHttp(config) {
1048
1051
  sendJson(res, 404, { error: "Not Found" });
1049
1052
  }
1050
1053
  catch (err) {
1054
+ if (err instanceof HttpBodyError) {
1055
+ if (req.aborted || res.headersSent)
1056
+ return;
1057
+ res.setHeader('Connection', 'close');
1058
+ sendJson(res, err.status, {
1059
+ jsonrpc: '2.0', id: null,
1060
+ error: { code: err.status === 400 ? -32700 : -32600, message: err.message }
1061
+ });
1062
+ return;
1063
+ }
1051
1064
  logSafeError("HTTP handler error", err);
1052
1065
  if (!res.headersSent) {
1053
1066
  sendJson(res, 500, {
@@ -13,6 +13,7 @@ import { randomUUID, createHash, randomBytes } from "node:crypto";
13
13
  import { createRemoteJWKSet, jwtVerify } from "jose";
14
14
  import { InMemoryKvStore, createStore } from "./kv-store.js";
15
15
  import { logSafeError, oauthErrorCode } from "../util/safe-errors.js";
16
+ import { HttpBodyError, readRequestBody } from "../util/http-body.js";
16
17
  // Load config from env. Returns null when OAuth proxy mode is disabled.
17
18
  export function loadOAuthConfig(env) {
18
19
  if (env.MCP_OAUTH_ENABLE?.toLowerCase() !== "true")
@@ -86,13 +87,19 @@ function sendJson(res, status, body) {
86
87
  });
87
88
  res.end(JSON.stringify(body));
88
89
  }
89
- function readBody(req) {
90
- return new Promise((resolve, reject) => {
91
- const chunks = [];
92
- req.on("data", (c) => chunks.push(c));
93
- req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
94
- req.on("error", reject);
95
- });
90
+ async function readBody(req, res) {
91
+ try {
92
+ return await readRequestBody(req, { maxBytes: 64 * 1024 });
93
+ }
94
+ catch (error) {
95
+ if (!(error instanceof HttpBodyError))
96
+ throw error;
97
+ if (!req.aborted) {
98
+ res.setHeader('Connection', 'close');
99
+ sendJson(res, error.status, { error: 'invalid_request', error_description: error.message });
100
+ }
101
+ return undefined;
102
+ }
96
103
  }
97
104
  function parseForm(raw) {
98
105
  const out = {};
@@ -195,9 +202,12 @@ export async function handleOAuthRoutes(req, res, cfg) {
195
202
  }
196
203
  // RFC 7591 — Dynamic Client Registration (handled locally)
197
204
  if (path === "/register" && req.method === "POST") {
205
+ const raw = await readBody(req, res);
206
+ if (raw === undefined)
207
+ return true;
198
208
  let meta = {};
199
209
  try {
200
- meta = JSON.parse((await readBody(req)) || "{}");
210
+ meta = JSON.parse(raw || "{}");
201
211
  }
202
212
  catch {
203
213
  sendJson(res, 400, { error: "invalid_client_metadata" });
@@ -269,12 +279,11 @@ export async function handleOAuthRoutes(req, res, cfg) {
269
279
  const upstreamState = q.get("state") ?? "";
270
280
  const code = q.get("code") ?? "";
271
281
  const err = q.get("error");
272
- const p = await store.get(`pending:${upstreamState}`);
282
+ const p = await store.take(`pending:${upstreamState}`);
273
283
  if (!p) {
274
284
  sendJson(res, 400, { error: "invalid_state" });
275
285
  return true;
276
286
  }
277
- await store.del(`pending:${upstreamState}`);
278
287
  if (err || !code) {
279
288
  const dest = new URL(p.clientRedirectUri);
280
289
  dest.searchParams.set("error", oauthErrorCode(err, 'invalid_request'));
@@ -333,16 +342,18 @@ export async function handleOAuthRoutes(req, res, cfg) {
333
342
  }
334
343
  // Token endpoint — code exchange (verify PKCE) and refresh pass-through.
335
344
  if (path === "/token" && req.method === "POST") {
336
- const form = parseForm(await readBody(req));
345
+ const raw = await readBody(req, res);
346
+ if (raw === undefined)
347
+ return true;
348
+ const form = parseForm(raw);
337
349
  const grant = form["grant_type"];
338
350
  if (grant === "authorization_code") {
339
- const issued = await store.get(`code:${form["code"] ?? ""}`);
351
+ const issued = await store.take(`code:${form["code"] ?? ""}`);
340
352
  if (!issued) {
341
353
  console.error("[oauth] /token authorization_code: invalid_grant (code not found/expired)");
342
354
  sendJson(res, 400, { error: "invalid_grant" });
343
355
  return true;
344
356
  }
345
- await store.del(`code:${form["code"]}`);
346
357
  const verifier = form["code_verifier"] ?? "";
347
358
  if (!verifier || s256(verifier) !== issued.codeChallenge) {
348
359
  console.error(`[oauth] /token authorization_code: PKCE FAILED (verifier=${verifier ? "present" : "missing"})`);
@@ -31,6 +31,12 @@ export class InMemoryKvStore {
31
31
  async set(key, value, ttlMs) {
32
32
  this.map.set(this.prefix + key, { value, expiresAt: Date.now() + ttlMs });
33
33
  }
34
+ async take(key) {
35
+ const entry = this.map.get(this.prefix + key);
36
+ // No await between lookup and deletion: concurrent consumers get one winner.
37
+ this.map.delete(this.prefix + key);
38
+ return entry && entry.expiresAt > Date.now() ? entry.value : undefined;
39
+ }
34
40
  async del(key) {
35
41
  this.map.delete(this.prefix + key);
36
42
  }
@@ -51,6 +57,11 @@ export class RedisKvStore {
51
57
  const raw = await this.client.get(this.prefix + key);
52
58
  return raw == null ? undefined : JSON.parse(raw);
53
59
  }
60
+ async take(key) {
61
+ // Atomic GET+DEL also works on Redis versions predating GETDEL (6.2).
62
+ const raw = await this.client.eval("local value = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return value", 1, this.prefix + key);
63
+ return raw == null ? undefined : JSON.parse(String(raw));
64
+ }
54
65
  async set(key, value, ttlMs) {
55
66
  await this.client.set(this.prefix + key, JSON.stringify(value), "PX", Math.max(1, Math.floor(ttlMs)));
56
67
  }
@@ -68,6 +68,17 @@ export class SessionRegistry {
68
68
  return undefined;
69
69
  return this.sessionAuth[sessionId];
70
70
  }
71
+ /** A session's tool set and upstream token must match every request's roles. */
72
+ validateAuth(sessionId, current) {
73
+ const bound = this.getAuth(sessionId);
74
+ if (!bound?.sub || !current?.sub || bound.sub !== current.sub)
75
+ return 'forbidden';
76
+ if (bound.isWriter !== current.isWriter) {
77
+ this.evict(sessionId);
78
+ return 'permissions_changed';
79
+ }
80
+ return 'ok';
81
+ }
71
82
  atCapacity() {
72
83
  return this.size() >= this.maxSessions;
73
84
  }
@@ -0,0 +1,55 @@
1
+ import { PublicError } from './safe-errors.js';
2
+ export class HttpBodyError extends PublicError {
3
+ status;
4
+ constructor(status, message) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ }
9
+ /** Bound buffering before JSON/form parsing, including chunked requests. */
10
+ export function readRequestBody(req, { maxBytes, timeoutMs = 30000 }) {
11
+ return new Promise((resolve, reject) => {
12
+ const chunks = [];
13
+ let size = 0;
14
+ const cleanup = () => {
15
+ clearTimeout(timer);
16
+ req.off('data', onData);
17
+ req.off('end', onEnd);
18
+ req.off('error', onError);
19
+ req.off('aborted', onAborted);
20
+ };
21
+ const fail = (error) => {
22
+ cleanup();
23
+ chunks.length = 0;
24
+ // A client can reset its socket after our early rejection.
25
+ req.once('error', () => { });
26
+ // Discard further bytes without buffering; the caller can still send 413.
27
+ req.resume();
28
+ reject(error);
29
+ };
30
+ const onData = (chunk) => {
31
+ size += chunk.length;
32
+ if (size > maxBytes)
33
+ return fail(new HttpBodyError(413, 'Request body too large'));
34
+ chunks.push(chunk);
35
+ };
36
+ const onEnd = () => {
37
+ cleanup();
38
+ resolve(Buffer.concat(chunks, size).toString('utf8'));
39
+ };
40
+ const onError = (error) => fail(error);
41
+ const onAborted = () => fail(new HttpBodyError(400, 'Request body interrupted'));
42
+ const timer = setTimeout(() => fail(new HttpBodyError(408, 'Request body timed out')), timeoutMs);
43
+ timer.unref?.();
44
+ if (req.aborted)
45
+ return onAborted();
46
+ const declared = req.headers['content-length'];
47
+ if (typeof declared === 'string' && Number(declared) > maxBytes) {
48
+ return fail(new HttpBodyError(413, 'Request body too large'));
49
+ }
50
+ req.on('data', onData);
51
+ req.on('end', onEnd);
52
+ req.on('error', onError);
53
+ req.on('aborted', onAborted);
54
+ });
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bookstack-mcp",
3
- "version": "5.7.0",
3
+ "version": "5.7.1",
4
4
  "description": "MCP server for BookStack wiki — search, read, create, and manage documentation via AI assistants",
5
5
  "type": "module",
6
6
  "bin": {