diff --git a/README.md b/README.md index e72ccc7..5634fac 100644 --- a/README.md +++ b/README.md @@ -63,10 +63,14 @@ If the browser doesn't open, copy `http://localhost:4000` into any browser — i | Category | Extensions | |-----------|----------------------------------------------| | Markdown | `.md` `.markdown` `.mdx` `.txt` | -| Data | `.json` `.yaml` `.yml` | +| HTML | `.html` `.htm` (sandboxed iframe preview) | +| Diagrams | `.mmd` `.mermaid` | +| Data | `.json` `.jsonl` `.ndjson` `.yaml` `.yml` `.csv` `.tsv` | | Config | `.toml` `.ini` `.conf` `.env` `.cfg` `.properties` | +| Logs | `.log` | | Crontab | `.cron` `.crontab` (and files named `crontab`) | | Images | `.png` `.jpg` `.jpeg` `.gif` `.svg` `.webp` `.bmp` `.ico` | +| Videos | `.mp4` `.m4v` `.webm` `.ogv` `.mov` | | Office / iWork | `.xls` `.xlsx` `.ppt` `.pptx` `.numbers` `.pages` `.key` (listed, open in default app / download fallback for normal files; no direct WebView preview) | | PDF | `.pdf` (browser built-in viewer in an iframe; open in new tab / default app / download) | diff --git a/bin/mdv.mjs b/bin/mdv.mjs index 1d4c44d..5411b30 100755 --- a/bin/mdv.mjs +++ b/bin/mdv.mjs @@ -45,9 +45,15 @@ if (args.includes('--help') || args.includes('-h')) { Supported formats: Markdown .md .markdown .mdx .txt - Data .json .yaml .yml + HTML .html .htm + Diagrams .mmd .mermaid + Data .json .jsonl .ndjson .yaml .yml .csv .tsv Config .toml .ini .conf .env .cfg .properties + Logs .log + Crontab .cron .crontab crontab Images .png .jpg .jpeg .gif .svg .webp .bmp .ico + Videos .mp4 .m4v .webm .ogv .mov + Documents .pdf .xls .xlsx .ppt .pptx .numbers .pages .key Examples: docview # View current directory diff --git a/server.mjs b/server.mjs index d350280..5b0caba 100644 --- a/server.mjs +++ b/server.mjs @@ -1,5 +1,5 @@ import { createServer } from 'node:http'; -import { createReadStream, readFileSync } from 'node:fs'; +import { createReadStream, readFileSync, realpathSync } from 'node:fs'; import { readFile, readdir, stat, realpath, open } from 'node:fs/promises'; import { createInterface } from 'node:readline'; import { join, resolve, relative, extname, basename, dirname, sep } from 'node:path'; @@ -2013,7 +2013,9 @@ const server = createServer(async (req, res) => { const st = await stat(fullPath); if (st.size > MAX_SEARCH_FILE_BYTES) continue; const content = await readFileText(fullPath); - const lines = content.split('\n'); + // CRLF files would otherwise keep a trailing \r on every line, + // which breaks `$` anchors and leaks into the result text. + const lines = content.split(/\r?\n/); const matchingLines = regexSearch ? new Set(await regexSearch.findMatches(lines, 100 - results.length)) : null; @@ -2221,20 +2223,36 @@ const server = createServer(async (req, res) => { refreshDocviewIgnore(); const MARKDOWN_LIKE = new Set(['.md', '.markdown', '.mdx', '.txt']); - const targetName = basename(targetPath).replace(/\.[^.]+$/, ''); + const targetName = basename(targetPath); const backlinks = []; - function isLinkToTarget(link, sourcePath) { - if (!link) return false; - const linkPath = link.split('#')[0].replace(/^\.\//, ''); - if (!linkPath) return false; - if (linkPath === targetPath) return true; - const sourceDir = dirname(sourcePath); - const resolved = join(sourceDir, linkPath).replace(/\\/g, '/'); - if (resolved === targetPath) return true; - const linkName = basename(linkPath).replace(/\.[^.]+$/, ''); - if (linkName === targetName && !linkPath.includes('/')) return true; - return false; + // Mirror the viewer: Markdown destinations resolve like URLs against the + // source file and are percent-decoded (resolveDocumentResource), and wiki + // links default to `.md`. Only wiki links also match by name in any folder. + function isLinkToTarget(link, sourcePath, isWiki) { + let dest = link.trim(); + if (isWiki) { + dest = dest.split(/[?#]/)[0].trim(); + if (dest && !(dest.split('/').pop() || '').includes('.')) dest += '.md'; + } else if (dest.startsWith('<')) { + const close = dest.indexOf('>'); + dest = dest.slice(1, close === -1 ? undefined : close); + } else { + dest = dest.split(/\s/)[0]; // drop an optional "title" + } + if (!dest || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(dest)) return false; + let resolvedLink; + let qualified; + try { + const base = sourcePath.split('/').map(encodeURIComponent).join('/'); + resolvedLink = decodeURIComponent(new URL(dest, `https://docview.invalid/${base}`).pathname.slice(1)); + // `sub%2Fnotes` names a folder just like `sub/notes` once decoded. + qualified = decodeURIComponent(dest).includes('/'); + } catch { + return false; + } + if (resolvedLink === targetPath) return true; + return isWiki && !qualified && basename(resolvedLink) === targetName; } async function scanBacklinks(dir) { @@ -2265,8 +2283,8 @@ const server = createServer(async (req, res) => { const linkRegex = /\[(?:[^\]]*)\]\(([^)]+)\)|\[\[([^\]|]+)(?:\|[^\]]*?)?\]\]/g; let match; while ((match = linkRegex.exec(content)) !== null) { - const linkTarget = match[1] || match[2]; - if (isLinkToTarget(linkTarget, relPath)) { + const isWiki = match[1] === undefined; + if (isLinkToTarget(isWiki ? match[2] : match[1], relPath, isWiki)) { const line = content.substring(0, match.index).split('\n').length; backlinks.push({ path: relPath, line }); break; @@ -2486,12 +2504,28 @@ function tryLocalDiagramCLI(type, source) { }); } +/** Same boundary as safePath(), synchronously, for Chokidar's ignore hook. */ +function resolvesOutsideRoot(path) { + let real; + try { + real = realpathSync.native(resolve(targetDir, path)); + } catch { + return false; // Missing paths are reported as unlink events. + } + const prefix = targetDir.endsWith(sep) ? targetDir : targetDir + sep; + return real !== targetDir && !real.startsWith(prefix); +} + // File watcher — chokidar v5 has no glob support, so watch the directory // itself, prune ignored paths via the `ignored` function, and filter events // by extension before broadcasting. function isWatchIgnored(path, stats) { const rel = relative(targetDir, resolve(targetDir, path)); if (!rel || rel.startsWith('..')) return false; + // Chokidar follows symlinks, so a link to /, $HOME, etc. would watch (and + // broadcast names from) a tree every other API refuses to expose. Stat-less + // calls cover event paths beneath a link; real files and dirs need no check. + if ((!stats || stats.isSymbolicLink()) && resolvesOutsideRoot(path)) return true; const segments = rel.split(sep); for (let i = 0; i < segments.length; i++) { const seg = segments[i]; diff --git a/tests/server-audit.test.mjs b/tests/server-audit.test.mjs index f52c4ca..b420c8b 100644 --- a/tests/server-audit.test.mjs +++ b/tests/server-audit.test.mjs @@ -310,6 +310,83 @@ test('watcher broadcasts changes to supported hidden files such as .env', async assert.match(events, /"event":"change","path":"\.env"/); }); +test('watcher does not follow symlinks out of the served root', async (t) => { + const directory = join(fixture, 'watch-boundary'); + const outside = join(fixture, 'watch-outside'); + await mkdir(join(directory, 'real'), { recursive: true }); + await mkdir(outside); + await writeFile(join(outside, 'leak.md'), 'outside\n'); + await writeFile(join(directory, 'real', 'inside.md'), 'inside\n'); + await symlink(outside, join(directory, 'escape')); + await symlink(join(directory, 'real'), join(directory, 'alias')); + const server = await startServer(t, { directory }); + const controller = new AbortController(); + t.after(() => controller.abort()); + const response = await fetch(server.base + '/api/watch', { signal: controller.signal }); + const reader = response.body.getReader(); + await reader.read(); + // Touch both sides until the in-root change arrives, so a missing outside + // event is not just the watcher still starting up. + const interval = setInterval(() => { + void writeFile(join(outside, 'leak.md'), `outside ${Date.now()}\n`); + void writeFile(join(directory, 'real', 'inside.md'), `inside ${Date.now()}\n`); + }, 200); + const timeout = setTimeout(() => controller.abort(), 4000); + t.after(() => { clearInterval(interval); clearTimeout(timeout); }); + let events = ''; + while (!/"path":"alias\/inside\.md"/.test(events) || !/"path":"real\/inside\.md"/.test(events)) { + const { value, done } = await reader.read().catch(() => ({ done: true })); + if (done) break; + events += Buffer.from(value).toString(); + } + // Give a straggling outside event one more interval to show up. + await new Promise((resolve) => setTimeout(resolve, 400)); + clearInterval(interval); + assert.match(events, /"path":"real\/inside\.md"/); + assert.match(events, /"path":"alias\/inside\.md"/, 'in-root symlinked directories are still watched'); + assert.doesNotMatch(events, /escape\//); +}); + +test('regex search anchors work on CRLF files and results omit carriage returns', async (t) => { + const directory = join(fixture, 'crlf'); + await mkdir(directory); + await writeFile(join(directory, 'windows.md'), 'alpha end\r\nbeta end\r\n'); + const server = await startServer(t, { directory }); + const regex = await (await server.request('/api/search?regex=1&context=1&q=' + encodeURIComponent('end$'))).json(); + assert.deepEqual(regex.map(({ line }) => line), [1, 2]); + const plain = await (await server.request('/api/search?context=1&q=alpha')).json(); + assert.equal(plain[0].text, 'alpha end'); + assert.deepEqual(plain[0].contextLines, ['alpha end', 'beta end']); +}); + +test('backlinks resolve Markdown links like the viewer does', async (t) => { + const directory = join(fixture, 'backlinks'); + await mkdir(join(directory, 'sub'), { recursive: true }); + await writeFile(join(directory, 'my doc.md'), '# Target\n'); + await writeFile(join(directory, 'sub', 'notes.md'), '# Notes\n'); + await writeFile(join(directory, 'encoded.md'), '[a](my%20doc.md)\n'); + await writeFile(join(directory, 'angle.md'), '[a]( "Title")\n'); + await writeFile(join(directory, 'parent.md'), 'x\n\n[a](sub/../my%20doc.md#top)\n'); + await writeFile(join(directory, 'wiki.md'), '[[my doc]]\n'); + await writeFile(join(directory, 'other-ext.md'), '[a](my%20doc.txt)\n'); + await writeFile(join(directory, 'wrong-dir.md'), '[a](notes.md)\n'); + await writeFile(join(directory, 'wiki-notes.md'), '[[notes]]\n'); + // An encoded separator still qualifies the wiki link to one folder. + await mkdir(join(directory, 'other')); + await writeFile(join(directory, 'other', 'notes.md'), '# Other notes\n'); + await writeFile(join(directory, 'wiki-encoded.md'), '[[sub%2Fnotes]]\n'); + const server = await startServer(t, { directory }); + const target = await (await server.request('/api/backlinks?path=' + encodeURIComponent('my doc.md'))).json(); + assert.deepEqual(target.map(({ path }) => path).sort(), ['angle.md', 'encoded.md', 'parent.md', 'wiki.md']); + assert.equal(target.find(({ path }) => path === 'parent.md').line, 3); + const notes = await (await server.request('/api/backlinks?path=sub/notes.md')).json(); + // A plain relative link opens notes.md beside its source; only wiki links + // match by name across directories. + assert.deepEqual(notes.map(({ path }) => path).sort(), ['wiki-encoded.md', 'wiki-notes.md']); + const otherNotes = await (await server.request('/api/backlinks?path=other/notes.md')).json(); + assert.deepEqual(otherNotes.map(({ path }) => path), ['wiki-notes.md']); +}); + test('CLI rejects an unsafe remote byte limit instead of silently disabling the cap', async () => { const child = spawn(NODE, [join(ROOT, 'server.mjs'), docs, '--remote-max-size', '9'.repeat(400)], { stdio: ['ignore', 'ignore', 'pipe'],