"""Web server for printing from the website; launched via `./receipt.py serve`. 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. Uploads are printed from memory and never written to disk. """ from __future__ import annotations import argparse import hmac import io import os import sys import threading from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile from fastapi.responses import HTMLResponse, JSONResponse from PIL import Image from pydantic import BaseModel, Field import receipt TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret MIN_TOKEN_CHARS = 16 MAX_NOTE_CHARS = 4000 MAX_CAPTION_CHARS = 500 # Sent by the page's fetch(). A cross-site form can't set it, and a cross-site # fetch that sets it needs a CORS preflight, which nginx's auth gate refuses. CSRF_HEADER_VALUE = "receipt" class Note(BaseModel): text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS) timestamp: bool = False def create_app(base: argparse.Namespace, token: str) -> FastAPI: # One job at a time: run_action's stdout capture is process-global and the # printer takes a single connection. lock = threading.Lock() app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) def require_token(x_receipt_token: str | None = Header(default=None)) -> None: if x_receipt_token is None or not hmac.compare_digest( x_receipt_token.encode(), token.encode() ): raise HTTPException(401, "Missing or invalid token.") 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.") def run(command: str, **params) -> JSONResponse: with lock: rc, output = receipt.run_action(command, base, **params) return JSONResponse({"ok": rc == 0, "output": output}, status_code=200 if rc == 0 else 502) authed = [Depends(require_token)] posting = [Depends(require_token), Depends(require_page_request)] @app.get("/healthz") def healthz() -> dict: return {"ok": True} @app.get("/", response_class=HTMLResponse, dependencies=authed) def page() -> str: return PAGE @app.get("/api/status", dependencies=authed) def status() -> JSONResponse: return run("status") @app.post("/api/note", dependencies=posting) def note(body: Note) -> JSONResponse: if not body.text.strip(): raise HTTPException(400, "Nothing to print.") return run("note", text=body.text, timestamp=body.timestamp) @app.post("/api/image", dependencies=posting) def image( file: UploadFile = File(...), # noqa: B008 - FastAPI's declaration idiom message: str = Form(default="", max_length=MAX_CAPTION_CHARS), ) -> JSONResponse: data = file.file.read(receipt.MAX_IMAGE_BYTES + 1) if len(data) > receipt.MAX_IMAGE_BYTES: raise HTTPException( 413, f"Image exceeds the {receipt.MAX_IMAGE_BYTES // 1024 // 1024} MB cap." ) # Reject non-images here, as a 400, rather than as a print failure. try: with Image.open(io.BytesIO(data)) as img: img.verify() except (Image.DecompressionBombError, OSError, SyntaxError, ValueError) as e: raise HTTPException(400, f"Not a printable image: {e}") from None return run("print", path=None, data=data, message=message.strip() or None) return app 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(":") if not sep or not port.isdigit(): print(f"--listen must be host:port, got {args.listen!r}.", 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). base = argparse.Namespace(**{**vars(args), "no_setup": True}) uvicorn.run(create_app(base, token), host=host.strip("[]"), port=int(port)) return 0 PAGE = """ Receipt Printer

Receipt printer

Note

Image

Max 16 MB. Printed full width, dithered.
Ready.
"""