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
package/PRIVACY.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# Privacy policy for bookstack-mcp
|
|
2
|
+
|
|
3
|
+
Last reviewed: 2026-10-09.
|
|
4
|
+
|
|
5
|
+
This policy describes the data handling implemented by the open-source
|
|
6
|
+
`bookstack-mcp` application in this repository. It applies to the software you
|
|
7
|
+
run locally or deploy on a server. A deployment operator, BookStack instance,
|
|
8
|
+
MCP client, AI provider, or other service may have additional data practices and
|
|
9
|
+
policies. This document does not establish those services' retention periods or
|
|
10
|
+
make commitments on their behalf.
|
|
11
|
+
|
|
12
|
+
The error-handling protections described below were merged in
|
|
13
|
+
[PR #47](https://github.com/ttpears/bookstack-mcp/pull/47) at security commit
|
|
14
|
+
[`35b218c5e7eca129ab94ad8f8b89275815697e3c`](https://github.com/ttpears/bookstack-mcp/commit/35b218c5e7eca129ab94ad8f8b89275815697e3c).
|
|
15
|
+
This policy does not imply that an existing package, image or deployment already
|
|
16
|
+
includes those changes. Check the source revision of the version you run.
|
|
17
|
+
|
|
18
|
+
## Data processed and where it goes
|
|
19
|
+
|
|
20
|
+
- **BookStack:** The application sends API requests to `BOOKSTACK_BASE_URL`,
|
|
21
|
+
including the configured API token ID and secret in an authorization header.
|
|
22
|
+
Requests can include search queries, identifiers, filters and, when write
|
|
23
|
+
tools are enabled, content, metadata, comments or image uploads. Responses can
|
|
24
|
+
contain private wiki content, attachment or export links, and user information
|
|
25
|
+
such as names and email addresses, subject to BookStack permissions.
|
|
26
|
+
- **MCP client:** Tool results and resources are returned to the connected MCP
|
|
27
|
+
client. The client can supply them to an AI provider or retain them in chat
|
|
28
|
+
history or logs under its own settings and policies. Read-only mode prevents
|
|
29
|
+
write tools from being registered; it does not prevent content from reaching
|
|
30
|
+
the client.
|
|
31
|
+
- **Image sources:** An enabled image-upload tool can read a caller-specified
|
|
32
|
+
local image file or download an HTTP(S) image, then upload its bytes to
|
|
33
|
+
BookStack. The image host receives the URL request and normal connection
|
|
34
|
+
information. Local file access is enabled in stdio mode; in HTTP mode it
|
|
35
|
+
requires `BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES=true`. HTTP image downloads are
|
|
36
|
+
restricted by `BOOKSTACK_IMAGE_ALLOWED_HOSTS`; stdio mode has no such host
|
|
37
|
+
restriction by default. These operations also require write tools to be
|
|
38
|
+
enabled.
|
|
39
|
+
- **Optional Microsoft Entra ID:** With `MCP_OAUTH_ENABLE=true`, the application
|
|
40
|
+
redirects sign-in to the configured Microsoft tenant, exchanges authorization
|
|
41
|
+
codes and refresh tokens with Microsoft, and fetches signing keys to validate
|
|
42
|
+
bearer tokens. The proxy processes client IDs, redirect URIs, OAuth state and
|
|
43
|
+
PKCE values, token responses and token claims. It uses the subject and roles
|
|
44
|
+
to bind HTTP sessions and select configured BookStack credentials. Token
|
|
45
|
+
responses are returned to the requesting MCP client.
|
|
46
|
+
- **Optional Redis:** When OAuth is enabled and `REDIS_URL` is configured, OAuth
|
|
47
|
+
broker state is sent to that Redis instance. Its hosting, access controls,
|
|
48
|
+
persistence and backups are controlled by the operator.
|
|
49
|
+
|
|
50
|
+
The application code has no built-in usage analytics, crash-reporting service,
|
|
51
|
+
or automatic reporting of runtime wiki content to the project maintainers. It
|
|
52
|
+
does not call an AI model API itself. These statements describe the application
|
|
53
|
+
code, not the behavior of your MCP client, infrastructure or third-party
|
|
54
|
+
services.
|
|
55
|
+
|
|
56
|
+
## Local and server deployments
|
|
57
|
+
|
|
58
|
+
Stdio mode communicates with a client through the process's standard input and
|
|
59
|
+
output. The process still makes network requests to the configured BookStack
|
|
60
|
+
instance and, when used, remote image sources. HTTP mode accepts MCP requests
|
|
61
|
+
over an HTTP listener, which defaults to `127.0.0.1`. Remote hosting introduces
|
|
62
|
+
an operator and any configured proxies or infrastructure into the data path.
|
|
63
|
+
|
|
64
|
+
BookStack credentials are supplied through environment variables or client
|
|
65
|
+
configuration. HTTP clients can optionally supply credentials per request when
|
|
66
|
+
`BOOKSTACK_ALLOW_REQUEST_CREDENTIALS=true`; those credentials are used in a
|
|
67
|
+
request-scoped client rather than stored as HTTP session credentials. OAuth
|
|
68
|
+
client secrets and other configuration are also read from the environment.
|
|
69
|
+
Credential storage by the launcher, operating system, container platform or
|
|
70
|
+
secret manager is outside this application's control.
|
|
71
|
+
|
|
72
|
+
The HTTP listener does not implement TLS itself. Operators must provide suitable
|
|
73
|
+
authentication, HTTPS or a trusted internal connection, host restrictions and
|
|
74
|
+
least-privilege BookStack tokens. BookStack certificate verification can be
|
|
75
|
+
disabled by configuration; doing so reduces protection for credentials and
|
|
76
|
+
content in transit. See [SECURITY.md](./SECURITY.md).
|
|
77
|
+
|
|
78
|
+
## Memory, broker state and retention
|
|
79
|
+
|
|
80
|
+
Requests and responses are processed in memory. Book ID-to-slug mappings are
|
|
81
|
+
cached in memory, with a ten-minute bulk refresh interval; this is not a
|
|
82
|
+
guaranteed deletion deadline for individual cache entries. HTTP transports and,
|
|
83
|
+
in OAuth mode, subject/write-role bindings are held in memory. The default HTTP
|
|
84
|
+
session idle timeout is thirty minutes and is configurable; session closure,
|
|
85
|
+
expiry and process shutdown release the corresponding application state.
|
|
86
|
+
|
|
87
|
+
OAuth broker state uses process memory unless Redis is configured. The current
|
|
88
|
+
broker assigns time-to-live values of thirty days for client registrations,
|
|
89
|
+
ten minutes for pending authorization flows, and five minutes for issued codes
|
|
90
|
+
and their associated upstream token responses. Pending flows and issued codes
|
|
91
|
+
are deleted when consumed. In-memory expiration uses access-time checks and a
|
|
92
|
+
periodic sweep; Redis uses per-key expiry. These are application state lifetimes,
|
|
93
|
+
not promises about secure memory erasure, provider retention, Redis persistence
|
|
94
|
+
or backups.
|
|
95
|
+
|
|
96
|
+
The application does not implement a persistent wiki-content database or its own
|
|
97
|
+
log-file retention system. BookStack, MCP clients, proxies, hosting platforms and
|
|
98
|
+
operators may retain content, credentials, access records, logs or backups
|
|
99
|
+
independently. Consult those services and the deployment operator for retention
|
|
100
|
+
and deletion requests.
|
|
101
|
+
|
|
102
|
+
## Logs and error responses
|
|
103
|
+
|
|
104
|
+
Diagnostics are written to standard error. They include the BookStack and public
|
|
105
|
+
HTTP URL origins (without URL credentials, paths, queries or fragments), OAuth
|
|
106
|
+
tenant, abbreviated HTTP session IDs, session counts, export page IDs and
|
|
107
|
+
lengths, rate-limit retries, and authentication diagnostics.
|
|
108
|
+
|
|
109
|
+
With the security commit identified above, upstream BookStack and image-source
|
|
110
|
+
failures are converted to application-authored context, numeric HTTP status and
|
|
111
|
+
allowlisted error codes. These errors omit upstream bodies, headers, arbitrary
|
|
112
|
+
messages and nested causes. MCP tool handlers preserve explicitly marked local
|
|
113
|
+
validation messages; startup and HTTP error logs omit complete exception
|
|
114
|
+
objects. OAuth failure logs and responses use numeric status and allowlisted
|
|
115
|
+
OAuth codes rather than upstream bodies or descriptions; callback diagnostics
|
|
116
|
+
omit callback values and client IDs. Successful OAuth token responses and
|
|
117
|
+
normal tool results still carry their intended data to the requesting client.
|
|
118
|
+
|
|
119
|
+
**Earlier versions can expose sensitive data in errors.** Builds that do not
|
|
120
|
+
include the identified security commit can log upstream response excerpts,
|
|
121
|
+
descriptions, client IDs or full exception objects, and return upstream error
|
|
122
|
+
details to MCP clients. Library exceptions can contain credentials, request
|
|
123
|
+
headers, URLs or private response data.
|
|
124
|
+
|
|
125
|
+
These application protections do not guarantee that all logs are free of
|
|
126
|
+
credentials or private content. MCP clients, proxies, hosting platforms and
|
|
127
|
+
other infrastructure can collect their own logs. Operators should restrict log
|
|
128
|
+
access, configure collection and retention, and review and redact sensitive
|
|
129
|
+
material before sharing logs or error reports.
|
|
130
|
+
|
|
131
|
+
## Third-party services and project interactions
|
|
132
|
+
|
|
133
|
+
Installing packages or images involves the registries and distribution services
|
|
134
|
+
you choose. Viewing this repository, its badges, or linked documentation involves
|
|
135
|
+
GitHub, Shields.io, HOL or other linked services. The HOL CI workflow scans the
|
|
136
|
+
repository on a GitHub runner with online analysis, SARIF upload, submissions and
|
|
137
|
+
PR comments disabled; it downloads the scanner and dependencies during setup.
|
|
138
|
+
That workflow does not run as part of the installed MCP server.
|
|
139
|
+
|
|
140
|
+
Information you choose to submit through GitHub issues, pull requests or other
|
|
141
|
+
project channels is handled by those services. Do not include tokens or private
|
|
142
|
+
wiki content in public submissions. For a suspected vulnerability or sensitive
|
|
143
|
+
disclosure, follow [SECURITY.md](./SECURITY.md). For a question about this
|
|
144
|
+
software's data handling, use the existing
|
|
145
|
+
[project issue tracker](https://github.com/ttpears/bookstack-mcp/issues) without
|
|
146
|
+
including sensitive information. For a particular hosted deployment, contact
|
|
147
|
+
its operator rather than assuming the repository maintainer operates it.
|
|
148
|
+
|
|
149
|
+
## Operator responsibilities and changes
|
|
150
|
+
|
|
151
|
+
Operators choose the BookStack instance, credentials, permitted clients, write
|
|
152
|
+
access, image sources, OAuth tenant, optional Redis, network controls and log
|
|
153
|
+
handling. They should inform their users of deployment-specific processing and
|
|
154
|
+
third-party services, provide their own applicable policies and contact channel,
|
|
155
|
+
and handle access or deletion requests for systems they control.
|
|
156
|
+
|
|
157
|
+
This policy is versioned with the repository and may change when the
|
|
158
|
+
implementation changes. Review the policy and configuration for the version you
|
|
159
|
+
actually run.
|
package/README.md
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/bookstack-mcp)
|
|
4
4
|
[](https://www.npmjs.com/package/bookstack-mcp)
|
|
5
5
|
[](https://github.com/ttpears/bookstack-mcp/actions/workflows/ci.yml)
|
|
6
|
+
[](https://hol.org/registry/plugins/ttpears%2Fbookstack-mcp)
|
|
6
7
|
[](https://nodejs.org)
|
|
7
8
|
[](https://modelcontextprotocol.io)
|
|
8
9
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -15,11 +16,15 @@ A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gi
|
|
|
15
16
|
npx bookstack-mcp
|
|
16
17
|
```
|
|
17
18
|
|
|
19
|
+
Read the [privacy policy](./PRIVACY.md) for data flows, credentials, optional
|
|
20
|
+
OAuth/Redis state, and logging. Your MCP client and deployment operator may have
|
|
21
|
+
additional policies.
|
|
22
|
+
|
|
18
23
|
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
24
|
|
|
20
25
|
## Features
|
|
21
26
|
|
|
22
|
-
-
|
|
27
|
+
- 21 read-only tools + 22 write tools for BookStack API access
|
|
23
28
|
- Books, chapters, pages, shelves, attachments, and comments — full CRUD
|
|
24
29
|
- Recycle bin support — restore or permanently delete soft-deleted content
|
|
25
30
|
- Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
|
|
@@ -55,8 +60,38 @@ BOOKSTACK_TOKEN_ID=your-token-id # Required
|
|
|
55
60
|
BOOKSTACK_TOKEN_SECRET=your-token-secret # Required
|
|
56
61
|
BOOKSTACK_ENABLE_WRITE=false # Optional, default false
|
|
57
62
|
BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=false # Optional, default false
|
|
63
|
+
BOOKSTACK_TIMEOUT_MS=30000 # Optional, timeout per HTTP attempt
|
|
64
|
+
BOOKSTACK_RETRY_TIMEOUT_MS=60000 # Optional, total budget per API request
|
|
58
65
|
```
|
|
59
66
|
|
|
67
|
+
Each API request has a total budget covering concurrency queue time, HTTP attempts,
|
|
68
|
+
and rate-limit backoff. HTTP 429 responses are retried up to five times, with each
|
|
69
|
+
delay capped at 30 seconds. If a delay cannot fit in the remaining budget or retries
|
|
70
|
+
are exhausted, the tool returns an explicit BookStack rate-limit error. The budget
|
|
71
|
+
applies to each API request; tools that fetch multiple endpoints can take longer.
|
|
72
|
+
|
|
73
|
+
With write operations enabled, `update_page` and `update_chapter` accept `priority`
|
|
74
|
+
as a non-negative integer (including numeric strings). Lower values sort first;
|
|
75
|
+
use these tools to order pages and chapters within a book.
|
|
76
|
+
|
|
77
|
+
`create_page` and `update_page` also accept an optional `changelog` message
|
|
78
|
+
(1–180 characters), saved as the revision summary in the page's history. It
|
|
79
|
+
needs BookStack v26.09 or newer; older versions silently ignore it.
|
|
80
|
+
|
|
81
|
+
`get_page` accepts `format: "raw"` to return the page's stored editor HTML
|
|
82
|
+
(BookStack's `raw_html`). The `html` format is the rendered view readers see:
|
|
83
|
+
page includes are resolved and the content filter has run, so attributes such as
|
|
84
|
+
`rel`, `data-*` or legacy `width`/`align` may be gone.
|
|
85
|
+
|
|
86
|
+
When you edit a page, match the format to the page's `editor` field:
|
|
87
|
+
|
|
88
|
+
- **HTML (WYSIWYG) pages:** read `format: "raw"` and send the result back as
|
|
89
|
+
`update_page.html`. Starting from `html` saves the rendered output and drops
|
|
90
|
+
whatever rendering removed.
|
|
91
|
+
- **Markdown pages:** read `format: "markdown"` and send the result back as
|
|
92
|
+
`update_page.markdown`. For these pages `raw_html` is HTML generated from the
|
|
93
|
+
Markdown, and saving any `html` clears the stored Markdown source.
|
|
94
|
+
|
|
60
95
|
> **Security warning:** `BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=true` disables TLS certificate verification for outgoing requests to BookStack. Use only for self-signed certs on a trusted LAN — connections become vulnerable to MITM attacks. The server logs a `WARNING` line at startup whenever this is enabled.
|
|
61
96
|
|
|
62
97
|
## Client Configuration
|
|
@@ -130,6 +165,48 @@ mcpServers:
|
|
|
130
165
|
url: http://bookstack-mcp:8080/mcp
|
|
131
166
|
```
|
|
132
167
|
|
|
168
|
+
#### Per-user BookStack credentials
|
|
169
|
+
|
|
170
|
+
Set `BOOKSTACK_ALLOW_REQUEST_CREDENTIALS=true` on the HTTP server to accept
|
|
171
|
+
`X-Bookstack-Token-Id` and `X-Bookstack-Token-Secret` on each request. Both headers
|
|
172
|
+
must be supplied together; when both are absent, the server uses its environment
|
|
173
|
+
credentials. This is opt-in and does not change the write-tool or OAuth role gates.
|
|
174
|
+
Use a read-only environment token with limited visibility for the fallback.
|
|
175
|
+
Credential overrides apply to each request, including reused MCP sessions, and
|
|
176
|
+
their slug caches are private to that request. Send credentials over HTTPS or a
|
|
177
|
+
trusted internal connection and configure proxies to redact these headers.
|
|
178
|
+
|
|
179
|
+
```yaml
|
|
180
|
+
mcpServers:
|
|
181
|
+
bookstack:
|
|
182
|
+
type: streamable-http
|
|
183
|
+
url: http://bookstack-mcp:8080/mcp
|
|
184
|
+
headers:
|
|
185
|
+
X-Bookstack-Token-Id: "{{BOOKSTACK_TOKEN_ID}}"
|
|
186
|
+
X-Bookstack-Token-Secret: "{{BOOKSTACK_TOKEN_SECRET}}"
|
|
187
|
+
customUserVars:
|
|
188
|
+
BOOKSTACK_TOKEN_ID: { title: "BookStack token ID" }
|
|
189
|
+
BOOKSTACK_TOKEN_SECRET: { title: "BookStack token secret" }
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
#### Gallery images
|
|
193
|
+
|
|
194
|
+
`list_images` lists images with optional `uploaded_to`, `offset`, `count`, and
|
|
195
|
+
`sort` parameters. With write mode enabled, `create_image` accepts exactly one
|
|
196
|
+
absolute `file_path` or HTTP(S) `url`, a required existing page ID `uploaded_to`,
|
|
197
|
+
and an optional `name`. It uploads the binary data directly and returns BookStack's
|
|
198
|
+
hosted URL, thumbnails, and `content.html` / `content.markdown` snippets. PNG,
|
|
199
|
+
JPEG, GIF, WebP, and SVG sources up to 50 MB are supported; BookStack may impose
|
|
200
|
+
smaller limits. `delete_image` deletes an image and its thumbnails by `id`.
|
|
201
|
+
|
|
202
|
+
In stdio mode, files and HTTP(S) URLs are available to the trusted local client.
|
|
203
|
+
In HTTP mode, local files are disabled unless
|
|
204
|
+
`BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES=true`. URL sources require a comma-separated
|
|
205
|
+
`BOOKSTACK_IMAGE_ALLOWED_HOSTS` hostname allowlist, which also applies to every
|
|
206
|
+
redirect. For example, allow your image service with
|
|
207
|
+
`BOOKSTACK_IMAGE_ALLOWED_HOSTS=images.example.com`. Source downloads never use
|
|
208
|
+
the BookStack authorization token. Deleting an image can break existing page references.
|
|
209
|
+
|
|
133
210
|
> **3.0.0 breaking change:** the deprecated HTTP+SSE transport (`GET /sse` + `POST /messages`) has been removed. Streamable HTTP at `/mcp` already speaks SSE for streaming responses, and is the only HTTP transport in current MCP clients. If you're on an older client that needs the legacy endpoints, pin to `bookstack-mcp@2.x`.
|
|
134
211
|
|
|
135
212
|
#### HTTP transport environment variables
|
|
@@ -243,6 +320,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
243
320
|
| `get_chapters` / `get_chapter` | List or get chapter details |
|
|
244
321
|
| `get_shelves` / `get_shelf` | List or get shelf details |
|
|
245
322
|
| `get_attachments` / `get_attachment` | List or get attachment details |
|
|
323
|
+
| `list_images` | List gallery images, optionally filtered by page |
|
|
246
324
|
| `get_comments` / `get_comment` | List or get page comments (BookStack v25.11+) |
|
|
247
325
|
| `find_users` | Look up BookStack users by name, email, or slug to resolve user slugs for `{created_by:X}`-style search filters |
|
|
248
326
|
| `get_recycle_bin` | List items in the recycle bin |
|
|
@@ -262,6 +340,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
262
340
|
| `delete_page` | Delete a page (recoverable from recycle bin) |
|
|
263
341
|
| `create_shelf` / `update_shelf` / `delete_shelf` | Manage shelves |
|
|
264
342
|
| `create_attachment` / `update_attachment` / `delete_attachment` | Manage attachments |
|
|
343
|
+
| `create_image` / `delete_image` | Upload gallery images from files or URLs, or delete images |
|
|
265
344
|
| `create_comment` / `update_comment` / `delete_comment` | Manage page comments (v25.11+) |
|
|
266
345
|
| `restore_deleted` / `permanently_delete` | Restore or permanently destroy items in the recycle bin |
|
|
267
346
|
|
package/dist/bookstack-client.js
CHANGED
|
@@ -2,18 +2,9 @@ import axios from 'axios';
|
|
|
2
2
|
import https from 'https';
|
|
3
3
|
import { Semaphore } from './util/semaphore.js';
|
|
4
4
|
import { countWords } from './util/word-count.js';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
return null;
|
|
9
|
-
const seconds = Number(value);
|
|
10
|
-
if (Number.isFinite(seconds))
|
|
11
|
-
return Math.max(0, seconds * 1000);
|
|
12
|
-
const dateMs = Date.parse(value);
|
|
13
|
-
if (Number.isFinite(dateMs))
|
|
14
|
-
return Math.max(0, dateMs - Date.now());
|
|
15
|
-
return null;
|
|
16
|
-
}
|
|
5
|
+
import { rateLimitedAdapter } from './util/rate-limit.js';
|
|
6
|
+
import { MAX_IMAGE_BYTES, readImageSource } from './image-source.js';
|
|
7
|
+
import { PublicError, logSafeError, safeError } from './util/safe-errors.js';
|
|
17
8
|
// BookStack resolves {created_by:X}/{updated_by:X}/{owned_by:X} by user SLUG, with 'me'
|
|
18
9
|
// as a shortcut for the token's own user, and silently SKIPS the filter when X matches no
|
|
19
10
|
// user's slug — the query falls back to unfiltered results, which is a confusing footgun
|
|
@@ -25,7 +16,7 @@ function validateUserIdFilters(query) {
|
|
|
25
16
|
for (const match of query.matchAll(re)) {
|
|
26
17
|
const [, neg, field, value] = match;
|
|
27
18
|
if (/^\d+$/.test(value)) {
|
|
28
|
-
throw new
|
|
19
|
+
throw new PublicError(`Search filter {${neg}${field}:${value}} takes a user slug or 'me', not a numeric user ID — ` +
|
|
29
20
|
`BookStack resolves these filters by slug and silently returns unfiltered results for ` +
|
|
30
21
|
`unmatched values. Use the find_users tool to look up a user's slug by name or email.`);
|
|
31
22
|
}
|
|
@@ -68,9 +59,15 @@ export class BookStackClient {
|
|
|
68
59
|
client;
|
|
69
60
|
enableWrite;
|
|
70
61
|
baseUrl;
|
|
62
|
+
slugCache;
|
|
63
|
+
imageSourcePolicy;
|
|
71
64
|
constructor(config) {
|
|
72
65
|
this.enableWrite = config.enableWrite || false;
|
|
73
66
|
this.baseUrl = config.baseUrl;
|
|
67
|
+
this.imageSourcePolicy = config;
|
|
68
|
+
this.slugCache = config.privateSlugCache
|
|
69
|
+
? { cache: new Map(), inflight: new Map() }
|
|
70
|
+
: getSlugCacheEntry(config.baseUrl);
|
|
74
71
|
const limiter = getConcurrencyLimiter(config.baseUrl, config.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY);
|
|
75
72
|
const baseAdapter = axios.getAdapter(axios.defaults.adapter);
|
|
76
73
|
this.client = axios.create({
|
|
@@ -83,25 +80,11 @@ export class BookStackClient {
|
|
|
83
80
|
httpsAgent: config.insecureSkipTlsVerify
|
|
84
81
|
? new https.Agent({ rejectUnauthorized: false })
|
|
85
82
|
: undefined,
|
|
86
|
-
|
|
87
|
-
// this adapter exactly once per HTTP attempt. The retry's backoff sleep
|
|
88
|
-
// happens in the response interceptor (outside the adapter), so the
|
|
89
|
-
// permit is released between attempts, not held during the wait.
|
|
90
|
-
adapter: (requestConfig) => limiter.run(() => baseAdapter(requestConfig)),
|
|
83
|
+
adapter: rateLimitedAdapter(baseAdapter, limiter, config.retryTimeoutMs ?? 60000),
|
|
91
84
|
});
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
throw error;
|
|
96
|
-
cfg.__retry429 = (cfg.__retry429 ?? 0) + 1;
|
|
97
|
-
if (cfg.__retry429 > MAX_RETRIES_429)
|
|
98
|
-
throw error;
|
|
99
|
-
const retryAfter = parseRetryAfter(error.response.headers?.['retry-after']);
|
|
100
|
-
const backoff = Math.min(30000, 1000 * 2 ** (cfg.__retry429 - 1));
|
|
101
|
-
const delay = retryAfter ?? backoff;
|
|
102
|
-
console.error(`BookStack rate limited (429); retry ${cfg.__retry429}/${MAX_RETRIES_429} in ${delay}ms`);
|
|
103
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
104
|
-
return this.client.request(cfg);
|
|
85
|
+
// Do not let SDK error conversion or callers expose Axios config/bodies.
|
|
86
|
+
this.client.interceptors.response.use(undefined, error => {
|
|
87
|
+
throw safeError(error, 'BookStack request failed');
|
|
105
88
|
});
|
|
106
89
|
}
|
|
107
90
|
applyFilters(params, filter) {
|
|
@@ -125,7 +108,7 @@ export class BookStackClient {
|
|
|
125
108
|
* single in-flight warm. Failure is non-fatal: getBookSlug lazily fills gaps.
|
|
126
109
|
*/
|
|
127
110
|
async warmBookSlugCache() {
|
|
128
|
-
const entry =
|
|
111
|
+
const entry = this.slugCache;
|
|
129
112
|
// A completed warm is still fresh → nothing to do (lazy fetch covers gaps).
|
|
130
113
|
if (entry.warmedAt !== undefined && Date.now() - entry.warmedAt < SLUG_CACHE_TTL_MS) {
|
|
131
114
|
return;
|
|
@@ -167,7 +150,7 @@ export class BookStackClient {
|
|
|
167
150
|
// A single bulk warm turns the per-result N+1 into +1; after it, every book
|
|
168
151
|
// that existed at warm time is a cache hit — shared across all sessions.
|
|
169
152
|
await this.warmBookSlugCache();
|
|
170
|
-
const entry =
|
|
153
|
+
const entry = this.slugCache;
|
|
171
154
|
const cached = entry.cache.get(bookId);
|
|
172
155
|
if (cached !== undefined)
|
|
173
156
|
return cached;
|
|
@@ -226,9 +209,15 @@ export class BookStackClient {
|
|
|
226
209
|
}
|
|
227
210
|
async enhancePageResponse(page, options) {
|
|
228
211
|
const url = await this.generatePageUrl(page);
|
|
229
|
-
// Pick a single content format to return to avoid 3x duplication (html + markdown + text)
|
|
212
|
+
// Pick a single content format to return to avoid 3x duplication (html + markdown + text).
|
|
213
|
+
// 'raw' is the stored editor HTML; unlike 'html' it has not been through BookStack's
|
|
214
|
+
// render step, so it is the safe base for HTML written back with update_page.
|
|
215
|
+
// Markdown-authored pages should be edited through 'markdown' instead.
|
|
230
216
|
const format = options?.format ?? 'markdown';
|
|
231
|
-
const fullContent = (format === 'html' ? page.html
|
|
217
|
+
const fullContent = (format === 'html' ? page.html
|
|
218
|
+
: format === 'raw' ? page.raw_html
|
|
219
|
+
: format === 'text' ? page.text
|
|
220
|
+
: page.markdown) || '';
|
|
232
221
|
// Character-range slicing so very large pages can be paginated
|
|
233
222
|
const DEFAULT_LIMIT = 50000;
|
|
234
223
|
const offset = Math.max(0, options?.offset ?? 0);
|
|
@@ -413,7 +402,7 @@ export class BookStackClient {
|
|
|
413
402
|
}
|
|
414
403
|
}
|
|
415
404
|
catch (error) {
|
|
416
|
-
|
|
405
|
+
logSafeError(`Markdown export fallback failed for page ${id}`, error);
|
|
417
406
|
}
|
|
418
407
|
}
|
|
419
408
|
return await this.enhancePageResponse(pageData, options);
|
|
@@ -433,65 +422,105 @@ export class BookStackClient {
|
|
|
433
422
|
const response = await this.client.get(`/chapters/${id}`);
|
|
434
423
|
return await this.enhanceChapterResponse(response.data);
|
|
435
424
|
}
|
|
425
|
+
async listImages(options = {}) {
|
|
426
|
+
const params = { offset: options.offset ?? 0, count: Math.min(options.count ?? 50, 500) };
|
|
427
|
+
if (options.sort)
|
|
428
|
+
params.sort = options.sort;
|
|
429
|
+
if (options.uploaded_to !== undefined)
|
|
430
|
+
params['filter[uploaded_to]'] = options.uploaded_to;
|
|
431
|
+
return (await this.client.get('/image-gallery', { params })).data;
|
|
432
|
+
}
|
|
433
|
+
async createImage(data) {
|
|
434
|
+
if (!this.enableWrite)
|
|
435
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
436
|
+
if (!Number.isInteger(data.uploaded_to) || data.uploaded_to < 1)
|
|
437
|
+
throw new PublicError('uploaded_to must be a positive page ID.');
|
|
438
|
+
const source = await readImageSource({ ...data,
|
|
439
|
+
allowLocalFiles: this.imageSourcePolicy.allowLocalImageFiles,
|
|
440
|
+
allowedHosts: this.imageSourcePolicy.imageAllowedHosts
|
|
441
|
+
});
|
|
442
|
+
const form = new FormData();
|
|
443
|
+
form.set('type', 'gallery');
|
|
444
|
+
form.set('uploaded_to', String(data.uploaded_to));
|
|
445
|
+
if (data.name !== undefined)
|
|
446
|
+
form.set('name', data.name);
|
|
447
|
+
form.set('image', new Blob([new Uint8Array(source.bytes)], { type: source.type }), source.filename);
|
|
448
|
+
try {
|
|
449
|
+
// Removing the JSON default lets Axios set the multipart boundary. Using
|
|
450
|
+
// the existing client preserves token auth, TLS settings and retry limits.
|
|
451
|
+
return (await this.client.post('/image-gallery', form, {
|
|
452
|
+
headers: { 'Content-Type': undefined }, maxBodyLength: MAX_IMAGE_BYTES + 1024 * 1024
|
|
453
|
+
})).data;
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
throw safeError(error, 'BookStack image upload failed');
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
async deleteImage(id) {
|
|
460
|
+
if (!this.enableWrite)
|
|
461
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
462
|
+
await this.client.delete(`/image-gallery/${id}`);
|
|
463
|
+
return { deleted: true, id };
|
|
464
|
+
}
|
|
436
465
|
async createBook(data) {
|
|
437
466
|
if (!this.enableWrite) {
|
|
438
|
-
throw new
|
|
467
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
439
468
|
}
|
|
440
469
|
const response = await this.client.post('/books', data);
|
|
441
470
|
return this.enhanceBookResponse(response.data);
|
|
442
471
|
}
|
|
443
472
|
async createChapter(data) {
|
|
444
473
|
if (!this.enableWrite) {
|
|
445
|
-
throw new
|
|
474
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
446
475
|
}
|
|
447
476
|
const response = await this.client.post('/chapters', data);
|
|
448
477
|
return await this.enhanceChapterResponse(response.data);
|
|
449
478
|
}
|
|
450
479
|
async updateBook(id, data) {
|
|
451
480
|
if (!this.enableWrite) {
|
|
452
|
-
throw new
|
|
481
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
453
482
|
}
|
|
454
483
|
const response = await this.client.put(`/books/${id}`, data);
|
|
455
484
|
return this.enhanceBookResponse(response.data);
|
|
456
485
|
}
|
|
457
486
|
async updateChapter(id, data) {
|
|
458
487
|
if (!this.enableWrite) {
|
|
459
|
-
throw new
|
|
488
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
460
489
|
}
|
|
461
490
|
const response = await this.client.put(`/chapters/${id}`, data);
|
|
462
491
|
return await this.enhanceChapterResponse(response.data);
|
|
463
492
|
}
|
|
464
493
|
async createPage(data) {
|
|
465
494
|
if (!this.enableWrite) {
|
|
466
|
-
throw new
|
|
495
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
467
496
|
}
|
|
468
497
|
const response = await this.client.post('/pages', data);
|
|
469
498
|
return await this.enhancePageResponse(response.data);
|
|
470
499
|
}
|
|
471
500
|
async deleteBook(id) {
|
|
472
501
|
if (!this.enableWrite) {
|
|
473
|
-
throw new
|
|
502
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
474
503
|
}
|
|
475
504
|
const response = await this.client.delete(`/books/${id}`);
|
|
476
505
|
return response.data;
|
|
477
506
|
}
|
|
478
507
|
async deleteChapter(id) {
|
|
479
508
|
if (!this.enableWrite) {
|
|
480
|
-
throw new
|
|
509
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
481
510
|
}
|
|
482
511
|
const response = await this.client.delete(`/chapters/${id}`);
|
|
483
512
|
return response.data;
|
|
484
513
|
}
|
|
485
514
|
async deletePage(id) {
|
|
486
515
|
if (!this.enableWrite) {
|
|
487
|
-
throw new
|
|
516
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
488
517
|
}
|
|
489
518
|
const response = await this.client.delete(`/pages/${id}`);
|
|
490
519
|
return response.data;
|
|
491
520
|
}
|
|
492
521
|
async updatePage(id, data) {
|
|
493
522
|
if (!this.enableWrite) {
|
|
494
|
-
throw new
|
|
523
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
495
524
|
}
|
|
496
525
|
const response = await this.client.put(`/pages/${id}`, data);
|
|
497
526
|
return await this.enhancePageResponse(response.data);
|
|
@@ -527,15 +556,15 @@ export class BookStackClient {
|
|
|
527
556
|
console.error(`Export response status: ${response.status}`);
|
|
528
557
|
// For text formats, validate and return as string
|
|
529
558
|
if (!response.data) {
|
|
530
|
-
throw new
|
|
559
|
+
throw new PublicError(`Empty ${format} content returned from BookStack API`);
|
|
531
560
|
}
|
|
532
561
|
console.error(`Text export length: ${response.data.length} characters`);
|
|
533
562
|
return response.data;
|
|
534
563
|
}
|
|
535
564
|
}
|
|
536
565
|
catch (error) {
|
|
537
|
-
|
|
538
|
-
throw
|
|
566
|
+
logSafeError(`Export error for page ${id}`, error);
|
|
567
|
+
throw safeError(error, `Failed to export page ${id} as ${format}`);
|
|
539
568
|
}
|
|
540
569
|
}
|
|
541
570
|
async exportBook(id, format) {
|
|
@@ -659,21 +688,21 @@ export class BookStackClient {
|
|
|
659
688
|
}
|
|
660
689
|
async createShelf(data) {
|
|
661
690
|
if (!this.enableWrite) {
|
|
662
|
-
throw new
|
|
691
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
663
692
|
}
|
|
664
693
|
const response = await this.client.post('/shelves', data);
|
|
665
694
|
return this.enhanceShelfResponse(response.data);
|
|
666
695
|
}
|
|
667
696
|
async updateShelf(id, data) {
|
|
668
697
|
if (!this.enableWrite) {
|
|
669
|
-
throw new
|
|
698
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
670
699
|
}
|
|
671
700
|
const response = await this.client.put(`/shelves/${id}`, data);
|
|
672
701
|
return this.enhanceShelfResponse(response.data);
|
|
673
702
|
}
|
|
674
703
|
async deleteShelf(id) {
|
|
675
704
|
if (!this.enableWrite) {
|
|
676
|
-
throw new
|
|
705
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
677
706
|
}
|
|
678
707
|
const response = await this.client.delete(`/shelves/${id}`);
|
|
679
708
|
return response.data;
|
|
@@ -707,7 +736,7 @@ export class BookStackClient {
|
|
|
707
736
|
}
|
|
708
737
|
async createAttachment(data) {
|
|
709
738
|
if (!this.enableWrite) {
|
|
710
|
-
throw new
|
|
739
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
711
740
|
}
|
|
712
741
|
const response = await this.client.post('/attachments', data);
|
|
713
742
|
const attachment = response.data;
|
|
@@ -718,7 +747,7 @@ export class BookStackClient {
|
|
|
718
747
|
}
|
|
719
748
|
async updateAttachment(id, data) {
|
|
720
749
|
if (!this.enableWrite) {
|
|
721
|
-
throw new
|
|
750
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
722
751
|
}
|
|
723
752
|
const response = await this.client.put(`/attachments/${id}`, data);
|
|
724
753
|
const attachment = response.data;
|
|
@@ -729,7 +758,7 @@ export class BookStackClient {
|
|
|
729
758
|
}
|
|
730
759
|
async deleteAttachment(id) {
|
|
731
760
|
if (!this.enableWrite) {
|
|
732
|
-
throw new
|
|
761
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
733
762
|
}
|
|
734
763
|
const response = await this.client.delete(`/attachments/${id}`);
|
|
735
764
|
return response.data;
|
|
@@ -753,21 +782,21 @@ export class BookStackClient {
|
|
|
753
782
|
}
|
|
754
783
|
async createComment(data) {
|
|
755
784
|
if (!this.enableWrite) {
|
|
756
|
-
throw new
|
|
785
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
757
786
|
}
|
|
758
787
|
const response = await this.client.post('/comments', data);
|
|
759
788
|
return response.data;
|
|
760
789
|
}
|
|
761
790
|
async updateComment(id, data) {
|
|
762
791
|
if (!this.enableWrite) {
|
|
763
|
-
throw new
|
|
792
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
764
793
|
}
|
|
765
794
|
const response = await this.client.put(`/comments/${id}`, data);
|
|
766
795
|
return response.data;
|
|
767
796
|
}
|
|
768
797
|
async deleteComment(id) {
|
|
769
798
|
if (!this.enableWrite) {
|
|
770
|
-
throw new
|
|
799
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
771
800
|
}
|
|
772
801
|
const response = await this.client.delete(`/comments/${id}`);
|
|
773
802
|
return response.data;
|
|
@@ -785,14 +814,14 @@ export class BookStackClient {
|
|
|
785
814
|
}
|
|
786
815
|
async restoreFromRecycleBin(deletionId) {
|
|
787
816
|
if (!this.enableWrite) {
|
|
788
|
-
throw new
|
|
817
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
789
818
|
}
|
|
790
819
|
const response = await this.client.put(`/recycle-bin/${deletionId}`);
|
|
791
820
|
return response.data;
|
|
792
821
|
}
|
|
793
822
|
async destroyFromRecycleBin(deletionId) {
|
|
794
823
|
if (!this.enableWrite) {
|
|
795
|
-
throw new
|
|
824
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
796
825
|
}
|
|
797
826
|
const response = await this.client.delete(`/recycle-bin/${deletionId}`);
|
|
798
827
|
return response.data;
|