obsidian-sync-mcp 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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/vault-readonly.ts","../src/tools.ts","../src/deeplink.ts","../src/write-scope.ts","../src/list-format.ts","../src/search-format.ts","../src/redact.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { 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, safeEqual } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange, pruneGhosts } from \"./index-sync.js\";\nimport { buildAllowedHosts, isHostAllowed, isOriginAllowed } from \"./host-guard.js\";\nimport { readOnlyVault } from \"./vault-readonly.js\";\nimport { registerTools } from \"./tools.js\";\nimport { parseWriteFolders } from \"./write-scope.js\";\nimport { redactCredentials, describeError, describeLogMessage } from \"./redact.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 // The library also logs raw Error objects and other values, not only strings.\n console.log(describeLogMessage(message, debugLogging));\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: ${redactCredentials(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\ntry {\n await vault.init();\n} catch (err) {\n console.error(`Failed to open the vault: ${describeError(err, debugLogging)}`);\n process.exit(1);\n}\nconsole.log(\"Vault ready.\");\n\n// READ_ONLY also hides the write tools (see registerTools); wrapping the backend\n// makes any write that bypasses the tools fail too.\nif (READ_ONLY) vault = readOnlyVault(vault);\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// The persisted file carries metadata (paths, mtimes, tags, links) but no note\n// text, since bodies are never written to disk. Keep that metadata serveable\n// right away — list_notes, tags and backlinks answer from the first request —\n// and re-read every body from sequence zero to repopulate the in-memory search\n// text. A from-zero _changes pass refreshes metadata and removes notes deleted\n// while the server was down, so nothing kept from disk goes stale. (Clearing\n// here instead would discard the metadata and leave list_notes empty on a\n// path-obfuscated vault until the full rebuild finishes.)\nif (searchIndex.size > 0 && searchIndex.contentCount < searchIndex.size) {\n console.log(`Persisted metadata for ${searchIndex.size} notes has no text; re-reading note bodies from the start so search_notes covers every note (metadata stays serveable meanwhile).`);\n searchIndex.since = \"0\";\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 since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n // Ghosts (notes that vanished while the server was down) can only be among\n // the paths already loaded from the persisted file: a from-zero pass\n // re-delivers every live note, so a loaded path it does not deliver is\n // gone. A remote \"Rebuild database\" recreates the DB with no tombstones to\n // replay, so this is the only way to catch those deletions. Snapshot the\n // loaded paths up front and track which the pass re-delivers; limiting the\n // prune to pre-existing paths means a note the live watcher adds mid-pass\n // is never pruned.\n const preexisting = new Set(searchIndex.listPaths());\n const seen = new Set<string>();\n let fromZero = since === \"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 const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n if (content !== null) seen.add(path); else seen.delete(path);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n try {\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n searchIndex.lastSyncAt = Date.now();\n } catch (err) {\n // Re-read from the start, but don't clear() first: a from-zero pass\n // repopulates everything, and clearing would discard the still-serveable\n // persisted metadata and — if this retry also fails — leave an empty\n // index that the periodic save would then persist over the good copy.\n console.warn(`Catch-up failed (${describeError(err, debugLogging)}), re-reading from the start...`);\n changes = 0;\n seen.clear();\n fromZero = true;\n const newSince = await vault.catchUp(\"0\", countingCallback, onBatch);\n searchIndex.since = newSince;\n searchIndex.lastSyncAt = Date.now();\n }\n // Drop loaded paths a completed from-zero pass did not re-deliver. A note\n // the watcher adds mid-pass is never pruned (it is not in `preexisting`);\n // one the watcher re-adds between the pass and the prune is re-added by\n // the next pre-search catch-up, so any race is self-correcting.\n if (fromZero) pruneGhosts(searchIndex, preexisting, seen);\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 searchIndex.state = \"ready\";\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => {\n searchIndex.state = \"failed\";\n console.error(`Index rebuild failed: ${describeError(err, debugLogging)}`);\n});\n\n// --- Pre-search catch-up ---\n// search_notes calls this before every search so a hit can never predate the\n// vault: one `_changes` request from the index's own sequence (milliseconds\n// when nothing changed), applied through the same applyIndexChange path as\n// the startup rebuild and the watcher. Calls are serialized so two searches\n// cannot interleave their batches. Errors are returned, never thrown: the\n// search still runs on the index as it is and the status line says so.\nlet syncChain: Promise<unknown> = Promise.resolve();\nasync function syncBeforeSearch(): Promise<{ unreadable: number; error?: string }> {\n if (!(COUCHDB_URL && vault.catchUp) || searchIndex.state !== \"ready\") return { unreadable: 0 };\n const run = async () => {\n const stats = { unreadable: 0 };\n try {\n const newSince = await vault.catchUp!(\n searchIndex.since || \"0\",\n (path, content, mtime) => applyIndexChange(searchIndex, path, content, mtime),\n undefined,\n stats,\n );\n searchIndex.since = newSince;\n searchIndex.lastSyncAt = Date.now();\n return { unreadable: stats.unreadable };\n } catch (err) {\n // Log the detail (credentials redacted) server-side; the status line\n // shown to the client gets a short reason, not a raw backend error\n // that would disclose internal hostnames or URLs.\n console.warn(`Pre-search catch-up failed: ${describeError(err, debugLogging)}`);\n return { unreadable: stats.unreadable, error: \"CouchDB sync error\" };\n }\n };\n const result = syncChain.then(run, run);\n syncChain = result.catch(() => undefined);\n return result;\n}\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) {\n searchIndex.since = String(seq);\n searchIndex.lastSyncAt = Date.now();\n }\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 && safeEqual(header, 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, COUCHDB_URL ? syncBeforeSearch : undefined);\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: ${describeError(err, debugLogging)}`);\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 approved: boolean;\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\n/**\n * Constant-time string comparison for secrets. Comparing SHA-256 digests gives\n * timingSafeEqual equal-length inputs, so it never throws on a length or\n * encoding mismatch and the secret's length is not revealed.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const da = createHash(\"sha256\").update(a).digest();\n const db = createHash(\"sha256\").update(b).digest();\n return timingSafeEqual(da, db);\n}\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 approved: false,\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, hostOf(redirectUri), client.clientName));\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 if (typeof submittedCsrf !== \"string\" || !safeEqual(submittedCsrf, expectedCsrf)) {\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, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n if (typeof submittedPassword !== \"string\" || !safeEqual(submittedPassword, password)) {\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, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n // Mark the code redeemable only now that the password has been verified.\n // Without this, /oauth/token would accept the code straight out of the\n // authorize page before any password was entered.\n pending.approved = true;\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 // The code is only redeemable once the password step succeeded.\n // It exists in pendingAuths from /oauth/authorize onward (and is\n // present in the authorize page HTML), so without this check the\n // password gate can be bypassed entirely.\n if (!pending.approved) {\n console.warn(\"Auth: /oauth/token invalid_grant. code not yet approved (password step not completed)\");\n return c.json({ error: \"invalid_grant\", error_description: \"authorization not approved\" }, 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 hostOf(uri: string): string {\n try {\n return new URL(uri).host;\n } catch {\n return uri;\n }\n}\n\nfunction renderPasswordPage(code: string, csrf: string, redirectHost: string, clientName: string | undefined, error?: string): string {\n const esc = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n const who = clientName ? `<b>${esc(clientName)}</b> (name self-reported)` : \"An application\";\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 .dest { background: #f3f3f3; padding: 8px 10px; border-radius: 6px; word-break: break-all; }\n .warn { color: #a15c00; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n <p>${who} is requesting access to your vault. After you approve, your browser will be sent to:</p>\n <p class=\"dest\"><b>${esc(redirectHost)}</b></p>\n <p class=\"warn\">Only enter your password if you recognize this destination. If you did not start this sign-in, close this page.</p>\n ${error ? `<p class=\"error\">${esc(error)}</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, and keeps the decrypted\n * note text in memory for `search_notes` (substring search over content).\n * Metadata persists to disk (encrypted if passphrase is set); the content map\n * is rebuilt from the vault at startup and is never written to disk.\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\";\nimport { isValidNotePath } from \"./note-path.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\n/**\n * Lifecycle of the in-memory index. \"building\" from construction until the\n * startup rebuild finishes, \"ready\" afterwards, \"failed\" if the rebuild threw.\n * Read by list_notes and search_notes so a client can tell a partial index from a complete one.\n */\nexport type IndexState = \"building\" | \"ready\" | \"failed\";\n\nexport interface SearchQuery {\n /** Case-insensitive substrings; a note matches when ANY term occurs (OR). A term may contain spaces. */\n terms?: string[];\n folder?: string;\n tag?: string;\n /** Only notes with mtime >= this (ms since epoch). */\n modifiedAfter?: number;\n limit?: number;\n}\n\nexport interface SearchHit {\n path: string;\n mtime: number;\n /** Distinct terms that matched in path/title or content. */\n matched: number;\n /** True when the path or the frontmatter title matched. Name hits rank first. */\n nameHit: boolean;\n /** One line of context around the first content match; whitespace collapsed. Empty for a name-only hit. */\n snippet: string;\n}\n\n/** Cut a one-line snippet around `idx` (match of length `len`), whitespace collapsed. */\nexport function snippetAround(text: string, idx: number, len: number, context = 80): string {\n const start = Math.max(0, idx - context);\n const end = Math.min(text.length, idx + len + context);\n const body = text.slice(start, end).replace(/\\s+/g, \" \").trim();\n return (start > 0 ? \"…\" : \"\") + body + (end < text.length ? \"…\" : \"\");\n}\n\nexport class SearchIndex {\n private _state: IndexState = \"building\";\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 /** Decrypted note text, in memory only — one copy per note; term matching is case-insensitive via a regex per term. */\n private content = new Map<string, string>();\n /** Frontmatter `title:` per path, when present — searched together with the path. */\n private titles = new Map<string, string>();\n private saving = false;\n private _since: string = \"\";\n /** When `since` last advanced from a completed catch-up or a watcher change (ms), null before the first. */\n private _lastSyncAt: number | null = null;\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 /**\n * Add or update a note in the index. The watcher and the pre-search\n * catch-up both write here without coordinating, so a write whose mtime is\n * not newer than the one recorded for text already held is skipped: a\n * stale copy can never replace a newer one. Mtimes loaded from disk carry\n * no text, so the startup rebuild still fills them in.\n */\n update(path: string, content: string, mtime?: number): void {\n if (mtime !== undefined && this.content.has(path) && mtime <= (this.mtimes.get(path) ?? -Infinity)) return;\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 // Same code path for the startup catch-up, the watcher and the\n // pre-search catch-up: whatever updates metadata also updates content.\n this.content.set(path, content);\n const parsed = parseFrontmatterAndLinks(content);\n const title = parsed.frontmatter[\"title\"];\n if (typeof title === \"string\" && title.trim().length > 0) {\n this.titles.set(path, title.trim());\n } else {\n this.titles.delete(path);\n }\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.content.delete(path);\n this.titles.delete(path);\n this.clearBacklinks(path);\n }\n }\n\n /** Decrypted text of a note, or null if the index holds no content for it. */\n getContent(path: string): string | null {\n return this.content.get(path) ?? null;\n }\n\n /** Notes whose text is in memory. Below `size` means search cannot see every note. */\n get contentCount(): number {\n return this.content.size;\n }\n\n /**\n * Search over path + frontmatter title first, then the in-memory text.\n * Ranked: name hits first, then number of distinct terms matched, then\n * newest first, then path. `limit` defaults to 20.\n */\n search(q: SearchQuery): { hits: SearchHit[]; total: number } {\n const prefix = q.folder ? (q.folder.endsWith(\"/\") ? q.folder : q.folder + \"/\") : undefined;\n const terms = (q.terms ?? []).filter((t) => t.length > 0).map((t) => ({\n text: t.toLowerCase(),\n // Case-insensitive (Unicode) search over the note text without a lowercased copy of the vault in memory.\n re: new RegExp(t.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"), \"iu\"),\n }));\n const hits: SearchHit[] = [];\n for (const [path, entry] of this.content) {\n // Mirror the ingest filter (GHSA-hfcr-mrh3-c584): the content map is\n // only fed validated paths, so this is defense in depth, not a gate.\n if (!isValidNotePath(path)) continue;\n if (prefix && !path.startsWith(prefix)) continue;\n if (q.tag && !this.getTags(path).includes(q.tag)) continue;\n const mtime = this.mtimes.get(path) ?? 0;\n if (q.modifiedAfter !== undefined && mtime < q.modifiedAfter) continue;\n // Step 1: path and title. Step 2: content. A term counts once even if it hits both.\n const title = this.titles.get(path);\n const name = title ? `${path} ${title}` : path;\n const nameLower = name.toLowerCase();\n let matched = 0;\n let nameHit = false;\n let anchor = -1;\n let anchorLen = 1;\n {\n for (const t of terms) {\n const inName = nameLower.includes(t.text);\n const i = entry.search(t.re);\n if (!inName && i === -1) continue;\n matched++;\n if (inName) nameHit = true;\n if (i !== -1 && (anchor === -1 || i < anchor)) {\n anchor = i;\n anchorLen = t.text.length;\n }\n }\n if (matched === 0) continue;\n }\n const snippet = anchor === -1 ? \"\" : snippetAround(entry, anchor, anchorLen);\n hits.push({ path, mtime, matched, nameHit, snippet });\n }\n hits.sort(\n (a, b) =>\n Number(b.nameHit) - Number(a.nameHit) ||\n b.matched - a.matched ||\n b.mtime - a.mtime ||\n a.path.localeCompare(b.path),\n );\n return { hits: hits.slice(0, q.limit ?? 20), total: hits.length };\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(isValidNotePath)\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 this._state = \"building\";\n }\n\n get state(): IndexState {\n return this._state;\n }\n\n set state(value: IndexState) {\n this._state = value;\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 lastSyncAt(): number | null {\n return this._lastSyncAt;\n }\n\n set lastSyncAt(value: number | null) {\n this._lastSyncAt = 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","/**\n * READ_ONLY enforcement at the backend layer.\n *\n * READ_ONLY=true already keeps the write tools from being registered. Wrapping\n * the backend as well means a write fails even if some future code path\n * reaches writeNote/deleteNote/moveNote without going through a tool.\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nexport const READ_ONLY_MESSAGE = \"READ_ONLY is enabled: the vault cannot be modified.\";\n\n/** Return a backend that delegates reads to `inner` and rejects every write. */\nexport function readOnlyVault(inner: VaultBackend): VaultBackend {\n const deny = async (): Promise<never> => {\n throw new Error(READ_ONLY_MESSAGE);\n };\n return {\n init: () => inner.init(),\n close: () => inner.close(),\n readNote: (path) => inner.readNote(path),\n getMetadata: (path) => inner.getMetadata(path),\n listNotes: (folder) => inner.listNotes(folder),\n listNotesWithMtime: (folder) => inner.listNotesWithMtime(folder),\n watchChanges: inner.watchChanges?.bind(inner),\n catchUp: inner.catchUp?.bind(inner),\n writeNote: deny,\n deleteNote: deny,\n moveNote: deny,\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\";\nimport { describeListing, describeNoMatch } from \"./list-format.js\";\nimport { describeHits, describeQuery, describeSync, type SyncStatus } from \"./search-format.js\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\n/** Runs a CouchDB catch-up before a search; undefined in local (VAULT_PATH) mode. */\nexport type SyncBeforeSearch = () => Promise<{ unreadable: number; error?: string }>;\n\nexport const SEARCH_MAX_HITS = 20;\n/** Each term is one more regex pass over every note (synchronous), so the count is capped. */\nexport const SEARCH_MAX_TERMS = 20;\n/** Each term is compiled into a regex; a very long one overflows the stack (~10 KB with flags iu) or blocks the event loop, so its length is capped. */\nexport const SEARCH_MAX_TERM_LENGTH = 200;\n\n/** Trim, drop empty terms, cut each to SEARCH_MAX_TERM_LENGTH and clamp to SEARCH_MAX_TERMS — a backstop behind the schema's .max(). */\nexport function cleanSearchTerms(terms: string[] | undefined): string[] {\n return (terms ?? [])\n .map((t) => t.trim().slice(0, SEARCH_MAX_TERM_LENGTH))\n .filter((t) => t.length > 0)\n .slice(0, SEARCH_MAX_TERMS);\n}\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\n// Claude Code persists any MCP tool result above ~50 000 characters to a file\n// and hands the model a 2 kB preview instead of the text. A tool can raise its\n// own threshold (hard ceiling 500 000) by declaring\n// `_meta[\"anthropic/maxResultSizeChars\"]` in its tools/list entry; text from\n// such a tool is then also exempt from MAX_MCP_OUTPUT_TOKENS. See\n// https://code.claude.com/docs/en/mcp#raise-the-limit-for-a-specific-tool\n// read_note returns whole notes, so it declares 100 000: enough for a large\n// note to arrive in one piece, small enough to keep one read inside a sane\n// context budget. Other clients ignore the key.\nexport const READ_NOTE_MAX_RESULT_SIZE_CHARS = 100_000;\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 syncBeforeSearch?: SyncBeforeSearch,\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 _meta: { \"anthropic/maxResultSizeChars\": READ_NOTE_MAX_RESULT_SIZE_CHARS },\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 let vaultTotal: number | null = searchIndex.size;\n let servedByVault = false;\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n servedByVault = notes.length > 0;\n // The fallback only tells us the vault total when it was unscoped.\n if (vaultTotal === 0) vaultTotal = folder ? null : notes.length;\n }\n const folderTotal = folder ? notes.length : null;\n const filters: string[] = [];\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n filters.push(`name=\"${name}\"`);\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n filters.push(`tag=\"${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 filters.push(`modified_after=\"${modified_after}\"`);\n }\n const index = { state: searchIndex.state, size: searchIndex.size, servedByVault };\n if (notes.length === 0) {\n return describeNoMatch({ vaultTotal, folder, folderTotal, filters, index });\n }\n const sortBy = sort_by === \"modified\" ? \"modified\" : \"name\";\n if (sortBy === \"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 header = describeListing({\n shown: capped.length,\n matched: total,\n vaultTotal,\n folder,\n folderTotal,\n filters,\n sortBy,\n limit: cap,\n omitted: notes.slice(cap).map((n) => n.path),\n index,\n });\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 return [header, ...lines].join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"search_notes\",\n description:\n \"Search note contents for terms, case-insensitive.\\n\" +\n \"Paths and frontmatter titles are searched first and such hits rank on top, marked [path/title]; content hits follow. \" +\n \"Returns paths with one context line each, never the note body: call read_note on a hit before relying on it. \" +\n \"Give `terms` (a note matches when ANY term occurs — OR, so list synonyms, field names and other-language wordings; a term may contain spaces; ranked by how many terms match) \" +\n \"Filters: folder, tag, modified_after. \" +\n \"The first line of every response is the index status: the CouchDB sequence the index is caught up with after a catch-up run just before the search, \" +\n \"the server time (local zone and UTC), its age in minutes, how many notes carry content, and any documents that could not be read.\",\n parameters: z.object({\n terms: z\n .array(z.string().max(SEARCH_MAX_TERM_LENGTH))\n .max(SEARCH_MAX_TERMS)\n .optional()\n .describe(`Case-insensitive substrings, at most ${SEARCH_MAX_TERMS} of at most ${SEARCH_MAX_TERM_LENGTH} characters each; a note matches when any of them occurs. E.g. ['drag i kanban', 'kanban', 'labels på kategori'].`),\n folder: z\n .string()\n .optional()\n .describe(\"Folder to search in, e.g. 'projects'. Omit for the whole vault.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Only notes carrying this tag, e.g. 'project'.\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only 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 hits to return, default and maximum ${SEARCH_MAX_HITS}.`),\n }),\n execute: async ({ terms, folder, tag, modified_after, limit }) => {\n const cleanTerms = cleanSearchTerms(terms);\n if (cleanTerms.length === 0) {\n return \"Give at least one term.\";\n }\n let modifiedAfter: number | undefined;\n if (modified_after) {\n modifiedAfter = new Date(modified_after).getTime();\n if (isNaN(modifiedAfter)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n }\n const cap = Math.max(1, Math.min(SEARCH_MAX_HITS, limit ?? SEARCH_MAX_HITS));\n\n // Catch up first, so a hit can never predate the vault (see main.ts).\n const sync = syncBeforeSearch ? await syncBeforeSearch() : { unreadable: 0 };\n const status: SyncStatus = {\n mode: syncBeforeSearch ? \"couchdb\" : \"local\",\n state: searchIndex.state,\n seq: searchIndex.since,\n syncedAt: searchIndex.lastSyncAt,\n now: Date.now(),\n notes: searchIndex.size,\n withContent: searchIndex.contentCount,\n unreadable: sync.unreadable,\n error: sync.error,\n };\n const { hits, total } = searchIndex.search({ terms: cleanTerms, folder, tag, modifiedAfter, limit: cap });\n const query = describeQuery(cleanTerms);\n return `${describeSync(status)}\\n${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;\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 // The sync layer reports success even when nothing existed at the\n // path, so \"Deleted\" would claim a cleanup that never happened.\n // readNote returns \"\" for an empty note and null only when absent.\n const existing = await vault.readNote(path);\n if (existing === null) return `Note not found: ${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","import type { IndexState } from \"./search.js\";\n\n/**\n * Response wording for list_notes (issue #19). Kept free of MCP/vault types so\n * it can be unit-tested: the goal is that an LLM client can never mistake a\n * truncated, filtered or still-indexing listing for \"the vault contains\n * nothing else\".\n */\n\nexport const MAX_NAMED_FOLDERS = 10;\n\nexport interface ListingSummary {\n /** Notes actually returned (after the limit). */\n shown: number;\n /** Notes matching all filters (before the limit). */\n matched: number;\n /** Notes in the whole vault, before any filter; null when unknown. */\n vaultTotal: number | null;\n /** Folder filter as given by the caller, if any. */\n folder?: string;\n /** Notes inside `folder` before the other filters; null when unknown. */\n folderTotal?: number | null;\n /** Non-folder filters that were applied, e.g. `name=\"x\"`, `tag=\"y\"`. */\n filters: string[];\n sortBy: \"name\" | \"modified\";\n limit: number;\n /** Paths cut by the limit, used to name the omitted folders. */\n omitted: string[];\n index: IndexStatus;\n}\n\nexport interface IndexStatus {\n state: IndexState;\n size: number;\n /** True when the notes were read straight from the vault because the index had nothing — the list itself is complete. */\n servedByVault?: boolean;\n}\n\nexport interface FolderCount {\n folder: string;\n count: number;\n}\n\nfunction plural(n: number, word: string): string {\n return `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n}\n\nfunction folderLabel(folder: string): string {\n return folder.endsWith(\"/\") ? folder : folder + \"/\";\n}\n\n/** Group paths by their immediate parent folder; root-level notes count under \"(root)\". */\nexport function countByFolder(paths: string[]): FolderCount[] {\n const counts = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n const folder = lastSlash === -1 ? \"(root)\" : p.slice(0, lastSlash);\n counts.set(folder, (counts.get(folder) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([folder, count]) => ({ folder, count }))\n .sort((a, b) => b.count - a.count || a.folder.localeCompare(b.folder));\n}\n\n/** \"Omitted 106: a/ (41), b/ (9), … and 3 more folders (56 notes).\" — the counts always add up to the total. */\nexport function describeOmitted(omitted: string[]): string {\n const groups = countByFolder(omitted);\n const named = groups.slice(0, MAX_NAMED_FOLDERS);\n const rest = groups.slice(MAX_NAMED_FOLDERS);\n const parts = named.map((g) => `${g.folder === \"(root)\" ? \"(root)\" : folderLabel(g.folder)} (${g.count})`);\n let text = `Omitted ${omitted.length}: ${parts.join(\", \")}`;\n if (rest.length > 0) {\n const restNotes = rest.reduce((sum, g) => sum + g.count, 0);\n text += `, and ${plural(rest.length, \"more folder\")} (${plural(restNotes, \"note\")})`;\n }\n return text + \".\";\n}\n\n/** Appended to every response while the index is not known to be complete. */\nexport function describeIndexState(index: IndexStatus): string {\n const caveat = index.servedByVault\n ? \"this list was read directly from the vault\"\n : \"this list may be incomplete\";\n switch (index.state) {\n case \"ready\":\n return \"\";\n case \"building\":\n return ` Index: catching up (${plural(index.size, \"note\")} indexed so far); ${caveat}.`;\n case \"failed\":\n return ` Index: rebuild failed at startup (see server log); ${index.servedByVault ? caveat : \"this list may be incomplete or stale\"}.`;\n }\n}\n\n/**\n * \"vault has N notes\" / \"folder has N notes\" — only when the number can be\n * trusted: the index is ready, or the notes came straight from the vault.\n * While the index is still building, its size is a partial count and the\n * index caveat carries it instead.\n */\nfunction describeScopeCount(s: Pick<ListingSummary, \"vaultTotal\" | \"folder\" | \"folderTotal\" | \"index\">): string {\n if (s.index.state !== \"ready\" && !s.index.servedByVault) return \"\";\n if (s.folder) return s.folderTotal != null ? `folder has ${plural(s.folderTotal, \"note\")}` : \"\";\n return s.vaultTotal != null ? `vault has ${plural(s.vaultTotal, \"note\")}` : \"\";\n}\n\n/** Response for a listing with zero matches. */\nexport function describeNoMatch(s: Omit<ListingSummary, \"shown\" | \"matched\" | \"omitted\" | \"sortBy\" | \"limit\">): string {\n const indexNote = describeIndexState(s.index);\n if (s.filters.length === 0) {\n if (s.folder) return `No notes found in folder: ${s.folder}${indexNote}`;\n return `Vault is empty.${indexNote}`;\n }\n const count = describeScopeCount(s);\n const scope = (s.folder ? ` in folder \"${folderLabel(s.folder)}\"` : \"\") + (count ? ` (${count})` : \"\");\n return `No notes match ${s.filters.join(\", \")}${scope}.${indexNote}`;\n}\n\n/**\n * First line of a non-empty listing. Always present, so the index state and\n * the filter scope are visible even when nothing was cut.\n */\nexport function describeListing(s: ListingSummary): string {\n const truncated = s.matched > s.shown;\n // \"5 notes match name=…\" reads as a sentence; \"Showing 100 of 150 notes matching …\" needs the participle.\n const verb = truncated ? \"matching\" : s.matched === 1 ? \"matches\" : \"match\";\n const filterClause = s.filters.length > 0 ? ` ${verb} ${s.filters.join(\", \")}` : \"\";\n const folderClause = s.folder ? ` in folder \"${folderLabel(s.folder)}\"` : \"\";\n const scopeParts: string[] = [];\n const count = s.filters.length > 0 || s.folder ? describeScopeCount(s) : \"\";\n if (count) scopeParts.push(count);\n // Every source (index, CouchDB enumeration, local glob) sorts by path with localeCompare, so \"sorted by name\" is literal.\n scopeParts.push(`sorted by ${s.sortBy}`);\n if (truncated) scopeParts.push(`limit=${s.limit}`);\n const scope = ` (${scopeParts.join(\", \")})`;\n\n let line = truncated\n ? `Showing ${s.shown} of ${plural(s.matched, \"note\")}${filterClause}${folderClause}${scope}.`\n : `${plural(s.matched, \"note\")}${filterClause}${folderClause}${scope}.`;\n if (truncated) {\n const hint = s.folder || s.filters.length > 0 ? \"Raise `limit` or narrow the filter.\" : \"Raise `limit` or add a `folder` filter.\";\n line += ` ${describeOmitted(s.omitted)} ${hint}`;\n }\n return line + describeIndexState(s.index);\n}\n","/**\n * Response wording for search_notes. Pure functions, no MCP/vault types, so\n * the index-status line — the part a client relies on to judge freshness —\n * is unit-testable against fixed instants.\n *\n * Every search response opens with one status line that says which CouchDB\n * sequence the index is caught up with, the server time (local zone plus UTC),\n * how old that is, how many notes carry content, and whether any document\n * could not be read during the pre-search catch-up. \"Caught up\" must never\n * hide a silent miss.\n */\n\nimport type { IndexState, SearchHit } from \"./search.js\";\n\n/**\n * Validate a display zone once. An unknown zone makes Intl.DateTimeFormat\n * throw, which would break every search_notes call, so it falls back to UTC\n * with a logged warning instead.\n */\nexport function resolveDisplayZone(raw: string | undefined): string {\n const zone = raw?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone });\n return zone;\n } catch {\n console.warn(`DISPLAY_TIMEZONE \"${zone}\" is not a valid IANA time zone; using UTC.`);\n return \"UTC\";\n }\n}\n\n/** Zone used for the human-readable half of the timestamp (default: the server's own zone). UTC is always printed beside it. */\nexport const DISPLAY_TIMEZONE = resolveDisplayZone(process.env.DISPLAY_TIMEZONE);\n\nexport interface SyncStatus {\n /** \"couchdb\" when a catch-up ran (or was attempted) before the search; \"local\" for a VAULT_PATH vault. */\n mode: \"couchdb\" | \"local\";\n state: IndexState;\n /** The index's CouchDB sequence after the catch-up (raw, e.g. \"39995-g1AAAA…\"). */\n seq: string;\n /** When the sequence last advanced (ms), null before the first catch-up. */\n syncedAt: number | null;\n /** Server time the response was built (ms). */\n now: number;\n notes: number;\n withContent: number;\n /** Documents the catch-up could not decrypt or load. */\n unreadable: number;\n /** Set when the pre-search catch-up threw; hits then come from the index as it was. */\n error?: string;\n}\n\n/** \"2026-09-20 15:30 CEST (13:30Z)\" — local zone from Intl (sv-SE yields CET/CEST), UTC beside it. */\nexport function formatServerTime(ms: number, timeZone: string = DISPLAY_TIMEZONE): string {\n const d = new Date(ms);\n const parts = new Intl.DateTimeFormat(\"sv-SE\", {\n timeZone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hourCycle: \"h23\",\n timeZoneName: \"short\",\n }).formatToParts(d);\n const get = (type: string) => parts.find((p) => p.type === type)?.value ?? \"\";\n const utc = d.toISOString().slice(11, 16);\n return `${get(\"year\")}-${get(\"month\")}-${get(\"day\")} ${get(\"hour\")}:${get(\"minute\")} ${get(\"timeZoneName\")} (${utc}Z)`;\n}\n\n/** The numeric prefix of a CouchDB sequence (\"39995\" from \"39995-g1AAAA…\"); \"none\" when empty. */\nexport function seqPrefix(seq: string): string {\n if (!seq) return \"none\";\n const dash = seq.indexOf(\"-\");\n return dash === -1 ? seq : seq.slice(0, dash);\n}\n\nfunction minutesBetween(from: number, to: number): number {\n return Math.max(0, Math.round((to - from) / 60_000));\n}\n\nfunction plural(n: number, word: string): string {\n return `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n}\n\n/** First line of every search_notes response. `timeZone` is the display zone; tests pass it so the wording does not depend on the machine's zone. */\nexport function describeSync(s: SyncStatus, timeZone: string = DISPLAY_TIMEZONE): string {\n const now = formatServerTime(s.now, timeZone);\n const coverage = `${s.withContent} of ${plural(s.notes, \"note\")} with content`;\n if (s.mode === \"local\") {\n return `Index: local vault, no sequence — ${now}; ${coverage}.`;\n }\n if (s.state === \"building\") {\n return `Index: still building (${plural(s.notes, \"note\")} so far), not caught up — ${now}; results may be incomplete.`;\n }\n if (s.state === \"failed\") {\n return `Index: rebuild failed at startup (see server log), not caught up — ${now}; results may be incomplete or stale.`;\n }\n if (s.error) {\n const last = s.syncedAt === null ? \"never\" : `${formatServerTime(s.syncedAt, timeZone)}, ${minutesBetween(s.syncedAt, s.now)} min ago`;\n return `Index: catch-up failed (${s.error}); last caught up with CouchDB seq ${seqPrefix(s.seq)} — ${last}; results may be stale.`;\n }\n const age = s.syncedAt === null ? 0 : minutesBetween(s.syncedAt, s.now);\n let line = `Index caught up with CouchDB seq ${seqPrefix(s.seq)} — ${now}, ${age} min; ${coverage}`;\n if (s.unreadable > 0) {\n line += `; ${plural(s.unreadable, \"document\")} could not be read`;\n }\n return line + \".\";\n}\n\n/** What was searched, for the second line. */\nexport function describeQuery(terms: string[]): string {\n return terms.map((t) => `\"${t}\"`).join(\", \");\n}\n\n/**\n * Hit lines: path with deep link and modification time (same shape as\n * list_notes), then one indented context line. Never the note body.\n */\nexport function describeHits(\n hits: SearchHit[],\n total: number,\n query: string,\n deepLink: (path: string) => string,\n): string {\n if (total === 0) return `No notes match ${query}.`;\n const shown = hits.length < total ? ` (showing ${hits.length}; narrow with folder, tag or modified_after)` : \"\";\n const nameHits = hits.filter((h) => h.nameHit).length;\n const byName = nameHits > 0 ? ` ${plural(nameHits, \"hit\")} by path or title listed first.` : \"\";\n const header = `${plural(total, \"note\")} ${total === 1 ? \"matches\" : \"match\"} ${query}${shown}.${byName} Call read_note on a hit before relying on it.`;\n const lines = hits.map((h) => {\n const date = h.mtime ? new Date(h.mtime).toISOString().slice(0, 16) : \"\";\n const context = h.nameHit\n ? (h.snippet ? `[path/title] ${h.snippet}` : \"[path/title match]\")\n : h.snippet;\n return `- ${date} [${h.path}](${deepLink(h.path)})\\n ${context}`;\n });\n return [header, ...lines].join(\"\\n\");\n}\n","/**\n * Log redaction helpers.\n *\n * COUCHDB_URL may embed credentials as `user:pass@host`. Anything written to\n * the log goes through these so the password never lands in container logs.\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nimport { inspect } from \"node:util\";\n\n/** Replace the userinfo part of every URL in `text` (e.g. `http://u:p@h` -> `http://***@h`). */\nexport function redactCredentials(text: string): string {\n // Greedy up to the last \"@\" before the path, as URL parsers split userinfo,\n // so an unencoded \"@\" in the password is still fully covered.\n return text.replace(/\\b([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/?#]+@/gi, \"$1***@\");\n}\n\n/**\n * One-line description of an error for logs: the message only, redacted.\n * With `verbose` (LOG_LEVEL=debug) the stack is kept, still redacted.\n * The cause chain is appended: fetch() reports \"fetch failed\" and keeps the\n * useful part (ECONNREFUSED, ENOTFOUND, ...) in `cause`.\n */\nexport function describeError(err: unknown, verbose = false): string {\n if (!(err instanceof Error)) return redactCredentials(String(err));\n let text = verbose && err.stack ? err.stack : `${err.name}: ${err.message}`;\n const causes: string[] = [];\n let cause: unknown = err.cause;\n for (let depth = 0; cause !== undefined && cause !== null && depth < 3; depth++) {\n if (cause instanceof Error) {\n causes.push(cause.message || String((cause as NodeJS.ErrnoException).code ?? cause.name));\n cause = cause.cause;\n } else {\n causes.push(String(cause));\n break;\n }\n }\n if (causes.length > 0) text += ` (cause: ${causes.join(\" <- \")})`;\n return redactCredentials(text);\n}\n\n/**\n * Redacted text for anything handed to the library log hook. The library logs\n * strings, but also raw Error objects (`Logger(ex)`) and occasionally other\n * values; console.log would print those (stack and cause chain included)\n * without redaction. Other values are rendered as console.log would, via\n * inspect(), which also copes with circular references and BigInt.\n */\nexport function describeLogMessage(message: unknown, verbose = false): string {\n if (typeof message === \"string\") return redactCredentials(message);\n if (message instanceof Error) return describeError(message, verbose);\n return redactCredentials(inspect(message));\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;A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AY,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,cAAc,KAAKA,aAAY,CAAC,EAAE;AAC5E,CAAC;","names":["createHash","client","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","plural","server","vault","searchIndex","syncBeforeSearch","debugLogging","createHash"]}
1
+ {"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/host-guard.ts","../src/vault-readonly.ts","../src/tools.ts","../src/deeplink.ts","../src/write-scope.ts","../src/list-format.ts","../src/search-format.ts","../src/redact.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { 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, safeEqual } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange, pruneGhosts } from \"./index-sync.js\";\nimport { buildAllowedHosts, isHostAllowed, isOriginAllowed } from \"./host-guard.js\";\nimport { readOnlyVault } from \"./vault-readonly.js\";\nimport { registerTools } from \"./tools.js\";\nimport { parseWriteFolders } from \"./write-scope.js\";\nimport { redactCredentials, describeError, describeLogMessage } from \"./redact.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 // The library also logs raw Error objects and other values, not only strings.\n console.log(describeLogMessage(message, debugLogging));\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 COUCHDB_ID_DERIVATION_KEY = process.env.COUCHDB_ID_DERIVATION_KEY || undefined;\nconst COUCHDB_CASE_SENSITIVE = process.env.COUCHDB_CASE_SENSITIVE === \"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 idDerivationKey: COUCHDB_ID_DERIVATION_KEY,\n caseSensitive: COUCHDB_CASE_SENSITIVE,\n });\n console.log(`Remote mode: ${redactCredentials(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\ntry {\n await vault.init();\n} catch (err) {\n console.error(`Failed to open the vault: ${describeError(err, debugLogging)}`);\n process.exit(1);\n}\nconsole.log(\"Vault ready.\");\n\n// READ_ONLY also hides the write tools (see registerTools); wrapping the backend\n// makes any write that bypasses the tools fail too.\nif (READ_ONLY) vault = readOnlyVault(vault);\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// The persisted file carries metadata (paths, mtimes, tags, links) but no note\n// text, since bodies are never written to disk. Keep that metadata serveable\n// right away — list_notes, tags and backlinks answer from the first request —\n// and re-read every body from sequence zero to repopulate the in-memory search\n// text. A from-zero _changes pass refreshes metadata and removes notes deleted\n// while the server was down, so nothing kept from disk goes stale. (Clearing\n// here instead would discard the metadata and leave list_notes empty on a\n// path-obfuscated vault until the full rebuild finishes.)\nif (searchIndex.size > 0 && searchIndex.contentCount < searchIndex.size) {\n console.log(`Persisted metadata for ${searchIndex.size} notes has no text; re-reading note bodies from the start so search_notes covers every note (metadata stays serveable meanwhile).`);\n searchIndex.since = \"0\";\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 since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n // Ghosts (notes that vanished while the server was down) can only be among\n // the paths already loaded from the persisted file: a from-zero pass\n // re-delivers every live note, so a loaded path it does not deliver is\n // gone. A remote \"Rebuild database\" recreates the DB with no tombstones to\n // replay, so this is the only way to catch those deletions. Snapshot the\n // loaded paths up front and track which the pass re-delivers; limiting the\n // prune to pre-existing paths means a note the live watcher adds mid-pass\n // is never pruned.\n const preexisting = new Set(searchIndex.listPaths());\n const seen = new Set<string>();\n let fromZero = since === \"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 const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n if (content !== null) seen.add(path); else seen.delete(path);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n try {\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n searchIndex.lastSyncAt = Date.now();\n } catch (err) {\n // Re-read from the start, but don't clear() first: a from-zero pass\n // repopulates everything, and clearing would discard the still-serveable\n // persisted metadata and — if this retry also fails — leave an empty\n // index that the periodic save would then persist over the good copy.\n console.warn(`Catch-up failed (${describeError(err, debugLogging)}), re-reading from the start...`);\n changes = 0;\n seen.clear();\n fromZero = true;\n const newSince = await vault.catchUp(\"0\", countingCallback, onBatch);\n searchIndex.since = newSince;\n searchIndex.lastSyncAt = Date.now();\n }\n // Drop loaded paths a completed from-zero pass did not re-deliver. A note\n // the watcher adds mid-pass is never pruned (it is not in `preexisting`);\n // one the watcher re-adds between the pass and the prune is re-added by\n // the next pre-search catch-up, so any race is self-correcting.\n if (fromZero) pruneGhosts(searchIndex, preexisting, seen);\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 searchIndex.state = \"ready\";\n // Start the live watcher only now: the catch-up has advanced `since` to the\n // live tip, so the watcher resumes from there. Starting it at boot (before\n // the catch-up set `since`) made it replay the whole feed from seq 0\n // alongside the catch-up — a duplicate decrypt pass that roughly doubled\n // startup on large vaults. No changes are missed: the catch-up drains to the\n // current tip, the watcher continues from it.\n if (COUCHDB_URL && vault.watchChanges) startCouchDbWatcher();\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => {\n searchIndex.state = \"failed\";\n console.error(`Index rebuild failed: ${describeError(err, debugLogging)}`);\n // Still start the watcher so live updates recover: it replays from the last\n // sequence the manipulator reached (seq 0 on a cold start) and reconnects on\n // its own. On the success path the watcher is already started inside\n // rebuildIndex(); beginWatch() guards against a double start.\n if (COUCHDB_URL && vault.watchChanges) startCouchDbWatcher();\n});\n\n// --- Pre-search catch-up ---\n// search_notes calls this before every search so a hit can never predate the\n// vault: one `_changes` request from the index's own sequence (milliseconds\n// when nothing changed), applied through the same applyIndexChange path as\n// the startup rebuild and the watcher. Calls are serialized so two searches\n// cannot interleave their batches. Errors are returned, never thrown: the\n// search still runs on the index as it is and the status line says so.\nlet syncChain: Promise<unknown> = Promise.resolve();\nasync function syncBeforeSearch(): Promise<{ unreadable: number; error?: string }> {\n if (!(COUCHDB_URL && vault.catchUp) || searchIndex.state !== \"ready\") return { unreadable: 0 };\n const run = async () => {\n const stats = { unreadable: 0 };\n try {\n const newSince = await vault.catchUp!(\n searchIndex.since || \"0\",\n (path, content, mtime) => applyIndexChange(searchIndex, path, content, mtime),\n undefined,\n stats,\n );\n searchIndex.since = newSince;\n searchIndex.lastSyncAt = Date.now();\n return { unreadable: stats.unreadable };\n } catch (err) {\n // Log the detail (credentials redacted) server-side; the status line\n // shown to the client gets a short reason, not a raw backend error\n // that would disclose internal hostnames or URLs.\n console.warn(`Pre-search catch-up failed: ${describeError(err, debugLogging)}`);\n return { unreadable: stats.unreadable, error: \"CouchDB sync error\" };\n }\n };\n const result = syncChain.then(run, run);\n syncChain = result.catch(() => undefined);\n return result;\n}\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}\n\n// Remote mode: watch the CouchDB _changes feed for LiveSync updates. Called from\n// rebuildIndex() after the initial catch-up, so the watcher resumes from the\n// caught-up `since` rather than replaying the whole feed from seq 0.\nfunction startCouchDbWatcher() {\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) {\n searchIndex.since = String(seq);\n searchIndex.lastSyncAt = Date.now();\n }\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 && safeEqual(header, 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, COUCHDB_URL ? syncBeforeSearch : undefined);\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: ${describeError(err, debugLogging)}`);\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 approved: boolean;\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\n/**\n * Constant-time string comparison for secrets. Comparing SHA-256 digests gives\n * timingSafeEqual equal-length inputs, so it never throws on a length or\n * encoding mismatch and the secret's length is not revealed.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const da = createHash(\"sha256\").update(a).digest();\n const db = createHash(\"sha256\").update(b).digest();\n return timingSafeEqual(da, db);\n}\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 approved: false,\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, hostOf(redirectUri), client.clientName));\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 if (typeof submittedCsrf !== \"string\" || !safeEqual(submittedCsrf, expectedCsrf)) {\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, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n if (typeof submittedPassword !== \"string\" || !safeEqual(submittedPassword, password)) {\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, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n // Mark the code redeemable only now that the password has been verified.\n // Without this, /oauth/token would accept the code straight out of the\n // authorize page before any password was entered.\n pending.approved = true;\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 // The code is only redeemable once the password step succeeded.\n // It exists in pendingAuths from /oauth/authorize onward (and is\n // present in the authorize page HTML), so without this check the\n // password gate can be bypassed entirely.\n if (!pending.approved) {\n console.warn(\"Auth: /oauth/token invalid_grant. code not yet approved (password step not completed)\");\n return c.json({ error: \"invalid_grant\", error_description: \"authorization not approved\" }, 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 hostOf(uri: string): string {\n try {\n return new URL(uri).host;\n } catch {\n return uri;\n }\n}\n\nfunction renderPasswordPage(code: string, csrf: string, redirectHost: string, clientName: string | undefined, error?: string): string {\n const esc = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n const who = clientName ? `<b>${esc(clientName)}</b> (name self-reported)` : \"An application\";\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 .dest { background: #f3f3f3; padding: 8px 10px; border-radius: 6px; word-break: break-all; }\n .warn { color: #a15c00; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n <p>${who} is requesting access to your vault. After you approve, your browser will be sent to:</p>\n <p class=\"dest\"><b>${esc(redirectHost)}</b></p>\n <p class=\"warn\">Only enter your password if you recognize this destination. If you did not start this sign-in, close this page.</p>\n ${error ? `<p class=\"error\">${esc(error)}</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, and keeps the decrypted\n * note text in memory for `search_notes` (substring search over content).\n * Metadata persists to disk (encrypted if passphrase is set); the content map\n * is rebuilt from the vault at startup and is never written to disk.\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\";\nimport { isValidNotePath } from \"./note-path.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\n/**\n * Lifecycle of the in-memory index. \"building\" from construction until the\n * startup rebuild finishes, \"ready\" afterwards, \"failed\" if the rebuild threw.\n * Read by list_notes and search_notes so a client can tell a partial index from a complete one.\n */\nexport type IndexState = \"building\" | \"ready\" | \"failed\";\n\nexport interface SearchQuery {\n /** Case-insensitive substrings; a note matches when ANY term occurs (OR). A term may contain spaces. */\n terms?: string[];\n folder?: string;\n tag?: string;\n /** Only notes with mtime >= this (ms since epoch). */\n modifiedAfter?: number;\n limit?: number;\n}\n\nexport interface SearchHit {\n path: string;\n mtime: number;\n /** Distinct terms that matched in path/title or content. */\n matched: number;\n /** True when the path or the frontmatter title matched. Name hits rank first. */\n nameHit: boolean;\n /** One line of context around the first content match; whitespace collapsed. Empty for a name-only hit. */\n snippet: string;\n}\n\n/** Cut a one-line snippet around `idx` (match of length `len`), whitespace collapsed. */\nexport function snippetAround(text: string, idx: number, len: number, context = 80): string {\n const start = Math.max(0, idx - context);\n const end = Math.min(text.length, idx + len + context);\n const body = text.slice(start, end).replace(/\\s+/g, \" \").trim();\n return (start > 0 ? \"…\" : \"\") + body + (end < text.length ? \"…\" : \"\");\n}\n\nexport class SearchIndex {\n private _state: IndexState = \"building\";\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 /** Decrypted note text, in memory only — one copy per note; term matching is case-insensitive via a regex per term. */\n private content = new Map<string, string>();\n /** Frontmatter `title:` per path, when present — searched together with the path. */\n private titles = new Map<string, string>();\n private saving = false;\n private _since: string = \"\";\n /** When `since` last advanced from a completed catch-up or a watcher change (ms), null before the first. */\n private _lastSyncAt: number | null = null;\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 /**\n * Add or update a note in the index. The watcher and the pre-search\n * catch-up both write here without coordinating, so a write whose mtime is\n * not newer than the one recorded for text already held is skipped: a\n * stale copy can never replace a newer one. Mtimes loaded from disk carry\n * no text, so the startup rebuild still fills them in.\n */\n update(path: string, content: string, mtime?: number): void {\n if (mtime !== undefined && this.content.has(path) && mtime <= (this.mtimes.get(path) ?? -Infinity)) return;\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 // Same code path for the startup catch-up, the watcher and the\n // pre-search catch-up: whatever updates metadata also updates content.\n this.content.set(path, content);\n const parsed = parseFrontmatterAndLinks(content);\n const title = parsed.frontmatter[\"title\"];\n if (typeof title === \"string\" && title.trim().length > 0) {\n this.titles.set(path, title.trim());\n } else {\n this.titles.delete(path);\n }\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.content.delete(path);\n this.titles.delete(path);\n this.clearBacklinks(path);\n }\n }\n\n /** Decrypted text of a note, or null if the index holds no content for it. */\n getContent(path: string): string | null {\n return this.content.get(path) ?? null;\n }\n\n /** Notes whose text is in memory. Below `size` means search cannot see every note. */\n get contentCount(): number {\n return this.content.size;\n }\n\n /**\n * Search over path + frontmatter title first, then the in-memory text.\n * Ranked: name hits first, then number of distinct terms matched, then\n * newest first, then path. `limit` defaults to 20.\n */\n search(q: SearchQuery): { hits: SearchHit[]; total: number } {\n const prefix = q.folder ? (q.folder.endsWith(\"/\") ? q.folder : q.folder + \"/\") : undefined;\n const terms = (q.terms ?? []).filter((t) => t.length > 0).map((t) => ({\n text: t.toLowerCase(),\n // Case-insensitive (Unicode) search over the note text without a lowercased copy of the vault in memory.\n re: new RegExp(t.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"), \"iu\"),\n }));\n const hits: SearchHit[] = [];\n for (const [path, entry] of this.content) {\n // Mirror the ingest filter (GHSA-hfcr-mrh3-c584): the content map is\n // only fed validated paths, so this is defense in depth, not a gate.\n if (!isValidNotePath(path)) continue;\n if (prefix && !path.startsWith(prefix)) continue;\n if (q.tag && !this.getTags(path).includes(q.tag)) continue;\n const mtime = this.mtimes.get(path) ?? 0;\n if (q.modifiedAfter !== undefined && mtime < q.modifiedAfter) continue;\n // Step 1: path and title. Step 2: content. A term counts once even if it hits both.\n const title = this.titles.get(path);\n const name = title ? `${path} ${title}` : path;\n const nameLower = name.toLowerCase();\n let matched = 0;\n let nameHit = false;\n let anchor = -1;\n let anchorLen = 1;\n {\n for (const t of terms) {\n const inName = nameLower.includes(t.text);\n const i = entry.search(t.re);\n if (!inName && i === -1) continue;\n matched++;\n if (inName) nameHit = true;\n if (i !== -1 && (anchor === -1 || i < anchor)) {\n anchor = i;\n anchorLen = t.text.length;\n }\n }\n if (matched === 0) continue;\n }\n const snippet = anchor === -1 ? \"\" : snippetAround(entry, anchor, anchorLen);\n hits.push({ path, mtime, matched, nameHit, snippet });\n }\n hits.sort(\n (a, b) =>\n Number(b.nameHit) - Number(a.nameHit) ||\n b.matched - a.matched ||\n b.mtime - a.mtime ||\n a.path.localeCompare(b.path),\n );\n return { hits: hits.slice(0, q.limit ?? 20), total: hits.length };\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(isValidNotePath)\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 this._state = \"building\";\n }\n\n get state(): IndexState {\n return this._state;\n }\n\n set state(value: IndexState) {\n this._state = value;\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 lastSyncAt(): number | null {\n return this._lastSyncAt;\n }\n\n set lastSyncAt(value: number | null) {\n this._lastSyncAt = 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","/**\n * READ_ONLY enforcement at the backend layer.\n *\n * READ_ONLY=true already keeps the write tools from being registered. Wrapping\n * the backend as well means a write fails even if some future code path\n * reaches writeNote/deleteNote/moveNote without going through a tool.\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nexport const READ_ONLY_MESSAGE = \"READ_ONLY is enabled: the vault cannot be modified.\";\n\n/** Return a backend that delegates reads to `inner` and rejects every write. */\nexport function readOnlyVault(inner: VaultBackend): VaultBackend {\n const deny = async (): Promise<never> => {\n throw new Error(READ_ONLY_MESSAGE);\n };\n return {\n init: () => inner.init(),\n close: () => inner.close(),\n readNote: (path) => inner.readNote(path),\n getMetadata: (path) => inner.getMetadata(path),\n listNotes: (folder) => inner.listNotes(folder),\n listNotesWithMtime: (folder) => inner.listNotesWithMtime(folder),\n watchChanges: inner.watchChanges?.bind(inner),\n catchUp: inner.catchUp?.bind(inner),\n writeNote: deny,\n deleteNote: deny,\n moveNote: deny,\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\";\nimport { describeListing, describeNoMatch } from \"./list-format.js\";\nimport { describeHits, describeQuery, describeSync, type SyncStatus } from \"./search-format.js\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\n/** Runs a CouchDB catch-up before a search; undefined in local (VAULT_PATH) mode. */\nexport type SyncBeforeSearch = () => Promise<{ unreadable: number; error?: string }>;\n\nexport const SEARCH_MAX_HITS = 20;\n/** Each term is one more regex pass over every note (synchronous), so the count is capped. */\nexport const SEARCH_MAX_TERMS = 20;\n/** Each term is compiled into a regex; a very long one overflows the stack (~10 KB with flags iu) or blocks the event loop, so its length is capped. */\nexport const SEARCH_MAX_TERM_LENGTH = 200;\n\n/** Trim, drop empty terms, cut each to SEARCH_MAX_TERM_LENGTH and clamp to SEARCH_MAX_TERMS — a backstop behind the schema's .max(). */\nexport function cleanSearchTerms(terms: string[] | undefined): string[] {\n return (terms ?? [])\n .map((t) => t.trim().slice(0, SEARCH_MAX_TERM_LENGTH))\n .filter((t) => t.length > 0)\n .slice(0, SEARCH_MAX_TERMS);\n}\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\n// Claude Code persists any MCP tool result above ~50 000 characters to a file\n// and hands the model a 2 kB preview instead of the text. A tool can raise its\n// own threshold (hard ceiling 500 000) by declaring\n// `_meta[\"anthropic/maxResultSizeChars\"]` in its tools/list entry; text from\n// such a tool is then also exempt from MAX_MCP_OUTPUT_TOKENS. See\n// https://code.claude.com/docs/en/mcp#raise-the-limit-for-a-specific-tool\n// read_note returns whole notes, so it declares 100 000: enough for a large\n// note to arrive in one piece, small enough to keep one read inside a sane\n// context budget. Other clients ignore the key.\nexport const READ_NOTE_MAX_RESULT_SIZE_CHARS = 100_000;\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 syncBeforeSearch?: SyncBeforeSearch,\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 _meta: { \"anthropic/maxResultSizeChars\": READ_NOTE_MAX_RESULT_SIZE_CHARS },\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 let vaultTotal: number | null = searchIndex.size;\n let servedByVault = false;\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n servedByVault = notes.length > 0;\n // The fallback only tells us the vault total when it was unscoped.\n if (vaultTotal === 0) vaultTotal = folder ? null : notes.length;\n }\n const folderTotal = folder ? notes.length : null;\n const filters: string[] = [];\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n filters.push(`name=\"${name}\"`);\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n filters.push(`tag=\"${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 filters.push(`modified_after=\"${modified_after}\"`);\n }\n const index = { state: searchIndex.state, size: searchIndex.size, servedByVault };\n if (notes.length === 0) {\n return describeNoMatch({ vaultTotal, folder, folderTotal, filters, index });\n }\n const sortBy = sort_by === \"modified\" ? \"modified\" : \"name\";\n if (sortBy === \"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 header = describeListing({\n shown: capped.length,\n matched: total,\n vaultTotal,\n folder,\n folderTotal,\n filters,\n sortBy,\n limit: cap,\n omitted: notes.slice(cap).map((n) => n.path),\n index,\n });\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 return [header, ...lines].join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"search_notes\",\n description:\n \"Search note contents for terms, case-insensitive.\\n\" +\n \"Paths and frontmatter titles are searched first and such hits rank on top, marked [path/title]; content hits follow. \" +\n \"Returns paths with one context line each, never the note body: call read_note on a hit before relying on it. \" +\n \"Give `terms` (a note matches when ANY term occurs — OR, so list synonyms, field names and other-language wordings; a term may contain spaces; ranked by how many terms match) \" +\n \"Filters: folder, tag, modified_after. \" +\n \"The first line of every response is the index status: the CouchDB sequence the index is caught up with after a catch-up run just before the search, \" +\n \"the server time (local zone and UTC), its age in minutes, how many notes carry content, and any documents that could not be read.\",\n parameters: z.object({\n terms: z\n .array(z.string().max(SEARCH_MAX_TERM_LENGTH))\n .max(SEARCH_MAX_TERMS)\n .optional()\n .describe(`Case-insensitive substrings, at most ${SEARCH_MAX_TERMS} of at most ${SEARCH_MAX_TERM_LENGTH} characters each; a note matches when any of them occurs. E.g. ['drag i kanban', 'kanban', 'labels på kategori'].`),\n folder: z\n .string()\n .optional()\n .describe(\"Folder to search in, e.g. 'projects'. Omit for the whole vault.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Only notes carrying this tag, e.g. 'project'.\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only 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 hits to return, default and maximum ${SEARCH_MAX_HITS}.`),\n }),\n execute: async ({ terms, folder, tag, modified_after, limit }) => {\n const cleanTerms = cleanSearchTerms(terms);\n if (cleanTerms.length === 0) {\n return \"Give at least one term.\";\n }\n let modifiedAfter: number | undefined;\n if (modified_after) {\n modifiedAfter = new Date(modified_after).getTime();\n if (isNaN(modifiedAfter)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n }\n const cap = Math.max(1, Math.min(SEARCH_MAX_HITS, limit ?? SEARCH_MAX_HITS));\n\n // Catch up first, so a hit can never predate the vault (see main.ts).\n const sync = syncBeforeSearch ? await syncBeforeSearch() : { unreadable: 0 };\n const status: SyncStatus = {\n mode: syncBeforeSearch ? \"couchdb\" : \"local\",\n state: searchIndex.state,\n seq: searchIndex.since,\n syncedAt: searchIndex.lastSyncAt,\n now: Date.now(),\n notes: searchIndex.size,\n withContent: searchIndex.contentCount,\n unreadable: sync.unreadable,\n error: sync.error,\n };\n const { hits, total } = searchIndex.search({ terms: cleanTerms, folder, tag, modifiedAfter, limit: cap });\n const query = describeQuery(cleanTerms);\n return `${describeSync(status)}\\n${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;\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 // The sync layer reports success even when nothing existed at the\n // path, so \"Deleted\" would claim a cleanup that never happened.\n // readNote returns \"\" for an empty note and null only when absent.\n const existing = await vault.readNote(path);\n if (existing === null) return `Note not found: ${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","import type { IndexState } from \"./search.js\";\n\n/**\n * Response wording for list_notes (issue #19). Kept free of MCP/vault types so\n * it can be unit-tested: the goal is that an LLM client can never mistake a\n * truncated, filtered or still-indexing listing for \"the vault contains\n * nothing else\".\n */\n\nexport const MAX_NAMED_FOLDERS = 10;\n\nexport interface ListingSummary {\n /** Notes actually returned (after the limit). */\n shown: number;\n /** Notes matching all filters (before the limit). */\n matched: number;\n /** Notes in the whole vault, before any filter; null when unknown. */\n vaultTotal: number | null;\n /** Folder filter as given by the caller, if any. */\n folder?: string;\n /** Notes inside `folder` before the other filters; null when unknown. */\n folderTotal?: number | null;\n /** Non-folder filters that were applied, e.g. `name=\"x\"`, `tag=\"y\"`. */\n filters: string[];\n sortBy: \"name\" | \"modified\";\n limit: number;\n /** Paths cut by the limit, used to name the omitted folders. */\n omitted: string[];\n index: IndexStatus;\n}\n\nexport interface IndexStatus {\n state: IndexState;\n size: number;\n /** True when the notes were read straight from the vault because the index had nothing — the list itself is complete. */\n servedByVault?: boolean;\n}\n\nexport interface FolderCount {\n folder: string;\n count: number;\n}\n\nfunction plural(n: number, word: string): string {\n return `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n}\n\nfunction folderLabel(folder: string): string {\n return folder.endsWith(\"/\") ? folder : folder + \"/\";\n}\n\n/** Group paths by their immediate parent folder; root-level notes count under \"(root)\". */\nexport function countByFolder(paths: string[]): FolderCount[] {\n const counts = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n const folder = lastSlash === -1 ? \"(root)\" : p.slice(0, lastSlash);\n counts.set(folder, (counts.get(folder) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([folder, count]) => ({ folder, count }))\n .sort((a, b) => b.count - a.count || a.folder.localeCompare(b.folder));\n}\n\n/** \"Omitted 106: a/ (41), b/ (9), … and 3 more folders (56 notes).\" — the counts always add up to the total. */\nexport function describeOmitted(omitted: string[]): string {\n const groups = countByFolder(omitted);\n const named = groups.slice(0, MAX_NAMED_FOLDERS);\n const rest = groups.slice(MAX_NAMED_FOLDERS);\n const parts = named.map((g) => `${g.folder === \"(root)\" ? \"(root)\" : folderLabel(g.folder)} (${g.count})`);\n let text = `Omitted ${omitted.length}: ${parts.join(\", \")}`;\n if (rest.length > 0) {\n const restNotes = rest.reduce((sum, g) => sum + g.count, 0);\n text += `, and ${plural(rest.length, \"more folder\")} (${plural(restNotes, \"note\")})`;\n }\n return text + \".\";\n}\n\n/** Appended to every response while the index is not known to be complete. */\nexport function describeIndexState(index: IndexStatus): string {\n const caveat = index.servedByVault\n ? \"this list was read directly from the vault\"\n : \"this list may be incomplete\";\n switch (index.state) {\n case \"ready\":\n return \"\";\n case \"building\":\n return ` Index: catching up (${plural(index.size, \"note\")} indexed so far); ${caveat}.`;\n case \"failed\":\n return ` Index: rebuild failed at startup (see server log); ${index.servedByVault ? caveat : \"this list may be incomplete or stale\"}.`;\n }\n}\n\n/**\n * \"vault has N notes\" / \"folder has N notes\" — only when the number can be\n * trusted: the index is ready, or the notes came straight from the vault.\n * While the index is still building, its size is a partial count and the\n * index caveat carries it instead.\n */\nfunction describeScopeCount(s: Pick<ListingSummary, \"vaultTotal\" | \"folder\" | \"folderTotal\" | \"index\">): string {\n if (s.index.state !== \"ready\" && !s.index.servedByVault) return \"\";\n if (s.folder) return s.folderTotal != null ? `folder has ${plural(s.folderTotal, \"note\")}` : \"\";\n return s.vaultTotal != null ? `vault has ${plural(s.vaultTotal, \"note\")}` : \"\";\n}\n\n/** Response for a listing with zero matches. */\nexport function describeNoMatch(s: Omit<ListingSummary, \"shown\" | \"matched\" | \"omitted\" | \"sortBy\" | \"limit\">): string {\n const indexNote = describeIndexState(s.index);\n if (s.filters.length === 0) {\n if (s.folder) return `No notes found in folder: ${s.folder}${indexNote}`;\n return `Vault is empty.${indexNote}`;\n }\n const count = describeScopeCount(s);\n const scope = (s.folder ? ` in folder \"${folderLabel(s.folder)}\"` : \"\") + (count ? ` (${count})` : \"\");\n return `No notes match ${s.filters.join(\", \")}${scope}.${indexNote}`;\n}\n\n/**\n * First line of a non-empty listing. Always present, so the index state and\n * the filter scope are visible even when nothing was cut.\n */\nexport function describeListing(s: ListingSummary): string {\n const truncated = s.matched > s.shown;\n // \"5 notes match name=…\" reads as a sentence; \"Showing 100 of 150 notes matching …\" needs the participle.\n const verb = truncated ? \"matching\" : s.matched === 1 ? \"matches\" : \"match\";\n const filterClause = s.filters.length > 0 ? ` ${verb} ${s.filters.join(\", \")}` : \"\";\n const folderClause = s.folder ? ` in folder \"${folderLabel(s.folder)}\"` : \"\";\n const scopeParts: string[] = [];\n const count = s.filters.length > 0 || s.folder ? describeScopeCount(s) : \"\";\n if (count) scopeParts.push(count);\n // Every source (index, CouchDB enumeration, local glob) sorts by path with localeCompare, so \"sorted by name\" is literal.\n scopeParts.push(`sorted by ${s.sortBy}`);\n if (truncated) scopeParts.push(`limit=${s.limit}`);\n const scope = ` (${scopeParts.join(\", \")})`;\n\n let line = truncated\n ? `Showing ${s.shown} of ${plural(s.matched, \"note\")}${filterClause}${folderClause}${scope}.`\n : `${plural(s.matched, \"note\")}${filterClause}${folderClause}${scope}.`;\n if (truncated) {\n const hint = s.folder || s.filters.length > 0 ? \"Raise `limit` or narrow the filter.\" : \"Raise `limit` or add a `folder` filter.\";\n line += ` ${describeOmitted(s.omitted)} ${hint}`;\n }\n return line + describeIndexState(s.index);\n}\n","/**\n * Response wording for search_notes. Pure functions, no MCP/vault types, so\n * the index-status line — the part a client relies on to judge freshness —\n * is unit-testable against fixed instants.\n *\n * Every search response opens with one status line that says which CouchDB\n * sequence the index is caught up with, the server time (local zone plus UTC),\n * how old that is, how many notes carry content, and whether any document\n * could not be read during the pre-search catch-up. \"Caught up\" must never\n * hide a silent miss.\n */\n\nimport type { IndexState, SearchHit } from \"./search.js\";\n\n/**\n * Validate a display zone once. An unknown zone makes Intl.DateTimeFormat\n * throw, which would break every search_notes call, so it falls back to UTC\n * with a logged warning instead.\n */\nexport function resolveDisplayZone(raw: string | undefined): string {\n const zone = raw?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: zone });\n return zone;\n } catch {\n console.warn(`DISPLAY_TIMEZONE \"${zone}\" is not a valid IANA time zone; using UTC.`);\n return \"UTC\";\n }\n}\n\n/** Zone used for the human-readable half of the timestamp (default: the server's own zone). UTC is always printed beside it. */\nexport const DISPLAY_TIMEZONE = resolveDisplayZone(process.env.DISPLAY_TIMEZONE);\n\nexport interface SyncStatus {\n /** \"couchdb\" when a catch-up ran (or was attempted) before the search; \"local\" for a VAULT_PATH vault. */\n mode: \"couchdb\" | \"local\";\n state: IndexState;\n /** The index's CouchDB sequence after the catch-up (raw, e.g. \"39995-g1AAAA…\"). */\n seq: string;\n /** When the sequence last advanced (ms), null before the first catch-up. */\n syncedAt: number | null;\n /** Server time the response was built (ms). */\n now: number;\n notes: number;\n withContent: number;\n /** Documents the catch-up could not decrypt or load. */\n unreadable: number;\n /** Set when the pre-search catch-up threw; hits then come from the index as it was. */\n error?: string;\n}\n\n/** \"2026-09-20 15:30 CEST (13:30Z)\" — local zone from Intl (sv-SE yields CET/CEST), UTC beside it. */\nexport function formatServerTime(ms: number, timeZone: string = DISPLAY_TIMEZONE): string {\n const d = new Date(ms);\n const parts = new Intl.DateTimeFormat(\"sv-SE\", {\n timeZone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hourCycle: \"h23\",\n timeZoneName: \"short\",\n }).formatToParts(d);\n const get = (type: string) => parts.find((p) => p.type === type)?.value ?? \"\";\n const utc = d.toISOString().slice(11, 16);\n return `${get(\"year\")}-${get(\"month\")}-${get(\"day\")} ${get(\"hour\")}:${get(\"minute\")} ${get(\"timeZoneName\")} (${utc}Z)`;\n}\n\n/** The numeric prefix of a CouchDB sequence (\"39995\" from \"39995-g1AAAA…\"); \"none\" when empty. */\nexport function seqPrefix(seq: string): string {\n if (!seq) return \"none\";\n const dash = seq.indexOf(\"-\");\n return dash === -1 ? seq : seq.slice(0, dash);\n}\n\nfunction minutesBetween(from: number, to: number): number {\n return Math.max(0, Math.round((to - from) / 60_000));\n}\n\nfunction plural(n: number, word: string): string {\n return `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n}\n\n/** First line of every search_notes response. `timeZone` is the display zone; tests pass it so the wording does not depend on the machine's zone. */\nexport function describeSync(s: SyncStatus, timeZone: string = DISPLAY_TIMEZONE): string {\n const now = formatServerTime(s.now, timeZone);\n const coverage = `${s.withContent} of ${plural(s.notes, \"note\")} with content`;\n if (s.mode === \"local\") {\n return `Index: local vault, no sequence — ${now}; ${coverage}.`;\n }\n if (s.state === \"building\") {\n return `Index: still building (${plural(s.notes, \"note\")} so far), not caught up — ${now}; results may be incomplete.`;\n }\n if (s.state === \"failed\") {\n return `Index: rebuild failed at startup (see server log), not caught up — ${now}; results may be incomplete or stale.`;\n }\n if (s.error) {\n const last = s.syncedAt === null ? \"never\" : `${formatServerTime(s.syncedAt, timeZone)}, ${minutesBetween(s.syncedAt, s.now)} min ago`;\n return `Index: catch-up failed (${s.error}); last caught up with CouchDB seq ${seqPrefix(s.seq)} — ${last}; results may be stale.`;\n }\n const age = s.syncedAt === null ? 0 : minutesBetween(s.syncedAt, s.now);\n let line = `Index caught up with CouchDB seq ${seqPrefix(s.seq)} — ${now}, ${age} min; ${coverage}`;\n if (s.unreadable > 0) {\n line += `; ${plural(s.unreadable, \"document\")} could not be read`;\n }\n return line + \".\";\n}\n\n/** What was searched, for the second line. */\nexport function describeQuery(terms: string[]): string {\n return terms.map((t) => `\"${t}\"`).join(\", \");\n}\n\n/**\n * Hit lines: path with deep link and modification time (same shape as\n * list_notes), then one indented context line. Never the note body.\n */\nexport function describeHits(\n hits: SearchHit[],\n total: number,\n query: string,\n deepLink: (path: string) => string,\n): string {\n if (total === 0) return `No notes match ${query}.`;\n const shown = hits.length < total ? ` (showing ${hits.length}; narrow with folder, tag or modified_after)` : \"\";\n const nameHits = hits.filter((h) => h.nameHit).length;\n const byName = nameHits > 0 ? ` ${plural(nameHits, \"hit\")} by path or title listed first.` : \"\";\n const header = `${plural(total, \"note\")} ${total === 1 ? \"matches\" : \"match\"} ${query}${shown}.${byName} Call read_note on a hit before relying on it.`;\n const lines = hits.map((h) => {\n const date = h.mtime ? new Date(h.mtime).toISOString().slice(0, 16) : \"\";\n const context = h.nameHit\n ? (h.snippet ? `[path/title] ${h.snippet}` : \"[path/title match]\")\n : h.snippet;\n return `- ${date} [${h.path}](${deepLink(h.path)})\\n ${context}`;\n });\n return [header, ...lines].join(\"\\n\");\n}\n","/**\n * Log redaction helpers.\n *\n * COUCHDB_URL may embed credentials as `user:pass@host`. Anything written to\n * the log goes through these so the password never lands in container logs.\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nimport { inspect } from \"node:util\";\n\n/** Replace the userinfo part of every URL in `text` (e.g. `http://u:p@h` -> `http://***@h`). */\nexport function redactCredentials(text: string): string {\n // Greedy up to the last \"@\" before the path, as URL parsers split userinfo,\n // so an unencoded \"@\" in the password is still fully covered.\n return text.replace(/\\b([a-z][a-z0-9+.-]*:\\/\\/)[^\\s/?#]+@/gi, \"$1***@\");\n}\n\n/**\n * One-line description of an error for logs: the message only, redacted.\n * With `verbose` (LOG_LEVEL=debug) the stack is kept, still redacted.\n * The cause chain is appended: fetch() reports \"fetch failed\" and keeps the\n * useful part (ECONNREFUSED, ENOTFOUND, ...) in `cause`.\n */\nexport function describeError(err: unknown, verbose = false): string {\n if (!(err instanceof Error)) return redactCredentials(String(err));\n let text = verbose && err.stack ? err.stack : `${err.name}: ${err.message}`;\n const causes: string[] = [];\n let cause: unknown = err.cause;\n for (let depth = 0; cause !== undefined && cause !== null && depth < 3; depth++) {\n if (cause instanceof Error) {\n causes.push(cause.message || String((cause as NodeJS.ErrnoException).code ?? cause.name));\n cause = cause.cause;\n } else {\n causes.push(String(cause));\n break;\n }\n }\n if (causes.length > 0) text += ` (cause: ${causes.join(\" <- \")})`;\n return redactCredentials(text);\n}\n\n/**\n * Redacted text for anything handed to the library log hook. The library logs\n * strings, but also raw Error objects (`Logger(ex)`) and occasionally other\n * values; console.log would print those (stack and cause chain included)\n * without redaction. Other values are rendered as console.log would, via\n * inspect(), which also copes with circular references and BigInt.\n */\nexport function describeLogMessage(message: unknown, verbose = false): string {\n if (typeof message === \"string\") return redactCredentials(message);\n if (message instanceof Error) return describeError(message, verbose);\n return redactCredentials(inspect(message));\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,OAAO,cAAc,gBAAgB;AAC9C,SAAS,YAAY;AACrB,SAAS,sBAAsB,kBAAkB;;;ACUjD,SAAS,YAAY,aAAa,YAAY,uBAAuB;AACrE,SAAS,UAAU,WAAW,OAAO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,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,QAA4C,sBAAsB,IAAI,EAAE;AAG1G,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACtC,UAAQ,MAAM,wBAAwB,cAAc,KAAKA,aAAY,CAAC,EAAE;AAC5E,CAAC;","names":["createHash","client","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","plural","server","vault","searchIndex","syncBeforeSearch","debugLogging","createHash"]}