Add serve --local for using the web page on this machine
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:
@@ -6,7 +6,7 @@ CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt
|
|||||||
|
|
||||||
- `receipt.py` — the CLI; subcommand per `cmd_*` function
|
- `receipt.py` — the CLI; subcommand per `cmd_*` function
|
||||||
- `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which captures stdout/stderr for the log panel and returns an `ActionResult` (rc, output, error kind). `textual` is an optional dependency (`[tui]` extra); the CLI works without it
|
- `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which captures stdout/stderr for the log panel and returns an `ActionResult` (rc, output, error kind). `textual` is an optional dependency (`[tui]` extra); the CLI works without it
|
||||||
- `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds, and `X-Requested-With: receipt` on POSTs. POSTs render the job in the request (`InvalidJob` → 400), queue the bytes in a `PrintQueue` and answer 202; one worker thread sends them, and the page long-polls `/api/jobs/{id}`. `/api/status` only tries the printer lock, so it never waits behind a print. Uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which is online over Wi-Fi and has the printer cabled to its `eth0` (printer 192.168.192.168, Pi 192.168.192.10 via the `receipt-printer` nmcli profile)
|
- `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds (`serve --local` drops it, binding to loopback only and refusing non-localhost `Host`s), and `X-Requested-With: receipt` on POSTs. POSTs render the job in the request (`InvalidJob` → 400), queue the bytes in a `PrintQueue` and answer 202; one worker thread sends them, and the page long-polls `/api/jobs/{id}`. `/api/status` only tries the printer lock, so it never waits behind a print. Uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which is online over Wi-Fi and has the printer cabled to its `eth0` (printer 192.168.192.168, Pi 192.168.192.10 via the `receipt-printer` nmcli profile)
|
||||||
- Scheduling (all run inside `serve`; `[web]` extra): `receipt_store.py` (SQLite at `$RECEIPT_DATA_DIR/receipt.db`, default `~/.local/share/receipt-maker`; additive-only migrations so `update.sh` rollbacks still read it), `receipt_models.py` (pydantic specs: a schedule is trigger + blocks + options), `receipt_triggers.py` (next fire times, DST-safe, plain-English `describe()`), `receipt_sources.py` (ICS/RSS/JSON fetch + parse), `receipt_content.py` (blocks → `receipt.Block`s, `{var}` template fill — never `str.format`), `receipt_scheduler.py` (`tick(now)` is deterministic; tests drive it with a fake clock). Webhooks are `POST /hook/{id}` with a per-schedule secret
|
- Scheduling (all run inside `serve`; `[web]` extra): `receipt_store.py` (SQLite at `$RECEIPT_DATA_DIR/receipt.db`, default `~/.local/share/receipt-maker`; additive-only migrations so `update.sh` rollbacks still read it), `receipt_models.py` (pydantic specs: a schedule is trigger + blocks + options), `receipt_triggers.py` (next fire times, DST-safe, plain-English `describe()`), `receipt_sources.py` (ICS/RSS/JSON fetch + parse), `receipt_content.py` (blocks → `receipt.Block`s, `{var}` template fill — never `str.format`), `receipt_scheduler.py` (`tick(now)` is deterministic; tests drive it with a fake clock). Webhooks are `POST /hook/{id}` with a per-schedule secret
|
||||||
- `web/` — the page (vanilla ES modules, no build step), served by token-gated routes with relative URLs
|
- `web/` — the page (vanilla ES modules, no build step), served by token-gated routes with relative URLs
|
||||||
- `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) tests the new Gitea commit in a scratch worktree, then fast-forwards the server's clone, restarts `receipt-web` and rolls back if `/healthz` doesn't answer. Pushing to Gitea `master` is the deploy
|
- `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) tests the new Gitea commit in a scratch worktree, then fast-forwards the server's clone, restarts `receipt-web` and rolls back if `/healthz` doesn't answer. Pushing to Gitea `master` is the deploy
|
||||||
|
|||||||
@@ -83,6 +83,16 @@ sudo nmcli con add type ethernet ifname eth0 con-name receipt-printer connection
|
|||||||
ipv4.method manual ipv4.addresses 192.168.192.10/24 ipv4.never-default yes ipv6.method disabled
|
ipv4.method manual ipv4.addresses 192.168.192.10/24 ipv4.never-default yes ipv6.method disabled
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Running it locally
|
||||||
|
|
||||||
|
To use the page from a browser on the machine the server runs on, without nginx or a token:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./receipt.py serve --local # then open http://127.0.0.1:8765/
|
||||||
|
```
|
||||||
|
|
||||||
|
`--local` only binds to localhost (`--listen` must be `127.0.0.1`, `[::1]` or `localhost`) and refuses requests whose `Host` isn't localhost, so other sites can't reach it by DNS rebinding. It still never runs the connect script: bring the Ethernet link up first (`./receipt.py status` does), or use `./receipt.py --usb serve --local`. Schedules run here too, from the same data directory as any other `serve` on this machine; set `RECEIPT_DATA_DIR` to keep a separate one.
|
||||||
|
|
||||||
### Setting up the server machine
|
### Setting up the server machine
|
||||||
|
|
||||||
1. Clone from Gitea to `~/Coding/receipt_maker` (the path the units use), and install into a venv there:
|
1. Clone from Gitea to `~/Coding/receipt_maker` (the path the units use), and install into a venv there:
|
||||||
|
|||||||
@@ -752,6 +752,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
default=os.environ.get("RECEIPT_WEB_LISTEN", DEFAULT_WEB_LISTEN),
|
default=os.environ.get("RECEIPT_WEB_LISTEN", DEFAULT_WEB_LISTEN),
|
||||||
help=f"host:port to bind (default: {DEFAULT_WEB_LISTEN}, env RECEIPT_WEB_LISTEN)",
|
help=f"host:port to bind (default: {DEFAULT_WEB_LISTEN}, env RECEIPT_WEB_LISTEN)",
|
||||||
)
|
)
|
||||||
|
serve_p.add_argument(
|
||||||
|
"--local",
|
||||||
|
action="store_true",
|
||||||
|
help="Serve the page to a browser on this machine without the token (localhost only)",
|
||||||
|
)
|
||||||
|
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
|
|||||||
+32
-9
@@ -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
|
/receipt/ on the site's admin session (auth_request), strips the prefix and
|
||||||
forwards here over Tailscale, adding X-Receipt-Token. Nothing is served
|
forwards here over Tailscale, adding X-Receipt-Token. Nothing is served
|
||||||
without that token, so reaching this port directly is not enough.
|
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),
|
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
|
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
|
TOKEN_ENV = "RECEIPT_WEB_TOKEN" # noqa: S105 - env var name, not a secret
|
||||||
MIN_TOKEN_CHARS = 16
|
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_NOTE_CHARS = models.MAX_NOTE_CHARS
|
||||||
MAX_CAPTION_CHARS = models.MAX_CAPTION_CHARS
|
MAX_CAPTION_CHARS = models.MAX_CAPTION_CHARS
|
||||||
MAX_QUEUED = 10 # jobs waiting for the printer; more is a 503
|
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(
|
def create_app(
|
||||||
config: receipt.PrinterConfig,
|
config: receipt.PrinterConfig,
|
||||||
token: str,
|
token: str | None,
|
||||||
store: Store | None = None,
|
store: Store | None = None,
|
||||||
clock: Callable[[], dt.datetime] | None = None,
|
clock: Callable[[], dt.datetime] | None = None,
|
||||||
start_scheduler: bool = True,
|
start_scheduler: bool = True,
|
||||||
) -> FastAPI:
|
) -> FastAPI:
|
||||||
|
"""token=None is local mode: no token, but only requests addressed to localhost."""
|
||||||
store = store or Store()
|
store = store or Store()
|
||||||
store.fail_interrupted_runs()
|
store.fail_interrupted_runs()
|
||||||
jobs = PrintQueue(config, store)
|
jobs = PrintQueue(config, store)
|
||||||
@@ -278,6 +284,10 @@ def create_app(
|
|||||||
):
|
):
|
||||||
raise HTTPException(401, "Missing or invalid token.")
|
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:
|
def require_page_request(x_requested_with: str | None = Header(default=None)) -> None:
|
||||||
if x_requested_with != CSRF_HEADER_VALUE:
|
if x_requested_with != CSRF_HEADER_VALUE:
|
||||||
raise HTTPException(403, "Requests must come from the receipt page.")
|
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)."""
|
"""Names of schedules whose spec matches (to refuse deleting what they use)."""
|
||||||
return [row["name"] for row in store.schedules() if predicate(row["spec"])]
|
return [row["name"] for row in store.schedules() if predicate(row["spec"])]
|
||||||
|
|
||||||
authed = [Depends(require_token)]
|
guard = require_token if token is not None else require_local_host
|
||||||
posting = [Depends(require_token), Depends(require_page_request)]
|
authed = [Depends(guard)]
|
||||||
|
posting = [Depends(guard), Depends(require_page_request)]
|
||||||
|
|
||||||
# --- page ---
|
# --- page ---
|
||||||
|
|
||||||
@@ -762,18 +773,27 @@ def hook_payload(body: bytes, content_type: str) -> dict:
|
|||||||
def serve(args: argparse.Namespace) -> int:
|
def serve(args: argparse.Namespace) -> int:
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|
||||||
|
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, "")
|
token = os.environ.get(TOKEN_ENV, "")
|
||||||
if len(token) < MIN_TOKEN_CHARS:
|
if len(token) < MIN_TOKEN_CHARS:
|
||||||
print(
|
print(
|
||||||
f"Set {TOKEN_ENV} to a random secret of at least {MIN_TOKEN_CHARS} characters "
|
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.",
|
"(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,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
return 1
|
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
|
# Never run the sudo connect script from a request: the service expects the
|
||||||
# printer link to be configured persistently (see README).
|
# printer link to be configured persistently (see README).
|
||||||
config = receipt.PrinterConfig(ip=args.ip, port=args.port, usb=args.usb, no_setup=True)
|
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
|
log.propagate = False
|
||||||
store = Store(default_path())
|
store = Store(default_path())
|
||||||
log.info("data in %s", store.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
|
return 0
|
||||||
|
|||||||
+40
-1
@@ -215,12 +215,51 @@ def test_printer_error_fails_the_job(client, monkeypatch):
|
|||||||
def test_serve_refuses_without_token(monkeypatch, capsys):
|
def test_serve_refuses_without_token(monkeypatch, capsys):
|
||||||
monkeypatch.delenv(receipt_web.TOKEN_ENV, raising=False)
|
monkeypatch.delenv(receipt_web.TOKEN_ENV, raising=False)
|
||||||
|
|
||||||
rc = receipt_web.serve(make_args(listen="127.0.0.1:8765"))
|
rc = receipt_web.serve(make_args(listen="127.0.0.1:8765", local=False))
|
||||||
|
|
||||||
assert rc == 1
|
assert rc == 1
|
||||||
assert receipt_web.TOKEN_ENV in capsys.readouterr().err
|
assert receipt_web.TOKEN_ENV in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_serve_refuses_other_addresses(capsys):
|
||||||
|
rc = receipt_web.serve(make_args(listen="0.0.0.0:8765", local=True))
|
||||||
|
|
||||||
|
assert rc == 1
|
||||||
|
assert "localhost" in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def local_client():
|
||||||
|
config = receipt.PrinterConfig(no_setup=True)
|
||||||
|
return TestClient(receipt_web.create_app(config, None), base_url="http://localhost:8765")
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_needs_no_token(local_client, fake_printer):
|
||||||
|
assert "Receipt printer" in local_client.get("/").text
|
||||||
|
|
||||||
|
res = local_client.post("/api/note", headers={"X-Requested-With": "receipt"},
|
||||||
|
json={"text": "hi"})
|
||||||
|
|
||||||
|
job = finished_job(local_client, res)
|
||||||
|
assert job["state"] == "done"
|
||||||
|
assert fake_printer.calls == ["open", "raw", "close"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("host", ["evil.example", "192.168.1.5:8765"])
|
||||||
|
def test_local_mode_refuses_other_hosts(local_client, fake_printer, host):
|
||||||
|
res = local_client.post("/api/note", json={"text": "hi"},
|
||||||
|
headers={"Host": host, "X-Requested-With": "receipt"})
|
||||||
|
|
||||||
|
assert res.status_code == 400
|
||||||
|
assert local_client.get("/", headers={"Host": host}).status_code == 400
|
||||||
|
assert fake_printer.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_still_needs_page_header(local_client, fake_printer):
|
||||||
|
assert local_client.post("/api/note", json={"text": "hi"}).status_code == 403
|
||||||
|
assert fake_printer.calls == []
|
||||||
|
|
||||||
|
|
||||||
SCHEDULE = {"name": "Chore", "trigger": {"type": "recurring", "times": ["08:00"]},
|
SCHEDULE = {"name": "Chore", "trigger": {"type": "recurring", "times": ["08:00"]},
|
||||||
"blocks": [{"type": "note", "text": "Water the plants"}]}
|
"blocks": [{"type": "note", "text": "Water the plants"}]}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user