obsidian-sync-mcp 0.5.5 → 0.5.6
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.
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Node polyfills for livesync-commonlib browser globals
|
|
3
|
+
if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
|
|
4
|
+
|
|
5
|
+
// src/index-sync.ts
|
|
6
|
+
function deriveContent(doc) {
|
|
7
|
+
if (doc.deleted) return null;
|
|
8
|
+
return "data" in doc && Array.isArray(doc.data) ? doc.data.join("") : "";
|
|
9
|
+
}
|
|
10
|
+
function applyIndexChange(index, path, content, mtime) {
|
|
11
|
+
if (content !== null) {
|
|
12
|
+
index.update(path, content, mtime);
|
|
13
|
+
} else {
|
|
14
|
+
index.remove(path);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
deriveContent,
|
|
20
|
+
applyIndexChange
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=chunk-SGLPTZJA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index-sync.ts"],"sourcesContent":["/**\n * Shared search-index sync helpers.\n *\n * Kept dependency-free (no livesync-commonlib imports) so the delete-vs-empty\n * routing is unit-testable in isolation.\n */\n\nexport interface IndexTarget {\n update(path: string, content: string, mtime?: number): void;\n remove(path: string): void;\n}\n\n/**\n * Derive index content from a LiveSync change doc.\n *\n * Returns `null` ONLY when the note is deleted. An existing note with no body\n * yields `\"\"` so a zero-byte note stays distinguishable from a deletion —\n * without this, a note that serializes with no `data` array would look deleted.\n */\nexport function deriveContent(doc: { deleted?: boolean; data?: unknown }): string | null {\n if (doc.deleted) return null;\n return \"data\" in doc && Array.isArray(doc.data) ? doc.data.join(\"\") : \"\";\n}\n\n/**\n * Route a change into the index: `null` content removes (the note was deleted),\n * any string — including `\"\"` — upserts. Using `content !== null` (rather than a\n * truthiness check) keeps zero-byte notes indexed instead of dropping them\n * (issues #5 / #6).\n */\nexport function applyIndexChange(index: IndexTarget, path: string, content: string | null, mtime?: number): void {\n if (content !== null) {\n index.update(path, content, mtime);\n } else {\n index.remove(path);\n }\n}\n"],"mappings":";;;;;AAmBO,SAAS,cAAc,KAA2D;AACrF,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,UAAU,OAAO,MAAM,QAAQ,IAAI,IAAI,IAAI,IAAI,KAAK,KAAK,EAAE,IAAI;AAC1E;AAQO,SAAS,iBAAiB,OAAoB,MAAc,SAAwB,OAAsB;AAC7G,MAAI,YAAY,MAAM;AAClB,UAAM,OAAO,MAAM,SAAS,KAAK;AAAA,EACrC,OAAO;AACH,UAAM,OAAO,IAAI;AAAA,EACrB;AACJ;","names":[]}
|
package/dist/main.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Node polyfills for livesync-commonlib browser globals
|
|
3
3
|
if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
|
|
4
|
+
import {
|
|
5
|
+
applyIndexChange
|
|
6
|
+
} from "./chunk-SGLPTZJA.js";
|
|
4
7
|
import {
|
|
5
8
|
parseFrontmatterAndLinks
|
|
6
9
|
} from "./chunk-52RMOUUH.js";
|
|
@@ -791,7 +794,7 @@ ${content}`;
|
|
|
791
794
|
return `Failed to move: ${from} \u2192 ${to}`;
|
|
792
795
|
}
|
|
793
796
|
searchIndex2.remove(from);
|
|
794
|
-
if (content) searchIndex2.update(to, content, Date.now());
|
|
797
|
+
if (content !== null) searchIndex2.update(to, content, Date.now());
|
|
795
798
|
const deepLink = makeDeepLink(vaultName, to);
|
|
796
799
|
return `Moved: ${from} \u2192 ${to}
|
|
797
800
|
[Open in Obsidian](${deepLink})`;
|
|
@@ -895,7 +898,7 @@ if (VAULT_PATH) {
|
|
|
895
898
|
console.error("COUCHDB_PASSWORD is required in remote mode.");
|
|
896
899
|
process.exit(1);
|
|
897
900
|
}
|
|
898
|
-
const { Vault } = await import("./vault-
|
|
901
|
+
const { Vault } = await import("./vault-BL4NJC75.js");
|
|
899
902
|
vault = new Vault({
|
|
900
903
|
couchdbUrl: COUCHDB_URL,
|
|
901
904
|
couchdbUser: COUCHDB_USER,
|
|
@@ -924,11 +927,7 @@ async function rebuildIndex() {
|
|
|
924
927
|
const start = performance.now();
|
|
925
928
|
if (COUCHDB_URL && vault.catchUp) {
|
|
926
929
|
const changeCallback = (path, content, mtime) => {
|
|
927
|
-
|
|
928
|
-
searchIndex.update(path, content, mtime);
|
|
929
|
-
} else {
|
|
930
|
-
searchIndex.remove(path);
|
|
931
|
-
}
|
|
930
|
+
applyIndexChange(searchIndex, path, content, mtime);
|
|
932
931
|
};
|
|
933
932
|
let since = searchIndex.since || "0";
|
|
934
933
|
if (debugLogging2) console.log(`[debug] CouchDB catch-up from since: ${since}`);
|
|
@@ -941,7 +940,7 @@ async function rebuildIndex() {
|
|
|
941
940
|
try {
|
|
942
941
|
const countingCallback = (path, content, mtime) => {
|
|
943
942
|
changes++;
|
|
944
|
-
if (debugLogging2) console.log(`[debug] Change: ${path} ${content ? "(update)" : "(delete)"}`);
|
|
943
|
+
if (debugLogging2) console.log(`[debug] Change: ${path} ${content !== null ? "(update)" : "(delete)"}`);
|
|
945
944
|
changeCallback(path, content, mtime);
|
|
946
945
|
};
|
|
947
946
|
const newSince = await vault.catchUp(since, countingCallback, onBatch);
|
|
@@ -973,7 +972,7 @@ async function rebuildIndex() {
|
|
|
973
972
|
for (let i = 0; i < notesWithMtime.length; i++) {
|
|
974
973
|
const { path, mtime } = notesWithMtime[i];
|
|
975
974
|
const content = await vault.readNote(path);
|
|
976
|
-
if (content) searchIndex.update(path, content, mtime);
|
|
975
|
+
if (content !== null) searchIndex.update(path, content, mtime);
|
|
977
976
|
if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {
|
|
978
977
|
console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);
|
|
979
978
|
}
|
|
@@ -1011,13 +1010,8 @@ if (VAULT_PATH) {
|
|
|
1011
1010
|
console.log("Watching vault for external changes.");
|
|
1012
1011
|
} else if (COUCHDB_URL && vault.watchChanges) {
|
|
1013
1012
|
vault.watchChanges((path, content, mtime, seq) => {
|
|
1014
|
-
if (
|
|
1015
|
-
|
|
1016
|
-
searchIndex.update(path, content, mtime);
|
|
1017
|
-
} else {
|
|
1018
|
-
if (debugLogging2) console.log(`[debug] CouchDB delete: ${path}`);
|
|
1019
|
-
searchIndex.remove(path);
|
|
1020
|
-
}
|
|
1013
|
+
if (debugLogging2) console.log(`[debug] CouchDB ${content === null ? "delete" : "change"}: ${path}`);
|
|
1014
|
+
applyIndexChange(searchIndex, path, content, mtime);
|
|
1021
1015
|
if (seq) searchIndex.since = String(seq);
|
|
1022
1016
|
});
|
|
1023
1017
|
console.log("Watching CouchDB for LiveSync changes.");
|
|
@@ -1025,7 +1019,7 @@ if (VAULT_PATH) {
|
|
|
1025
1019
|
var BASE_INSTRUCTIONS = "Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.";
|
|
1026
1020
|
var serverOptions = {
|
|
1027
1021
|
name: "obsidian-sync-mcp",
|
|
1028
|
-
version: "0.5.
|
|
1022
|
+
version: "0.5.6",
|
|
1029
1023
|
instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
|
|
1030
1024
|
|
|
1031
1025
|
${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
|
|
@@ -1080,7 +1074,7 @@ server.start({
|
|
|
1080
1074
|
transportType: "httpStream",
|
|
1081
1075
|
httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
|
|
1082
1076
|
});
|
|
1083
|
-
console.log(`obsidian-sync-mcp v${"0.5.
|
|
1077
|
+
console.log(`obsidian-sync-mcp v${"0.5.6"} listening on port ${PORT}`);
|
|
1084
1078
|
process.on("unhandledRejection", (err) => {
|
|
1085
1079
|
console.error("Unhandled rejection:", err);
|
|
1086
1080
|
});
|
package/dist/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/tools.ts","../src/deeplink.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { timingSafeEqual, createHash } from \"crypto\";\nimport { watch, readFileSync, statSync } from \"fs\";\nimport { stat } from \"fs/promises\";\nimport { setGlobalLogFunction, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { mountPasswordAuth } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { registerTools } from \"./tools.js\";\n\n// Suppress livesync-commonlib logs that expose vault file paths in production.\n// Set LOG_LEVEL=debug to see all library logs during development.\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\nsetGlobalLogFunction((message, level = LEVEL_INFO) => {\n if (level < LEVEL_INFO) return;\n if (!debugLogging && typeof message === \"string\") {\n if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;\n if (message.includes(\"replicator\") || message.includes(\"Replicator\") || message.includes(\"ReplicatorService\")) return;\n }\n console.log(message);\n});\n\n// --- Configuration from environment ---\nconst VAULT_PATH = process.env.VAULT_PATH; // Local mode: path to vault directory\nconst COUCHDB_URL = process.env.COUCHDB_URL;\nconst COUCHDB_USER = process.env.COUCHDB_USER ?? \"admin\";\nconst COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;\nconst COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? \"obsidian\";\nconst COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || undefined;\nconst COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === \"true\";\nconst VAULT_NAME = process.env.VAULT_NAME ?? \"MyVault\";\nconst PORT = parseInt(process.env.PORT ?? \"8787\");\nconst BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;\nconst AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;\nconst READ_ONLY = process.env.READ_ONLY === \"true\";\n\n// Extra instructions appended to the MCP `instructions` string.\n// File wins if both are set (loud warning); missing file is fatal.\nconst MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || undefined;\nconst MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || undefined;\nlet MCP_EXTRA_INSTRUCTIONS: string | undefined;\nconst MCP_INSTRUCTIONS_MAX_BYTES = 32 * 1024;\nif (MCP_INSTRUCTIONS_FILE) {\n try {\n const size = statSync(MCP_INSTRUCTIONS_FILE).size;\n if (size > MCP_INSTRUCTIONS_MAX_BYTES) {\n throw new Error(`file is ${size} bytes, exceeds ${MCP_INSTRUCTIONS_MAX_BYTES} byte cap`);\n }\n MCP_EXTRA_INSTRUCTIONS = readFileSync(MCP_INSTRUCTIONS_FILE, \"utf8\").trim() || undefined;\n } catch (err) {\n console.error(`Failed to read MCP_INSTRUCTIONS_FILE (${MCP_INSTRUCTIONS_FILE}): ${(err as Error).message}`);\n process.exit(1);\n }\n if (MCP_INSTRUCTIONS_ENV) {\n console.warn(\"MCP_INSTRUCTIONS_FILE is set; ignoring MCP_INSTRUCTIONS env var.\");\n }\n} else if (MCP_INSTRUCTIONS_ENV) {\n MCP_EXTRA_INSTRUCTIONS = MCP_INSTRUCTIONS_ENV;\n}\n\n// --- Initialize vault (local or remote) ---\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nlet vault: VaultBackend;\n\nif (VAULT_PATH) {\n const { LocalVault } = await import(\"./vault-local.js\");\n vault = new LocalVault(VAULT_PATH);\n console.log(`Local mode: ${VAULT_PATH}`);\n} else if (COUCHDB_URL) {\n if (!COUCHDB_PASSWORD) {\n console.error(\"COUCHDB_PASSWORD is required in remote mode.\");\n process.exit(1);\n }\n const { Vault } = await import(\"./vault.js\");\n vault = new Vault({\n couchdbUrl: COUCHDB_URL,\n couchdbUser: COUCHDB_USER,\n couchdbPassword: COUCHDB_PASSWORD,\n database: COUCHDB_DATABASE,\n passphrase: COUCHDB_PASSPHRASE,\n obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,\n });\n console.log(`Remote mode: ${COUCHDB_URL}`);\n} else {\n console.error(\"Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.\");\n process.exit(1);\n}\n\nawait vault.init();\nconsole.log(\"Vault ready.\");\n\n// --- Per-vault data directory ---\nconst baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? \"/tmp\", \".obsidian-mcp\");\nconst vaultId = createHash(\"sha256\").update(VAULT_NAME).digest(\"hex\").slice(0, 12);\nconst dataDir = join(baseDataDir, vaultId);\n\n// --- Search index ---\nconst indexPath = join(dataDir, \"search-index.json\");\nconst searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);\n\n// Load persisted metadata from disk\nawait searchIndex.loadFromDisk();\nif (debugLogging) {\n console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || \"(none)\"}`);\n}\n\n// Sync metadata in background (server starts immediately)\nasync function rebuildIndex() {\n const start = performance.now();\n\n if (COUCHDB_URL && vault.catchUp) {\n const changeCallback = (path: string, content: string | null, mtime?: number) => {\n if (content) {\n searchIndex.update(path, content, mtime);\n } else {\n searchIndex.remove(path);\n }\n };\n\n let since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n const onBatch = async (batchSince: string, processed: number) => {\n searchIndex.since = batchSince;\n await searchIndex.saveToDisk();\n console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);\n };\n try {\n const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content ? \"(update)\" : \"(delete)\"}`);\n changeCallback(path, content, mtime);\n };\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n } catch (err) {\n console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);\n searchIndex.clear();\n changes = 0;\n const newSince = await vault.catchUp(\"0\", (path, content, mtime) => {\n changes++;\n changeCallback(path, content, mtime);\n }, onBatch);\n searchIndex.since = newSince;\n }\n if (changes > 0) {\n console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1000).toFixed(1)}s (${searchIndex.size} notes).`);\n } else {\n console.log(`Search index up to date (${searchIndex.size} notes).`);\n }\n } else if (VAULT_PATH) {\n const notesWithMtime = await vault.listNotesWithMtime();\n if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);\n if (notesWithMtime.length > 0) {\n const vaultPaths = new Set(notesWithMtime.map((n) => n.path));\n for (const p of searchIndex.listPaths()) {\n if (!vaultPaths.has(p)) searchIndex.remove(p);\n }\n console.log(`Building search index (${notesWithMtime.length} notes)...`);\n for (let i = 0; i < notesWithMtime.length; i++) {\n const { path, mtime } = notesWithMtime[i];\n const content = await vault.readNote(path);\n if (content) searchIndex.update(path, content, mtime);\n if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {\n console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);\n }\n }\n console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1000).toFixed(1)}s`);\n }\n }\n await searchIndex.saveToDisk();\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => console.error(\"Index rebuild failed:\", err));\n\n// --- Watch for external changes ---\nlet fsWatcher: ReturnType<typeof watch> | null = null;\nif (VAULT_PATH) {\n // Local mode: watch filesystem for changes from Obsidian\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {\n if (!filename || !filename.endsWith(\".md\")) return;\n const notePath = filename.replace(/\\\\/g, \"/\");\n if (notePath.startsWith(\".obsidian/\") || notePath.includes(\"/.obsidian/\")) return;\n\n // Debounce: coalesce rapid events for the same file (Obsidian fires 2-3 per save)\n if (pending.has(notePath)) clearTimeout(pending.get(notePath)!);\n pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));\n });\n\n async function handleFileChange(notePath: string) {\n pending.delete(notePath);\n try {\n const content = await vault.readNote(notePath);\n if (content !== null) {\n const s = await stat(join(VAULT_PATH!, notePath));\n searchIndex.update(notePath, content, s.mtimeMs);\n } else {\n searchIndex.remove(notePath);\n }\n } catch {\n // File deleted or path blocked by safePath\n searchIndex.remove(notePath);\n }\n }\n console.log(\"Watching vault for external changes.\");\n} else if (COUCHDB_URL && vault.watchChanges) {\n // Remote mode: watch CouchDB _changes feed for LiveSync updates\n vault.watchChanges((path: string, content: string | null, mtime?: number, seq?: string | number) => {\n if (content) {\n if (debugLogging) console.log(`[debug] CouchDB change: ${path} (mtime: ${mtime})`);\n searchIndex.update(path, content, mtime);\n } else {\n if (debugLogging) console.log(`[debug] CouchDB delete: ${path}`);\n searchIndex.remove(path);\n }\n if (seq) searchIndex.since = String(seq);\n });\n console.log(\"Watching CouchDB for LiveSync changes.\");\n}\n\n// --- MCP Server ---\nconst BASE_INSTRUCTIONS = \"Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.\";\nconst serverOptions: ConstructorParameters<typeof FastMCP>[0] = {\n name: \"obsidian-sync-mcp\",\n version: process.env.npm_package_version ?? \"0.0.0\",\n instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}\\n\\n${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS,\n};\n\n// Auth\nimport type { AuthHandle } from \"./auth.js\";\nlet auth: AuthHandle | null = null;\n\nif (AUTH_TOKEN) {\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n const header = req.headers[\"authorization\"];\n // Accept static Bearer token (for curl, MCP Inspector, custom agents)\n const expected = `Bearer ${AUTH_TOKEN}`;\n if (header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {\n return { authenticated: true };\n }\n // Accept OAuth-issued tokens (for Claude Web/Desktop/Mobile)\n if (auth?.validateToken(header)) {\n return { authenticated: true };\n }\n throw new Response(\"Unauthorized\", { status: 401 });\n };\n console.log(\"Auth enabled (password-gated OAuth).\");\n} else {\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. Set MCP_AUTH_TOKEN or HOST=127.0.0.1.\");\n } else {\n console.log(\"Auth disabled (set MCP_AUTH_TOKEN to enable).\");\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);\n\n// --- Graceful shutdown ---\nasync function shutdown() {\n console.log(\"Shutting down...\");\n if (fsWatcher) fsWatcher.close();\n await searchIndex.saveToDisk();\n if (auth) await auth.saveTokens();\n await vault.close();\n process.exit(0);\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n\n// --- Periodic save (every 5 minutes) ---\nsetInterval(async () => {\n await searchIndex.saveToDisk();\n if (auth) {\n auth.cleanup();\n await auth.saveTokens();\n }\n}, 5 * 60 * 1000).unref();\n\n// --- Start server ---\nserver.start({\n transportType: \"httpStream\",\n httpStream: { port: PORT, endpoint: \"/mcp\", host: process.env.HOST ?? \"0.0.0.0\" },\n});\nconsole.log(`obsidian-sync-mcp v${process.env.npm_package_version ?? \"unknown\"} listening on port ${PORT}`);\n\n// Prevent unhandled rejections from crashing the server (e.g. decryption failures in watcher)\nprocess.on(\"unhandledRejection\", (err) => {\n console.error(\"Unhandled rejection:\", err);\n});\n","/**\n * Password-gated OAuth provider for MCP.\n *\n * Implements a self-contained OAuth 2.1 flow:\n * - Claude connects -> gets 401 with metadata pointer\n * - Claude discovers /.well-known/oauth-protected-resource\n * - Claude registers via /oauth/register (DCR)\n * - Claude redirects user to /oauth/authorize\n * - User sees a password page, enters MCP_AUTH_TOKEN\n * - Claude exchanges code for access token via /oauth/token\n * - All subsequent requests carry Bearer token\n *\n * No external identity provider needed.\n */\n\nimport { randomUUID, randomBytes, createHash, timingSafeEqual } from \"crypto\";\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type { Hono } from \"hono\";\n\ninterface PendingAuth {\n clientId: string;\n redirectUri: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n state: string;\n code: string;\n createdAt: number;\n}\n\ninterface TokenRecord {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n expiresAt: number;\n refreshExpiresAt: number;\n}\n\ninterface RegisteredClient {\n clientId: string;\n clientSecret: string;\n redirectUris: string[];\n clientName?: string;\n}\n\nconst TOKEN_EXPIRY_MS = 3600 * 1000; // 1 hour\nconst DEFAULT_REFRESH_DAYS = 14;\nconst REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1000;\nconst MAX_FAILED_BEFORE_LOCKOUT = 5;\nconst BASE_LOCKOUT_MS = 5 * 1000; // 5 seconds, doubles each lockout\nconst MAX_CLIENTS = 100;\nconst MAX_PENDING = 100;\nconst PENDING_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface AuthHandle {\n validateToken: (auth: string | undefined) => boolean;\n saveTokens: () => Promise<void>;\n loadTokens: () => Promise<boolean>;\n cleanup: () => void;\n}\n\nexport function mountPasswordAuth(app: Hono, baseUrl: string, password: string, persistPath?: string): AuthHandle {\n const pendingAuths = new Map<string, PendingAuth>();\n const csrfTokens = new Map<string, string>(); // code -> csrf token\n const tokens = new Map<string, TokenRecord>();\n const refreshTokens = new Map<string, TokenRecord>();\n const clients = new Map<string, RegisteredClient>();\n\n // Cleanup expired pending auths and CSRF tokens\n function cleanupPending() {\n const now = Date.now();\n for (const [code, pending] of pendingAuths) {\n if (now - pending.createdAt > PENDING_TTL_MS) {\n pendingAuths.delete(code);\n csrfTokens.delete(code);\n }\n }\n }\n\n // Rate limiting: exponential backoff, never resets until success\n let failedAttempts = 0;\n let lockoutCount = 0;\n let lockedUntil = 0;\n\n // 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 return c.json({ error: \"too_many_clients\" }, 429);\n }\n const body = await c.req.json();\n\n // Validate redirect_uris\n const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.slice(0, 5) : [];\n if (redirectUris.length === 0) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"redirect_uris required\" }, 400);\n }\n const safeUri = (u: any) => {\n if (typeof u !== \"string\" || u.length > 2048) return false;\n const lower = u.toLowerCase();\n return !lower.startsWith(\"javascript:\") && !lower.startsWith(\"data:\") && !lower.startsWith(\"file:\");\n };\n if (redirectUris.some((u: any) => !safeUri(u))) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"invalid redirect_uri\" }, 400);\n }\n\n const clientId = randomUUID();\n const clientSecret = randomBytes(32).toString(\"hex\");\n const clientName = typeof body.client_name === \"string\" ? body.client_name.slice(0, 256) : undefined;\n\n const client: RegisteredClient = {\n clientId,\n clientSecret,\n redirectUris,\n clientName,\n };\n clients.set(clientId, client);\n\n return c.json({\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uris: client.redirectUris,\n client_name: client.clientName,\n token_endpoint_auth_method: \"client_secret_post\",\n }, 201);\n });\n\n // --- Authorization endpoint ---\n\n app.get(\"/oauth/authorize\", (c) => {\n const clientId = c.req.query(\"client_id\") ?? \"\";\n const redirectUri = c.req.query(\"redirect_uri\") ?? \"\";\n const codeChallenge = c.req.query(\"code_challenge\") ?? \"\";\n const codeChallengeMethod = c.req.query(\"code_challenge_method\") ?? \"S256\";\n const state = c.req.query(\"state\") ?? \"\";\n\n // Validate redirect URI against registered client\n const client = clients.get(clientId);\n if (!client) {\n return c.text(\"Unknown client\", 400);\n }\n if (!client.redirectUris.includes(redirectUri)) {\n return c.text(\"Invalid redirect URI\", 400);\n }\n\n // Require S256 PKCE\n if (codeChallengeMethod !== \"S256\" || !codeChallenge) {\n return c.text(\"PKCE with S256 is required\", 400);\n }\n\n cleanupPending();\n if (pendingAuths.size >= MAX_PENDING) {\n return c.text(\"Too many pending authorizations\", 429);\n }\n\n const code = randomBytes(32).toString(\"hex\");\n pendingAuths.set(code, {\n clientId,\n redirectUri,\n codeChallenge,\n codeChallengeMethod,\n state,\n code,\n createdAt: Date.now(),\n });\n\n const csrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, csrf);\n return c.html(renderPasswordPage(code, csrf));\n });\n\n // --- Approval handler ---\n\n app.post(\"/oauth/approve\", async (c) => {\n const body = await c.req.parseBody();\n const code = body[\"code\"] as string;\n const submittedCsrf = body[\"csrf\"] as string;\n const submittedPassword = body[\"password\"] as string;\n\n const pending = pendingAuths.get(code);\n const expectedCsrf = csrfTokens.get(code);\n if (!pending || !expectedCsrf) {\n return c.html(\"<p>Invalid or expired authorization request.</p>\", 400);\n }\n\n // Validate CSRF token\n const csrfA = Buffer.from(submittedCsrf ?? \"\");\n const csrfB = Buffer.from(expectedCsrf);\n if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {\n return c.html(\"<p>Invalid request.</p>\", 403);\n }\n\n // Rate limiting: check lockout\n if (Date.now() < lockedUntil) {\n const waitSec = Math.ceil((lockedUntil - Date.now()) / 1000);\n console.warn(`Auth: locked out, ${waitSec}s remaining`);\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n const a = Buffer.from(submittedPassword);\n const b = Buffer.from(password);\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n failedAttempts++;\n console.warn(`Auth: failed attempt ${failedAttempts} total`);\n\n // Rotate CSRF token on each failed attempt\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n\n if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {\n lockoutCount = Math.min(lockoutCount + 1, 10);\n const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);\n lockedUntil = Date.now() + lockoutMs;\n console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1000}s`);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n console.log(\"Auth: password accepted, issuing authorization code.\");\n\n const url = new URL(pending.redirectUri);\n url.searchParams.set(\"code\", code);\n if (pending.state) url.searchParams.set(\"state\", pending.state);\n const redirectUrl = url.toString();\n\n return c.redirect(redirectUrl);\n });\n\n // --- Token endpoint ---\n\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.parseBody();\n const grantType = body[\"grant_type\"] as string;\n\n if (grantType === \"authorization_code\") {\n const code = body[\"code\"] as string;\n const clientId = body[\"client_id\"] as string;\n const codeVerifier = body[\"code_verifier\"] as string;\n const redirectUri = body[\"redirect_uri\"] as string;\n\n const pending = pendingAuths.get(code);\n if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {\n if (pending) pendingAuths.delete(code);\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Verify client_id matches the original request\n if (clientId !== pending.clientId) {\n return c.json({ error: \"invalid_grant\", error_description: \"client_id mismatch\" }, 400);\n }\n\n // Verify redirect_uri matches the original request\n if (redirectUri !== pending.redirectUri) {\n return c.json({ error: \"invalid_grant\", error_description: \"redirect_uri mismatch\" }, 400);\n }\n\n // Verify PKCE\n if (pending.codeChallengeMethod === \"S256\") {\n const expected = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed\" }, 400);\n }\n }\n\n pendingAuths.delete(code);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const refreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken,\n clientId: pending.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS,\n };\n tokens.set(accessToken, record);\n refreshTokens.set(refreshToken, record);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: refreshToken,\n });\n }\n\n if (grantType === \"refresh_token\") {\n const refreshToken = body[\"refresh_token\"] as string;\n const old = refreshTokens.get(refreshToken);\n if (!old) {\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Check refresh token expiry\n if (Date.now() > old.refreshExpiresAt) {\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n console.log(\"Auth: refresh token expired, user must re-authenticate.\");\n return c.json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" }, 400);\n }\n\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const newRefreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken: newRefreshToken,\n clientId: old.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: old.refreshExpiresAt, // keep original expiry\n };\n tokens.set(accessToken, record);\n refreshTokens.set(newRefreshToken, record);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: newRefreshToken,\n });\n }\n\n return c.json({ error: \"unsupported_grant_type\" }, 400);\n });\n\n return {\n validateToken(authHeader: string | undefined): boolean {\n if (!authHeader?.startsWith(\"Bearer \")) return false;\n const token = authHeader.slice(7);\n const record = tokens.get(token);\n if (!record) return false;\n if (Date.now() > record.expiresAt) {\n tokens.delete(token);\n return false;\n }\n return true;\n },\n\n async saveTokens(): Promise<void> {\n 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 console.log(`Auth tokens saved to disk (${tokens.size} sessions).`);\n } catch (err) {\n console.error(\"Failed to save auth tokens:\", err);\n }\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 // Evict clients with no active tokens or refresh 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 for (const [k, c] of clients) {\n if (!activeClientIds.has(c.clientId)) clients.delete(k);\n }\n },\n\n async loadTokens(): Promise<boolean> {\n if (!persistPath) return false;\n try {\n const raw = await readFile(persistPath, \"utf-8\");\n const data = JSON.parse(raw);\n const now = Date.now();\n for (const [k, v] of Object.entries(data.tokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.clients ?? {})) {\n const client = v as RegisteredClient;\n if (client.clientId && client.redirectUris) clients.set(k, client);\n }\n console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);\n return tokens.size > 0;\n } catch {\n return false;\n }\n },\n };\n}\n\nfunction renderPasswordPage(code: string, csrf: string, error?: string): string {\n return `<!DOCTYPE html>\n<html><head><title>Obsidian Sync MCP - Authorize</title>\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'\">\n<style>\n body { font-family: system-ui; max-width: 400px; margin: 80px auto; padding: 0 20px; }\n h1 { font-size: 1.3em; }\n input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }\n button { padding: 10px 20px; font-size: 1em; cursor: pointer; }\n .error { color: red; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n ${error ? `<p class=\"error\">${error.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\")}</p>` : \"<p>Enter the server password to authorize access to your vault.</p>\"}\n <form method=\"POST\" action=\"/oauth/approve\" autocomplete=\"on\">\n <input type=\"hidden\" name=\"code\" value=\"${code.replace(/&/g, \"&\").replace(/\"/g, \""\")}\">\n <input type=\"hidden\" name=\"csrf\" value=\"${csrf.replace(/&/g, \"&\").replace(/\"/g, \""\")}\">\n <input type=\"text\" name=\"username\" id=\"username\" value=\"obsidian-sync-mcp\" autocomplete=\"username\" style=\"position:absolute;opacity:0;width:1px;height:1px;pointer-events:none\">\n <input type=\"password\" name=\"password\" id=\"password\" placeholder=\"Password\" autocomplete=\"current-password\" autofocus required>\n <br><button type=\"submit\">Authorize</button>\n </form>\n</body></html>`;\n}\n","/**\n * Metadata index for vault notes.\n *\n * Tracks paths, mtimes, tags, links, and backlinks.\n * Persists to disk (encrypted if passphrase is set).\n * No full-text search — metadata only.\n */\n\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from \"crypto\";\nimport { parseFrontmatterAndLinks } from \"./parse.js\";\n\n\nfunction encrypt(text: string, passphrase: string): string {\n const salt = randomBytes(16);\n const key = scryptSync(passphrase, salt, 32);\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const encrypted = Buffer.concat([cipher.update(text, \"utf-8\"), cipher.final()]);\n const tag = (cipher as any).getAuthTag() as Buffer;\n return salt.toString(\"hex\") + \":\" + iv.toString(\"hex\") + \":\" + tag.toString(\"hex\") + \":\" + encrypted.toString(\"hex\");\n}\n\nfunction decrypt(data: string, passphrase: string): string {\n const [saltHex, ivHex, tagHex, encryptedHex] = data.split(\":\");\n const key = scryptSync(passphrase, Buffer.from(saltHex, \"hex\"), 32);\n const decipher = createDecipheriv(\"aes-256-gcm\", key, Buffer.from(ivHex, \"hex\"));\n (decipher as any).setAuthTag(Buffer.from(tagHex, \"hex\"));\n return Buffer.concat([decipher.update(Buffer.from(encryptedHex, \"hex\")), decipher.final()]).toString(\"utf-8\");\n}\n\nexport class SearchIndex {\n private mtimes = new Map<string, number>();\n private tags = new Map<string, string[]>();\n private links = new Map<string, string[]>();\n private backlinks = new Map<string, Set<string>>();\n private knownPaths = new Set<string>();\n private saving = false;\n private _since: string = \"\";\n private persistPath: string | null;\n private passphrase: string | null;\n\n constructor(persistPath?: string, passphrase?: string) {\n this.persistPath = persistPath ?? null;\n this.passphrase = passphrase ?? null;\n }\n\n /** Load metadata from disk. */\n async loadFromDisk(): Promise<boolean> {\n if (!this.persistPath) return false;\n try {\n let raw = await readFile(this.persistPath, \"utf-8\");\n if (this.passphrase) {\n raw = decrypt(raw, this.passphrase);\n }\n const data = JSON.parse(raw);\n for (const [path, mtime] of Object.entries(data.mtimes ?? {})) {\n this.mtimes.set(path, mtime as number);\n this.knownPaths.add(path);\n }\n for (const [path, t] of Object.entries(data.tags ?? {})) {\n this.tags.set(path, t as string[]);\n }\n for (const [path, l] of Object.entries(data.links ?? {})) {\n const targets = l as string[];\n this.links.set(path, targets);\n for (const target of targets) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n }\n if (data.since) this._since = data.since;\n console.log(`Search metadata loaded from disk (${this.knownPaths.size} notes, since: ${this._since ? \"yes\" : \"none\"}).`);\n return this.knownPaths.size > 0;\n } catch {\n return false;\n }\n }\n\n /** Save metadata to disk. Encrypted if passphrase is set. */\n async saveToDisk(): Promise<void> {\n if (!this.persistPath || this.saving) return;\n this.saving = true;\n try {\n await mkdir(dirname(this.persistPath), { recursive: true });\n let data = JSON.stringify({\n mtimes: Object.fromEntries(this.mtimes),\n tags: Object.fromEntries(this.tags),\n links: Object.fromEntries(this.links),\n since: this._since,\n });\n if (this.passphrase) {\n data = encrypt(data, this.passphrase);\n }\n await writeFile(this.persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(this.persistPath, 0o600);\n console.log(`Search index saved to disk (${this.knownPaths.size} notes${this.passphrase ? \", encrypted\" : \"\"}).`);\n } catch (err) {\n console.error(\"Failed to save search index:\", err);\n } finally {\n this.saving = false;\n }\n }\n\n /** Add or update a note in the index. */\n update(path: string, content: string, mtime?: number): void {\n if (this.knownPaths.has(path)) {\n this.clearBacklinks(path);\n }\n this.knownPaths.add(path);\n if (mtime !== undefined) this.mtimes.set(path, mtime);\n const parsed = parseFrontmatterAndLinks(content);\n if (parsed.tags.length > 0) {\n this.tags.set(path, parsed.tags);\n } else {\n this.tags.delete(path);\n }\n if (parsed.links.length > 0) {\n this.links.set(path, parsed.links);\n for (const target of parsed.links) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n } else {\n this.links.delete(path);\n }\n }\n\n /** Remove a note from the index. */\n remove(path: string): void {\n if (this.knownPaths.has(path)) {\n this.knownPaths.delete(path);\n this.mtimes.delete(path);\n this.tags.delete(path);\n this.clearBacklinks(path);\n }\n }\n\n /** Remove all backlink entries where path is the source. */\n private clearBacklinks(path: string): void {\n const oldLinks = this.links.get(path);\n if (oldLinks) {\n for (const target of oldLinks) {\n const key = target.toLowerCase();\n this.backlinks.get(key)?.delete(path);\n if (this.backlinks.get(key)?.size === 0) this.backlinks.delete(key);\n }\n }\n this.links.delete(path);\n }\n\n /** List all indexed paths, optionally filtered by folder prefix. */\n listPaths(folder?: string): string[] {\n return this.listWithMtime(folder).map((n) => n.path);\n }\n\n /** List all indexed paths with mtimes, optionally filtered by folder prefix. */\n listWithMtime(folder?: string): Array<{ path: string; mtime: number }> {\n const prefix = folder && !folder.endsWith(\"/\") ? folder + \"/\" : folder;\n const entries = [...this.knownPaths]\n .filter((p) => p.endsWith(\".md\"))\n .filter((p) => !prefix || p.startsWith(prefix))\n .map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));\n return entries.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n /** Get mtime for a path. */\n getMtime(path: string): number {\n return this.mtimes.get(path) ?? 0;\n }\n\n /** Get tags for a path. */\n getTags(path: string): string[] {\n return this.tags.get(path) ?? [];\n }\n\n /** Get outgoing links for a path. */\n getLinks(path: string): string[] {\n return this.links.get(path) ?? [];\n }\n\n /** Get backlinks for a path (notes that link to it). Case-insensitive, matches by full path or filename. */\n getBacklinks(path: string): string[] {\n const results = new Set<string>();\n const withMd = (path.endsWith(\".md\") ? path : path + \".md\").toLowerCase();\n const withoutMd = (path.endsWith(\".md\") ? path.slice(0, -3) : path).toLowerCase();\n const nameOnly = withoutMd.includes(\"/\") ? withoutMd.slice(withoutMd.lastIndexOf(\"/\") + 1) : withoutMd;\n\n for (const target of [withMd, withoutMd, nameOnly]) {\n const sources = this.backlinks.get(target);\n if (sources) {\n for (const s of sources) results.add(s);\n }\n }\n return [...results].sort();\n }\n\n /** List all tags across the vault with counts. */\n listAllTags(): Array<{ tag: string; count: number }> {\n const counts = new Map<string, number>();\n for (const tags of this.tags.values()) {\n for (const t of tags) {\n counts.set(t, (counts.get(t) ?? 0) + 1);\n }\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((a, b) => b.count - a.count);\n }\n\n /** Clear all index data (for full rebuild after DB nuke). */\n clear(): void {\n const paths = Array.from(this.knownPaths);\n for (const p of paths) this.remove(p);\n this._since = \"\";\n }\n\n get since(): string {\n return this._since;\n }\n\n set since(value: string) {\n this._since = value;\n }\n\n get size(): number {\n return this.knownPaths.size;\n }\n}\n","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\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\nexport function registerTools(\n server: FastMCP,\n vault: VaultBackend,\n searchIndex: SearchIndex,\n vaultName: string,\n readOnly = false,\n) {\n if (readOnly) {\n console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(\", \")}).`);\n }\n const _addTool = server.addTool.bind(server);\n server.addTool = (tool: any) => {\n const original = tool.execute;\n tool.execute = async (args: any, ctx: any) => {\n if (debugLogging) console.log(`[tool] ${tool.name}(${JSON.stringify(args)})`);\n const start = performance.now();\n const result = await original(args, ctx);\n if (debugLogging) console.log(`[tool] ${tool.name} → ${((performance.now() - start)).toFixed(0)}ms`);\n return result;\n };\n return _addTool(tool);\n };\n server.addTool({\n name: \"read_note\",\n description:\n \"Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n }),\n execute: async ({ path }) => {\n const content = await vault.readNote(path);\n if (content === null) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n return `[Open in Obsidian](${deepLink})\\n\\n---\\n\\n${content}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"write_note\",\n description:\n \"Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does — read first if you need to preserve existing content.\",\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 const ok = await vault.writeNote(path, content);\n if (!ok) {\n return `Failed to write note: ${path}`;\n }\n searchIndex.update(path, content, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note saved: ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"list_notes\",\n description: \"List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(name='meeting') to find notes by name. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.\",\n parameters: z.object({\n folder: z\n .string()\n .optional()\n .describe(\"Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes.\"),\n name: z\n .string()\n .optional()\n .describe(\"Filter by name (case-insensitive substring match on path), e.g. 'meeting' or 'project-x'.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags.\"),\n sort_by: z\n .enum([\"name\", \"modified\"])\n .optional()\n .describe(\"Sort order: 'name' (default) or 'modified' (most recent first).\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'.\"),\n limit: z.coerce\n .number()\n .optional()\n .describe(\"Max number of notes to return. Default 100.\"),\n }),\n execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {\n // Use search index (works with encrypted vaults), fall back to vault\n let notes = searchIndex.listWithMtime(folder);\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n }\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n }\n if (modified_after) {\n const cutoff = new Date(modified_after).getTime();\n if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n notes = notes.filter((n) => n.mtime >= cutoff);\n }\n if (notes.length === 0) {\n return folder ? `No notes found in folder: ${folder}` : \"Vault is empty.\";\n }\n if (sort_by === \"modified\") {\n notes.sort((a, b) => b.mtime - a.mtime);\n }\n const cap = limit ?? 100;\n const total = notes.length;\n const capped = notes.slice(0, cap);\n const lines = capped.map((n) => {\n const deepLink = makeDeepLink(vaultName, n.path);\n const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : \"\";\n return `- ${date} [${n.path}](${deepLink})`;\n });\n if (total > cap) {\n lines.push(`\\n... and ${total - cap} more. Use a folder filter or limit to narrow results.`);\n }\n return lines.join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_folders\",\n description:\n \"List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.\",\n parameters: z.object({}),\n execute: async () => {\n let paths = searchIndex.listPaths();\n if (paths.length === 0) {\n paths = await vault.listNotes();\n }\n const folders = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n folders.set(\"(root)\", (folders.get(\"(root)\") ?? 0) + 1);\n } else {\n const folder = p.slice(0, lastSlash);\n folders.set(folder, (folders.get(folder) ?? 0) + 1);\n // Ensure all parent folders appear in the list\n let parent = folder;\n while (parent.includes(\"/\")) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n if (!folders.has(parent)) folders.set(parent, 0);\n }\n }\n }\n if (folders.size === 0) {\n return \"Vault is empty.\";\n }\n const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));\n return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_tags\",\n description:\n \"List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes.\",\n parameters: z.object({}),\n execute: async () => {\n const tags = searchIndex.listAllTags();\n if (tags.length === 0) {\n return \"No tags found in the vault.\";\n }\n return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join(\"\\n\");\n },\n });\n\n\n\n if (!readOnly) server.addTool({\n name: \"edit_note\",\n description:\n \"Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.\",\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 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.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note to delete\"),\n }),\n execute: async ({ 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.\",\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 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 if (content) 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"],"mappings":";;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,mBAAAA,kBAAiB,cAAAC,mBAAkB;AAC5C,SAAS,OAAO,cAAc,gBAAgB;AAC9C,SAAS,YAAY;AACrB,SAAS,sBAAsB,kBAAkB;;;ACUjD,SAAS,YAAY,aAAa,YAAY,uBAAuB;AACrE,SAAS,UAAU,WAAW,OAAO,aAAa;AAClD,SAAS,eAAe;AA4BxB,IAAM,kBAAkB,OAAO;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB,SAAS,QAAQ,IAAI,oBAAoB,OAAO,oBAAoB,CAAC,KAAK,wBAAwB,KAAK,OAAO;AACzI,IAAM,4BAA4B;AAClC,IAAM,kBAAkB,IAAI;AAC5B,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,iBAAiB,KAAK,KAAK;AAS1B,SAAS,kBAAkB,KAAW,SAAiB,UAAkB,aAAkC;AAC9G,QAAM,eAAe,oBAAI,IAAyB;AAClD,QAAM,aAAa,oBAAI,IAAoB;AAC3C,QAAM,SAAS,oBAAI,IAAyB;AAC5C,QAAM,gBAAgB,oBAAI,IAAyB;AACnD,QAAM,UAAU,oBAAI,IAA8B;AAGlD,WAAS,iBAAiB;AACtB,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW,CAAC,MAAM,OAAO,KAAK,cAAc;AACxC,UAAI,MAAM,QAAQ,YAAY,gBAAgB;AAC1C,qBAAa,OAAO,IAAI;AACxB,mBAAW,OAAO,IAAI;AAAA,MAC1B;AAAA,IACJ;AAAA,EACJ;AAGA,MAAI,iBAAiB;AACrB,M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AAQ,MAAM,wBAAwB,GAAG;AAC7C,CAAC;","names":["timingSafeEqual","createHash","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","server","vault","searchIndex","debugLogging","createHash","timingSafeEqual"]}
|
|
1
|
+
{"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/tools.ts","../src/deeplink.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { timingSafeEqual, createHash } from \"crypto\";\nimport { watch, readFileSync, statSync } from \"fs\";\nimport { stat } from \"fs/promises\";\nimport { setGlobalLogFunction, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { mountPasswordAuth } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange } from \"./index-sync.js\";\nimport { registerTools } from \"./tools.js\";\n\n// Suppress livesync-commonlib logs that expose vault file paths in production.\n// Set LOG_LEVEL=debug to see all library logs during development.\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\nsetGlobalLogFunction((message, level = LEVEL_INFO) => {\n if (level < LEVEL_INFO) return;\n if (!debugLogging && typeof message === \"string\") {\n if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;\n if (message.includes(\"replicator\") || message.includes(\"Replicator\") || message.includes(\"ReplicatorService\")) return;\n }\n console.log(message);\n});\n\n// --- Configuration from environment ---\nconst VAULT_PATH = process.env.VAULT_PATH; // Local mode: path to vault directory\nconst COUCHDB_URL = process.env.COUCHDB_URL;\nconst COUCHDB_USER = process.env.COUCHDB_USER ?? \"admin\";\nconst COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;\nconst COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? \"obsidian\";\nconst COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || undefined;\nconst COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === \"true\";\nconst VAULT_NAME = process.env.VAULT_NAME ?? \"MyVault\";\nconst PORT = parseInt(process.env.PORT ?? \"8787\");\nconst BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;\nconst AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;\nconst READ_ONLY = process.env.READ_ONLY === \"true\";\n\n// Extra instructions appended to the MCP `instructions` string.\n// File wins if both are set (loud warning); missing file is fatal.\nconst MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || undefined;\nconst MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || undefined;\nlet MCP_EXTRA_INSTRUCTIONS: string | undefined;\nconst MCP_INSTRUCTIONS_MAX_BYTES = 32 * 1024;\nif (MCP_INSTRUCTIONS_FILE) {\n try {\n const size = statSync(MCP_INSTRUCTIONS_FILE).size;\n if (size > MCP_INSTRUCTIONS_MAX_BYTES) {\n throw new Error(`file is ${size} bytes, exceeds ${MCP_INSTRUCTIONS_MAX_BYTES} byte cap`);\n }\n MCP_EXTRA_INSTRUCTIONS = readFileSync(MCP_INSTRUCTIONS_FILE, \"utf8\").trim() || undefined;\n } catch (err) {\n console.error(`Failed to read MCP_INSTRUCTIONS_FILE (${MCP_INSTRUCTIONS_FILE}): ${(err as Error).message}`);\n process.exit(1);\n }\n if (MCP_INSTRUCTIONS_ENV) {\n console.warn(\"MCP_INSTRUCTIONS_FILE is set; ignoring MCP_INSTRUCTIONS env var.\");\n }\n} else if (MCP_INSTRUCTIONS_ENV) {\n MCP_EXTRA_INSTRUCTIONS = MCP_INSTRUCTIONS_ENV;\n}\n\n// --- Initialize vault (local or remote) ---\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nlet vault: VaultBackend;\n\nif (VAULT_PATH) {\n const { LocalVault } = await import(\"./vault-local.js\");\n vault = new LocalVault(VAULT_PATH);\n console.log(`Local mode: ${VAULT_PATH}`);\n} else if (COUCHDB_URL) {\n if (!COUCHDB_PASSWORD) {\n console.error(\"COUCHDB_PASSWORD is required in remote mode.\");\n process.exit(1);\n }\n const { Vault } = await import(\"./vault.js\");\n vault = new Vault({\n couchdbUrl: COUCHDB_URL,\n couchdbUser: COUCHDB_USER,\n couchdbPassword: COUCHDB_PASSWORD,\n database: COUCHDB_DATABASE,\n passphrase: COUCHDB_PASSPHRASE,\n obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,\n });\n console.log(`Remote mode: ${COUCHDB_URL}`);\n} else {\n console.error(\"Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.\");\n process.exit(1);\n}\n\nawait vault.init();\nconsole.log(\"Vault ready.\");\n\n// --- Per-vault data directory ---\nconst baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? \"/tmp\", \".obsidian-mcp\");\nconst vaultId = createHash(\"sha256\").update(VAULT_NAME).digest(\"hex\").slice(0, 12);\nconst dataDir = join(baseDataDir, vaultId);\n\n// --- Search index ---\nconst indexPath = join(dataDir, \"search-index.json\");\nconst searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);\n\n// Load persisted metadata from disk\nawait searchIndex.loadFromDisk();\nif (debugLogging) {\n console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || \"(none)\"}`);\n}\n\n// Sync metadata in background (server starts immediately)\nasync function rebuildIndex() {\n const start = performance.now();\n\n if (COUCHDB_URL && vault.catchUp) {\n const changeCallback = (path: string, content: string | null, mtime?: number) => {\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n\n let since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n const onBatch = async (batchSince: string, processed: number) => {\n searchIndex.since = batchSince;\n await searchIndex.saveToDisk();\n console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);\n };\n try {\n const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n changeCallback(path, content, mtime);\n };\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n } catch (err) {\n console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);\n searchIndex.clear();\n changes = 0;\n const newSince = await vault.catchUp(\"0\", (path, content, mtime) => {\n changes++;\n changeCallback(path, content, mtime);\n }, onBatch);\n searchIndex.since = newSince;\n }\n if (changes > 0) {\n console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1000).toFixed(1)}s (${searchIndex.size} notes).`);\n } else {\n console.log(`Search index up to date (${searchIndex.size} notes).`);\n }\n } else if (VAULT_PATH) {\n const notesWithMtime = await vault.listNotesWithMtime();\n if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);\n if (notesWithMtime.length > 0) {\n const vaultPaths = new Set(notesWithMtime.map((n) => n.path));\n for (const p of searchIndex.listPaths()) {\n if (!vaultPaths.has(p)) searchIndex.remove(p);\n }\n console.log(`Building search index (${notesWithMtime.length} notes)...`);\n for (let i = 0; i < notesWithMtime.length; i++) {\n const { path, mtime } = notesWithMtime[i];\n const content = await vault.readNote(path);\n // Index empty notes too (content === \"\"); readNote returns null only if absent.\n if (content !== null) searchIndex.update(path, content, mtime);\n if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {\n console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);\n }\n }\n console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1000).toFixed(1)}s`);\n }\n }\n await searchIndex.saveToDisk();\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => console.error(\"Index rebuild failed:\", err));\n\n// --- Watch for external changes ---\nlet fsWatcher: ReturnType<typeof watch> | null = null;\nif (VAULT_PATH) {\n // Local mode: watch filesystem for changes from Obsidian\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {\n if (!filename || !filename.endsWith(\".md\")) return;\n const notePath = filename.replace(/\\\\/g, \"/\");\n if (notePath.startsWith(\".obsidian/\") || notePath.includes(\"/.obsidian/\")) return;\n\n // Debounce: coalesce rapid events for the same file (Obsidian fires 2-3 per save)\n if (pending.has(notePath)) clearTimeout(pending.get(notePath)!);\n pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));\n });\n\n async function handleFileChange(notePath: string) {\n pending.delete(notePath);\n try {\n const content = await vault.readNote(notePath);\n if (content !== null) {\n const s = await stat(join(VAULT_PATH!, notePath));\n searchIndex.update(notePath, content, s.mtimeMs);\n } else {\n searchIndex.remove(notePath);\n }\n } catch {\n // File deleted or path blocked by safePath\n searchIndex.remove(notePath);\n }\n }\n console.log(\"Watching vault for external changes.\");\n} else if (COUCHDB_URL && vault.watchChanges) {\n // Remote mode: watch CouchDB _changes feed for LiveSync updates\n vault.watchChanges((path: string, content: string | null, mtime?: number, seq?: string | number) => {\n if (debugLogging) console.log(`[debug] CouchDB ${content === null ? \"delete\" : \"change\"}: ${path}`);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n if (seq) searchIndex.since = String(seq);\n });\n console.log(\"Watching CouchDB for LiveSync changes.\");\n}\n\n// --- MCP Server ---\nconst BASE_INSTRUCTIONS = \"Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.\";\nconst serverOptions: ConstructorParameters<typeof FastMCP>[0] = {\n name: \"obsidian-sync-mcp\",\n version: process.env.npm_package_version ?? \"0.0.0\",\n instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}\\n\\n${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS,\n};\n\n// Auth\nimport type { AuthHandle } from \"./auth.js\";\nlet auth: AuthHandle | null = null;\n\nif (AUTH_TOKEN) {\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n const header = req.headers[\"authorization\"];\n // Accept static Bearer token (for curl, MCP Inspector, custom agents)\n const expected = `Bearer ${AUTH_TOKEN}`;\n if (header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {\n return { authenticated: true };\n }\n // Accept OAuth-issued tokens (for Claude Web/Desktop/Mobile)\n if (auth?.validateToken(header)) {\n return { authenticated: true };\n }\n throw new Response(\"Unauthorized\", { status: 401 });\n };\n console.log(\"Auth enabled (password-gated OAuth).\");\n} else {\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. Set MCP_AUTH_TOKEN or HOST=127.0.0.1.\");\n } else {\n console.log(\"Auth disabled (set MCP_AUTH_TOKEN to enable).\");\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);\n\n// --- Graceful shutdown ---\nasync function shutdown() {\n console.log(\"Shutting down...\");\n if (fsWatcher) fsWatcher.close();\n await searchIndex.saveToDisk();\n if (auth) await auth.saveTokens();\n await vault.close();\n process.exit(0);\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n\n// --- Periodic save (every 5 minutes) ---\nsetInterval(async () => {\n await searchIndex.saveToDisk();\n if (auth) {\n auth.cleanup();\n await auth.saveTokens();\n }\n}, 5 * 60 * 1000).unref();\n\n// --- Start server ---\nserver.start({\n transportType: \"httpStream\",\n httpStream: { port: PORT, endpoint: \"/mcp\", host: process.env.HOST ?? \"0.0.0.0\" },\n});\nconsole.log(`obsidian-sync-mcp v${process.env.npm_package_version ?? \"unknown\"} listening on port ${PORT}`);\n\n// Prevent unhandled rejections from crashing the server (e.g. decryption failures in watcher)\nprocess.on(\"unhandledRejection\", (err) => {\n console.error(\"Unhandled rejection:\", err);\n});\n","/**\n * Password-gated OAuth provider for MCP.\n *\n * Implements a self-contained OAuth 2.1 flow:\n * - Claude connects -> gets 401 with metadata pointer\n * - Claude discovers /.well-known/oauth-protected-resource\n * - Claude registers via /oauth/register (DCR)\n * - Claude redirects user to /oauth/authorize\n * - User sees a password page, enters MCP_AUTH_TOKEN\n * - Claude exchanges code for access token via /oauth/token\n * - All subsequent requests carry Bearer token\n *\n * No external identity provider needed.\n */\n\nimport { randomUUID, randomBytes, createHash, timingSafeEqual } from \"crypto\";\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type { Hono } from \"hono\";\n\ninterface PendingAuth {\n clientId: string;\n redirectUri: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n state: string;\n code: string;\n createdAt: number;\n}\n\ninterface TokenRecord {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n expiresAt: number;\n refreshExpiresAt: number;\n}\n\ninterface RegisteredClient {\n clientId: string;\n clientSecret: string;\n redirectUris: string[];\n clientName?: string;\n}\n\nconst TOKEN_EXPIRY_MS = 3600 * 1000; // 1 hour\nconst DEFAULT_REFRESH_DAYS = 14;\nconst REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1000;\nconst MAX_FAILED_BEFORE_LOCKOUT = 5;\nconst BASE_LOCKOUT_MS = 5 * 1000; // 5 seconds, doubles each lockout\nconst MAX_CLIENTS = 100;\nconst MAX_PENDING = 100;\nconst PENDING_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface AuthHandle {\n validateToken: (auth: string | undefined) => boolean;\n saveTokens: () => Promise<void>;\n loadTokens: () => Promise<boolean>;\n cleanup: () => void;\n}\n\nexport function mountPasswordAuth(app: Hono, baseUrl: string, password: string, persistPath?: string): AuthHandle {\n const pendingAuths = new Map<string, PendingAuth>();\n const csrfTokens = new Map<string, string>(); // code -> csrf token\n const tokens = new Map<string, TokenRecord>();\n const refreshTokens = new Map<string, TokenRecord>();\n const clients = new Map<string, RegisteredClient>();\n\n // Cleanup expired pending auths and CSRF tokens\n function cleanupPending() {\n const now = Date.now();\n for (const [code, pending] of pendingAuths) {\n if (now - pending.createdAt > PENDING_TTL_MS) {\n pendingAuths.delete(code);\n csrfTokens.delete(code);\n }\n }\n }\n\n // Rate limiting: exponential backoff, never resets until success\n let failedAttempts = 0;\n let lockoutCount = 0;\n let lockedUntil = 0;\n\n // 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 return c.json({ error: \"too_many_clients\" }, 429);\n }\n const body = await c.req.json();\n\n // Validate redirect_uris\n const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.slice(0, 5) : [];\n if (redirectUris.length === 0) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"redirect_uris required\" }, 400);\n }\n const safeUri = (u: any) => {\n if (typeof u !== \"string\" || u.length > 2048) return false;\n const lower = u.toLowerCase();\n return !lower.startsWith(\"javascript:\") && !lower.startsWith(\"data:\") && !lower.startsWith(\"file:\");\n };\n if (redirectUris.some((u: any) => !safeUri(u))) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"invalid redirect_uri\" }, 400);\n }\n\n const clientId = randomUUID();\n const clientSecret = randomBytes(32).toString(\"hex\");\n const clientName = typeof body.client_name === \"string\" ? body.client_name.slice(0, 256) : undefined;\n\n const client: RegisteredClient = {\n clientId,\n clientSecret,\n redirectUris,\n clientName,\n };\n clients.set(clientId, client);\n\n return c.json({\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uris: client.redirectUris,\n client_name: client.clientName,\n token_endpoint_auth_method: \"client_secret_post\",\n }, 201);\n });\n\n // --- Authorization endpoint ---\n\n app.get(\"/oauth/authorize\", (c) => {\n const clientId = c.req.query(\"client_id\") ?? \"\";\n const redirectUri = c.req.query(\"redirect_uri\") ?? \"\";\n const codeChallenge = c.req.query(\"code_challenge\") ?? \"\";\n const codeChallengeMethod = c.req.query(\"code_challenge_method\") ?? \"S256\";\n const state = c.req.query(\"state\") ?? \"\";\n\n // Validate redirect URI against registered client\n const client = clients.get(clientId);\n if (!client) {\n return c.text(\"Unknown client\", 400);\n }\n if (!client.redirectUris.includes(redirectUri)) {\n return c.text(\"Invalid redirect URI\", 400);\n }\n\n // Require S256 PKCE\n if (codeChallengeMethod !== \"S256\" || !codeChallenge) {\n return c.text(\"PKCE with S256 is required\", 400);\n }\n\n cleanupPending();\n if (pendingAuths.size >= MAX_PENDING) {\n return c.text(\"Too many pending authorizations\", 429);\n }\n\n const code = randomBytes(32).toString(\"hex\");\n pendingAuths.set(code, {\n clientId,\n redirectUri,\n codeChallenge,\n codeChallengeMethod,\n state,\n code,\n createdAt: Date.now(),\n });\n\n const csrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, csrf);\n return c.html(renderPasswordPage(code, csrf));\n });\n\n // --- Approval handler ---\n\n app.post(\"/oauth/approve\", async (c) => {\n const body = await c.req.parseBody();\n const code = body[\"code\"] as string;\n const submittedCsrf = body[\"csrf\"] as string;\n const submittedPassword = body[\"password\"] as string;\n\n const pending = pendingAuths.get(code);\n const expectedCsrf = csrfTokens.get(code);\n if (!pending || !expectedCsrf) {\n return c.html(\"<p>Invalid or expired authorization request.</p>\", 400);\n }\n\n // Validate CSRF token\n const csrfA = Buffer.from(submittedCsrf ?? \"\");\n const csrfB = Buffer.from(expectedCsrf);\n if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {\n return c.html(\"<p>Invalid request.</p>\", 403);\n }\n\n // Rate limiting: check lockout\n if (Date.now() < lockedUntil) {\n const waitSec = Math.ceil((lockedUntil - Date.now()) / 1000);\n console.warn(`Auth: locked out, ${waitSec}s remaining`);\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n const a = Buffer.from(submittedPassword);\n const b = Buffer.from(password);\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n failedAttempts++;\n console.warn(`Auth: failed attempt ${failedAttempts} total`);\n\n // Rotate CSRF token on each failed attempt\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n\n if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {\n lockoutCount = Math.min(lockoutCount + 1, 10);\n const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);\n lockedUntil = Date.now() + lockoutMs;\n console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1000}s`);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n console.log(\"Auth: password accepted, issuing authorization code.\");\n\n const url = new URL(pending.redirectUri);\n url.searchParams.set(\"code\", code);\n if (pending.state) url.searchParams.set(\"state\", pending.state);\n const redirectUrl = url.toString();\n\n return c.redirect(redirectUrl);\n });\n\n // --- Token endpoint ---\n\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.parseBody();\n const grantType = body[\"grant_type\"] as string;\n\n if (grantType === \"authorization_code\") {\n const code = body[\"code\"] as string;\n const clientId = body[\"client_id\"] as string;\n const codeVerifier = body[\"code_verifier\"] as string;\n const redirectUri = body[\"redirect_uri\"] as string;\n\n const pending = pendingAuths.get(code);\n if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {\n if (pending) pendingAuths.delete(code);\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Verify client_id matches the original request\n if (clientId !== pending.clientId) {\n return c.json({ error: \"invalid_grant\", error_description: \"client_id mismatch\" }, 400);\n }\n\n // Verify redirect_uri matches the original request\n if (redirectUri !== pending.redirectUri) {\n return c.json({ error: \"invalid_grant\", error_description: \"redirect_uri mismatch\" }, 400);\n }\n\n // Verify PKCE\n if (pending.codeChallengeMethod === \"S256\") {\n const expected = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed\" }, 400);\n }\n }\n\n pendingAuths.delete(code);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const refreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken,\n clientId: pending.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS,\n };\n tokens.set(accessToken, record);\n refreshTokens.set(refreshToken, record);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: refreshToken,\n });\n }\n\n if (grantType === \"refresh_token\") {\n const refreshToken = body[\"refresh_token\"] as string;\n const old = refreshTokens.get(refreshToken);\n if (!old) {\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Check refresh token expiry\n if (Date.now() > old.refreshExpiresAt) {\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n console.log(\"Auth: refresh token expired, user must re-authenticate.\");\n return c.json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" }, 400);\n }\n\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const newRefreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken: newRefreshToken,\n clientId: old.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: old.refreshExpiresAt, // keep original expiry\n };\n tokens.set(accessToken, record);\n refreshTokens.set(newRefreshToken, record);\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: newRefreshToken,\n });\n }\n\n return c.json({ error: \"unsupported_grant_type\" }, 400);\n });\n\n return {\n validateToken(authHeader: string | undefined): boolean {\n if (!authHeader?.startsWith(\"Bearer \")) return false;\n const token = authHeader.slice(7);\n const record = tokens.get(token);\n if (!record) return false;\n if (Date.now() > record.expiresAt) {\n tokens.delete(token);\n return false;\n }\n return true;\n },\n\n async saveTokens(): Promise<void> {\n 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 console.log(`Auth tokens saved to disk (${tokens.size} sessions).`);\n } catch (err) {\n console.error(\"Failed to save auth tokens:\", err);\n }\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 // Evict clients with no active tokens or refresh 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 for (const [k, c] of clients) {\n if (!activeClientIds.has(c.clientId)) clients.delete(k);\n }\n },\n\n async loadTokens(): Promise<boolean> {\n if (!persistPath) return false;\n try {\n const raw = await readFile(persistPath, \"utf-8\");\n const data = JSON.parse(raw);\n const now = Date.now();\n for (const [k, v] of Object.entries(data.tokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.clients ?? {})) {\n const client = v as RegisteredClient;\n if (client.clientId && client.redirectUris) clients.set(k, client);\n }\n console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);\n return tokens.size > 0;\n } catch {\n return false;\n }\n },\n };\n}\n\nfunction renderPasswordPage(code: string, csrf: string, error?: string): string {\n return `<!DOCTYPE html>\n<html><head><title>Obsidian Sync MCP - Authorize</title>\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'\">\n<style>\n body { font-family: system-ui; max-width: 400px; margin: 80px auto; padding: 0 20px; }\n h1 { font-size: 1.3em; }\n input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }\n button { padding: 10px 20px; font-size: 1em; cursor: pointer; }\n .error { color: red; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n ${error ? `<p class=\"error\">${error.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\")}</p>` : \"<p>Enter the server password to authorize access to your vault.</p>\"}\n <form method=\"POST\" action=\"/oauth/approve\" autocomplete=\"on\">\n <input type=\"hidden\" name=\"code\" value=\"${code.replace(/&/g, \"&\").replace(/\"/g, \""\")}\">\n <input type=\"hidden\" name=\"csrf\" value=\"${csrf.replace(/&/g, \"&\").replace(/\"/g, \""\")}\">\n <input type=\"text\" name=\"username\" id=\"username\" value=\"obsidian-sync-mcp\" autocomplete=\"username\" style=\"position:absolute;opacity:0;width:1px;height:1px;pointer-events:none\">\n <input type=\"password\" name=\"password\" id=\"password\" placeholder=\"Password\" autocomplete=\"current-password\" autofocus required>\n <br><button type=\"submit\">Authorize</button>\n </form>\n</body></html>`;\n}\n","/**\n * Metadata index for vault notes.\n *\n * Tracks paths, mtimes, tags, links, and backlinks.\n * Persists to disk (encrypted if passphrase is set).\n * No full-text search — metadata only.\n */\n\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { createCipheriv, createDecipheriv, randomBytes, scryptSync } from \"crypto\";\nimport { parseFrontmatterAndLinks } from \"./parse.js\";\n\n\nfunction encrypt(text: string, passphrase: string): string {\n const salt = randomBytes(16);\n const key = scryptSync(passphrase, salt, 32);\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n const encrypted = Buffer.concat([cipher.update(text, \"utf-8\"), cipher.final()]);\n const tag = (cipher as any).getAuthTag() as Buffer;\n return salt.toString(\"hex\") + \":\" + iv.toString(\"hex\") + \":\" + tag.toString(\"hex\") + \":\" + encrypted.toString(\"hex\");\n}\n\nfunction decrypt(data: string, passphrase: string): string {\n const [saltHex, ivHex, tagHex, encryptedHex] = data.split(\":\");\n const key = scryptSync(passphrase, Buffer.from(saltHex, \"hex\"), 32);\n const decipher = createDecipheriv(\"aes-256-gcm\", key, Buffer.from(ivHex, \"hex\"));\n (decipher as any).setAuthTag(Buffer.from(tagHex, \"hex\"));\n return Buffer.concat([decipher.update(Buffer.from(encryptedHex, \"hex\")), decipher.final()]).toString(\"utf-8\");\n}\n\nexport class SearchIndex {\n private mtimes = new Map<string, number>();\n private tags = new Map<string, string[]>();\n private links = new Map<string, string[]>();\n private backlinks = new Map<string, Set<string>>();\n private knownPaths = new Set<string>();\n private saving = false;\n private _since: string = \"\";\n private persistPath: string | null;\n private passphrase: string | null;\n\n constructor(persistPath?: string, passphrase?: string) {\n this.persistPath = persistPath ?? null;\n this.passphrase = passphrase ?? null;\n }\n\n /** Load metadata from disk. */\n async loadFromDisk(): Promise<boolean> {\n if (!this.persistPath) return false;\n try {\n let raw = await readFile(this.persistPath, \"utf-8\");\n if (this.passphrase) {\n raw = decrypt(raw, this.passphrase);\n }\n const data = JSON.parse(raw);\n for (const [path, mtime] of Object.entries(data.mtimes ?? {})) {\n this.mtimes.set(path, mtime as number);\n this.knownPaths.add(path);\n }\n for (const [path, t] of Object.entries(data.tags ?? {})) {\n this.tags.set(path, t as string[]);\n }\n for (const [path, l] of Object.entries(data.links ?? {})) {\n const targets = l as string[];\n this.links.set(path, targets);\n for (const target of targets) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n }\n if (data.since) this._since = data.since;\n console.log(`Search metadata loaded from disk (${this.knownPaths.size} notes, since: ${this._since ? \"yes\" : \"none\"}).`);\n return this.knownPaths.size > 0;\n } catch {\n return false;\n }\n }\n\n /** Save metadata to disk. Encrypted if passphrase is set. */\n async saveToDisk(): Promise<void> {\n if (!this.persistPath || this.saving) return;\n this.saving = true;\n try {\n await mkdir(dirname(this.persistPath), { recursive: true });\n let data = JSON.stringify({\n mtimes: Object.fromEntries(this.mtimes),\n tags: Object.fromEntries(this.tags),\n links: Object.fromEntries(this.links),\n since: this._since,\n });\n if (this.passphrase) {\n data = encrypt(data, this.passphrase);\n }\n await writeFile(this.persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(this.persistPath, 0o600);\n console.log(`Search index saved to disk (${this.knownPaths.size} notes${this.passphrase ? \", encrypted\" : \"\"}).`);\n } catch (err) {\n console.error(\"Failed to save search index:\", err);\n } finally {\n this.saving = false;\n }\n }\n\n /** Add or update a note in the index. */\n update(path: string, content: string, mtime?: number): void {\n if (this.knownPaths.has(path)) {\n this.clearBacklinks(path);\n }\n this.knownPaths.add(path);\n if (mtime !== undefined) this.mtimes.set(path, mtime);\n const parsed = parseFrontmatterAndLinks(content);\n if (parsed.tags.length > 0) {\n this.tags.set(path, parsed.tags);\n } else {\n this.tags.delete(path);\n }\n if (parsed.links.length > 0) {\n this.links.set(path, parsed.links);\n for (const target of parsed.links) {\n const key = target.toLowerCase();\n if (!this.backlinks.has(key)) this.backlinks.set(key, new Set());\n this.backlinks.get(key)!.add(path);\n }\n } else {\n this.links.delete(path);\n }\n }\n\n /** Remove a note from the index. */\n remove(path: string): void {\n if (this.knownPaths.has(path)) {\n this.knownPaths.delete(path);\n this.mtimes.delete(path);\n this.tags.delete(path);\n this.clearBacklinks(path);\n }\n }\n\n /** Remove all backlink entries where path is the source. */\n private clearBacklinks(path: string): void {\n const oldLinks = this.links.get(path);\n if (oldLinks) {\n for (const target of oldLinks) {\n const key = target.toLowerCase();\n this.backlinks.get(key)?.delete(path);\n if (this.backlinks.get(key)?.size === 0) this.backlinks.delete(key);\n }\n }\n this.links.delete(path);\n }\n\n /** List all indexed paths, optionally filtered by folder prefix. */\n listPaths(folder?: string): string[] {\n return this.listWithMtime(folder).map((n) => n.path);\n }\n\n /** List all indexed paths with mtimes, optionally filtered by folder prefix. */\n listWithMtime(folder?: string): Array<{ path: string; mtime: number }> {\n const prefix = folder && !folder.endsWith(\"/\") ? folder + \"/\" : folder;\n const entries = [...this.knownPaths]\n .filter((p) => p.endsWith(\".md\"))\n .filter((p) => !prefix || p.startsWith(prefix))\n .map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));\n return entries.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n /** Get mtime for a path. */\n getMtime(path: string): number {\n return this.mtimes.get(path) ?? 0;\n }\n\n /** Get tags for a path. */\n getTags(path: string): string[] {\n return this.tags.get(path) ?? [];\n }\n\n /** Get outgoing links for a path. */\n getLinks(path: string): string[] {\n return this.links.get(path) ?? [];\n }\n\n /** Get backlinks for a path (notes that link to it). Case-insensitive, matches by full path or filename. */\n getBacklinks(path: string): string[] {\n const results = new Set<string>();\n const withMd = (path.endsWith(\".md\") ? path : path + \".md\").toLowerCase();\n const withoutMd = (path.endsWith(\".md\") ? path.slice(0, -3) : path).toLowerCase();\n const nameOnly = withoutMd.includes(\"/\") ? withoutMd.slice(withoutMd.lastIndexOf(\"/\") + 1) : withoutMd;\n\n for (const target of [withMd, withoutMd, nameOnly]) {\n const sources = this.backlinks.get(target);\n if (sources) {\n for (const s of sources) results.add(s);\n }\n }\n return [...results].sort();\n }\n\n /** List all tags across the vault with counts. */\n listAllTags(): Array<{ tag: string; count: number }> {\n const counts = new Map<string, number>();\n for (const tags of this.tags.values()) {\n for (const t of tags) {\n counts.set(t, (counts.get(t) ?? 0) + 1);\n }\n }\n return [...counts.entries()]\n .map(([tag, count]) => ({ tag, count }))\n .sort((a, b) => b.count - a.count);\n }\n\n /** Clear all index data (for full rebuild after DB nuke). */\n clear(): void {\n const paths = Array.from(this.knownPaths);\n for (const p of paths) this.remove(p);\n this._since = \"\";\n }\n\n get since(): string {\n return this._since;\n }\n\n set since(value: string) {\n this._since = value;\n }\n\n get size(): number {\n return this.knownPaths.size;\n }\n}\n","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\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\nexport function registerTools(\n server: FastMCP,\n vault: VaultBackend,\n searchIndex: SearchIndex,\n vaultName: string,\n readOnly = false,\n) {\n if (readOnly) {\n console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(\", \")}).`);\n }\n const _addTool = server.addTool.bind(server);\n server.addTool = (tool: any) => {\n const original = tool.execute;\n tool.execute = async (args: any, ctx: any) => {\n if (debugLogging) console.log(`[tool] ${tool.name}(${JSON.stringify(args)})`);\n const start = performance.now();\n const result = await original(args, ctx);\n if (debugLogging) console.log(`[tool] ${tool.name} → ${((performance.now() - start)).toFixed(0)}ms`);\n return result;\n };\n return _addTool(tool);\n };\n server.addTool({\n name: \"read_note\",\n description:\n \"Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n }),\n execute: async ({ path }) => {\n const content = await vault.readNote(path);\n if (content === null) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n return `[Open in Obsidian](${deepLink})\\n\\n---\\n\\n${content}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"write_note\",\n description:\n \"Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does — read first if you need to preserve existing content.\",\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 const ok = await vault.writeNote(path, content);\n if (!ok) {\n return `Failed to write note: ${path}`;\n }\n searchIndex.update(path, content, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note saved: ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"list_notes\",\n description: \"List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(name='meeting') to find notes by name. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.\",\n parameters: z.object({\n folder: z\n .string()\n .optional()\n .describe(\"Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes.\"),\n name: z\n .string()\n .optional()\n .describe(\"Filter by name (case-insensitive substring match on path), e.g. 'meeting' or 'project-x'.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags.\"),\n sort_by: z\n .enum([\"name\", \"modified\"])\n .optional()\n .describe(\"Sort order: 'name' (default) or 'modified' (most recent first).\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'.\"),\n limit: z.coerce\n .number()\n .optional()\n .describe(\"Max number of notes to return. Default 100.\"),\n }),\n execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {\n // Use search index (works with encrypted vaults), fall back to vault\n let notes = searchIndex.listWithMtime(folder);\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n }\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n }\n if (modified_after) {\n const cutoff = new Date(modified_after).getTime();\n if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n notes = notes.filter((n) => n.mtime >= cutoff);\n }\n if (notes.length === 0) {\n return folder ? `No notes found in folder: ${folder}` : \"Vault is empty.\";\n }\n if (sort_by === \"modified\") {\n notes.sort((a, b) => b.mtime - a.mtime);\n }\n const cap = limit ?? 100;\n const total = notes.length;\n const capped = notes.slice(0, cap);\n const lines = capped.map((n) => {\n const deepLink = makeDeepLink(vaultName, n.path);\n const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : \"\";\n return `- ${date} [${n.path}](${deepLink})`;\n });\n if (total > cap) {\n lines.push(`\\n... and ${total - cap} more. Use a folder filter or limit to narrow results.`);\n }\n return lines.join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_folders\",\n description:\n \"List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.\",\n parameters: z.object({}),\n execute: async () => {\n let paths = searchIndex.listPaths();\n if (paths.length === 0) {\n paths = await vault.listNotes();\n }\n const folders = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n folders.set(\"(root)\", (folders.get(\"(root)\") ?? 0) + 1);\n } else {\n const folder = p.slice(0, lastSlash);\n folders.set(folder, (folders.get(folder) ?? 0) + 1);\n // Ensure all parent folders appear in the list\n let parent = folder;\n while (parent.includes(\"/\")) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n if (!folders.has(parent)) folders.set(parent, 0);\n }\n }\n }\n if (folders.size === 0) {\n return \"Vault is empty.\";\n }\n const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));\n return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_tags\",\n description:\n \"List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes.\",\n parameters: z.object({}),\n execute: async () => {\n const tags = searchIndex.listAllTags();\n if (tags.length === 0) {\n return \"No tags found in the vault.\";\n }\n return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join(\"\\n\");\n },\n });\n\n\n\n if (!readOnly) server.addTool({\n name: \"edit_note\",\n description:\n \"Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.\",\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 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.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note to delete\"),\n }),\n execute: async ({ 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.\",\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 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"],"mappings":";;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,mBAAAA,kBAAiB,cAAAC,mBAAkB;AAC5C,SAAS,OAAO,cAAc,gBAAgB;AAC9C,SAAS,YAAY;AACrB,SAAS,sBAAsB,kBAAkB;;;ACUjD,SAAS,YAAY,aAAa,YAAY,uBAAuB;AACrE,SAAS,UAAU,WAAW,OAAO,aAAa;AAClD,SAAS,eAAe;AA4BxB,IAAM,kBAAkB,OAAO;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB,SAAS,QAAQ,IAAI,oBAAoB,OAAO,oBAAoB,CAAC,KAAK,wBAAwB,KAAK,OAAO;AACzI,IAAM,4BAA4B;AAClC,IAAM,kBAAkB,IAAI;AAC5B,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,iBAAiB,KAAK,KAAK;AAS1B,SAAS,kBAAkB,KAAW,SAAiB,UAAkB,aAAkC;AAC9G,QAAM,eAAe,oBAAI,IAAyB;AAClD,QAAM,aAAa,oBAAI,IAAoB;AAC3C,QAAM,SAAS,oBAAI,IAAyB;AAC5C,QAAM,gBAAgB,oBAAI,IAAyB;AACnD,QAAM,UAAU,oBAAI,IAA8B;AAGlD,WAAS,iBAAiB;AACtB,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW,CAAC,MAAM,OAAO,KAAK,cAAc;AACxC,UAAI,MAAM,QAAQ,YAAY,gBAAgB;AAC1C,qBAAa,OAAO,IAAI;AACxB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kdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","server","vault","searchIndex","debugLogging","createHash","timingSafeEqual"]}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Node polyfills for livesync-commonlib browser globals
|
|
3
3
|
if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
|
|
4
|
+
import {
|
|
5
|
+
deriveContent
|
|
6
|
+
} from "./chunk-SGLPTZJA.js";
|
|
4
7
|
import {
|
|
5
8
|
__reExport,
|
|
6
9
|
parseFrontmatterAndLinks
|
|
@@ -11024,12 +11027,8 @@ var Vault = class _Vault {
|
|
|
11024
11027
|
static docToChange(doc, callback, seq) {
|
|
11025
11028
|
const path = doc.path ?? "";
|
|
11026
11029
|
if (!path.endsWith(".md")) return;
|
|
11027
|
-
|
|
11028
|
-
|
|
11029
|
-
} else {
|
|
11030
|
-
const content = "data" in doc && Array.isArray(doc.data) ? doc.data.join("") : null;
|
|
11031
|
-
callback(path, content, doc.mtime, seq);
|
|
11032
|
-
}
|
|
11030
|
+
const content = deriveContent(doc);
|
|
11031
|
+
callback(path, content, content === null ? void 0 : doc.mtime, seq);
|
|
11033
11032
|
}
|
|
11034
11033
|
async catchUp(since, callback, onBatch) {
|
|
11035
11034
|
const BATCH_SIZE2 = 50;
|
|
@@ -11155,4 +11154,4 @@ var Vault = class _Vault {
|
|
|
11155
11154
|
export {
|
|
11156
11155
|
Vault
|
|
11157
11156
|
};
|
|
11158
|
-
//# sourceMappingURL=vault-
|
|
11157
|
+
//# sourceMappingURL=vault-BL4NJC75.js.map
|