bookstack-mcp 5.3.0 → 5.4.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 +12 -4
- package/dist/bookstack-client.js +28 -9
- package/dist/index.js +105 -20
- package/dist/oauth/entra-proxy.js +11 -0
- package/dist/session-registry.js +95 -0
- package/dist/util/word-count.js +16 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,9 +15,11 @@ A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gi
|
|
|
15
15
|
npx bookstack-mcp
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
Field notes: [Why my BookStack MCP server starts read-only](https://hackyourworld.com/bookstack-mcp-server-read-only-by-default/) covers the shared-token rate-limit failure, process-wide cache, response-size measurements, and permission boundaries that shaped the current design.
|
|
19
|
+
|
|
18
20
|
## Features
|
|
19
21
|
|
|
20
|
-
- 20 read-only tools +
|
|
22
|
+
- 20 read-only tools + 20 write tools for complete BookStack API coverage
|
|
21
23
|
- Books, chapters, pages, shelves, attachments, and comments — full CRUD
|
|
22
24
|
- Recycle bin support — restore or permanently delete soft-deleted content
|
|
23
25
|
- Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
|
|
@@ -242,7 +244,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
242
244
|
| `get_shelves` / `get_shelf` | List or get shelf details |
|
|
243
245
|
| `get_attachments` / `get_attachment` | List or get attachment details |
|
|
244
246
|
| `get_comments` / `get_comment` | List or get page comments (BookStack v25.11+) |
|
|
245
|
-
| `find_users` | Look up BookStack users by name, email, or slug to resolve
|
|
247
|
+
| `find_users` | Look up BookStack users by name, email, or slug to resolve user slugs for `{created_by:X}`-style search filters |
|
|
246
248
|
| `get_recycle_bin` | List items in the recycle bin |
|
|
247
249
|
| `export_page` | Export page as HTML, PDF, Markdown, plaintext, or ZIP |
|
|
248
250
|
| `export_book` | Export entire book |
|
|
@@ -253,8 +255,8 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
253
255
|
|
|
254
256
|
| Tool | Description |
|
|
255
257
|
|------|-------------|
|
|
256
|
-
| `create_book` / `delete_book` | Create or delete a book |
|
|
257
|
-
| `create_chapter` / `delete_chapter` | Create or delete a chapter |
|
|
258
|
+
| `create_book` / `update_book` / `delete_book` | Create, update, or delete a book |
|
|
259
|
+
| `create_chapter` / `update_chapter` / `delete_chapter` | Create, update (including moving to a different book or reordering), or delete a chapter |
|
|
258
260
|
| `create_page` | Create a new page (HTML or Markdown) |
|
|
259
261
|
| `update_page` | Update content, rename, or move to a different book/chapter |
|
|
260
262
|
| `delete_page` | Delete a page (recoverable from recycle bin) |
|
|
@@ -271,6 +273,12 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
271
273
|
4. In the **API Tokens** section, create a new token
|
|
272
274
|
5. Copy the Token ID and Token Secret
|
|
273
275
|
|
|
276
|
+
> **Also grant the role “Export Content”** if you read pages written in the
|
|
277
|
+
> WYSIWYG editor. BookStack returns an empty `markdown` body for those pages, and
|
|
278
|
+
> `get_page` recovers it from the server-side HTML→markdown export endpoint. Without
|
|
279
|
+
> the permission that fallback fails and the page reads as empty. The default Viewer
|
|
280
|
+
> role does not include it.
|
|
281
|
+
|
|
274
282
|
## Security
|
|
275
283
|
|
|
276
284
|
- Write operations are **disabled by default**
|
package/dist/bookstack-client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import axios from 'axios';
|
|
2
2
|
import https from 'https';
|
|
3
3
|
import { Semaphore } from './util/semaphore.js';
|
|
4
|
+
import { countWords } from './util/word-count.js';
|
|
4
5
|
const MAX_RETRIES_429 = 5;
|
|
5
6
|
function parseRetryAfter(value) {
|
|
6
7
|
if (typeof value !== 'string' || !value)
|
|
@@ -13,16 +14,20 @@ function parseRetryAfter(value) {
|
|
|
13
14
|
return Math.max(0, dateMs - Date.now());
|
|
14
15
|
return null;
|
|
15
16
|
}
|
|
16
|
-
// BookStack
|
|
17
|
-
//
|
|
18
|
-
//
|
|
17
|
+
// BookStack resolves {created_by:X}/{updated_by:X}/{owned_by:X} by user SLUG, with 'me'
|
|
18
|
+
// as a shortcut for the token's own user, and silently SKIPS the filter when X matches no
|
|
19
|
+
// user's slug — the query falls back to unfiltered results, which is a confusing footgun
|
|
20
|
+
// (SearchRunner::filterCreatedBy et al. look users up by slug only). A numeric user ID is
|
|
21
|
+
// the classic way to hit it, so reject that form up front and point the caller at
|
|
22
|
+
// find_users for the slug.
|
|
19
23
|
function validateUserIdFilters(query) {
|
|
20
|
-
const re = /\{(created_by|updated_by|owned_by):([^}\s]+)\}/g;
|
|
24
|
+
const re = /\{(!?)(created_by|updated_by|owned_by):([^}\s]+)\}/g;
|
|
21
25
|
for (const match of query.matchAll(re)) {
|
|
22
|
-
const [, field, value] = match;
|
|
23
|
-
if (
|
|
24
|
-
throw new Error(`Search filter {${field}:${value}}
|
|
25
|
-
`
|
|
26
|
+
const [, neg, field, value] = match;
|
|
27
|
+
if (/^\d+$/.test(value)) {
|
|
28
|
+
throw new Error(`Search filter {${neg}${field}:${value}} takes a user slug or 'me', not a numeric user ID — ` +
|
|
29
|
+
`BookStack resolves these filters by slug and silently returns unfiltered results for ` +
|
|
30
|
+
`unmatched values. Use the find_users tool to look up a user's slug by name or email.`);
|
|
26
31
|
}
|
|
27
32
|
}
|
|
28
33
|
}
|
|
@@ -240,7 +245,7 @@ export class BookStackClient {
|
|
|
240
245
|
return {
|
|
241
246
|
...pageMeta,
|
|
242
247
|
url,
|
|
243
|
-
word_count: page
|
|
248
|
+
word_count: countWords(page),
|
|
244
249
|
content_format: format,
|
|
245
250
|
content_total_chars: totalChars,
|
|
246
251
|
content_offset: offset,
|
|
@@ -442,6 +447,20 @@ export class BookStackClient {
|
|
|
442
447
|
const response = await this.client.post('/chapters', data);
|
|
443
448
|
return await this.enhanceChapterResponse(response.data);
|
|
444
449
|
}
|
|
450
|
+
async updateBook(id, data) {
|
|
451
|
+
if (!this.enableWrite) {
|
|
452
|
+
throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
453
|
+
}
|
|
454
|
+
const response = await this.client.put(`/books/${id}`, data);
|
|
455
|
+
return this.enhanceBookResponse(response.data);
|
|
456
|
+
}
|
|
457
|
+
async updateChapter(id, data) {
|
|
458
|
+
if (!this.enableWrite) {
|
|
459
|
+
throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
460
|
+
}
|
|
461
|
+
const response = await this.client.put(`/chapters/${id}`, data);
|
|
462
|
+
return await this.enhanceChapterResponse(response.data);
|
|
463
|
+
}
|
|
445
464
|
async createPage(data) {
|
|
446
465
|
if (!this.enableWrite) {
|
|
447
466
|
throw new Error('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
package/dist/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { z } from "zod";
|
|
|
12
12
|
import { BookStackClient } from "./bookstack-client.js";
|
|
13
13
|
import { registerPrompts } from "./prompts.js";
|
|
14
14
|
import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
|
|
15
|
+
import { SessionRegistry } from "./session-registry.js";
|
|
15
16
|
const PKG_VERSION = (() => {
|
|
16
17
|
try {
|
|
17
18
|
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
@@ -152,7 +153,7 @@ function registerTools(server, client, config) {
|
|
|
152
153
|
// Common params (offset/count/sort/filter/id) are self-describing and intentionally
|
|
153
154
|
// bare so tool definitions stay compact in the MCP tools/list payload.
|
|
154
155
|
readTool("search_content", {
|
|
155
|
-
description: "Search BookStack content. Supports advanced syntax like {type:page} or {book_id:5}. {created_by:X}/{updated_by:X}/{owned_by:X}
|
|
156
|
+
description: "Search BookStack content. Supports advanced syntax like {type:page} or {book_id:5}. {created_by:X}/{updated_by:X}/{owned_by:X} take a user slug or 'me' — use find_users to resolve names to slugs.",
|
|
156
157
|
inputSchema: {
|
|
157
158
|
query: z.string(),
|
|
158
159
|
type: z.enum(["book", "page", "chapter", "bookshelf"]).optional(),
|
|
@@ -434,7 +435,7 @@ function registerTools(server, client, config) {
|
|
|
434
435
|
};
|
|
435
436
|
});
|
|
436
437
|
readTool("find_users", {
|
|
437
|
-
description: "List users; filter by name/email/slug (partial match). Resolves names to
|
|
438
|
+
description: "List users; filter by name/email/slug (partial match). Resolves names to user slugs for {created_by:X}/{updated_by:X}/{owned_by:X} search filters. Requires admin token.",
|
|
438
439
|
inputSchema: {
|
|
439
440
|
name: z.string().optional(),
|
|
440
441
|
email: z.string().optional(),
|
|
@@ -522,6 +523,52 @@ function registerTools(server, client, config) {
|
|
|
522
523
|
content: [{ type: "text", text: JSON.stringify(chapter) }]
|
|
523
524
|
};
|
|
524
525
|
});
|
|
526
|
+
writeTool("update_book", {
|
|
527
|
+
description: "Update an existing book",
|
|
528
|
+
inputSchema: {
|
|
529
|
+
id: z.coerce.number().min(1),
|
|
530
|
+
name: z.string().optional().describe("New book name"),
|
|
531
|
+
description: z.string().optional().describe("New book description"),
|
|
532
|
+
tags: z.array(z.object({
|
|
533
|
+
name: z.string(),
|
|
534
|
+
value: z.string()
|
|
535
|
+
}).strict()).optional().describe("Tags for the book")
|
|
536
|
+
}
|
|
537
|
+
}, async (args) => {
|
|
538
|
+
const book = await client.updateBook(args.id, {
|
|
539
|
+
name: args.name,
|
|
540
|
+
description: args.description,
|
|
541
|
+
tags: args.tags
|
|
542
|
+
});
|
|
543
|
+
return {
|
|
544
|
+
content: [{ type: "text", text: JSON.stringify(book) }]
|
|
545
|
+
};
|
|
546
|
+
});
|
|
547
|
+
writeTool("update_chapter", {
|
|
548
|
+
description: "Update an existing chapter. Pass book_id to move the chapter to a different book, or priority to reorder it within its book.",
|
|
549
|
+
inputSchema: {
|
|
550
|
+
id: z.coerce.number().min(1),
|
|
551
|
+
name: z.string().optional().describe("New chapter name"),
|
|
552
|
+
description: z.string().optional().describe("New chapter description"),
|
|
553
|
+
book_id: z.coerce.number().min(1).optional().describe("Optional: Move chapter to this book"),
|
|
554
|
+
priority: z.coerce.number().int().min(0).optional().describe("Optional: Reorder chapter within its book (non-negative integer, lower sorts first)"),
|
|
555
|
+
tags: z.array(z.object({
|
|
556
|
+
name: z.string(),
|
|
557
|
+
value: z.string()
|
|
558
|
+
}).strict()).optional().describe("Tags for the chapter")
|
|
559
|
+
}
|
|
560
|
+
}, async (args) => {
|
|
561
|
+
const chapter = await client.updateChapter(args.id, {
|
|
562
|
+
name: args.name,
|
|
563
|
+
description: args.description,
|
|
564
|
+
book_id: args.book_id,
|
|
565
|
+
priority: args.priority,
|
|
566
|
+
tags: args.tags
|
|
567
|
+
});
|
|
568
|
+
return {
|
|
569
|
+
content: [{ type: "text", text: JSON.stringify(chapter) }]
|
|
570
|
+
};
|
|
571
|
+
});
|
|
525
572
|
writeTool("create_page", {
|
|
526
573
|
description: "Create a new page in BookStack",
|
|
527
574
|
inputSchema: {
|
|
@@ -801,9 +848,13 @@ async function startHttp(config) {
|
|
|
801
848
|
: hostHeader.split(":")[0];
|
|
802
849
|
return allowedHosts.includes(hostname) ? null : `Host '${hostname}' not allowed`;
|
|
803
850
|
};
|
|
804
|
-
const
|
|
805
|
-
|
|
806
|
-
const
|
|
851
|
+
const idleTtlRaw = process.env.BOOKSTACK_SESSION_IDLE_TTL_MS;
|
|
852
|
+
const idleTtlParsed = idleTtlRaw ? parseInt(idleTtlRaw, 10) : NaN;
|
|
853
|
+
const idleTtlMs = Number.isFinite(idleTtlParsed) && idleTtlParsed > 0 ? idleTtlParsed : undefined;
|
|
854
|
+
const maxSessionsRaw = process.env.BOOKSTACK_MAX_SESSIONS;
|
|
855
|
+
const maxSessionsParsed = maxSessionsRaw ? parseInt(maxSessionsRaw, 10) : NaN;
|
|
856
|
+
const maxSessions = Number.isFinite(maxSessionsParsed) && maxSessionsParsed > 0 ? maxSessionsParsed : undefined;
|
|
857
|
+
const sessions = new SessionRegistry({ idleTtlMs, maxSessions });
|
|
807
858
|
const readJsonBody = (req) => new Promise((resolve, reject) => {
|
|
808
859
|
const chunks = [];
|
|
809
860
|
req.on("data", (c) => chunks.push(c));
|
|
@@ -824,6 +875,9 @@ async function startHttp(config) {
|
|
|
824
875
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
825
876
|
res.end(JSON.stringify(body));
|
|
826
877
|
};
|
|
878
|
+
// A session id is bearer-equivalent: anyone holding it can drive the session. Log only
|
|
879
|
+
// a prefix — enough to correlate a session's life across lines, not enough to replay.
|
|
880
|
+
const shortSid = (sid) => `${sid.slice(0, 8)}...`;
|
|
827
881
|
const httpServer = createHttpServer(async (req, res) => {
|
|
828
882
|
try {
|
|
829
883
|
const hostError = validateHost(req);
|
|
@@ -855,9 +909,10 @@ async function startHttp(config) {
|
|
|
855
909
|
if (req.method === "POST") {
|
|
856
910
|
parsedBody = await readJsonBody(req);
|
|
857
911
|
}
|
|
858
|
-
if (sessionId &&
|
|
912
|
+
if (sessionId && sessions.has(sessionId)) {
|
|
859
913
|
// Reject a valid token belonging to a different subject than the session was bound to.
|
|
860
|
-
|
|
914
|
+
const boundAuth = sessions.getAuth(sessionId);
|
|
915
|
+
if (config.oauth && boundAuth && auth?.sub !== boundAuth.sub) {
|
|
861
916
|
sendJson(res, 403, {
|
|
862
917
|
jsonrpc: "2.0",
|
|
863
918
|
error: { code: -32003, message: "Forbidden: token does not match session" },
|
|
@@ -865,9 +920,32 @@ async function startHttp(config) {
|
|
|
865
920
|
});
|
|
866
921
|
return;
|
|
867
922
|
}
|
|
868
|
-
transport =
|
|
923
|
+
transport = sessions.get(sessionId);
|
|
924
|
+
}
|
|
925
|
+
else if (sessionId) {
|
|
926
|
+
// The session was terminated (idle sweep, or a restart — sessions are held in
|
|
927
|
+
// process memory only). MCP's Streamable HTTP spec, Session Management §3:
|
|
928
|
+
// the server "MUST respond to requests containing that session ID with HTTP
|
|
929
|
+
// 404 Not Found", and §4 makes 404 the one signal that tells a client to
|
|
930
|
+
// re-initialize. Answering 400 here leaves the client no defined recovery, so
|
|
931
|
+
// the connector stays down until a human reconnects it.
|
|
932
|
+
console.error(`[mcp] ${req.method} session ${shortSid(sessionId)} not found -> 404 (client should re-initialize); live=${sessions.size()}`);
|
|
933
|
+
sendJson(res, 404, {
|
|
934
|
+
jsonrpc: "2.0",
|
|
935
|
+
error: { code: -32001, message: "Session not found" },
|
|
936
|
+
id: null
|
|
937
|
+
});
|
|
938
|
+
return;
|
|
869
939
|
}
|
|
870
|
-
else if (
|
|
940
|
+
else if (req.method === "POST" && isInitializeRequest(parsedBody)) {
|
|
941
|
+
if (sessions.atCapacity()) {
|
|
942
|
+
sendJson(res, 503, {
|
|
943
|
+
jsonrpc: "2.0",
|
|
944
|
+
error: { code: -32000, message: "Server busy: maximum concurrent sessions reached" },
|
|
945
|
+
id: null
|
|
946
|
+
});
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
871
949
|
// Choose the per-session credential: writers (with a write token configured) get the
|
|
872
950
|
// write token and write tools; everyone else gets the read-only token.
|
|
873
951
|
const useWrite = !!(auth?.isWriter && config.write);
|
|
@@ -875,17 +953,16 @@ async function startHttp(config) {
|
|
|
875
953
|
transport = new StreamableHTTPServerTransport({
|
|
876
954
|
sessionIdGenerator: () => randomUUID(),
|
|
877
955
|
onsessioninitialized: (sid) => {
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
sessionAuth[sid] = auth;
|
|
956
|
+
sessions.register(sid, transport, config.oauth && auth ? auth : undefined);
|
|
957
|
+
console.error(`[mcp] session ${shortSid(sid)} initialized; live=${sessions.size()}`);
|
|
881
958
|
}
|
|
882
959
|
});
|
|
883
960
|
transport.onclose = () => {
|
|
884
961
|
const sid = transport.sessionId;
|
|
885
|
-
if (sid
|
|
886
|
-
delete
|
|
887
|
-
|
|
888
|
-
|
|
962
|
+
if (sid) {
|
|
963
|
+
sessions.delete(sid);
|
|
964
|
+
console.error(`[mcp] session ${shortSid(sid)} closed; live=${sessions.size()}`);
|
|
965
|
+
}
|
|
889
966
|
};
|
|
890
967
|
const server = buildServer(sessionConfig);
|
|
891
968
|
await server.connect(transport);
|
|
@@ -903,7 +980,13 @@ async function startHttp(config) {
|
|
|
903
980
|
}
|
|
904
981
|
// Health check
|
|
905
982
|
if (pathname === "/health" || pathname === "/") {
|
|
906
|
-
sendJson(res, 200, {
|
|
983
|
+
sendJson(res, 200, {
|
|
984
|
+
status: "ok",
|
|
985
|
+
server: "bookstack-mcp",
|
|
986
|
+
transport: "http",
|
|
987
|
+
sessions: sessions.size(),
|
|
988
|
+
memoryRssBytes: process.memoryUsage().rss
|
|
989
|
+
});
|
|
907
990
|
return;
|
|
908
991
|
}
|
|
909
992
|
sendJson(res, 404, { error: "Not Found" });
|
|
@@ -925,16 +1008,18 @@ async function startHttp(config) {
|
|
|
925
1008
|
console.error(allowedHosts
|
|
926
1009
|
? ` Allowed Host headers: ${allowedHosts.join(", ")}`
|
|
927
1010
|
: ` Host header validation: DISABLED (set MCP_HTTP_ALLOWED_HOSTS to enable)`);
|
|
1011
|
+
console.error(` Session limits: idle TTL ${Math.round(sessions.idleTtlMs / 60000)}m, max concurrent ${sessions.maxSessions}`);
|
|
928
1012
|
});
|
|
929
1013
|
const shutdown = async () => {
|
|
930
1014
|
console.error("Shutting down HTTP server...");
|
|
931
|
-
for (const sid of
|
|
1015
|
+
for (const sid of sessions.sessionIds()) {
|
|
932
1016
|
try {
|
|
933
|
-
await
|
|
1017
|
+
await sessions.get(sid)?.close();
|
|
934
1018
|
}
|
|
935
1019
|
catch { }
|
|
936
|
-
delete
|
|
1020
|
+
sessions.delete(sid);
|
|
937
1021
|
}
|
|
1022
|
+
sessions.dispose();
|
|
938
1023
|
httpServer.close(() => process.exit(0));
|
|
939
1024
|
};
|
|
940
1025
|
process.on("SIGINT", shutdown);
|
|
@@ -369,6 +369,17 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
369
369
|
}),
|
|
370
370
|
});
|
|
371
371
|
const refreshJson = await refreshRes.json().catch(() => null);
|
|
372
|
+
if (refreshRes.ok) {
|
|
373
|
+
// Never log the body here: on success it carries the access and refresh tokens.
|
|
374
|
+
console.error("[oauth] /token refresh_token: OK");
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
// A failed refresh is what a user experiences as the connector going away, so it
|
|
378
|
+
// has to be visible. Only Entra's error code and description are logged; a failure
|
|
379
|
+
// response carries no token material.
|
|
380
|
+
console.error(`[oauth] /token refresh_token: FAILED status=${refreshRes.status} ` +
|
|
381
|
+
`error=${refreshJson?.error ?? "unknown"} desc=${(refreshJson?.error_description ?? "").slice(0, 300)}`);
|
|
382
|
+
}
|
|
372
383
|
sendJson(res, refreshRes.ok ? 200 : 400, refreshJson ?? { error: "invalid_grant" });
|
|
373
384
|
return true;
|
|
374
385
|
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Production traffic shows SSE streams recycling roughly every 5 minutes as normal,
|
|
2
|
+
// healthy behavior (reconnect/backoff churn). 30 minutes gives 6x that margin, so a
|
|
3
|
+
// normal reconnect cycle — even a slow or retried one — never gets mistaken for an
|
|
4
|
+
// abandoned session, while still bounding how long a truly abandoned session's
|
|
5
|
+
// transport (and the McpServer + tool closures it holds) can leak.
|
|
6
|
+
const DEFAULT_IDLE_TTL_MS = 30 * 60 * 1000;
|
|
7
|
+
// Sweep cadence mirrors oauth/kv-store.ts's InMemoryKvStore.
|
|
8
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
|
|
9
|
+
// Hard cap as a second line of defense: bounds worst-case memory even if the TTL
|
|
10
|
+
// logic has a bug, or a burst of sessions arrives faster than a sweep tick.
|
|
11
|
+
const DEFAULT_MAX_SESSIONS = 1000;
|
|
12
|
+
/**
|
|
13
|
+
* Tracks live StreamableHTTPServerTransport sessions and their OAuth binding for the
|
|
14
|
+
* HTTP transport. Mirrors oauth/kv-store.ts's InMemoryKvStore: a periodic sweep
|
|
15
|
+
* (`setInterval`, `.unref()`'d) evicts sessions idle longer than `idleTtlMs`, with a
|
|
16
|
+
* lazy expiry check on access as a backstop between sweeps. `maxSessions` is a hard
|
|
17
|
+
* cap enforced independently of the TTL. `dispose()` stops the sweep timer.
|
|
18
|
+
*/
|
|
19
|
+
export class SessionRegistry {
|
|
20
|
+
transports = {};
|
|
21
|
+
sessionAuth = {};
|
|
22
|
+
lastSeen = {};
|
|
23
|
+
idleTtlMs;
|
|
24
|
+
maxSessions;
|
|
25
|
+
sweep;
|
|
26
|
+
constructor(options = {}) {
|
|
27
|
+
this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
|
|
28
|
+
this.maxSessions = options.maxSessions ?? DEFAULT_MAX_SESSIONS;
|
|
29
|
+
const sweepIntervalMs = options.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
|
|
30
|
+
this.sweep = setInterval(() => this.sweepExpired(), sweepIntervalMs);
|
|
31
|
+
this.sweep.unref?.();
|
|
32
|
+
}
|
|
33
|
+
/** Closes the transport (best-effort) before dropping it from bookkeeping, mirroring shutdown(). */
|
|
34
|
+
evict(sessionId) {
|
|
35
|
+
this.transports[sessionId]?.close().catch(() => { });
|
|
36
|
+
this.delete(sessionId);
|
|
37
|
+
}
|
|
38
|
+
sweepExpired() {
|
|
39
|
+
const now = Date.now();
|
|
40
|
+
for (const sid of Object.keys(this.transports)) {
|
|
41
|
+
if (now - (this.lastSeen[sid] ?? 0) >= this.idleTtlMs)
|
|
42
|
+
this.evict(sid);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Evicts sessionId if idle-expired. Returns true if it was (or already is) absent. */
|
|
46
|
+
purgeIfExpired(sessionId) {
|
|
47
|
+
if (!(sessionId in this.transports))
|
|
48
|
+
return true;
|
|
49
|
+
const seen = this.lastSeen[sessionId];
|
|
50
|
+
if (seen === undefined || Date.now() - seen >= this.idleTtlMs) {
|
|
51
|
+
this.evict(sessionId);
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
has(sessionId) {
|
|
57
|
+
return !this.purgeIfExpired(sessionId);
|
|
58
|
+
}
|
|
59
|
+
/** Also refreshes the session's idle timer — every real request is a keep-alive. */
|
|
60
|
+
get(sessionId) {
|
|
61
|
+
if (this.purgeIfExpired(sessionId))
|
|
62
|
+
return undefined;
|
|
63
|
+
this.lastSeen[sessionId] = Date.now();
|
|
64
|
+
return this.transports[sessionId];
|
|
65
|
+
}
|
|
66
|
+
getAuth(sessionId) {
|
|
67
|
+
if (this.purgeIfExpired(sessionId))
|
|
68
|
+
return undefined;
|
|
69
|
+
return this.sessionAuth[sessionId];
|
|
70
|
+
}
|
|
71
|
+
atCapacity() {
|
|
72
|
+
return this.size() >= this.maxSessions;
|
|
73
|
+
}
|
|
74
|
+
register(sessionId, transport, auth) {
|
|
75
|
+
this.transports[sessionId] = transport;
|
|
76
|
+
this.lastSeen[sessionId] = Date.now();
|
|
77
|
+
if (auth)
|
|
78
|
+
this.sessionAuth[sessionId] = auth;
|
|
79
|
+
}
|
|
80
|
+
delete(sessionId) {
|
|
81
|
+
delete this.transports[sessionId];
|
|
82
|
+
delete this.sessionAuth[sessionId];
|
|
83
|
+
delete this.lastSeen[sessionId];
|
|
84
|
+
}
|
|
85
|
+
sessionIds() {
|
|
86
|
+
return Object.keys(this.transports);
|
|
87
|
+
}
|
|
88
|
+
size() {
|
|
89
|
+
return this.sessionIds().length;
|
|
90
|
+
}
|
|
91
|
+
dispose() {
|
|
92
|
+
if (this.sweep)
|
|
93
|
+
clearInterval(this.sweep);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// BookStack only populates page.text for markdown-authored pages. For pages
|
|
2
|
+
// written in the WYSIWYG editor it comes back empty, so a word count taken
|
|
3
|
+
// from page.text alone reports 0 for pages that plainly have content (#10).
|
|
4
|
+
// Fall back to whichever body the response actually carries.
|
|
5
|
+
function stripHtml(html) {
|
|
6
|
+
return html
|
|
7
|
+
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
|
|
8
|
+
.replace(/<[^>]+>/g, ' ')
|
|
9
|
+
.replace(/ /gi, ' ');
|
|
10
|
+
}
|
|
11
|
+
export function countWords(page) {
|
|
12
|
+
const source = page.text || page.markdown || (page.html ? stripHtml(page.html) : '');
|
|
13
|
+
// Split on any whitespace, not a single space: a page whose lines are
|
|
14
|
+
// newline-separated counts as one word under /' '/.
|
|
15
|
+
return source.split(/\s+/).filter(Boolean).length;
|
|
16
|
+
}
|