obsidian-sync-mcp 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/note-path.ts","../src/attachment-path.ts","../src/parse.ts","../src/vault-backend.ts"],"sourcesContent":["/**\n * Shared validation for note paths, applied by both the CouchDB and local\n * backends before any read, write, delete or move.\n *\n * The note model is markdown-only: `list_notes` only ever surfaces `*.md`\n * files; binary attachments have their own validator (attachment-path.ts)\n * built on validateVaultPathShape below. Enforcing that here keeps\n * the tools from reaching anything that isn't a note, which closes two real\n * problems:\n * - CouchDB mode: a path like `obsydian_livesync_version` or a `ix:`/`ps:`\n * prefixed id would otherwise become a document id and overwrite LiveSync's\n * own control documents, stopping sync on every device.\n * - Local mode: a path like `.obsidian/plugins/x/main.js` would otherwise\n * write executable plugin code into the vault, and `.obsidian/.../data.json`\n * would expose LiveSync credentials.\n *\n * Rules: vault-relative, ends in `.md`, no `..`, no leading `/`, no `:` (its\n * only use here is LiveSync's internal id prefixes), no NUL, and no path\n * segment (split on either slash) that starts with `.` (hidden files and the\n * `.obsidian` config dir). Root-level LiveSync control flag files are also\n * rejected even though they are `.md`.\n */\n\n// LiveSync's note-shaped control files, all at the vault root. Writing one and\n// letting it sync triggers a vault-wide rebuild/fetch on every device, so they\n// are not writable through the note tools. Compared lowercase because LiveSync\n// lowercases ids when case-insensitive handling is on.\nconst RESERVED_ROOT_FILES = new Set([\n \"redflag.md\",\n \"redflag2.md\",\n \"redflag3.md\",\n \"flag_rebuild.md\",\n \"flag_fetch.md\",\n]);\n\n/**\n * The rules every vault path must pass, note or attachment: vault-relative,\n * no `..`, no leading `/`, no `:`, no NUL, no empty segment and no segment\n * starting with `.`. `kind` only names the path in error messages.\n */\nexport function validateVaultPathShape(path: string, kind: string): void {\n const problem = vaultPathShapeProblem(path);\n if (problem !== null) throw new Error(`Invalid ${kind} path${problem}`);\n}\n\n/**\n * Why `path` fails validateVaultPathShape, as the suffix of its error message\n * (\"\" when there is no detail), or null when it passes. Non-throwing so hot\n * paths like link parsing don't pay for an exception per rejected target.\n */\nexport function vaultPathShapeProblem(path: string): string | null {\n if (!path || path.length > 1000) return \"\";\n if (path.startsWith(\"/\") || path.includes(\"\\0\") || path.includes(\"..\")) return \"\";\n if (path.includes(\":\")) return \": ':' is not allowed\";\n for (const segment of path.split(/[/\\\\]/)) {\n if (segment === \"\") return \": empty path segment\";\n if (segment.startsWith(\".\")) return \": dot-folders and hidden files (e.g. .obsidian) are not allowed\";\n }\n return null;\n}\n\nexport function validateNotePath(path: string): void {\n validateVaultPathShape(path, \"note\");\n if (!path.endsWith(\".md\")) {\n throw new Error(\"Invalid note path: must be a vault-relative path ending in .md\");\n }\n // Root-level control flag files (no folder segment).\n if (!path.includes(\"/\") && !path.includes(\"\\\\\") && RESERVED_ROOT_FILES.has(path.toLowerCase())) {\n throw new Error(\"Invalid note path: reserved LiveSync control file\");\n }\n}\n\n/** Boolean form of validateNotePath, for filtering listings and the index. */\nexport function isValidNotePath(path: string): boolean {\n try {\n validateNotePath(path);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Validation for attachment paths (images, PDFs, audio, video).\n *\n * Attachments get the same shape rules as notes (see note-path.ts) — no `..`,\n * no `:`, no dot-folders — so they cannot reach LiveSync control documents or\n * `.obsidian/`. On top of that the extension must be on an allowlist of binary\n * media types Obsidian can embed. Text-like formats (`.md`, `.svg`, `.html`,\n * `.js`, `.json`, `.css`, `.canvas`, ...) are never attachments: they are\n * either notes, executable in Obsidian, or stored by LiveSync as plain text.\n */\n\nimport { validateVaultPathShape, vaultPathShapeProblem } from \"./note-path.js\";\n\n/** Binary formats Obsidian embeds natively. SVG is left out on purpose: it is text and can carry script. */\nexport const SUPPORTED_ATTACHMENT_EXTENSIONS: readonly string[] = [\n // images\n \"avif\", \"bmp\", \"gif\", \"jpeg\", \"jpg\", \"png\", \"webp\",\n // audio\n \"flac\", \"m4a\", \"mp3\", \"ogg\", \"wav\", \"3gp\",\n // video\n \"mkv\", \"mov\", \"mp4\", \"ogv\", \"webm\",\n // documents\n \"pdf\",\n];\n\n/**\n * Parse ATTACHMENT_EXTENSIONS into an allowlist. Unset means every supported\n * extension. The variable can only narrow the list: an unsupported entry is an\n * error rather than a silent widening of what may be written.\n */\nexport function parseAttachmentExtensions(raw: string | undefined): Set<string> {\n if (raw === undefined || raw.trim() === \"\") return new Set(SUPPORTED_ATTACHMENT_EXTENSIONS);\n const requested = raw\n .split(\",\")\n .map((e) => e.trim().toLowerCase().replace(/^\\./, \"\"))\n .filter(Boolean);\n const unsupported = requested.filter((e) => !SUPPORTED_ATTACHMENT_EXTENSIONS.includes(e));\n if (unsupported.length > 0) {\n throw new Error(\n `ATTACHMENT_EXTENSIONS contains unsupported extensions: ${unsupported.join(\", \")}. ` +\n `Supported: ${SUPPORTED_ATTACHMENT_EXTENSIONS.join(\", \")}.`,\n );\n }\n return new Set(requested);\n}\n\n/** Lowercased extension without the dot, or \"\" when there is none. */\nexport function attachmentExtension(path: string): string {\n const name = path.split(/[/\\\\]/).pop() ?? \"\";\n const dot = name.lastIndexOf(\".\");\n return dot <= 0 ? \"\" : name.slice(dot + 1).toLowerCase();\n}\n\nconst SUPPORTED = new Set(SUPPORTED_ATTACHMENT_EXTENSIONS);\n\nexport function validateAttachmentPath(path: string, allowed: ReadonlySet<string> = SUPPORTED): void {\n validateVaultPathShape(path, \"attachment\");\n const ext = attachmentExtension(path);\n if (!ext || !allowed.has(ext)) {\n throw new Error(\n `Invalid attachment path: extension must be one of ${[...allowed].sort().join(\", \")}`,\n );\n }\n}\n\n/** Boolean form of validateAttachmentPath. Doesn't throw: link parsing calls it for every link target. */\nexport function isValidAttachmentPath(path: string, allowed: ReadonlySet<string> = SUPPORTED): boolean {\n const ext = attachmentExtension(path);\n return !!ext && allowed.has(ext) && vaultPathShapeProblem(path) === null;\n}\n","/**\n * Parse Obsidian markdown content for frontmatter, tags, and links.\n */\n\nimport { isValidAttachmentPath } from \"./attachment-path.js\";\n\nexport interface NoteMetadata {\n frontmatter: Record<string, string>;\n tags: string[];\n links: string[];\n}\n\n// Link patterns. Each part stops at a bracket, paren or newline, so a failed\n// match only scans up to the next one. Otherwise it rescans the rest of the\n// note, which is quadratic on input like \"[\".repeat(20000), and parsing is\n// synchronous and runs on every note at startup. No length cap is needed on\n// top: attachment targets are capped by isValidAttachmentPath after decoding.\n\n// [[wikilinks]]. A #heading, #^block or #page=2 suffix points into the target,\n// so [[Note#Heading]] links Note and ![[paper.pdf#page=2]] embeds paper.pdf.\n// [[#Heading]] (same note) is not a link.\nconst WIKILINK = /\\[\\[([^[\\]|#\\n]+)(?:#[^[\\]|\\n]*)?(?:\\|[^[\\]\\n]*)?\\]\\]/g;\n\n// Markdown link text: plain characters, or one level of [brackets], so\n// [see [1]](note.md) and [![thumb](t.png)](full.png) parse. The two\n// alternatives never match the same character, so this adds no backtracking.\nconst LINK_LABEL = String.raw`[^[\\]\\n]|\\[[^[\\]\\n]*\\]`;\n\n// [markdown links](path.md), also with a #heading: [x](path.md#Heading) links path.md.\nconst NOTE_LINK = new RegExp(String.raw`\\[(?:${LINK_LABEL})+\\]\\(([^()#\\n]+\\.md)(?:#[^()\\n]*)?\\)`, \"g\");\n\n// Markdown links and embeds to attachments: ![](Attachments/shot.png),\n// [report](<docs/Q1 report.pdf>), ![alt](my%20image.png \"title\").\nconst ATTACHMENT_LINK = new RegExp(String.raw`\\[((?:${LINK_LABEL})*)\\]\\((<[^<>\\n]+>|[^()\\s]+)(?:\\s+\"[^\"\\n]*\")?\\)`, \"g\");\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 for (const match of content.matchAll(WIKILINK)) links.push(match[1]);\n for (const match of content.matchAll(NOTE_LINK)) links.push(match[1]);\n addAttachmentLinks(content, links);\n\n return { frontmatter, tags: [...tags], links: [...new Set(links)] };\n}\n\n/**\n * Add the attachment targets of markdown links in `text` to `links`, recorded\n * URL-decoded so list_attachments can tell which files are still used. Also\n * looks inside each link's text once, since matches don't overlap and the\n * outer link of [![thumb](t.png)](full.png) would hide the inner image.\n */\nfunction addAttachmentLinks(text: string, links: string[], nested = false): void {\n for (const match of text.matchAll(ATTACHMENT_LINK)) {\n if (!nested && match[1].includes(\"[\")) addAttachmentLinks(match[1], links, true);\n // Drop a #page=2 fragment, as for wikilinks. Before decoding, since a\n // literal # in a file name is written %23.\n let target = match[2].replace(/^<|>$/g, \"\").replace(/#.*$/, \"\");\n if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.endsWith(\".md\")) continue;\n // Obsidian URL-decodes markdown link targets (a literal % is written %25).\n try { target = decodeURIComponent(target); } catch { continue; }\n target = target.replace(/^(\\.\\.?\\/)+/, \"\");\n if (isValidAttachmentPath(target)) links.push(target);\n }\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","import type { NoteMetadata } from \"./parse.js\";\n\nexport interface NoteInfo extends NoteMetadata {\n path: string;\n size: number;\n ctime: number;\n mtime: number;\n}\n\nexport interface NoteListing {\n path: string;\n mtime: number;\n}\n\nexport interface AttachmentInfo {\n path: string;\n size: number;\n ctime: number;\n mtime: number;\n}\n\n/** An attachment appeared or changed (info), or was deleted (null). */\nexport type AttachmentChangeCallback = (path: string, info: { size: number; mtime: number } | null) => void;\n\nexport interface WriteOptions {\n /** Replace an existing file. Default false. */\n overwrite?: boolean;\n}\n\nexport interface MoveOptions extends WriteOptions {\n /**\n * Largest file a backend may load into memory to move it. CouchDB mode\n * copies the bytes (read, write, delete); local mode renames and ignores it.\n */\n maxBytes?: number;\n}\n\n/** A move would have to load a file larger than `MoveOptions.maxBytes`. */\nexport class AttachmentTooLargeError extends Error {\n constructor(readonly path: string, readonly size: number, readonly limit: number) {\n super(`Attachment is ${size} bytes, over the ${limit}-byte limit for moving it: ${path}`);\n this.name = \"AttachmentTooLargeError\";\n }\n}\n\n/** A copying move wrote the destination but could not delete the source, so both exist. */\nexport class AttachmentMoveIncompleteError extends Error {\n constructor(readonly from: string, readonly to: string) {\n super(`Copied ${from} to ${to}, but could not delete ${from}`);\n this.name = \"AttachmentMoveIncompleteError\";\n }\n}\n\n/** A write or move without `overwrite` found a file already at the destination. */\nexport class AttachmentExistsError extends Error {\n constructor(readonly path: string) {\n super(`Attachment already exists: ${path}`);\n this.name = \"AttachmentExistsError\";\n }\n}\n\nexport interface VaultBackend {\n init(): Promise<void>;\n close(): Promise<void>;\n readNote(path: string): Promise<string | null>;\n writeNote(path: string, content: string): Promise<boolean>;\n deleteNote(path: string): Promise<boolean>;\n moveNote(from: string, to: string): Promise<boolean>;\n getMetadata(path: string): Promise<NoteInfo | null>;\n listNotes(folder?: string): Promise<string[]>;\n listNotesWithMtime(folder?: string): Promise<NoteListing[]>;\n /**\n * Binary attachments (see attachment-path.ts). Paths are validated by the backend too.\n * Without `overwrite`, writing or moving onto an existing file throws\n * AttachmentExistsError, checked in the same step as the write.\n */\n writeAttachment(path: string, data: Uint8Array, options?: WriteOptions): Promise<boolean>;\n deleteAttachment(path: string): Promise<boolean>;\n moveAttachment(from: string, to: string, options?: MoveOptions): Promise<boolean>;\n getAttachmentInfo(path: string): Promise<AttachmentInfo | null>;\n /** Every attachment in the vault. Local mode only; CouchDB mode learns them from the change feed. */\n listAttachments?(): Promise<AttachmentInfo[]>;\n /** `onAttachment` also reports attachment changes, from metadata only (no chunks are loaded). */\n watchChanges?(callback: (path: string, content: string | null, mtime?: number, seq?: string | number) => void, onAttachment?: AttachmentChangeCallback): void;\n /**\n * Catch up on changes since a sequence. Returns the new sequence. CouchDB only.\n * `stats.unreadable` counts documents that could not be decrypted or loaded\n * and were therefore skipped — the caller reports them so \"caught up\" never\n * hides a silent miss.\n */\n catchUp?(since: string, callback: (path: string, content: string | null, mtime?: number) => void, onBatch?: (since: string, processed: number) => Promise<void>, stats?: { unreadable: number }, onAttachment?: AttachmentChangeCallback): Promise<string>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAOM,SAAS,uBAAuB,MAAc,MAAoB;AACrE,QAAM,UAAU,sBAAsB,IAAI;AAC1C,MAAI,YAAY,KAAM,OAAM,IAAI,MAAM,WAAW,IAAI,QAAQ,OAAO,EAAE;AAC1E;AAOO,SAAS,sBAAsB,MAA6B;AAC/D,MAAI,CAAC,QAAQ,KAAK,SAAS,IAAM,QAAO;AACxC,MAAI,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,KAA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AK,IAAI,KAAK,MAAM,OAAO,GAAG,EAAE,QAAQ,UAAU,GAAG;AAChF,WAAO;AACP,QAAI,IAAI;AAAA,EACZ;AACA,SAAO,SAAS,KAAK,MAAM,IAAI;AACnC;;;ACxJO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAC/C,YAAqB,MAAuB,MAAuB,OAAe;AAC9E,UAAM,iBAAiB,IAAI,oBAAoB,KAAK,8BAA8B,IAAI,EAAE;AADvE;AAAuB;AAAuB;AAE/D,SAAK,OAAO;AAAA,EAChB;AACJ;AAGO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACrD,YAAqB,MAAuB,IAAY;AACpD,UAAM,UAAU,IAAI,OAAO,EAAE,0BAA0B,IAAI,EAAE;AAD5C;AAAuB;AAExC,SAAK,OAAO;AAAA,EAChB;AACJ;AAGO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC7C,YAAqB,MAAc;AAC/B,UAAM,8BAA8B,IAAI,EAAE;AADzB;AAEjB,SAAK,OAAO;AAAA,EAChB;AACJ;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vault-local.ts"],"sourcesContent":["import { readFile, writeFile, unlink, mkdir, stat, lstat, realpath, rename, link, copyFile } from \"fs/promises\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { realpathSync, constants } from \"fs\";\nimport { glob } from \"fs/promises\";\nimport { parseFrontmatterAndLinks } from \"./parse.js\";\nimport { validateNotePath, isValidNotePath } from \"./note-path.js\";\nimport { validateAttachmentPath, isValidAttachmentPath } from \"./attachment-path.js\";\nimport { AttachmentExistsError, AttachmentMoveIncompleteError, type VaultBackend, type NoteInfo, type NoteListing, type AttachmentInfo, type WriteOptions, type MoveOptions } from \"./vault-backend.js\";\n\n// Not defined on Windows, which has no symlinks a non-admin can create anyway.\nconst NOFOLLOW = constants.O_NOFOLLOW ?? 0;\n\nexport class LocalVault implements VaultBackend {\n private root: string;\n\n constructor(vaultPath: string) {\n this.root = realpathSync(resolve(vaultPath));\n }\n\n private async safePath(path: string, kind: \"note\" | \"attachment\" | \"folder\" = \"folder\", { noSymlink = false } = {}): Promise<string> {\n // Note operations must target a real note (.md, no dot-folders, etc.)\n // and attachment operations an allowed media file; folder listing\n // passes a directory and skips this.\n if (kind === \"note\") validateNotePath(path);\n if (kind === \"attachment\") validateAttachmentPath(path);\n const full = resolve(this.root, path);\n // Lexical check first (catches ../ without hitting disk)\n if (!full.startsWith(this.root + sep)) {\n throw new Error(\"Path traversal blocked\");\n }\n // Resolve symlinks and re-check (catches symlink escapes). A path\n // that doesn't exist yet resolves through its nearest existing\n // ancestor, so a symlinked parent can't redirect a write either.\n const real = await this.resolveExisting(full);\n if (!real.startsWith(this.root + sep)) {\n throw new Error(\"Path traversal blocked\");\n }\n // The name was validated, but a symlink inside the vault can point at\n // a note, a dot-folder or another type, so the target must pass too.\n if (kind !== \"folder\" && !this.isValidKind(relative(this.root, real), kind)) {\n throw new Error(\"Path traversal blocked\");\n }\n // realpath fails with ENOENT on a dangling symlink, so it resolves as\n // a new file, but a write would follow it and create outside the vault.\n if (await this.hasDanglingSymlink(full)) {\n throw new Error(\"Path traversal blocked\");\n }\n // Writing or deleting through a symlink would act on its target, a\n // different path from the one the caller named.\n if (noSymlink && (await this.isSymlink(full))) {\n throw new Error(`Refusing to modify a symlink: ${path}`);\n }\n return real;\n }\n\n /**\n * mkdir for an attachment write to `fullPath` (from safePath), then check\n * the path again: a folder swapped for a symlink since would redirect the\n * write. Returns false when mkdir fails.\n */\n private async mkdirChecked(path: string, fullPath: string): Promise<boolean> {\n try {\n await mkdir(dirname(fullPath), { recursive: true });\n } catch {\n return false;\n }\n if ((await this.safePath(path, \"attachment\", { noSymlink: true })) !== fullPath) {\n throw new Error(\"Path traversal blocked\");\n }\n return true;\n }\n\n private isValidKind(rel: string, kind: \"note\" | \"attachment\"): boolean {\n const path = rel.split(sep).join(\"/\");\n return kind === \"note\" ? isValidNotePath(path) : isValidAttachmentPath(path);\n }\n\n private async isSymlink(full: string): Promise<boolean> {\n try {\n return (await lstat(full)).isSymbolicLink();\n } catch (e: any) {\n if (e.code === \"ENOENT\") return false;\n throw e;\n }\n }\n\n /**\n * realpath of `full`, or for a path that doesn't exist yet the realpath of\n * its nearest existing ancestor joined with the rest.\n */\n private async resolveExisting(full: string): Promise<string> {\n const rest: string[] = [];\n let current = full;\n for (;;) {\n try {\n return join(await realpath(current), ...rest);\n } catch (e: any) {\n if (e.code !== \"ENOENT\") throw e;\n const parent = dirname(current);\n if (parent === current) return full; // reached filesystem root\n rest.unshift(basename(current));\n current = parent;\n }\n }\n }\n\n /** Whether `full` or one of its ancestors below the root is a symlink to nothing. */\n private async hasDanglingSymlink(full: string): Promise<boolean> {\n for (let current = full; current !== this.root; current = dirname(current)) {\n let s;\n try {\n s = await lstat(current);\n } catch (e: any) {\n if (e.code === \"ENOENT\") continue;\n throw e;\n }\n // The nearest existing entry decides: anything but a symlink is\n // real, and a resolvable symlink was checked by resolveExisting.\n if (!s.isSymbolicLink()) return false;\n try {\n await realpath(current);\n return false;\n } catch (e: any) {\n if (e.code === \"ENOENT\") return true;\n throw e;\n }\n }\n return false;\n }\n\n async init(): Promise<void> {}\n\n async close(): Promise<void> {}\n\n async readNote(path: string): Promise<string | null> {\n const fullPath = await this.safePath(path, \"note\");\n try {\n return await readFile(fullPath, \"utf-8\");\n } catch {\n return null;\n }\n }\n\n async writeNote(path: string, content: string): Promise<boolean> {\n const fullPath = await this.safePath(path, \"note\");\n try {\n await mkdir(dirname(fullPath), { recursive: true });\n await writeFile(fullPath, content, \"utf-8\");\n return true;\n } catch {\n return false;\n }\n }\n\n async deleteNote(path: string): Promise<boolean> {\n const fullPath = await this.safePath(path, \"note\");\n try {\n await unlink(fullPath);\n return true;\n } catch {\n return false;\n }\n }\n\n async moveNote(from: string, to: string): Promise<boolean> {\n const fromPath = await this.safePath(from, \"note\");\n const toPath = await this.safePath(to, \"note\");\n if (fromPath === toPath) {\n // Same file: a no-op, or a case-only rename on a case-insensitive\n // filesystem, where toPath is the realpath and has the old case.\n try {\n await rename(fromPath, resolve(this.root, to));\n return true;\n } catch {\n return false;\n }\n }\n try {\n await mkdir(dirname(toPath), { recursive: true });\n await rename(fromPath, toPath);\n return true;\n } catch (e: any) {\n if (e.code === \"EXDEV\") {\n // Cross-device: fall back to copy-delete\n const content = await this.readNote(from);\n if (content === null) return false;\n const wrote = await this.writeNote(to, content);\n if (!wrote) return false;\n return await this.deleteNote(from);\n }\n return false;\n }\n }\n\n async getMetadata(path: string): Promise<NoteInfo | null> {\n const fullPath = await this.safePath(path, \"note\");\n try {\n const [content, s] = await Promise.all([\n readFile(fullPath, \"utf-8\"),\n stat(fullPath),\n ]);\n return {\n path,\n size: s.size,\n ctime: s.birthtimeMs,\n mtime: s.mtimeMs,\n ...parseFrontmatterAndLinks(content),\n };\n } catch {\n return null;\n }\n }\n\n async listNotes(folder?: string): Promise<string[]> {\n const notes = await this.listNotesWithMtime(folder);\n return notes.map((n) => n.path);\n }\n\n async listNotesWithMtime(folder?: string): Promise<NoteListing[]> {\n if (folder && !folder.endsWith(\"/\") && !folder.endsWith(\"\\\\\")) folder += \"/\";\n const searchDir = folder ? await this.safePath(folder) : this.root;\n const entries: string[] = [];\n try {\n for await (const entry of glob(\"**/*.md\", { cwd: searchDir })) {\n const full = folder ? `${folder}${entry}` : entry;\n if (!isValidNotePath(full)) continue;\n entries.push(full);\n }\n } catch {\n return [];\n }\n const results = await Promise.all(\n entries.map(async (p) => {\n try {\n const s = await stat(resolve(this.root, p));\n return { path: p, mtime: s.mtimeMs };\n } catch {\n return { path: p, mtime: 0 };\n }\n }),\n );\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n\n async writeAttachment(path: string, data: Uint8Array, { overwrite = false }: WriteOptions = {}): Promise<boolean> {\n const fullPath = await this.safePath(path, \"attachment\", { noSymlink: true });\n if (!(await this.mkdirChecked(path, fullPath))) return false;\n try {\n // O_EXCL fails if the file exists, in the same step as the create,\n // so two concurrent creates can't both succeed. O_NOFOLLOW refuses\n // a symlink put in place since safePath checked.\n const flag = constants.O_WRONLY | constants.O_CREAT | (overwrite ? constants.O_TRUNC : constants.O_EXCL) | NOFOLLOW;\n await writeFile(fullPath, data, { flag });\n return true;\n } catch (e: any) {\n if (e.code === \"EEXIST\") throw new AttachmentExistsError(path);\n if (e.code === \"ELOOP\") throw new Error(`Refusing to modify a symlink: ${path}`);\n return false;\n }\n }\n\n async deleteAttachment(path: string): Promise<boolean> {\n const fullPath = await this.safePath(path, \"attachment\", { noSymlink: true });\n try {\n await unlink(fullPath);\n return true;\n } catch {\n return false;\n }\n }\n\n async moveAttachment(from: string, to: string, { overwrite = false }: MoveOptions = {}): Promise<boolean> {\n const fromPath = await this.safePath(from, \"attachment\", { noSymlink: true });\n const toPath = await this.safePath(to, \"attachment\", { noSymlink: true });\n if (fromPath === toPath) {\n // Same file, which link below would refuse with EEXIST. rename is a\n // no-op here, or the case-only rename on a case-insensitive filesystem.\n try {\n await rename(fromPath, resolve(this.root, to));\n return true;\n } catch {\n return false;\n }\n }\n if (!(await this.mkdirChecked(to, toPath))) return false;\n try {\n if (overwrite) {\n await rename(fromPath, toPath);\n return true;\n }\n // rename would replace an existing destination; link fails with\n // EEXIST instead.\n await link(fromPath, toPath);\n } catch (e: any) {\n if (e.code === \"EEXIST\") throw new AttachmentExistsError(to);\n // Cross-device, or a filesystem without hard links: copy, then delete.\n if (![\"EXDEV\", \"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\"].includes(e.code)) return false;\n try {\n await copyFile(fromPath, toPath, overwrite ? 0 : constants.COPYFILE_EXCL);\n } catch (copyErr: any) {\n if (copyErr.code === \"EEXIST\") throw new AttachmentExistsError(to);\n return false;\n }\n }\n // The destination now exists, by link or copy; only the source is left.\n try {\n await unlink(fromPath);\n return true;\n } catch {\n throw new AttachmentMoveIncompleteError(from, to);\n }\n }\n\n async getAttachmentInfo(path: string): Promise<AttachmentInfo | null> {\n const fullPath = await this.safePath(path, \"attachment\");\n try {\n const s = await stat(fullPath);\n if (!s.isFile()) return null;\n return { path, size: s.size, ctime: s.birthtimeMs, mtime: s.mtimeMs };\n } catch {\n return null;\n }\n }\n\n async listAttachments(): Promise<AttachmentInfo[]> {\n const results: AttachmentInfo[] = [];\n try {\n // Dot-folders (.obsidian, .trash, .git) are never attachments; skip them while walking.\n for await (const entry of glob(\"**/*\", { cwd: this.root, exclude: (p: any) => String(typeof p === \"string\" ? p : p.name).split(/[/\\\\]/).some((seg: string) => seg.startsWith(\".\")) })) {\n const path = entry.replace(/\\\\/g, \"/\");\n if (!isValidAttachmentPath(path)) continue;\n try {\n // A symlink out of the vault would leak the target's name and\n // size, and one to a note or dot-folder isn't an attachment.\n const real = await realpath(resolve(this.root, path));\n if (!real.startsWith(this.root + sep) || !this.isValidKind(relative(this.root, real), \"attachment\")) continue;\n const s = await stat(real);\n if (s.isFile()) results.push({ path, size: s.size, ctime: s.birthtimeMs, mtime: s.mtimeMs });\n } catch {\n // Vanished between listing and stat, or a dangling symlink.\n }\n }\n } catch {\n return [];\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,UAAU,WAAW,QAAQ,OAAO,MAAM,OAAO,UAAU,QAAQ,MAAM,gBAAgB;AAClG,SAAS,UAAU,SAAS,MAAM,UAAU,SAAS,WAAW;AAChE,SAAS,cAAc,iBAAiB;AACxC,SAAS,YAAY;AAOrB,IAAM,WAAW,UAAU,cAAc;AAElC,IAAM,aAAN,MAAyC;AAAA,EACpC;AAAA,EAER,YAAY,WAAmB;AAC3B,SAAK,OAAO,aAAa,QAAQ,SAAS,CAAC;AAAA,EAC/C;AAAA,EAEA,MAAc,SAAS,MAAc,OAAyC,UAAU,EAAE,YAAY,MAAM,IAAI,CAAC,GAAoB;AAIjI,QAAI,SAAS,OAAQ,kBAAiB,IAAI;AAC1C,QAAI,SAAS,aAAc,wBAAuB,IAAI;AACtD,UAAM,OAAO,QAAQ,KA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