roam-research-mcp 5.0.2 → 5.1.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/README.md CHANGED
@@ -307,7 +307,7 @@ ROAM_SYSTEM_WRITE_KEY=your-secret-key
307
307
  | `protected` | No | If `true`, writes require `ROAM_SYSTEM_WRITE_KEY` confirmation — **except on the default graph**, see below |
308
308
  | `memoriesTag` | No | Tag for `roam_remember`/`roam_recall` (overrides global default) |
309
309
 
310
- **Two kinds of access control (and how they differ)**
310
+ <a id="two-kinds-of-access-control-and-how-they-differ"></a>**Two kinds of access control (and how they differ)**
311
311
 
312
312
  The server has two independent locks. They're easy to mix up because both are "keys" — here's the plain version (both are **optional and off by default**):
313
313
 
@@ -320,7 +320,7 @@ The server has two independent locks. They're easy to mix up because both are "k
320
320
  | When you need it | Only if the server is reachable beyond your own machine (e.g. `-H 0.0.0.0`) | Whenever you want a guard against accidental edits to important graphs |
321
321
  | How it's sent | HTTP header: `Authorization: Bearer <token>` | A `write_key` argument on write tools / CLI commands |
322
322
 
323
- Think of a house: the **bearer token locks the front door** (keeps strangers out entirely), and the **write key locks a safe inside** (even someone already in the house needs it to change what's in the safe). On your own machine bound to `127.0.0.1`, the front door faces a wall — you don't need the bearer token there. The write key is still handy locally as an "are you sure?" guard, because **Roam has no undo**.
323
+ Think of a house: the **bearer token locks the front door** (keeps strangers out entirely), and the **write key locks a safe inside** (even someone already in the house needs it to change what's in the safe). On your own machine bound to `127.0.0.1`, the front door faces a wall, and a server without a token also turns away web pages that try to reach it by DNS rebinding (see `HTTP_ALLOWED_HOSTS` below), so you don't need the bearer token there. The write key is still handy locally as an "are you sure?" guard, because **Roam has no undo**.
324
324
 
325
325
  So: to mark a graph as needing the write key, set `protected: true` on it and configure `ROAM_SYSTEM_WRITE_KEY`; callers then pass a matching `write_key` for any write to that graph.
326
326
 
@@ -330,7 +330,9 @@ So: to mark a graph as needing the write key, set `protected: true` on it and co
330
330
  - `ROAM_MEMORIES_TAG`: Default tag for `roam_remember`/`roam_recall` (fallback when per-graph `memoriesTag` not set).
331
331
  - `HTTP_STREAM_PORT`: Port for the HTTP Stream transport (defaults to 8088). **`--server` mode only** — stdio mode opens no socket, so this is ignored there.
332
332
  - `HTTP_STREAM_HOST`: Host to bind the HTTP transport to (defaults to `127.0.0.1`, loopback-only). **`--server` mode only.** Set to `0.0.0.0` to expose on the LAN, and set `HTTP_AUTH_TOKEN` when you do.
333
- - `HTTP_AUTH_TOKEN`: Optional bearer token that locks the **whole** HTTP endpoint. Unset = open (fine for loopback). When set, every MCP request must send `Authorization: Bearer <token>` (`GET /health` stays open). Use it whenever you bind beyond `127.0.0.1`. Different from `ROAM_SYSTEM_WRITE_KEY` — see [Two kinds of access control](#two-kinds-of-access-control-and-how-they-differ).
333
+ - `HTTP_AUTH_TOKEN`: Optional bearer token that locks the **whole** HTTP endpoint. Unset = no token: the server then answers only requests addressed to `localhost`, an IP address, or a name in `HTTP_ALLOWED_HOSTS`, and only browser requests from an origin in `CORS_ORIGIN`. When set, every MCP request must send `Authorization: Bearer <token>` (`GET /health` stays open). Use it whenever you bind beyond `127.0.0.1`. Different from `ROAM_SYSTEM_WRITE_KEY` — see [Two kinds of access control](#two-kinds-of-access-control-and-how-they-differ).
334
+ - `HTTP_ALLOWED_HOSTS`: Hostnames a server **without** `HTTP_AUTH_TOKEN` answers to, beyond `localhost` and IP addresses (comma-separated; ports are ignored), e.g. `roam-mcp` for a Docker service name or `mybox.local`. A request addressed to any other name gets a 403. That is what stops a web page from reaching the server by pointing its own hostname at `127.0.0.1` (DNS rebinding). Ignored when `HTTP_AUTH_TOKEN` is set.
335
+ - `CORS_ORIGIN`: Browser origins allowed to call the HTTP server (comma-separated; defaults to `http://localhost:5678,https://roamresearch.com`; `*` allows any). Without `HTTP_AUTH_TOKEN`, a request from any other origin gets a 403.
334
336
 
335
337
  ### Running the Server
336
338
 
@@ -382,7 +384,7 @@ Point MCP clients at it with an HTTP transport config:
382
384
 
383
385
  Env vars (tokens, graphs) live with the **server** process, not the client config.
384
386
 
385
- **Securing an exposed server (two layers):**
387
+ <a id="securing-an-exposed-server-two-layers"></a>**Securing an exposed server (two layers):**
386
388
  If you bind beyond loopback (`-H 0.0.0.0`), add the perimeter lock:
387
389
 
388
390
  ```bash
@@ -418,9 +420,16 @@ curl -s http://127.0.0.1:8088/health # verify
418
420
  **3. Docker**
419
421
 
420
422
  ```bash
421
- docker run -p 8088:8088 --env-file .env roam-research-mcp --server
423
+ docker build -t roam-research-mcp .
424
+ docker run --init -p 127.0.0.1:8088:8088 \
425
+ -e HTTP_STREAM_HOST=0.0.0.0 -e HTTP_STREAM_PORT=8088 \
426
+ --env-file .env roam-research-mcp --server
422
427
  ```
423
428
 
429
+ Set `HTTP_AUTH_TOKEN` to a random secret in `.env` before running; MCP requests must include `Authorization: Bearer <token>`. The published port is loopback-only by default. For remote access, follow [Securing an exposed server](#securing-an-exposed-server-two-layers) and intentionally publish on the required host address.
430
+
431
+ The `-e` values win over `--env-file`, so the server listens on the published port whatever `.env` says. `--init` lets `docker stop` end the server straight away instead of killing it after 10 seconds.
432
+
424
433
  ### Configuring in LLMs
425
434
 
426
435
  **Claude Desktop / Cline:**
@@ -1,6 +1,7 @@
1
1
  import * as dotenv from 'dotenv';
2
2
  import { dirname, join } from 'path';
3
3
  import { existsSync } from 'fs';
4
+ import { hostnameOf } from '../utils/host-validation.js';
4
5
  // Get the project root from the script path
5
6
  const scriptPath = process.argv[1]; // Full path to the running script
6
7
  const projectRoot = dirname(dirname(scriptPath)); // Go up two levels from build/index.js
@@ -16,12 +17,20 @@ const HTTP_STREAM_PORT = process.env.HTTP_STREAM_PORT || '8088';
16
17
  const HTTP_STREAM_HOST = process.env.HTTP_STREAM_HOST || '127.0.0.1';
17
18
  // Optional transport-level bearer token (authentication). When set, every HTTP
18
19
  // MCP request must send `Authorization: Bearer <token>` (the /health probe stays
19
- // open). Unset = open, i.e. unchanged. This is the perimeter lock; it is separate
20
+ // open). Unset = no token, and the server refuses DNS-rebinding requests instead
21
+ // (see utils/host-validation.ts). This is the perimeter lock; it is separate
20
22
  // from ROAM_SYSTEM_WRITE_KEY, which is per-graph write authorization.
21
23
  const HTTP_AUTH_TOKEN = process.env.HTTP_AUTH_TOKEN;
22
24
  const CORS_ORIGINS = (process.env.CORS_ORIGIN || 'http://localhost:5678,https://roamresearch.com')
23
25
  .split(',')
24
26
  .map(origin => origin.trim());
27
+ // Hostnames, beyond `localhost` and IP addresses, that a server without a token
28
+ // answers to (comma-separated, ports ignored), e.g. a Docker service name.
29
+ // Ignored when HTTP_AUTH_TOKEN is set.
30
+ const HTTP_ALLOWED_HOSTS = (process.env.HTTP_ALLOWED_HOSTS || '')
31
+ .split(',')
32
+ .map(host => hostnameOf(host))
33
+ .filter(Boolean);
25
34
  // Re-export for backwards compatibility with single-graph mode
26
35
  // These are still used by CLI commands and for validation
27
36
  const API_TOKEN = process.env.ROAM_API_TOKEN;
@@ -89,4 +98,4 @@ export function validateEnvironment() {
89
98
  }
90
99
  }
91
100
  }
92
- export { API_TOKEN, GRAPH_NAME, HTTP_STREAM_PORT, HTTP_STREAM_HOST, HTTP_AUTH_TOKEN, CORS_ORIGINS, ROAM_GRAPHS, ROAM_DEFAULT_GRAPH };
101
+ export { API_TOKEN, GRAPH_NAME, HTTP_STREAM_PORT, HTTP_STREAM_HOST, HTTP_AUTH_TOKEN, CORS_ORIGINS, HTTP_ALLOWED_HOSTS, ROAM_GRAPHS, ROAM_DEFAULT_GRAPH };
@@ -4,6 +4,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
4
4
  import { CallToolRequestSchema, ErrorCode, ListResourcesRequestSchema, ReadResourceRequestSchema, McpError, ListToolsRequestSchema, ListPromptsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
5
  import { HTTP_STREAM_PORT, HTTP_STREAM_HOST, HTTP_AUTH_TOKEN, validateEnvironment } from '../config/environment.js';
6
6
  import { isBearerAuthorized } from '../utils/auth.js';
7
+ import { rebindingRefusal } from '../utils/host-validation.js';
7
8
  import { RoamError, toErrorResult } from '../shared/errors.js';
8
9
  import { createRegistryFromEnv } from '../config/graph-registry.js';
9
10
  import { toolSchemas } from '../tools/schemas.js';
@@ -13,7 +14,7 @@ import { join, dirname } from 'node:path';
13
14
  import { createServer } from 'node:http';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  import { isPortInUse } from '../utils/net.js';
16
- import { CORS_ORIGINS } from '../config/environment.js';
17
+ import { CORS_ORIGINS, HTTP_ALLOWED_HOSTS } from '../config/environment.js';
17
18
  const __filename = fileURLToPath(import.meta.url);
18
19
  const __dirname = dirname(__filename);
19
20
  // Read package.json to get the version
@@ -334,6 +335,21 @@ export class RoamServer {
334
335
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID');
335
336
  res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
336
337
  res.setHeader('Access-Control-Allow-Credentials', 'true');
338
+ // Without a token, refuse what a DNS-rebinding web page sends: a Host
339
+ // this server doesn't answer to, or an Origin CORS_ORIGIN doesn't allow.
340
+ // Checked before /health, which lists the graph names.
341
+ if (!HTTP_AUTH_TOKEN) {
342
+ const refusal = rebindingRefusal(req, HTTP_ALLOWED_HOSTS, CORS_ORIGINS);
343
+ if (refusal) {
344
+ res.writeHead(403, { 'Content-Type': 'application/json' });
345
+ res.end(JSON.stringify({
346
+ jsonrpc: '2.0',
347
+ error: { code: -32001, message: `Forbidden: ${refusal}` },
348
+ id: null,
349
+ }));
350
+ return;
351
+ }
352
+ }
337
353
  // Handle preflight OPTIONS requests
338
354
  if (req.method === 'OPTIONS') {
339
355
  res.writeHead(204); // No Content
@@ -0,0 +1,56 @@
1
+ import { isIP } from 'node:net';
2
+ /**
3
+ * DNS-rebinding checks for an HTTP server running WITHOUT a bearer token.
4
+ *
5
+ * A web page can point its own hostname at 127.0.0.1 after it loads. The
6
+ * browser then treats this server as same-origin, so CORS never applies and
7
+ * the page can call every tool. Two headers still give it away: `Host` carries
8
+ * the page's hostname rather than one this server answers to, and `Origin`
9
+ * names the page. With a token set none of this is needed: the page cannot
10
+ * authenticate.
11
+ */
12
+ /**
13
+ * The hostname in a Host header or an allow-list entry: port and IPv6
14
+ * brackets removed, lowercased, trailing dot dropped.
15
+ */
16
+ export function hostnameOf(host) {
17
+ const value = host.trim().toLowerCase();
18
+ if (value.startsWith('[')) {
19
+ const end = value.indexOf(']');
20
+ return end === -1 ? value : value.slice(1, end);
21
+ }
22
+ const colon = value.lastIndexOf(':');
23
+ return (colon === -1 ? value : value.slice(0, colon)).replace(/\.$/, '');
24
+ }
25
+ /**
26
+ * `localhost` and IP addresses always pass: a rebinding page can only put a
27
+ * hostname it controls in the header, never an IP. Anything else must be
28
+ * listed. A missing Host passes too, since every browser sends one.
29
+ */
30
+ function isAllowedHost(host, allowedHosts) {
31
+ if (!host)
32
+ return true;
33
+ const name = hostnameOf(host);
34
+ return name === 'localhost' || isIP(name) !== 0 || allowedHosts.includes(name);
35
+ }
36
+ /** No Origin (not a browser, or a same-origin GET), or one CORS_ORIGIN allows. */
37
+ function isAllowedOrigin(origin, corsOrigins) {
38
+ if (!origin)
39
+ return true;
40
+ return corsOrigins.includes('*') || corsOrigins.includes(origin);
41
+ }
42
+ /**
43
+ * Why a request to a server without a bearer token must be refused, or null if
44
+ * it may be answered. Preflights skip the Origin check: the CORS headers
45
+ * already decide what a browser may do after one.
46
+ */
47
+ export function rebindingRefusal(req, allowedHosts, corsOrigins) {
48
+ const { host, origin } = req.headers;
49
+ if (!isAllowedHost(host, allowedHosts)) {
50
+ return `Host ${JSON.stringify(host)} is not allowed: add its name to HTTP_ALLOWED_HOSTS, or set HTTP_AUTH_TOKEN`;
51
+ }
52
+ if (req.method !== 'OPTIONS' && !isAllowedOrigin(origin, corsOrigins)) {
53
+ return `Origin ${JSON.stringify(origin)} is not allowed: add it to CORS_ORIGIN, or set HTTP_AUTH_TOKEN`;
54
+ }
55
+ return null;
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roam-research-mcp",
3
- "version": "5.0.2",
3
+ "version": "5.1.0",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {