obsidian-sync-mcp 0.7.1 → 0.7.3

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
@@ -246,7 +246,7 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
246
246
  | `COUCHDB_URL` | CouchDB mode | — | CouchDB server URL |
247
247
  | `COUCHDB_USER` | CouchDB mode | `admin` | CouchDB username |
248
248
  | `COUCHDB_PASSWORD` | CouchDB mode | — | CouchDB password (required) |
249
- | `COUCHDB_DATABASE` | CouchDB mode | `obsidian` | CouchDB database name |
249
+ | `COUCHDB_DATABASE` | CouchDB mode | `obsidian` | CouchDB database name. The server never creates it: if it doesn't exist, startup fails with an error |
250
250
  | `COUCHDB_PASSPHRASE` | CouchDB mode | — | LiveSync E2E encryption passphrase (must match plugin setting) |
251
251
  | `COUCHDB_OBFUSCATE_PROPERTIES` | CouchDB mode | `false` | Set to `true` if "Obfuscate Properties" is enabled in LiveSync (obfuscates file paths, sizes, dates in the database). For existing vaults the actual setting is auto-detected at startup; this value only decides the format for a brand-new empty database |
252
252
  | `VAULT_NAME` | Both | `MyVault` | Vault name (used for deep links and index storage) |
@@ -258,7 +258,7 @@ Without `MCP_AUTH_TOKEN`, the server runs without authentication — suitable fo
258
258
  | `DATA_DIR` | Optional | `~/.obsidian-mcp` | Directory for persisted data (metadata index, auth tokens) |
259
259
  | `LOG_LEVEL` | Optional | — | Set to `debug` for verbose logging (library logs, change feed, index sync) |
260
260
  | `MCP_REFRESH_DAYS` | Optional | `14` | Days before auth session expires |
261
- | `READ_ONLY` | Optional | `false` | Set to `true` to disable all write tools (`write_note`, `edit_note`, `delete_note`, `move_note`). Only read tools are exposed via MCP. Useful when sharing the server with multiple AI clients and write access should be opt-in. |
261
+ | `READ_ONLY` | Optional | `false` | Set to `true` to disable all write tools (`write_note`, `edit_note`, `delete_note`, `move_note`). Only read tools are exposed via MCP, and the vault backend rejects writes as well. Useful when sharing the server with multiple AI clients and write access should be opt-in. This protects the vault from MCP clients; it is not a database-level guarantee. To make CouchDB itself refuse writes, use CouchDB-side controls, such as a `validate_doc_update` function that rejects the server's CouchDB user. |
262
262
  | `WRITE_FOLDERS` | Optional | — | Comma-separated list of vault-relative folders where writes are allowed (e.g. `MCP,Inbox`). When set, the whole vault stays readable but `write_note`, `edit_note`, `delete_note`, and `move_note` refuse paths outside these folders (`move_note` requires both source and destination to be writable). Enforced server-side, unlike `MCP_INSTRUCTIONS`. Matching is case-sensitive and folder-boundary-aware (`MCP` matches `MCP/note.md` but not `MCP-private/note.md`). Ignored when `READ_ONLY=true`; unset means the whole vault is writable. |
263
263
  | `MCP_INSTRUCTIONS` | Optional | — | Extra text appended to the server's MCP `instructions` (the string clients inject into the system prompt). Use this to bake vault-specific conventions into the server — e.g. folder structure, naming rules, folders to avoid — so they apply across every MCP client without per-client config. Best-effort: not all clients respect `instructions`. |
264
264
  | `MCP_INSTRUCTIONS_FILE` | Optional | — | Path to a file (e.g. markdown) whose contents are appended to the MCP `instructions`. Easier than `MCP_INSTRUCTIONS` for multi-line conventions. If both are set, the file wins and `MCP_INSTRUCTIONS` is ignored (with a startup warning). Missing/unreadable file or files larger than 32 KB are fatal startup errors. **Store this file somewhere only the service user can write (e.g. `chmod 600`)** — its contents land in every MCP session's system prompt, so write access to it = prompt-injection access to every client. |
@@ -312,6 +312,8 @@ This server gives an AI agent read/write access to your Obsidian vault.
312
312
 
313
313
  **Use HTTPS in production.** Use a tunnel or deploy behind a reverse proxy.
314
314
 
315
+ **Don't leave `LOG_LEVEL=debug` on in production.** Debug logging records every tool call's arguments, including note contents, and full error stacks. Credentials embedded in `COUCHDB_URL` are redacted from logs at every level.
316
+
315
317
  This software is provided as-is under the [MIT license](https://github.com/es617/obsidian-sync-mcp/blob/main/LICENSE). You are responsible for what agents do with your vault.
316
318
 
317
319
  ---
@@ -135,8 +135,52 @@ function maskInlineSpans(text) {
135
135
  return result + text.slice(from);
136
136
  }
137
137
 
138
+ // src/note-path.ts
139
+ var RESERVED_ROOT_FILES = /* @__PURE__ */ new Set([
140
+ "redflag.md",
141
+ "redflag2.md",
142
+ "redflag3.md",
143
+ "flag_rebuild.md",
144
+ "flag_fetch.md"
145
+ ]);
146
+ function validateNotePath(path) {
147
+ if (!path || path.length > 1e3) {
148
+ throw new Error("Invalid note path");
149
+ }
150
+ if (path.startsWith("/") || path.includes("\0") || path.includes("..")) {
151
+ throw new Error("Invalid note path");
152
+ }
153
+ if (path.includes(":")) {
154
+ throw new Error("Invalid note path: ':' is not allowed");
155
+ }
156
+ if (!path.endsWith(".md")) {
157
+ throw new Error("Invalid note path: must be a vault-relative path ending in .md");
158
+ }
159
+ for (const segment of path.split(/[/\\]/)) {
160
+ if (segment === "") {
161
+ throw new Error("Invalid note path: empty path segment");
162
+ }
163
+ if (segment.startsWith(".")) {
164
+ throw new Error("Invalid note path: dot-folders and hidden files (e.g. .obsidian) are not allowed");
165
+ }
166
+ }
167
+ if (!path.includes("/") && !path.includes("\\") && RESERVED_ROOT_FILES.has(path.toLowerCase())) {
168
+ throw new Error("Invalid note path: reserved LiveSync control file");
169
+ }
170
+ }
171
+ function isValidNotePath(path) {
172
+ try {
173
+ validateNotePath(path);
174
+ return true;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+
138
180
  export {
139
181
  __reExport,
140
- parseFrontmatterAndLinks
182
+ parseFrontmatterAndLinks,
183
+ validateNotePath,
184
+ isValidNotePath
141
185
  };
142
- //# sourceMappingURL=chunk-43MP6CJE.js.map
186
+ //# sourceMappingURL=chunk-VR63UUCB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parse.ts","../src/note-path.ts"],"sourcesContent":["/**\n * Parse Obsidian markdown content for frontmatter, tags, and links.\n */\n\nexport interface NoteMetadata {\n frontmatter: Record<string, string>;\n tags: string[];\n links: string[];\n}\n\nexport function parseFrontmatterAndLinks(content: string): NoteMetadata {\n const frontmatter: Record<string, any> = {};\n const tags = new Set<string>();\n const links: string[] = [];\n\n // Parse YAML frontmatter\n if (content.startsWith(\"---\\n\")) {\n const end = content.indexOf(\"\\n---\", 4);\n if (end !== -1) {\n const yaml = content.slice(4, end);\n let inTagsList = false;\n for (const line of yaml.split(\"\\n\")) {\n // Multi-line tags list item: \" - tagname\"\n if (inTagsList) {\n const listItem = line.match(/^\\s+-\\s+(.+)/);\n if (listItem) {\n const trimmed = listItem[1].trim();\n if (trimmed) tags.add(trimmed);\n continue;\n }\n inTagsList = false;\n }\n\n const match = line.match(/^([\\p{L}\\p{N}_][\\p{L}\\p{M}\\p{N}_-]*)\\s*:\\s*(.+)/u);\n if (match) {\n frontmatter[match[1]] = match[2].trim();\n }\n // Frontmatter tags (inline: [a, b] or start of multi-line list)\n if (/^tags\\s*:/.test(line)) {\n const value = line.replace(/^tags\\s*:\\s*/, \"\").trim();\n if (value) {\n // Inline: tags: [a, b] or tags: a, b\n const tagValues = value.replace(/[[\\]]/g, \"\");\n for (const t of tagValues.split(\",\")) {\n const trimmed = t.trim();\n if (trimmed) tags.add(trimmed);\n }\n } else {\n // Multi-line list follows\n inTagsList = true;\n }\n }\n }\n }\n }\n\n // Inline #tags. Obsidian does not read tags out of code, and a tag must\n // contain at least one non-numerical character (\"#1984 isn't a valid tag,\n // but #y1984 is\" — obsidian.md/help/tags), so code spans and fenced blocks\n // are masked out first and all-digit matches are dropped.\n for (const match of maskCode(content).matchAll(/(^|\\s)#([\\p{L}\\p{N}_/-][\\p{L}\\p{M}\\p{N}_/-]*)/gu)) {\n if (/^\\p{Nd}+$/u.test(match[2])) continue;\n tags.add(match[2]);\n }\n\n // [[wikilinks]]\n for (const match of content.matchAll(/\\[\\[([^\\]|]+)(?:\\|[^\\]]+)?\\]\\]/g)) {\n links.push(match[1]);\n }\n\n // [markdown links](path.md)\n for (const match of content.matchAll(/\\[([^\\]]+)\\]\\(([^)]+\\.md)\\)/g)) {\n links.push(match[2]);\n }\n\n return { frontmatter, tags: [...tags], links: [...new Set(links)] };\n}\n\n/**\n * Replace fenced code blocks (``` or ~~~, opener at line start with up to three\n * spaces of indent, closer of the same character and at least the same length;\n * an unclosed fence runs to the end) and inline code spans (a backtick run of\n * length n closes at the next run of exactly n within the same paragraph — a\n * span never crosses a blank line; an unmatched run is literal)\n * with dots, so offsets are preserved and nothing inside can start or extend a\n * tag. Indented code blocks, %% comments and math are not masked.\n */\nexport function maskCode(content: string): string {\n const lines = content.split(\"\\n\");\n const out: string[] = [];\n let fence: { char: string; len: number } | null = null;\n const inline: string[] = [];\n const flushInline = () => {\n if (inline.length === 0) return;\n out.push(...maskInlineSpans(inline.join(\"\\n\")).split(\"\\n\"));\n inline.length = 0;\n };\n for (const line of lines) {\n const open = line.match(/^ {0,3}(`{3,}|~{3,})/);\n if (fence) {\n const close = open && open[1][0] === fence.char && open[1].length >= fence.len && line.trim() === open[1];\n out.push(\".\".repeat(line.length));\n if (close) fence = null;\n continue;\n }\n if (open && (open[1][0] === \"~\" || !line.slice(open[0].length).includes(\"`\"))) {\n flushInline();\n fence = { char: open[1][0], len: open[1].length };\n out.push(\".\".repeat(line.length));\n continue;\n }\n if (line.trim() === \"\") {\n flushInline();\n out.push(line);\n continue;\n }\n inline.push(line);\n }\n flushInline();\n return out.join(\"\\n\");\n}\n\nfunction maskInlineSpans(text: string): string {\n // Collect backtick runs in one pass, then link each run to the next run of\n // the same length (scanning right to left) so matching stays linear.\n const runs: { at: number; len: number }[] = [];\n for (let i = 0; i < text.length; ) {\n if (text[i] !== \"`\") { i++; continue; }\n let n = 0;\n while (text[i + n] === \"`\") n++;\n runs.push({ at: i, len: n });\n i += n;\n }\n const next: number[] = [];\n const seen = new Map<number, number>();\n for (let r = runs.length - 1; r >= 0; r--) {\n next[r] = seen.get(runs[r].len) ?? -1;\n seen.set(runs[r].len, r);\n }\n let result = \"\";\n let from = 0;\n for (let r = 0; r < runs.length; ) {\n const c = next[r];\n if (c === -1) { r++; continue; }\n const start = runs[r].at;\n const end = runs[c].at + runs[c].len;\n result += text.slice(from, start) + text.slice(start, end).replace(/[^\\n]/g, \".\");\n from = end;\n r = c + 1;\n }\n return result + text.slice(from);\n}\n\nexport function extractSnippet(content: string, query: string, context = 80): string {\n const lower = content.toLowerCase();\n\n // Try exact phrase first\n let idx = lower.indexOf(query.toLowerCase());\n\n // Try to find the smallest span containing all query words\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).map((w) => w.toLowerCase());\n if (words.length > 1) {\n let bestStart = -1;\n let bestLen = Infinity;\n // For each occurrence of the first word, find the nearest span containing all words\n const first = words[0];\n let pos = 0;\n while (pos < lower.length) {\n const start = lower.indexOf(first, pos);\n if (start === -1) break;\n // Find last position needed to include all words from this start\n let spanEnd = start + first.length;\n let allFound = true;\n for (let i = 1; i < words.length; i++) {\n const wi = lower.indexOf(words[i], Math.max(0, start - 200));\n if (wi === -1) { allFound = false; break; }\n spanEnd = Math.max(spanEnd, wi + words[i].length);\n }\n if (allFound) {\n const spanStart = Math.min(start, ...words.map((w) => lower.indexOf(w, Math.max(0, start - 200))).filter((i) => i >= 0));\n const len = spanEnd - spanStart;\n if (len < bestLen) { bestStart = spanStart; bestLen = len; }\n }\n pos = start + 1;\n }\n if (bestStart >= 0 && bestLen <= 500) idx = bestStart;\n }\n }\n\n // Fall back to longest matching word\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).sort((a, b) => b.length - a.length);\n for (const word of words) {\n idx = lower.indexOf(word.toLowerCase());\n if (idx !== -1) break;\n }\n }\n\n if (idx === -1) {\n return content.slice(0, 160) + (content.length > 160 ? \"...\" : \"\");\n }\n const start = Math.max(0, idx - context);\n const end = Math.min(content.length, idx + query.length + context);\n return (start > 0 ? \"...\" : \"\") + content.slice(start, end) + (end < content.length ? \"...\" : \"\");\n}\n","/**\n * Shared validation for note paths, applied by both the CouchDB and local\n * backends before any read, write, delete or move.\n *\n * The note model is markdown-only: `list_notes` only ever surfaces `*.md`\n * files, and binary attachments are not supported. Enforcing that here keeps\n * the tools from reaching anything that isn't a note, which closes two real\n * problems:\n * - CouchDB mode: a path like `obsydian_livesync_version` or a `ix:`/`ps:`\n * prefixed id would otherwise become a document id and overwrite LiveSync's\n * own control documents, stopping sync on every device.\n * - Local mode: a path like `.obsidian/plugins/x/main.js` would otherwise\n * write executable plugin code into the vault, and `.obsidian/.../data.json`\n * would expose LiveSync credentials.\n *\n * Rules: vault-relative, ends in `.md`, no `..`, no leading `/`, no `:` (its\n * only use here is LiveSync's internal id prefixes), no NUL, and no path\n * segment (split on either slash) that starts with `.` (hidden files and the\n * `.obsidian` config dir). Root-level LiveSync control flag files are also\n * rejected even though they are `.md`.\n */\n\n// LiveSync's note-shaped control files, all at the vault root. Writing one and\n// letting it sync triggers a vault-wide rebuild/fetch on every device, so they\n// are not writable through the note tools. Compared lowercase because LiveSync\n// lowercases ids when case-insensitive handling is on.\nconst RESERVED_ROOT_FILES = new Set([\n \"redflag.md\",\n \"redflag2.md\",\n \"redflag3.md\",\n \"flag_rebuild.md\",\n \"flag_fetch.md\",\n]);\n\nexport function validateNotePath(path: string): void {\n if (!path || path.length > 1000) {\n throw new Error(\"Invalid note path\");\n }\n if (path.startsWith(\"/\") || path.includes(\"\\0\") || path.includes(\"..\")) {\n throw new Error(\"Invalid note path\");\n }\n if (path.includes(\":\")) {\n throw new Error(\"Invalid note path: ':' is not allowed\");\n }\n if (!path.endsWith(\".md\")) {\n throw new Error(\"Invalid note path: must be a vault-relative path ending in .md\");\n }\n for (const segment of path.split(/[/\\\\]/)) {\n if (segment === \"\") {\n throw new Error(\"Invalid note path: empty path segment\");\n }\n if (segment.startsWith(\".\")) {\n throw new Error(\"Invalid note path: dot-folders and hidden files (e.g. .obsidian) are not allowed\");\n }\n }\n // Root-level control flag files (no folder segment).\n if (!path.includes(\"/\") && !path.includes(\"\\\\\") && RESERVED_ROOT_FILES.has(path.toLowerCase())) {\n throw new Error(\"Invalid note path: reserved LiveSync control file\");\n }\n}\n\n/** Boolean form of validateNotePath, for filtering listings and the index. */\nexport function isValidNotePath(path: string): boolean {\n try {\n validateNotePath(path);\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAUO,SAAS,yBAAyB,SAA+B;AACpE,QAAM,cAAmC,CAAC;AAC1C,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,QAAkB,CAAC;AAGzB,MAAI,QAAQ,WAAW,OAAO,GAAG;AAC7B,UAAM,MAAM,QAAQ,QAAQ,SAAS,CAAC;AACtC,QAAI,QAAQ,IAAI;AACZ,YAAM,OAAO,QAAQ,MAAM,GAAG,GAAG;AACjC,UAAI,aAAa;AACjB,iBAAW,QAAQ,KAAK,MAAM,IAAI,GAAG;AAEjC,YAAI,YAAY;AACZ,gBAAM,WAAW,KAAK,MAAM,cAAc;AAC1C,cAAI,UAAU;AACV,kBAAM,UAAU,SAAS,CAAC,EAAE,KAAK;AACjC,gBAAI,QAAS,MAAK,IAAI,OAAO;AAC7B;AAAA,UACJ;AACA,uBAAa;AAAA,QACjB;AAEA,cAAM,QAAQ,KAAK,MAAM,kDAAkD;AAC3E,YAAI,OAAO;AACP,sBAAY,MAAM,CAAC,CAAC,IAAI,MAAM,CAAC,EAAE,KAAK;AAAA,QAC1C;AAEA,YAAI,YAAY,KAAK,IAAI,GAAG;AACxB,gBAAM,QAAQ,KAAK,QAAQ,gBAAgB,EAAE,EAAE,KAAK;AACpD,cAAI,OAAO;AAEP,kBAAM,YAAY,MAAM,QAAQ,UAAU,EAAE;AAC5C,uBAAW,KAAK,UAAU,MAAM,GAAG,GAAG;AAClC,oBAAM,UAAU,EAAE,KAAK;AACvB,kBAAI,QAAS,MAAK,IAAI,OAAO;AAAA,YACjC;AAAA,UACJ,OAAO;AAEH,yBAAa;AAAA,UACjB;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAMA,aAAW,SAAS,SAAS,OAAO,EAAE,SAAS,iDAAiD,GAAG;AAC/F,QAAI,WAAC,cAAU,GAAC,EA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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAEM,SAAS,iBAAiB,MAAoB;AACjD,MAAI,CAAC,QAAQ,KAAK,SAAS,KAAM;AAC7B,UAAM,IAAI,MAAM,mBAAmB;AAAA,EACvC;AACA,MAAI,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,IAAI,GAAG;AACpE,UAAM,IAAI,MAAM,mBAAmB;AAAA,EACvC;AACA,MAAI,KAAK,SAAS,GAAG,GAAG;AACpB,UAAM,IAAI,MAAM,uCAAuC;AAAA,EAC3D;AACA,MAAI,CAAC,KAAK,SAAS,KAAK,GAAG;AACvB,UAAM,IAAI,MAAM,gEAAgE;AAAA,EACpF;AACA,aAAW,WAAW,KAAK,MAAM,OAAO,GAAG;AACvC,QAAI,YAAY,IAAI;AAChB,YAAM,IAAI,MAAM,uCAAuC;AAAA,IAC3D;AACA,QAAI,QAAQ,WAAW,GAAG,GAAG;AACzB,YAAM,IAAI,MAAM,kFAAkF;AAAA,IACtG;AAAA,EACJ;AAEA,MAAI,CAAC,KAAK,SAAS,GAAG,KAAK,CAAC,KAAK,SAAS,IAAI,KAAK,oBAAoB,IAAI,KAAK,YAAY,CAAC,GAAG;AAC5F,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACvE;AACJ;AAGO,SAAS,gBAAgB,MAAuB;AACnD,MAAI;AACA,qBAAiB,IAAI;AACrB,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;","names":[]}
package/dist/main.js CHANGED
@@ -5,13 +5,14 @@ import {
5
5
  applyIndexChange
6
6
  } from "./chunk-SGLPTZJA.js";
7
7
  import {
8
+ isValidNotePath,
8
9
  parseFrontmatterAndLinks
9
- } from "./chunk-43MP6CJE.js";
10
+ } from "./chunk-VR63UUCB.js";
10
11
 
11
12
  // src/main.ts
12
13
  import { FastMCP } from "fastmcp";
13
14
  import { join } from "path";
14
- import { timingSafeEqual as timingSafeEqual2, createHash as createHash2 } from "crypto";
15
+ import { createHash as createHash2 } from "crypto";
15
16
  import { watch, readFileSync, statSync } from "fs";
16
17
  import { stat } from "fs/promises";
17
18
  import { setGlobalLogFunction, LEVEL_INFO } from "octagonal-wheels/common/logger";
@@ -28,6 +29,11 @@ var BASE_LOCKOUT_MS = 5 * 1e3;
28
29
  var MAX_CLIENTS = 100;
29
30
  var MAX_PENDING = 100;
30
31
  var PENDING_TTL_MS = 10 * 60 * 1e3;
32
+ function safeEqual(a, b) {
33
+ const da = createHash("sha256").update(a).digest();
34
+ const db = createHash("sha256").update(b).digest();
35
+ return timingSafeEqual(da, db);
36
+ }
31
37
  function mountPasswordAuth(app, baseUrl, password, persistPath) {
32
38
  const pendingAuths = /* @__PURE__ */ new Map();
33
39
  const csrfTokens = /* @__PURE__ */ new Map();
@@ -179,7 +185,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
179
185
  console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);
180
186
  const csrf = randomBytes(32).toString("hex");
181
187
  csrfTokens.set(code, csrf);
182
- return c.html(renderPasswordPage(code, csrf));
188
+ return c.html(renderPasswordPage(code, csrf, hostOf(redirectUri), client.clientName));
183
189
  });
184
190
  app.post("/oauth/approve", async (c) => {
185
191
  const body = await c.req.parseBody();
@@ -191,9 +197,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
191
197
  if (!pending || !expectedCsrf) {
192
198
  return c.html("<p>Invalid or expired authorization request.</p>", 400);
193
199
  }
194
- const csrfA = Buffer.from(submittedCsrf ?? "");
195
- const csrfB = Buffer.from(expectedCsrf);
196
- if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {
200
+ if (typeof submittedCsrf !== "string" || !safeEqual(submittedCsrf, expectedCsrf)) {
197
201
  return c.html("<p>Invalid request.</p>", 403);
198
202
  }
199
203
  if (Date.now() < lockedUntil) {
@@ -201,11 +205,9 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
201
205
  console.warn(`Auth: locked out, ${waitSec}s remaining`);
202
206
  const newCsrf = randomBytes(32).toString("hex");
203
207
  csrfTokens.set(code, newCsrf);
204
- return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
208
+ return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
205
209
  }
206
- const a = Buffer.from(submittedPassword);
207
- const b = Buffer.from(password);
208
- if (a.length !== b.length || !timingSafeEqual(a, b)) {
210
+ if (typeof submittedPassword !== "string" || !safeEqual(submittedPassword, password)) {
209
211
  failedAttempts++;
210
212
  console.warn(`Auth: failed attempt ${failedAttempts} total`);
211
213
  const newCsrf = randomBytes(32).toString("hex");
@@ -215,9 +217,9 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
215
217
  const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);
216
218
  lockedUntil = Date.now() + lockoutMs;
217
219
  console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1e3}s`);
218
- return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
220
+ return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
219
221
  }
220
- return c.html(renderPasswordPage(code, newCsrf, "Wrong password."), 401);
222
+ return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, "Wrong password."), 401);
221
223
  }
222
224
  failedAttempts = 0;
223
225
  lockoutCount = 0;
@@ -380,7 +382,16 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
380
382
  }
381
383
  };
382
384
  }
383
- function renderPasswordPage(code, csrf, error) {
385
+ function hostOf(uri) {
386
+ try {
387
+ return new URL(uri).host;
388
+ } catch {
389
+ return uri;
390
+ }
391
+ }
392
+ function renderPasswordPage(code, csrf, redirectHost, clientName, error) {
393
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
394
+ const who = clientName ? `<b>${esc(clientName)}</b> (name self-reported)` : "An application";
384
395
  return `<!DOCTYPE html>
385
396
  <html><head><title>Obsidian Sync MCP - Authorize</title>
386
397
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
@@ -390,10 +401,15 @@ function renderPasswordPage(code, csrf, error) {
390
401
  input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }
391
402
  button { padding: 10px 20px; font-size: 1em; cursor: pointer; }
392
403
  .error { color: red; }
404
+ .dest { background: #f3f3f3; padding: 8px 10px; border-radius: 6px; word-break: break-all; }
405
+ .warn { color: #a15c00; }
393
406
  </style></head>
394
407
  <body>
395
408
  <h1>Obsidian Sync MCP</h1>
396
- ${error ? `<p class="error">${error.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>` : "<p>Enter the server password to authorize access to your vault.</p>"}
409
+ <p>${who} is requesting access to your vault. After you approve, your browser will be sent to:</p>
410
+ <p class="dest"><b>${esc(redirectHost)}</b></p>
411
+ <p class="warn">Only enter your password if you recognize this destination. If you did not start this sign-in, close this page.</p>
412
+ ${error ? `<p class="error">${esc(error)}</p>` : ""}
397
413
  <form method="POST" action="/oauth/approve" autocomplete="on">
398
414
  <input type="hidden" name="code" value="${code.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">
399
415
  <input type="hidden" name="csrf" value="${csrf.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">
@@ -547,7 +563,7 @@ var SearchIndex = class {
547
563
  /** List all indexed paths with mtimes, optionally filtered by folder prefix. */
548
564
  listWithMtime(folder) {
549
565
  const prefix = folder && !folder.endsWith("/") ? folder + "/" : folder;
550
- const entries = [...this.knownPaths].filter((p) => p.endsWith(".md")).filter((p) => !prefix || p.startsWith(prefix)).map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));
566
+ const entries = [...this.knownPaths].filter(isValidNotePath).filter((p) => !prefix || p.startsWith(prefix)).map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));
551
567
  return entries.sort((a, b) => a.path.localeCompare(b.path));
552
568
  }
553
569
  /** Get mtime for a path. */
@@ -644,6 +660,27 @@ function isOriginAllowed(originHeader, allowed) {
644
660
  }
645
661
  }
646
662
 
663
+ // src/vault-readonly.ts
664
+ var READ_ONLY_MESSAGE = "READ_ONLY is enabled: the vault cannot be modified.";
665
+ function readOnlyVault(inner) {
666
+ const deny = async () => {
667
+ throw new Error(READ_ONLY_MESSAGE);
668
+ };
669
+ return {
670
+ init: () => inner.init(),
671
+ close: () => inner.close(),
672
+ readNote: (path) => inner.readNote(path),
673
+ getMetadata: (path) => inner.getMetadata(path),
674
+ listNotes: (folder) => inner.listNotes(folder),
675
+ listNotesWithMtime: (folder) => inner.listNotesWithMtime(folder),
676
+ watchChanges: inner.watchChanges?.bind(inner),
677
+ catchUp: inner.catchUp?.bind(inner),
678
+ writeNote: deny,
679
+ deleteNote: deny,
680
+ moveNote: deny
681
+ };
682
+ }
683
+
647
684
  // src/tools.ts
648
685
  import { z } from "zod";
649
686
 
@@ -1048,6 +1085,34 @@ Backlinks: ${backlinks.join(", ")}`);
1048
1085
  });
1049
1086
  }
1050
1087
 
1088
+ // src/redact.ts
1089
+ import { inspect } from "util";
1090
+ function redactCredentials(text) {
1091
+ return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]+@/gi, "$1***@");
1092
+ }
1093
+ function describeError(err, verbose = false) {
1094
+ if (!(err instanceof Error)) return redactCredentials(String(err));
1095
+ let text = verbose && err.stack ? err.stack : `${err.name}: ${err.message}`;
1096
+ const causes = [];
1097
+ let cause = err.cause;
1098
+ for (let depth = 0; cause !== void 0 && cause !== null && depth < 3; depth++) {
1099
+ if (cause instanceof Error) {
1100
+ causes.push(cause.message || String(cause.code ?? cause.name));
1101
+ cause = cause.cause;
1102
+ } else {
1103
+ causes.push(String(cause));
1104
+ break;
1105
+ }
1106
+ }
1107
+ if (causes.length > 0) text += ` (cause: ${causes.join(" <- ")})`;
1108
+ return redactCredentials(text);
1109
+ }
1110
+ function describeLogMessage(message, verbose = false) {
1111
+ if (typeof message === "string") return redactCredentials(message);
1112
+ if (message instanceof Error) return describeError(message, verbose);
1113
+ return redactCredentials(inspect(message));
1114
+ }
1115
+
1051
1116
  // src/main.ts
1052
1117
  var debugLogging2 = process.env.LOG_LEVEL === "debug";
1053
1118
  setGlobalLogFunction((message, level = LEVEL_INFO) => {
@@ -1056,7 +1121,7 @@ setGlobalLogFunction((message, level = LEVEL_INFO) => {
1056
1121
  if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;
1057
1122
  if (message.includes("replicator") || message.includes("Replicator") || message.includes("ReplicatorService")) return;
1058
1123
  }
1059
- console.log(message);
1124
+ console.log(describeLogMessage(message, debugLogging2));
1060
1125
  });
1061
1126
  var VAULT_PATH = process.env.VAULT_PATH;
1062
1127
  var COUCHDB_URL = process.env.COUCHDB_URL;
@@ -1094,7 +1159,7 @@ if (MCP_INSTRUCTIONS_FILE) {
1094
1159
  }
1095
1160
  var vault;
1096
1161
  if (VAULT_PATH) {
1097
- const { LocalVault } = await import("./vault-local-S53KTNRT.js");
1162
+ const { LocalVault } = await import("./vault-local-OURGENR5.js");
1098
1163
  vault = new LocalVault(VAULT_PATH);
1099
1164
  console.log(`Local mode: ${VAULT_PATH}`);
1100
1165
  } else if (COUCHDB_URL) {
@@ -1102,7 +1167,7 @@ if (VAULT_PATH) {
1102
1167
  console.error("COUCHDB_PASSWORD is required in remote mode.");
1103
1168
  process.exit(1);
1104
1169
  }
1105
- const { Vault } = await import("./vault-YGHHZZZQ.js");
1170
+ const { Vault } = await import("./vault-EJSNMND5.js");
1106
1171
  vault = new Vault({
1107
1172
  couchdbUrl: COUCHDB_URL,
1108
1173
  couchdbUser: COUCHDB_USER,
@@ -1111,13 +1176,19 @@ if (VAULT_PATH) {
1111
1176
  passphrase: COUCHDB_PASSPHRASE,
1112
1177
  obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES
1113
1178
  });
1114
- console.log(`Remote mode: ${COUCHDB_URL}`);
1179
+ console.log(`Remote mode: ${redactCredentials(COUCHDB_URL)}`);
1115
1180
  } else {
1116
1181
  console.error("Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.");
1117
1182
  process.exit(1);
1118
1183
  }
1119
- await vault.init();
1184
+ try {
1185
+ await vault.init();
1186
+ } catch (err) {
1187
+ console.error(`Failed to open the vault: ${describeError(err, debugLogging2)}`);
1188
+ process.exit(1);
1189
+ }
1120
1190
  console.log("Vault ready.");
1191
+ if (READ_ONLY) vault = readOnlyVault(vault);
1121
1192
  var baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? "/tmp", ".obsidian-mcp");
1122
1193
  var vaultId = createHash2("sha256").update(VAULT_NAME).digest("hex").slice(0, 12);
1123
1194
  var dataDir = join(baseDataDir, vaultId);
@@ -1150,7 +1221,7 @@ async function rebuildIndex() {
1150
1221
  const newSince = await vault.catchUp(since, countingCallback, onBatch);
1151
1222
  searchIndex.since = newSince;
1152
1223
  } catch (err) {
1153
- console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);
1224
+ console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), rebuilding index from scratch...`);
1154
1225
  searchIndex.clear();
1155
1226
  changes = 0;
1156
1227
  const newSince = await vault.catchUp("0", (path, content, mtime) => {
@@ -1189,7 +1260,7 @@ async function rebuildIndex() {
1189
1260
  }
1190
1261
  rebuildIndex().catch((err) => {
1191
1262
  searchIndex.state = "failed";
1192
- console.error("Index rebuild failed:", err);
1263
+ console.error(`Index rebuild failed: ${describeError(err, debugLogging2)}`);
1193
1264
  });
1194
1265
  var fsWatcher = null;
1195
1266
  if (VAULT_PATH) {
@@ -1227,7 +1298,7 @@ if (VAULT_PATH) {
1227
1298
  var BASE_INSTRUCTIONS = "Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.";
1228
1299
  var serverOptions = {
1229
1300
  name: "obsidian-sync-mcp",
1230
- version: "0.7.1",
1301
+ version: "0.7.3",
1231
1302
  instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
1232
1303
 
1233
1304
  ${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
@@ -1237,7 +1308,7 @@ if (AUTH_TOKEN) {
1237
1308
  serverOptions.authenticate = async (req) => {
1238
1309
  const header = req.headers["authorization"];
1239
1310
  const expected = `Bearer ${AUTH_TOKEN}`;
1240
- if (header && header.length === expected.length && timingSafeEqual2(Buffer.from(header), Buffer.from(expected))) {
1311
+ if (header && safeEqual(header, expected)) {
1241
1312
  return { authenticated: true };
1242
1313
  }
1243
1314
  if (auth?.validateToken(header)) {
@@ -1294,8 +1365,8 @@ server.start({
1294
1365
  transportType: "httpStream",
1295
1366
  httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
1296
1367
  });
1297
- console.log(`obsidian-sync-mcp v${"0.7.1"} listening on port ${PORT}`);
1368
+ console.log(`obsidian-sync-mcp v${"0.7.3"} listening on port ${PORT}`);
1298
1369
  process.on("unhandledRejection", (err) => {
1299
- console.error("Unhandled rejection:", err);
1370
+ console.error(`Unhandled rejection: ${describeError(err, debugLogging2)}`);
1300
1371
  });
1301
1372
  //# sourceMappingURL=main.js.map