bookstack-mcp 5.4.1 → 5.6.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/PRIVACY.md +159 -0
- package/README.md +80 -1
- package/dist/bookstack-client.js +88 -59
- package/dist/image-source.js +85 -0
- package/dist/index.js +79 -24
- package/dist/oauth/entra-proxy.js +17 -13
- package/dist/request-credentials.js +39 -0
- package/dist/util/rate-limit.js +81 -0
- package/dist/util/safe-errors.js +55 -0
- package/dist/util/semaphore.js +21 -4
- package/package.json +6 -5
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import { basename, extname, isAbsolute } from 'node:path';
|
|
4
|
+
import { PublicError, safeError } from './util/safe-errors.js';
|
|
5
|
+
export const MAX_IMAGE_BYTES = 50 * 1024 * 1024;
|
|
6
|
+
const TYPES = {
|
|
7
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
8
|
+
'.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml'
|
|
9
|
+
};
|
|
10
|
+
export async function readImageSource(options) {
|
|
11
|
+
try {
|
|
12
|
+
return await loadImageSource(options);
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
throw safeError(error, 'Image source read failed');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function loadImageSource(options) {
|
|
19
|
+
if (!!options.file_path === !!options.url)
|
|
20
|
+
throw new PublicError('Provide exactly one of file_path or url.');
|
|
21
|
+
let bytes;
|
|
22
|
+
let filename;
|
|
23
|
+
let type;
|
|
24
|
+
if (options.file_path) {
|
|
25
|
+
if (options.allowLocalFiles === false)
|
|
26
|
+
throw new PublicError('Local image files are disabled for this server.');
|
|
27
|
+
if (!isAbsolute(options.file_path))
|
|
28
|
+
throw new PublicError('file_path must be absolute.');
|
|
29
|
+
filename = basename(options.file_path);
|
|
30
|
+
type = TYPES[extname(filename).toLowerCase()];
|
|
31
|
+
if (!type)
|
|
32
|
+
throw new PublicError('Supported image formats: PNG, JPEG, GIF, WebP and SVG.');
|
|
33
|
+
const file = await open(options.file_path, 'r');
|
|
34
|
+
try {
|
|
35
|
+
const stat = await file.stat();
|
|
36
|
+
if (!stat.isFile() || stat.size > MAX_IMAGE_BYTES)
|
|
37
|
+
throw new PublicError('Image must be a regular file no larger than 50 MB.');
|
|
38
|
+
bytes = Buffer.alloc(stat.size);
|
|
39
|
+
let offset = 0;
|
|
40
|
+
while (offset < bytes.length) {
|
|
41
|
+
const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
|
|
42
|
+
if (!bytesRead)
|
|
43
|
+
break;
|
|
44
|
+
offset += bytesRead;
|
|
45
|
+
}
|
|
46
|
+
bytes = bytes.subarray(0, offset);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await file.close();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
let url = new URL(options.url);
|
|
54
|
+
for (let redirect = 0;; redirect++) {
|
|
55
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
|
|
56
|
+
throw new PublicError('Image URL must use HTTP(S) without embedded credentials.');
|
|
57
|
+
}
|
|
58
|
+
if (options.allowedHosts && !options.allowedHosts.includes(url.hostname.toLowerCase())) {
|
|
59
|
+
throw new PublicError('Image URL host is not in BOOKSTACK_IMAGE_ALLOWED_HOSTS.');
|
|
60
|
+
}
|
|
61
|
+
const response = await axios.get(url.href, {
|
|
62
|
+
responseType: 'arraybuffer', maxContentLength: MAX_IMAGE_BYTES,
|
|
63
|
+
maxRedirects: 0, timeout: 30000,
|
|
64
|
+
validateStatus: status => (status >= 200 && status < 300) || [301, 302, 303, 307, 308].includes(status)
|
|
65
|
+
});
|
|
66
|
+
if (response.status >= 300) {
|
|
67
|
+
if (redirect >= 3 || !response.headers.location)
|
|
68
|
+
throw new PublicError('Too many image URL redirects or missing Location.');
|
|
69
|
+
url = new URL(response.headers.location, url);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
filename = basename(url.pathname) || 'image';
|
|
73
|
+
type = String(response.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
|
|
74
|
+
if (!Object.values(TYPES).includes(type))
|
|
75
|
+
type = TYPES[extname(filename).toLowerCase()];
|
|
76
|
+
if (!type)
|
|
77
|
+
throw new PublicError('Supported image formats: PNG, JPEG, GIF, WebP and SVG.');
|
|
78
|
+
bytes = Buffer.from(response.data);
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!bytes.length || bytes.length > MAX_IMAGE_BYTES)
|
|
83
|
+
throw new PublicError('Image must contain between 1 byte and 50 MB.');
|
|
84
|
+
return { bytes, filename, type };
|
|
85
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -9,10 +9,11 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
9
9
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
10
10
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
11
11
|
import { z } from "zod";
|
|
12
|
-
import { BookStackClient } from "./bookstack-client.js";
|
|
13
12
|
import { registerPrompts } from "./prompts.js";
|
|
14
13
|
import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
|
|
15
14
|
import { SessionRegistry } from "./session-registry.js";
|
|
15
|
+
import { parseRequestCredentials, requestScopedClient, withRequestCredentials } from "./request-credentials.js";
|
|
16
|
+
import { PublicError, logSafeError, safeError, safeUrlOrigin } from "./util/safe-errors.js";
|
|
16
17
|
const PKG_VERSION = (() => {
|
|
17
18
|
try {
|
|
18
19
|
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
@@ -41,7 +42,7 @@ function getRequiredEnvVar(name) {
|
|
|
41
42
|
return value;
|
|
42
43
|
}
|
|
43
44
|
function buildServer(config) {
|
|
44
|
-
const client =
|
|
45
|
+
const client = requestScopedClient(config);
|
|
45
46
|
const server = new McpServer({
|
|
46
47
|
name: "bookstack-mcp",
|
|
47
48
|
version: PKG_VERSION
|
|
@@ -79,7 +80,7 @@ function registerResources(server, client) {
|
|
|
79
80
|
}, async (uri, variables) => {
|
|
80
81
|
const id = Number(variables.id);
|
|
81
82
|
if (!Number.isFinite(id) || id < 1) {
|
|
82
|
-
throw new
|
|
83
|
+
throw new PublicError(`Invalid book id: ${variables.id}`);
|
|
83
84
|
}
|
|
84
85
|
const book = await client.getBook(id);
|
|
85
86
|
return {
|
|
@@ -117,7 +118,7 @@ function registerResources(server, client) {
|
|
|
117
118
|
}, async (uri, variables) => {
|
|
118
119
|
const id = Number(variables.id);
|
|
119
120
|
if (!Number.isFinite(id) || id < 1) {
|
|
120
|
-
throw new
|
|
121
|
+
throw new PublicError(`Invalid page id: ${variables.id}`);
|
|
121
122
|
}
|
|
122
123
|
const page = await client.getPage(id, { format: "markdown" });
|
|
123
124
|
return {
|
|
@@ -144,11 +145,19 @@ function registerResources(server, client) {
|
|
|
144
145
|
});
|
|
145
146
|
}
|
|
146
147
|
function registerTools(server, client, config) {
|
|
148
|
+
const safeHandler = (handler) => async (...args) => {
|
|
149
|
+
try {
|
|
150
|
+
return await handler(...args);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
throw safeError(error);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
147
156
|
// Helpers wrap registerTool and inject MCP tool annotations so clients can
|
|
148
157
|
// distinguish read-only from destructive operations. Typed loosely to defer
|
|
149
158
|
// to the SDK's generic overloads at the call sites.
|
|
150
|
-
const readTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...READ_ONLY_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
|
|
151
|
-
const writeTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...WRITE_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
|
|
159
|
+
const readTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...READ_ONLY_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, safeHandler(handler)));
|
|
160
|
+
const writeTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...WRITE_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, safeHandler(handler)));
|
|
152
161
|
// Register read-only tools.
|
|
153
162
|
// Common params (offset/count/sort/filter/id) are self-describing and intentionally
|
|
154
163
|
// bare so tool definitions stay compact in the MCP tools/list payload.
|
|
@@ -190,7 +199,7 @@ function registerTools(server, client, config) {
|
|
|
190
199
|
offset: z.coerce.number().default(0),
|
|
191
200
|
count: z.coerce.number().max(500).default(50),
|
|
192
201
|
sort: z.string().optional(),
|
|
193
|
-
filter: z.record(z.any()).optional()
|
|
202
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
194
203
|
}
|
|
195
204
|
}, async (args) => {
|
|
196
205
|
const books = await client.getBooks({
|
|
@@ -222,7 +231,7 @@ function registerTools(server, client, config) {
|
|
|
222
231
|
offset: z.coerce.number().default(0),
|
|
223
232
|
count: z.coerce.number().max(500).default(50),
|
|
224
233
|
sort: z.string().optional(),
|
|
225
|
-
filter: z.record(z.any()).optional()
|
|
234
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
226
235
|
}
|
|
227
236
|
}, async (args) => {
|
|
228
237
|
const pages = await client.getPages({
|
|
@@ -241,7 +250,7 @@ function registerTools(server, client, config) {
|
|
|
241
250
|
description: "Get a page. Returns one format (default markdown); use offset/limit + content_next_offset to paginate large pages.",
|
|
242
251
|
inputSchema: {
|
|
243
252
|
id: z.coerce.number().min(1),
|
|
244
|
-
format: z.enum(["markdown", "html", "text"]).optional().describe("Which content format to return. Defaults to markdown."),
|
|
253
|
+
format: z.enum(["markdown", "html", "text", "raw"]).optional().describe("Which content format to return. Defaults to markdown. 'html' is the rendered page as readers see it (includes resolved, content filtering applied); 'raw' is the stored editor HTML. To edit a page, check its 'editor' field: for HTML (WYSIWYG) pages read 'raw' and send it back as update_page.html; for Markdown pages read 'markdown' and send it back as update_page.markdown, because saving html clears the stored Markdown source."),
|
|
245
254
|
offset: z.coerce.number().min(0).optional().describe("Character offset into the content to start from (default 0)"),
|
|
246
255
|
limit: z.coerce.number().min(1).max(200000).optional().describe("Max characters of content to return (default 50000)")
|
|
247
256
|
}
|
|
@@ -350,7 +359,7 @@ function registerTools(server, client, config) {
|
|
|
350
359
|
offset: z.coerce.number().default(0),
|
|
351
360
|
count: z.coerce.number().max(500).default(50),
|
|
352
361
|
sort: z.string().optional(),
|
|
353
|
-
filter: z.record(z.any()).optional()
|
|
362
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
354
363
|
}
|
|
355
364
|
}, async (args) => {
|
|
356
365
|
const shelves = await client.getShelves({
|
|
@@ -380,7 +389,7 @@ function registerTools(server, client, config) {
|
|
|
380
389
|
offset: z.coerce.number().default(0),
|
|
381
390
|
count: z.coerce.number().max(500).default(50),
|
|
382
391
|
sort: z.string().optional(),
|
|
383
|
-
filter: z.record(z.any()).optional()
|
|
392
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
384
393
|
}
|
|
385
394
|
}, async (args) => {
|
|
386
395
|
const attachments = await client.getAttachments({
|
|
@@ -479,8 +488,30 @@ function registerTools(server, client, config) {
|
|
|
479
488
|
content: [{ type: "text", text: JSON.stringify(items) }]
|
|
480
489
|
};
|
|
481
490
|
});
|
|
491
|
+
readTool("list_images", {
|
|
492
|
+
description: "List gallery images, optionally filtered by their page ID.",
|
|
493
|
+
inputSchema: {
|
|
494
|
+
uploaded_to: z.coerce.number().int().min(1).optional(),
|
|
495
|
+
offset: z.coerce.number().int().min(0).optional(),
|
|
496
|
+
count: z.coerce.number().int().min(1).max(500).optional(),
|
|
497
|
+
sort: z.string().optional()
|
|
498
|
+
}
|
|
499
|
+
}, async (args) => ({ content: [{ type: "text", text: JSON.stringify(await client.listImages(args)) }] }));
|
|
482
500
|
// Register write tools if enabled
|
|
483
501
|
if (config.enableWrite) {
|
|
502
|
+
writeTool("create_image", {
|
|
503
|
+
description: "Upload a gallery image from exactly one absolute file_path or HTTP(S) url. Server source policy applies. Returns hosted URL, thumbnails and HTML/Markdown content.",
|
|
504
|
+
inputSchema: {
|
|
505
|
+
file_path: z.string().min(1).optional(),
|
|
506
|
+
url: z.string().url().optional(),
|
|
507
|
+
name: z.string().min(1).max(180).optional(),
|
|
508
|
+
uploaded_to: z.coerce.number().int().min(1).describe("Existing page ID")
|
|
509
|
+
}
|
|
510
|
+
}, async (args) => ({ content: [{ type: "text", text: JSON.stringify(await client.createImage(args)) }] }));
|
|
511
|
+
writeTool("delete_image", {
|
|
512
|
+
description: "Delete a gallery image and its thumbnails. Existing page references may break.",
|
|
513
|
+
inputSchema: { id: z.coerce.number().int().min(1) }
|
|
514
|
+
}, async (args) => ({ content: [{ type: "text", text: JSON.stringify(await client.deleteImage(args.id)) }] }));
|
|
484
515
|
writeTool("create_book", {
|
|
485
516
|
description: "Create a new book in BookStack",
|
|
486
517
|
inputSchema: {
|
|
@@ -576,7 +607,8 @@ function registerTools(server, client, config) {
|
|
|
576
607
|
book_id: z.coerce.number().min(1).describe("Book ID where the page will be created"),
|
|
577
608
|
chapter_id: z.coerce.number().optional().describe("Optional: Chapter ID if page should be in a chapter"),
|
|
578
609
|
html: z.string().optional().describe("Optional: HTML content"),
|
|
579
|
-
markdown: z.string().optional().describe("Optional: Markdown content")
|
|
610
|
+
markdown: z.string().optional().describe("Optional: Markdown content"),
|
|
611
|
+
changelog: z.string().min(1).max(180).optional().describe("Optional: Revision changelog message shown in the page history (BookStack v26.09+; older servers ignore it)")
|
|
580
612
|
}
|
|
581
613
|
}, async (args) => {
|
|
582
614
|
const page = await client.createPage({
|
|
@@ -584,21 +616,24 @@ function registerTools(server, client, config) {
|
|
|
584
616
|
book_id: args.book_id,
|
|
585
617
|
chapter_id: args.chapter_id,
|
|
586
618
|
html: args.html,
|
|
587
|
-
markdown: args.markdown
|
|
619
|
+
markdown: args.markdown,
|
|
620
|
+
changelog: args.changelog
|
|
588
621
|
});
|
|
589
622
|
return {
|
|
590
623
|
content: [{ type: "text", text: JSON.stringify(page) }]
|
|
591
624
|
};
|
|
592
625
|
});
|
|
593
626
|
writeTool("update_page", {
|
|
594
|
-
description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location.",
|
|
627
|
+
description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location, or priority to reorder it.",
|
|
595
628
|
inputSchema: {
|
|
596
629
|
id: z.coerce.number().min(1),
|
|
597
630
|
name: z.string().optional().describe("Optional: New page name"),
|
|
598
631
|
html: z.string().optional().describe("Optional: New HTML content"),
|
|
599
632
|
markdown: z.string().optional().describe("Optional: New Markdown content"),
|
|
600
633
|
book_id: z.coerce.number().min(1).optional().describe("Optional: Move page to this book"),
|
|
601
|
-
chapter_id: z.coerce.number().optional().describe("Optional: Move page into this chapter (must belong to the target book; pass 0 to move out of any chapter)")
|
|
634
|
+
chapter_id: z.coerce.number().optional().describe("Optional: Move page into this chapter (must belong to the target book; pass 0 to move out of any chapter)"),
|
|
635
|
+
priority: z.coerce.number().int().min(0).optional().describe("Optional: Sort order (non-negative integer, lower sorts first)"),
|
|
636
|
+
changelog: z.string().min(1).max(180).optional().describe("Optional: Revision changelog message shown in the page history (BookStack v26.09+; older servers ignore it)")
|
|
602
637
|
}
|
|
603
638
|
}, async (args) => {
|
|
604
639
|
const page = await client.updatePage(args.id, {
|
|
@@ -606,7 +641,9 @@ function registerTools(server, client, config) {
|
|
|
606
641
|
html: args.html,
|
|
607
642
|
markdown: args.markdown,
|
|
608
643
|
book_id: args.book_id,
|
|
609
|
-
chapter_id: args.chapter_id
|
|
644
|
+
chapter_id: args.chapter_id,
|
|
645
|
+
priority: args.priority,
|
|
646
|
+
changelog: args.changelog
|
|
610
647
|
});
|
|
611
648
|
return {
|
|
612
649
|
content: [{ type: "text", text: JSON.stringify(page) }]
|
|
@@ -824,6 +861,7 @@ async function startStdio(config) {
|
|
|
824
861
|
console.error("BookStack MCP server running on stdio");
|
|
825
862
|
}
|
|
826
863
|
async function startHttp(config) {
|
|
864
|
+
const requestCredentialsEnabled = process.env.BOOKSTACK_ALLOW_REQUEST_CREDENTIALS?.toLowerCase() === "true";
|
|
827
865
|
const port = parseInt(process.env.MCP_HTTP_PORT ?? "8080", 10);
|
|
828
866
|
const host = process.env.MCP_HTTP_HOST ?? "127.0.0.1";
|
|
829
867
|
const mcpPath = process.env.MCP_HTTP_PATH ?? "/mcp";
|
|
@@ -903,6 +941,14 @@ async function startHttp(config) {
|
|
|
903
941
|
}
|
|
904
942
|
auth = { sub: result.sub, isWriter: !!result.isWriter };
|
|
905
943
|
}
|
|
944
|
+
let requestCredentials;
|
|
945
|
+
try {
|
|
946
|
+
requestCredentials = parseRequestCredentials(req.headers, requestCredentialsEnabled);
|
|
947
|
+
}
|
|
948
|
+
catch (error) {
|
|
949
|
+
sendJson(res, 400, { jsonrpc: "2.0", error: { code: -32602, message: error.message }, id: null });
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
906
952
|
const sessionId = req.headers["mcp-session-id"];
|
|
907
953
|
let transport;
|
|
908
954
|
let parsedBody;
|
|
@@ -975,7 +1021,7 @@ async function startHttp(config) {
|
|
|
975
1021
|
});
|
|
976
1022
|
return;
|
|
977
1023
|
}
|
|
978
|
-
await transport.handleRequest(req, res, parsedBody);
|
|
1024
|
+
await withRequestCredentials(requestCredentials, () => transport.handleRequest(req, res, parsedBody));
|
|
979
1025
|
return;
|
|
980
1026
|
}
|
|
981
1027
|
// Health check
|
|
@@ -992,7 +1038,7 @@ async function startHttp(config) {
|
|
|
992
1038
|
sendJson(res, 404, { error: "Not Found" });
|
|
993
1039
|
}
|
|
994
1040
|
catch (err) {
|
|
995
|
-
|
|
1041
|
+
logSafeError("HTTP handler error", err);
|
|
996
1042
|
if (!res.headersSent) {
|
|
997
1043
|
sendJson(res, 500, {
|
|
998
1044
|
jsonrpc: "2.0",
|
|
@@ -1027,11 +1073,16 @@ async function startHttp(config) {
|
|
|
1027
1073
|
}
|
|
1028
1074
|
async function main() {
|
|
1029
1075
|
const baseUrl = getRequiredEnvVar('BOOKSTACK_BASE_URL');
|
|
1076
|
+
const transportMode = (process.env.MCP_TRANSPORT ?? 'stdio').toLowerCase();
|
|
1077
|
+
const isHttpTransport = transportMode === 'http' || transportMode === 'sse';
|
|
1030
1078
|
const insecureSkipTlsVerify = process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true';
|
|
1031
1079
|
const envEnableWrite = process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true';
|
|
1032
1080
|
const timeoutRaw = process.env.BOOKSTACK_TIMEOUT_MS;
|
|
1033
1081
|
const timeoutParsed = timeoutRaw ? parseInt(timeoutRaw, 10) : NaN;
|
|
1034
1082
|
const timeoutMs = Number.isFinite(timeoutParsed) && timeoutParsed > 0 ? timeoutParsed : undefined;
|
|
1083
|
+
const retryTimeoutParsed = Number(process.env.BOOKSTACK_RETRY_TIMEOUT_MS);
|
|
1084
|
+
const retryTimeoutMs = Number.isFinite(retryTimeoutParsed) && retryTimeoutParsed > 0
|
|
1085
|
+
? retryTimeoutParsed : undefined;
|
|
1035
1086
|
const concurrencyRaw = process.env.BOOKSTACK_MAX_CONCURRENCY;
|
|
1036
1087
|
const concurrencyParsed = concurrencyRaw ? parseInt(concurrencyRaw, 10) : NaN;
|
|
1037
1088
|
const maxConcurrency = Number.isFinite(concurrencyParsed) && concurrencyParsed > 0
|
|
@@ -1053,6 +1104,11 @@ async function main() {
|
|
|
1053
1104
|
enableWrite: oauth ? false : envEnableWrite,
|
|
1054
1105
|
insecureSkipTlsVerify,
|
|
1055
1106
|
timeoutMs,
|
|
1107
|
+
retryTimeoutMs,
|
|
1108
|
+
allowLocalImageFiles: !isHttpTransport || process.env.BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES?.toLowerCase() === 'true',
|
|
1109
|
+
imageAllowedHosts: isHttpTransport
|
|
1110
|
+
? (process.env.BOOKSTACK_IMAGE_ALLOWED_HOSTS ?? '').split(',').map(host => host.trim().toLowerCase()).filter(Boolean)
|
|
1111
|
+
: undefined,
|
|
1056
1112
|
maxConcurrency
|
|
1057
1113
|
};
|
|
1058
1114
|
// The write credential is optional and only used by the OAuth proxy for sessions whose
|
|
@@ -1060,14 +1116,14 @@ async function main() {
|
|
|
1060
1116
|
const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
|
|
1061
1117
|
const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
|
|
1062
1118
|
const write = (writeTokenId && writeTokenSecret)
|
|
1063
|
-
? {
|
|
1119
|
+
? { ...read, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true }
|
|
1064
1120
|
: null;
|
|
1065
1121
|
const config = { read, write, oauth };
|
|
1066
1122
|
console.error('Initializing BookStack MCP Server...');
|
|
1067
|
-
console.error(`BookStack
|
|
1123
|
+
console.error(`BookStack origin: ${safeUrlOrigin(baseUrl)}`);
|
|
1068
1124
|
if (oauth) {
|
|
1069
1125
|
console.error(`Auth: Entra OAuth proxy ENABLED (tenant ${oauth.tenantId})`);
|
|
1070
|
-
console.error(` Public
|
|
1126
|
+
console.error(` Public origin: ${safeUrlOrigin(oauth.serverUrl)}`);
|
|
1071
1127
|
console.error(` Write role: ${oauth.writeRole}`);
|
|
1072
1128
|
if (!write) {
|
|
1073
1129
|
console.error(' WARNING: no BOOKSTACK_WRITE_TOKEN_ID/SECRET set — all sessions are read-only regardless of role.');
|
|
@@ -1079,8 +1135,7 @@ async function main() {
|
|
|
1079
1135
|
if (insecureSkipTlsVerify) {
|
|
1080
1136
|
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.');
|
|
1081
1137
|
}
|
|
1082
|
-
|
|
1083
|
-
if (transportMode === "http" || transportMode === "sse") {
|
|
1138
|
+
if (isHttpTransport) {
|
|
1084
1139
|
await startHttp(config);
|
|
1085
1140
|
}
|
|
1086
1141
|
else {
|
|
@@ -1088,6 +1143,6 @@ async function main() {
|
|
|
1088
1143
|
}
|
|
1089
1144
|
}
|
|
1090
1145
|
main().catch((err) => {
|
|
1091
|
-
|
|
1146
|
+
logSafeError('Server startup failed', err);
|
|
1092
1147
|
process.exit(1);
|
|
1093
1148
|
});
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { randomUUID, createHash, randomBytes } from "node:crypto";
|
|
13
13
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
14
14
|
import { InMemoryKvStore, createStore } from "./kv-store.js";
|
|
15
|
+
import { logSafeError, oauthErrorCode } from "../util/safe-errors.js";
|
|
15
16
|
// Load config from env. Returns null when OAuth proxy mode is disabled.
|
|
16
17
|
export function loadOAuthConfig(env) {
|
|
17
18
|
if (env.MCP_OAUTH_ENABLE?.toLowerCase() !== "true")
|
|
@@ -162,9 +163,9 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
162
163
|
const url = new URL(req.url ?? "/", cfg.serverUrl);
|
|
163
164
|
const path = url.pathname;
|
|
164
165
|
if (["/register", "/authorize", "/callback", "/token"].includes(path)) {
|
|
165
|
-
console.error(`[oauth] ${
|
|
166
|
+
console.error(`[oauth] ${path}` +
|
|
166
167
|
(path === "/callback"
|
|
167
|
-
? ` error=${url.searchParams.
|
|
168
|
+
? ` error=${url.searchParams.has("error")} code=${url.searchParams.has("code")} state=${url.searchParams.has("state")}`
|
|
168
169
|
: ""));
|
|
169
170
|
}
|
|
170
171
|
// RFC 9728 — Protected Resource Metadata
|
|
@@ -276,7 +277,7 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
276
277
|
await store.del(`pending:${upstreamState}`);
|
|
277
278
|
if (err || !code) {
|
|
278
279
|
const dest = new URL(p.clientRedirectUri);
|
|
279
|
-
dest.searchParams.set("error", err
|
|
280
|
+
dest.searchParams.set("error", oauthErrorCode(err, 'invalid_request'));
|
|
280
281
|
if (p.clientState)
|
|
281
282
|
dest.searchParams.set("state", p.clientState);
|
|
282
283
|
res.writeHead(302, { Location: dest.toString() });
|
|
@@ -302,8 +303,10 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
302
303
|
tokenJson = JSON.parse(rawTok);
|
|
303
304
|
}
|
|
304
305
|
catch { /* non-JSON */ }
|
|
305
|
-
if (!tokenRes.ok ||
|
|
306
|
-
|
|
306
|
+
if (!tokenRes.ok || typeof tokenJson?.access_token !== 'string' || !tokenJson.access_token) {
|
|
307
|
+
logSafeError('[oauth] /callback Entra token exchange FAILED', {
|
|
308
|
+
status: tokenRes.status, code: oauthErrorCode(tokenJson?.error)
|
|
309
|
+
});
|
|
307
310
|
const dest = new URL(p.clientRedirectUri);
|
|
308
311
|
dest.searchParams.set("error", "server_error");
|
|
309
312
|
if (p.clientState)
|
|
@@ -347,7 +350,7 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
347
350
|
return true;
|
|
348
351
|
}
|
|
349
352
|
if (form["client_id"] && form["client_id"] !== issued.clientId) {
|
|
350
|
-
console.error(
|
|
353
|
+
console.error('[oauth] /token authorization_code: client mismatch');
|
|
351
354
|
sendJson(res, 400, { error: "invalid_client" });
|
|
352
355
|
return true;
|
|
353
356
|
}
|
|
@@ -369,18 +372,19 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
369
372
|
}),
|
|
370
373
|
});
|
|
371
374
|
const refreshJson = await refreshRes.json().catch(() => null);
|
|
372
|
-
|
|
375
|
+
const refreshed = refreshRes.ok && typeof refreshJson?.access_token === 'string' && !!refreshJson.access_token;
|
|
376
|
+
if (refreshed) {
|
|
373
377
|
// Never log the body here: on success it carries the access and refresh tokens.
|
|
374
378
|
console.error("[oauth] /token refresh_token: OK");
|
|
375
379
|
}
|
|
376
380
|
else {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
console.error(`[oauth] /token refresh_token: FAILED status=${refreshRes.status} ` +
|
|
381
|
-
`error=${refreshJson?.error ?? "unknown"} desc=${(refreshJson?.error_description ?? "").slice(0, 300)}`);
|
|
381
|
+
logSafeError('[oauth] /token refresh_token: FAILED', {
|
|
382
|
+
status: refreshRes.status, code: oauthErrorCode(refreshJson?.error, 'invalid_grant')
|
|
383
|
+
});
|
|
382
384
|
}
|
|
383
|
-
sendJson(res,
|
|
385
|
+
sendJson(res, refreshed ? 200 : 400, refreshed ? refreshJson : {
|
|
386
|
+
error: oauthErrorCode(refreshJson?.error, 'invalid_grant')
|
|
387
|
+
});
|
|
384
388
|
return true;
|
|
385
389
|
}
|
|
386
390
|
sendJson(res, 400, { error: "unsupported_grant_type" });
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { BookStackClient } from './bookstack-client.js';
|
|
3
|
+
const requests = new AsyncLocalStorage();
|
|
4
|
+
export function parseRequestCredentials(headers, enabled) {
|
|
5
|
+
if (!enabled)
|
|
6
|
+
return undefined;
|
|
7
|
+
const tokenId = headers['x-bookstack-token-id'];
|
|
8
|
+
const tokenSecret = headers['x-bookstack-token-secret'];
|
|
9
|
+
if (tokenId === undefined && tokenSecret === undefined)
|
|
10
|
+
return undefined;
|
|
11
|
+
if (typeof tokenId !== 'string' || typeof tokenSecret !== 'string' ||
|
|
12
|
+
!tokenId.trim() || !tokenSecret.trim() || /[\s:,]/.test(tokenId) || /[\s,]/.test(tokenSecret)) {
|
|
13
|
+
throw new Error('Supply both X-Bookstack-Token-Id and X-Bookstack-Token-Secret as single non-empty credentials.');
|
|
14
|
+
}
|
|
15
|
+
return { tokenId, tokenSecret };
|
|
16
|
+
}
|
|
17
|
+
export function withRequestCredentials(credentials, fn) {
|
|
18
|
+
return requests.run({ credentials, clients: new Map() }, fn);
|
|
19
|
+
}
|
|
20
|
+
/** Tool/resource closures use the current HTTP request identity, including when
|
|
21
|
+
* a session is reused. Each request owns its clients and private slug caches. */
|
|
22
|
+
export function requestScopedClient(config) {
|
|
23
|
+
const fallback = new BookStackClient(config);
|
|
24
|
+
return new Proxy(fallback, {
|
|
25
|
+
get(target, property) {
|
|
26
|
+
const request = requests.getStore();
|
|
27
|
+
let selected = target;
|
|
28
|
+
if (request?.credentials) {
|
|
29
|
+
selected = request.clients.get(target);
|
|
30
|
+
if (!selected) {
|
|
31
|
+
selected = new BookStackClient({ ...config, ...request.credentials, privateSlugCache: true });
|
|
32
|
+
request.clients.set(target, selected);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const value = Reflect.get(selected, property);
|
|
36
|
+
return typeof value === 'function' ? value.bind(selected) : value;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { AxiosError } from 'axios';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import { PublicError } from './safe-errors.js';
|
|
4
|
+
const MAX_RETRIES = 5;
|
|
5
|
+
const MAX_DELAY_MS = 30000;
|
|
6
|
+
export function retryDelay(value, retry) {
|
|
7
|
+
let delay = 1000 * 2 ** (retry - 1);
|
|
8
|
+
if (typeof value === 'string' && value.trim()) {
|
|
9
|
+
const seconds = Number(value);
|
|
10
|
+
const parsed = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
|
|
11
|
+
if (Number.isFinite(parsed))
|
|
12
|
+
delay = parsed;
|
|
13
|
+
}
|
|
14
|
+
return Math.min(MAX_DELAY_MS, Math.max(0, delay));
|
|
15
|
+
}
|
|
16
|
+
export class BookStackRateLimitError extends PublicError {
|
|
17
|
+
retryAfterMs;
|
|
18
|
+
code = 'BOOKSTACK_RATE_LIMITED';
|
|
19
|
+
status = 429;
|
|
20
|
+
constructor(retryAfterMs) {
|
|
21
|
+
super('BookStack rate limited (HTTP 429): retry budget exhausted. Try again later or reduce parallel tool calls.');
|
|
22
|
+
this.retryAfterMs = retryAfterMs;
|
|
23
|
+
this.name = 'BookStackRateLimitError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** One budget covers queueing, HTTP attempts and backoff. Permits are released
|
|
27
|
+
* during backoff, and cancellation removes queued work instead of leaking it. */
|
|
28
|
+
export function rateLimitedAdapter(adapter, limiter, budgetMs) {
|
|
29
|
+
return async (config) => {
|
|
30
|
+
const controller = new AbortController();
|
|
31
|
+
const originalSignal = config.signal;
|
|
32
|
+
const cancel = () => controller.abort();
|
|
33
|
+
if (originalSignal?.aborted)
|
|
34
|
+
cancel();
|
|
35
|
+
originalSignal?.addEventListener?.('abort', cancel);
|
|
36
|
+
const deadline = Date.now() + budgetMs;
|
|
37
|
+
const timeoutError = new AxiosError('BookStack request deadline exceeded', 'ETIMEDOUT', config);
|
|
38
|
+
const timer = setTimeout(() => controller.abort(timeoutError), budgetMs);
|
|
39
|
+
let last429;
|
|
40
|
+
let delay = 0;
|
|
41
|
+
try {
|
|
42
|
+
for (let retry = 0;; retry++) {
|
|
43
|
+
try {
|
|
44
|
+
return await limiter.run(() => {
|
|
45
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
46
|
+
return adapter({
|
|
47
|
+
...config,
|
|
48
|
+
signal: controller.signal,
|
|
49
|
+
timeout: config.timeout > 0 ? Math.min(config.timeout, remaining) : remaining
|
|
50
|
+
});
|
|
51
|
+
}, controller.signal);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (controller.signal.aborted)
|
|
55
|
+
throw error;
|
|
56
|
+
if (!(error instanceof AxiosError) || error.response?.status !== 429)
|
|
57
|
+
throw error;
|
|
58
|
+
last429 = error;
|
|
59
|
+
delay = retryDelay(error.response.headers?.['retry-after'], retry + 1);
|
|
60
|
+
if (retry >= MAX_RETRIES || delay >= deadline - Date.now()) {
|
|
61
|
+
throw new BookStackRateLimitError(delay);
|
|
62
|
+
}
|
|
63
|
+
console.error(`BookStack rate limited (429); retry ${retry + 1}/${MAX_RETRIES} in ${delay}ms`);
|
|
64
|
+
await sleep(delay, undefined, { signal: controller.signal });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (controller.signal.aborted && !originalSignal?.aborted) {
|
|
70
|
+
if (last429)
|
|
71
|
+
throw new BookStackRateLimitError(delay);
|
|
72
|
+
throw timeoutError;
|
|
73
|
+
}
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
originalSignal?.removeEventListener?.('abort', cancel);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Messages authored by this application, rather than supplied by a remote
|
|
2
|
+
* service or a library. Only these messages may reach MCP clients unchanged. */
|
|
3
|
+
export class PublicError extends Error {
|
|
4
|
+
}
|
|
5
|
+
const OAUTH_CODES = new Set([
|
|
6
|
+
'invalid_grant', 'invalid_client', 'invalid_request', 'unauthorized_client',
|
|
7
|
+
'access_denied', 'temporarily_unavailable', 'server_error', 'invalid_scope',
|
|
8
|
+
'interaction_required', 'consent_required', 'login_required'
|
|
9
|
+
]);
|
|
10
|
+
const SAFE_CODES = new Set([
|
|
11
|
+
'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT',
|
|
12
|
+
'ECONNABORTED', 'ERR_NETWORK', 'ERR_CANCELED', 'ERR_BAD_REQUEST',
|
|
13
|
+
'ERR_BAD_RESPONSE', 'ERR_INVALID_URL', 'ENOENT', 'EACCES', 'BOOKSTACK_RATE_LIMITED',
|
|
14
|
+
...OAUTH_CODES
|
|
15
|
+
]);
|
|
16
|
+
/** Allowlist fields, not a recursive dump/redaction of arbitrary error objects.
|
|
17
|
+
* In particular, messages, stacks, causes, config, headers and bodies are omitted. */
|
|
18
|
+
export function safeErrorDetails(error) {
|
|
19
|
+
try {
|
|
20
|
+
if (!error || typeof error !== 'object')
|
|
21
|
+
return {};
|
|
22
|
+
const value = error;
|
|
23
|
+
const status = value.response?.status ?? value.status;
|
|
24
|
+
return {
|
|
25
|
+
...(typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599 ? { status } : {}),
|
|
26
|
+
...(typeof value.code === 'string' && SAFE_CODES.has(value.code) ? { code: value.code } : {})
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return {}; // A throwing getter must not defeat the error boundary.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function safeError(error, context = 'Operation failed') {
|
|
34
|
+
if (error instanceof PublicError)
|
|
35
|
+
return error;
|
|
36
|
+
const { status, code } = safeErrorDetails(error);
|
|
37
|
+
const details = [status === undefined ? '' : `HTTP ${status}`, code ?? ''].filter(Boolean);
|
|
38
|
+
const result = new PublicError(`${context}${details.length ? ` (${details.join('; ')})` : ''}`);
|
|
39
|
+
return Object.assign(result, safeErrorDetails(error));
|
|
40
|
+
}
|
|
41
|
+
export function logSafeError(event, error) {
|
|
42
|
+
console.error(event, safeErrorDetails(error));
|
|
43
|
+
}
|
|
44
|
+
export function safeUrlOrigin(value) {
|
|
45
|
+
try {
|
|
46
|
+
const url = new URL(value);
|
|
47
|
+
return ['http:', 'https:'].includes(url.protocol) ? url.origin : '<invalid URL>';
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return '<invalid URL>';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function oauthErrorCode(value, fallback = 'server_error') {
|
|
54
|
+
return typeof value === 'string' && OAUTH_CODES.has(value) ? value : fallback;
|
|
55
|
+
}
|