roam-research-mcp 5.0.2 → 5.1.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 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 };
@@ -137,43 +137,28 @@ export class SearchUtils {
137
137
  return tagMap;
138
138
  }
139
139
  /**
140
- * Generate case variations for case-insensitive search.
141
- * Returns: [original, capitalized first letter, ALL CAPS, all lowercase]
140
+ * Quote literal search text for Roam's Java regex engine. (?iu) enables
141
+ * Unicode-aware case-insensitivity; metacharacters retain their literal meaning.
142
+ * Roam's backend supports re-pattern/re-find, but not clojure.string/lower-case.
142
143
  */
143
- static getCaseVariations(text, caseSensitive = false) {
144
- if (caseSensitive) {
145
- return [text];
146
- }
147
- return [
148
- text,
149
- text.charAt(0).toUpperCase() + text.slice(1),
150
- text.toUpperCase(),
151
- text.toLowerCase()
152
- ];
144
+ static caseInsensitivePattern(text) {
145
+ return ednString(`(?iu)${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`);
153
146
  }
154
- /**
155
- * Build OR where clause for case-insensitive text search.
156
- * @param text - The search text
157
- * @param variable - The Datomic variable name (e.g., "?block-str")
158
- * @param caseSensitive - Whether to use case-sensitive matching
159
- * @returns Datomic OR clause string
160
- */
147
+ /** Match a literal substring, optionally ignoring capitalization. */
161
148
  static buildTextSearchClause(text, variable, caseSensitive = false) {
162
- const variations = this.getCaseVariations(text, caseSensitive);
163
- const clauses = variations.map(term => `[(clojure.string/includes? ${variable} ${ednString(term)})]`);
164
- return `(or ${clauses.join(' ')})`;
149
+ if (caseSensitive) {
150
+ return `[(clojure.string/includes? ${variable} ${ednString(text)})]`;
151
+ }
152
+ return `[(re-pattern ${this.caseInsensitivePattern(text)}) ${variable}-pattern]
153
+ [(re-find ${variable}-pattern ${variable})]`;
165
154
  }
166
- /**
167
- * Build OR where clause for case-insensitive tag/page title matching.
168
- * @param tag - The tag/page title to match
169
- * @param variable - The Datomic variable name (e.g., "?ref-page")
170
- * @param caseSensitive - Whether to use case-sensitive matching
171
- * @returns Datomic OR clause string
172
- */
155
+ /** Match a whole referenced page title, optionally ignoring capitalization. */
173
156
  static buildTagMatchClause(tag, variable, caseSensitive = false) {
174
- const variations = this.getCaseVariations(tag, caseSensitive);
175
- const clauses = variations.map(t => `[${variable} :node/title ${ednString(t)}]`);
176
- return `(or ${clauses.join(' ')})`;
157
+ if (caseSensitive)
158
+ return `[${variable} :node/title ${ednString(tag)}]`;
159
+ return `[${variable} :node/title ${variable}-title]
160
+ [(re-pattern ${this.caseInsensitivePattern(tag)}) ${variable}-pattern]
161
+ [(re-matches ${variable}-pattern ${variable}-title)]`;
177
162
  }
178
163
  /**
179
164
  * The two spellings of a status marker: `{{[[TODO]]}}` (what Roam's checkbox
@@ -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
@@ -197,11 +198,11 @@ export class RoamServer {
197
198
  return toolResult(request.params.name, result);
198
199
  }
199
200
  case 'roam_search_for_tag': {
200
- const { primary_tag, page_title_uid, near_tag } = cleanedArgs;
201
+ const { primary_tag, page_title_uid, near_tag, case_sensitive } = cleanedArgs;
201
202
  if (!primary_tag) {
202
203
  throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: primary_tag (the tag to search for). Use page_title_uid to limit search to a specific page.');
203
204
  }
204
- const result = await toolHandlers.searchForTag(primary_tag, page_title_uid, near_tag);
205
+ const result = await toolHandlers.searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive);
205
206
  return toolResult(request.params.name, result);
206
207
  }
207
208
  case 'roam_search_by_status': {
@@ -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
@@ -1,5 +1,8 @@
1
+ import { q } from '@roam-research/roam-api-sdk';
2
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
1
3
  import { TagSearchHandlerImpl, BlockRefSearchHandlerImpl, HierarchySearchHandlerImpl, TextSearchHandlerImpl, StatusSearchHandlerImpl, DatomicSearchHandlerImpl } from './handlers.js';
2
4
  import { collectHiddenUids, filterHiddenMatches } from '../../helpers/hidden.js';
5
+ import { resolveRefs } from '../../helpers/refs.js';
3
6
  export class SearchOperations {
4
7
  constructor(graph) {
5
8
  this.graph = graph;
@@ -69,11 +72,12 @@ export class SearchOperations {
69
72
  message: `Found ${matches.length} block(s) with status ${status}${include ? ` including "${include}"` : ''}${exclude ? ` excluding "${exclude}"` : ''}`
70
73
  };
71
74
  }
72
- async searchForTag(primary_tag, page_title_uid, near_tag) {
75
+ async searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive) {
73
76
  const handler = new TagSearchHandlerImpl(this.graph, {
74
77
  primary_tag,
75
78
  page_title_uid,
76
79
  near_tag,
80
+ case_sensitive,
77
81
  });
78
82
  return this.withoutHidden(await handler.execute());
79
83
  }
@@ -97,35 +101,63 @@ export class SearchOperations {
97
101
  return handler.execute();
98
102
  }
99
103
  async searchByDate(params) {
100
- // Convert dates to timestamps
101
- const startTimestamp = new Date(`${params.start_date}T00:00:00`).getTime();
102
- const endTimestamp = params.end_date ? new Date(`${params.end_date}T23:59:59`).getTime() : undefined;
103
- // Use text search handler for content-based filtering
104
- const handler = new TextSearchHandlerImpl(this.graph, {
105
- text: '', // Empty text to match all blocks
106
- });
107
- // Filtered before the map below, which renames block_uid -> uid; after it
108
- // the hidden-UID closure would have nothing to match on.
109
- const result = await this.withoutHidden(await handler.execute());
110
- // Filter results by date
111
- const matches = result.matches
112
- .filter(match => {
113
- const time = params.type === 'created' ?
114
- new Date(match.content || '').getTime() : // Use content date for creation time
115
- Date.now(); // Use current time for modification time (simplified)
116
- return time >= startTimestamp && (!endTimestamp || time <= endTimestamp);
117
- })
118
- .map(match => ({
119
- uid: match.block_uid,
120
- type: 'block',
121
- time: params.type === 'created' ?
122
- new Date(match.content || '').getTime() :
123
- Date.now(),
124
- ...(params.include_content && { content: match.content }),
125
- page_title: match.page_title
104
+ const parseDay = (value) => {
105
+ const day = new Date(`${value}T00:00:00`);
106
+ const parts = value.split('-').map(Number);
107
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(day.getTime()) ||
108
+ day.getFullYear() !== parts[0] || day.getMonth() + 1 !== parts[1] || day.getDate() !== parts[2]) {
109
+ throw new McpError(ErrorCode.InvalidParams, `Invalid date "${value}"; expected YYYY-MM-DD.`);
110
+ }
111
+ return day;
112
+ };
113
+ const start = parseDay(params.start_date).getTime();
114
+ const endDay = params.end_date === undefined ? undefined : parseDay(params.end_date);
115
+ if (endDay && endDay.getTime() < start) {
116
+ throw new McpError(ErrorCode.InvalidParams, 'end_date must be on or after start_date.');
117
+ }
118
+ // Next calendar midnight includes the entire final day, including .999,
119
+ // and handles days shortened or lengthened by daylight-saving transitions.
120
+ endDay?.setDate(endDay.getDate() + 1);
121
+ const inputs = endDay ? [start, endDay.getTime()] : [start];
122
+ const timeClause = params.type === 'both'
123
+ ? '(or [?e :create/time ?time] [?e :edit/time ?time])'
124
+ : `[?e :${params.type === 'created' ? 'create' : 'edit'}/time ?time]`;
125
+ const scopes = params.scope === 'both'
126
+ ? ['block', 'page'] : [params.scope === 'pages' ? 'page' : 'block'];
127
+ const results = await Promise.all(scopes.map(async (type) => {
128
+ const entityClause = type === 'block'
129
+ ? `[?e :block/string ?content]
130
+ [?e :block/page ?page]
131
+ [?page :node/title ?page-title]`
132
+ : `[?e :node/title ?content]
133
+ [?e :node/title ?page-title]`;
134
+ const query = `[:find ?uid ?content ?page-title ?time
135
+ :in $ ?start ${endDay ? '?end' : ''}
136
+ :where [?e :block/uid ?uid]
137
+ ${entityClause}
138
+ ${timeClause}
139
+ [(>= ?time ?start)]
140
+ ${endDay ? '[(< ?time ?end)]' : ''}]`;
141
+ const rows = await q(this.graph, query, inputs);
142
+ return rows.map(([block_uid, content, page_title, time]) => ({ block_uid, content, page_title, time, type }));
126
143
  }));
127
- // Sort by time
128
- const sortedMatches = matches.sort((a, b) => b.time - a.time);
144
+ const hidden = await collectHiddenUids(this.graph);
145
+ const visible = filterHiddenMatches(results.flat(), hidden);
146
+ const matchesByUid = new Map();
147
+ for (const match of visible) {
148
+ const previous = matchesByUid.get(match.block_uid);
149
+ // With type=both an entity may match twice. Return it once, with the
150
+ // latest timestamp that actually falls inside the requested range.
151
+ if (!previous || match.time > previous.time)
152
+ matchesByUid.set(match.block_uid, match);
153
+ }
154
+ const matches = await Promise.all([...matchesByUid.values()]
155
+ .map(async ({ block_uid, content, ...match }) => ({
156
+ uid: block_uid,
157
+ ...match,
158
+ ...(params.include_content !== false && { content: await resolveRefs(this.graph, content) }),
159
+ })));
160
+ const sortedMatches = matches.sort((a, b) => b.time - a.time || a.uid.localeCompare(b.uid));
129
161
  return {
130
162
  success: true,
131
163
  matches: sortedMatches,
@@ -417,7 +417,7 @@ export const toolSchemas = {
417
417
  },
418
418
  case_sensitive: {
419
419
  type: 'boolean',
420
- description: 'Optional: Whether the search should be case-sensitive. If false, it will search for the provided tag, capitalized versions, and first word capitalized versions.',
420
+ description: 'Optional: Whether the search should be case-sensitive. Defaults to Unicode-aware case-insensitive matching of the complete tag title.',
421
421
  default: false
422
422
  },
423
423
  limit: {
@@ -562,7 +562,7 @@ export const toolSchemas = {
562
562
  },
563
563
  case_sensitive: {
564
564
  type: 'boolean',
565
- description: 'Optional: Whether the search should be case-sensitive. If false, it will search for the provided text, capitalized versions, and first word capitalized versions. Only used when scope is "blocks".',
565
+ description: 'Optional: Whether the search should be case-sensitive. Defaults to Unicode-aware case-insensitive matching of literal text. Only used when scope is "blocks".',
566
566
  default: false
567
567
  },
568
568
  limit: {
@@ -588,16 +588,16 @@ export const toolSchemas = {
588
588
  properties: withMultiGraphParams({
589
589
  start_date: {
590
590
  type: 'string',
591
- description: 'Start date in ISO format (YYYY-MM-DD)',
591
+ description: 'Inclusive start date in ISO format (YYYY-MM-DD), in the server\'s local timezone.',
592
592
  },
593
593
  end_date: {
594
594
  type: 'string',
595
- description: 'Optional: End date in ISO format (YYYY-MM-DD)',
595
+ description: 'Optional: Inclusive end date in ISO format (YYYY-MM-DD), in the server\'s local timezone. Omit for no upper bound.',
596
596
  },
597
597
  type: {
598
598
  type: 'string',
599
599
  enum: ['created', 'modified', 'both'],
600
- description: 'Whether to search by creation date, modification date, or both',
600
+ description: 'Whether to search stored creation timestamps, modification timestamps, or either. With "both", each entity is returned once with its latest matching timestamp.',
601
601
  },
602
602
  scope: {
603
603
  type: 'string',
@@ -606,7 +606,7 @@ export const toolSchemas = {
606
606
  },
607
607
  include_content: {
608
608
  type: 'boolean',
609
- description: 'Whether to include the content of matching blocks/pages',
609
+ description: 'Whether to include matching block text or page titles. Defaults to true.',
610
610
  default: true,
611
611
  }
612
612
  }),
@@ -62,8 +62,8 @@ export class ToolHandlers {
62
62
  async searchByStatus(status, page_title_uid, include, exclude) {
63
63
  return this.searchOps.searchByStatus(status, page_title_uid, include, exclude);
64
64
  }
65
- async searchForTag(primary_tag, page_title_uid, near_tag) {
66
- return this.searchOps.searchForTag(primary_tag, page_title_uid, near_tag);
65
+ async searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive) {
66
+ return this.searchOps.searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive);
67
67
  }
68
68
  async searchBlockRefs(params) {
69
69
  return this.searchOps.searchBlockRefs(params);
@@ -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.1",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {