obsidian-sync-mcp 0.6.5 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-52RMOUUH.js → chunk-43MP6CJE.js} +72 -3
- package/dist/chunk-43MP6CJE.js.map +1 -0
- package/dist/main.js +129 -14
- package/dist/main.js.map +1 -1
- package/dist/{vault-W6NTMJCS.js → vault-YGHHZZZQ.js} +2 -2
- package/dist/{vault-local-B3MNR7YI.js → vault-local-S53KTNRT.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-52RMOUUH.js.map +0 -1
- /package/dist/{vault-W6NTMJCS.js.map → vault-YGHHZZZQ.js.map} +0 -0
- /package/dist/{vault-local-B3MNR7YI.js.map → vault-local-S53KTNRT.js.map} +0 -0
|
@@ -35,7 +35,7 @@ function parseFrontmatterAndLinks(content) {
|
|
|
35
35
|
}
|
|
36
36
|
inTagsList = false;
|
|
37
37
|
}
|
|
38
|
-
const match = line.match(/^(\
|
|
38
|
+
const match = line.match(/^([\p{L}\p{N}_][\p{L}\p{M}\p{N}_-]*)\s*:\s*(.+)/u);
|
|
39
39
|
if (match) {
|
|
40
40
|
frontmatter[match[1]] = match[2].trim();
|
|
41
41
|
}
|
|
@@ -54,7 +54,8 @@ function parseFrontmatterAndLinks(content) {
|
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
for (const match of content.matchAll(/(^|\s)#([\
|
|
57
|
+
for (const match of maskCode(content).matchAll(/(^|\s)#([\p{L}\p{N}_/-][\p{L}\p{M}\p{N}_/-]*)/gu)) {
|
|
58
|
+
if (new RegExp("^\\p{Nd}+$", "u").test(match[2])) continue;
|
|
58
59
|
tags.add(match[2]);
|
|
59
60
|
}
|
|
60
61
|
for (const match of content.matchAll(/\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/g)) {
|
|
@@ -65,9 +66,77 @@ function parseFrontmatterAndLinks(content) {
|
|
|
65
66
|
}
|
|
66
67
|
return { frontmatter, tags: [...tags], links: [...new Set(links)] };
|
|
67
68
|
}
|
|
69
|
+
function maskCode(content) {
|
|
70
|
+
const lines = content.split("\n");
|
|
71
|
+
const out = [];
|
|
72
|
+
let fence = null;
|
|
73
|
+
const inline = [];
|
|
74
|
+
const flushInline = () => {
|
|
75
|
+
if (inline.length === 0) return;
|
|
76
|
+
out.push(...maskInlineSpans(inline.join("\n")).split("\n"));
|
|
77
|
+
inline.length = 0;
|
|
78
|
+
};
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
const open = line.match(/^ {0,3}(`{3,}|~{3,})/);
|
|
81
|
+
if (fence) {
|
|
82
|
+
const close = open && open[1][0] === fence.char && open[1].length >= fence.len && line.trim() === open[1];
|
|
83
|
+
out.push(".".repeat(line.length));
|
|
84
|
+
if (close) fence = null;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (open && (open[1][0] === "~" || !line.slice(open[0].length).includes("`"))) {
|
|
88
|
+
flushInline();
|
|
89
|
+
fence = { char: open[1][0], len: open[1].length };
|
|
90
|
+
out.push(".".repeat(line.length));
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (line.trim() === "") {
|
|
94
|
+
flushInline();
|
|
95
|
+
out.push(line);
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
inline.push(line);
|
|
99
|
+
}
|
|
100
|
+
flushInline();
|
|
101
|
+
return out.join("\n");
|
|
102
|
+
}
|
|
103
|
+
function maskInlineSpans(text) {
|
|
104
|
+
const runs = [];
|
|
105
|
+
for (let i = 0; i < text.length; ) {
|
|
106
|
+
if (text[i] !== "`") {
|
|
107
|
+
i++;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
let n = 0;
|
|
111
|
+
while (text[i + n] === "`") n++;
|
|
112
|
+
runs.push({ at: i, len: n });
|
|
113
|
+
i += n;
|
|
114
|
+
}
|
|
115
|
+
const next = [];
|
|
116
|
+
const seen = /* @__PURE__ */ new Map();
|
|
117
|
+
for (let r = runs.length - 1; r >= 0; r--) {
|
|
118
|
+
next[r] = seen.get(runs[r].len) ?? -1;
|
|
119
|
+
seen.set(runs[r].len, r);
|
|
120
|
+
}
|
|
121
|
+
let result = "";
|
|
122
|
+
let from = 0;
|
|
123
|
+
for (let r = 0; r < runs.length; ) {
|
|
124
|
+
const c = next[r];
|
|
125
|
+
if (c === -1) {
|
|
126
|
+
r++;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const start = runs[r].at;
|
|
130
|
+
const end = runs[c].at + runs[c].len;
|
|
131
|
+
result += text.slice(from, start) + text.slice(start, end).replace(/[^\n]/g, ".");
|
|
132
|
+
from = end;
|
|
133
|
+
r = c + 1;
|
|
134
|
+
}
|
|
135
|
+
return result + text.slice(from);
|
|
136
|
+
}
|
|
68
137
|
|
|
69
138
|
export {
|
|
70
139
|
__reExport,
|
|
71
140
|
parseFrontmatterAndLinks
|
|
72
141
|
};
|
|
73
|
-
//# sourceMappingURL=chunk-
|
|
142
|
+
//# sourceMappingURL=chunk-43MP6CJE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/parse.ts"],"sourcesContent":["/**\n * Parse Obsidian markdown content for frontmatter, tags, and links.\n */\n\nexport interface NoteMetadata {\n frontmatter: Record<string, string>;\n tags: string[];\n links: string[];\n}\n\nexport function parseFrontmatterAndLinks(content: string): NoteMetadata {\n const frontmatter: Record<string, any> = {};\n const tags = new Set<string>();\n const links: string[] = [];\n\n // Parse YAML frontmatter\n if (content.startsWith(\"---\\n\")) {\n const end = content.indexOf(\"\\n---\", 4);\n if (end !== -1) {\n const yaml = content.slice(4, end);\n let inTagsList = false;\n for (const line of yaml.split(\"\\n\")) {\n // Multi-line tags list item: \" - tagname\"\n if (inTagsList) {\n const listItem = line.match(/^\\s+-\\s+(.+)/);\n if (listItem) {\n const trimmed = listItem[1].trim();\n if (trimmed) tags.add(trimmed);\n continue;\n }\n inTagsList = false;\n }\n\n const match = line.match(/^([\\p{L}\\p{N}_][\\p{L}\\p{M}\\p{N}_-]*)\\s*:\\s*(.+)/u);\n if (match) {\n frontmatter[match[1]] = match[2].trim();\n }\n // Frontmatter tags (inline: [a, b] or start of multi-line list)\n if (/^tags\\s*:/.test(line)) {\n const value = line.replace(/^tags\\s*:\\s*/, \"\").trim();\n if (value) {\n // Inline: tags: [a, b] or tags: a, b\n const tagValues = value.replace(/[[\\]]/g, \"\");\n for (const t of tagValues.split(\",\")) {\n const trimmed = t.trim();\n if (trimmed) tags.add(trimmed);\n }\n } else {\n // Multi-line list follows\n inTagsList = true;\n }\n }\n }\n }\n }\n\n // Inline #tags. Obsidian does not read tags out of code, and a tag must\n // contain at least one non-numerical character (\"#1984 isn't a valid tag,\n // but #y1984 is\" — obsidian.md/help/tags), so code spans and fenced blocks\n // are masked out first and all-digit matches are dropped.\n for (const match of maskCode(content).matchAll(/(^|\\s)#([\\p{L}\\p{N}_/-][\\p{L}\\p{M}\\p{N}_/-]*)/gu)) {\n if (/^\\p{Nd}+$/u.test(match[2])) continue;\n tags.add(match[2]);\n }\n\n // [[wikilinks]]\n for (const match of content.matchAll(/\\[\\[([^\\]|]+)(?:\\|[^\\]]+)?\\]\\]/g)) {\n links.push(match[1]);\n }\n\n // [markdown links](path.md)\n for (const match of content.matchAll(/\\[([^\\]]+)\\]\\(([^)]+\\.md)\\)/g)) {\n links.push(match[2]);\n }\n\n return { frontmatter, tags: [...tags], links: [...new Set(links)] };\n}\n\n/**\n * Replace fenced code blocks (``` or ~~~, opener at line start with up to three\n * spaces of indent, closer of the same character and at least the same length;\n * an unclosed fence runs to the end) and inline code spans (a backtick run of\n * length n closes at the next run of exactly n within the same paragraph — a\n * span never crosses a blank line; an unmatched run is literal)\n * with dots, so offsets are preserved and nothing inside can start or extend a\n * tag. Indented code blocks, %% comments and math are not masked.\n */\nexport function maskCode(content: string): string {\n const lines = content.split(\"\\n\");\n const out: string[] = [];\n let fence: { char: string; len: number } | null = null;\n const inline: string[] = [];\n const flushInline = () => {\n if (inline.length === 0) return;\n out.push(...maskInlineSpans(inline.join(\"\\n\")).split(\"\\n\"));\n inline.length = 0;\n };\n for (const line of lines) {\n const open = line.match(/^ {0,3}(`{3,}|~{3,})/);\n if (fence) {\n const close = open && open[1][0] === fence.char && open[1].length >= fence.len && line.trim() === open[1];\n out.push(\".\".repeat(line.length));\n if (close) fence = null;\n continue;\n }\n if (open && (open[1][0] === \"~\" || !line.slice(open[0].length).includes(\"`\"))) {\n flushInline();\n fence = { char: open[1][0], len: open[1].length };\n out.push(\".\".repeat(line.length));\n continue;\n }\n if (line.trim() === \"\") {\n flushInline();\n out.push(line);\n continue;\n }\n inline.push(line);\n }\n flushInline();\n return out.join(\"\\n\");\n}\n\nfunction maskInlineSpans(text: string): string {\n // Collect backtick runs in one pass, then link each run to the next run of\n // the same length (scanning right to left) so matching stays linear.\n const runs: { at: number; len: number }[] = [];\n for (let i = 0; i < text.length; ) {\n if (text[i] !== \"`\") { i++; continue; }\n let n = 0;\n while (text[i + n] === \"`\") n++;\n runs.push({ at: i, len: n });\n i += n;\n }\n const next: number[] = [];\n const seen = new Map<number, number>();\n for (let r = runs.length - 1; r >= 0; r--) {\n next[r] = seen.get(runs[r].len) ?? -1;\n seen.set(runs[r].len, r);\n }\n let result = \"\";\n let from = 0;\n for (let r = 0; r < runs.length; ) {\n const c = next[r];\n if (c === -1) { r++; continue; }\n const start = runs[r].at;\n const end = runs[c].at + runs[c].len;\n result += text.slice(from, start) + text.slice(start, end).replace(/[^\\n]/g, \".\");\n from = end;\n r = c + 1;\n }\n return result + text.slice(from);\n}\n\nexport function extractSnippet(content: string, query: string, context = 80): string {\n const lower = content.toLowerCase();\n\n // Try exact phrase first\n let idx = lower.indexOf(query.toLowerCase());\n\n // Try to find the smallest span containing all query words\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).map((w) => w.toLowerCase());\n if (words.length > 1) {\n let bestStart = -1;\n let bestLen = Infinity;\n // For each occurrence of the first word, find the nearest span containing all words\n const first = words[0];\n let pos = 0;\n while (pos < lower.length) {\n const start = lower.indexOf(first, pos);\n if (start === -1) break;\n // Find last position needed to include all words from this start\n let spanEnd = start + first.length;\n let allFound = true;\n for (let i = 1; i < words.length; i++) {\n const wi = lower.indexOf(words[i], Math.max(0, start - 200));\n if (wi === -1) { allFound = false; break; }\n spanEnd = Math.max(spanEnd, wi + words[i].length);\n }\n if (allFound) {\n const spanStart = Math.min(start, ...words.map((w) => lower.indexOf(w, Math.max(0, start - 200))).filter((i) => i >= 0));\n const len = spanEnd - spanStart;\n if (len < bestLen) { bestStart = spanStart; bestLen = len; }\n }\n pos = start + 1;\n }\n if (bestStart >= 0 && bestLen <= 500) idx = bestStart;\n }\n }\n\n // Fall back to longest matching word\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).sort((a, b) => b.length - a.length);\n for (const word of words) {\n idx = lower.indexOf(word.toLowerCase());\n if (idx !== -1) break;\n }\n }\n\n if (idx === -1) {\n return content.slice(0, 160) + (content.length > 160 ? \"...\" : \"\");\n }\n const start = Math.max(0, idx - context);\n const end = Math.min(content.length, idx + query.length + context);\n return (start > 0 ? \"...\" : \"\") + content.slice(start, end) + (end < content.length ? \"...\" : \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAUO,SAAS,yBAAyB,SAA+B;AACpE,QAAM,cAAmC,CAAC;AAC1C,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,QAAkB,CAAC;AAGzB,MAAI,QAAQ,WAAW,OAAO,GAAG;AAC7B,UAAM,MAAM,QAAQ,QAAQ,SAAS,CAAC;AACtC,QAAI,QAAQ,IAAI;AACZ,YAAM,OAAO,QAAQ,MAAM,GAAG,GAAG;AACjC,UAAI,aAAa;AACjB,iBAAW,QAAQ,KAAK,MAAM,IAAI,GAAG;AAEjC,YAAI,YAAY;AACZ,gBAAM,WAAW,KAAK,MAAM,cAAc;AAC1C,cAAI,UAAU;AACV,k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M,OAAiB,CAAC;AACxB,QAAM,OAAO,oBAAI,IAAoB;AACrC,WAAS,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;AACvC,SAAK,CAAC,IAAI,KAAK,IAAI,KAAK,CAAC,EAAE,GAAG,KAAK;AACnC,SAAK,IAAI,KAAK,CAAC,EAAE,KAAK,CAAC;AAAA,EAC3B;AACA,MAAI,SAAS;AACb,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,KAAK,UAAU;AAC/B,UAAM,IAAI,KAAK,CAAC;AAChB,QAAI,MAAM,IAAI;AAAE;AAAK;AAAA,IAAU;AAC/B,UAAM,QAAQ,KAAK,CAAC,EAAE;AACtB,UAAM,MAAM,KAAK,CAAC,EAAE,KAAK,KAAK,CAAC,EAAE;AACjC,cAAU,KAAK,MAAM,MAAM,KAAK,IAAI,KAAK,MAAM,OAAO,GAAG,EAAE,QAAQ,UAAU,GAAG;AAChF,WAAO;AACP,QAAI,IAAI;AAAA,EACZ;AACA,SAAO,SAAS,KAAK,MAAM,IAAI;AACnC;","names":[]}
|
package/dist/main.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-SGLPTZJA.js";
|
|
7
7
|
import {
|
|
8
8
|
parseFrontmatterAndLinks
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-43MP6CJE.js";
|
|
10
10
|
|
|
11
11
|
// src/main.ts
|
|
12
12
|
import { FastMCP } from "fastmcp";
|
|
@@ -173,7 +173,8 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
|
|
|
173
173
|
codeChallengeMethod,
|
|
174
174
|
state,
|
|
175
175
|
code,
|
|
176
|
-
createdAt: Date.now()
|
|
176
|
+
createdAt: Date.now(),
|
|
177
|
+
approved: false
|
|
177
178
|
});
|
|
178
179
|
console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);
|
|
179
180
|
const csrf = randomBytes(32).toString("hex");
|
|
@@ -222,6 +223,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
|
|
|
222
223
|
lockoutCount = 0;
|
|
223
224
|
lockedUntil = 0;
|
|
224
225
|
csrfTokens.delete(code);
|
|
226
|
+
pending.approved = true;
|
|
225
227
|
console.log("Auth: password accepted, issuing authorization code.");
|
|
226
228
|
const url = new URL(pending.redirectUri);
|
|
227
229
|
url.searchParams.set("code", code);
|
|
@@ -246,6 +248,10 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
|
|
|
246
248
|
if (pending) pendingAuths.delete(code);
|
|
247
249
|
return c.json({ error: "invalid_grant" }, 400);
|
|
248
250
|
}
|
|
251
|
+
if (!pending.approved) {
|
|
252
|
+
console.warn("Auth: /oauth/token invalid_grant. code not yet approved (password step not completed)");
|
|
253
|
+
return c.json({ error: "invalid_grant", error_description: "authorization not approved" }, 400);
|
|
254
|
+
}
|
|
249
255
|
if (clientId !== pending.clientId) {
|
|
250
256
|
console.warn(
|
|
251
257
|
`Auth: /oauth/token client_id mismatch. received=${JSON.stringify(clientId)} expected=${JSON.stringify(pending.clientId)}`
|
|
@@ -419,6 +425,7 @@ function decrypt(data, passphrase) {
|
|
|
419
425
|
return Buffer.concat([decipher.update(Buffer.from(encryptedHex, "hex")), decipher.final()]).toString("utf-8");
|
|
420
426
|
}
|
|
421
427
|
var SearchIndex = class {
|
|
428
|
+
_state = "building";
|
|
422
429
|
mtimes = /* @__PURE__ */ new Map();
|
|
423
430
|
tags = /* @__PURE__ */ new Map();
|
|
424
431
|
links = /* @__PURE__ */ new Map();
|
|
@@ -584,6 +591,13 @@ var SearchIndex = class {
|
|
|
584
591
|
const paths = Array.from(this.knownPaths);
|
|
585
592
|
for (const p of paths) this.remove(p);
|
|
586
593
|
this._since = "";
|
|
594
|
+
this._state = "building";
|
|
595
|
+
}
|
|
596
|
+
get state() {
|
|
597
|
+
return this._state;
|
|
598
|
+
}
|
|
599
|
+
set state(value) {
|
|
600
|
+
this._state = value;
|
|
587
601
|
}
|
|
588
602
|
get since() {
|
|
589
603
|
return this._since;
|
|
@@ -654,9 +668,84 @@ function isPathWritable(path, writeFolders) {
|
|
|
654
668
|
return writeFolders.some((folder) => normalized.startsWith(folder + "/"));
|
|
655
669
|
}
|
|
656
670
|
|
|
671
|
+
// src/list-format.ts
|
|
672
|
+
var MAX_NAMED_FOLDERS = 10;
|
|
673
|
+
function plural(n, word) {
|
|
674
|
+
return `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
675
|
+
}
|
|
676
|
+
function folderLabel(folder) {
|
|
677
|
+
return folder.endsWith("/") ? folder : folder + "/";
|
|
678
|
+
}
|
|
679
|
+
function countByFolder(paths) {
|
|
680
|
+
const counts = /* @__PURE__ */ new Map();
|
|
681
|
+
for (const p of paths) {
|
|
682
|
+
const lastSlash = p.lastIndexOf("/");
|
|
683
|
+
const folder = lastSlash === -1 ? "(root)" : p.slice(0, lastSlash);
|
|
684
|
+
counts.set(folder, (counts.get(folder) ?? 0) + 1);
|
|
685
|
+
}
|
|
686
|
+
return [...counts.entries()].map(([folder, count]) => ({ folder, count })).sort((a, b) => b.count - a.count || a.folder.localeCompare(b.folder));
|
|
687
|
+
}
|
|
688
|
+
function describeOmitted(omitted) {
|
|
689
|
+
const groups = countByFolder(omitted);
|
|
690
|
+
const named = groups.slice(0, MAX_NAMED_FOLDERS);
|
|
691
|
+
const rest = groups.slice(MAX_NAMED_FOLDERS);
|
|
692
|
+
const parts = named.map((g) => `${g.folder === "(root)" ? "(root)" : folderLabel(g.folder)} (${g.count})`);
|
|
693
|
+
let text = `Omitted ${omitted.length}: ${parts.join(", ")}`;
|
|
694
|
+
if (rest.length > 0) {
|
|
695
|
+
const restNotes = rest.reduce((sum, g) => sum + g.count, 0);
|
|
696
|
+
text += `, and ${plural(rest.length, "more folder")} (${plural(restNotes, "note")})`;
|
|
697
|
+
}
|
|
698
|
+
return text + ".";
|
|
699
|
+
}
|
|
700
|
+
function describeIndexState(index) {
|
|
701
|
+
const caveat = index.servedByVault ? "this list was read directly from the vault" : "this list may be incomplete";
|
|
702
|
+
switch (index.state) {
|
|
703
|
+
case "ready":
|
|
704
|
+
return "";
|
|
705
|
+
case "building":
|
|
706
|
+
return ` Index: catching up (${plural(index.size, "note")} indexed so far); ${caveat}.`;
|
|
707
|
+
case "failed":
|
|
708
|
+
return ` Index: rebuild failed at startup (see server log); ${index.servedByVault ? caveat : "this list may be incomplete or stale"}.`;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
function describeScopeCount(s) {
|
|
712
|
+
if (s.index.state !== "ready" && !s.index.servedByVault) return "";
|
|
713
|
+
if (s.folder) return s.folderTotal != null ? `folder has ${plural(s.folderTotal, "note")}` : "";
|
|
714
|
+
return s.vaultTotal != null ? `vault has ${plural(s.vaultTotal, "note")}` : "";
|
|
715
|
+
}
|
|
716
|
+
function describeNoMatch(s) {
|
|
717
|
+
const indexNote = describeIndexState(s.index);
|
|
718
|
+
if (s.filters.length === 0) {
|
|
719
|
+
if (s.folder) return `No notes found in folder: ${s.folder}${indexNote}`;
|
|
720
|
+
return `Vault is empty.${indexNote}`;
|
|
721
|
+
}
|
|
722
|
+
const count = describeScopeCount(s);
|
|
723
|
+
const scope = (s.folder ? ` in folder "${folderLabel(s.folder)}"` : "") + (count ? ` (${count})` : "");
|
|
724
|
+
return `No notes match ${s.filters.join(", ")}${scope}.${indexNote}`;
|
|
725
|
+
}
|
|
726
|
+
function describeListing(s) {
|
|
727
|
+
const truncated = s.matched > s.shown;
|
|
728
|
+
const verb = truncated ? "matching" : s.matched === 1 ? "matches" : "match";
|
|
729
|
+
const filterClause = s.filters.length > 0 ? ` ${verb} ${s.filters.join(", ")}` : "";
|
|
730
|
+
const folderClause = s.folder ? ` in folder "${folderLabel(s.folder)}"` : "";
|
|
731
|
+
const scopeParts = [];
|
|
732
|
+
const count = s.filters.length > 0 || s.folder ? describeScopeCount(s) : "";
|
|
733
|
+
if (count) scopeParts.push(count);
|
|
734
|
+
scopeParts.push(`sorted by ${s.sortBy}`);
|
|
735
|
+
if (truncated) scopeParts.push(`limit=${s.limit}`);
|
|
736
|
+
const scope = ` (${scopeParts.join(", ")})`;
|
|
737
|
+
let line = truncated ? `Showing ${s.shown} of ${plural(s.matched, "note")}${filterClause}${folderClause}${scope}.` : `${plural(s.matched, "note")}${filterClause}${folderClause}${scope}.`;
|
|
738
|
+
if (truncated) {
|
|
739
|
+
const hint = s.folder || s.filters.length > 0 ? "Raise `limit` or narrow the filter." : "Raise `limit` or add a `folder` filter.";
|
|
740
|
+
line += ` ${describeOmitted(s.omitted)} ${hint}`;
|
|
741
|
+
}
|
|
742
|
+
return line + describeIndexState(s.index);
|
|
743
|
+
}
|
|
744
|
+
|
|
657
745
|
// src/tools.ts
|
|
658
746
|
var debugLogging = process.env.LOG_LEVEL === "debug";
|
|
659
747
|
var WRITE_TOOLS = ["write_note", "edit_note", "delete_note", "move_note"];
|
|
748
|
+
var READ_NOTE_MAX_RESULT_SIZE_CHARS = 1e5;
|
|
660
749
|
function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = false, writeFolders = null) {
|
|
661
750
|
if (readOnly) {
|
|
662
751
|
console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(", ")}).`);
|
|
@@ -680,6 +769,7 @@ function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = fals
|
|
|
680
769
|
server2.addTool({
|
|
681
770
|
name: "read_note",
|
|
682
771
|
description: "Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.",
|
|
772
|
+
_meta: { "anthropic/maxResultSizeChars": READ_NOTE_MAX_RESULT_SIZE_CHARS },
|
|
683
773
|
parameters: z.object({
|
|
684
774
|
path: z.string().describe("Vault-relative path to the note, e.g. 'daily/2026-03-23.md'")
|
|
685
775
|
}),
|
|
@@ -728,40 +818,59 @@ ${content}`;
|
|
|
728
818
|
}),
|
|
729
819
|
execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {
|
|
730
820
|
let notes = searchIndex2.listWithMtime(folder);
|
|
821
|
+
let vaultTotal = searchIndex2.size;
|
|
822
|
+
let servedByVault = false;
|
|
731
823
|
if (notes.length === 0) {
|
|
732
824
|
notes = await vault2.listNotesWithMtime(folder);
|
|
825
|
+
servedByVault = notes.length > 0;
|
|
826
|
+
if (vaultTotal === 0) vaultTotal = folder ? null : notes.length;
|
|
733
827
|
}
|
|
828
|
+
const folderTotal = folder ? notes.length : null;
|
|
829
|
+
const filters = [];
|
|
734
830
|
if (name) {
|
|
735
831
|
const lower = name.toLowerCase();
|
|
736
832
|
notes = notes.filter((n) => n.path.toLowerCase().includes(lower));
|
|
833
|
+
filters.push(`name="${name}"`);
|
|
737
834
|
}
|
|
738
835
|
if (tag) {
|
|
739
836
|
notes = notes.filter((n) => searchIndex2.getTags(n.path).includes(tag));
|
|
837
|
+
filters.push(`tag="${tag}"`);
|
|
740
838
|
}
|
|
741
839
|
if (modified_after) {
|
|
742
840
|
const cutoff = new Date(modified_after).getTime();
|
|
743
841
|
if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;
|
|
744
842
|
notes = notes.filter((n) => n.mtime >= cutoff);
|
|
843
|
+
filters.push(`modified_after="${modified_after}"`);
|
|
745
844
|
}
|
|
845
|
+
const index = { state: searchIndex2.state, size: searchIndex2.size, servedByVault };
|
|
746
846
|
if (notes.length === 0) {
|
|
747
|
-
return
|
|
847
|
+
return describeNoMatch({ vaultTotal, folder, folderTotal, filters, index });
|
|
748
848
|
}
|
|
749
|
-
|
|
849
|
+
const sortBy = sort_by === "modified" ? "modified" : "name";
|
|
850
|
+
if (sortBy === "modified") {
|
|
750
851
|
notes.sort((a, b) => b.mtime - a.mtime);
|
|
751
852
|
}
|
|
752
853
|
const cap = limit ?? 100;
|
|
753
854
|
const total = notes.length;
|
|
754
855
|
const capped = notes.slice(0, cap);
|
|
856
|
+
const header = describeListing({
|
|
857
|
+
shown: capped.length,
|
|
858
|
+
matched: total,
|
|
859
|
+
vaultTotal,
|
|
860
|
+
folder,
|
|
861
|
+
folderTotal,
|
|
862
|
+
filters,
|
|
863
|
+
sortBy,
|
|
864
|
+
limit: cap,
|
|
865
|
+
omitted: notes.slice(cap).map((n) => n.path),
|
|
866
|
+
index
|
|
867
|
+
});
|
|
755
868
|
const lines = capped.map((n) => {
|
|
756
869
|
const deepLink = makeDeepLink(vaultName, n.path);
|
|
757
870
|
const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : "";
|
|
758
871
|
return `- ${date} [${n.path}](${deepLink})`;
|
|
759
872
|
});
|
|
760
|
-
|
|
761
|
-
lines.push(`
|
|
762
|
-
... and ${total - cap} more. Use a folder filter or limit to narrow results.`);
|
|
763
|
-
}
|
|
764
|
-
return lines.join("\n");
|
|
873
|
+
return [header, ...lines].join("\n");
|
|
765
874
|
}
|
|
766
875
|
});
|
|
767
876
|
server2.addTool({
|
|
@@ -865,6 +974,8 @@ ${content}`;
|
|
|
865
974
|
}),
|
|
866
975
|
execute: async ({ path }) => {
|
|
867
976
|
if (!isPathWritable(path, writeFolders)) return denyWrite(path);
|
|
977
|
+
const existing = await vault2.readNote(path);
|
|
978
|
+
if (existing === null) return `Note not found: ${path}`;
|
|
868
979
|
const ok = await vault2.deleteNote(path);
|
|
869
980
|
if (ok) searchIndex2.remove(path);
|
|
870
981
|
return ok ? `Deleted: ${path}` : `Failed to delete: ${path}`;
|
|
@@ -983,7 +1094,7 @@ if (MCP_INSTRUCTIONS_FILE) {
|
|
|
983
1094
|
}
|
|
984
1095
|
var vault;
|
|
985
1096
|
if (VAULT_PATH) {
|
|
986
|
-
const { LocalVault } = await import("./vault-local-
|
|
1097
|
+
const { LocalVault } = await import("./vault-local-S53KTNRT.js");
|
|
987
1098
|
vault = new LocalVault(VAULT_PATH);
|
|
988
1099
|
console.log(`Local mode: ${VAULT_PATH}`);
|
|
989
1100
|
} else if (COUCHDB_URL) {
|
|
@@ -991,7 +1102,7 @@ if (VAULT_PATH) {
|
|
|
991
1102
|
console.error("COUCHDB_PASSWORD is required in remote mode.");
|
|
992
1103
|
process.exit(1);
|
|
993
1104
|
}
|
|
994
|
-
const { Vault } = await import("./vault-
|
|
1105
|
+
const { Vault } = await import("./vault-YGHHZZZQ.js");
|
|
995
1106
|
vault = new Vault({
|
|
996
1107
|
couchdbUrl: COUCHDB_URL,
|
|
997
1108
|
couchdbUser: COUCHDB_USER,
|
|
@@ -1074,8 +1185,12 @@ async function rebuildIndex() {
|
|
|
1074
1185
|
}
|
|
1075
1186
|
}
|
|
1076
1187
|
await searchIndex.saveToDisk();
|
|
1188
|
+
searchIndex.state = "ready";
|
|
1077
1189
|
}
|
|
1078
|
-
rebuildIndex().catch((err) =>
|
|
1190
|
+
rebuildIndex().catch((err) => {
|
|
1191
|
+
searchIndex.state = "failed";
|
|
1192
|
+
console.error("Index rebuild failed:", err);
|
|
1193
|
+
});
|
|
1079
1194
|
var fsWatcher = null;
|
|
1080
1195
|
if (VAULT_PATH) {
|
|
1081
1196
|
const pending = /* @__PURE__ */ new Map();
|
|
@@ -1112,7 +1227,7 @@ if (VAULT_PATH) {
|
|
|
1112
1227
|
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.";
|
|
1113
1228
|
var serverOptions = {
|
|
1114
1229
|
name: "obsidian-sync-mcp",
|
|
1115
|
-
version: "0.
|
|
1230
|
+
version: "0.7.1",
|
|
1116
1231
|
instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
|
|
1117
1232
|
|
|
1118
1233
|
${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
|
|
@@ -1179,7 +1294,7 @@ server.start({
|
|
|
1179
1294
|
transportType: "httpStream",
|
|
1180
1295
|
httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
|
|
1181
1296
|
});
|
|
1182
|
-
console.log(`obsidian-sync-mcp v${"0.
|
|
1297
|
+
console.log(`obsidian-sync-mcp v${"0.7.1"} listening on port ${PORT}`);
|
|
1183
1298
|
process.on("unhandledRejection", (err) => {
|
|
1184
1299
|
console.error("Unhandled rejection:", err);
|
|
1185
1300
|
});
|
package/dist/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/host-guard.ts","../src/tools.ts","../src/deeplink.ts","../src/write-scope.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { timingSafeEqual, createHash } from \"crypto\";\nimport { watch, readFileSync, statSync } from \"fs\";\nimport { stat } from \"fs/promises\";\nimport { setGlobalLogFunction, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { mountPasswordAuth } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange } from \"./index-sync.js\";\nimport { buildAllowedHosts, isHostAllowed, isOriginAllowed } from \"./host-guard.js\";\nimport { registerTools } from \"./tools.js\";\nimport { parseWriteFolders } from \"./write-scope.js\";\n\n// Suppress livesync-commonlib logs that expose vault file paths in production.\n// Set LOG_LEVEL=debug to see all library logs during development.\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\nsetGlobalLogFunction((message, level = LEVEL_INFO) => {\n if (level < LEVEL_INFO) return;\n if (!debugLogging && typeof message === \"string\") {\n if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;\n if (message.includes(\"replicator\") || message.includes(\"Replicator\") || message.includes(\"ReplicatorService\")) return;\n }\n console.log(message);\n});\n\n// --- Configuration from environment ---\nconst VAULT_PATH = process.env.VAULT_PATH; // Local mode: path to vault directory\nconst COUCHDB_URL = process.env.COUCHDB_URL;\nconst COUCHDB_USER = process.env.COUCHDB_USER ?? \"admin\";\nconst COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;\nconst COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? \"obsidian\";\nconst COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || undefined;\nconst COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === \"true\";\nconst VAULT_NAME = process.env.VAULT_NAME ?? \"MyVault\";\nconst PORT = parseInt(process.env.PORT ?? \"8787\");\nconst BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;\nconst AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;\nconst READ_ONLY = process.env.READ_ONLY === \"true\";\nconst WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);\n\n// Extra instructions appended to the MCP `instructions` string.\n// File wins if both are set (loud warning); missing file is fatal.\nconst MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || undefined;\nconst MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || undefined;\nlet MCP_EXTRA_INSTRUCTIONS: string | undefined;\nconst MCP_INSTRUCTIONS_MAX_BYTES = 32 * 1024;\nif (MCP_INSTRUCTIONS_FILE) {\n try {\n const size = statSync(MCP_INSTRUCTIONS_FILE).size;\n if (size > MCP_INSTRUCTIONS_MAX_BYTES) {\n throw new Error(`file is ${size} bytes, exceeds ${MCP_INSTRUCTIONS_MAX_BYTES} byte cap`);\n }\n MCP_EXTRA_INSTRUCTIONS = readFileSync(MCP_INSTRUCTIONS_FILE, \"utf8\").trim() || undefined;\n } catch (err) {\n console.error(`Failed to read MCP_INSTRUCTIONS_FILE (${MCP_INSTRUCTIONS_FILE}): ${(err as Error).message}`);\n process.exit(1);\n }\n if (MCP_INSTRUCTIONS_ENV) {\n console.warn(\"MCP_INSTRUCTIONS_FILE is set; ignoring MCP_INSTRUCTIONS env var.\");\n }\n} else if (MCP_INSTRUCTIONS_ENV) {\n MCP_EXTRA_INSTRUCTIONS = MCP_INSTRUCTIONS_ENV;\n}\n\n// --- Initialize vault (local or remote) ---\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nlet vault: VaultBackend;\n\nif (VAULT_PATH) {\n const { LocalVault } = await import(\"./vault-local.js\");\n vault = new LocalVault(VAULT_PATH);\n console.log(`Local mode: ${VAULT_PATH}`);\n} else if (COUCHDB_URL) {\n if (!COUCHDB_PASSWORD) {\n console.error(\"COUCHDB_PASSWORD is required in remote mode.\");\n process.exit(1);\n }\n const { Vault } = await import(\"./vault.js\");\n vault = new Vault({\n couchdbUrl: COUCHDB_URL,\n couchdbUser: COUCHDB_USER,\n couchdbPassword: COUCHDB_PASSWORD,\n database: COUCHDB_DATABASE,\n passphrase: COUCHDB_PASSPHRASE,\n obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,\n });\n console.log(`Remote mode: ${COUCHDB_URL}`);\n} else {\n console.error(\"Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.\");\n process.exit(1);\n}\n\nawait vault.init();\nconsole.log(\"Vault ready.\");\n\n// --- Per-vault data directory ---\nconst baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? \"/tmp\", \".obsidian-mcp\");\nconst vaultId = createHash(\"sha256\").update(VAULT_NAME).digest(\"hex\").slice(0, 12);\nconst dataDir = join(baseDataDir, vaultId);\n\n// --- Search index ---\nconst indexPath = join(dataDir, \"search-index.json\");\nconst searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);\n\n// Load persisted metadata from disk\nawait searchIndex.loadFromDisk();\nif (debugLogging) {\n console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || \"(none)\"}`);\n}\n\n// Sync metadata in background (server starts immediately)\nasync function rebuildIndex() {\n const start = performance.now();\n\n if (COUCHDB_URL && vault.catchUp) {\n const changeCallback = (path: string, content: string | null, mtime?: number) => {\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n\n let since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n const onBatch = async (batchSince: string, processed: number) => {\n searchIndex.since = batchSince;\n await searchIndex.saveToDisk();\n console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);\n };\n try {\n const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n changeCallback(path, content, mtime);\n };\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n } catch (err) {\n console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);\n searchIndex.clear();\n changes = 0;\n const newSince = await vault.catchUp(\"0\", (path, content, mtime) => {\n changes++;\n changeCallback(path, content, mtime);\n }, onBatch);\n searchIndex.since = newSince;\n }\n if (changes > 0) {\n console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1000).toFixed(1)}s (${searchIndex.size} notes).`);\n } else {\n console.log(`Search index up to date (${searchIndex.size} notes).`);\n }\n } else if (VAULT_PATH) {\n const notesWithMtime = await vault.listNotesWithMtime();\n if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);\n if (notesWithMtime.length > 0) {\n const vaultPaths = new Set(notesWithMtime.map((n) => n.path));\n for (const p of searchIndex.listPaths()) {\n if (!vaultPaths.has(p)) searchIndex.remove(p);\n }\n console.log(`Building search index (${notesWithMtime.length} notes)...`);\n for (let i = 0; i < notesWithMtime.length; i++) {\n const { path, mtime } = notesWithMtime[i];\n const content = await vault.readNote(path);\n // Index empty notes too (content === \"\"); readNote returns null only if absent.\n if (content !== null) searchIndex.update(path, content, mtime);\n if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {\n console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);\n }\n }\n console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1000).toFixed(1)}s`);\n }\n }\n await searchIndex.saveToDisk();\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => console.error(\"Index rebuild failed:\", err));\n\n// --- Watch for external changes ---\nlet fsWatcher: ReturnType<typeof watch> | null = null;\nif (VAULT_PATH) {\n // Local mode: watch filesystem for changes from Obsidian\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {\n if (!filename || !filename.endsWith(\".md\")) return;\n const notePath = filename.replace(/\\\\/g, \"/\");\n if (notePath.startsWith(\".obsidian/\") || notePath.includes(\"/.obsidian/\")) return;\n\n // Debounce: coalesce rapid events for the same file (Obsidian fires 2-3 per save)\n if (pending.has(notePath)) clearTimeout(pending.get(notePath)!);\n pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));\n });\n\n async function handleFileChange(notePath: string) {\n pending.delete(notePath);\n try {\n const content = await vault.readNote(notePath);\n if (content !== null) {\n const s = await stat(join(VAULT_PATH!, notePath));\n searchIndex.update(notePath, content, s.mtimeMs);\n } else {\n searchIndex.remove(notePath);\n }\n } catch {\n // File deleted or path blocked by safePath\n searchIndex.remove(notePath);\n }\n }\n console.log(\"Watching vault for external changes.\");\n} else if (COUCHDB_URL && vault.watchChanges) {\n // Remote mode: watch CouchDB _changes feed for LiveSync updates\n vault.watchChanges((path: string, content: string | null, mtime?: number, seq?: string | number) => {\n if (debugLogging) console.log(`[debug] CouchDB ${content === null ? \"delete\" : \"change\"}: ${path}`);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n if (seq) searchIndex.since = String(seq);\n });\n console.log(\"Watching CouchDB for LiveSync changes.\");\n}\n\n// --- MCP Server ---\nconst BASE_INSTRUCTIONS = \"Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.\";\nconst serverOptions: ConstructorParameters<typeof FastMCP>[0] = {\n name: \"obsidian-sync-mcp\",\n version: process.env.npm_package_version ?? \"0.0.0\",\n instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}\\n\\n${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS,\n};\n\n// Auth\nimport type { AuthHandle } from \"./auth.js\";\nlet auth: AuthHandle | null = null;\n\nif (AUTH_TOKEN) {\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n const header = req.headers[\"authorization\"];\n // Accept static Bearer token (for curl, MCP Inspector, custom agents)\n const expected = `Bearer ${AUTH_TOKEN}`;\n if (header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {\n return { authenticated: true };\n }\n // Accept OAuth-issued tokens (for Claude Web/Desktop/Mobile)\n if (auth?.validateToken(header)) {\n return { authenticated: true };\n }\n // RFC 9728: point strict clients (e.g. Gemini) at the resource\n // metadata; Claude probes /.well-known directly but others rely on this.\n throw new Response(\"Unauthorized\", {\n status: 401,\n headers: { \"WWW-Authenticate\": `Bearer resource_metadata=\"${BASE_URL}/.well-known/oauth-protected-resource\"` },\n });\n };\n console.log(\"Auth enabled (password-gated OAuth).\");\n} else {\n // No token: enforce a Host-header allowlist so the \"local only\" precondition\n // actually holds. Without this, DNS rebinding lets any website the operator\n // visits reach the tool surface (CWE-350) even on a loopback bind, because\n // the browser still sends the attacker's hostname in Host. Defaults to\n // localhost; MCP_ALLOWED_HOSTS extends it for legit LAN/private-network use.\n const allowedHosts = buildAllowedHosts(process.env.MCP_ALLOWED_HOSTS);\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n // Host check defeats DNS rebinding; Origin check defeats a direct\n // cross-origin browser fetch to loopback (the transport sends wildcard CORS).\n if (!isHostAllowed(req.headers[\"host\"], allowedHosts)) {\n throw new Response(\"Forbidden: Host not allowed\", { status: 403 });\n }\n if (!isOriginAllowed(req.headers[\"origin\"], allowedHosts)) {\n throw new Response(\"Forbidden: cross-origin request rejected\", { status: 403 });\n }\n return { authenticated: true };\n };\n console.log(`Auth disabled — accepting only local Host/Origin headers: ${[...allowedHosts].join(\", \")}. Set MCP_ALLOWED_HOSTS to add hosts, or MCP_AUTH_TOKEN for authenticated remote access.`);\n const host = process.env.HOST ?? \"0.0.0.0\";\n if (host === \"0.0.0.0\") {\n console.warn(\"WARNING: No authentication and listening on all interfaces. Browser attacks (DNS rebinding and cross-origin fetch) are blocked by the Host/Origin checks, but any non-browser client that can reach this port has full vault access. Set MCP_AUTH_TOKEN, or HOST=127.0.0.1 to bind to loopback only.\");\n }\n}\n\nconst server = new FastMCP(serverOptions);\n\nif (AUTH_TOKEN) {\n const tokenPath = join(dataDir, \"auth-tokens.json\");\n auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);\n await auth.loadTokens();\n}\n\n// --- Tools ---\nregisterTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);\n\n// --- Graceful shutdown ---\nasync function shutdown() {\n console.log(\"Shutting down...\");\n if (fsWatcher) fsWatcher.close();\n await searchIndex.saveToDisk();\n if (auth) await auth.saveTokens();\n await vault.close();\n process.exit(0);\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n\n// --- Periodic save (every 5 minutes) ---\nsetInterval(async () => {\n await searchIndex.saveToDisk();\n if (auth) {\n auth.cleanup();\n await auth.saveTokens();\n }\n}, 5 * 60 * 1000).unref();\n\n// --- Start server ---\nserver.start({\n transportType: \"httpStream\",\n httpStream: { port: PORT, endpoint: \"/mcp\", host: process.env.HOST ?? \"0.0.0.0\" },\n});\nconsole.log(`obsidian-sync-mcp v${process.env.npm_package_version ?? \"unknown\"} listening on port ${PORT}`);\n\n// Prevent unhandled rejections from crashing the server (e.g. decryption failures in watcher)\nprocess.on(\"unhandledRejection\", (err) => {\n console.error(\"Unhandled rejection:\", err);\n});\n","/**\n * Password-gated OAuth provider for MCP.\n *\n * Implements a self-contained OAuth 2.1 flow:\n * - Claude connects -> gets 401 with metadata pointer\n * - Claude discovers /.well-known/oauth-protected-resource\n * - Claude registers via /oauth/register (DCR)\n * - Claude redirects user to /oauth/authorize\n * - User sees a password page, enters MCP_AUTH_TOKEN\n * - Claude exchanges code for access token via /oauth/token\n * - All subsequent requests carry Bearer token\n *\n * No external identity provider needed.\n */\n\nimport { randomUUID, randomBytes, createHash, timingSafeEqual } from \"crypto\";\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type { Hono } from \"hono\";\n\ninterface PendingAuth {\n clientId: string;\n redirectUri: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n state: string;\n code: string;\n createdAt: number;\n}\n\ninterface TokenRecord {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n expiresAt: number;\n refreshExpiresAt: number;\n}\n\ninterface RegisteredClient {\n clientId: string;\n clientSecret?: string;\n tokenEndpointAuthMethod: \"client_secret_post\" | \"none\";\n redirectUris: string[];\n clientName?: string;\n createdAt?: number;\n}\n\nconst TOKEN_EXPIRY_MS = 3600 * 1000; // 1 hour\nconst DEFAULT_REFRESH_DAYS = 14;\nconst REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1000;\nconst MAX_FAILED_BEFORE_LOCKOUT = 5;\nconst BASE_LOCKOUT_MS = 5 * 1000; // 5 seconds, doubles each lockout\nconst MAX_CLIENTS = 100;\nconst MAX_PENDING = 100;\nconst PENDING_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface AuthHandle {\n validateToken: (auth: string | undefined) => boolean;\n saveTokens: () => Promise<void>;\n loadTokens: () => Promise<boolean>;\n cleanup: () => void;\n}\n\nexport function mountPasswordAuth(app: Hono, baseUrl: string, password: string, persistPath?: string): AuthHandle {\n const pendingAuths = new Map<string, PendingAuth>();\n const csrfTokens = new Map<string, string>(); // code -> csrf token\n const tokens = new Map<string, TokenRecord>();\n const refreshTokens = new Map<string, TokenRecord>();\n const clients = new Map<string, RegisteredClient>();\n\n // Cleanup expired pending auths and CSRF tokens\n function cleanupPending() {\n const now = Date.now();\n for (const [code, pending] of pendingAuths) {\n if (now - pending.createdAt > PENDING_TTL_MS) {\n pendingAuths.delete(code);\n csrfTokens.delete(code);\n }\n }\n }\n\n // Rate limiting: exponential backoff, never resets until success\n let failedAttempts = 0;\n let lockoutCount = 0;\n let lockedUntil = 0;\n\n // Persist clients + tokens. Called on every state change (not just the\n // periodic save): a restart or Fly suspend right after registration or\n // token issuance must not lose the new state.\n async function persist(): Promise<void> {\n if (!persistPath) return;\n try {\n await mkdir(dirname(persistPath), { recursive: true });\n const now = Date.now();\n const activeTokens = [...tokens.entries()].filter(([, r]) => r.expiresAt > now);\n const activeRefresh = [...refreshTokens.entries()].filter(([, r]) => r.refreshExpiresAt > now);\n const data = JSON.stringify({\n tokens: Object.fromEntries(activeTokens),\n refreshTokens: Object.fromEntries(activeRefresh),\n clients: Object.fromEntries(clients),\n });\n await writeFile(persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(persistPath, 0o600);\n } catch (err) {\n console.error(\"Failed to save auth tokens:\", err);\n }\n }\n\n // HTTPS warning\n if (!baseUrl.startsWith(\"https://\") && !baseUrl.includes(\"localhost\")) {\n console.warn(\"WARNING: BASE_URL is not HTTPS. OAuth tokens will be sent in cleartext. Use a tunnel (cloudflared, tailscale, ngrok) to provide TLS.\");\n }\n\n // --- Discovery endpoints ---\n\n app.get(\"/.well-known/oauth-protected-resource\", (c) => {\n return c.json({\n resource: baseUrl,\n authorization_servers: [baseUrl],\n scopes_supported: [\"mcp\"],\n });\n });\n\n app.get(\"/.well-known/oauth-authorization-server\", (c) => {\n return c.json({\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/oauth/authorize`,\n token_endpoint: `${baseUrl}/oauth/token`,\n registration_endpoint: `${baseUrl}/oauth/register`,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"client_secret_post\", \"none\"],\n scopes_supported: [\"mcp\"],\n });\n });\n\n // --- Dynamic Client Registration (RFC 7591) ---\n\n app.post(\"/oauth/register\", async (c) => {\n if (clients.size >= MAX_CLIENTS) {\n // Evict the oldest client with no live tokens to make room; only\n // reject when every slot is held by a client with active tokens.\n const activeClientIds = new Set<string>();\n for (const r of tokens.values()) activeClientIds.add(r.clientId);\n for (const r of refreshTokens.values()) activeClientIds.add(r.clientId);\n let oldest: RegisteredClient | undefined;\n for (const client of clients.values()) {\n if (activeClientIds.has(client.clientId)) continue;\n if (!oldest || (client.createdAt ?? 0) < (oldest.createdAt ?? 0)) oldest = client;\n }\n if (!oldest) {\n return c.json({ error: \"too_many_clients\" }, 429);\n }\n clients.delete(oldest.clientId);\n }\n const body = await c.req.json();\n\n // Validate redirect_uris\n const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.slice(0, 5) : [];\n if (redirectUris.length === 0) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"redirect_uris required\" }, 400);\n }\n const safeUri = (u: any) => {\n if (typeof u !== \"string\" || u.length > 2048) return false;\n const lower = u.toLowerCase();\n return !lower.startsWith(\"javascript:\") && !lower.startsWith(\"data:\") && !lower.startsWith(\"file:\");\n };\n if (redirectUris.some((u: any) => !safeUri(u))) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"invalid redirect_uri\" }, 400);\n }\n\n const clientId = randomUUID();\n // Honor the client's requested auth method (RFC 7591 §2). Only\n // \"client_secret_post\" and \"none\" are advertised as supported, so\n // anything else falls back to the confidential-client default rather\n // than silently registering a method we don't understand.\n const tokenEndpointAuthMethod: \"client_secret_post\" | \"none\" =\n body.token_endpoint_auth_method === \"none\" ? \"none\" : \"client_secret_post\";\n const clientSecret = tokenEndpointAuthMethod === \"none\" ? undefined : randomBytes(32).toString(\"hex\");\n const clientName = typeof body.client_name === \"string\" ? body.client_name.slice(0, 256) : undefined;\n\n const client: RegisteredClient = {\n clientId,\n clientSecret,\n tokenEndpointAuthMethod,\n redirectUris,\n clientName,\n createdAt: Date.now(),\n };\n clients.set(clientId, client);\n await persist();\n\n console.log(\n `Auth: registered client_id=${clientId} redirect_uris=${JSON.stringify(redirectUris)} ` +\n `requested_auth_method=${JSON.stringify(body.token_endpoint_auth_method ?? \"(unspecified)\")} (responding with ${tokenEndpointAuthMethod})`\n );\n\n return c.json({\n client_id: clientId,\n ...(clientSecret ? { client_secret: clientSecret } : {}),\n redirect_uris: client.redirectUris,\n client_name: client.clientName,\n token_endpoint_auth_method: tokenEndpointAuthMethod,\n }, 201);\n });\n\n // --- Authorization endpoint ---\n\n app.get(\"/oauth/authorize\", (c) => {\n const clientId = c.req.query(\"client_id\") ?? \"\";\n const redirectUri = c.req.query(\"redirect_uri\") ?? \"\";\n const codeChallenge = c.req.query(\"code_challenge\") ?? \"\";\n const codeChallengeMethod = c.req.query(\"code_challenge_method\") ?? \"S256\";\n const state = c.req.query(\"state\") ?? \"\";\n\n // Validate redirect URI against registered client\n const client = clients.get(clientId);\n if (!client) {\n console.warn(`Auth: /oauth/authorize unknown client_id=${JSON.stringify(clientId)}`);\n return c.text(\"Unknown client\", 400);\n }\n if (!client.redirectUris.includes(redirectUri)) {\n console.warn(\n `Auth: /oauth/authorize redirect_uri mismatch. received=${JSON.stringify(redirectUri)} ` +\n `registered=${JSON.stringify(client.redirectUris)}`\n );\n return c.text(\"Invalid redirect URI\", 400);\n }\n\n // Require S256 PKCE\n if (codeChallengeMethod !== \"S256\" || !codeChallenge) {\n console.warn(`Auth: /oauth/authorize missing/unsupported PKCE. method=${JSON.stringify(codeChallengeMethod)} challenge_present=${!!codeChallenge}`);\n return c.text(\"PKCE with S256 is required\", 400);\n }\n\n cleanupPending();\n if (pendingAuths.size >= MAX_PENDING) {\n return c.text(\"Too many pending authorizations\", 429);\n }\n\n const code = randomBytes(32).toString(\"hex\");\n pendingAuths.set(code, {\n clientId,\n redirectUri,\n codeChallenge,\n codeChallengeMethod,\n state,\n code,\n createdAt: Date.now(),\n });\n\n console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);\n\n const csrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, csrf);\n return c.html(renderPasswordPage(code, csrf));\n });\n\n // --- Approval handler ---\n\n app.post(\"/oauth/approve\", async (c) => {\n const body = await c.req.parseBody();\n const code = body[\"code\"] as string;\n const submittedCsrf = body[\"csrf\"] as string;\n const submittedPassword = body[\"password\"] as string;\n\n const pending = pendingAuths.get(code);\n const expectedCsrf = csrfTokens.get(code);\n if (!pending || !expectedCsrf) {\n return c.html(\"<p>Invalid or expired authorization request.</p>\", 400);\n }\n\n // Validate CSRF token\n const csrfA = Buffer.from(submittedCsrf ?? \"\");\n const csrfB = Buffer.from(expectedCsrf);\n if (csrfA.length !== csrfB.length || !timingSafeEqual(csrfA, csrfB)) {\n return c.html(\"<p>Invalid request.</p>\", 403);\n }\n\n // Rate limiting: check lockout\n if (Date.now() < lockedUntil) {\n const waitSec = Math.ceil((lockedUntil - Date.now()) / 1000);\n console.warn(`Auth: locked out, ${waitSec}s remaining`);\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);\n }\n\n const a = Buffer.from(submittedPassword);\n const b = Buffer.from(password);\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n failedAttempts++;\n console.warn(`Auth: failed attempt ${failedAttempts} total`);\n\n // Rotate CSRF token on each failed attempt\n const newCsrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, newCsrf);\n\n if (failedAttempts >= MAX_FAILED_BEFORE_LOCKOUT) {\n lockoutCount = Math.min(lockoutCount + 1, 10);\n const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);\n lockedUntil = Date.now() + lockoutMs;\n console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1000}s`);\n return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1000)} seconds.`), 429);\n }\n\n return c.html(renderPasswordPage(code, newCsrf, \"Wrong password.\"), 401);\n }\n\n // Password correct — reset everything\n failedAttempts = 0;\n lockoutCount = 0;\n lockedUntil = 0;\n csrfTokens.delete(code);\n console.log(\"Auth: password accepted, issuing authorization code.\");\n\n const url = new URL(pending.redirectUri);\n url.searchParams.set(\"code\", code);\n if (pending.state) url.searchParams.set(\"state\", pending.state);\n const redirectUrl = url.toString();\n\n return c.redirect(redirectUrl);\n });\n\n // --- Token endpoint ---\n\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.parseBody();\n const grantType = body[\"grant_type\"] as string;\n console.log(`Auth: /oauth/token request grant_type=${JSON.stringify(grantType)}`);\n\n if (grantType === \"authorization_code\") {\n const code = body[\"code\"] as string;\n const clientId = body[\"client_id\"] as string;\n const codeVerifier = body[\"code_verifier\"] as string;\n const redirectUri = body[\"redirect_uri\"] as string;\n\n const pending = pendingAuths.get(code);\n if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {\n console.warn(\n `Auth: /oauth/token invalid_grant. code_known=${!!pending} ` +\n `expired=${pending ? Date.now() - pending.createdAt > PENDING_TTL_MS : \"n/a\"}`\n );\n if (pending) pendingAuths.delete(code);\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Verify client_id matches the original request\n if (clientId !== pending.clientId) {\n console.warn(\n `Auth: /oauth/token client_id mismatch. received=${JSON.stringify(clientId)} expected=${JSON.stringify(pending.clientId)}`\n );\n return c.json({ error: \"invalid_grant\", error_description: \"client_id mismatch\" }, 400);\n }\n\n // Verify redirect_uri matches the original request\n if (redirectUri !== pending.redirectUri) {\n console.warn(\n `Auth: /oauth/token redirect_uri mismatch. received=${JSON.stringify(redirectUri)} expected=${JSON.stringify(pending.redirectUri)}`\n );\n return c.json({ error: \"invalid_grant\", error_description: \"redirect_uri mismatch\" }, 400);\n }\n\n // Verify PKCE\n if (pending.codeChallengeMethod === \"S256\") {\n const expected = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n console.warn(\"Auth: /oauth/token PKCE verification failed\");\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed\" }, 400);\n }\n }\n\n pendingAuths.delete(code);\n console.log(`Auth: /oauth/token issuing access token client_id=${pending.clientId}`);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const refreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken,\n clientId: pending.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS,\n };\n tokens.set(accessToken, record);\n refreshTokens.set(refreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: refreshToken,\n });\n }\n\n if (grantType === \"refresh_token\") {\n const refreshToken = body[\"refresh_token\"] as string;\n const old = refreshTokens.get(refreshToken);\n if (!old) {\n console.warn(\"Auth: /oauth/token refresh_token unknown\");\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Check refresh token expiry\n if (Date.now() > old.refreshExpiresAt) {\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n console.log(\"Auth: refresh token expired, user must re-authenticate.\");\n return c.json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" }, 400);\n }\n\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const newRefreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken: newRefreshToken,\n clientId: old.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: old.refreshExpiresAt, // keep original expiry\n };\n tokens.set(accessToken, record);\n refreshTokens.set(newRefreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: newRefreshToken,\n });\n }\n\n console.warn(`Auth: /oauth/token unsupported_grant_type=${JSON.stringify(grantType)}`);\n return c.json({ error: \"unsupported_grant_type\" }, 400);\n });\n\n return {\n validateToken(authHeader: string | undefined): boolean {\n if (!authHeader?.startsWith(\"Bearer \")) return false;\n const token = authHeader.slice(7);\n const record = tokens.get(token);\n if (!record) return false;\n if (Date.now() > record.expiresAt) {\n tokens.delete(token);\n return false;\n }\n return true;\n },\n\n async saveTokens(): Promise<void> {\n await persist();\n },\n\n cleanup(): void {\n const now = Date.now();\n for (const [k, r] of tokens) { if (r.expiresAt <= now) tokens.delete(k); }\n for (const [k, r] of refreshTokens) { if (r.refreshExpiresAt <= now) refreshTokens.delete(k); }\n // Registered clients are NOT evicted here: AI clients cache their\n // client_id indefinitely and retry it after token expiry, so\n // dropping a registration means \"Unknown client\" until the user\n // deletes and re-adds the connector (issue #13). The clients map\n // is bounded at registration time instead.\n },\n\n async loadTokens(): Promise<boolean> {\n if (!persistPath) return false;\n try {\n const raw = await readFile(persistPath, \"utf-8\");\n const data = JSON.parse(raw);\n const now = Date.now();\n for (const [k, v] of Object.entries(data.tokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.clients ?? {})) {\n const client = v as RegisteredClient;\n if (client.clientId && client.redirectUris) clients.set(k, client);\n }\n console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);\n return tokens.size > 0;\n } catch {\n return false;\n }\n },\n };\n}\n\nfunction renderPasswordPage(code: string, csrf: string, error?: string): string {\n return `<!DOCTYPE html>\n<html><head><title>Obsidian Sync MCP - Authorize</title>\n<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'\">\n<style>\n body { font-family: system-ui; max-width: 400px; margin: 80px auto; padding: 0 20px; }\n h1 { font-size: 1.3em; }\n input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }\n button { padding: 10px 20px; font-size: 1em; cursor: pointer; }\n .error { color: red; }\n</style></head>\n<body>\n <h1>Obsidian Sync MCP</h1>\n ${error ? `<p class=\"error\">${error.replace(/&/g, \"&\").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","/**\n * Host-header allowlisting to defeat DNS-rebinding attacks (CWE-350).\n *\n * When the server runs without MCP_AUTH_TOKEN (\"local only\" mode), a malicious\n * web page the operator visits can use DNS rebinding to point its hostname at\n * 127.0.0.1 and reach the MCP endpoint from the browser. Binding to loopback\n * does NOT help — the OS resolves the attacker hostname to loopback while the\n * page keeps its origin. The browser still sends the attacker's hostname in the\n * `Host` header, so validating Host against a localhost allowlist rejects the\n * rebound request. A bearer token (auth mode) already defeats this, since a\n * browser won't attach it; this guard protects the no-token path.\n *\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nconst LOCAL_HOSTS = [\"localhost\", \"127.0.0.1\", \"::1\"];\n\n/** Extract a normalized, lowercased hostname from a raw `Host` header (strips port and IPv6 brackets). */\nexport function parseHostname(hostHeader: string | undefined | null): string | null {\n if (!hostHeader) return null;\n // A real Host header is a bare host[:port]. Reject anything carrying userinfo\n // or a path (e.g. \"attacker.example@127.0.0.1\", \"127.0.0.1/x\") so a crafted\n // value can't normalize into the allowlist.\n if (hostHeader.includes(\"@\") || hostHeader.includes(\"/\")) return null;\n try {\n // Wrapping in a URL parses `host:port` and `[ipv6]:port` correctly.\n const u = new URL(`http://${hostHeader}`);\n if (u.username || u.password || u.pathname !== \"/\" || u.search || u.hash) return null;\n return u.hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** Build the set of allowed hostnames: always localhost, plus any from a comma-separated list. */\nexport function buildAllowedHosts(extra?: string): Set<string> {\n const set = new Set(LOCAL_HOSTS);\n for (const entry of (extra ?? \"\").split(\",\").map((s) => s.trim()).filter(Boolean)) {\n set.add(parseHostname(entry) ?? entry.toLowerCase());\n }\n return set;\n}\n\n/** True if the request's Host header resolves to an allowed hostname. Missing/malformed Host is rejected. */\nexport function isHostAllowed(hostHeader: string | undefined | null, allowed: Set<string>): boolean {\n const hostname = parseHostname(hostHeader);\n return hostname !== null && allowed.has(hostname);\n}\n\n/**\n * True if the request has no browser `Origin`, or its Origin host is allowlisted.\n *\n * Host validation alone is not enough: the transport answers with a wildcard\n * `Access-Control-Allow-Origin: *`, so a page at any origin can skip DNS\n * rebinding and directly `fetch('http://127.0.0.1:<port>/mcp')` — that request\n * carries a genuine loopback Host (passes isHostAllowed) but an attacker Origin.\n * Non-browser MCP clients (CLI, desktop apps) send no Origin, so requiring\n * \"no Origin, or an allowlisted Origin\" blocks cross-origin browsers without\n * affecting legitimate local callers.\n */\nexport function isOriginAllowed(originHeader: string | undefined | null, allowed: Set<string>): boolean {\n if (!originHeader) return true; // non-browser client — no Origin header\n try {\n const hostname = new URL(originHeader).hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n return allowed.has(hostname);\n } catch {\n return false; // \"null\"/opaque or malformed Origin — reject\n }\n}\n","import type { FastMCP } from \"fastmcp\";\nimport { z } from \"zod\";\nimport { makeDeepLink } from \"./deeplink.js\";\nimport type { VaultBackend } from \"./vault-backend.js\";\nimport type { SearchIndex } from \"./search.js\";\nimport { isPathWritable } from \"./write-scope.js\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\nexport function registerTools(\n server: FastMCP,\n vault: VaultBackend,\n searchIndex: SearchIndex,\n vaultName: string,\n readOnly = false,\n writeFolders: string[] | null = null,\n) {\n if (readOnly) {\n console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(\", \")}).`);\n } else if (writeFolders) {\n console.log(`WRITE_FOLDERS: writes restricted to ${writeFolders.map((f) => f + \"/\").join(\", \")}.`);\n }\n const writeScopeNote = writeFolders\n ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + \"/\").join(\", \")}.`\n : \"\";\n const denyWrite = (path: string) =>\n `Write access denied: '${path}' is outside the writable folders (${writeFolders!.map((f) => f + \"/\").join(\", \")}).`;\n const _addTool = server.addTool.bind(server);\n server.addTool = (tool: any) => {\n const original = tool.execute;\n tool.execute = async (args: any, ctx: any) => {\n if (debugLogging) console.log(`[tool] ${tool.name}(${JSON.stringify(args)})`);\n const start = performance.now();\n const result = await original(args, ctx);\n if (debugLogging) console.log(`[tool] ${tool.name} → ${((performance.now() - start)).toFixed(0)}ms`);\n return result;\n };\n return _addTool(tool);\n };\n server.addTool({\n name: \"read_note\",\n description:\n \"Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n }),\n execute: async ({ path }) => {\n const content = await vault.readNote(path);\n if (content === null) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n return `[Open in Obsidian](${deepLink})\\n\\n---\\n\\n${content}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"write_note\",\n description:\n \"Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does — read first if you need to preserve existing content.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n content: z.string().describe(\"Full markdown content for the note\"),\n }),\n execute: async ({ path, content }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.writeNote(path, content);\n if (!ok) {\n return `Failed to write note: ${path}`;\n }\n searchIndex.update(path, content, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note saved: ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"list_notes\",\n description: \"List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(name='meeting') to find notes by name. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.\",\n parameters: z.object({\n folder: z\n .string()\n .optional()\n .describe(\"Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes.\"),\n name: z\n .string()\n .optional()\n .describe(\"Filter by name (case-insensitive substring match on path), e.g. 'meeting' or 'project-x'.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags.\"),\n sort_by: z\n .enum([\"name\", \"modified\"])\n .optional()\n .describe(\"Sort order: 'name' (default) or 'modified' (most recent first).\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'.\"),\n limit: z.coerce\n .number()\n .optional()\n .describe(\"Max number of notes to return. Default 100.\"),\n }),\n execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {\n // Use search index (works with encrypted vaults), fall back to vault\n let notes = searchIndex.listWithMtime(folder);\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n }\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n }\n if (modified_after) {\n const cutoff = new Date(modified_after).getTime();\n if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n notes = notes.filter((n) => n.mtime >= cutoff);\n }\n if (notes.length === 0) {\n return folder ? `No notes found in folder: ${folder}` : \"Vault is empty.\";\n }\n if (sort_by === \"modified\") {\n notes.sort((a, b) => b.mtime - a.mtime);\n }\n const cap = limit ?? 100;\n const total = notes.length;\n const capped = notes.slice(0, cap);\n const lines = capped.map((n) => {\n const deepLink = makeDeepLink(vaultName, n.path);\n const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : \"\";\n return `- ${date} [${n.path}](${deepLink})`;\n });\n if (total > cap) {\n lines.push(`\\n... and ${total - cap} more. Use a folder filter or limit to narrow results.`);\n }\n return lines.join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_folders\",\n description:\n \"List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.\",\n parameters: z.object({}),\n execute: async () => {\n let paths = searchIndex.listPaths();\n if (paths.length === 0) {\n paths = await vault.listNotes();\n }\n const folders = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n folders.set(\"(root)\", (folders.get(\"(root)\") ?? 0) + 1);\n } else {\n const folder = p.slice(0, lastSlash);\n folders.set(folder, (folders.get(folder) ?? 0) + 1);\n // Ensure all parent folders appear in the list\n let parent = folder;\n while (parent.includes(\"/\")) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n if (!folders.has(parent)) folders.set(parent, 0);\n }\n }\n }\n if (folders.size === 0) {\n return \"Vault is empty.\";\n }\n const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));\n return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_tags\",\n description:\n \"List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes.\",\n parameters: z.object({}),\n execute: async () => {\n const tags = searchIndex.listAllTags();\n if (tags.length === 0) {\n return \"No tags found in the vault.\";\n }\n return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join(\"\\n\");\n },\n });\n\n\n\n if (!readOnly) server.addTool({\n name: \"edit_note\",\n description:\n \"Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-25.md'\"),\n content: z.string().describe(\"Text to append, prepend, or use as replacement for old_text\"),\n operation: z\n .enum([\"append\", \"prepend\", \"replace\"])\n .optional()\n .describe(\"'append' (default): add to end. 'prepend': add after frontmatter. 'replace': swap old_text with content.\"),\n old_text: z\n .string()\n .optional()\n .describe(\"Required for replace operation. Exact text to find and replace. Must match exactly once.\"),\n }),\n execute: async ({ path, content: newContent, operation, old_text }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const existing = await vault.readNote(path);\n if (existing === null) {\n return `Note not found: ${path}`;\n }\n\n let updated: string;\n const op = operation ?? \"append\";\n\n if (op === \"replace\") {\n if (!old_text) {\n return \"old_text is required for replace operation.\";\n }\n const idx = existing.indexOf(old_text);\n if (idx === -1) {\n return \"old_text not found in note.\";\n }\n if (existing.indexOf(old_text, idx + 1) !== -1) {\n return \"old_text matches multiple times. Provide a longer, unique string.\";\n }\n updated = existing.slice(0, idx) + newContent + existing.slice(idx + old_text.length);\n } else if (op === \"prepend\") {\n // Insert after frontmatter if present\n const fmMatch = existing.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n/);\n if (fmMatch) {\n const afterFm = fmMatch[0].length;\n updated = existing.slice(0, afterFm) + newContent + \"\\n\" + existing.slice(afterFm);\n } else {\n updated = newContent + \"\\n\" + existing;\n }\n } else {\n // append\n updated = existing.endsWith(\"\\n\") ? existing + newContent : existing + \"\\n\" + newContent;\n }\n\n const ok = await vault.writeNote(path, updated);\n if (!ok) {\n return `Failed to edit note: ${path}`;\n }\n searchIndex.update(path, updated, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note edited (${op}): ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"delete_note\",\n description: \"Delete a note from the Obsidian vault.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note to delete\"),\n }),\n execute: async ({ path }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.deleteNote(path);\n if (ok) searchIndex.remove(path);\n return ok ? `Deleted: ${path}` : `Failed to delete: ${path}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"move_note\",\n description:\n \"Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically.\" + writeScopeNote,\n parameters: z.object({\n from: z.string().describe(\"Current path, e.g. 'daily/old-name.md'\"),\n to: z.string().describe(\"New path, e.g. 'projects/new-name.md'\"),\n }),\n execute: async ({ from, to }) => {\n // Moving out of a folder deletes there; moving in writes there — both ends must be writable.\n if (!isPathWritable(from, writeFolders)) return denyWrite(from);\n if (!isPathWritable(to, writeFolders)) return denyWrite(to);\n const content = await vault.readNote(from);\n const ok = await vault.moveNote(from, to);\n if (!ok) {\n return `Failed to move: ${from} → ${to}`;\n }\n searchIndex.remove(from);\n // content === \"\" is an empty-but-present note: keep it indexed at the new path.\n if (content !== null) searchIndex.update(to, content, Date.now());\n const deepLink = makeDeepLink(vaultName, to);\n return `Moved: ${from} → ${to}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"get_note_metadata\",\n description:\n \"Get metadata about a note without reading its full content. Returns frontmatter, tags, outgoing links, backlinks (notes that link to this one), size, and timestamps. Use this to navigate the knowledge graph.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'projects/my-project.md'\"),\n }),\n execute: async ({ path }) => {\n const meta = await vault.getMetadata(path);\n if (!meta) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n const lines = [\n `**${path}**`,\n `Size: ${meta.size} bytes`,\n `Created: ${new Date(meta.ctime).toISOString()}`,\n `Modified: ${new Date(meta.mtime).toISOString()}`,\n ];\n if (Object.keys(meta.frontmatter).length > 0) {\n lines.push(`\\nFrontmatter:`);\n for (const [k, v] of Object.entries(meta.frontmatter)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n if (meta.tags.length > 0) {\n lines.push(`\\nTags: ${meta.tags.map((t) => `#${t}`).join(\", \")}`);\n }\n if (meta.links.length > 0) {\n lines.push(`\\nOutgoing links: ${meta.links.join(\", \")}`);\n }\n const backlinks = searchIndex.getBacklinks(path);\n if (backlinks.length > 0) {\n lines.push(`\\nBacklinks: ${backlinks.join(\", \")}`);\n }\n lines.push(`\\n[Open in Obsidian](${deepLink})`);\n return lines.join(\"\\n\");\n },\n });\n}\n","/**\n * Generate Obsidian deep links for notes.\n * Works on Mac and iOS: obsidian://open?vault=<name>&file=<path>\n */\nexport function makeDeepLink(vaultName: string, notePath: string): string {\n const cleanPath = notePath.replace(/\\.md$/, \"\");\n const encodedVault = encodeURIComponent(vaultName);\n const encodedPath = encodeURIComponent(cleanPath);\n return `obsidian://open?vault=${encodedVault}&file=${encodedPath}`;\n}\n","// Folder-scoped write access (WRITE_FOLDERS env var).\n// When set, write tools only accept paths inside the listed vault-relative folders.\n\n/** Parse the WRITE_FOLDERS env var into a normalized folder list, or null for unrestricted. */\nexport function parseWriteFolders(raw: string | undefined): string[] | null {\n if (raw === undefined) return null;\n const folders = raw\n .split(\",\")\n .map((f) => f.trim().replace(/^\\/+|\\/+$/g, \"\"))\n .filter(Boolean);\n return folders.length > 0 ? folders : null;\n}\n\n/**\n * Check whether a vault-relative path falls inside one of the writable folders.\n * Matching is case-sensitive and folder-boundary-aware (\"MCP\" matches \"MCP/x.md\",\n * not \"MCP-private/x.md\"). A null folder list means writes are unrestricted.\n */\nexport function isPathWritable(path: string, writeFolders: string[] | null): boolean {\n if (writeFolders === null) return true;\n const normalized = path.replace(/^\\/+/, \"\");\n // Backends reject traversal too; deny here so the scope check can't be reasoned around.\n // Split on backslash as well: on Windows \"MCP/..\\x\" resolves as traversal.\n if (normalized.split(/[/\\\\]/).includes(\"..\")) return false;\n return writeFolders.some((folder) => normalized.startsWith(folder + \"/\"));\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,mBAAAA,kBAAiB,cAAAC,mBAAkB;AAC5C,SAAS,OAAO,cAAc,gBAAgB;AAC9C,SAAS,YAAY;AACrB,SAAS,sBAAsB,kBAAkB;;;ACUjD,SAAS,YAAY,aAAa,YAAY,uBAAuB;AACrE,SAAS,U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AAI,CAAC,0FAA0F;AAC/L,QAAM,OAAO,QAAQ,IAAI,QAAQ;AACjC,MAAI,SAAS,WAAW;AACpB,YAAQ,KAAK,sSAAsS;AAAA,EACvT;AACJ;AAEA,IAAM,SAAS,IAAI,QAAQ,aAAa;AAExC,IAAI,YAAY;AACZ,QAAM,YAAY,KAAK,SAAS,kBAAkB;AAClD,SAAO,kBAAkB,OAAO,OAAO,GAAG,UAAU,YAAY,SAAS;AACzE,QAAM,KAAK,WAAW;AAC1B;AAGA,cAAc,QAAQ,OAAO,aAAa,YAAY,WAAW,aAAa;AAG9E,eAAe,WAAW;AACtB,UAAQ,IAAI,kBAAkB;AAC9B,MAAI,UAAW,WAAU,MAAM;AAC/B,QAAM,YAAY,WAAW;AAC7B,MAAI,KAAM,OAAM,KAAK,WAAW;AAChC,QAAM,MAAM,MAAM;AAClB,UAAQ,KAAK,CAAC;AAClB;AACA,QAAQ,GAAG,WAAW,QAAQ;AAC9B,QAAQ,GAAG,UAAU,QAAQ;AAG7B,YAAY,YAAY;AACpB,QAAM,YAAY,WAAW;AAC7B,MAAI,MAAM;AACN,SAAK,QAAQ;AACb,UAAM,KAAK,WAAW;AAAA,EAC1B;AACJ,GAAG,IAAI,KAAK,GAAI,EAAE,MAAM;AAGxB,OAAO,MAAM;AAAA,EACT,eAAe;AAAA,EACf,YAAY,EAAE,MAAM,MAAM,UAAU,QAAQ,MAAM,QAAQ,IAAI,QAAQ,UAAU;AACpF,CAAC;AACD,QAAQ,IAAI,sBAAsB,OAA4C,sBAAsB,IAAI,EAAE;AAG1G,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACtC,UAAQ,MAAM,wBAAwB,GAAG;AAC7C,CAAC;","names":["timingSafeEqual","createHash","client","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","server","vault","searchIndex","debugLogging","createHash","timingSafeEqual"]}
|
|
1
|
+
{"version":3,"sources":["../src/main.ts","../src/auth.ts","../src/search.ts","../src/host-guard.ts","../src/tools.ts","../src/deeplink.ts","../src/write-scope.ts","../src/list-format.ts"],"sourcesContent":["import { FastMCP } from \"fastmcp\";\nimport { join } from \"path\";\nimport { timingSafeEqual, createHash } from \"crypto\";\nimport { watch, readFileSync, statSync } from \"fs\";\nimport { stat } from \"fs/promises\";\nimport { setGlobalLogFunction, LEVEL_INFO } from \"octagonal-wheels/common/logger\";\nimport { mountPasswordAuth } from \"./auth.js\";\nimport { SearchIndex } from \"./search.js\";\nimport { applyIndexChange } from \"./index-sync.js\";\nimport { buildAllowedHosts, isHostAllowed, isOriginAllowed } from \"./host-guard.js\";\nimport { registerTools } from \"./tools.js\";\nimport { parseWriteFolders } from \"./write-scope.js\";\n\n// Suppress livesync-commonlib logs that expose vault file paths in production.\n// Set LOG_LEVEL=debug to see all library logs during development.\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\nsetGlobalLogFunction((message, level = LEVEL_INFO) => {\n if (level < LEVEL_INFO) return;\n if (!debugLogging && typeof message === \"string\") {\n if (/^(GET|PUT|DELETE|WATCH|FOLLOW|Sensible merge|Object merge):/.test(message)) return;\n if (message.includes(\"replicator\") || message.includes(\"Replicator\") || message.includes(\"ReplicatorService\")) return;\n }\n console.log(message);\n});\n\n// --- Configuration from environment ---\nconst VAULT_PATH = process.env.VAULT_PATH; // Local mode: path to vault directory\nconst COUCHDB_URL = process.env.COUCHDB_URL;\nconst COUCHDB_USER = process.env.COUCHDB_USER ?? \"admin\";\nconst COUCHDB_PASSWORD = process.env.COUCHDB_PASSWORD;\nconst COUCHDB_DATABASE = process.env.COUCHDB_DATABASE ?? \"obsidian\";\nconst COUCHDB_PASSPHRASE = process.env.COUCHDB_PASSPHRASE || undefined;\nconst COUCHDB_OBFUSCATE_PROPERTIES = process.env.COUCHDB_OBFUSCATE_PROPERTIES === \"true\";\nconst VAULT_NAME = process.env.VAULT_NAME ?? \"MyVault\";\nconst PORT = parseInt(process.env.PORT ?? \"8787\");\nconst BASE_URL = process.env.BASE_URL ?? `http://localhost:${PORT}`;\nconst AUTH_TOKEN = process.env.MCP_AUTH_TOKEN;\nconst READ_ONLY = process.env.READ_ONLY === \"true\";\nconst WRITE_FOLDERS = parseWriteFolders(process.env.WRITE_FOLDERS);\n\n// Extra instructions appended to the MCP `instructions` string.\n// File wins if both are set (loud warning); missing file is fatal.\nconst MCP_INSTRUCTIONS_FILE = process.env.MCP_INSTRUCTIONS_FILE?.trim() || undefined;\nconst MCP_INSTRUCTIONS_ENV = process.env.MCP_INSTRUCTIONS?.trim() || undefined;\nlet MCP_EXTRA_INSTRUCTIONS: string | undefined;\nconst MCP_INSTRUCTIONS_MAX_BYTES = 32 * 1024;\nif (MCP_INSTRUCTIONS_FILE) {\n try {\n const size = statSync(MCP_INSTRUCTIONS_FILE).size;\n if (size > MCP_INSTRUCTIONS_MAX_BYTES) {\n throw new Error(`file is ${size} bytes, exceeds ${MCP_INSTRUCTIONS_MAX_BYTES} byte cap`);\n }\n MCP_EXTRA_INSTRUCTIONS = readFileSync(MCP_INSTRUCTIONS_FILE, \"utf8\").trim() || undefined;\n } catch (err) {\n console.error(`Failed to read MCP_INSTRUCTIONS_FILE (${MCP_INSTRUCTIONS_FILE}): ${(err as Error).message}`);\n process.exit(1);\n }\n if (MCP_INSTRUCTIONS_ENV) {\n console.warn(\"MCP_INSTRUCTIONS_FILE is set; ignoring MCP_INSTRUCTIONS env var.\");\n }\n} else if (MCP_INSTRUCTIONS_ENV) {\n MCP_EXTRA_INSTRUCTIONS = MCP_INSTRUCTIONS_ENV;\n}\n\n// --- Initialize vault (local or remote) ---\nimport type { VaultBackend } from \"./vault-backend.js\";\n\nlet vault: VaultBackend;\n\nif (VAULT_PATH) {\n const { LocalVault } = await import(\"./vault-local.js\");\n vault = new LocalVault(VAULT_PATH);\n console.log(`Local mode: ${VAULT_PATH}`);\n} else if (COUCHDB_URL) {\n if (!COUCHDB_PASSWORD) {\n console.error(\"COUCHDB_PASSWORD is required in remote mode.\");\n process.exit(1);\n }\n const { Vault } = await import(\"./vault.js\");\n vault = new Vault({\n couchdbUrl: COUCHDB_URL,\n couchdbUser: COUCHDB_USER,\n couchdbPassword: COUCHDB_PASSWORD,\n database: COUCHDB_DATABASE,\n passphrase: COUCHDB_PASSPHRASE,\n obfuscatePaths: COUCHDB_OBFUSCATE_PROPERTIES,\n });\n console.log(`Remote mode: ${COUCHDB_URL}`);\n} else {\n console.error(\"Set VAULT_PATH for local mode or COUCHDB_URL for remote mode.\");\n process.exit(1);\n}\n\nawait vault.init();\nconsole.log(\"Vault ready.\");\n\n// --- Per-vault data directory ---\nconst baseDataDir = process.env.DATA_DIR ?? join(process.env.HOME ?? process.env.USERPROFILE ?? \"/tmp\", \".obsidian-mcp\");\nconst vaultId = createHash(\"sha256\").update(VAULT_NAME).digest(\"hex\").slice(0, 12);\nconst dataDir = join(baseDataDir, vaultId);\n\n// --- Search index ---\nconst indexPath = join(dataDir, \"search-index.json\");\nconst searchIndex = new SearchIndex(indexPath, COUCHDB_PASSPHRASE);\n\n// Load persisted metadata from disk\nawait searchIndex.loadFromDisk();\nif (debugLogging) {\n console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || \"(none)\"}`);\n}\n\n// Sync metadata in background (server starts immediately)\nasync function rebuildIndex() {\n const start = performance.now();\n\n if (COUCHDB_URL && vault.catchUp) {\n const changeCallback = (path: string, content: string | null, mtime?: number) => {\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n };\n\n let since = searchIndex.since || \"0\";\n if (debugLogging) console.log(`[debug] CouchDB catch-up from since: ${since}`);\n let changes = 0;\n const onBatch = async (batchSince: string, processed: number) => {\n searchIndex.since = batchSince;\n await searchIndex.saveToDisk();\n console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);\n };\n try {\n const countingCallback = (path: string, content: string | null, mtime?: number) => {\n changes++;\n if (debugLogging) console.log(`[debug] Change: ${path} ${content !== null ? \"(update)\" : \"(delete)\"}`);\n changeCallback(path, content, mtime);\n };\n const newSince = await vault.catchUp(since, countingCallback, onBatch);\n searchIndex.since = newSince;\n } catch (err) {\n console.warn(`Catch-up failed (${err}), rebuilding index from scratch...`);\n searchIndex.clear();\n changes = 0;\n const newSince = await vault.catchUp(\"0\", (path, content, mtime) => {\n changes++;\n changeCallback(path, content, mtime);\n }, onBatch);\n searchIndex.since = newSince;\n }\n if (changes > 0) {\n console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1000).toFixed(1)}s (${searchIndex.size} notes).`);\n } else {\n console.log(`Search index up to date (${searchIndex.size} notes).`);\n }\n } else if (VAULT_PATH) {\n const notesWithMtime = await vault.listNotesWithMtime();\n if (debugLogging) console.log(`[debug] Vault has ${notesWithMtime.length} notes`);\n if (notesWithMtime.length > 0) {\n const vaultPaths = new Set(notesWithMtime.map((n) => n.path));\n for (const p of searchIndex.listPaths()) {\n if (!vaultPaths.has(p)) searchIndex.remove(p);\n }\n console.log(`Building search index (${notesWithMtime.length} notes)...`);\n for (let i = 0; i < notesWithMtime.length; i++) {\n const { path, mtime } = notesWithMtime[i];\n const content = await vault.readNote(path);\n // Index empty notes too (content === \"\"); readNote returns null only if absent.\n if (content !== null) searchIndex.update(path, content, mtime);\n if (notesWithMtime.length > 100 && (i + 1) % 500 === 0) {\n console.log(` indexed ${i + 1}/${notesWithMtime.length}...`);\n }\n }\n console.log(`Search index built: ${searchIndex.size} notes in ${((performance.now() - start) / 1000).toFixed(1)}s`);\n }\n }\n await searchIndex.saveToDisk();\n searchIndex.state = \"ready\";\n}\n// Fire and forget — server starts while index builds\nrebuildIndex().catch((err) => {\n searchIndex.state = \"failed\";\n console.error(\"Index rebuild failed:\", err);\n});\n\n// --- Watch for external changes ---\nlet fsWatcher: ReturnType<typeof watch> | null = null;\nif (VAULT_PATH) {\n // Local mode: watch filesystem for changes from Obsidian\n const pending = new Map<string, ReturnType<typeof setTimeout>>();\n fsWatcher = watch(VAULT_PATH, { recursive: true }, (event, filename) => {\n if (!filename || !filename.endsWith(\".md\")) return;\n const notePath = filename.replace(/\\\\/g, \"/\");\n if (notePath.startsWith(\".obsidian/\") || notePath.includes(\"/.obsidian/\")) return;\n\n // Debounce: coalesce rapid events for the same file (Obsidian fires 2-3 per save)\n if (pending.has(notePath)) clearTimeout(pending.get(notePath)!);\n pending.set(notePath, setTimeout(() => handleFileChange(notePath), 100));\n });\n\n async function handleFileChange(notePath: string) {\n pending.delete(notePath);\n try {\n const content = await vault.readNote(notePath);\n if (content !== null) {\n const s = await stat(join(VAULT_PATH!, notePath));\n searchIndex.update(notePath, content, s.mtimeMs);\n } else {\n searchIndex.remove(notePath);\n }\n } catch {\n // File deleted or path blocked by safePath\n searchIndex.remove(notePath);\n }\n }\n console.log(\"Watching vault for external changes.\");\n} else if (COUCHDB_URL && vault.watchChanges) {\n // Remote mode: watch CouchDB _changes feed for LiveSync updates\n vault.watchChanges((path: string, content: string | null, mtime?: number, seq?: string | number) => {\n if (debugLogging) console.log(`[debug] CouchDB ${content === null ? \"delete\" : \"change\"}: ${path}`);\n // content === \"\" is an empty-but-present note: index it, don't drop it.\n applyIndexChange(searchIndex, path, content, mtime);\n if (seq) searchIndex.since = String(seq);\n });\n console.log(\"Watching CouchDB for LiveSync changes.\");\n}\n\n// --- MCP Server ---\nconst BASE_INSTRUCTIONS = \"Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.\";\nconst serverOptions: ConstructorParameters<typeof FastMCP>[0] = {\n name: \"obsidian-sync-mcp\",\n version: process.env.npm_package_version ?? \"0.0.0\",\n instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}\\n\\n${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS,\n};\n\n// Auth\nimport type { AuthHandle } from \"./auth.js\";\nlet auth: AuthHandle | null = null;\n\nif (AUTH_TOKEN) {\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n const header = req.headers[\"authorization\"];\n // Accept static Bearer token (for curl, MCP Inspector, custom agents)\n const expected = `Bearer ${AUTH_TOKEN}`;\n if (header && header.length === expected.length && timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {\n return { authenticated: true };\n }\n // Accept OAuth-issued tokens (for Claude Web/Desktop/Mobile)\n if (auth?.validateToken(header)) {\n return { authenticated: true };\n }\n // RFC 9728: point strict clients (e.g. Gemini) at the resource\n // metadata; Claude probes /.well-known directly but others rely on this.\n throw new Response(\"Unauthorized\", {\n status: 401,\n headers: { \"WWW-Authenticate\": `Bearer resource_metadata=\"${BASE_URL}/.well-known/oauth-protected-resource\"` },\n });\n };\n console.log(\"Auth enabled (password-gated OAuth).\");\n} else {\n // No token: enforce a Host-header allowlist so the \"local only\" precondition\n // actually holds. Without this, DNS rebinding lets any website the operator\n // visits reach the tool surface (CWE-350) even on a loopback bind, because\n // the browser still sends the attacker's hostname in Host. Defaults to\n // localhost; MCP_ALLOWED_HOSTS extends it for legit LAN/private-network use.\n const allowedHosts = buildAllowedHosts(process.env.MCP_ALLOWED_HOSTS);\n serverOptions.authenticate = async (req: import(\"http\").IncomingMessage) => {\n // Host check defeats DNS rebinding; Origin check defeats a direct\n // cross-origin browser fetch to loopback (the transport sends wildcard CORS).\n if (!isHostAllowed(req.headers[\"host\"], allowedHosts)) {\n throw new Response(\"Forbidden: Host not allowed\", { status: 403 });\n }\n if (!isOriginAllowed(req.headers[\"origin\"], allowedHosts)) {\n throw new Response(\"Forbidden: cross-origin request rejected\", { status: 403 });\n }\n return { authenticated: true };\n };\n console.log(`Auth disabled — accepting only local Host/Origin headers: ${[...allowedHosts].join(\", \")}. Set MCP_ALLOWED_HOSTS to add hosts, or MCP_AUTH_TOKEN for authenticated remote access.`);\n const host = process.env.HOST ?? \"0.0.0.0\";\n if (host === \"0.0.0.0\") {\n console.warn(\"WARNING: No authentication and listening on all interfaces. Browser attacks (DNS rebinding and cross-origin fetch) are blocked by the Host/Origin checks, but any non-browser client that can reach this port has full vault access. Set MCP_AUTH_TOKEN, or HOST=127.0.0.1 to bind to loopback only.\");\n }\n}\n\nconst server = new FastMCP(serverOptions);\n\nif (AUTH_TOKEN) {\n const tokenPath = join(dataDir, \"auth-tokens.json\");\n auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);\n await auth.loadTokens();\n}\n\n// --- Tools ---\nregisterTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);\n\n// --- Graceful shutdown ---\nasync function shutdown() {\n console.log(\"Shutting down...\");\n if (fsWatcher) fsWatcher.close();\n await searchIndex.saveToDisk();\n if (auth) await auth.saveTokens();\n await vault.close();\n process.exit(0);\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n\n// --- Periodic save (every 5 minutes) ---\nsetInterval(async () => {\n await searchIndex.saveToDisk();\n if (auth) {\n auth.cleanup();\n await auth.saveTokens();\n }\n}, 5 * 60 * 1000).unref();\n\n// --- Start server ---\nserver.start({\n transportType: \"httpStream\",\n httpStream: { port: PORT, endpoint: \"/mcp\", host: process.env.HOST ?? \"0.0.0.0\" },\n});\nconsole.log(`obsidian-sync-mcp v${process.env.npm_package_version ?? \"unknown\"} listening on port ${PORT}`);\n\n// Prevent unhandled rejections from crashing the server (e.g. decryption failures in watcher)\nprocess.on(\"unhandledRejection\", (err) => {\n console.error(\"Unhandled rejection:\", err);\n});\n","/**\n * Password-gated OAuth provider for MCP.\n *\n * Implements a self-contained OAuth 2.1 flow:\n * - Claude connects -> gets 401 with metadata pointer\n * - Claude discovers /.well-known/oauth-protected-resource\n * - Claude registers via /oauth/register (DCR)\n * - Claude redirects user to /oauth/authorize\n * - User sees a password page, enters MCP_AUTH_TOKEN\n * - Claude exchanges code for access token via /oauth/token\n * - All subsequent requests carry Bearer token\n *\n * No external identity provider needed.\n */\n\nimport { randomUUID, randomBytes, createHash, timingSafeEqual } from \"crypto\";\nimport { readFile, writeFile, mkdir, chmod } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport type { Hono } from \"hono\";\n\ninterface PendingAuth {\n clientId: string;\n redirectUri: string;\n codeChallenge: string;\n codeChallengeMethod: string;\n state: string;\n code: string;\n createdAt: number;\n approved: boolean;\n}\n\ninterface TokenRecord {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n expiresAt: number;\n refreshExpiresAt: number;\n}\n\ninterface RegisteredClient {\n clientId: string;\n clientSecret?: string;\n tokenEndpointAuthMethod: \"client_secret_post\" | \"none\";\n redirectUris: string[];\n clientName?: string;\n createdAt?: number;\n}\n\nconst TOKEN_EXPIRY_MS = 3600 * 1000; // 1 hour\nconst DEFAULT_REFRESH_DAYS = 14;\nconst REFRESH_EXPIRY_MS = (parseInt(process.env.MCP_REFRESH_DAYS ?? String(DEFAULT_REFRESH_DAYS)) || DEFAULT_REFRESH_DAYS) * 24 * 3600 * 1000;\nconst MAX_FAILED_BEFORE_LOCKOUT = 5;\nconst BASE_LOCKOUT_MS = 5 * 1000; // 5 seconds, doubles each lockout\nconst MAX_CLIENTS = 100;\nconst MAX_PENDING = 100;\nconst PENDING_TTL_MS = 10 * 60 * 1000; // 10 minutes\n\nexport interface AuthHandle {\n validateToken: (auth: string | undefined) => boolean;\n saveTokens: () => Promise<void>;\n loadTokens: () => Promise<boolean>;\n cleanup: () => void;\n}\n\nexport function mountPasswordAuth(app: Hono, baseUrl: string, password: string, persistPath?: string): AuthHandle {\n const pendingAuths = new Map<string, PendingAuth>();\n const csrfTokens = new Map<string, string>(); // code -> csrf token\n const tokens = new Map<string, TokenRecord>();\n const refreshTokens = new Map<string, TokenRecord>();\n const clients = new Map<string, RegisteredClient>();\n\n // Cleanup expired pending auths and CSRF tokens\n function cleanupPending() {\n const now = Date.now();\n for (const [code, pending] of pendingAuths) {\n if (now - pending.createdAt > PENDING_TTL_MS) {\n pendingAuths.delete(code);\n csrfTokens.delete(code);\n }\n }\n }\n\n // Rate limiting: exponential backoff, never resets until success\n let failedAttempts = 0;\n let lockoutCount = 0;\n let lockedUntil = 0;\n\n // Persist clients + tokens. Called on every state change (not just the\n // periodic save): a restart or Fly suspend right after registration or\n // token issuance must not lose the new state.\n async function persist(): Promise<void> {\n if (!persistPath) return;\n try {\n await mkdir(dirname(persistPath), { recursive: true });\n const now = Date.now();\n const activeTokens = [...tokens.entries()].filter(([, r]) => r.expiresAt > now);\n const activeRefresh = [...refreshTokens.entries()].filter(([, r]) => r.refreshExpiresAt > now);\n const data = JSON.stringify({\n tokens: Object.fromEntries(activeTokens),\n refreshTokens: Object.fromEntries(activeRefresh),\n clients: Object.fromEntries(clients),\n });\n await writeFile(persistPath, data, { encoding: \"utf-8\", mode: 0o600 });\n await chmod(persistPath, 0o600);\n } catch (err) {\n console.error(\"Failed to save auth tokens:\", err);\n }\n }\n\n // HTTPS warning\n if (!baseUrl.startsWith(\"https://\") && !baseUrl.includes(\"localhost\")) {\n console.warn(\"WARNING: BASE_URL is not HTTPS. OAuth tokens will be sent in cleartext. Use a tunnel (cloudflared, tailscale, ngrok) to provide TLS.\");\n }\n\n // --- Discovery endpoints ---\n\n app.get(\"/.well-known/oauth-protected-resource\", (c) => {\n return c.json({\n resource: baseUrl,\n authorization_servers: [baseUrl],\n scopes_supported: [\"mcp\"],\n });\n });\n\n app.get(\"/.well-known/oauth-authorization-server\", (c) => {\n return c.json({\n issuer: baseUrl,\n authorization_endpoint: `${baseUrl}/oauth/authorize`,\n token_endpoint: `${baseUrl}/oauth/token`,\n registration_endpoint: `${baseUrl}/oauth/register`,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"client_secret_post\", \"none\"],\n scopes_supported: [\"mcp\"],\n });\n });\n\n // --- Dynamic Client Registration (RFC 7591) ---\n\n app.post(\"/oauth/register\", async (c) => {\n if (clients.size >= MAX_CLIENTS) {\n // Evict the oldest client with no live tokens to make room; only\n // reject when every slot is held by a client with active tokens.\n const activeClientIds = new Set<string>();\n for (const r of tokens.values()) activeClientIds.add(r.clientId);\n for (const r of refreshTokens.values()) activeClientIds.add(r.clientId);\n let oldest: RegisteredClient | undefined;\n for (const client of clients.values()) {\n if (activeClientIds.has(client.clientId)) continue;\n if (!oldest || (client.createdAt ?? 0) < (oldest.createdAt ?? 0)) oldest = client;\n }\n if (!oldest) {\n return c.json({ error: \"too_many_clients\" }, 429);\n }\n clients.delete(oldest.clientId);\n }\n const body = await c.req.json();\n\n // Validate redirect_uris\n const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris.slice(0, 5) : [];\n if (redirectUris.length === 0) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"redirect_uris required\" }, 400);\n }\n const safeUri = (u: any) => {\n if (typeof u !== \"string\" || u.length > 2048) return false;\n const lower = u.toLowerCase();\n return !lower.startsWith(\"javascript:\") && !lower.startsWith(\"data:\") && !lower.startsWith(\"file:\");\n };\n if (redirectUris.some((u: any) => !safeUri(u))) {\n return c.json({ error: \"invalid_client_metadata\", error_description: \"invalid redirect_uri\" }, 400);\n }\n\n const clientId = randomUUID();\n // Honor the client's requested auth method (RFC 7591 §2). Only\n // \"client_secret_post\" and \"none\" are advertised as supported, so\n // anything else falls back to the confidential-client default rather\n // than silently registering a method we don't understand.\n const tokenEndpointAuthMethod: \"client_secret_post\" | \"none\" =\n body.token_endpoint_auth_method === \"none\" ? \"none\" : \"client_secret_post\";\n const clientSecret = tokenEndpointAuthMethod === \"none\" ? undefined : randomBytes(32).toString(\"hex\");\n const clientName = typeof body.client_name === \"string\" ? body.client_name.slice(0, 256) : undefined;\n\n const client: RegisteredClient = {\n clientId,\n clientSecret,\n tokenEndpointAuthMethod,\n redirectUris,\n clientName,\n createdAt: Date.now(),\n };\n clients.set(clientId, client);\n await persist();\n\n console.log(\n `Auth: registered client_id=${clientId} redirect_uris=${JSON.stringify(redirectUris)} ` +\n `requested_auth_method=${JSON.stringify(body.token_endpoint_auth_method ?? \"(unspecified)\")} (responding with ${tokenEndpointAuthMethod})`\n );\n\n return c.json({\n client_id: clientId,\n ...(clientSecret ? { client_secret: clientSecret } : {}),\n redirect_uris: client.redirectUris,\n client_name: client.clientName,\n token_endpoint_auth_method: tokenEndpointAuthMethod,\n }, 201);\n });\n\n // --- Authorization endpoint ---\n\n app.get(\"/oauth/authorize\", (c) => {\n const clientId = c.req.query(\"client_id\") ?? \"\";\n const redirectUri = c.req.query(\"redirect_uri\") ?? \"\";\n const codeChallenge = c.req.query(\"code_challenge\") ?? \"\";\n const codeChallengeMethod = c.req.query(\"code_challenge_method\") ?? \"S256\";\n const state = c.req.query(\"state\") ?? \"\";\n\n // Validate redirect URI against registered client\n const client = clients.get(clientId);\n if (!client) {\n console.warn(`Auth: /oauth/authorize unknown client_id=${JSON.stringify(clientId)}`);\n return c.text(\"Unknown client\", 400);\n }\n if (!client.redirectUris.includes(redirectUri)) {\n console.warn(\n `Auth: /oauth/authorize redirect_uri mismatch. received=${JSON.stringify(redirectUri)} ` +\n `registered=${JSON.stringify(client.redirectUris)}`\n );\n return c.text(\"Invalid redirect URI\", 400);\n }\n\n // Require S256 PKCE\n if (codeChallengeMethod !== \"S256\" || !codeChallenge) {\n console.warn(`Auth: /oauth/authorize missing/unsupported PKCE. method=${JSON.stringify(codeChallengeMethod)} challenge_present=${!!codeChallenge}`);\n return c.text(\"PKCE with S256 is required\", 400);\n }\n\n cleanupPending();\n if (pendingAuths.size >= MAX_PENDING) {\n return c.text(\"Too many pending authorizations\", 429);\n }\n\n const code = randomBytes(32).toString(\"hex\");\n pendingAuths.set(code, {\n clientId,\n redirectUri,\n codeChallenge,\n codeChallengeMethod,\n state,\n code,\n createdAt: Date.now(),\n approved: false,\n });\n\n console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);\n\n const csrf = randomBytes(32).toString(\"hex\");\n csrfTokens.set(code, csrf);\n return c.html(renderPasswordPage(code, csrf));\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 // Mark the code redeemable only now that the password has been verified.\n // Without this, /oauth/token would accept the code straight out of the\n // authorize page before any password was entered.\n pending.approved = true;\n console.log(\"Auth: password accepted, issuing authorization code.\");\n\n const url = new URL(pending.redirectUri);\n url.searchParams.set(\"code\", code);\n if (pending.state) url.searchParams.set(\"state\", pending.state);\n const redirectUrl = url.toString();\n\n return c.redirect(redirectUrl);\n });\n\n // --- Token endpoint ---\n\n app.post(\"/oauth/token\", async (c) => {\n const body = await c.req.parseBody();\n const grantType = body[\"grant_type\"] as string;\n console.log(`Auth: /oauth/token request grant_type=${JSON.stringify(grantType)}`);\n\n if (grantType === \"authorization_code\") {\n const code = body[\"code\"] as string;\n const clientId = body[\"client_id\"] as string;\n const codeVerifier = body[\"code_verifier\"] as string;\n const redirectUri = body[\"redirect_uri\"] as string;\n\n const pending = pendingAuths.get(code);\n if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) {\n console.warn(\n `Auth: /oauth/token invalid_grant. code_known=${!!pending} ` +\n `expired=${pending ? Date.now() - pending.createdAt > PENDING_TTL_MS : \"n/a\"}`\n );\n if (pending) pendingAuths.delete(code);\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // The code is only redeemable once the password step succeeded.\n // It exists in pendingAuths from /oauth/authorize onward (and is\n // present in the authorize page HTML), so without this check the\n // password gate can be bypassed entirely.\n if (!pending.approved) {\n console.warn(\"Auth: /oauth/token invalid_grant. code not yet approved (password step not completed)\");\n return c.json({ error: \"invalid_grant\", error_description: \"authorization not approved\" }, 400);\n }\n\n // Verify client_id matches the original request\n if (clientId !== pending.clientId) {\n console.warn(\n `Auth: /oauth/token client_id mismatch. received=${JSON.stringify(clientId)} expected=${JSON.stringify(pending.clientId)}`\n );\n return c.json({ error: \"invalid_grant\", error_description: \"client_id mismatch\" }, 400);\n }\n\n // Verify redirect_uri matches the original request\n if (redirectUri !== pending.redirectUri) {\n console.warn(\n `Auth: /oauth/token redirect_uri mismatch. received=${JSON.stringify(redirectUri)} expected=${JSON.stringify(pending.redirectUri)}`\n );\n return c.json({ error: \"invalid_grant\", error_description: \"redirect_uri mismatch\" }, 400);\n }\n\n // Verify PKCE\n if (pending.codeChallengeMethod === \"S256\") {\n const expected = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n console.warn(\"Auth: /oauth/token PKCE verification failed\");\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed\" }, 400);\n }\n }\n\n pendingAuths.delete(code);\n console.log(`Auth: /oauth/token issuing access token client_id=${pending.clientId}`);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const refreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken,\n clientId: pending.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: Date.now() + REFRESH_EXPIRY_MS,\n };\n tokens.set(accessToken, record);\n refreshTokens.set(refreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: refreshToken,\n });\n }\n\n if (grantType === \"refresh_token\") {\n const refreshToken = body[\"refresh_token\"] as string;\n const old = refreshTokens.get(refreshToken);\n if (!old) {\n console.warn(\"Auth: /oauth/token refresh_token unknown\");\n return c.json({ error: \"invalid_grant\" }, 400);\n }\n\n // Check refresh token expiry\n if (Date.now() > old.refreshExpiresAt) {\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n console.log(\"Auth: refresh token expired, user must re-authenticate.\");\n return c.json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" }, 400);\n }\n\n tokens.delete(old.accessToken);\n refreshTokens.delete(refreshToken);\n\n const accessToken = randomBytes(32).toString(\"hex\");\n const newRefreshToken = randomBytes(32).toString(\"hex\");\n const record: TokenRecord = {\n accessToken,\n refreshToken: newRefreshToken,\n clientId: old.clientId,\n expiresAt: Date.now() + TOKEN_EXPIRY_MS,\n refreshExpiresAt: old.refreshExpiresAt, // keep original expiry\n };\n tokens.set(accessToken, record);\n refreshTokens.set(newRefreshToken, record);\n await persist();\n\n return c.json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: TOKEN_EXPIRY_MS / 1000,\n refresh_token: newRefreshToken,\n });\n }\n\n console.warn(`Auth: /oauth/token unsupported_grant_type=${JSON.stringify(grantType)}`);\n return c.json({ error: \"unsupported_grant_type\" }, 400);\n });\n\n return {\n validateToken(authHeader: string | undefined): boolean {\n if (!authHeader?.startsWith(\"Bearer \")) return false;\n const token = authHeader.slice(7);\n const record = tokens.get(token);\n if (!record) return false;\n if (Date.now() > record.expiresAt) {\n tokens.delete(token);\n return false;\n }\n return true;\n },\n\n async saveTokens(): Promise<void> {\n await persist();\n },\n\n cleanup(): void {\n const now = Date.now();\n for (const [k, r] of tokens) { if (r.expiresAt <= now) tokens.delete(k); }\n for (const [k, r] of refreshTokens) { if (r.refreshExpiresAt <= now) refreshTokens.delete(k); }\n // Registered clients are NOT evicted here: AI clients cache their\n // client_id indefinitely and retry it after token expiry, so\n // dropping a registration means \"Unknown client\" until the user\n // deletes and re-adds the connector (issue #13). The clients map\n // is bounded at registration time instead.\n },\n\n async loadTokens(): Promise<boolean> {\n if (!persistPath) return false;\n try {\n const raw = await readFile(persistPath, \"utf-8\");\n const data = JSON.parse(raw);\n const now = Date.now();\n for (const [k, v] of Object.entries(data.tokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.expiresAt > now) tokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.refreshTokens ?? {})) {\n const record = v as TokenRecord;\n if (record.accessToken && record.refreshToken && record.refreshExpiresAt > now) refreshTokens.set(k, record);\n }\n for (const [k, v] of Object.entries(data.clients ?? {})) {\n const client = v as RegisteredClient;\n if (client.clientId && client.redirectUris) clients.set(k, client);\n }\n console.log(`Auth tokens loaded from disk (${tokens.size} sessions).`);\n return tokens.size > 0;\n } catch {\n return false;\n }\n },\n };\n}\n\nfunction 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\n/**\n * Lifecycle of the in-memory index. \"building\" from construction until the\n * startup rebuild finishes, \"ready\" afterwards, \"failed\" if the rebuild threw.\n * Read by list_notes so a client can tell a partial index from a complete one.\n */\nexport type IndexState = \"building\" | \"ready\" | \"failed\";\n\nexport class SearchIndex {\n private _state: IndexState = \"building\";\n private mtimes = new Map<string, number>();\n private tags = new Map<string, string[]>();\n private links = new Map<string, string[]>();\n private backlinks = new Map<string, Set<string>>();\n private knownPaths = new Set<string>();\n 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 this._state = \"building\";\n }\n\n get state(): IndexState {\n return this._state;\n }\n\n set state(value: IndexState) {\n this._state = value;\n }\n\n get since(): string {\n return this._since;\n }\n\n set since(value: string) {\n this._since = value;\n }\n\n get size(): number {\n return this.knownPaths.size;\n }\n}\n","/**\n * Host-header allowlisting to defeat DNS-rebinding attacks (CWE-350).\n *\n * When the server runs without MCP_AUTH_TOKEN (\"local only\" mode), a malicious\n * web page the operator visits can use DNS rebinding to point its hostname at\n * 127.0.0.1 and reach the MCP endpoint from the browser. Binding to loopback\n * does NOT help — the OS resolves the attacker hostname to loopback while the\n * page keeps its origin. The browser still sends the attacker's hostname in the\n * `Host` header, so validating Host against a localhost allowlist rejects the\n * rebound request. A bearer token (auth mode) already defeats this, since a\n * browser won't attach it; this guard protects the no-token path.\n *\n * Kept dependency-free so it is unit-testable in isolation.\n */\n\nconst LOCAL_HOSTS = [\"localhost\", \"127.0.0.1\", \"::1\"];\n\n/** Extract a normalized, lowercased hostname from a raw `Host` header (strips port and IPv6 brackets). */\nexport function parseHostname(hostHeader: string | undefined | null): string | null {\n if (!hostHeader) return null;\n // A real Host header is a bare host[:port]. Reject anything carrying userinfo\n // or a path (e.g. \"attacker.example@127.0.0.1\", \"127.0.0.1/x\") so a crafted\n // value can't normalize into the allowlist.\n if (hostHeader.includes(\"@\") || hostHeader.includes(\"/\")) return null;\n try {\n // Wrapping in a URL parses `host:port` and `[ipv6]:port` correctly.\n const u = new URL(`http://${hostHeader}`);\n if (u.username || u.password || u.pathname !== \"/\" || u.search || u.hash) return null;\n return u.hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n } catch {\n return null;\n }\n}\n\n/** Build the set of allowed hostnames: always localhost, plus any from a comma-separated list. */\nexport function buildAllowedHosts(extra?: string): Set<string> {\n const set = new Set(LOCAL_HOSTS);\n for (const entry of (extra ?? \"\").split(\",\").map((s) => s.trim()).filter(Boolean)) {\n set.add(parseHostname(entry) ?? entry.toLowerCase());\n }\n return set;\n}\n\n/** True if the request's Host header resolves to an allowed hostname. Missing/malformed Host is rejected. */\nexport function isHostAllowed(hostHeader: string | undefined | null, allowed: Set<string>): boolean {\n const hostname = parseHostname(hostHeader);\n return hostname !== null && allowed.has(hostname);\n}\n\n/**\n * True if the request has no browser `Origin`, or its Origin host is allowlisted.\n *\n * Host validation alone is not enough: the transport answers with a wildcard\n * `Access-Control-Allow-Origin: *`, so a page at any origin can skip DNS\n * rebinding and directly `fetch('http://127.0.0.1:<port>/mcp')` — that request\n * carries a genuine loopback Host (passes isHostAllowed) but an attacker Origin.\n * Non-browser MCP clients (CLI, desktop apps) send no Origin, so requiring\n * \"no Origin, or an allowlisted Origin\" blocks cross-origin browsers without\n * affecting legitimate local callers.\n */\nexport function isOriginAllowed(originHeader: string | undefined | null, allowed: Set<string>): boolean {\n if (!originHeader) return true; // non-browser client — no Origin header\n try {\n const hostname = new URL(originHeader).hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n return allowed.has(hostname);\n } catch {\n return false; // \"null\"/opaque or malformed Origin — reject\n }\n}\n","import type { FastMCP } from \"fastmcp\";\nimport { z } from \"zod\";\nimport { makeDeepLink } from \"./deeplink.js\";\nimport type { VaultBackend } from \"./vault-backend.js\";\nimport type { SearchIndex } from \"./search.js\";\nimport { isPathWritable } from \"./write-scope.js\";\nimport { describeListing, describeNoMatch } from \"./list-format.js\";\n\nconst debugLogging = process.env.LOG_LEVEL === \"debug\";\n\nconst WRITE_TOOLS = [\"write_note\", \"edit_note\", \"delete_note\", \"move_note\"] as const;\n\n// Claude Code persists any MCP tool result above ~50 000 characters to a file\n// and hands the model a 2 kB preview instead of the text. A tool can raise its\n// own threshold (hard ceiling 500 000) by declaring\n// `_meta[\"anthropic/maxResultSizeChars\"]` in its tools/list entry; text from\n// such a tool is then also exempt from MAX_MCP_OUTPUT_TOKENS. See\n// https://code.claude.com/docs/en/mcp#raise-the-limit-for-a-specific-tool\n// read_note returns whole notes, so it declares 100 000: enough for a large\n// note to arrive in one piece, small enough to keep one read inside a sane\n// context budget. Other clients ignore the key.\nexport const READ_NOTE_MAX_RESULT_SIZE_CHARS = 100_000;\n\nexport function registerTools(\n server: FastMCP,\n vault: VaultBackend,\n searchIndex: SearchIndex,\n vaultName: string,\n readOnly = false,\n writeFolders: string[] | null = null,\n) {\n if (readOnly) {\n console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(\", \")}).`);\n } else if (writeFolders) {\n console.log(`WRITE_FOLDERS: writes restricted to ${writeFolders.map((f) => f + \"/\").join(\", \")}.`);\n }\n const writeScopeNote = writeFolders\n ? ` Writes are only allowed inside: ${writeFolders.map((f) => f + \"/\").join(\", \")}.`\n : \"\";\n const denyWrite = (path: string) =>\n `Write access denied: '${path}' is outside the writable folders (${writeFolders!.map((f) => f + \"/\").join(\", \")}).`;\n const _addTool = server.addTool.bind(server);\n server.addTool = (tool: any) => {\n const original = tool.execute;\n tool.execute = async (args: any, ctx: any) => {\n if (debugLogging) console.log(`[tool] ${tool.name}(${JSON.stringify(args)})`);\n const start = performance.now();\n const result = await original(args, ctx);\n if (debugLogging) console.log(`[tool] ${tool.name} → ${((performance.now() - start)).toFixed(0)}ms`);\n return result;\n };\n return _addTool(tool);\n };\n server.addTool({\n name: \"read_note\",\n description:\n \"Read the content of a note from the Obsidian vault. Returns the markdown content and a deep link to open it in Obsidian.\",\n _meta: { \"anthropic/maxResultSizeChars\": READ_NOTE_MAX_RESULT_SIZE_CHARS },\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n }),\n execute: async ({ path }) => {\n const content = await vault.readNote(path);\n if (content === null) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n return `[Open in Obsidian](${deepLink})\\n\\n---\\n\\n${content}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"write_note\",\n description:\n \"Write or update a note in the Obsidian vault. Creates the note if it doesn't exist. Replaces the entire content if it does — read first if you need to preserve existing content.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-23.md'\"),\n content: z.string().describe(\"Full markdown content for the note\"),\n }),\n execute: async ({ path, content }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const ok = await vault.writeNote(path, content);\n if (!ok) {\n return `Failed to write note: ${path}`;\n }\n searchIndex.update(path, content, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note saved: ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"list_notes\",\n description: \"List markdown notes in the vault with modification timestamps. Examples: list_notes(sort_by='modified', limit=10) for 10 most recent notes. list_notes(name='meeting') to find notes by name. list_notes(folder='daily') for a specific folder. list_notes(tag='project') for notes with a specific tag. Returns up to 100 notes by default.\",\n parameters: z.object({\n folder: z\n .string()\n .optional()\n .describe(\"Folder to filter by, e.g. 'daily' or 'projects'. Omit for all notes.\"),\n name: z\n .string()\n .optional()\n .describe(\"Filter by name (case-insensitive substring match on path), e.g. 'meeting' or 'project-x'.\"),\n tag: z\n .string()\n .optional()\n .describe(\"Filter by tag, e.g. 'project' or 'daily'. Use list_tags to discover available tags.\"),\n sort_by: z\n .enum([\"name\", \"modified\"])\n .optional()\n .describe(\"Sort order: 'name' (default) or 'modified' (most recent first).\"),\n modified_after: z\n .string()\n .optional()\n .describe(\"Only include notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'.\"),\n limit: z.coerce\n .number()\n .optional()\n .describe(\"Max number of notes to return. Default 100.\"),\n }),\n execute: async ({ folder, name, tag, sort_by, modified_after, limit }) => {\n // Use search index (works with encrypted vaults), fall back to vault\n let notes = searchIndex.listWithMtime(folder);\n let vaultTotal: number | null = searchIndex.size;\n let servedByVault = false;\n if (notes.length === 0) {\n notes = await vault.listNotesWithMtime(folder);\n servedByVault = notes.length > 0;\n // The fallback only tells us the vault total when it was unscoped.\n if (vaultTotal === 0) vaultTotal = folder ? null : notes.length;\n }\n const folderTotal = folder ? notes.length : null;\n const filters: string[] = [];\n if (name) {\n const lower = name.toLowerCase();\n notes = notes.filter((n) => n.path.toLowerCase().includes(lower));\n filters.push(`name=\"${name}\"`);\n }\n if (tag) {\n notes = notes.filter((n) => searchIndex.getTags(n.path).includes(tag));\n filters.push(`tag=\"${tag}\"`);\n }\n if (modified_after) {\n const cutoff = new Date(modified_after).getTime();\n if (isNaN(cutoff)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;\n notes = notes.filter((n) => n.mtime >= cutoff);\n filters.push(`modified_after=\"${modified_after}\"`);\n }\n const index = { state: searchIndex.state, size: searchIndex.size, servedByVault };\n if (notes.length === 0) {\n return describeNoMatch({ vaultTotal, folder, folderTotal, filters, index });\n }\n const sortBy = sort_by === \"modified\" ? \"modified\" : \"name\";\n if (sortBy === \"modified\") {\n notes.sort((a, b) => b.mtime - a.mtime);\n }\n const cap = limit ?? 100;\n const total = notes.length;\n const capped = notes.slice(0, cap);\n const header = describeListing({\n shown: capped.length,\n matched: total,\n vaultTotal,\n folder,\n folderTotal,\n filters,\n sortBy,\n limit: cap,\n omitted: notes.slice(cap).map((n) => n.path),\n index,\n });\n const lines = capped.map((n) => {\n const deepLink = makeDeepLink(vaultName, n.path);\n const date = n.mtime ? new Date(n.mtime).toISOString().slice(0, 16) : \"\";\n return `- ${date} [${n.path}](${deepLink})`;\n });\n return [header, ...lines].join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_folders\",\n description:\n \"List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.\",\n parameters: z.object({}),\n execute: async () => {\n let paths = searchIndex.listPaths();\n if (paths.length === 0) {\n paths = await vault.listNotes();\n }\n const folders = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n folders.set(\"(root)\", (folders.get(\"(root)\") ?? 0) + 1);\n } else {\n const folder = p.slice(0, lastSlash);\n folders.set(folder, (folders.get(folder) ?? 0) + 1);\n // Ensure all parent folders appear in the list\n let parent = folder;\n while (parent.includes(\"/\")) {\n parent = parent.slice(0, parent.lastIndexOf(\"/\"));\n if (!folders.has(parent)) folders.set(parent, 0);\n }\n }\n }\n if (folders.size === 0) {\n return \"Vault is empty.\";\n }\n const sorted = [...folders.entries()].sort((a, b) => a[0].localeCompare(b[0]));\n return sorted.map(([f, count]) => `- ${f} (${count} notes)`).join(\"\\n\");\n },\n });\n\n server.addTool({\n name: \"list_tags\",\n description:\n \"List all tags used in the vault, sorted by frequency. Use this to discover tags before filtering with list_notes.\",\n parameters: z.object({}),\n execute: async () => {\n const tags = searchIndex.listAllTags();\n if (tags.length === 0) {\n return \"No tags found in the vault.\";\n }\n return tags.map(({ tag, count }) => `- #${tag} (${count} notes)`).join(\"\\n\");\n },\n });\n\n\n\n if (!readOnly) server.addTool({\n name: \"edit_note\",\n description:\n \"Edit a note without rewriting it. Use 'append' (default) to add content to the end, 'prepend' to add after frontmatter, or 'replace' to swap old_text with new content. For replace, the old_text must match exactly once.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'daily/2026-03-25.md'\"),\n content: z.string().describe(\"Text to append, prepend, or use as replacement for old_text\"),\n operation: z\n .enum([\"append\", \"prepend\", \"replace\"])\n .optional()\n .describe(\"'append' (default): add to end. 'prepend': add after frontmatter. 'replace': swap old_text with content.\"),\n old_text: z\n .string()\n .optional()\n .describe(\"Required for replace operation. Exact text to find and replace. Must match exactly once.\"),\n }),\n execute: async ({ path, content: newContent, operation, old_text }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n const existing = await vault.readNote(path);\n if (existing === null) {\n return `Note not found: ${path}`;\n }\n\n let updated: string;\n const op = operation ?? \"append\";\n\n if (op === \"replace\") {\n if (!old_text) {\n return \"old_text is required for replace operation.\";\n }\n const idx = existing.indexOf(old_text);\n if (idx === -1) {\n return \"old_text not found in note.\";\n }\n if (existing.indexOf(old_text, idx + 1) !== -1) {\n return \"old_text matches multiple times. Provide a longer, unique string.\";\n }\n updated = existing.slice(0, idx) + newContent + existing.slice(idx + old_text.length);\n } else if (op === \"prepend\") {\n // Insert after frontmatter if present\n const fmMatch = existing.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n/);\n if (fmMatch) {\n const afterFm = fmMatch[0].length;\n updated = existing.slice(0, afterFm) + newContent + \"\\n\" + existing.slice(afterFm);\n } else {\n updated = newContent + \"\\n\" + existing;\n }\n } else {\n // append\n updated = existing.endsWith(\"\\n\") ? existing + newContent : existing + \"\\n\" + newContent;\n }\n\n const ok = await vault.writeNote(path, updated);\n if (!ok) {\n return `Failed to edit note: ${path}`;\n }\n searchIndex.update(path, updated, Date.now());\n const deepLink = makeDeepLink(vaultName, path);\n return `Note edited (${op}): ${path}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"delete_note\",\n description: \"Delete a note from the Obsidian vault.\" + writeScopeNote,\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note to delete\"),\n }),\n execute: async ({ path }) => {\n if (!isPathWritable(path, writeFolders)) return denyWrite(path);\n // The sync layer reports success even when nothing existed at the\n // path, so \"Deleted\" would claim a cleanup that never happened.\n // readNote returns \"\" for an empty note and null only when absent.\n const existing = await vault.readNote(path);\n if (existing === null) return `Note not found: ${path}`;\n const ok = await vault.deleteNote(path);\n if (ok) searchIndex.remove(path);\n return ok ? `Deleted: ${path}` : `Failed to delete: ${path}`;\n },\n });\n\n if (!readOnly) server.addTool({\n name: \"move_note\",\n description:\n \"Move or rename a note. Use this to rename a note within the same folder, move it to a different folder, or both at once. Creates destination folders automatically.\" + writeScopeNote,\n parameters: z.object({\n from: z.string().describe(\"Current path, e.g. 'daily/old-name.md'\"),\n to: z.string().describe(\"New path, e.g. 'projects/new-name.md'\"),\n }),\n execute: async ({ from, to }) => {\n // Moving out of a folder deletes there; moving in writes there — both ends must be writable.\n if (!isPathWritable(from, writeFolders)) return denyWrite(from);\n if (!isPathWritable(to, writeFolders)) return denyWrite(to);\n const content = await vault.readNote(from);\n const ok = await vault.moveNote(from, to);\n if (!ok) {\n return `Failed to move: ${from} → ${to}`;\n }\n searchIndex.remove(from);\n // content === \"\" is an empty-but-present note: keep it indexed at the new path.\n if (content !== null) searchIndex.update(to, content, Date.now());\n const deepLink = makeDeepLink(vaultName, to);\n return `Moved: ${from} → ${to}\\n[Open in Obsidian](${deepLink})`;\n },\n });\n\n server.addTool({\n name: \"get_note_metadata\",\n description:\n \"Get metadata about a note without reading its full content. Returns frontmatter, tags, outgoing links, backlinks (notes that link to this one), size, and timestamps. Use this to navigate the knowledge graph.\",\n parameters: z.object({\n path: z.string().describe(\"Vault-relative path to the note, e.g. 'projects/my-project.md'\"),\n }),\n execute: async ({ path }) => {\n const meta = await vault.getMetadata(path);\n if (!meta) {\n return `Note not found: ${path}`;\n }\n const deepLink = makeDeepLink(vaultName, path);\n const lines = [\n `**${path}**`,\n `Size: ${meta.size} bytes`,\n `Created: ${new Date(meta.ctime).toISOString()}`,\n `Modified: ${new Date(meta.mtime).toISOString()}`,\n ];\n if (Object.keys(meta.frontmatter).length > 0) {\n lines.push(`\\nFrontmatter:`);\n for (const [k, v] of Object.entries(meta.frontmatter)) {\n lines.push(` ${k}: ${v}`);\n }\n }\n if (meta.tags.length > 0) {\n lines.push(`\\nTags: ${meta.tags.map((t) => `#${t}`).join(\", \")}`);\n }\n if (meta.links.length > 0) {\n lines.push(`\\nOutgoing links: ${meta.links.join(\", \")}`);\n }\n const backlinks = searchIndex.getBacklinks(path);\n if (backlinks.length > 0) {\n lines.push(`\\nBacklinks: ${backlinks.join(\", \")}`);\n }\n lines.push(`\\n[Open in Obsidian](${deepLink})`);\n return lines.join(\"\\n\");\n },\n });\n}\n","/**\n * Generate Obsidian deep links for notes.\n * Works on Mac and iOS: obsidian://open?vault=<name>&file=<path>\n */\nexport function makeDeepLink(vaultName: string, notePath: string): string {\n const cleanPath = notePath.replace(/\\.md$/, \"\");\n const encodedVault = encodeURIComponent(vaultName);\n const encodedPath = encodeURIComponent(cleanPath);\n return `obsidian://open?vault=${encodedVault}&file=${encodedPath}`;\n}\n","// Folder-scoped write access (WRITE_FOLDERS env var).\n// When set, write tools only accept paths inside the listed vault-relative folders.\n\n/** Parse the WRITE_FOLDERS env var into a normalized folder list, or null for unrestricted. */\nexport function parseWriteFolders(raw: string | undefined): string[] | null {\n if (raw === undefined) return null;\n const folders = raw\n .split(\",\")\n .map((f) => f.trim().replace(/^\\/+|\\/+$/g, \"\"))\n .filter(Boolean);\n return folders.length > 0 ? folders : null;\n}\n\n/**\n * Check whether a vault-relative path falls inside one of the writable folders.\n * Matching is case-sensitive and folder-boundary-aware (\"MCP\" matches \"MCP/x.md\",\n * not \"MCP-private/x.md\"). A null folder list means writes are unrestricted.\n */\nexport function isPathWritable(path: string, writeFolders: string[] | null): boolean {\n if (writeFolders === null) return true;\n const normalized = path.replace(/^\\/+/, \"\");\n // Backends reject traversal too; deny here so the scope check can't be reasoned around.\n // Split on backslash as well: on Windows \"MCP/..\\x\" resolves as traversal.\n if (normalized.split(/[/\\\\]/).includes(\"..\")) return false;\n return writeFolders.some((folder) => normalized.startsWith(folder + \"/\"));\n}\n","import type { IndexState } from \"./search.js\";\n\n/**\n * Response wording for list_notes (issue #19). Kept free of MCP/vault types so\n * it can be unit-tested: the goal is that an LLM client can never mistake a\n * truncated, filtered or still-indexing listing for \"the vault contains\n * nothing else\".\n */\n\nexport const MAX_NAMED_FOLDERS = 10;\n\nexport interface ListingSummary {\n /** Notes actually returned (after the limit). */\n shown: number;\n /** Notes matching all filters (before the limit). */\n matched: number;\n /** Notes in the whole vault, before any filter; null when unknown. */\n vaultTotal: number | null;\n /** Folder filter as given by the caller, if any. */\n folder?: string;\n /** Notes inside `folder` before the other filters; null when unknown. */\n folderTotal?: number | null;\n /** Non-folder filters that were applied, e.g. `name=\"x\"`, `tag=\"y\"`. */\n filters: string[];\n sortBy: \"name\" | \"modified\";\n limit: number;\n /** Paths cut by the limit, used to name the omitted folders. */\n omitted: string[];\n index: IndexStatus;\n}\n\nexport interface IndexStatus {\n state: IndexState;\n size: number;\n /** True when the notes were read straight from the vault because the index had nothing — the list itself is complete. */\n servedByVault?: boolean;\n}\n\nexport interface FolderCount {\n folder: string;\n count: number;\n}\n\nfunction plural(n: number, word: string): string {\n return `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n}\n\nfunction folderLabel(folder: string): string {\n return folder.endsWith(\"/\") ? folder : folder + \"/\";\n}\n\n/** Group paths by their immediate parent folder; root-level notes count under \"(root)\". */\nexport function countByFolder(paths: string[]): FolderCount[] {\n const counts = new Map<string, number>();\n for (const p of paths) {\n const lastSlash = p.lastIndexOf(\"/\");\n const folder = lastSlash === -1 ? \"(root)\" : p.slice(0, lastSlash);\n counts.set(folder, (counts.get(folder) ?? 0) + 1);\n }\n return [...counts.entries()]\n .map(([folder, count]) => ({ folder, count }))\n .sort((a, b) => b.count - a.count || a.folder.localeCompare(b.folder));\n}\n\n/** \"Omitted 106: a/ (41), b/ (9), … and 3 more folders (56 notes).\" — the counts always add up to the total. */\nexport function describeOmitted(omitted: string[]): string {\n const groups = countByFolder(omitted);\n const named = groups.slice(0, MAX_NAMED_FOLDERS);\n const rest = groups.slice(MAX_NAMED_FOLDERS);\n const parts = named.map((g) => `${g.folder === \"(root)\" ? \"(root)\" : folderLabel(g.folder)} (${g.count})`);\n let text = `Omitted ${omitted.length}: ${parts.join(\", \")}`;\n if (rest.length > 0) {\n const restNotes = rest.reduce((sum, g) => sum + g.count, 0);\n text += `, and ${plural(rest.length, \"more folder\")} (${plural(restNotes, \"note\")})`;\n }\n return text + \".\";\n}\n\n/** Appended to every response while the index is not known to be complete. */\nexport function describeIndexState(index: IndexStatus): string {\n const caveat = index.servedByVault\n ? \"this list was read directly from the vault\"\n : \"this list may be incomplete\";\n switch (index.state) {\n case \"ready\":\n return \"\";\n case \"building\":\n return ` Index: catching up (${plural(index.size, \"note\")} indexed so far); ${caveat}.`;\n case \"failed\":\n return ` Index: rebuild failed at startup (see server log); ${index.servedByVault ? caveat : \"this list may be incomplete or stale\"}.`;\n }\n}\n\n/**\n * \"vault has N notes\" / \"folder has N notes\" — only when the number can be\n * trusted: the index is ready, or the notes came straight from the vault.\n * While the index is still building, its size is a partial count and the\n * index caveat carries it instead.\n */\nfunction describeScopeCount(s: Pick<ListingSummary, \"vaultTotal\" | \"folder\" | \"folderTotal\" | \"index\">): string {\n if (s.index.state !== \"ready\" && !s.index.servedByVault) return \"\";\n if (s.folder) return s.folderTotal != null ? `folder has ${plural(s.folderTotal, \"note\")}` : \"\";\n return s.vaultTotal != null ? `vault has ${plural(s.vaultTotal, \"note\")}` : \"\";\n}\n\n/** Response for a listing with zero matches. */\nexport function describeNoMatch(s: Omit<ListingSummary, \"shown\" | \"matched\" | \"omitted\" | \"sortBy\" | \"limit\">): string {\n const indexNote = describeIndexState(s.index);\n if (s.filters.length === 0) {\n if (s.folder) return `No notes found in folder: ${s.folder}${indexNote}`;\n return `Vault is empty.${indexNote}`;\n }\n const count = describeScopeCount(s);\n const scope = (s.folder ? ` in folder \"${folderLabel(s.folder)}\"` : \"\") + (count ? ` (${count})` : \"\");\n return `No notes match ${s.filters.join(\", \")}${scope}.${indexNote}`;\n}\n\n/**\n * First line of a non-empty listing. Always present, so the index state and\n * the filter scope are visible even when nothing was cut.\n */\nexport function describeListing(s: ListingSummary): string {\n const truncated = s.matched > s.shown;\n // \"5 notes match name=…\" reads as a sentence; \"Showing 100 of 150 notes matching …\" needs the participle.\n const verb = truncated ? \"matching\" : s.matched === 1 ? \"matches\" : \"match\";\n const filterClause = s.filters.length > 0 ? ` ${verb} ${s.filters.join(\", \")}` : \"\";\n const folderClause = s.folder ? ` in folder \"${folderLabel(s.folder)}\"` : \"\";\n const scopeParts: string[] = [];\n const count = s.filters.length > 0 || s.folder ? describeScopeCount(s) : \"\";\n if (count) scopeParts.push(count);\n // Every source (index, CouchDB enumeration, local glob) sorts by path with localeCompare, so \"sorted by name\" is literal.\n scopeParts.push(`sorted by ${s.sortBy}`);\n if (truncated) scopeParts.push(`limit=${s.limit}`);\n const scope = ` (${scopeParts.join(\", \")})`;\n\n let line = truncated\n ? `Showing ${s.shown} of ${plural(s.matched, \"note\")}${filterClause}${folderClause}${scope}.`\n : `${plural(s.matched, \"note\")}${filterClause}${folderClause}${scope}.`;\n if (truncated) {\n const hint = s.folder || s.filters.length > 0 ? \"Raise `limit` or narrow the filter.\" : \"Raise `limit` or add a `folder` filter.\";\n line += ` ${describeOmitted(s.omitted)} ${hint}`;\n }\n return line + describeIndexState(s.index);\n}\n"],"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;AA+BxB,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;AA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sBAAsB,OAA4C,sBAAsB,IAAI,EAAE;AAG1G,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACtC,UAAQ,MAAM,wBAAwB,GAAG;AAC7C,CAAC;","names":["timingSafeEqual","createHash","client","readFile","writeFile","mkdir","chmod","dirname","randomBytes","randomBytes","readFile","mkdir","dirname","writeFile","chmod","server","vault","searchIndex","debugLogging","createHash","timingSafeEqual"]}
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
import {
|
|
8
8
|
__reExport,
|
|
9
9
|
parseFrontmatterAndLinks
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-43MP6CJE.js";
|
|
11
11
|
|
|
12
12
|
// lib/livesync-commonlib/src/common/types.ts
|
|
13
13
|
import {
|
|
@@ -10220,4 +10220,4 @@ var Vault = class _Vault {
|
|
|
10220
10220
|
export {
|
|
10221
10221
|
Vault
|
|
10222
10222
|
};
|
|
10223
|
-
//# sourceMappingURL=vault-
|
|
10223
|
+
//# sourceMappingURL=vault-YGHHZZZQ.js.map
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
|
|
4
4
|
import {
|
|
5
5
|
parseFrontmatterAndLinks
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-43MP6CJE.js";
|
|
7
7
|
|
|
8
8
|
// src/vault-local.ts
|
|
9
9
|
import { readFile, writeFile, unlink, mkdir, stat, realpath, rename } from "fs/promises";
|
|
@@ -131,4 +131,4 @@ var LocalVault = class {
|
|
|
131
131
|
export {
|
|
132
132
|
LocalVault
|
|
133
133
|
};
|
|
134
|
-
//# sourceMappingURL=vault-local-
|
|
134
|
+
//# sourceMappingURL=vault-local-S53KTNRT.js.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parse.ts"],"sourcesContent":["/**\n * Parse Obsidian markdown content for frontmatter, tags, and links.\n */\n\nexport interface NoteMetadata {\n frontmatter: Record<string, string>;\n tags: string[];\n links: string[];\n}\n\nexport function parseFrontmatterAndLinks(content: string): NoteMetadata {\n const frontmatter: Record<string, any> = {};\n const tags = new Set<string>();\n const links: string[] = [];\n\n // Parse YAML frontmatter\n if (content.startsWith(\"---\\n\")) {\n const end = content.indexOf(\"\\n---\", 4);\n if (end !== -1) {\n const yaml = content.slice(4, end);\n let inTagsList = false;\n for (const line of yaml.split(\"\\n\")) {\n // Multi-line tags list item: \" - tagname\"\n if (inTagsList) {\n const listItem = line.match(/^\\s+-\\s+(.+)/);\n if (listItem) {\n const trimmed = listItem[1].trim();\n if (trimmed) tags.add(trimmed);\n continue;\n }\n inTagsList = false;\n }\n\n const match = line.match(/^(\\w[\\w-]*)\\s*:\\s*(.+)/);\n if (match) {\n frontmatter[match[1]] = match[2].trim();\n }\n // Frontmatter tags (inline: [a, b] or start of multi-line list)\n if (/^tags\\s*:/.test(line)) {\n const value = line.replace(/^tags\\s*:\\s*/, \"\").trim();\n if (value) {\n // Inline: tags: [a, b] or tags: a, b\n const tagValues = value.replace(/[[\\]]/g, \"\");\n for (const t of tagValues.split(\",\")) {\n const trimmed = t.trim();\n if (trimmed) tags.add(trimmed);\n }\n } else {\n // Multi-line list follows\n inTagsList = true;\n }\n }\n }\n }\n }\n\n // Inline #tags\n for (const match of content.matchAll(/(^|\\s)#([\\w/-]+)/g)) {\n tags.add(match[2]);\n }\n\n // [[wikilinks]]\n for (const match of content.matchAll(/\\[\\[([^\\]|]+)(?:\\|[^\\]]+)?\\]\\]/g)) {\n links.push(match[1]);\n }\n\n // [markdown links](path.md)\n for (const match of content.matchAll(/\\[([^\\]]+)\\]\\(([^)]+\\.md)\\)/g)) {\n links.push(match[2]);\n }\n\n return { frontmatter, tags: [...tags], links: [...new Set(links)] };\n}\n\nexport function extractSnippet(content: string, query: string, context = 80): string {\n const lower = content.toLowerCase();\n\n // Try exact phrase first\n let idx = lower.indexOf(query.toLowerCase());\n\n // Try to find the smallest span containing all query words\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).map((w) => w.toLowerCase());\n if (words.length > 1) {\n let bestStart = -1;\n let bestLen = Infinity;\n // For each occurrence of the first word, find the nearest span containing all words\n const first = words[0];\n let pos = 0;\n while (pos < lower.length) {\n const start = lower.indexOf(first, pos);\n if (start === -1) break;\n // Find last position needed to include all words from this start\n let spanEnd = start + first.length;\n let allFound = true;\n for (let i = 1; i < words.length; i++) {\n const wi = lower.indexOf(words[i], Math.max(0, start - 200));\n if (wi === -1) { allFound = false; break; }\n spanEnd = Math.max(spanEnd, wi + words[i].length);\n }\n if (allFound) {\n const spanStart = Math.min(start, ...words.map((w) => lower.indexOf(w, Math.max(0, start - 200))).filter((i) => i >= 0));\n const len = spanEnd - spanStart;\n if (len < bestLen) { bestStart = spanStart; bestLen = len; }\n }\n pos = start + 1;\n }\n if (bestStart >= 0 && bestLen <= 500) idx = bestStart;\n }\n }\n\n // Fall back to longest matching word\n if (idx === -1) {\n const words = query.split(/\\s+/).filter((w) => w.length >= 3).sort((a, b) => b.length - a.length);\n for (const word of words) {\n idx = lower.indexOf(word.toLowerCase());\n if (idx !== -1) break;\n }\n }\n\n if (idx === -1) {\n return content.slice(0, 160) + (content.length > 160 ? \"...\" : \"\");\n }\n const start = Math.max(0, idx - context);\n const end = Math.min(content.length, idx + query.length + context);\n return (start > 0 ? \"...\" : \"\") + content.slice(start, end) + (end < content.length ? \"...\" : \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAUO,SAAS,yBAAyB,SAA+B;AACpE,QAAM,cAAmC,CAAC;AAC1C,QAAM,OAAO,oBAAI,IAAY;AAC7B,QAAM,QAAkB,CAAC;AAGzB,MAAI,QAAQ,WAAW,OAAO,GAAG;AAC7B,UAAM,MAAM,QAAQ,QAAQ,SAAS,CAAC;AACtC,QAAI,QAAQ,IAAI;AACZ,YAAM,OAAO,QAAQ,MAAM,GAAG,GAAG;AACjC,UAAI,aAAa;AACjB,iBAAW,QA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