bookstack-mcp 5.4.0 → 5.5.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 +68 -1
- package/dist/bookstack-client.js +80 -57
- package/dist/image-source.js +85 -0
- package/dist/index.js +101 -25
- package/dist/oauth/entra-proxy.js +22 -7
- 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,9 +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
|
+
|
|
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.
|
|
24
|
+
|
|
18
25
|
## Features
|
|
19
26
|
|
|
20
|
-
-
|
|
27
|
+
- 21 read-only tools + 22 write tools for BookStack API access
|
|
21
28
|
- Books, chapters, pages, shelves, attachments, and comments — full CRUD
|
|
22
29
|
- Recycle bin support — restore or permanently delete soft-deleted content
|
|
23
30
|
- Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
|
|
@@ -53,8 +60,24 @@ BOOKSTACK_TOKEN_ID=your-token-id # Required
|
|
|
53
60
|
BOOKSTACK_TOKEN_SECRET=your-token-secret # Required
|
|
54
61
|
BOOKSTACK_ENABLE_WRITE=false # Optional, default false
|
|
55
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
|
|
56
65
|
```
|
|
57
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
|
+
|
|
58
81
|
> **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.
|
|
59
82
|
|
|
60
83
|
## Client Configuration
|
|
@@ -128,6 +151,48 @@ mcpServers:
|
|
|
128
151
|
url: http://bookstack-mcp:8080/mcp
|
|
129
152
|
```
|
|
130
153
|
|
|
154
|
+
#### Per-user BookStack credentials
|
|
155
|
+
|
|
156
|
+
Set `BOOKSTACK_ALLOW_REQUEST_CREDENTIALS=true` on the HTTP server to accept
|
|
157
|
+
`X-Bookstack-Token-Id` and `X-Bookstack-Token-Secret` on each request. Both headers
|
|
158
|
+
must be supplied together; when both are absent, the server uses its environment
|
|
159
|
+
credentials. This is opt-in and does not change the write-tool or OAuth role gates.
|
|
160
|
+
Use a read-only environment token with limited visibility for the fallback.
|
|
161
|
+
Credential overrides apply to each request, including reused MCP sessions, and
|
|
162
|
+
their slug caches are private to that request. Send credentials over HTTPS or a
|
|
163
|
+
trusted internal connection and configure proxies to redact these headers.
|
|
164
|
+
|
|
165
|
+
```yaml
|
|
166
|
+
mcpServers:
|
|
167
|
+
bookstack:
|
|
168
|
+
type: streamable-http
|
|
169
|
+
url: http://bookstack-mcp:8080/mcp
|
|
170
|
+
headers:
|
|
171
|
+
X-Bookstack-Token-Id: "{{BOOKSTACK_TOKEN_ID}}"
|
|
172
|
+
X-Bookstack-Token-Secret: "{{BOOKSTACK_TOKEN_SECRET}}"
|
|
173
|
+
customUserVars:
|
|
174
|
+
BOOKSTACK_TOKEN_ID: { title: "BookStack token ID" }
|
|
175
|
+
BOOKSTACK_TOKEN_SECRET: { title: "BookStack token secret" }
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
#### Gallery images
|
|
179
|
+
|
|
180
|
+
`list_images` lists images with optional `uploaded_to`, `offset`, `count`, and
|
|
181
|
+
`sort` parameters. With write mode enabled, `create_image` accepts exactly one
|
|
182
|
+
absolute `file_path` or HTTP(S) `url`, a required existing page ID `uploaded_to`,
|
|
183
|
+
and an optional `name`. It uploads the binary data directly and returns BookStack's
|
|
184
|
+
hosted URL, thumbnails, and `content.html` / `content.markdown` snippets. PNG,
|
|
185
|
+
JPEG, GIF, WebP, and SVG sources up to 50 MB are supported; BookStack may impose
|
|
186
|
+
smaller limits. `delete_image` deletes an image and its thumbnails by `id`.
|
|
187
|
+
|
|
188
|
+
In stdio mode, files and HTTP(S) URLs are available to the trusted local client.
|
|
189
|
+
In HTTP mode, local files are disabled unless
|
|
190
|
+
`BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES=true`. URL sources require a comma-separated
|
|
191
|
+
`BOOKSTACK_IMAGE_ALLOWED_HOSTS` hostname allowlist, which also applies to every
|
|
192
|
+
redirect. For example, allow your image service with
|
|
193
|
+
`BOOKSTACK_IMAGE_ALLOWED_HOSTS=images.example.com`. Source downloads never use
|
|
194
|
+
the BookStack authorization token. Deleting an image can break existing page references.
|
|
195
|
+
|
|
131
196
|
> **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`.
|
|
132
197
|
|
|
133
198
|
#### HTTP transport environment variables
|
|
@@ -241,6 +306,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
241
306
|
| `get_chapters` / `get_chapter` | List or get chapter details |
|
|
242
307
|
| `get_shelves` / `get_shelf` | List or get shelf details |
|
|
243
308
|
| `get_attachments` / `get_attachment` | List or get attachment details |
|
|
309
|
+
| `list_images` | List gallery images, optionally filtered by page |
|
|
244
310
|
| `get_comments` / `get_comment` | List or get page comments (BookStack v25.11+) |
|
|
245
311
|
| `find_users` | Look up BookStack users by name, email, or slug to resolve user slugs for `{created_by:X}`-style search filters |
|
|
246
312
|
| `get_recycle_bin` | List items in the recycle bin |
|
|
@@ -260,6 +326,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
260
326
|
| `delete_page` | Delete a page (recoverable from recycle bin) |
|
|
261
327
|
| `create_shelf` / `update_shelf` / `delete_shelf` | Manage shelves |
|
|
262
328
|
| `create_attachment` / `update_attachment` / `delete_attachment` | Manage attachments |
|
|
329
|
+
| `create_image` / `delete_image` | Upload gallery images from files or URLs, or delete images |
|
|
263
330
|
| `create_comment` / `update_comment` / `delete_comment` | Manage page comments (v25.11+) |
|
|
264
331
|
| `restore_deleted` / `permanently_delete` | Restore or permanently destroy items in the recycle bin |
|
|
265
332
|
|
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;
|
|
@@ -413,7 +396,7 @@ export class BookStackClient {
|
|
|
413
396
|
}
|
|
414
397
|
}
|
|
415
398
|
catch (error) {
|
|
416
|
-
|
|
399
|
+
logSafeError(`Markdown export fallback failed for page ${id}`, error);
|
|
417
400
|
}
|
|
418
401
|
}
|
|
419
402
|
return await this.enhancePageResponse(pageData, options);
|
|
@@ -433,65 +416,105 @@ export class BookStackClient {
|
|
|
433
416
|
const response = await this.client.get(`/chapters/${id}`);
|
|
434
417
|
return await this.enhanceChapterResponse(response.data);
|
|
435
418
|
}
|
|
419
|
+
async listImages(options = {}) {
|
|
420
|
+
const params = { offset: options.offset ?? 0, count: Math.min(options.count ?? 50, 500) };
|
|
421
|
+
if (options.sort)
|
|
422
|
+
params.sort = options.sort;
|
|
423
|
+
if (options.uploaded_to !== undefined)
|
|
424
|
+
params['filter[uploaded_to]'] = options.uploaded_to;
|
|
425
|
+
return (await this.client.get('/image-gallery', { params })).data;
|
|
426
|
+
}
|
|
427
|
+
async createImage(data) {
|
|
428
|
+
if (!this.enableWrite)
|
|
429
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
430
|
+
if (!Number.isInteger(data.uploaded_to) || data.uploaded_to < 1)
|
|
431
|
+
throw new PublicError('uploaded_to must be a positive page ID.');
|
|
432
|
+
const source = await readImageSource({ ...data,
|
|
433
|
+
allowLocalFiles: this.imageSourcePolicy.allowLocalImageFiles,
|
|
434
|
+
allowedHosts: this.imageSourcePolicy.imageAllowedHosts
|
|
435
|
+
});
|
|
436
|
+
const form = new FormData();
|
|
437
|
+
form.set('type', 'gallery');
|
|
438
|
+
form.set('uploaded_to', String(data.uploaded_to));
|
|
439
|
+
if (data.name !== undefined)
|
|
440
|
+
form.set('name', data.name);
|
|
441
|
+
form.set('image', new Blob([new Uint8Array(source.bytes)], { type: source.type }), source.filename);
|
|
442
|
+
try {
|
|
443
|
+
// Removing the JSON default lets Axios set the multipart boundary. Using
|
|
444
|
+
// the existing client preserves token auth, TLS settings and retry limits.
|
|
445
|
+
return (await this.client.post('/image-gallery', form, {
|
|
446
|
+
headers: { 'Content-Type': undefined }, maxBodyLength: MAX_IMAGE_BYTES + 1024 * 1024
|
|
447
|
+
})).data;
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
throw safeError(error, 'BookStack image upload failed');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
async deleteImage(id) {
|
|
454
|
+
if (!this.enableWrite)
|
|
455
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
456
|
+
await this.client.delete(`/image-gallery/${id}`);
|
|
457
|
+
return { deleted: true, id };
|
|
458
|
+
}
|
|
436
459
|
async createBook(data) {
|
|
437
460
|
if (!this.enableWrite) {
|
|
438
|
-
throw new
|
|
461
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
439
462
|
}
|
|
440
463
|
const response = await this.client.post('/books', data);
|
|
441
464
|
return this.enhanceBookResponse(response.data);
|
|
442
465
|
}
|
|
443
466
|
async createChapter(data) {
|
|
444
467
|
if (!this.enableWrite) {
|
|
445
|
-
throw new
|
|
468
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
446
469
|
}
|
|
447
470
|
const response = await this.client.post('/chapters', data);
|
|
448
471
|
return await this.enhanceChapterResponse(response.data);
|
|
449
472
|
}
|
|
450
473
|
async updateBook(id, data) {
|
|
451
474
|
if (!this.enableWrite) {
|
|
452
|
-
throw new
|
|
475
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
453
476
|
}
|
|
454
477
|
const response = await this.client.put(`/books/${id}`, data);
|
|
455
478
|
return this.enhanceBookResponse(response.data);
|
|
456
479
|
}
|
|
457
480
|
async updateChapter(id, data) {
|
|
458
481
|
if (!this.enableWrite) {
|
|
459
|
-
throw new
|
|
482
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
460
483
|
}
|
|
461
484
|
const response = await this.client.put(`/chapters/${id}`, data);
|
|
462
485
|
return await this.enhanceChapterResponse(response.data);
|
|
463
486
|
}
|
|
464
487
|
async createPage(data) {
|
|
465
488
|
if (!this.enableWrite) {
|
|
466
|
-
throw new
|
|
489
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
467
490
|
}
|
|
468
491
|
const response = await this.client.post('/pages', data);
|
|
469
492
|
return await this.enhancePageResponse(response.data);
|
|
470
493
|
}
|
|
471
494
|
async deleteBook(id) {
|
|
472
495
|
if (!this.enableWrite) {
|
|
473
|
-
throw new
|
|
496
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
474
497
|
}
|
|
475
498
|
const response = await this.client.delete(`/books/${id}`);
|
|
476
499
|
return response.data;
|
|
477
500
|
}
|
|
478
501
|
async deleteChapter(id) {
|
|
479
502
|
if (!this.enableWrite) {
|
|
480
|
-
throw new
|
|
503
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
481
504
|
}
|
|
482
505
|
const response = await this.client.delete(`/chapters/${id}`);
|
|
483
506
|
return response.data;
|
|
484
507
|
}
|
|
485
508
|
async deletePage(id) {
|
|
486
509
|
if (!this.enableWrite) {
|
|
487
|
-
throw new
|
|
510
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
488
511
|
}
|
|
489
512
|
const response = await this.client.delete(`/pages/${id}`);
|
|
490
513
|
return response.data;
|
|
491
514
|
}
|
|
492
515
|
async updatePage(id, data) {
|
|
493
516
|
if (!this.enableWrite) {
|
|
494
|
-
throw new
|
|
517
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
495
518
|
}
|
|
496
519
|
const response = await this.client.put(`/pages/${id}`, data);
|
|
497
520
|
return await this.enhancePageResponse(response.data);
|
|
@@ -527,15 +550,15 @@ export class BookStackClient {
|
|
|
527
550
|
console.error(`Export response status: ${response.status}`);
|
|
528
551
|
// For text formats, validate and return as string
|
|
529
552
|
if (!response.data) {
|
|
530
|
-
throw new
|
|
553
|
+
throw new PublicError(`Empty ${format} content returned from BookStack API`);
|
|
531
554
|
}
|
|
532
555
|
console.error(`Text export length: ${response.data.length} characters`);
|
|
533
556
|
return response.data;
|
|
534
557
|
}
|
|
535
558
|
}
|
|
536
559
|
catch (error) {
|
|
537
|
-
|
|
538
|
-
throw
|
|
560
|
+
logSafeError(`Export error for page ${id}`, error);
|
|
561
|
+
throw safeError(error, `Failed to export page ${id} as ${format}`);
|
|
539
562
|
}
|
|
540
563
|
}
|
|
541
564
|
async exportBook(id, format) {
|
|
@@ -659,21 +682,21 @@ export class BookStackClient {
|
|
|
659
682
|
}
|
|
660
683
|
async createShelf(data) {
|
|
661
684
|
if (!this.enableWrite) {
|
|
662
|
-
throw new
|
|
685
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
663
686
|
}
|
|
664
687
|
const response = await this.client.post('/shelves', data);
|
|
665
688
|
return this.enhanceShelfResponse(response.data);
|
|
666
689
|
}
|
|
667
690
|
async updateShelf(id, data) {
|
|
668
691
|
if (!this.enableWrite) {
|
|
669
|
-
throw new
|
|
692
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
670
693
|
}
|
|
671
694
|
const response = await this.client.put(`/shelves/${id}`, data);
|
|
672
695
|
return this.enhanceShelfResponse(response.data);
|
|
673
696
|
}
|
|
674
697
|
async deleteShelf(id) {
|
|
675
698
|
if (!this.enableWrite) {
|
|
676
|
-
throw new
|
|
699
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
677
700
|
}
|
|
678
701
|
const response = await this.client.delete(`/shelves/${id}`);
|
|
679
702
|
return response.data;
|
|
@@ -707,7 +730,7 @@ export class BookStackClient {
|
|
|
707
730
|
}
|
|
708
731
|
async createAttachment(data) {
|
|
709
732
|
if (!this.enableWrite) {
|
|
710
|
-
throw new
|
|
733
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
711
734
|
}
|
|
712
735
|
const response = await this.client.post('/attachments', data);
|
|
713
736
|
const attachment = response.data;
|
|
@@ -718,7 +741,7 @@ export class BookStackClient {
|
|
|
718
741
|
}
|
|
719
742
|
async updateAttachment(id, data) {
|
|
720
743
|
if (!this.enableWrite) {
|
|
721
|
-
throw new
|
|
744
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
722
745
|
}
|
|
723
746
|
const response = await this.client.put(`/attachments/${id}`, data);
|
|
724
747
|
const attachment = response.data;
|
|
@@ -729,7 +752,7 @@ export class BookStackClient {
|
|
|
729
752
|
}
|
|
730
753
|
async deleteAttachment(id) {
|
|
731
754
|
if (!this.enableWrite) {
|
|
732
|
-
throw new
|
|
755
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
733
756
|
}
|
|
734
757
|
const response = await this.client.delete(`/attachments/${id}`);
|
|
735
758
|
return response.data;
|
|
@@ -753,21 +776,21 @@ export class BookStackClient {
|
|
|
753
776
|
}
|
|
754
777
|
async createComment(data) {
|
|
755
778
|
if (!this.enableWrite) {
|
|
756
|
-
throw new
|
|
779
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
757
780
|
}
|
|
758
781
|
const response = await this.client.post('/comments', data);
|
|
759
782
|
return response.data;
|
|
760
783
|
}
|
|
761
784
|
async updateComment(id, data) {
|
|
762
785
|
if (!this.enableWrite) {
|
|
763
|
-
throw new
|
|
786
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
764
787
|
}
|
|
765
788
|
const response = await this.client.put(`/comments/${id}`, data);
|
|
766
789
|
return response.data;
|
|
767
790
|
}
|
|
768
791
|
async deleteComment(id) {
|
|
769
792
|
if (!this.enableWrite) {
|
|
770
|
-
throw new
|
|
793
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
771
794
|
}
|
|
772
795
|
const response = await this.client.delete(`/comments/${id}`);
|
|
773
796
|
return response.data;
|
|
@@ -785,14 +808,14 @@ export class BookStackClient {
|
|
|
785
808
|
}
|
|
786
809
|
async restoreFromRecycleBin(deletionId) {
|
|
787
810
|
if (!this.enableWrite) {
|
|
788
|
-
throw new
|
|
811
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
789
812
|
}
|
|
790
813
|
const response = await this.client.put(`/recycle-bin/${deletionId}`);
|
|
791
814
|
return response.data;
|
|
792
815
|
}
|
|
793
816
|
async destroyFromRecycleBin(deletionId) {
|
|
794
817
|
if (!this.enableWrite) {
|
|
795
|
-
throw new
|
|
818
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
796
819
|
}
|
|
797
820
|
const response = await this.client.delete(`/recycle-bin/${deletionId}`);
|
|
798
821
|
return response.data;
|