obsidian-sync-mcp 0.6.2 → 0.6.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/dist/main.js CHANGED
@@ -51,8 +51,8 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
51
51
  try {
52
52
  await mkdir(dirname(persistPath), { recursive: true });
53
53
  const now = Date.now();
54
- const activeTokens = [...tokens.entries()].filter(([_, r]) => r.expiresAt > now);
55
- const activeRefresh = [...refreshTokens.entries()].filter(([_, r]) => r.refreshExpiresAt > now);
54
+ const activeTokens = [...tokens.entries()].filter(([, r]) => r.expiresAt > now);
55
+ const activeRefresh = [...refreshTokens.entries()].filter(([, r]) => r.refreshExpiresAt > now);
56
56
  const data = JSON.stringify({
57
57
  tokens: Object.fromEntries(activeTokens),
58
58
  refreshTokens: Object.fromEntries(activeRefresh),
@@ -116,23 +116,28 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
116
116
  return c.json({ error: "invalid_client_metadata", error_description: "invalid redirect_uri" }, 400);
117
117
  }
118
118
  const clientId = randomUUID();
119
- const clientSecret = randomBytes(32).toString("hex");
119
+ const tokenEndpointAuthMethod = body.token_endpoint_auth_method === "none" ? "none" : "client_secret_post";
120
+ const clientSecret = tokenEndpointAuthMethod === "none" ? void 0 : randomBytes(32).toString("hex");
120
121
  const clientName = typeof body.client_name === "string" ? body.client_name.slice(0, 256) : void 0;
121
122
  const client = {
122
123
  clientId,
123
124
  clientSecret,
125
+ tokenEndpointAuthMethod,
124
126
  redirectUris,
125
127
  clientName,
126
128
  createdAt: Date.now()
127
129
  };
128
130
  clients.set(clientId, client);
129
131
  await persist();
132
+ console.log(
133
+ `Auth: registered client_id=${clientId} redirect_uris=${JSON.stringify(redirectUris)} requested_auth_method=${JSON.stringify(body.token_endpoint_auth_method ?? "(unspecified)")} (responding with ${tokenEndpointAuthMethod})`
134
+ );
130
135
  return c.json({
131
136
  client_id: clientId,
132
- client_secret: clientSecret,
137
+ ...clientSecret ? { client_secret: clientSecret } : {},
133
138
  redirect_uris: client.redirectUris,
134
139
  client_name: client.clientName,
135
- token_endpoint_auth_method: "client_secret_post"
140
+ token_endpoint_auth_method: tokenEndpointAuthMethod
136
141
  }, 201);
137
142
  });
138
143
  app.get("/oauth/authorize", (c) => {
@@ -143,12 +148,17 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
143
148
  const state = c.req.query("state") ?? "";
144
149
  const client = clients.get(clientId);
145
150
  if (!client) {
151
+ console.warn(`Auth: /oauth/authorize unknown client_id=${JSON.stringify(clientId)}`);
146
152
  return c.text("Unknown client", 400);
147
153
  }
148
154
  if (!client.redirectUris.includes(redirectUri)) {
155
+ console.warn(
156
+ `Auth: /oauth/authorize redirect_uri mismatch. received=${JSON.stringify(redirectUri)} registered=${JSON.stringify(client.redirectUris)}`
157
+ );
149
158
  return c.text("Invalid redirect URI", 400);
150
159
  }
151
160
  if (codeChallengeMethod !== "S256" || !codeChallenge) {
161
+ console.warn(`Auth: /oauth/authorize missing/unsupported PKCE. method=${JSON.stringify(codeChallengeMethod)} challenge_present=${!!codeChallenge}`);
152
162
  return c.text("PKCE with S256 is required", 400);
153
163
  }
154
164
  cleanupPending();
@@ -165,6 +175,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
165
175
  code,
166
176
  createdAt: Date.now()
167
177
  });
178
+ console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);
168
179
  const csrf = randomBytes(32).toString("hex");
169
180
  csrfTokens.set(code, csrf);
170
181
  return c.html(renderPasswordPage(code, csrf));
@@ -221,6 +232,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
221
232
  app.post("/oauth/token", async (c) => {
222
233
  const body = await c.req.parseBody();
223
234
  const grantType = body["grant_type"];
235
+ console.log(`Auth: /oauth/token request grant_type=${JSON.stringify(grantType)}`);
224
236
  if (grantType === "authorization_code") {
225
237
  const code = body["code"];
226
238
  const clientId = body["client_id"];
@@ -228,22 +240,33 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
228
240
  const redirectUri = body["redirect_uri"];
229
241
  const pending = pendingAuths.get(code);
230
242
  if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {
243
+ console.warn(
244
+ `Auth: /oauth/token invalid_grant. code_known=${!!pending} expired=${pending ? Date.now() - pending.createdAt > PENDING_TTL_MS : "n/a"}`
245
+ );
231
246
  if (pending) pendingAuths.delete(code);
232
247
  return c.json({ error: "invalid_grant" }, 400);
233
248
  }
234
249
  if (clientId !== pending.clientId) {
250
+ console.warn(
251
+ `Auth: /oauth/token client_id mismatch. received=${JSON.stringify(clientId)} expected=${JSON.stringify(pending.clientId)}`
252
+ );
235
253
  return c.json({ error: "invalid_grant", error_description: "client_id mismatch" }, 400);
236
254
  }
237
255
  if (redirectUri !== pending.redirectUri) {
256
+ console.warn(
257
+ `Auth: /oauth/token redirect_uri mismatch. received=${JSON.stringify(redirectUri)} expected=${JSON.stringify(pending.redirectUri)}`
258
+ );
238
259
  return c.json({ error: "invalid_grant", error_description: "redirect_uri mismatch" }, 400);
239
260
  }
240
261
  if (pending.codeChallengeMethod === "S256") {
241
262
  const expected = createHash("sha256").update(codeVerifier).digest("base64url");
242
263
  if (expected !== pending.codeChallenge) {
264
+ console.warn("Auth: /oauth/token PKCE verification failed");
243
265
  return c.json({ error: "invalid_grant", error_description: "PKCE verification failed" }, 400);
244
266
  }
245
267
  }
246
268
  pendingAuths.delete(code);
269
+ console.log(`Auth: /oauth/token issuing access token client_id=${pending.clientId}`);
247
270
  const accessToken = randomBytes(32).toString("hex");
248
271
  const refreshToken = randomBytes(32).toString("hex");
249
272
  const record = {
@@ -267,6 +290,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
267
290
  const refreshToken = body["refresh_token"];
268
291
  const old = refreshTokens.get(refreshToken);
269
292
  if (!old) {
293
+ console.warn("Auth: /oauth/token refresh_token unknown");
270
294
  return c.json({ error: "invalid_grant" }, 400);
271
295
  }
272
296
  if (Date.now() > old.refreshExpiresAt) {
@@ -297,6 +321,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
297
321
  refresh_token: newRefreshToken
298
322
  });
299
323
  }
324
+ console.warn(`Auth: /oauth/token unsupported_grant_type=${JSON.stringify(grantType)}`);
300
325
  return c.json({ error: "unsupported_grant_type" }, 400);
301
326
  });
302
327
  return {
@@ -1087,7 +1112,7 @@ if (VAULT_PATH) {
1087
1112
  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.";
1088
1113
  var serverOptions = {
1089
1114
  name: "obsidian-sync-mcp",
1090
- version: "0.6.2",
1115
+ version: "0.6.3",
1091
1116
  instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
1092
1117
 
1093
1118
  ${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
@@ -1154,7 +1179,7 @@ server.start({
1154
1179
  transportType: "httpStream",
1155
1180
  httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
1156
1181
  });
1157
- console.log(`obsidian-sync-mcp v${"0.6.2"} listening on port ${PORT}`);
1182
+ console.log(`obsidian-sync-mcp v${"0.6.3"} listening on port ${PORT}`);
1158
1183
  process.on("unhandledRejection", (err) => {
1159
1184
  console.error("Unhandled rejection:", err);
1160
1185
  });
package/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/host-guard.ts","../src/tools.ts","../src/deeplink.ts","../src/write-scope.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { timingSafeEqual, createHash } from \"crypto\";\nimport { watch, readFileSync, statSync } from \"fs\";\nimport { stat } from \"fs/promises\";\nimport { setGlobalLogFunction, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { mountPasswordAuth } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange } from \"./index-sync.js\";\nimport { buildAllowedHosts, isHostAllowed, isOriginAllowed } from \"./host-guard.js\";\nimport { registerTools } from \"./tools.js\";\nimport { parseWriteFolders } from \"./write-scope.js\";\n\n// Suppress livesync-commonlib logs that expose vault file paths in production.\n// Set LOG_LEVEL=debug to see all library logs during development.\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\nsetGlobalLogFunction((message, level = LEVEL_INFO) => {\n if (level < LEVEL_INFO) return;\n if (!debugLogging && typeof message === \"string\") {\n if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;\n if (message.includes(\"replicator\") || message.includes(\"Replicator\") || message.includes(\"ReplicatorService\")) return;\n }\n console.log(message);\n});\n\n// --- Configuration from environment ---\nconst VAULT_PATH = process.env.VAULT_PATH; // Local mode: path to vault directory\nconst COUCHDB_URL = process.env.COUCHDB_URL;\nconst COUCHDB_USER = process.env.COUCHDB_USER ?? \"admin\";\nconst COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;\nconst COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? \"obsidian\";\nconst COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || undefined;\nconst COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === \"true\";\nconst VAULT_NAME = process.env.VAULT_NAME ?? \"MyVault\";\nconst PORT = parseInt(process.env.PORT ?? \"8787\");\nconst BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;\nconst AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;\nconst READ_ONLY = process.env.READ_ONLY === \"true\";\nconst WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);\n\n// Extra instructions appended to the MCP `instructions` string.\n// File wins if both are set (loud warning); missing file is fatal.\nconst MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || undefined;\nconst MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || undefined;\nlet MCP_EXTRA_INSTRUCTIONS: string | undefined;\nconst MCP_INSTRUCTIONS_MAX_BYTES = 32 * 1024;\nif (MCP_INSTRUCTIONS_FILE) {\n try {\n const size = statSync(MCP_INSTRUCTIONS_FILE).size;\n if (size > MCP_INSTRUCTIONS_MAX_BYTES) {\n throw new Error(`file is ${size} bytes, exceeds ${MCP_INSTRUCTIONS_MAX_BYTES} byte cap`);\n }\n MCP_EXTRA_INSTRUCTIONS = readFileSync(MCP_INSTRUCTIONS_FILE, \"utf8\").trim() || undefined;\n } catch (err) {\n console.error(`Failed to read MCP_INSTRUCTIONS_FILE (${MCP_INSTRUCTIONS_FILE}): ${(err as Error).message}`);\n process.exit(1);\n }\n if (MCP_INSTRUCTIONS_ENV) {\n console.warn(\"MCP_INSTRUCTIONS_FILE is set; ignoring MCP_INSTRUCTIONS env var.\");\n }\n} else if (MCP_INSTRUCTIONS_ENV) {\n MCP_EXTRA_INSTRUCTIONS = MCP_INSTRUCTIONS_ENV;\n}\n\n// --- Initialize vault (local or remote) ---\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nlet vault: VaultBackend;\n\nif (VAULT_PATH) {\n const { LocalVault } = await import(\"./vault-local.js\");\n vault = new LocalVault(VAULT_PATH);\n console.log(`Local mode: ${VAULT_PATH}`);\n} else if (COUCHDB_URL) {\n if (!COUCHDB_PASSWORD) {\n console.error(\"COUCHDB_PASSWORD is required in remote mode.\");\n process.exit(1);\n }\n const { Vault } = await import(\"./vault.js\");\n vault = new Vault({\n couchdbUrl: COUCHDB_URL,\n couchdbUser: COUCHDB_USER,\n couchdbPassword: COUCHDB_PASSWORD,\n database: COUCHDB_DATABASE,\n passphrase: COUCHDB_PASSPHRASE,\n obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,\n });\n console.log(`Remote mode: ${COUCHDB_URL}`);\n} else {\n console.error(\"Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.\");\n process.exit(1);\n}\n\nawait vault.init();\nconsole.log(\"Vault ready.\");\n\n// --- Per-vault data directory ---\nconst baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? \"/tmp\", \".obsidian-mcp\");\nconst vaultId = createHash(\"sha256\").update(VAULT_NAME).digest(\"hex\").slice(0, 12);\nconst dataDir = join(baseDataDir, vaultId);\n\n// --- Search index ---\nconst indexPath = join(dataDir, \"search-index.json\");\nconst searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);\n\n// Load persisted metadata from disk\nawait searchIndex.loadFromDisk();\nif (debugLogging) {\n console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || \"(none)\"}`);\n}\n\n// Sync metadata in background (server starts immediately)\nasync function rebuildIndex() {\n const start = performance.now();\n\n if (COUCHDB_URL && vault.catchUp) {\n const changeCallback = (path: string, content: string | null, mtime?: number) => {\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n\n let since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n const onBatch = async (batchSince: string, processed: number) => {\n searchIndex.since = batchSince;\n await searchIndex.saveToDisk();\n console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);\n };\n try {\n const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n changeCallback(path, content, mtime);\n };\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n } catch (err) {\n console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);\n searchIndex.clear();\n changes = 0;\n const newSince = await vault.catchUp(\"0\", (path, content, mtime) => {\n changes++;\n changeCallback(path, content, mtime);\n }, onBatch);\n searchIndex.since = newSince;\n }\n if (changes > 0) {\n console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1000).toFixed(1)}s (${searchIndex.size} notes).`);\n } else {\n console.log(`Search index up to date (${searchIndex.size} notes).`);\n }\n } else if (VAULT_PATH) {\n const notesWithMtime = await vault.listNotesWithMtime();\n if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);\n if (notesWithMtime.length > 0) {\n const vaultPaths = new Set(notesWithMtime.map((n) => n.path));\n for (const p of searchIndex.listPaths()) {\n if (!vaultPaths.has(p)) searchIndex.remove(p);\n }\n console.log(`Building search index (${notesWithMtime.length} notes)...`);\n for (let i = 0; i < notesWithMtime.length; i++) {\n const { path, mtime } = notesWithMtime[i];\n const content = await vault.readNote(path);\n // Index empty notes too (content === \"\"); readNote returns null only if absent.\n if (content !== null) searchIndex.update(path, content, mtime);\n if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {\n console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);\n }\n }\n console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1000).toFixed(1)}s`);\n }\n }\n await searchIndex.saveToDisk();\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => console.error(\"Index rebuild failed:\", err));\n\n// --- Watch for external changes ---\nlet fsWatcher: ReturnType<typeof watch> | null = null;\nif (VAULT_PATH) {\n // Local mode: watch filesystem for changes from Obsidian\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {\n if (!filename || !filename.endsWith(\".md\")) return;\n const notePath = filename.replace(/\\\\/g, \"/\");\n if (notePath.startsWith(\".obsidian/\") || notePath.includes(\"/.obsidian/\")) return;\n\n // Debounce: coalesce rapid events for the same file (Obsidian fires 2-3 per save)\n if (pending.has(notePath)) clearTimeout(pending.get(notePath)!);\n pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));\n });\n\n async function handleFileChange(notePath: string) {\n pending.delete(notePath);\n try {\n const content = await vault.readNote(notePath);\n if (content !== null) {\n const s = await stat(join(VAULT_PATH!, notePath));\n searchIndex.update(notePath, content, s.mtimeMs);\n } else {\n searchIndex.remove(notePath);\n }\n } catch {\n // File deleted or path blocked by safePath\n searchIndex.remove(notePath);\n }\n }\n console.log(\"Watching vault for external changes.\");\n} else if (COUCHDB_URL && vault.watchChanges) {\n // Remote mode: watch CouchDB _changes feed for LiveSync updates\n vault.watchChanges((path: string, content: string | null, mtime?: number, seq?: string | number) => {\n if (debugLogging) console.log(`[debug] CouchDB ${content === null ? \"delete\" : \"change\"}: ${path}`);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n if (seq) searchIndex.since = String(seq);\n });\n console.log(\"Watching CouchDB for LiveSync changes.\");\n}\n\n// --- MCP Server ---\nconst 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.\";\nconst serverOptions: ConstructorParameters<typeof FastMCP>[0] = {\n name: \"obsidian-sync-mcp\",\n version: process.env.npm_package_version ?? \"0.0.0\",\n instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}\\n\\n${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS,\n};\n\n// Auth\nimport type { AuthHandle } from \"./auth.js\";\nlet auth: AuthHandle | null = null;\n\nif (AUTH_TOKEN) {\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n const header = req.headers[\"authorization\"];\n // Accept static Bearer token (for curl, MCP Inspector, custom agents)\n const expected = `Bearer ${AUTH_TOKEN}`;\n if (header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {\n return { authenticated: true };\n }\n // Accept OAuth-issued tokens (for Claude Web/Desktop/Mobile)\n if (auth?.validateToken(header)) {\n return { authenticated: true };\n }\n // RFC 9728: point strict clients (e.g. Gemini) at the resource\n // metadata; Claude probes /.well-known directly but others rely on this.\n throw new Response(\"Unauthorized\", {\n status: 401,\n headers: { \"WWW-Authenticate\": `Bearer resource_metadata=\"${BASE_URL}/.well-known/oauth-protected-resource\"` },\n });\n };\n console.log(\"Auth enabled (password-gated OAuth).\");\n} else {\n // No token: enforce a Host-header allowlist so the \"local only\" precondition\n // actually holds. Without this, DNS rebinding lets any website the operator\n // visits reach the tool surface (CWE-350) even on a loopback bind, because\n // the browser still sends the attacker's hostname in Host. Defaults to\n // localhost; MCP_ALLOWED_HOSTS extends it for legit LAN/private-network use.\n const allowedHosts = buildAllowedHosts(process.env.MCP_ALLOWED_HOSTS);\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n // Host check defeats DNS rebinding; Origin check defeats a direct\n // cross-origin browser fetch to loopback (the transport sends wildcard CORS).\n if (!isHostAllowed(req.headers[\"host\"], allowedHosts)) {\n throw new Response(\"Forbidden: Host not allowed\", { status: 403 });\n }\n if (!isOriginAllowed(req.headers[\"origin\"], allowedHosts)) {\n throw new Response(\"Forbidden: cross-origin request rejected\", { status: 403 });\n }\n return { authenticated: true };\n };\n console.log(`Auth disabled — accepting only local Host/Origin headers: ${[...allowedHosts].join(\", \")}. Set MCP_ALLOWED_HOSTS to add hosts, or MCP_AUTH_TOKEN for authenticated remote access.`);\n const host = process.env.HOST ?? \"0.0.0.0\";\n if (host === \"0.0.0.0\") {\n console.warn(\"WARNING: No authentication and listening on all interfaces. Browser attacks (DNS rebinding and cross-origin fetch) are blocked by the Host/Origin checks, but any non-browser client that can reach this port has full vault access. Set MCP_AUTH_TOKEN, or HOST=127.0.0.1 to bind to loopback only.\");\n }\n}\n\nconst server = new FastMCP(serverOptions);\n\nif (AUTH_TOKEN) {\n const tokenPath = join(dataDir, \"auth-tokens.json\");\n auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);\n await auth.loadTokens();\n}\n\n// --- Tools ---\nregisterTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);\n\n// --- Graceful shutdown ---\nasync function shutdown() {\n console.log(\"Shutting down...\");\n if (fsWatcher) fsWatcher.close();\n await searchIndex.saveToDisk();\n if (auth) await auth.saveTokens();\n await vault.close();\n process.exit(0);\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n\n// --- Periodic save (every 5 minutes) ---\nsetInterval(async () => {\n await searchIndex.saveToDisk();\n if (auth) {\n auth.cleanup();\n await auth.saveTokens();\n }\n}, 5 * 60 * 1000).unref();\n\n// --- Start server ---\nserver.start({\n transportType: \"httpStream\",\n httpStream: { port: PORT, endpoint: \"/mcp\", host: process.env.HOST ?? \"0.0.0.0\" },\n});\nconsole.log(`obsidian-sync-mcp v${process.env.npm_package_version ?? \"unknown\"} listening on port ${PORT}`);\n\n// Prevent unhandled rejections from crashing the server (e.g. decryption failures in watcher)\nprocess.on(\"unhandledRejection\", (err) => {\n console.error(\"Unhandled rejection:\", err);\n});\n","/**\n * Password-gated OAuth provider for MCP.\n *\n * Implements a self-contained OAuth 2.1 flow:\n * - Claude connects -> gets 401 with metadata pointer\n * - Claude discovers /.well-known/oauth-protected-resource\n * - Claude registers via /oauth/register (DCR)\n * - Claude redirects user to /oauth/authorize\n * - User sees a password page, enters MCP_AUTH_TOKEN\n * - Claude exchanges code for access token via /oauth/token\n * - All subsequent requests carry Bearer token\n *\n * No external identity provider needed.\n */\n\nimport { randomUUID, randomBytes, createHash, timingSafeEqual } from \"crypto\";\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type { Hono } from \"hono\";\n\ninterface PendingAuth {\n clientId: string;\n redirectUri: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n state: string;\n code: string;\n createdAt: number;\n}\n\ninterface TokenRecord {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n expiresAt: number;\n refreshExpiresAt: number;\n}\n\ninterface RegisteredClient {\n clientId: string;\n clientSecret: string;\n redirectUris: string[];\n clientName?: string;\n createdAt?: number;\n}\n\nconst TOKEN_EXPIRY_MS = 3600 * 1000; // 1 hour\nconst DEFAULT_REFRESH_DAYS = 14;\nconst REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1000;\nconst MAX_FAILED_BEFORE_LOCKOUT = 5;\nconst BASE_LOCKOUT_MS = 5 * 1000; // 5 seconds, doubles each lockout\nconst MAX_CLIENTS = 100;\nconst MAX_PENDING = 100;\nconst PENDING_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface AuthHandle {\n validateToken: (auth: string | undefined) => boolean;\n saveTokens: () => Promise<void>;\n loadTokens: () => Promise<boolean>;\n cleanup: () => void;\n}\n\nexport function mountPasswordAuth(app: Hono, baseUrl: string, password: string, persistPath?: string): AuthHandle {\n const pendingAuths = new Map<string, PendingAuth>();\n const csrfTokens = new Map<string, string>(); // code -> csrf token\n const tokens = new Map<string, TokenRecord>();\n const refreshTokens = new Map<string, TokenRecord>();\n const clients = new Map<string, RegisteredClient>();\n\n // Cleanup expired pending auths and CSRF tokens\n function cleanupPending() {\n const now = Date.now();\n for (const [code, pending] of pendingAuths) {\n if (now - pending.createdAt > PENDING_TTL_MS) {\n pendingAuths.delete(code);\n csrfTokens.delete(code);\n }\n }\n }\n\n // Rate limiting: exponential backoff, never resets until success\n let failedAttempts = 0;\n let lockoutCount = 0;\n let lockedUntil = 0;\n\n // Persist clients + tokens. Called on every state change (not just the\n // periodic save): a restart or Fly suspend right after registration or\n // token issuance must not lose the new state.\n async function persist(): Promise<void> {\n if (!persistPath) return;\n try {\n await mkdir(dirname(persistPath), { recursive: true });\n const now = Date.now();\n const activeTokens = [...tokens.entries()].filter(([_, r]) => r.expiresAt > now);\n const activeRefresh = [...refreshTokens.entries()].filter(([_, r]) => r.refreshExpiresAt > now);\n const data = JSON.stringify({\n tokens: Object.fromEntries(activeTokens),\n refreshTokens: Object.fromEntries(activeRefresh),\n clients: Object.fromEntries(clients),\n });\n await writeFile(persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(persistPath, 0o600);\n } catch (err) {\n console.error(\"Failed to save auth tokens:\", err);\n }\n }\n\n // HTTPS warning\n if (!baseUrl.startsWith(\"https://\") && !baseUrl.includes(\"localhost\")) {\n console.warn(\"WARNING: BASE_URL is not HTTPS. OAuth tokens will be sent in cleartext. Use a tunnel (cloudflared, tailscale, ngrok) to provide TLS.\");\n }\n\n // --- Discovery endpoints ---\n\n app.get(\"/.well-known/oauth-protected-resource\", (c) => {\n return c.json({\n resource: baseUrl,\n authorization_servers: [baseUrl],\n scopes_supported: [\"mcp\"],\n });\n });\n\n app.get(\"/.well-known/oauth-authorization-server\", (c) => {\n return c.json({\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/oauth/authorize`,\n token_endpoint: `${baseUrl}/oauth/token`,\n registration_endpoint: `${baseUrl}/oauth/register`,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"client_secret_post\", \"none\"],\n scopes_supported: [\"mcp\"],\n });\n });\n\n // --- Dynamic Client Registration (RFC 7591) ---\n\n app.post(\"/oauth/register\", async (c) => {\n if (clients.size >= MAX_CLIENTS) {\n // Evict the oldest client with no live tokens to make room; only\n // reject when every slot is held by a client with active tokens.\n const activeClientIds = new Set<string>();\n for (const r of tokens.values()) activeClientIds.add(r.clientId);\n for (const r of refreshTokens.values()) activeClientIds.add(r.clientId);\n let oldest: RegisteredClient | undefined;\n for (const client of clients.values()) {\n if (activeClientIds.has(client.clientId)) continue;\n if (!oldest || (client.createdAt ?? 0) < (oldest.createdAt ?? 0)) oldest = client;\n }\n if (!oldest) {\n return c.json({ error: \"too_many_clients\" }, 429);\n }\n clients.delete(oldest.clientId);\n }\n const body = await c.req.json();\n\n // Validate redirect_uris\n const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.slice(0, 5) : [];\n if (redirectUris.length === 0) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"redirect_uris required\" }, 400);\n }\n const safeUri = (u: any) => {\n if (typeof u !== \"string\" || u.length > 2048) return false;\n const lower = u.toLowerCase();\n return !lower.startsWith(\"javascript:\") && !lower.startsWith(\"data:\") && !lower.startsWith(\"file:\");\n };\n if (redirectUris.some((u: any) => !safeUri(u))) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"invalid redirect_uri\" }, 400);\n }\n\n const clientId = randomUUID();\n const clientSecret = randomBytes(32).toString(\"hex\");\n const clientName = typeof body.client_name === \"string\" ? body.client_name.slice(0, 256) : undefined;\n\n const client: RegisteredClient = {\n clientId,\n clientSecret,\n redirectUris,\n clientName,\n createdAt: Date.now(),\n };\n clients.set(clientId, client);\n await persist();\n\n return c.json({\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uris: client.redirectUris,\n client_name: client.clientName,\n token_endpoint_auth_method: \"client_secret_post\",\n }, 201);\n });\n\n // --- Authorization endpoint ---\n\n app.get(\"/oauth/authorize\", (c) => {\n const clientId = c.req.query(\"client_id\") ?? \"\";\n const redirectUri = c.req.query(\"redirect_uri\") ?? \"\";\n const codeChallenge = c.req.query(\"code_challenge\") ?? \"\";\n const codeChallengeMethod = c.req.query(\"code_challenge_method\") ?? \"S256\";\n const state = c.req.query(\"state\") ?? \"\";\n\n // Validate redirect URI against registered client\n const client = clients.get(clientId);\n if (!client) {\n return c.text(\"Unknown client\", 400);\n }\n if (!client.redirectUris.includes(redirectUri)) {\n return c.text(\"Invalid redirect URI\", 400);\n }\n\n // Require S256 PKCE\n if (codeChallengeMethod !== \"S256\" || !codeChallenge) {\n return c.text(\"PKCE with S256 is required\", 400);\n }\n\n cleanupPending();\n if (pendingAuths.size >= MAX_PENDING) {\n return c.text(\"Too many pending authorizations\", 429);\n }\n\n const code = randomBytes(32).toString(\"hex\");\n pendingAuths.set(code, {\n clientId,\n redirectUri,\n codeChallenge,\n codeChallengeMethod,\n state,\n code,\n createdAt: Date.now(),\n });\n\n const csrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, csrf);\n return c.html(renderPasswordPage(code, csrf));\n });\n\n // --- Approval handler ---\n\n app.post(\"/oauth/approve\", async (c) => {\n const body = await c.req.parseBody();\n const code = body[\"code\"] as string;\n const submittedCsrf = body[\"csrf\"] as string;\n const submittedPassword = body[\"password\"] as string;\n\n const pending = pendingAuths.get(code);\n const expectedCsrf = csrfTokens.get(code);\n if (!pending || !expectedCsrf) {\n return c.html(\"<p>Invalid or expired authorization request.</p>\", 400);\n }\n\n // Validate CSRF token\n const csrfA = Buffer.from(submittedCsrf ?? \"\");\n const csrfB = Buffer.from(expectedCsrf);\n if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {\n return c.html(\"<p>Invalid request.</p>\", 403);\n }\n\n // Rate limiting: check lockout\n if (Date.now() < lockedUntil) {\n const waitSec = Math.ceil((lockedUntil - Date.now()) / 1000);\n console.warn(`Auth: locked out, ${waitSec}s remaining`);\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n const a = Buffer.from(submittedPassword);\n const b = Buffer.from(password);\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n failedAttempts++;\n console.warn(`Auth: failed attempt ${failedAttempts} total`);\n\n // Rotate CSRF token on each failed attempt\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n\n if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {\n lockoutCount = Math.min(lockoutCount + 1, 10);\n const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);\n lockedUntil = Date.now() + lockoutMs;\n console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1000}s`);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n console.log(\"Auth: password accepted, issuing authorization code.\");\n\n const url = new URL(pending.redirectUri);\n url.searchParams.set(\"code\", code);\n if (pending.state) url.searchParams.set(\"state\", pending.state);\n const redirectUrl = url.toString();\n\n return c.redirect(redirectUrl);\n });\n\n // --- Token endpoint ---\n\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.parseBody();\n const grantType = body[\"grant_type\"] as string;\n\n if (grantType === \"authorization_code\") {\n const code = body[\"code\"] as string;\n const clientId = body[\"client_id\"] as string;\n const codeVerifier = body[\"code_verifier\"] as string;\n const redirectUri = body[\"redirect_uri\"] as string;\n\n const pending = pendingAuths.get(code);\n if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {\n if (pending) pendingAuths.delete(code);\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Verify client_id matches the original request\n if (clientId !== pending.clientId) {\n return c.json({ error: \"invalid_grant\", error_description: \"client_id mismatch\" }, 400);\n }\n\n // Verify redirect_uri matches the original request\n if (redirectUri !== pending.redirectUri) {\n return c.json({ error: \"invalid_grant\", error_description: \"redirect_uri mismatch\" }, 400);\n }\n\n // Verify PKCE\n if (pending.codeChallengeMethod === \"S256\") {\n const expected = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed\" }, 400);\n }\n }\n\n pendingAuths.delete(code);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const refreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken,\n clientId: pending.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS,\n };\n tokens.set(accessToken, record);\n refreshTokens.set(refreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: refreshToken,\n });\n }\n\n if (grantType === \"refresh_token\") {\n const refreshToken = body[\"refresh_token\"] as string;\n const old = refreshTokens.get(refreshToken);\n if (!old) {\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Check refresh token expiry\n if (Date.now() > old.refreshExpiresAt) {\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n console.log(\"Auth: refresh token expired, user must re-authenticate.\");\n return c.json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" }, 400);\n }\n\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const newRefreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken: newRefreshToken,\n clientId: old.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: old.refreshExpiresAt, // keep original expiry\n };\n tokens.set(accessToken, record);\n refreshTokens.set(newRefreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: newRefreshToken,\n });\n }\n\n return c.json({ error: \"unsupported_grant_type\" }, 400);\n });\n\n return {\n validateToken(authHeader: string | undefined): boolean {\n if (!authHeader?.startsWith(\"Bearer \")) return false;\n const token = authHeader.slice(7);\n const record = tokens.get(token);\n if (!record) return false;\n if (Date.now() > record.expiresAt) {\n tokens.delete(token);\n return false;\n }\n return true;\n },\n\n async saveTokens(): Promise<void> {\n await persist();\n },\n\n cleanup(): void {\n const now = Date.now();\n for (const [k, r] of tokens) { if (r.expiresAt <= now) tokens.delete(k); }\n for (const [k, r] of refreshTokens) { if (r.refreshExpiresAt <= now) refreshTokens.delete(k); }\n // Registered clients are NOT evicted here: AI clients cache their\n // client_id indefinitely and retry it after token expiry, so\n // dropping a registration means \"Unknown client\" until the user\n // deletes and re-adds the connector (issue #13). The clients map\n // is bounded at registration time instead.\n },\n\n async loadTokens(): Promise<boolean> {\n if (!persistPath) return false;\n try {\n const raw = await readFile(persistPath, \"utf-8\");\n const data = JSON.parse(raw);\n const now = Date.now();\n for (const [k, v] of Object.entries(data.tokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.clients ?? {})) {\n const client = v as RegisteredClient;\n if (client.clientId && client.redirectUris) clients.set(k, client);\n }\n console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);\n return tokens.size > 0;\n } catch {\n return false;\n }\n },\n };\n}\n\nfunction renderPasswordPage(code: string, csrf: string, error?: string): string {\n return `<!DOCTYPE html>\n<html><head><title>Obsidian Sync MCP - Authorize</title>\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'\">\n<style>\n body { font-family: system-ui; max-width: 400px; margin: 80px auto; padding: 0 20px; }\n h1 { font-size: 1.3em; }\n input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }\n button { padding: 10px 20px; font-size: 1em; cursor: pointer; }\n .error { color: red; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n ${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>\"}\n <form method=\"POST\" action=\"/oauth/approve\" autocomplete=\"on\">\n <input type=\"hidden\" name=\"code\" value=\"${code.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\")}\">\n <input type=\"hidden\" name=\"csrf\" value=\"${csrf.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\")}\">\n <input type=\"text\" name=\"username\" id=\"username\" value=\"obsidian-sync-mcp\" autocomplete=\"username\" style=\"position:absolute;opacity:0;width:1px;height:1px;pointer-events:none\">\n <input type=\"password\" name=\"password\" id=\"password\" placeholder=\"Password\" autocomplete=\"current-password\" autofocus required>\n <br><button type=\"submit\">Authorize</button>\n </form>\n</body></html>`;\n}\n","/**\n * Metadata index for vault notes.\n *\n * Tracks paths, mtimes, tags, links, and backlinks.\n * Persists to disk (encrypted if passphrase is set).\n * No full-text search — metadata only.\n */\n\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from \"crypto\";\nimport { parseFrontmatterAndLinks } from \"./parse.js\";\n\n\nfunction encrypt(text: string, passphrase: string): string {\n const salt = randomBytes(16);\n const key = scryptSync(passphrase, salt, 32);\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const encrypted = Buffer.concat([cipher.update(text, \"utf-8\"), cipher.final()]);\n const tag = (cipher as any).getAuthTag() as Buffer;\n return salt.toString(\"hex\") + \":\" + iv.toString(\"hex\") + \":\" + tag.toString(\"hex\") + \":\" + encrypted.toString(\"hex\");\n}\n\nfunction decrypt(data: string, passphrase: string): string {\n const [saltHex, ivHex, tagHex, encryptedHex] = data.split(\":\");\n const key = scryptSync(passphrase, Buffer.from(saltHex, \"hex\"), 32);\n const decipher = createDecipheriv(\"aes-256-gcm\", key, Buffer.from(ivHex, \"hex\"));\n (decipher as any).setAuthTag(Buffer.from(tagHex, \"hex\"));\n return Buffer.concat([decipher.update(Buffer.from(encryptedHex, \"hex\")), decipher.final()]).toString(\"utf-8\");\n}\n\nexport class SearchIndex {\n private mtimes = new Map<string, number>();\n private tags = new Map<string, string[]>();\n private links = new Map<string, string[]>();\n private backlinks = new Map<string, Set<string>>();\n private knownPaths = new Set<string>();\n private saving = false;\n private _since: string = \"\";\n private persistPath: string | null;\n private passphrase: string | null;\n\n constructor(persistPath?: string, passphrase?: string) {\n this.persistPath = persistPath ?? null;\n this.passphrase = passphrase ?? null;\n }\n\n /** Load metadata from disk. */\n async loadFromDisk(): Promise<boolean> {\n if (!this.persistPath) return false;\n try {\n let raw = await readFile(this.persistPath, \"utf-8\");\n if (this.passphrase) {\n raw = decrypt(raw, this.passphrase);\n }\n const data = JSON.parse(raw);\n for (const [path, mtime] of Object.entries(data.mtimes ?? {})) {\n this.mtimes.set(path, mtime as number);\n this.knownPaths.add(path);\n }\n for (const [path, t] of Object.entries(data.tags ?? {})) {\n this.tags.set(path, t as string[]);\n }\n for (const [path, l] of Object.entries(data.links ?? {})) {\n const targets = l as string[];\n this.links.set(path, targets);\n for (const target of targets) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n }\n if (data.since) this._since = data.since;\n console.log(`Search metadata loaded from disk (${this.knownPaths.size} notes, since: ${this._since ? \"yes\" : \"none\"}).`);\n return this.knownPaths.size > 0;\n } catch {\n return false;\n }\n }\n\n /** Save metadata to disk. Encrypted if passphrase is set. */\n async saveToDisk(): Promise<void> {\n if (!this.persistPath || this.saving) return;\n this.saving = true;\n try {\n await mkdir(dirname(this.persistPath), { recursive: true });\n let data = JSON.stringify({\n mtimes: Object.fromEntries(this.mtimes),\n tags: Object.fromEntries(this.tags),\n links: Object.fromEntries(this.links),\n since: this._since,\n });\n if (this.passphrase) {\n data = encrypt(data, this.passphrase);\n }\n await writeFile(this.persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(this.persistPath, 0o600);\n console.log(`Search index saved to disk (${this.knownPaths.size} notes${this.passphrase ? \", encrypted\" : \"\"}).`);\n } catch (err) {\n console.error(\"Failed to save search index:\", err);\n } finally {\n this.saving = false;\n }\n }\n\n /** Add or update a note in the index. */\n update(path: string, content: string, mtime?: number): void {\n if (this.knownPaths.has(path)) {\n this.clearBacklinks(path);\n }\n this.knownPaths.add(path);\n if (mtime !== undefined) this.mtimes.set(path, mtime);\n const parsed = parseFrontmatterAndLinks(content);\n if (parsed.tags.length > 0) {\n this.tags.set(path, parsed.tags);\n } else {\n this.tags.delete(path);\n }\n if (parsed.links.length > 0) {\n this.links.set(path, parsed.links);\n for (const target of parsed.links) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n } else {\n this.links.delete(path);\n }\n }\n\n /** Remove a note from the index. */\n remove(path: string): void {\n if (this.knownPaths.has(path)) {\n this.knownPaths.delete(path);\n this.mtimes.delete(path);\n this.tags.delete(path);\n this.clearBacklinks(path);\n }\n }\n\n /** Remove all backlink entries where path is the source. */\n private clearBacklinks(path: string): void {\n const oldLinks = this.links.get(path);\n if (oldLinks) {\n for (const target of oldLinks) {\n const key = target.toLowerCase();\n this.backlinks.get(key)?.delete(path);\n if (this.backlinks.get(key)?.size === 0) this.backlinks.delete(key);\n }\n }\n this.links.delete(path);\n }\n\n /** List all indexed paths, optionally filtered by folder prefix. */\n listPaths(folder?: string): string[] {\n return this.listWithMtime(folder).map((n) => n.path);\n }\n\n /** List all indexed paths with mtimes, optionally filtered by folder prefix. */\n listWithMtime(folder?: string): Array<{ path: string; mtime: number }> {\n const prefix = folder && !folder.endsWith(\"/\") ? folder + \"/\" : folder;\n const entries = [...this.knownPaths]\n .filter((p) => p.endsWith(\".md\"))\n .filter((p) => !prefix || p.startsWith(prefix))\n .map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));\n return entries.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n /** Get mtime for a path. */\n getMtime(path: string): number {\n return this.mtimes.get(path) ?? 0;\n }\n\n /** Get tags for a path. */\n getTags(path: string): string[] {\n return this.tags.get(path) ?? [];\n }\n\n /** Get outgoing links for a path. */\n getLinks(path: string): string[] {\n return this.links.get(path) ?? [];\n }\n\n /** Get backlinks for a path (notes that link to it). Case-insensitive, matches by full path or filename. */\n getBacklinks(path: string): string[] {\n const results = new Set<string>();\n const withMd = (path.endsWith(\".md\") ? path : path + \".md\").toLowerCase();\n const withoutMd = (path.endsWith(\".md\") ? path.slice(0, -3) : path).toLowerCase();\n const nameOnly = withoutMd.includes(\"/\") ? withoutMd.slice(withoutMd.lastIndexOf(\"/\") + 1) : withoutMd;\n\n for (const target of [withMd, withoutMd, nameOnly]) {\n const sources = this.backlinks.get(target);\n if (sources) {\n for (const s of sources) results.add(s);\n }\n }\n return [...results].sort();\n }\n\n /** List all tags across the vault with counts. */\n listAllTags(): Array<{ tag: string; count: number }> {\n const counts = new Map<string, number>();\n for (const tags of this.tags.values()) {\n for (const t of tags) {\n counts.set(t, (counts.get(t) ?? 0) + 1);\n }\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((a, b) => b.count - a.count);\n }\n\n /** Clear all index data (for full rebuild after DB nuke). */\n clear(): void {\n const paths = Array.from(this.knownPaths);\n for (const p of paths) this.remove(p);\n this._since = \"\";\n }\n\n get since(): string {\n return this._since;\n }\n\n set since(value: string) {\n this._since = value;\n }\n\n get size(): number {\n return this.knownPaths.size;\n }\n}\n","/**\n * Host-header allowlisting to defeat DNS-rebinding attacks (CWE-350).\n *\n * When the server runs without MCP_AUTH_TOKEN (\"local only\" mode), a malicious\n * web page the operator visits can use DNS rebinding to point its hostname at\n * 127.0.0.1 and reach the MCP endpoint from the browser. Binding to loopback\n * does NOT help — the OS resolves the attacker hostname to loopback while the\n * page keeps its origin. The browser still sends the attacker's hostname in the\n * `Host` header, so validating Host against a localhost allowlist rejects the\n * rebound request. A bearer token (auth mode) already defeats this, since a\n * browser won't attach it; this guard protects the no-token path.\n *\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nconst LOCAL_HOSTS = [\"localhost\", \"127.0.0.1\", \"::1\"];\n\n/** Extract a normalized, lowercased hostname from a raw `Host` header (strips port and IPv6 brackets). */\nexport function parseHostname(hostHeader: string | undefined | null): string | null {\n if (!hostHeader) return null;\n // A real Host header is a bare host[:port]. Reject anything carrying userinfo\n // or a path (e.g. \"attacker.example@127.0.0.1\", \"127.0.0.1/x\") so a crafted\n // value can't normalize into the allowlist.\n if (hostHeader.includes(\"@\") || hostHeader.includes(\"/\")) return null;\n try {\n // Wrapping in a URL parses `host:port` and `[ipv6]:port` correctly.\n const u = new URL(`http://${hostHeader}`);\n if (u.username || u.password || u.pathname !== \"/\" || u.search || u.hash) return null;\n return u.hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** Build the set of allowed hostnames: always localhost, plus any from a comma-separated list. */\nexport function buildAllowedHosts(extra?: string): Set<string> {\n const set = new Set(LOCAL_HOSTS);\n for (const entry of (extra ?? \"\").split(\",\").map((s) => s.trim()).filter(Boolean)) {\n set.add(parseHostname(entry) ?? entry.toLowerCase());\n }\n return set;\n}\n\n/** True if the request's Host header resolves to an allowed hostname. Missing/malformed Host is rejected. */\nexport function isHostAllowed(hostHeader: string | undefined | null, allowed: Set<string>): boolean {\n const hostname = parseHostname(hostHeader);\n return hostname !== null && allowed.has(hostname);\n}\n\n/**\n * True if the request has no browser `Origin`, or its Origin host is allowlisted.\n *\n * Host validation alone is not enough: the transport answers with a wildcard\n * `Access-Control-Allow-Origin: *`, so a page at any origin can skip DNS\n * rebinding and directly `fetch('http://127.0.0.1:<port>/mcp')` — that request\n * carries a genuine loopback Host (passes isHostAllowed) but an attacker Origin.\n * Non-browser MCP clients (CLI, desktop apps) send no Origin, so requiring\n * \"no Origin, or an allowlisted Origin\" blocks cross-origin browsers without\n * affecting legitimate local callers.\n */\nexport function isOriginAllowed(originHeader: string | undefined | null, allowed: Set<string>): boolean {\n if (!originHeader) return true; // non-browser client — no Origin header\n try {\n const hostname = new URL(originHeader).hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n return allowed.has(hostname);\n } catch {\n return false; // \"null\"/opaque or malformed Origin — reject\n }\n}\n","import type { FastMCP } from \"fastmcp\";\nimport { z } from \"zod\";\nimport { makeDeepLink } from \"./deeplink.js\";\nimport type { VaultBackend } from \"./vault-backend.js\";\nimport type { SearchIndex } from \"./search.js\";\nimport { isPathWritable } from \"./write-scope.js\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\nexport function registerTools(\n server: FastMCP,\n vault: VaultBackend,\n searchIndex: SearchIndex,\n vaultName: string,\n readOnly = false,\n writeFolders: string[] | null = null,\n) {\n if (readOnly) {\n console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(\", \")}).`);\n } else if (writeFolders) {\n console.log(`WRITE_FOLDERS: writes restricted to ${writeFolders.map((f) => f + \"/\").join(\", \")}.`);\n }\n const writeScopeNote = writeFolders\n ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + \"/\").join(\", \")}.`\n : \"\";\n const denyWrite = (path: string) =>\n `Write access denied: '${path}' is outside the writable folders (${writeFolders!.map((f) => f + \"/\").join(\", \")}).`;\n const _addTool = server.addTool.bind(server);\n server.addTool = (tool: any) => {\n const original = tool.execute;\n tool.execute = async (args: any, ctx: any) => {\n if (debugLogging) console.log(`[tool] ${tool.name}(${JSON.stringify(args)})`);\n const start = performance.now();\n const result = await original(args, ctx);\n if (debugLogging) console.log(`[tool] ${tool.name} → ${((performance.now() - start)).toFixed(0)}ms`);\n return result;\n };\n return _addTool(tool);\n };\n server.addTool({\n name: \"read_note\",\n description:\n \"Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n }),\n execute: async ({ path }) => {\n const content = await vault.readNote(path);\n if (content === null) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n return `[Open in Obsidian](${deepLink})\\n\\n---\\n\\n${content}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"write_note\",\n description:\n \"Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does — read first if you need to preserve existing content.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n content: z.string().describe(\"Full markdown content for the note\"),\n }),\n execute: async ({ path, content }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.writeNote(path, content);\n if (!ok) {\n return `Failed to write note: ${path}`;\n }\n searchIndex.update(path, content, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note saved: ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"list_notes\",\n description: \"List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(name='meeting') to find notes by name. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.\",\n parameters: z.object({\n folder: z\n .string()\n .optional()\n .describe(\"Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes.\"),\n name: z\n .string()\n .optional()\n .describe(\"Filter by name (case-insensitive substring match on path), e.g. 'meeting' or 'project-x'.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags.\"),\n sort_by: z\n .enum([\"name\", \"modified\"])\n .optional()\n .describe(\"Sort order: 'name' (default) or 'modified' (most recent first).\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'.\"),\n limit: z.coerce\n .number()\n .optional()\n .describe(\"Max number of notes to return. Default 100.\"),\n }),\n execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {\n // Use search index (works with encrypted vaults), fall back to vault\n let notes = searchIndex.listWithMtime(folder);\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n }\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n }\n if (modified_after) {\n const cutoff = new Date(modified_after).getTime();\n if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n notes = notes.filter((n) => n.mtime >= cutoff);\n }\n if (notes.length === 0) {\n return folder ? `No notes found in folder: ${folder}` : \"Vault is empty.\";\n }\n if (sort_by === \"modified\") {\n notes.sort((a, b) => b.mtime - a.mtime);\n }\n const cap = limit ?? 100;\n const total = notes.length;\n const capped = notes.slice(0, cap);\n const lines = capped.map((n) => {\n const deepLink = makeDeepLink(vaultName, n.path);\n const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : \"\";\n return `- ${date} [${n.path}](${deepLink})`;\n });\n if (total > cap) {\n lines.push(`\\n... and ${total - cap} more. Use a folder filter or limit to narrow results.`);\n }\n return lines.join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_folders\",\n description:\n \"List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.\",\n parameters: z.object({}),\n execute: async () => {\n let paths = searchIndex.listPaths();\n if (paths.length === 0) {\n paths = await vault.listNotes();\n }\n const folders = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n folders.set(\"(root)\", (folders.get(\"(root)\") ?? 0) + 1);\n } else {\n const folder = p.slice(0, lastSlash);\n folders.set(folder, (folders.get(folder) ?? 0) + 1);\n // Ensure all parent folders appear in the list\n let parent = folder;\n while (parent.includes(\"/\")) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n if (!folders.has(parent)) folders.set(parent, 0);\n }\n }\n }\n if (folders.size === 0) {\n return \"Vault is empty.\";\n }\n const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));\n return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_tags\",\n description:\n \"List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes.\",\n parameters: z.object({}),\n execute: async () => {\n const tags = searchIndex.listAllTags();\n if (tags.length === 0) {\n return \"No tags found in the vault.\";\n }\n return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join(\"\\n\");\n },\n });\n\n\n\n if (!readOnly) server.addTool({\n name: \"edit_note\",\n description:\n \"Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-25.md'\"),\n content: z.string().describe(\"Text to append, prepend, or use as replacement for old_text\"),\n operation: z\n .enum([\"append\", \"prepend\", \"replace\"])\n .optional()\n .describe(\"'append' (default): add to end. 'prepend': add after frontmatter. 'replace': swap old_text with content.\"),\n old_text: z\n .string()\n .optional()\n .describe(\"Required for replace operation. Exact text to find and replace. Must match exactly once.\"),\n }),\n execute: async ({ path, content: newContent, operation, old_text }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const existing = await vault.readNote(path);\n if (existing === null) {\n return `Note not found: ${path}`;\n }\n\n let updated: string;\n const op = operation ?? \"append\";\n\n if (op === \"replace\") {\n if (!old_text) {\n return \"old_text is required for replace operation.\";\n }\n const idx = existing.indexOf(old_text);\n if (idx === -1) {\n return \"old_text not found in note.\";\n }\n if (existing.indexOf(old_text, idx + 1) !== -1) {\n return \"old_text matches multiple times. Provide a longer, unique string.\";\n }\n updated = existing.slice(0, idx) + newContent + existing.slice(idx + old_text.length);\n } else if (op === \"prepend\") {\n // Insert after frontmatter if present\n const fmMatch = existing.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n/);\n if (fmMatch) {\n const afterFm = fmMatch[0].length;\n updated = existing.slice(0, afterFm) + newContent + \"\\n\" + existing.slice(afterFm);\n } else {\n updated = newContent + \"\\n\" + existing;\n }\n } else {\n // append\n updated = existing.endsWith(\"\\n\") ? existing + newContent : existing + \"\\n\" + newContent;\n }\n\n const ok = await vault.writeNote(path, updated);\n if (!ok) {\n return `Failed to edit note: ${path}`;\n }\n searchIndex.update(path, updated, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note edited (${op}): ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"delete_note\",\n description: \"Delete a note from the Obsidian vault.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note to delete\"),\n }),\n execute: async ({ path }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.deleteNote(path);\n if (ok) searchIndex.remove(path);\n return ok ? `Deleted: ${path}` : `Failed to delete: ${path}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"move_note\",\n description:\n \"Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically.\" + writeScopeNote,\n parameters: z.object({\n from: z.string().describe(\"Current path, e.g. 'daily/old-name.md'\"),\n to: z.string().describe(\"New path, e.g. 'projects/new-name.md'\"),\n }),\n execute: async ({ from, to }) => {\n // Moving out of a folder deletes there; moving in writes there — both ends must be writable.\n if (!isPathWritable(from, writeFolders)) return denyWrite(from);\n if (!isPathWritable(to, writeFolders)) return denyWrite(to);\n const content = await vault.readNote(from);\n const ok = await vault.moveNote(from, to);\n if (!ok) {\n return `Failed to move: ${from} → ${to}`;\n }\n searchIndex.remove(from);\n // content === \"\" is an empty-but-present note: keep it indexed at the new path.\n if (content !== null) searchIndex.update(to, content, Date.now());\n const deepLink = makeDeepLink(vaultName, to);\n return `Moved: ${from} → ${to}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"get_note_metadata\",\n description:\n \"Get metadata about a note without reading its full content. Returns frontmatter, tags, outgoing links, backlinks (notes that link to this one), size, and timestamps. Use this to navigate the knowledge graph.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'projects/my-project.md'\"),\n }),\n execute: async ({ path }) => {\n const meta = await vault.getMetadata(path);\n if (!meta) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n const lines = [\n `**${path}**`,\n `Size: ${meta.size} bytes`,\n `Created: ${new Date(meta.ctime).toISOString()}`,\n `Modified: ${new Date(meta.mtime).toISOString()}`,\n ];\n if (Object.keys(meta.frontmatter).length > 0) {\n lines.push(`\\nFrontmatter:`);\n for (const [k, v] of Object.entries(meta.frontmatter)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n if (meta.tags.length > 0) {\n lines.push(`\\nTags: ${meta.tags.map((t) => `#${t}`).join(\", \")}`);\n }\n if (meta.links.length > 0) {\n lines.push(`\\nOutgoing links: ${meta.links.join(\", \")}`);\n }\n const backlinks = searchIndex.getBacklinks(path);\n if (backlinks.length > 0) {\n lines.push(`\\nBacklinks: ${backlinks.join(\", \")}`);\n }\n lines.push(`\\n[Open in Obsidian](${deepLink})`);\n return lines.join(\"\\n\");\n },\n });\n}\n","/**\n * Generate Obsidian deep links for notes.\n * Works on Mac and iOS: obsidian://open?vault=<name>&file=<path>\n */\nexport function makeDeepLink(vaultName: string, notePath: string): string {\n const cleanPath = notePath.replace(/\\.md$/, \"\");\n const encodedVault = encodeURIComponent(vaultName);\n const encodedPath = encodeURIComponent(cleanPath);\n return `obsidian://open?vault=${encodedVault}&file=${encodedPath}`;\n}\n","// Folder-scoped write access (WRITE_FOLDERS env var).\n// When set, write tools only accept paths inside the listed vault-relative folders.\n\n/** Parse the WRITE_FOLDERS env var into a normalized folder list, or null for unrestricted. */\nexport function parseWriteFolders(raw: string | undefined): string[] | null {\n if (raw === undefined) return null;\n const folders = raw\n .split(\",\")\n .map((f) => f.trim().replace(/^\\/+|\\/+$/g, \"\"))\n .filter(Boolean);\n return folders.length > 0 ? folders : null;\n}\n\n/**\n * Check whether a vault-relative path falls inside one of the writable folders.\n * Matching is case-sensitive and folder-boundary-aware (\"MCP\" matches \"MCP/x.md\",\n * not \"MCP-private/x.md\"). A null folder list means writes are unrestricted.\n */\nexport function isPathWritable(path: string, writeFolders: string[] | null): boolean {\n if (writeFolders === null) return true;\n const normalized = path.replace(/^\\/+/, \"\");\n // Backends reject traversal too; deny here so the scope check can't be reasoned around.\n // Split on backslash as well: on Windows \"MCP/..\\x\" resolves as traversal.\n if (normalized.split(/[/\\\\]/).includes(\"..\")) return false;\n return writeFolders.some((folder) => normalized.startsWith(folder + \"/\"));\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,mBAAAA,kBAAiB,cAAAC,mBAAkB;AAC5C,SAAS,OAAO,cAAc,gBAAgB;AAC9C,SAAS,YAAY;AACrB,SAAS,sBAAsB,kBAAkB;;;ACUjD,SAAS,YAAY,aAAa,YAAY,uBAAuB;AACrE,SAAS,UAAU,WAAW,OAAO,aAAa;AAClD,SAAS,eAAe;AA6BxB,IAAM,kBAAkB,OAAO;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB,SAAS,QAAQ,IAAI,oBAAoB,OAAO,oBAAoB,CAAC,KAAK,wBAAwB,KAAK,OAAO;AACzI,IAAM,4BAA4B;AAClC,IAAM,kBAAkB,IAAI;AAC5B,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,iBAAiB,KAAK,KAAK;AAS1B,SAAS,kBAAkB,KAAW,SAAiB,UAAkB,aAAkC;AAC9G,QAAM,eAAe,oBAAI,IAAyB;AAClD,QAAM,aAAa,oBAAI,IAAoB;AAC3C,QAAM,SAAS,oBAAI,IAAyB;AAC5C,QAAM,gBAAgB,oBAAI,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;AAC9B,MAAI,UAAW,WAAU,MAAM;AAC/B,QAAM,YAAY,WAAW;AAC7B,MAAI,KAAM,OAAM,KAAK,WAAW;AAChC,QAAM,MAAM,MAAM;AAClB,UAAQ,KAAK,CAAC;AAClB;AACA,QAAQ,GAAG,WAAW,QAAQ;AAC9B,QAAQ,GAAG,UAAU,QAAQ;AAG7B,YAAY,YAAY;AACpB,QAAM,YAAY,WAAW;AAC7B,MAAI,MAAM;AACN,SAAK,QAAQ;AACb,UAAM,KAAK,WAAW;AAAA,EAC1B;AACJ,GAAG,IAAI,KAAK,GAAI,EAAE,MAAM;AAGxB,OAAO,MAAM;AAAA,EACT,eAAe;AAAA,EACf,YAAY,EAAE,MAAM,MAAM,UAAU,QAAQ,MAAM,QAAQ,IAAI,QAAQ,UAAU;AACpF,CAAC;AACD,QAAQ,IAAI,sBAAsB,OAA4C,sBAAsB,IAAI,EAAE;AAG1G,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACtC,UAAQ,MAAM,wBAAwB,GAAG;AAC7C,CAAC;","names":["timingSafeEqual","createHash","client","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","server","vault","searchIndex","debugLogging","createHash","timingSafeEqual"]}
1
+ {"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/host-guard.ts","../src/tools.ts","../src/deeplink.ts","../src/write-scope.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { timingSafeEqual, createHash } from \"crypto\";\nimport { watch, readFileSync, statSync } from \"fs\";\nimport { stat } from \"fs/promises\";\nimport { setGlobalLogFunction, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { mountPasswordAuth } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange } from \"./index-sync.js\";\nimport { buildAllowedHosts, isHostAllowed, isOriginAllowed } from \"./host-guard.js\";\nimport { registerTools } from \"./tools.js\";\nimport { parseWriteFolders } from \"./write-scope.js\";\n\n// Suppress livesync-commonlib logs that expose vault file paths in production.\n// Set LOG_LEVEL=debug to see all library logs during development.\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\nsetGlobalLogFunction((message, level = LEVEL_INFO) => {\n if (level < LEVEL_INFO) return;\n if (!debugLogging && typeof message === \"string\") {\n if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;\n if (message.includes(\"replicator\") || message.includes(\"Replicator\") || message.includes(\"ReplicatorService\")) return;\n }\n console.log(message);\n});\n\n// --- Configuration from environment ---\nconst VAULT_PATH = process.env.VAULT_PATH; // Local mode: path to vault directory\nconst COUCHDB_URL = process.env.COUCHDB_URL;\nconst COUCHDB_USER = process.env.COUCHDB_USER ?? \"admin\";\nconst COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;\nconst COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? \"obsidian\";\nconst COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || undefined;\nconst COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === \"true\";\nconst VAULT_NAME = process.env.VAULT_NAME ?? \"MyVault\";\nconst PORT = parseInt(process.env.PORT ?? \"8787\");\nconst BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;\nconst AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;\nconst READ_ONLY = process.env.READ_ONLY === \"true\";\nconst WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);\n\n// Extra instructions appended to the MCP `instructions` string.\n// File wins if both are set (loud warning); missing file is fatal.\nconst MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || undefined;\nconst MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || undefined;\nlet MCP_EXTRA_INSTRUCTIONS: string | undefined;\nconst MCP_INSTRUCTIONS_MAX_BYTES = 32 * 1024;\nif (MCP_INSTRUCTIONS_FILE) {\n try {\n const size = statSync(MCP_INSTRUCTIONS_FILE).size;\n if (size > MCP_INSTRUCTIONS_MAX_BYTES) {\n throw new Error(`file is ${size} bytes, exceeds ${MCP_INSTRUCTIONS_MAX_BYTES} byte cap`);\n }\n MCP_EXTRA_INSTRUCTIONS = readFileSync(MCP_INSTRUCTIONS_FILE, \"utf8\").trim() || undefined;\n } catch (err) {\n console.error(`Failed to read MCP_INSTRUCTIONS_FILE (${MCP_INSTRUCTIONS_FILE}): ${(err as Error).message}`);\n process.exit(1);\n }\n if (MCP_INSTRUCTIONS_ENV) {\n console.warn(\"MCP_INSTRUCTIONS_FILE is set; ignoring MCP_INSTRUCTIONS env var.\");\n }\n} else if (MCP_INSTRUCTIONS_ENV) {\n MCP_EXTRA_INSTRUCTIONS = MCP_INSTRUCTIONS_ENV;\n}\n\n// --- Initialize vault (local or remote) ---\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nlet vault: VaultBackend;\n\nif (VAULT_PATH) {\n const { LocalVault } = await import(\"./vault-local.js\");\n vault = new LocalVault(VAULT_PATH);\n console.log(`Local mode: ${VAULT_PATH}`);\n} else if (COUCHDB_URL) {\n if (!COUCHDB_PASSWORD) {\n console.error(\"COUCHDB_PASSWORD is required in remote mode.\");\n process.exit(1);\n }\n const { Vault } = await import(\"./vault.js\");\n vault = new Vault({\n couchdbUrl: COUCHDB_URL,\n couchdbUser: COUCHDB_USER,\n couchdbPassword: COUCHDB_PASSWORD,\n database: COUCHDB_DATABASE,\n passphrase: COUCHDB_PASSPHRASE,\n obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,\n });\n console.log(`Remote mode: ${COUCHDB_URL}`);\n} else {\n console.error(\"Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.\");\n process.exit(1);\n}\n\nawait vault.init();\nconsole.log(\"Vault ready.\");\n\n// --- Per-vault data directory ---\nconst baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? \"/tmp\", \".obsidian-mcp\");\nconst vaultId = createHash(\"sha256\").update(VAULT_NAME).digest(\"hex\").slice(0, 12);\nconst dataDir = join(baseDataDir, vaultId);\n\n// --- Search index ---\nconst indexPath = join(dataDir, \"search-index.json\");\nconst searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);\n\n// Load persisted metadata from disk\nawait searchIndex.loadFromDisk();\nif (debugLogging) {\n console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || \"(none)\"}`);\n}\n\n// Sync metadata in background (server starts immediately)\nasync function rebuildIndex() {\n const start = performance.now();\n\n if (COUCHDB_URL && vault.catchUp) {\n const changeCallback = (path: string, content: string | null, mtime?: number) => {\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n\n let since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n const onBatch = async (batchSince: string, processed: number) => {\n searchIndex.since = batchSince;\n await searchIndex.saveToDisk();\n console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);\n };\n try {\n const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n changeCallback(path, content, mtime);\n };\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n } catch (err) {\n console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);\n searchIndex.clear();\n changes = 0;\n const newSince = await vault.catchUp(\"0\", (path, content, mtime) => {\n changes++;\n changeCallback(path, content, mtime);\n }, onBatch);\n searchIndex.since = newSince;\n }\n if (changes > 0) {\n console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1000).toFixed(1)}s (${searchIndex.size} notes).`);\n } else {\n console.log(`Search index up to date (${searchIndex.size} notes).`);\n }\n } else if (VAULT_PATH) {\n const notesWithMtime = await vault.listNotesWithMtime();\n if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);\n if (notesWithMtime.length > 0) {\n const vaultPaths = new Set(notesWithMtime.map((n) => n.path));\n for (const p of searchIndex.listPaths()) {\n if (!vaultPaths.has(p)) searchIndex.remove(p);\n }\n console.log(`Building search index (${notesWithMtime.length} notes)...`);\n for (let i = 0; i < notesWithMtime.length; i++) {\n const { path, mtime } = notesWithMtime[i];\n const content = await vault.readNote(path);\n // Index empty notes too (content === \"\"); readNote returns null only if absent.\n if (content !== null) searchIndex.update(path, content, mtime);\n if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {\n console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);\n }\n }\n console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1000).toFixed(1)}s`);\n }\n }\n await searchIndex.saveToDisk();\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => console.error(\"Index rebuild failed:\", err));\n\n// --- Watch for external changes ---\nlet fsWatcher: ReturnType<typeof watch> | null = null;\nif (VAULT_PATH) {\n // Local mode: watch filesystem for changes from Obsidian\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {\n if (!filename || !filename.endsWith(\".md\")) return;\n const notePath = filename.replace(/\\\\/g, \"/\");\n if (notePath.startsWith(\".obsidian/\") || notePath.includes(\"/.obsidian/\")) return;\n\n // Debounce: coalesce rapid events for the same file (Obsidian fires 2-3 per save)\n if (pending.has(notePath)) clearTimeout(pending.get(notePath)!);\n pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));\n });\n\n async function handleFileChange(notePath: string) {\n pending.delete(notePath);\n try {\n const content = await vault.readNote(notePath);\n if (content !== null) {\n const s = await stat(join(VAULT_PATH!, notePath));\n searchIndex.update(notePath, content, s.mtimeMs);\n } else {\n searchIndex.remove(notePath);\n }\n } catch {\n // File deleted or path blocked by safePath\n searchIndex.remove(notePath);\n }\n }\n console.log(\"Watching vault for external changes.\");\n} else if (COUCHDB_URL && vault.watchChanges) {\n // Remote mode: watch CouchDB _changes feed for LiveSync updates\n vault.watchChanges((path: string, content: string | null, mtime?: number, seq?: string | number) => {\n if (debugLogging) console.log(`[debug] CouchDB ${content === null ? \"delete\" : \"change\"}: ${path}`);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n if (seq) searchIndex.since = String(seq);\n });\n console.log(\"Watching CouchDB for LiveSync changes.\");\n}\n\n// --- MCP Server ---\nconst 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.\";\nconst serverOptions: ConstructorParameters<typeof FastMCP>[0] = {\n name: \"obsidian-sync-mcp\",\n version: process.env.npm_package_version ?? \"0.0.0\",\n instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}\\n\\n${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS,\n};\n\n// Auth\nimport type { AuthHandle } from \"./auth.js\";\nlet auth: AuthHandle | null = null;\n\nif (AUTH_TOKEN) {\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n const header = req.headers[\"authorization\"];\n // Accept static Bearer token (for curl, MCP Inspector, custom agents)\n const expected = `Bearer ${AUTH_TOKEN}`;\n if (header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {\n return { authenticated: true };\n }\n // Accept OAuth-issued tokens (for Claude Web/Desktop/Mobile)\n if (auth?.validateToken(header)) {\n return { authenticated: true };\n }\n // RFC 9728: point strict clients (e.g. Gemini) at the resource\n // metadata; Claude probes /.well-known directly but others rely on this.\n throw new Response(\"Unauthorized\", {\n status: 401,\n headers: { \"WWW-Authenticate\": `Bearer resource_metadata=\"${BASE_URL}/.well-known/oauth-protected-resource\"` },\n });\n };\n console.log(\"Auth enabled (password-gated OAuth).\");\n} else {\n // No token: enforce a Host-header allowlist so the \"local only\" precondition\n // actually holds. Without this, DNS rebinding lets any website the operator\n // visits reach the tool surface (CWE-350) even on a loopback bind, because\n // the browser still sends the attacker's hostname in Host. Defaults to\n // localhost; MCP_ALLOWED_HOSTS extends it for legit LAN/private-network use.\n const allowedHosts = buildAllowedHosts(process.env.MCP_ALLOWED_HOSTS);\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n // Host check defeats DNS rebinding; Origin check defeats a direct\n // cross-origin browser fetch to loopback (the transport sends wildcard CORS).\n if (!isHostAllowed(req.headers[\"host\"], allowedHosts)) {\n throw new Response(\"Forbidden: Host not allowed\", { status: 403 });\n }\n if (!isOriginAllowed(req.headers[\"origin\"], allowedHosts)) {\n throw new Response(\"Forbidden: cross-origin request rejected\", { status: 403 });\n }\n return { authenticated: true };\n };\n console.log(`Auth disabled — accepting only local Host/Origin headers: ${[...allowedHosts].join(\", \")}. Set MCP_ALLOWED_HOSTS to add hosts, or MCP_AUTH_TOKEN for authenticated remote access.`);\n const host = process.env.HOST ?? \"0.0.0.0\";\n if (host === \"0.0.0.0\") {\n console.warn(\"WARNING: No authentication and listening on all interfaces. Browser attacks (DNS rebinding and cross-origin fetch) are blocked by the Host/Origin checks, but any non-browser client that can reach this port has full vault access. Set MCP_AUTH_TOKEN, or HOST=127.0.0.1 to bind to loopback only.\");\n }\n}\n\nconst server = new FastMCP(serverOptions);\n\nif (AUTH_TOKEN) {\n const tokenPath = join(dataDir, \"auth-tokens.json\");\n auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);\n await auth.loadTokens();\n}\n\n// --- Tools ---\nregisterTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);\n\n// --- Graceful shutdown ---\nasync function shutdown() {\n console.log(\"Shutting down...\");\n if (fsWatcher) fsWatcher.close();\n await searchIndex.saveToDisk();\n if (auth) await auth.saveTokens();\n await vault.close();\n process.exit(0);\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n\n// --- Periodic save (every 5 minutes) ---\nsetInterval(async () => {\n await searchIndex.saveToDisk();\n if (auth) {\n auth.cleanup();\n await auth.saveTokens();\n }\n}, 5 * 60 * 1000).unref();\n\n// --- Start server ---\nserver.start({\n transportType: \"httpStream\",\n httpStream: { port: PORT, endpoint: \"/mcp\", host: process.env.HOST ?? \"0.0.0.0\" },\n});\nconsole.log(`obsidian-sync-mcp v${process.env.npm_package_version ?? \"unknown\"} listening on port ${PORT}`);\n\n// Prevent unhandled rejections from crashing the server (e.g. decryption failures in watcher)\nprocess.on(\"unhandledRejection\", (err) => {\n console.error(\"Unhandled rejection:\", err);\n});\n","/**\n * Password-gated OAuth provider for MCP.\n *\n * Implements a self-contained OAuth 2.1 flow:\n * - Claude connects -> gets 401 with metadata pointer\n * - Claude discovers /.well-known/oauth-protected-resource\n * - Claude registers via /oauth/register (DCR)\n * - Claude redirects user to /oauth/authorize\n * - User sees a password page, enters MCP_AUTH_TOKEN\n * - Claude exchanges code for access token via /oauth/token\n * - All subsequent requests carry Bearer token\n *\n * No external identity provider needed.\n */\n\nimport { randomUUID, randomBytes, createHash, timingSafeEqual } from \"crypto\";\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type { Hono } from \"hono\";\n\ninterface PendingAuth {\n clientId: string;\n redirectUri: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n state: string;\n code: string;\n createdAt: number;\n}\n\ninterface TokenRecord {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n expiresAt: number;\n refreshExpiresAt: number;\n}\n\ninterface RegisteredClient {\n clientId: string;\n clientSecret?: string;\n tokenEndpointAuthMethod: \"client_secret_post\" | \"none\";\n redirectUris: string[];\n clientName?: string;\n createdAt?: number;\n}\n\nconst TOKEN_EXPIRY_MS = 3600 * 1000; // 1 hour\nconst DEFAULT_REFRESH_DAYS = 14;\nconst REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1000;\nconst MAX_FAILED_BEFORE_LOCKOUT = 5;\nconst BASE_LOCKOUT_MS = 5 * 1000; // 5 seconds, doubles each lockout\nconst MAX_CLIENTS = 100;\nconst MAX_PENDING = 100;\nconst PENDING_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface AuthHandle {\n validateToken: (auth: string | undefined) => boolean;\n saveTokens: () => Promise<void>;\n loadTokens: () => Promise<boolean>;\n cleanup: () => void;\n}\n\nexport function mountPasswordAuth(app: Hono, baseUrl: string, password: string, persistPath?: string): AuthHandle {\n const pendingAuths = new Map<string, PendingAuth>();\n const csrfTokens = new Map<string, string>(); // code -> csrf token\n const tokens = new Map<string, TokenRecord>();\n const refreshTokens = new Map<string, TokenRecord>();\n const clients = new Map<string, RegisteredClient>();\n\n // Cleanup expired pending auths and CSRF tokens\n function cleanupPending() {\n const now = Date.now();\n for (const [code, pending] of pendingAuths) {\n if (now - pending.createdAt > PENDING_TTL_MS) {\n pendingAuths.delete(code);\n csrfTokens.delete(code);\n }\n }\n }\n\n // Rate limiting: exponential backoff, never resets until success\n let failedAttempts = 0;\n let lockoutCount = 0;\n let lockedUntil = 0;\n\n // Persist clients + tokens. Called on every state change (not just the\n // periodic save): a restart or Fly suspend right after registration or\n // token issuance must not lose the new state.\n async function persist(): Promise<void> {\n if (!persistPath) return;\n try {\n await mkdir(dirname(persistPath), { recursive: true });\n const now = Date.now();\n const activeTokens = [...tokens.entries()].filter(([, r]) => r.expiresAt > now);\n const activeRefresh = [...refreshTokens.entries()].filter(([, r]) => r.refreshExpiresAt > now);\n const data = JSON.stringify({\n tokens: Object.fromEntries(activeTokens),\n refreshTokens: Object.fromEntries(activeRefresh),\n clients: Object.fromEntries(clients),\n });\n await writeFile(persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(persistPath, 0o600);\n } catch (err) {\n console.error(\"Failed to save auth tokens:\", err);\n }\n }\n\n // HTTPS warning\n if (!baseUrl.startsWith(\"https://\") && !baseUrl.includes(\"localhost\")) {\n console.warn(\"WARNING: BASE_URL is not HTTPS. OAuth tokens will be sent in cleartext. Use a tunnel (cloudflared, tailscale, ngrok) to provide TLS.\");\n }\n\n // --- Discovery endpoints ---\n\n app.get(\"/.well-known/oauth-protected-resource\", (c) => {\n return c.json({\n resource: baseUrl,\n authorization_servers: [baseUrl],\n scopes_supported: [\"mcp\"],\n });\n });\n\n app.get(\"/.well-known/oauth-authorization-server\", (c) => {\n return c.json({\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/oauth/authorize`,\n token_endpoint: `${baseUrl}/oauth/token`,\n registration_endpoint: `${baseUrl}/oauth/register`,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"client_secret_post\", \"none\"],\n scopes_supported: [\"mcp\"],\n });\n });\n\n // --- Dynamic Client Registration (RFC 7591) ---\n\n app.post(\"/oauth/register\", async (c) => {\n if (clients.size >= MAX_CLIENTS) {\n // Evict the oldest client with no live tokens to make room; only\n // reject when every slot is held by a client with active tokens.\n const activeClientIds = new Set<string>();\n for (const r of tokens.values()) activeClientIds.add(r.clientId);\n for (const r of refreshTokens.values()) activeClientIds.add(r.clientId);\n let oldest: RegisteredClient | undefined;\n for (const client of clients.values()) {\n if (activeClientIds.has(client.clientId)) continue;\n if (!oldest || (client.createdAt ?? 0) < (oldest.createdAt ?? 0)) oldest = client;\n }\n if (!oldest) {\n return c.json({ error: \"too_many_clients\" }, 429);\n }\n clients.delete(oldest.clientId);\n }\n const body = await c.req.json();\n\n // Validate redirect_uris\n const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.slice(0, 5) : [];\n if (redirectUris.length === 0) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"redirect_uris required\" }, 400);\n }\n const safeUri = (u: any) => {\n if (typeof u !== \"string\" || u.length > 2048) return false;\n const lower = u.toLowerCase();\n return !lower.startsWith(\"javascript:\") && !lower.startsWith(\"data:\") && !lower.startsWith(\"file:\");\n };\n if (redirectUris.some((u: any) => !safeUri(u))) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"invalid redirect_uri\" }, 400);\n }\n\n const clientId = randomUUID();\n // Honor the client's requested auth method (RFC 7591 §2). Only\n // \"client_secret_post\" and \"none\" are advertised as supported, so\n // anything else falls back to the confidential-client default rather\n // than silently registering a method we don't understand.\n const tokenEndpointAuthMethod: \"client_secret_post\" | \"none\" =\n body.token_endpoint_auth_method === \"none\" ? \"none\" : \"client_secret_post\";\n const clientSecret = tokenEndpointAuthMethod === \"none\" ? undefined : randomBytes(32).toString(\"hex\");\n const clientName = typeof body.client_name === \"string\" ? body.client_name.slice(0, 256) : undefined;\n\n const client: RegisteredClient = {\n clientId,\n clientSecret,\n tokenEndpointAuthMethod,\n redirectUris,\n clientName,\n createdAt: Date.now(),\n };\n clients.set(clientId, client);\n await persist();\n\n console.log(\n `Auth: registered client_id=${clientId} redirect_uris=${JSON.stringify(redirectUris)} ` +\n `requested_auth_method=${JSON.stringify(body.token_endpoint_auth_method ?? \"(unspecified)\")} (responding with ${tokenEndpointAuthMethod})`\n );\n\n return c.json({\n client_id: clientId,\n ...(clientSecret ? { client_secret: clientSecret } : {}),\n redirect_uris: client.redirectUris,\n client_name: client.clientName,\n token_endpoint_auth_method: tokenEndpointAuthMethod,\n }, 201);\n });\n\n // --- Authorization endpoint ---\n\n app.get(\"/oauth/authorize\", (c) => {\n const clientId = c.req.query(\"client_id\") ?? \"\";\n const redirectUri = c.req.query(\"redirect_uri\") ?? \"\";\n const codeChallenge = c.req.query(\"code_challenge\") ?? \"\";\n const codeChallengeMethod = c.req.query(\"code_challenge_method\") ?? \"S256\";\n const state = c.req.query(\"state\") ?? \"\";\n\n // Validate redirect URI against registered client\n const client = clients.get(clientId);\n if (!client) {\n console.warn(`Auth: /oauth/authorize unknown client_id=${JSON.stringify(clientId)}`);\n return c.text(\"Unknown client\", 400);\n }\n if (!client.redirectUris.includes(redirectUri)) {\n console.warn(\n `Auth: /oauth/authorize redirect_uri mismatch. received=${JSON.stringify(redirectUri)} ` +\n `registered=${JSON.stringify(client.redirectUris)}`\n );\n return c.text(\"Invalid redirect URI\", 400);\n }\n\n // Require S256 PKCE\n if (codeChallengeMethod !== \"S256\" || !codeChallenge) {\n console.warn(`Auth: /oauth/authorize missing/unsupported PKCE. method=${JSON.stringify(codeChallengeMethod)} challenge_present=${!!codeChallenge}`);\n return c.text(\"PKCE with S256 is required\", 400);\n }\n\n cleanupPending();\n if (pendingAuths.size >= MAX_PENDING) {\n return c.text(\"Too many pending authorizations\", 429);\n }\n\n const code = randomBytes(32).toString(\"hex\");\n pendingAuths.set(code, {\n clientId,\n redirectUri,\n codeChallenge,\n codeChallengeMethod,\n state,\n code,\n createdAt: Date.now(),\n });\n\n console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);\n\n const csrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, csrf);\n return c.html(renderPasswordPage(code, csrf));\n });\n\n // --- Approval handler ---\n\n app.post(\"/oauth/approve\", async (c) => {\n const body = await c.req.parseBody();\n const code = body[\"code\"] as string;\n const submittedCsrf = body[\"csrf\"] as string;\n const submittedPassword = body[\"password\"] as string;\n\n const pending = pendingAuths.get(code);\n const expectedCsrf = csrfTokens.get(code);\n if (!pending || !expectedCsrf) {\n return c.html(\"<p>Invalid or expired authorization request.</p>\", 400);\n }\n\n // Validate CSRF token\n const csrfA = Buffer.from(submittedCsrf ?? \"\");\n const csrfB = Buffer.from(expectedCsrf);\n if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {\n return c.html(\"<p>Invalid request.</p>\", 403);\n }\n\n // Rate limiting: check lockout\n if (Date.now() < lockedUntil) {\n const waitSec = Math.ceil((lockedUntil - Date.now()) / 1000);\n console.warn(`Auth: locked out, ${waitSec}s remaining`);\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n const a = Buffer.from(submittedPassword);\n const b = Buffer.from(password);\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n failedAttempts++;\n console.warn(`Auth: failed attempt ${failedAttempts} total`);\n\n // Rotate CSRF token on each failed attempt\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n\n if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {\n lockoutCount = Math.min(lockoutCount + 1, 10);\n const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);\n lockedUntil = Date.now() + lockoutMs;\n console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1000}s`);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n console.log(\"Auth: password accepted, issuing authorization code.\");\n\n const url = new URL(pending.redirectUri);\n url.searchParams.set(\"code\", code);\n if (pending.state) url.searchParams.set(\"state\", pending.state);\n const redirectUrl = url.toString();\n\n return c.redirect(redirectUrl);\n });\n\n // --- Token endpoint ---\n\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.parseBody();\n const grantType = body[\"grant_type\"] as string;\n console.log(`Auth: /oauth/token request grant_type=${JSON.stringify(grantType)}`);\n\n if (grantType === \"authorization_code\") {\n const code = body[\"code\"] as string;\n const clientId = body[\"client_id\"] as string;\n const codeVerifier = body[\"code_verifier\"] as string;\n const redirectUri = body[\"redirect_uri\"] as string;\n\n const pending = pendingAuths.get(code);\n if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {\n console.warn(\n `Auth: /oauth/token invalid_grant. code_known=${!!pending} ` +\n `expired=${pending ? Date.now() - pending.createdAt > PENDING_TTL_MS : \"n/a\"}`\n );\n if (pending) pendingAuths.delete(code);\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Verify client_id matches the original request\n if (clientId !== pending.clientId) {\n console.warn(\n `Auth: /oauth/token client_id mismatch. received=${JSON.stringify(clientId)} expected=${JSON.stringify(pending.clientId)}`\n );\n return c.json({ error: \"invalid_grant\", error_description: \"client_id mismatch\" }, 400);\n }\n\n // Verify redirect_uri matches the original request\n if (redirectUri !== pending.redirectUri) {\n console.warn(\n `Auth: /oauth/token redirect_uri mismatch. received=${JSON.stringify(redirectUri)} expected=${JSON.stringify(pending.redirectUri)}`\n );\n return c.json({ error: \"invalid_grant\", error_description: \"redirect_uri mismatch\" }, 400);\n }\n\n // Verify PKCE\n if (pending.codeChallengeMethod === \"S256\") {\n const expected = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n console.warn(\"Auth: /oauth/token PKCE verification failed\");\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed\" }, 400);\n }\n }\n\n pendingAuths.delete(code);\n console.log(`Auth: /oauth/token issuing access token client_id=${pending.clientId}`);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const refreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken,\n clientId: pending.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS,\n };\n tokens.set(accessToken, record);\n refreshTokens.set(refreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: refreshToken,\n });\n }\n\n if (grantType === \"refresh_token\") {\n const refreshToken = body[\"refresh_token\"] as string;\n const old = refreshTokens.get(refreshToken);\n if (!old) {\n console.warn(\"Auth: /oauth/token refresh_token unknown\");\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Check refresh token expiry\n if (Date.now() > old.refreshExpiresAt) {\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n console.log(\"Auth: refresh token expired, user must re-authenticate.\");\n return c.json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" }, 400);\n }\n\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const newRefreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken: newRefreshToken,\n clientId: old.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: old.refreshExpiresAt, // keep original expiry\n };\n tokens.set(accessToken, record);\n refreshTokens.set(newRefreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: newRefreshToken,\n });\n }\n\n console.warn(`Auth: /oauth/token unsupported_grant_type=${JSON.stringify(grantType)}`);\n return c.json({ error: \"unsupported_grant_type\" }, 400);\n });\n\n return {\n validateToken(authHeader: string | undefined): boolean {\n if (!authHeader?.startsWith(\"Bearer \")) return false;\n const token = authHeader.slice(7);\n const record = tokens.get(token);\n if (!record) return false;\n if (Date.now() > record.expiresAt) {\n tokens.delete(token);\n return false;\n }\n return true;\n },\n\n async saveTokens(): Promise<void> {\n await persist();\n },\n\n cleanup(): void {\n const now = Date.now();\n for (const [k, r] of tokens) { if (r.expiresAt <= now) tokens.delete(k); }\n for (const [k, r] of refreshTokens) { if (r.refreshExpiresAt <= now) refreshTokens.delete(k); }\n // Registered clients are NOT evicted here: AI clients cache their\n // client_id indefinitely and retry it after token expiry, so\n // dropping a registration means \"Unknown client\" until the user\n // deletes and re-adds the connector (issue #13). The clients map\n // is bounded at registration time instead.\n },\n\n async loadTokens(): Promise<boolean> {\n if (!persistPath) return false;\n try {\n const raw = await readFile(persistPath, \"utf-8\");\n const data = JSON.parse(raw);\n const now = Date.now();\n for (const [k, v] of Object.entries(data.tokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.clients ?? {})) {\n const client = v as RegisteredClient;\n if (client.clientId && client.redirectUris) clients.set(k, client);\n }\n console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);\n return tokens.size > 0;\n } catch {\n return false;\n }\n },\n };\n}\n\nfunction renderPasswordPage(code: string, csrf: string, error?: string): string {\n return `<!DOCTYPE html>\n<html><head><title>Obsidian Sync MCP - Authorize</title>\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'\">\n<style>\n body { font-family: system-ui; max-width: 400px; margin: 80px auto; padding: 0 20px; }\n h1 { font-size: 1.3em; }\n input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }\n button { padding: 10px 20px; font-size: 1em; cursor: pointer; }\n .error { color: red; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n ${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>\"}\n <form method=\"POST\" action=\"/oauth/approve\" autocomplete=\"on\">\n <input type=\"hidden\" name=\"code\" value=\"${code.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\")}\">\n <input type=\"hidden\" name=\"csrf\" value=\"${csrf.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\")}\">\n <input type=\"text\" name=\"username\" id=\"username\" value=\"obsidian-sync-mcp\" autocomplete=\"username\" style=\"position:absolute;opacity:0;width:1px;height:1px;pointer-events:none\">\n <input type=\"password\" name=\"password\" id=\"password\" placeholder=\"Password\" autocomplete=\"current-password\" autofocus required>\n <br><button type=\"submit\">Authorize</button>\n </form>\n</body></html>`;\n}\n","/**\n * Metadata index for vault notes.\n *\n * Tracks paths, mtimes, tags, links, and backlinks.\n * Persists to disk (encrypted if passphrase is set).\n * No full-text search — metadata only.\n */\n\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from \"crypto\";\nimport { parseFrontmatterAndLinks } from \"./parse.js\";\n\n\nfunction encrypt(text: string, passphrase: string): string {\n const salt = randomBytes(16);\n const key = scryptSync(passphrase, salt, 32);\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const encrypted = Buffer.concat([cipher.update(text, \"utf-8\"), cipher.final()]);\n const tag = (cipher as any).getAuthTag() as Buffer;\n return salt.toString(\"hex\") + \":\" + iv.toString(\"hex\") + \":\" + tag.toString(\"hex\") + \":\" + encrypted.toString(\"hex\");\n}\n\nfunction decrypt(data: string, passphrase: string): string {\n const [saltHex, ivHex, tagHex, encryptedHex] = data.split(\":\");\n const key = scryptSync(passphrase, Buffer.from(saltHex, \"hex\"), 32);\n const decipher = createDecipheriv(\"aes-256-gcm\", key, Buffer.from(ivHex, \"hex\"));\n (decipher as any).setAuthTag(Buffer.from(tagHex, \"hex\"));\n return Buffer.concat([decipher.update(Buffer.from(encryptedHex, \"hex\")), decipher.final()]).toString(\"utf-8\");\n}\n\nexport class SearchIndex {\n private mtimes = new Map<string, number>();\n private tags = new Map<string, string[]>();\n private links = new Map<string, string[]>();\n private backlinks = new Map<string, Set<string>>();\n private knownPaths = new Set<string>();\n private saving = false;\n private _since: string = \"\";\n private persistPath: string | null;\n private passphrase: string | null;\n\n constructor(persistPath?: string, passphrase?: string) {\n this.persistPath = persistPath ?? null;\n this.passphrase = passphrase ?? null;\n }\n\n /** Load metadata from disk. */\n async loadFromDisk(): Promise<boolean> {\n if (!this.persistPath) return false;\n try {\n let raw = await readFile(this.persistPath, \"utf-8\");\n if (this.passphrase) {\n raw = decrypt(raw, this.passphrase);\n }\n const data = JSON.parse(raw);\n for (const [path, mtime] of Object.entries(data.mtimes ?? {})) {\n this.mtimes.set(path, mtime as number);\n this.knownPaths.add(path);\n }\n for (const [path, t] of Object.entries(data.tags ?? {})) {\n this.tags.set(path, t as string[]);\n }\n for (const [path, l] of Object.entries(data.links ?? {})) {\n const targets = l as string[];\n this.links.set(path, targets);\n for (const target of targets) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n }\n if (data.since) this._since = data.since;\n console.log(`Search metadata loaded from disk (${this.knownPaths.size} notes, since: ${this._since ? \"yes\" : \"none\"}).`);\n return this.knownPaths.size > 0;\n } catch {\n return false;\n }\n }\n\n /** Save metadata to disk. Encrypted if passphrase is set. */\n async saveToDisk(): Promise<void> {\n if (!this.persistPath || this.saving) return;\n this.saving = true;\n try {\n await mkdir(dirname(this.persistPath), { recursive: true });\n let data = JSON.stringify({\n mtimes: Object.fromEntries(this.mtimes),\n tags: Object.fromEntries(this.tags),\n links: Object.fromEntries(this.links),\n since: this._since,\n });\n if (this.passphrase) {\n data = encrypt(data, this.passphrase);\n }\n await writeFile(this.persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(this.persistPath, 0o600);\n console.log(`Search index saved to disk (${this.knownPaths.size} notes${this.passphrase ? \", encrypted\" : \"\"}).`);\n } catch (err) {\n console.error(\"Failed to save search index:\", err);\n } finally {\n this.saving = false;\n }\n }\n\n /** Add or update a note in the index. */\n update(path: string, content: string, mtime?: number): void {\n if (this.knownPaths.has(path)) {\n this.clearBacklinks(path);\n }\n this.knownPaths.add(path);\n if (mtime !== undefined) this.mtimes.set(path, mtime);\n const parsed = parseFrontmatterAndLinks(content);\n if (parsed.tags.length > 0) {\n this.tags.set(path, parsed.tags);\n } else {\n this.tags.delete(path);\n }\n if (parsed.links.length > 0) {\n this.links.set(path, parsed.links);\n for (const target of parsed.links) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n } else {\n this.links.delete(path);\n }\n }\n\n /** Remove a note from the index. */\n remove(path: string): void {\n if (this.knownPaths.has(path)) {\n this.knownPaths.delete(path);\n this.mtimes.delete(path);\n this.tags.delete(path);\n this.clearBacklinks(path);\n }\n }\n\n /** Remove all backlink entries where path is the source. */\n private clearBacklinks(path: string): void {\n const oldLinks = this.links.get(path);\n if (oldLinks) {\n for (const target of oldLinks) {\n const key = target.toLowerCase();\n this.backlinks.get(key)?.delete(path);\n if (this.backlinks.get(key)?.size === 0) this.backlinks.delete(key);\n }\n }\n this.links.delete(path);\n }\n\n /** List all indexed paths, optionally filtered by folder prefix. */\n listPaths(folder?: string): string[] {\n return this.listWithMtime(folder).map((n) => n.path);\n }\n\n /** List all indexed paths with mtimes, optionally filtered by folder prefix. */\n listWithMtime(folder?: string): Array<{ path: string; mtime: number }> {\n const prefix = folder && !folder.endsWith(\"/\") ? folder + \"/\" : folder;\n const entries = [...this.knownPaths]\n .filter((p) => p.endsWith(\".md\"))\n .filter((p) => !prefix || p.startsWith(prefix))\n .map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));\n return entries.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n /** Get mtime for a path. */\n getMtime(path: string): number {\n return this.mtimes.get(path) ?? 0;\n }\n\n /** Get tags for a path. */\n getTags(path: string): string[] {\n return this.tags.get(path) ?? [];\n }\n\n /** Get outgoing links for a path. */\n getLinks(path: string): string[] {\n return this.links.get(path) ?? [];\n }\n\n /** Get backlinks for a path (notes that link to it). Case-insensitive, matches by full path or filename. */\n getBacklinks(path: string): string[] {\n const results = new Set<string>();\n const withMd = (path.endsWith(\".md\") ? path : path + \".md\").toLowerCase();\n const withoutMd = (path.endsWith(\".md\") ? path.slice(0, -3) : path).toLowerCase();\n const nameOnly = withoutMd.includes(\"/\") ? withoutMd.slice(withoutMd.lastIndexOf(\"/\") + 1) : withoutMd;\n\n for (const target of [withMd, withoutMd, nameOnly]) {\n const sources = this.backlinks.get(target);\n if (sources) {\n for (const s of sources) results.add(s);\n }\n }\n return [...results].sort();\n }\n\n /** List all tags across the vault with counts. */\n listAllTags(): Array<{ tag: string; count: number }> {\n const counts = new Map<string, number>();\n for (const tags of this.tags.values()) {\n for (const t of tags) {\n counts.set(t, (counts.get(t) ?? 0) + 1);\n }\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((a, b) => b.count - a.count);\n }\n\n /** Clear all index data (for full rebuild after DB nuke). */\n clear(): void {\n const paths = Array.from(this.knownPaths);\n for (const p of paths) this.remove(p);\n this._since = \"\";\n }\n\n get since(): string {\n return this._since;\n }\n\n set since(value: string) {\n this._since = value;\n }\n\n get size(): number {\n return this.knownPaths.size;\n }\n}\n","/**\n * Host-header allowlisting to defeat DNS-rebinding attacks (CWE-350).\n *\n * When the server runs without MCP_AUTH_TOKEN (\"local only\" mode), a malicious\n * web page the operator visits can use DNS rebinding to point its hostname at\n * 127.0.0.1 and reach the MCP endpoint from the browser. Binding to loopback\n * does NOT help — the OS resolves the attacker hostname to loopback while the\n * page keeps its origin. The browser still sends the attacker's hostname in the\n * `Host` header, so validating Host against a localhost allowlist rejects the\n * rebound request. A bearer token (auth mode) already defeats this, since a\n * browser won't attach it; this guard protects the no-token path.\n *\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nconst LOCAL_HOSTS = [\"localhost\", \"127.0.0.1\", \"::1\"];\n\n/** Extract a normalized, lowercased hostname from a raw `Host` header (strips port and IPv6 brackets). */\nexport function parseHostname(hostHeader: string | undefined | null): string | null {\n if (!hostHeader) return null;\n // A real Host header is a bare host[:port]. Reject anything carrying userinfo\n // or a path (e.g. \"attacker.example@127.0.0.1\", \"127.0.0.1/x\") so a crafted\n // value can't normalize into the allowlist.\n if (hostHeader.includes(\"@\") || hostHeader.includes(\"/\")) return null;\n try {\n // Wrapping in a URL parses `host:port` and `[ipv6]:port` correctly.\n const u = new URL(`http://${hostHeader}`);\n if (u.username || u.password || u.pathname !== \"/\" || u.search || u.hash) return null;\n return u.hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** Build the set of allowed hostnames: always localhost, plus any from a comma-separated list. */\nexport function buildAllowedHosts(extra?: string): Set<string> {\n const set = new Set(LOCAL_HOSTS);\n for (const entry of (extra ?? \"\").split(\",\").map((s) => s.trim()).filter(Boolean)) {\n set.add(parseHostname(entry) ?? entry.toLowerCase());\n }\n return set;\n}\n\n/** True if the request's Host header resolves to an allowed hostname. Missing/malformed Host is rejected. */\nexport function isHostAllowed(hostHeader: string | undefined | null, allowed: Set<string>): boolean {\n const hostname = parseHostname(hostHeader);\n return hostname !== null && allowed.has(hostname);\n}\n\n/**\n * True if the request has no browser `Origin`, or its Origin host is allowlisted.\n *\n * Host validation alone is not enough: the transport answers with a wildcard\n * `Access-Control-Allow-Origin: *`, so a page at any origin can skip DNS\n * rebinding and directly `fetch('http://127.0.0.1:<port>/mcp')` — that request\n * carries a genuine loopback Host (passes isHostAllowed) but an attacker Origin.\n * Non-browser MCP clients (CLI, desktop apps) send no Origin, so requiring\n * \"no Origin, or an allowlisted Origin\" blocks cross-origin browsers without\n * affecting legitimate local callers.\n */\nexport function isOriginAllowed(originHeader: string | undefined | null, allowed: Set<string>): boolean {\n if (!originHeader) return true; // non-browser client — no Origin header\n try {\n const hostname = new URL(originHeader).hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n return allowed.has(hostname);\n } catch {\n return false; // \"null\"/opaque or malformed Origin — reject\n }\n}\n","import type { FastMCP } from \"fastmcp\";\nimport { z } from \"zod\";\nimport { makeDeepLink } from \"./deeplink.js\";\nimport type { VaultBackend } from \"./vault-backend.js\";\nimport type { SearchIndex } from \"./search.js\";\nimport { isPathWritable } from \"./write-scope.js\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\nexport function registerTools(\n server: FastMCP,\n vault: VaultBackend,\n searchIndex: SearchIndex,\n vaultName: string,\n readOnly = false,\n writeFolders: string[] | null = null,\n) {\n if (readOnly) {\n console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(\", \")}).`);\n } else if (writeFolders) {\n console.log(`WRITE_FOLDERS: writes restricted to ${writeFolders.map((f) => f + \"/\").join(\", \")}.`);\n }\n const writeScopeNote = writeFolders\n ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + \"/\").join(\", \")}.`\n : \"\";\n const denyWrite = (path: string) =>\n `Write access denied: '${path}' is outside the writable folders (${writeFolders!.map((f) => f + \"/\").join(\", \")}).`;\n const _addTool = server.addTool.bind(server);\n server.addTool = (tool: any) => {\n const original = tool.execute;\n tool.execute = async (args: any, ctx: any) => {\n if (debugLogging) console.log(`[tool] ${tool.name}(${JSON.stringify(args)})`);\n const start = performance.now();\n const result = await original(args, ctx);\n if (debugLogging) console.log(`[tool] ${tool.name} → ${((performance.now() - start)).toFixed(0)}ms`);\n return result;\n };\n return _addTool(tool);\n };\n server.addTool({\n name: \"read_note\",\n description:\n \"Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n }),\n execute: async ({ path }) => {\n const content = await vault.readNote(path);\n if (content === null) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n return `[Open in Obsidian](${deepLink})\\n\\n---\\n\\n${content}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"write_note\",\n description:\n \"Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does — read first if you need to preserve existing content.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n content: z.string().describe(\"Full markdown content for the note\"),\n }),\n execute: async ({ path, content }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.writeNote(path, content);\n if (!ok) {\n return `Failed to write note: ${path}`;\n }\n searchIndex.update(path, content, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note saved: ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"list_notes\",\n description: \"List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(name='meeting') to find notes by name. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.\",\n parameters: z.object({\n folder: z\n .string()\n .optional()\n .describe(\"Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes.\"),\n name: z\n .string()\n .optional()\n .describe(\"Filter by name (case-insensitive substring match on path), e.g. 'meeting' or 'project-x'.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags.\"),\n sort_by: z\n .enum([\"name\", \"modified\"])\n .optional()\n .describe(\"Sort order: 'name' (default) or 'modified' (most recent first).\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'.\"),\n limit: z.coerce\n .number()\n .optional()\n .describe(\"Max number of notes to return. Default 100.\"),\n }),\n execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {\n // Use search index (works with encrypted vaults), fall back to vault\n let notes = searchIndex.listWithMtime(folder);\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n }\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n }\n if (modified_after) {\n const cutoff = new Date(modified_after).getTime();\n if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n notes = notes.filter((n) => n.mtime >= cutoff);\n }\n if (notes.length === 0) {\n return folder ? `No notes found in folder: ${folder}` : \"Vault is empty.\";\n }\n if (sort_by === \"modified\") {\n notes.sort((a, b) => b.mtime - a.mtime);\n }\n const cap = limit ?? 100;\n const total = notes.length;\n const capped = notes.slice(0, cap);\n const lines = capped.map((n) => {\n const deepLink = makeDeepLink(vaultName, n.path);\n const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : \"\";\n return `- ${date} [${n.path}](${deepLink})`;\n });\n if (total > cap) {\n lines.push(`\\n... and ${total - cap} more. Use a folder filter or limit to narrow results.`);\n }\n return lines.join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_folders\",\n description:\n \"List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.\",\n parameters: z.object({}),\n execute: async () => {\n let paths = searchIndex.listPaths();\n if (paths.length === 0) {\n paths = await vault.listNotes();\n }\n const folders = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n folders.set(\"(root)\", (folders.get(\"(root)\") ?? 0) + 1);\n } else {\n const folder = p.slice(0, lastSlash);\n folders.set(folder, (folders.get(folder) ?? 0) + 1);\n // Ensure all parent folders appear in the list\n let parent = folder;\n while (parent.includes(\"/\")) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n if (!folders.has(parent)) folders.set(parent, 0);\n }\n }\n }\n if (folders.size === 0) {\n return \"Vault is empty.\";\n }\n const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));\n return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_tags\",\n description:\n \"List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes.\",\n parameters: z.object({}),\n execute: async () => {\n const tags = searchIndex.listAllTags();\n if (tags.length === 0) {\n return \"No tags found in the vault.\";\n }\n return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join(\"\\n\");\n },\n });\n\n\n\n if (!readOnly) server.addTool({\n name: \"edit_note\",\n description:\n \"Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-25.md'\"),\n content: z.string().describe(\"Text to append, prepend, or use as replacement for old_text\"),\n operation: z\n .enum([\"append\", \"prepend\", \"replace\"])\n .optional()\n .describe(\"'append' (default): add to end. 'prepend': add after frontmatter. 'replace': swap old_text with content.\"),\n old_text: z\n .string()\n .optional()\n .describe(\"Required for replace operation. Exact text to find and replace. Must match exactly once.\"),\n }),\n execute: async ({ path, content: newContent, operation, old_text }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const existing = await vault.readNote(path);\n if (existing === null) {\n return `Note not found: ${path}`;\n }\n\n let updated: string;\n const op = operation ?? \"append\";\n\n if (op === \"replace\") {\n if (!old_text) {\n return \"old_text is required for replace operation.\";\n }\n const idx = existing.indexOf(old_text);\n if (idx === -1) {\n return \"old_text not found in note.\";\n }\n if (existing.indexOf(old_text, idx + 1) !== -1) {\n return \"old_text matches multiple times. Provide a longer, unique string.\";\n }\n updated = existing.slice(0, idx) + newContent + existing.slice(idx + old_text.length);\n } else if (op === \"prepend\") {\n // Insert after frontmatter if present\n const fmMatch = existing.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n/);\n if (fmMatch) {\n const afterFm = fmMatch[0].length;\n updated = existing.slice(0, afterFm) + newContent + \"\\n\" + existing.slice(afterFm);\n } else {\n updated = newContent + \"\\n\" + existing;\n }\n } else {\n // append\n updated = existing.endsWith(\"\\n\") ? existing + newContent : existing + \"\\n\" + newContent;\n }\n\n const ok = await vault.writeNote(path, updated);\n if (!ok) {\n return `Failed to edit note: ${path}`;\n }\n searchIndex.update(path, updated, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note edited (${op}): ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"delete_note\",\n description: \"Delete a note from the Obsidian vault.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note to delete\"),\n }),\n execute: async ({ path }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.deleteNote(path);\n if (ok) searchIndex.remove(path);\n return ok ? `Deleted: ${path}` : `Failed to delete: ${path}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"move_note\",\n description:\n \"Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically.\" + writeScopeNote,\n parameters: z.object({\n from: z.string().describe(\"Current path, e.g. 'daily/old-name.md'\"),\n to: z.string().describe(\"New path, e.g. 'projects/new-name.md'\"),\n }),\n execute: async ({ from, to }) => {\n // Moving out of a folder deletes there; moving in writes there — both ends must be writable.\n if (!isPathWritable(from, writeFolders)) return denyWrite(from);\n if (!isPathWritable(to, writeFolders)) return denyWrite(to);\n const content = await vault.readNote(from);\n const ok = await vault.moveNote(from, to);\n if (!ok) {\n return `Failed to move: ${from} → ${to}`;\n }\n searchIndex.remove(from);\n // content === \"\" is an empty-but-present note: keep it indexed at the new path.\n if (content !== null) searchIndex.update(to, content, Date.now());\n const deepLink = makeDeepLink(vaultName, to);\n return `Moved: ${from} → ${to}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"get_note_metadata\",\n description:\n \"Get metadata about a note without reading its full content. Returns frontmatter, tags, outgoing links, backlinks (notes that link to this one), size, and timestamps. Use this to navigate the knowledge graph.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'projects/my-project.md'\"),\n }),\n execute: async ({ path }) => {\n const meta = await vault.getMetadata(path);\n if (!meta) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n const lines = [\n `**${path}**`,\n `Size: ${meta.size} bytes`,\n `Created: ${new Date(meta.ctime).toISOString()}`,\n `Modified: ${new Date(meta.mtime).toISOString()}`,\n ];\n if (Object.keys(meta.frontmatter).length > 0) {\n lines.push(`\\nFrontmatter:`);\n for (const [k, v] of Object.entries(meta.frontmatter)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n if (meta.tags.length > 0) {\n lines.push(`\\nTags: ${meta.tags.map((t) => `#${t}`).join(\", \")}`);\n }\n if (meta.links.length > 0) {\n lines.push(`\\nOutgoing links: ${meta.links.join(\", \")}`);\n }\n const backlinks = searchIndex.getBacklinks(path);\n if (backlinks.length > 0) {\n lines.push(`\\nBacklinks: ${backlinks.join(\", \")}`);\n }\n lines.push(`\\n[Open in Obsidian](${deepLink})`);\n return lines.join(\"\\n\");\n },\n });\n}\n","/**\n * Generate Obsidian deep links for notes.\n * Works on Mac and iOS: obsidian://open?vault=<name>&file=<path>\n */\nexport function makeDeepLink(vaultName: string, notePath: string): string {\n const cleanPath = notePath.replace(/\\.md$/, \"\");\n const encodedVault = encodeURIComponent(vaultName);\n const encodedPath = encodeURIComponent(cleanPath);\n return `obsidian://open?vault=${encodedVault}&file=${encodedPath}`;\n}\n","// Folder-scoped write access (WRITE_FOLDERS env var).\n// When set, write tools only accept paths inside the listed vault-relative folders.\n\n/** Parse the WRITE_FOLDERS env var into a normalized folder list, or null for unrestricted. */\nexport function parseWriteFolders(raw: string | undefined): string[] | null {\n if (raw === undefined) return null;\n const folders = raw\n .split(\",\")\n .map((f) => f.trim().replace(/^\\/+|\\/+$/g, \"\"))\n .filter(Boolean);\n return folders.length > 0 ? folders : null;\n}\n\n/**\n * Check whether a vault-relative path falls inside one of the writable folders.\n * Matching is case-sensitive and folder-boundary-aware (\"MCP\" matches \"MCP/x.md\",\n * not \"MCP-private/x.md\"). A null folder list means writes are unrestricted.\n */\nexport function isPathWritable(path: string, writeFolders: string[] | null): boolean {\n if (writeFolders === null) return true;\n const normalized = path.replace(/^\\/+/, \"\");\n // Backends reject traversal too; deny here so the scope check can't be reasoned around.\n // Split on backslash as well: on Windows \"MCP/..\\x\" resolves as traversal.\n if (normalized.split(/[/\\\\]/).includes(\"..\")) return false;\n return writeFolders.some((folder) => normalized.startsWith(folder + \"/\"));\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,mBAAAA,kBAAiB,cAAAC,mBAAkB;AAC5C,SAAS,OAAO,cAAc,gBAAgB;AAC9C,SAAS,YAAY;AACrB,SAAS,sBAAsB,kBAAkB;;;ACUjD,SAAS,YAAY,aAAa,YAAY,uBAAuB;AACrE,SAAS,UAAU,WAAW,OAAO,aAAa;AAClD,SAAS,eAAe;AA8BxB,IAAM,kBAAkB,OAAO;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB,SAAS,QAAQ,IAAI,oBAAoB,OAAO,oBAAoB,CAAC,KAAK,wBAAwB,KAAK,OAAO;AACzI,IAAM,4BAA4B;AAClC,IAAM,kBAAkB,IAAI;AAC5B,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,iBAAiB,KAAK,KAAK;AAS1B,SAAS,kBAAkB,KAAW,SAAiB,UAAkB,aAAkC;AAC9G,QAAM,eAAe,oBAAI,IAAyB;AAClD,QAAM,aAAa,oBAAI,IAAoB;AAC3C,QAAM,SAAS,oBAAI,IAAyB;AAC5C,QAAM,gBAAgB,oBAAI,IAAyB;AACnD,QAAM,UAAU,oBAAI,IAA8B;AAGlD,WAAS,iBAAiB;AACtB,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW,CAAC,MAAM,OAAO,KAAK,cAAc;AACxC,UAAI,MAAM,QAAQ,YAAY,gBAAgB;AAC1C,qBAAa,OAAO,IAA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AM;AACN,SAAK,QAAQ;AACb,UAAM,KAAK,WAAW;AAAA,EAC1B;AACJ,GAAG,IAAI,KAAK,GAAI,EAAE,MAAM;AAGxB,OAAO,MAAM;AAAA,EACT,eAAe;AAAA,EACf,YAAY,EAAE,MAAM,MAAM,UAAU,QAAQ,MAAM,QAAQ,IAAI,QAAQ,UAAU;AACpF,CAAC;AACD,QAAQ,IAAI,sBAAsB,OAA4C,sBAAsB,IAAI,EAAE;AAG1G,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACtC,UAAQ,MAAM,wBAAwB,GAAG;AAC7C,CAAC;","names":["timingSafeEqual","createHash","client","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","server","vault","searchIndex","debugLogging","createHash","timingSafeEqual"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "obsidian-sync-mcp",
3
3
  "mcpName": "io.github.es617/obsidian-sync-mcp",
4
- "version": "0.6.2",
4
+ "version": "0.6.3",
5
5
  "description": "Give any AI agent access to your Obsidian vault over MCP",
6
6
  "type": "module",
7
7
  "license": "MIT",