mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-20 07:04:21 +01:00
A second process rather than more routes on the bot's own app. This one can rewrite .env, and the bot's port already serves /_selftest, which posts for real into a real group; keeping them apart means the surface that can reconfigure the bot only listens while somebody has the page open. The tagger's seven routes move here unchanged, out of tool/ and into the coverage gate -- which is the reason an unconditional ImportError once sat in tagger.py through two releases. The media route is still indexed by integer, and that is not a style choice: a filename from a client is a path, and the directory holds private photographs. FastAPI refuses a name with 422 before the handler runs, which the tests assert. guard.py is the part that was not asked for. Binding to loopback stops the network, not the browser already running on this machine, and two attacks reach a loopback port from an ordinary web page: a cross-origin form, which can only send urlencoded, multipart or plain text, so requiring application/json refuses it with no token to keep; and DNS rebinding, whose request still carries the attacker's hostname in Host. Forty lines instead of authentication, which is the right trade for something started by hand and stopped again a few minutes later. assets.py branches on whether the page has been built, because StaticFiles raises at construction on a missing directory -- mounting it unconditionally would take the app down on a fresh clone, and in CI, where pytest never runs pnpm build. Both branches are tested; "not built" answers with the command. The container restart goes through signal_bot.external, wrapped in asyncio.to_thread: it is synchronous with a 60s default, and blocking the loop would freeze the page showing the restart. 100% branch coverage across all eleven modules, no omits, no pragmas. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01416TegJ3sa8xL5qGGgrygP
76 lines
2.8 KiB
Python
76 lines
2.8 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""Serving the built page, and saying so plainly when it is not built.
|
|
|
|
``StaticFiles`` raises at construction when its directory is missing, so
|
|
mounting it unconditionally would make the whole app fail to start on a fresh
|
|
clone -- and in CI, where pytest runs without ever invoking ``pnpm build``.
|
|
The branch is therefore explicit: built, or a 503 that names the command to
|
|
run. "Not built yet" is a normal state with an obvious fix, and it deserves a
|
|
sentence rather than a traceback.
|
|
|
|
No new dependency. Starlette's ``StaticFiles`` is anyio-based and needs no
|
|
``aiofiles``, which is verified rather than assumed: this repository's runtime
|
|
pins are exactly six packages and adding a seventh would trip the freshness
|
|
gate.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import TYPE_CHECKING, Final
|
|
|
|
from fastapi import FastAPI, Response, status
|
|
from fastapi.responses import HTMLResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
|
|
INDEX: Final = "index.html"
|
|
ASSETS: Final = "assets"
|
|
BUILD_COMMAND: Final = "pnpm --dir web install && pnpm --dir web build"
|
|
|
|
NOT_BUILT: Final = (
|
|
"<!doctype html><meta charset=utf-8><title>signal-bot</title>"
|
|
"<p>The management page has not been built yet. Run:"
|
|
f"<pre>{BUILD_COMMAND}</pre>"
|
|
)
|
|
|
|
|
|
def is_built(dist: Path) -> bool:
|
|
"""Whether there is a built page to serve.
|
|
|
|
Args:
|
|
dist: The directory ``vite build`` writes into.
|
|
|
|
Returns:
|
|
True when both halves of a vite build are there. Both, because
|
|
mounting StaticFiles on a missing ``assets/`` raises exactly the way
|
|
a missing ``dist/`` does, and a half-built directory should answer
|
|
"not built" rather than take the app down with it.
|
|
"""
|
|
return (dist / INDEX).is_file() and (dist / ASSETS).is_dir()
|
|
|
|
|
|
def install(app: FastAPI, dist: Path) -> None:
|
|
"""Serve the built page, or explain its absence, at every unclaimed path.
|
|
|
|
Registered last, after every API route, so the catch-all cannot shadow
|
|
them. The catch-all exists because the page routes client-side: a reload
|
|
on a sub-view asks this server for a path only the browser knows about.
|
|
|
|
Args:
|
|
app: The FastAPI application to serve from.
|
|
dist: The directory ``vite build`` writes into.
|
|
"""
|
|
if is_built(dist):
|
|
# Hashed filenames under /assets, so they are safe to cache and are
|
|
# the only paths that must not fall through to index.html.
|
|
app.mount(f"/{ASSETS}", StaticFiles(directory=dist / ASSETS), name=ASSETS)
|
|
|
|
@app.get("/{_path:path}", response_class=HTMLResponse)
|
|
async def page(_path: str, response: Response) -> str:
|
|
if not is_built(dist):
|
|
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
|
|
return NOT_BUILT
|
|
return (dist / INDEX).read_text(encoding="utf-8")
|