Add serve --local for using the web page on this machine
CI / test (3.10) (push) Successful in 1m24s
CI / test (3.12) (push) Successful in 1m5s
CI / test (3.13) (push) Successful in 1m3s

The page is unreachable without nginx, since every route but /healthz
needs the X-Receipt-Token header it adds. `serve --local` serves it
without a token instead: it only binds to a loopback address and answers
only requests whose Host is localhost, 127.0.0.1 or ::1, so another site
can't reach it by DNS rebinding. POSTs still need the page header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-14 22:24:52 +00:00
co-authored by Claude Opus 5.5
parent ba92f1fbda
commit 0d4e2130a6
5 changed files with 91 additions and 14 deletions
+35 -12
View File
@@ -4,6 +4,8 @@ Runs on the machine the printer is cabled to. nginx on the web host gates
/receipt/ on the site's admin session (auth_request), strips the prefix and
forwards here over Tailscale, adding X-Receipt-Token. Nothing is served
without that token, so reaching this port directly is not enough.
`serve --local` drops the token for a browser on the same machine: it binds
to loopback only and refuses any Host but localhost's.
Jobs are rendered and validated in the request (bad input is a 400 at once),
then queued: POST answers 202 with a job id and the page long-polls
@@ -66,6 +68,9 @@ from receipt_triggers import TriggerError, describe, ruleset
TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret
MIN_TOKEN_CHARS = 16
# Local mode serves only these Host names: a page on another site can reach a
# loopback port by DNS rebinding, but its requests still carry its own Host.
LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
MAX_NOTE_CHARS = models.MAX_NOTE_CHARS
MAX_CAPTION_CHARS = models.MAX_CAPTION_CHARS
MAX_QUEUED = 10 # jobs waiting for the printer; more is a 503
@@ -255,11 +260,12 @@ def run_name(text: str, limit: int = 60) -> str:
def create_app(
config: receipt.PrinterConfig,
token: str,
token: str | None,
store: Store | None = None,
clock: Callable[[], dt.datetime] | None = None,
start_scheduler: bool = True,
) -> FastAPI:
"""token=None is local mode: no token, but only requests addressed to localhost."""
store = store or Store()
store.fail_interrupted_runs()
jobs = PrintQueue(config, store)
@@ -278,6 +284,10 @@ def create_app(
):
raise HTTPException(401, "Missing or invalid token.")
def require_local_host(request: Request) -> None:
if request.url.hostname not in LOCAL_HOSTS:
raise HTTPException(400, "Local mode only answers requests to localhost.")
def require_page_request(x_requested_with: str | None = Header(default=None)) -> None:
if x_requested_with != CSRF_HEADER_VALUE:
raise HTTPException(403, "Requests must come from the receipt page.")
@@ -365,8 +375,9 @@ def create_app(
"""Names of schedules whose spec matches (to refuse deleting what they use)."""
return [row["name"] for row in store.schedules() if predicate(row["spec"])]
authed = [Depends(require_token)]
posting = [Depends(require_token), Depends(require_page_request)]
guard = require_token if token is not None else require_local_host
authed = [Depends(guard)]
posting = [Depends(guard), Depends(require_page_request)]
# --- page ---
@@ -762,18 +773,27 @@ def hook_payload(body: bytes, content_type: str) -> dict:
def serve(args: argparse.Namespace) -> int:
import uvicorn
token = os.environ.get(TOKEN_ENV, "")
if len(token) < MIN_TOKEN_CHARS:
print(
f"Set {TOKEN_ENV} to a random secret of at least {MIN_TOKEN_CHARS} characters "
"(e.g. `openssl rand -hex 32`); nginx on the web host sends the same value.",
file=sys.stderr,
)
return 1
host, sep, port = args.listen.rpartition(":")
host = host.strip("[]")
if not sep or not port.isdigit():
print(f"--listen must be host:port, got {args.listen!r}.", file=sys.stderr)
return 1
if args.local:
if host not in LOCAL_HOSTS:
print(f"--local serves without the token, so it only binds to localhost, "
f"not {host!r}.", file=sys.stderr)
return 1
token = None
else:
token = os.environ.get(TOKEN_ENV, "")
if len(token) < MIN_TOKEN_CHARS:
print(
f"Set {TOKEN_ENV} to a random secret of at least {MIN_TOKEN_CHARS} characters "
"(e.g. `openssl rand -hex 32`); nginx on the web host sends the same value. "
"Or use --local to open the page on this machine without one.",
file=sys.stderr,
)
return 1
# Never run the sudo connect script from a request: the service expects the
# printer link to be configured persistently (see README).
config = receipt.PrinterConfig(ip=args.ip, port=args.port, usb=args.usb, no_setup=True)
@@ -785,5 +805,8 @@ def serve(args: argparse.Namespace) -> int:
log.propagate = False
store = Store(default_path())
log.info("data in %s", store.path)
uvicorn.run(create_app(config, token, store), host=host.strip("[]"), port=int(port))
if token is None:
url_host = f"[{host}]" if ":" in host else host
log.info("local mode, no token: open http://%s:%s/", url_host, port)
uvicorn.run(create_app(config, token, store), host=host, port=int(port))
return 0