From 64d8fc9ce9922f38780cc677478cbfb47b21a87e Mon Sep 17 00:00:00 2001 From: Kyle Javier [kj_sh604] Date: Mon, 16 Mar 2026 14:24:34 -0400 Subject: merge: python rewrite (#1) * refactor: Dockerfile * refactor: docker-compose.yml * refactor: docker-entrypoint.sh * refactor: src/font.php * refactor: src/fonts.php * refactor: src/index.php * refactor: src/upload.php * refactor: src/app.py * refactor: src/index.html * refactor: src/requirements.txt * refactor: 24.04 vps compatibility and README re-write * refactor: python .gitignore update * refactor: README.md--- src/app.py | 188 +++++++++++++ src/font.php | 50 ---- src/fonts.php | 77 ------ src/index.html | 742 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/index.php | 743 --------------------------------------------------- src/requirements.txt | 3 + src/upload.php | 66 ----- 7 files changed, 933 insertions(+), 936 deletions(-) create mode 100644 src/app.py delete mode 100644 src/font.php delete mode 100644 src/fonts.php create mode 100644 src/index.html delete mode 100644 src/index.php create mode 100644 src/requirements.txt delete mode 100644 src/upload.php (limited to 'src') diff --git a/src/app.py b/src/app.py new file mode 100644 index 0000000..7d75f2b --- /dev/null +++ b/src/app.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 + +import base64 +import os +import re +import secrets +import subprocess +from pathlib import Path + +import magic +from flask import Flask, Response, jsonify, request, send_file, send_from_directory + +app = Flask(__name__, static_folder=None) +app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50 MB upload cap + +UPLOAD_DIR = Path(__file__).parent / "uploads" +UPLOAD_DIR.mkdir(mode=0o755, exist_ok=True) + +ALLOWED_MIME = { + "image/png": "png", + "image/jpeg": "jpg", + "image/gif": "gif", + "image/webp": "webp", + "image/svg+xml": "svg", + "image/bmp": "bmp", +} + +# build list of allowed font directories +_FONT_DIRS: list[Path] = [ + Path("/usr/share/fonts"), + Path("/usr/local/share/fonts"), +] +for _home in Path("/home").glob("*"): + _FONT_DIRS.append(_home / ".local" / "share" / "fonts") + _FONT_DIRS.append(_home / ".fonts") + + +def _allowed_font_dirs() -> list[str]: + """return resolved, existent font dirs with trailing separator.""" + out = [] + for d in _FONT_DIRS: + try: + out.append(str(d.resolve(strict=True)) + os.sep) + except (OSError, RuntimeError): + pass + return out + + +@app.route("/") +def index(): + return send_from_directory(app.root_path, "index.html") + + +@app.route("/uploads/") +def uploads(filename: str): + return send_from_directory(UPLOAD_DIR, filename) + + +@app.route("/upload", methods=["POST"]) +def upload(): + if "image" not in request.files: + return jsonify({"error": "no file provided"}), 400 + + f = request.files["image"] + if not f.filename: + return jsonify({"error": "empty filename"}), 400 + + data = f.read() + if not data: + return jsonify({"error": "empty file"}), 400 + + mime = magic.from_buffer(data, mime=True) + if mime not in ALLOWED_MIME: + return jsonify({"error": f"invalid file type: {mime}"}), 400 + + ext = ALLOWED_MIME[mime] + basename = re.sub(r"[^a-zA-Z0-9_-]", "_", Path(f.filename).stem)[:64] + filename = f"{basename}_{secrets.token_hex(4)}.{ext}" + + (UPLOAD_DIR / filename).write_bytes(data) + + return jsonify({"filename": filename, "url": f"uploads/{filename}"}) + + +@app.route("/fonts") +def fonts(): + try: + result = subprocess.run( + ["fc-list", "--format=%{family}|%{style}|%{file}\n"], + capture_output=True, + text=True, + shell=False, + timeout=10, + check=False, + ) + except (FileNotFoundError, subprocess.TimeoutExpired): + return jsonify([]) + + if result.returncode != 0: + return jsonify([]) + + if not result.stdout.strip(): + return jsonify([]) + + def style_score(style: str) -> int: + s = style.strip().lower() + if s in ("regular", "roman", "book", "text"): + return 0 + if s == "bold": + return 1 + if "italic" in s or "oblique" in s: + return 2 + return 3 + + best: dict[str, dict] = {} + for line in result.stdout.splitlines(): + parts = line.split("|", 2) + if len(parts) < 3: + continue + family = parts[0].split(",")[0].strip() + if not family: + continue + style = parts[1].split(",")[0].strip() + file_path = parts[2].strip() + if not Path(file_path).exists(): + continue + score = style_score(style) + if family not in best or score < best[family]["score"]: + best[family] = {"file": file_path, "score": score} + + fmt_map = {"ttf": "truetype", "otf": "opentype", "woff": "woff", "woff2": "woff2"} + fonts_list = [ + { + "family": family, + "file": base64.b64encode(entry["file"].encode()).decode(), + "format": fmt_map.get(Path(entry["file"]).suffix.lstrip(".").lower(), "truetype"), + } + for family, entry in best.items() + ] + fonts_list.sort(key=lambda x: x["family"].casefold()) + + resp = jsonify(fonts_list) + resp.headers["Cache-Control"] = "public, max-age=3600" + return resp + + +@app.route("/font") +def font(): + encoded = request.args.get("f", "") + if not encoded: + return Response("missing parameter", status=400) + + try: + file_str = base64.b64decode(encoded).decode("utf-8") + except Exception: + return Response("invalid parameter", status=400) + + # null byte guard + if "\x00" in file_str: + return Response("invalid parameter", status=400) + + p = Path(file_str) + if not p.exists(): + return Response("font not found", status=404) + + try: + real = p.resolve(strict=True) + except (OSError, RuntimeError): + return Response("font not found", status=404) + + # path traversal guard: real path must be under an allowed font dir + real_str = str(real) + os.sep + if not any(real_str.startswith(d) for d in _allowed_font_dirs()): + return Response("access denied", status=403) + + mime_map = { + "ttf": "font/ttf", + "otf": "font/otf", + "woff": "font/woff", + "woff2": "font/woff2", + } + mime = mime_map.get(real.suffix.lstrip(".").lower(), "application/octet-stream") + + return send_file(real, mimetype=mime, max_age=31536000, conditional=True) + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=3000) diff --git a/src/font.php b/src/font.php deleted file mode 100644 index d12ceb8..0000000 --- a/src/font.php +++ /dev/null @@ -1,50 +0,0 @@ - 'font/ttf', - 'otf' => 'font/otf', - 'woff' => 'font/woff', - 'woff2' => 'font/woff2', - default => 'application/octet-stream', -}; - -header("Content-Type: $mime"); -header('Cache-Control: public, max-age=31536000, immutable'); -header('Content-Length: ' . filesize($file)); -readfile($file); diff --git a/src/fonts.php b/src/fonts.php deleted file mode 100644 index 6d7912b..0000000 --- a/src/fonts.php +++ /dev/null @@ -1,77 +0,0 @@ - ['pipe', 'w'], 2 => ['pipe', 'w']]; -$proc = proc_open($cmd, $desc, $pipes); - -$output = ''; -if (is_resource($proc)) { - $output = stream_get_contents($pipes[1]); - fclose($pipes[1]); - fclose($pipes[2]); - proc_close($proc); -} -if (!$output) { - echo json_encode([]); - exit; -} - -$lines = array_filter(explode("\n", trim($output))); -$best = []; // family => ['file' => ..., 'score' => ...] - -/* lower score = higher priority */ -$style_score = static function (string $style): int { - $s = strtolower(trim($style)); - if ($s === 'regular' || $s === 'roman' || $s === 'book' || $s === 'text') return 0; - if ($s === 'bold') return 1; - if (str_contains($s, 'italic') || str_contains($s, 'oblique')) return 2; - return 3; -}; - -foreach ($lines as $line) { - $parts = explode('|', $line, 3); - if (count($parts) < 3) continue; - - /* take first family name (some entries are comma-separated) */ - $families = explode(',', $parts[0]); - $family = trim($families[0]); - - if (empty($family)) continue; - - $style = trim(explode(',', $parts[1])[0]); - $file = trim($parts[2]); - if (!file_exists($file)) continue; - - $score = $style_score($style); - - if (!isset($best[$family]) || $score < $best[$family]['score']) { - $best[$family] = ['file' => $file, 'score' => $score]; - } -} - -$fonts = []; -foreach ($best as $family => $entry) { - $file = $entry['file']; - $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); - $format = match ($ext) { - 'ttf' => 'truetype', - 'otf' => 'opentype', - 'woff' => 'woff', - 'woff2' => 'woff2', - default => 'truetype', - }; - - $fonts[] = [ - 'family' => $family, - 'file' => base64_encode($file), - 'format' => $format, - ]; -} - -usort($fonts, fn($a, $b) => strcasecmp($a['family'], $b['family'])); -echo json_encode($fonts); diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..ef2f584 --- /dev/null +++ b/src/index.html @@ -0,0 +1,742 @@ + + + + + + + sent-web + + + + + + + +
+

sent-web

+

suckless's sent tool ported to the very sucky web world

+
+ +
+
+ + + +
+ + + +
+
+ + + +
+ + + +
+

F5 to present · Esc to exit · ← → h l j k space enter to navigate

+
+ + +
+
+
+ + + + + \ No newline at end of file diff --git a/src/index.php b/src/index.php deleted file mode 100644 index f855f39..0000000 --- a/src/index.php +++ /dev/null @@ -1,743 +0,0 @@ - - - - - - - - sent-web - - - - - - - -
-

sent-web

-

suckless's sent tool ported to the very sucky web world

-
- -
-
- - - -
- - - -
-
- - - -
- - - -
-

F5 to present · Esc to exit · ← → h l j k space enter to navigate

-
- - -
-
-
- - - - - \ No newline at end of file diff --git a/src/requirements.txt b/src/requirements.txt new file mode 100644 index 0000000..dfce493 --- /dev/null +++ b/src/requirements.txt @@ -0,0 +1,3 @@ +flask>=3.0,<3.2 +gunicorn>=22,<24 +python-magic>=0.4.27,<0.5 \ No newline at end of file diff --git a/src/upload.php b/src/upload.php deleted file mode 100644 index 62db139..0000000 --- a/src/upload.php +++ /dev/null @@ -1,66 +0,0 @@ - 'Method not allowed']); - exit; -} - -if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) { - $code = $_FILES['image']['error'] ?? 'unknown'; - http_response_code(400); - echo json_encode(['error' => "Upload failed (code: $code)"]); - exit; -} - -$file = $_FILES['image']; -$allowed = [ - 'image/png', 'image/jpeg', 'image/gif', - 'image/webp', 'image/svg+xml', 'image/bmp', -]; - -$finfo = finfo_open(FILEINFO_MIME_TYPE); -$mime = finfo_file($finfo, $file['tmp_name']); -finfo_close($finfo); - -if (!in_array($mime, $allowed, true)) { - http_response_code(400); - echo json_encode(['error' => "Invalid file type: $mime"]); - exit; -} - -$ext = match ($mime) { - 'image/png' => 'png', - 'image/jpeg' => 'jpg', - 'image/gif' => 'gif', - 'image/webp' => 'webp', - 'image/svg+xml' => 'svg', - 'image/bmp' => 'bmp', - default => 'bin', -}; - -/* generate safe filename */ -$basename = pathinfo($file['name'], PATHINFO_FILENAME); -$basename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $basename); -$basename = substr($basename, 0, 64); -$filename = $basename . '_' . bin2hex(random_bytes(4)) . '.' . $ext; - -$uploadDir = __DIR__ . '/uploads'; -if (!is_dir($uploadDir)) { - mkdir($uploadDir, 0755, true); -} - -$dest = $uploadDir . '/' . $filename; -if (!move_uploaded_file($file['tmp_name'], $dest)) { - http_response_code(500); - echo json_encode(['error' => 'Failed to save file']); - exit; -} - -echo json_encode([ - 'filename' => $filename, - 'url' => 'uploads/' . $filename, -]); -- cgit v1.2.3