Files
receipt_maker/receipt_web.py
T
adamfandClaude Opus 5.5 f55b20fb82
CI / test (3.12) (push) Failing after 43s
CI / test (3.10) (push) Failing after 6m6s
CI / test (3.13) (push) Failing after 36s
Add a web server for printing from the site, deployed on stppi
`./receipt.py serve` (receipt_web.py, the new [web] extra) serves a page
for printing a note or an uploaded image. The site's nginx gates
/receipt/ on the admin session and proxies to it over Tailscale, adding
X-Receipt-Token; nothing but /healthz answers without it, and POSTs also
need X-Requested-With: receipt. Jobs run one at a time behind a lock
around run_action(), and uploads print from memory.

run_action(), _dispatch() and setup_network_quiet() move from the TUI to
receipt.py so the server doesn't need textual. --no-setup (needs_setup())
skips the sudo connect script everywhere it would run; serve always sets
it. cmd_print takes in-memory `data`.

deploy/ has the systemd user units. receipt-update.timer runs update.sh
every 5 minutes: it fast-forwards the clone from Gitea, runs the tests
and restarts receipt-web, rolling back if they fail.

Also included from earlier uncommitted work: the CI matrix moved to the
right place, connect_receipt.sh no longer re-parses CLI values in
bash -c, RECEIPT_PRINTER_IP/PORT are validated, pyusb is declared, the
ruff S rules are on, and the img/ cache and junk/ are no longer tracked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 21:22:31 +01:00

320 lines
12 KiB
Python

"""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 = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Receipt Printer</title>
<style>
:root {
--bg: #f6f5f2; --card: #fff; --text: #1d1d1b; --muted: #6b6a66;
--border: #dcdad4; --accent: #2f5bd3; --ok: #1f7a3a; --err: #b42318;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #161615; --card: #20201e; --text: #ecebe7; --muted: #9c9a94;
--border: #3a3936; --accent: #7a9cff; --ok: #5cc27c; --err: #ff7a6b;
}
}
* { box-sizing: border-box; }
body {
margin: 0; padding: 24px 16px; background: var(--bg); color: var(--text);
font: 15px/1.5 system-ui, sans-serif;
}
main { max-width: 560px; margin: 0 auto; display: grid; gap: 16px; }
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
h1 { font-size: 1.3rem; margin: 0; }
h2 { font-size: 1rem; margin: 0 0 10px; }
section {
background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px;
}
textarea, input[type=text] {
width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px;
background: var(--bg); color: var(--text); font: inherit;
}
textarea { min-height: 140px; font-family: ui-monospace, monospace; resize: vertical; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px;
margin-top: 10px; flex-wrap: wrap; }
button {
padding: 8px 16px; border: 0; border-radius: 6px; background: var(--accent); color: #fff;
font: inherit; font-weight: 600; cursor: pointer;
}
button:disabled { opacity: .5; cursor: progress; }
.pill {
font-size: .85rem; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--border);
color: var(--muted); background: none; cursor: pointer; font-weight: 400;
}
.pill.ok { color: var(--ok); border-color: var(--ok); }
.pill.err { color: var(--err); border-color: var(--err); }
#drop {
display: block; border: 2px dashed var(--border); border-radius: 8px; padding: 16px;
text-align: center; color: var(--muted); cursor: pointer;
}
#drop.over { border-color: var(--accent); }
#preview { max-width: 100%; max-height: 260px; display: none; margin: 10px auto 0;
filter: grayscale(1); }
#file { display: none; }
#log { white-space: pre-wrap; font-family: ui-monospace, monospace; font-size: .85rem;
margin: 0; color: var(--muted); }
#log.ok { color: var(--ok); }
#log.err { color: var(--err); }
.muted { color: var(--muted); font-size: .85rem; }
</style>
</head>
<body>
<main>
<header>
<h1>Receipt printer</h1>
<button id="status" class="pill" title="Check again">checking…</button>
</header>
<section>
<h2>Note</h2>
<form id="note-form">
<textarea id="note" maxlength="4000" placeholder="Wrapped to 48 columns" required></textarea>
<div class="row">
<label class="muted"><input type="checkbox" id="timestamp"> Date/time header</label>
<button type="submit">Print note</button>
</div>
</form>
</section>
<section>
<h2>Image</h2>
<form id="image-form">
<label id="drop" for="file">Choose, drop or paste an image</label>
<input type="file" id="file" accept="image/*">
<img id="preview" alt="">
<div class="row">
<input type="text" id="caption" maxlength="500" placeholder="Caption (optional)">
</div>
<div class="row">
<span class="muted">Max 16 MB. Printed full width, dithered.</span>
<button type="submit">Print image</button>
</div>
</form>
</section>
<section><pre id="log">Ready.</pre></section>
</main>
<script>
const $ = (id) => document.getElementById(id);
const log = $("log");
let picked = null;
function show(text, cls) { log.textContent = text; log.className = cls || ""; }
async function call(path, init) {
init = init || {};
init.headers = Object.assign({"X-Requested-With": "receipt"}, init.headers || {});
const res = await fetch(path, init);
let body = {};
try { body = await res.json(); } catch (e) { /* nginx pages aren't JSON */ }
if (!("ok" in body) && !("detail" in body)) {
// Not from this server: nginx's offline page, or its login redirect.
const offline = [502, 503, 504].includes(res.status);
return {ok: false, text: offline ? "The printer machine is offline."
: "Signed out? Reload the page and sign in."};
}
let detail = body.detail;
if (Array.isArray(detail)) detail = detail.map((d) => d.msg).join("; ");
return {ok: res.ok && body.ok !== false, text: body.output || detail || res.statusText};
}
async function checkStatus() {
const pill = $("status");
pill.textContent = "checking…"; pill.className = "pill";
const r = await call("api/status");
pill.textContent = r.ok ? "printer ready" : "printer offline";
pill.className = "pill " + (r.ok ? "ok" : "err");
pill.title = r.text;
}
async function submit(form, path, init) {
const buttons = document.querySelectorAll("button");
buttons.forEach((b) => b.disabled = true);
show("Printing…");
try {
const r = await call(path, init);
show(r.ok ? (r.text || "Printed.") : r.text, r.ok ? "ok" : "err");
return r.ok;
} catch (e) {
show("Request failed: " + e, "err");
return false;
} finally {
buttons.forEach((b) => b.disabled = false);
}
}
$("note-form").addEventListener("submit", async (e) => {
e.preventDefault();
const ok = await submit(e.target, "api/note", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked}),
});
if (ok) $("note").value = "";
});
function pick(file) {
if (!file || !file.type.startsWith("image/")) return;
picked = file;
const preview = $("preview");
if (preview.src) URL.revokeObjectURL(preview.src);
preview.src = URL.createObjectURL(file);
preview.style.display = "block";
$("drop").textContent = file.name || "Pasted image";
}
$("file").addEventListener("change", (e) => pick(e.target.files[0]));
const drop = $("drop");
drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
drop.addEventListener("dragleave", () => drop.classList.remove("over"));
drop.addEventListener("drop", (e) => {
e.preventDefault(); drop.classList.remove("over"); pick(e.dataTransfer.files[0]);
});
document.addEventListener("paste", (e) => {
const item = [...e.clipboardData.items].find((i) => i.type.startsWith("image/"));
if (item) pick(item.getAsFile());
});
$("image-form").addEventListener("submit", async (e) => {
e.preventDefault();
if (!picked) { show("Choose an image first.", "err"); return; }
const data = new FormData();
data.append("file", picked, picked.name || "pasted.png");
data.append("message", $("caption").value);
await submit(e.target, "api/image", {method: "POST", body: data});
});
$("status").addEventListener("click", checkStatus);
checkStatus();
</script>
</body>
</html>
"""