markdotserver 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,547 @@
1
+ # SPDX-FileCopyrightText: 2026 Alexey Agafonov
2
+ # SPDX-License-Identifier: MIT
3
+ """Read-only filesystem access confined to the documentation root."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ import threading
10
+ import time
11
+ from dataclasses import dataclass, replace
12
+ from enum import StrEnum
13
+ from pathlib import Path, PurePosixPath
14
+ from typing import Any, Literal
15
+
16
+ __all__ = [
17
+ "ASSET_KINDS",
18
+ "DEFAULT_DOCUMENT_NAMES",
19
+ "DOCUMENT_KINDS",
20
+ "SOURCE_KINDS",
21
+ "Entry",
22
+ "FileKind",
23
+ "Filesystem",
24
+ "FilesystemError",
25
+ "HiddenPath",
26
+ "InvalidPath",
27
+ "NotADirectory",
28
+ "NotAFile",
29
+ "OutsideRoot",
30
+ "PathNotFound",
31
+ "PermissionDenied",
32
+ "TextTooLarge",
33
+ "UnsupportedFile",
34
+ "is_asset",
35
+ "is_document",
36
+ "is_source",
37
+ "kind_for_name",
38
+ "kind_for_path",
39
+ ]
40
+
41
+
42
+ class FileKind(StrEnum):
43
+ """The rendering class of a visible path."""
44
+
45
+ MARKDOWN = "markdown"
46
+ GRAPHVIZ = "graphviz"
47
+ SVG = "svg"
48
+ IMAGE = "image"
49
+ TEXT = "text"
50
+ DIRECTORY = "directory"
51
+ UNSUPPORTED = "unsupported"
52
+
53
+
54
+ _EXTENSION_KINDS: dict[str, FileKind] = {
55
+ ".md": FileKind.MARKDOWN,
56
+ ".markdown": FileKind.MARKDOWN,
57
+ ".dot": FileKind.GRAPHVIZ,
58
+ ".gv": FileKind.GRAPHVIZ,
59
+ ".svg": FileKind.SVG,
60
+ ".png": FileKind.IMAGE,
61
+ ".jpg": FileKind.IMAGE,
62
+ ".jpeg": FileKind.IMAGE,
63
+ ".gif": FileKind.IMAGE,
64
+ ".webp": FileKind.IMAGE,
65
+ ".txt": FileKind.TEXT,
66
+ }
67
+
68
+ DOCUMENT_KINDS = frozenset(
69
+ {
70
+ FileKind.MARKDOWN,
71
+ FileKind.GRAPHVIZ,
72
+ FileKind.SVG,
73
+ FileKind.IMAGE,
74
+ FileKind.TEXT,
75
+ }
76
+ )
77
+ SOURCE_KINDS = frozenset(
78
+ {FileKind.MARKDOWN, FileKind.GRAPHVIZ, FileKind.SVG, FileKind.TEXT}
79
+ )
80
+ ASSET_KINDS = frozenset({FileKind.SVG, FileKind.IMAGE})
81
+
82
+ DEFAULT_DOCUMENT_NAMES = ("README.md", "readme.md", "index.md", "INDEX.md")
83
+
84
+ _DRIVE_RE = re.compile(r"^[A-Za-z]:")
85
+
86
+ #: ``O_NOFOLLOW`` is absent on Windows, where symlinks need a privilege anyway.
87
+ _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
88
+
89
+ #: A backslash separates path components only on Windows. Everywhere else it is
90
+ #: an ordinary filename character, so rejecting it would make perfectly legal
91
+ #: files unreachable even though the tree lists them.
92
+ _BACKSLASH_IS_SEPARATOR = os.sep == "\\"
93
+
94
+ _DEFAULT_MAX_TREE_DEPTH = 32
95
+ _DEFAULT_TREE_CACHE_TTL = 2.0
96
+
97
+
98
+ class FilesystemError(Exception):
99
+ """Base class for filesystem access failures with an HTTP status hint."""
100
+
101
+ status_code = 500
102
+
103
+
104
+ class InvalidPath(FilesystemError):
105
+ """The requested path is malformed."""
106
+
107
+ status_code = 400
108
+
109
+
110
+ class PathNotFound(FilesystemError):
111
+ """The requested path does not exist."""
112
+
113
+ status_code = 404
114
+
115
+
116
+ class OutsideRoot(FilesystemError):
117
+ """The requested path resolves outside the documentation root."""
118
+
119
+ status_code = 404
120
+
121
+
122
+ class HiddenPath(FilesystemError):
123
+ """The requested path is hidden or resolves through a hidden component."""
124
+
125
+ status_code = 404
126
+
127
+
128
+ class NotAFile(FilesystemError):
129
+ """A file was expected but the path is not a regular file."""
130
+
131
+ status_code = 404
132
+
133
+
134
+ class NotADirectory(FilesystemError):
135
+ """A directory was expected but the path is not a directory."""
136
+
137
+ status_code = 404
138
+
139
+
140
+ class UnsupportedFile(FilesystemError):
141
+ """The path has a kind that is not allowed for the requested operation."""
142
+
143
+ status_code = 404
144
+
145
+
146
+ class PermissionDenied(FilesystemError):
147
+ """The process is not permitted to read the path."""
148
+
149
+ status_code = 403
150
+
151
+
152
+ class TextTooLarge(FilesystemError):
153
+ """A text document exceeds the configured size limit."""
154
+
155
+ status_code = 413
156
+
157
+
158
+ def kind_for_name(name: str) -> FileKind:
159
+ """Return the kind implied by a path's suffix, ignoring case."""
160
+ suffix = PurePosixPath(name).suffix.lower()
161
+ return _EXTENSION_KINDS.get(suffix, FileKind.UNSUPPORTED)
162
+
163
+
164
+ def kind_for_path(path: Path) -> FileKind:
165
+ """Return the kind of an existing path, including directories."""
166
+ try:
167
+ if path.is_dir():
168
+ return FileKind.DIRECTORY
169
+ if path.is_file():
170
+ return kind_for_name(path.name)
171
+ except OSError:
172
+ return FileKind.UNSUPPORTED
173
+ return FileKind.UNSUPPORTED
174
+
175
+
176
+ def is_document(kind: FileKind) -> bool:
177
+ """Return whether the kind can be displayed in the content pane."""
178
+ return kind in DOCUMENT_KINDS
179
+
180
+
181
+ def is_source(kind: FileKind) -> bool:
182
+ """Return whether plain-text source mode is available for the kind."""
183
+ return kind in SOURCE_KINDS
184
+
185
+
186
+ def is_asset(kind: FileKind) -> bool:
187
+ """Return whether the kind can be served directly as a binary asset."""
188
+ return kind in ASSET_KINDS
189
+
190
+
191
+ @dataclass(frozen=True, slots=True)
192
+ class Entry:
193
+ """One visible node in the directory tree."""
194
+
195
+ name: str
196
+ path: str
197
+ kind: FileKind
198
+ children: tuple[Entry, ...] = ()
199
+ truncated: bool = False
200
+
201
+ def to_dict(self) -> dict[str, Any]:
202
+ """Return a JSON-safe representation for the tree API."""
203
+ data: dict[str, Any] = {
204
+ "name": self.name,
205
+ "path": self.path,
206
+ "kind": self.kind.value,
207
+ }
208
+ if self.kind is FileKind.DIRECTORY:
209
+ data["children"] = [child.to_dict() for child in self.children]
210
+ if self.truncated:
211
+ data["truncated"] = True
212
+ return data
213
+
214
+
215
+ @dataclass(frozen=True, slots=True)
216
+ class _ScanEntry:
217
+ """A listed entry plus the canonical path it was resolved to."""
218
+
219
+ entry: Entry
220
+ resolved: Path
221
+ is_symlink: bool = False
222
+
223
+
224
+ def _path_parts(raw_path: str) -> tuple[str, ...]:
225
+ """Split and validate a route-supplied POSIX path into components."""
226
+ if "\x00" in raw_path:
227
+ raise InvalidPath("path contains a null byte")
228
+ if _BACKSLASH_IS_SEPARATOR and "\\" in raw_path:
229
+ raise InvalidPath("backslashes are not allowed in paths")
230
+ if raw_path.startswith("/") or _DRIVE_RE.match(raw_path):
231
+ raise InvalidPath("absolute paths are not allowed")
232
+
233
+ parts = tuple(part for part in raw_path.split("/") if part)
234
+ if any(part == ".." for part in parts):
235
+ raise InvalidPath("parent path components are not allowed")
236
+ return parts
237
+
238
+
239
+ def _reject_hidden(parts: tuple[str, ...]) -> None:
240
+ if any(part.startswith(".") for part in parts):
241
+ raise HiddenPath("hidden paths are not accessible")
242
+
243
+
244
+ def _entry_sort_key(item: _ScanEntry) -> tuple[bool, str, str]:
245
+ entry = item.entry
246
+ return (entry.kind is not FileKind.DIRECTORY, entry.name.casefold(), entry.name)
247
+
248
+
249
+ class Filesystem:
250
+ """Read-only access to a validated documentation root."""
251
+
252
+ def __init__(
253
+ self,
254
+ root: str | Path,
255
+ *,
256
+ max_tree_depth: int = _DEFAULT_MAX_TREE_DEPTH,
257
+ tree_cache_ttl: float = _DEFAULT_TREE_CACHE_TTL,
258
+ ) -> None:
259
+ try:
260
+ resolved = Path(root).expanduser().resolve(strict=True)
261
+ except FileNotFoundError as exc:
262
+ raise PathNotFound(f"documentation root does not exist: {root}") from exc
263
+ except OSError as exc:
264
+ raise InvalidPath(
265
+ f"cannot resolve documentation root {root}: {exc}"
266
+ ) from exc
267
+ if not resolved.is_dir():
268
+ raise NotADirectory(f"documentation root is not a directory: {resolved}")
269
+ self.root = resolved
270
+ self.max_tree_depth = max(1, int(max_tree_depth))
271
+ self.tree_cache_ttl = float(tree_cache_ttl)
272
+ self._tree_lock = threading.Lock()
273
+ self._tree_cache: tuple[float, tuple[Entry, ...]] | None = None
274
+
275
+ def relative_path(self, path: Path) -> str:
276
+ """Return a resolved path as a POSIX-style path relative to the root.
277
+
278
+ The root itself is spelled ``""``. ``Path.relative_to`` yields ``"."``
279
+ for it, and feeding that back through ``resolve`` would reject it as a
280
+ hidden component, 404-ing the root directory listing.
281
+ """
282
+ if path == self.root:
283
+ return ""
284
+ return path.relative_to(self.root).as_posix()
285
+
286
+ def resolve(
287
+ self,
288
+ raw_path: str,
289
+ *,
290
+ expect: Literal["file", "directory"] | None = None,
291
+ ) -> Path:
292
+ """Resolve a route path, rejecting traversal, hidden names and escapes."""
293
+ parts = _path_parts(raw_path)
294
+ _reject_hidden(parts)
295
+
296
+ candidate = self.root.joinpath(*parts)
297
+ try:
298
+ resolved = candidate.resolve(strict=True)
299
+ except FileNotFoundError as exc:
300
+ raise PathNotFound(f"path does not exist: {raw_path}") from exc
301
+ except PermissionError as exc:
302
+ raise PermissionDenied(f"permission denied: {raw_path}") from exc
303
+ except RuntimeError as exc:
304
+ raise InvalidPath(f"cannot resolve path: {raw_path}") from exc
305
+ except OSError as exc:
306
+ raise InvalidPath(f"cannot resolve path: {raw_path}") from exc
307
+
308
+ if not resolved.is_relative_to(self.root):
309
+ raise OutsideRoot(f"path is outside the documentation root: {raw_path}")
310
+ _reject_hidden(resolved.relative_to(self.root).parts)
311
+
312
+ if expect == "file" and not resolved.is_file():
313
+ raise NotAFile(f"not a file: {raw_path}")
314
+ if expect == "directory" and not resolved.is_dir():
315
+ raise NotADirectory(f"not a directory: {raw_path}")
316
+ return resolved
317
+
318
+ def inspect(
319
+ self,
320
+ raw_path: str,
321
+ *,
322
+ expect: Literal["file", "directory"] | None = None,
323
+ ) -> tuple[Path, str, FileKind]:
324
+ """Resolve once and return the canonical path, relative path and kind.
325
+
326
+ Routes use this instead of calling :meth:`resolve` and then re-deriving
327
+ the kind, which would stat the same path several times.
328
+ """
329
+ resolved = self.resolve(raw_path, expect=expect)
330
+ return resolved, self.relative_path(resolved), kind_for_path(resolved)
331
+
332
+ def list_directory(self, raw_path: str = "") -> list[Entry]:
333
+ """Return the visible, sorted entries of one directory."""
334
+ directory = self.resolve(raw_path, expect="directory")
335
+ prefix = "" if directory == self.root else self.relative_path(directory)
336
+ return [item.entry for item in self._list(directory, prefix)]
337
+
338
+ def build_tree(self, *, fresh: bool = False) -> tuple[Entry, ...]:
339
+ """Return the complete visible tree below the root.
340
+
341
+ The result is cached for ``tree_cache_ttl`` seconds because rebuilding it
342
+ stats every visible file. Pass ``fresh=True`` to force a rescan, which is
343
+ what the interface's Refresh control does.
344
+ """
345
+ with self._tree_lock:
346
+ cached = self._tree_cache
347
+ if (
348
+ not fresh
349
+ and cached is not None
350
+ and (time.monotonic() - cached[0]) < self.tree_cache_ttl
351
+ ):
352
+ return cached[1]
353
+ tree = self._build_tree(
354
+ self.root, "", frozenset({self.root}), 0, {self.root}
355
+ )
356
+ self._tree_cache = (time.monotonic(), tree)
357
+ return tree
358
+
359
+ def invalidate_tree_cache(self) -> None:
360
+ """Drop the cached tree so the next build rescans the root."""
361
+ with self._tree_lock:
362
+ self._tree_cache = None
363
+
364
+ def default_document(self) -> str | None:
365
+ """Return the preferred default document path, if one exists."""
366
+ for name in DEFAULT_DOCUMENT_NAMES:
367
+ try:
368
+ self.resolve(name, expect="file")
369
+ except FilesystemError:
370
+ continue
371
+ return name
372
+ return None
373
+
374
+ def read_text(self, raw_path: str, *, max_bytes: int | None = None) -> str:
375
+ """Read a Markdown, Graphviz, SVG or text file as decoded UTF-8."""
376
+ path = self.resolve(raw_path, expect="file")
377
+ return self.read_resolved(path, raw_path=raw_path, max_bytes=max_bytes)
378
+
379
+ def read_resolved(
380
+ self,
381
+ path: Path,
382
+ *,
383
+ raw_path: str,
384
+ max_bytes: int | None = None,
385
+ ) -> str:
386
+ """Read an already-resolved path, enforcing the kind and size limits."""
387
+ # The kind is taken from the resolved path's own name, not the caller's
388
+ # label, so a symlink named ``notes.md`` pointing at ``script.dot`` is
389
+ # treated as what it resolves to.
390
+ if kind_for_name(path.name) not in SOURCE_KINDS:
391
+ raise UnsupportedFile(f"not a text document: {raw_path}")
392
+ return self._read_bytes(path, raw_path, max_bytes=max_bytes)
393
+
394
+ def open_asset(self, path: Path, *, raw_path: str) -> tuple[int, int]:
395
+ """Open an already-resolved asset and return ``(descriptor, size)``.
396
+
397
+ The caller owns the descriptor. Like text reads, the open uses
398
+ ``O_NOFOLLOW`` so the final component cannot be swapped for a symlink
399
+ between resolution and opening.
400
+ """
401
+ descriptor = self._open_nofollow(path, raw_path)
402
+ try:
403
+ return descriptor, os.fstat(descriptor).st_size
404
+ except OSError as exc:
405
+ os.close(descriptor)
406
+ raise PathNotFound(f"path does not exist: {raw_path}") from exc
407
+
408
+ def _open_nofollow(self, path: Path, raw_path: str) -> int:
409
+ # Opening by descriptor with O_NOFOLLOW closes the window between
410
+ # resolving the path and reading it: if the final component is swapped
411
+ # for a symlink in between, the open fails instead of following it.
412
+ try:
413
+ return os.open(path, os.O_RDONLY | _O_NOFOLLOW)
414
+ except PermissionError as exc:
415
+ raise PermissionDenied(f"permission denied: {raw_path}") from exc
416
+ except OSError as exc:
417
+ raise PathNotFound(f"path does not exist: {raw_path}") from exc
418
+
419
+ def _read_bytes(self, path: Path, raw_path: str, *, max_bytes: int | None) -> str:
420
+ descriptor = self._open_nofollow(path, raw_path)
421
+
422
+ try:
423
+ size = os.fstat(descriptor).st_size
424
+ if max_bytes is not None and size > max_bytes:
425
+ raise TextTooLarge(f"text file exceeds {max_bytes} bytes: {raw_path}")
426
+ with os.fdopen(descriptor, "rb") as stream:
427
+ descriptor = -1
428
+ if max_bytes is None:
429
+ data = stream.read()
430
+ else:
431
+ data = stream.read(max_bytes + 1)
432
+ except PermissionError as exc:
433
+ raise PermissionDenied(f"permission denied: {raw_path}") from exc
434
+ except OSError as exc:
435
+ raise PathNotFound(f"path does not exist: {raw_path}") from exc
436
+ finally:
437
+ if descriptor >= 0:
438
+ os.close(descriptor)
439
+
440
+ if max_bytes is not None and len(data) > max_bytes:
441
+ # The file grew between the stat and the read.
442
+ raise TextTooLarge(f"text file exceeds {max_bytes} bytes: {raw_path}")
443
+
444
+ return data.decode("utf-8-sig", errors="replace")
445
+
446
+ def _list(self, directory: Path, prefix: str) -> list[_ScanEntry]:
447
+ items: list[_ScanEntry] = []
448
+ try:
449
+ with os.scandir(directory) as iterator:
450
+ for entry in iterator:
451
+ item = self._make_entry(entry, prefix)
452
+ if item is not None:
453
+ items.append(item)
454
+ except PermissionError as exc:
455
+ raise PermissionDenied(f"permission denied: {prefix or '.'}") from exc
456
+ except OSError as exc:
457
+ raise PathNotFound(
458
+ f"cannot list directory: {prefix or '.'}: {exc}"
459
+ ) from exc
460
+ items.sort(key=_entry_sort_key)
461
+ return items
462
+
463
+ def _build_tree(
464
+ self,
465
+ directory: Path,
466
+ prefix: str,
467
+ ancestors: frozenset[Path],
468
+ depth: int,
469
+ expanded: set[Path],
470
+ ) -> tuple[Entry, ...]:
471
+ entries: list[Entry] = []
472
+ for item in self._list(directory, prefix):
473
+ entry = item.entry
474
+ if entry.kind is not FileKind.DIRECTORY:
475
+ entries.append(entry)
476
+ continue
477
+ if depth >= self.max_tree_depth:
478
+ # Stop descending but keep the node visible and honest about it,
479
+ # so neither this function nor the template macro can recurse
480
+ # without bound.
481
+ entries.append(replace(entry, truncated=True))
482
+ continue
483
+ resolved = item.resolved
484
+ if resolved in ancestors:
485
+ continue
486
+ if item.is_symlink and resolved in expanded:
487
+ # The ancestor chain only stops cycles. Sibling symlinks to the
488
+ # same directory form a DAG whose expansion multiplies at every
489
+ # level, so a target any walk already expanded is shown but not
490
+ # descended into again.
491
+ entries.append(replace(entry, truncated=True))
492
+ continue
493
+ expanded.add(resolved)
494
+ children = self._build_tree(
495
+ resolved, entry.path, ancestors | {resolved}, depth + 1, expanded
496
+ )
497
+ entries.append(replace(entry, children=children))
498
+ return tuple(entries)
499
+
500
+ def _make_entry(self, item: os.DirEntry[str], prefix: str) -> _ScanEntry | None:
501
+ name = item.name
502
+ if name.startswith("."):
503
+ return None
504
+
505
+ try:
506
+ is_symlink = item.is_symlink()
507
+ if is_symlink:
508
+ # Only a symlink can escape the root or hide behind a dotted
509
+ # component, so only symlinks pay for a full realpath.
510
+ resolved = Path(item.path).resolve(strict=True)
511
+ if not resolved.is_relative_to(self.root):
512
+ return None
513
+ relative = resolved.relative_to(self.root)
514
+ if any(part.startswith(".") for part in relative.parts):
515
+ return None
516
+ is_dir = resolved.is_dir()
517
+ is_file = resolved.is_file()
518
+ # The link advertises what it resolves to: the view routes
519
+ # classify the resolved path, so the tree must agree or it
520
+ # would promise a diagram and deliver text (or vice versa).
521
+ target_name = resolved.name
522
+ else:
523
+ # The scanned directory is already canonical and visible, so a
524
+ # non-symlink child inherits both properties. ``is_dir`` and
525
+ # ``is_file`` use ``d_type`` here and cost no extra syscall.
526
+ resolved = Path(item.path)
527
+ is_dir = item.is_dir(follow_symlinks=False)
528
+ is_file = item.is_file(follow_symlinks=False)
529
+ target_name = name
530
+ except OSError:
531
+ return None
532
+
533
+ if is_dir:
534
+ kind = FileKind.DIRECTORY
535
+ elif is_file:
536
+ kind = kind_for_name(target_name)
537
+ if kind is FileKind.UNSUPPORTED:
538
+ return None
539
+ else:
540
+ return None
541
+
542
+ entry_path = f"{prefix}/{name}" if prefix else name
543
+ return _ScanEntry(
544
+ Entry(name=name, path=entry_path, kind=kind),
545
+ resolved,
546
+ is_symlink=is_symlink,
547
+ )