okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
1.6 KiB35 linesraw
1"""Which files of serve/web the server hands out below /web/: the page's translations and the vendored KaTeX.
2
3The flat files (app.js, app.css, ...) are served by serve/server.py itself. The two folders here hold more than one
4level, so each has its own whitelist: a name pattern and the types it may have. Nothing outside these folders is ever
5read, a name with a backslash, a colon or a percent sign is refused, and the resolved path must stay inside the folder.
6"""
7from __future__ import annotations
8
9import re
10from pathlib import Path
11
12WEB = Path(__file__).resolve().parent / "web"
13
14# /web/locales/<lang>.json   e.g. de.json, pt-BR.json
15LOCALE = re.compile(r"^/web/locales/(?P<name>[a-z]{2,3}(?:-[A-Z]{2})?\.json)$")
16# /web/vendor/katex/dist/... : the script, the style sheet and the fonts only
17VENDOR_TYPES = {".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".woff2": "font/woff2"}
18VENDOR_PREFIX = "/web/vendor/katex/"
19
20
21def subtree_file(path: str, web: Path = WEB):
22    """(file, content type) for a /web/locales or /web/vendor path, or None when it is not served."""
23    if any(c in path for c in ("\\", ":", "%", "\0")) or ".." in path:
24        return None
25    m = LOCALE.match(path)
26    if m:
27        f = web / "locales" / m.group("name")
28        return (f, "application/json; charset=utf-8") if f.is_file() else None
29    if path.startswith(VENDOR_PREFIX):
30        vendor = (web / "vendor" / "katex").resolve()
31        f = (vendor / path[len(VENDOR_PREFIX):]).resolve()
32        ctype = VENDOR_TYPES.get(f.suffix)
33        if ctype and f.is_relative_to(vendor) and f.is_file():
34            return f, ctype
35    return None