Fix security, robustness, and config-drift issues
- Close printer handles (contextlib.closing) in CLI and TUI - Whitelist 4chan image extensions + numeric tim (path traversal) - Cap downloads at 16 MB - clean: unlink instead of rmtree, cover legacy dir, add -y flag - TUI: escape captured output as rich Text; propagate failure exit code - Pass --ip/--port through to connect_receipt.sh via env - Fix double-space textln calls - CI matrix 3.10/3.12/3.13 - pytest pythonpath so tests run without editable install - Print retry narrowed to OSError/escpos errors Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -11,7 +11,10 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-python@v5
|
- uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: ${{ matrix.python }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
python: ["3.10", "3.12", "3.13"]
|
||||||
- run: pip install -e '.[dev]'
|
- run: pip install -e '.[dev]'
|
||||||
- run: ruff check .
|
- run: ruff check .
|
||||||
- run: pytest
|
- run: pytest
|
||||||
|
|||||||
+5
-3
@@ -2,9 +2,11 @@
|
|||||||
# Bring up the network interface for the Epson TM-T20II and verify it is reachable.
|
# Bring up the network interface for the Epson TM-T20II and verify it is reachable.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
PRINTER_IP="192.168.192.168"
|
# Overridable by the CLI, which exports these to match --ip/--port.
|
||||||
PRINTER_PORT=9100
|
PRINTER_IP="${RECEIPT_PRINTER_IP:-192.168.192.168}"
|
||||||
HOST_ADDR="192.168.192.10/24"
|
PRINTER_PORT="${RECEIPT_PRINTER_PORT:-9100}"
|
||||||
|
# Our address on the printer's /24, host part .10
|
||||||
|
HOST_ADDR="${PRINTER_IP%.*}.10/24"
|
||||||
|
|
||||||
# Prefer a USB Ethernet interface; fall back to eth0
|
# Prefer a USB Ethernet interface; fall back to eth0
|
||||||
iface=$(ip -o link | awk -F': ' '/enx|enp.*u/{print $2}' | head -n 1)
|
iface=$(ip -o link | awk -F': ' '/enx|enp.*u/{print $2}' | head -n 1)
|
||||||
|
|||||||
@@ -38,3 +38,4 @@ select = ["E", "F", "W", "I", "UP", "B", "SIM"]
|
|||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
|
pythonpath = ["."] # tests import receipt/receipt_tui without an editable install
|
||||||
|
|||||||
+72
-27
@@ -4,9 +4,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import contextlib
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
import shutil
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import textwrap
|
import textwrap
|
||||||
@@ -14,6 +14,7 @@ from datetime import datetime
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
from escpos import exceptions as escpos_exceptions
|
||||||
from escpos import printer
|
from escpos import printer
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
@@ -24,6 +25,7 @@ USB_PRODUCT_ID = 0x0202
|
|||||||
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
|
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
|
||||||
TEXT_COLUMNS = 48 # font A columns on 80mm paper
|
TEXT_COLUMNS = 48 # font A columns on 80mm paper
|
||||||
HTTP_TIMEOUT = 15 # seconds
|
HTTP_TIMEOUT = 15 # seconds
|
||||||
|
MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded image
|
||||||
|
|
||||||
BASE_DIR = Path(__file__).resolve().parent
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
IMG_DIR = BASE_DIR / "img"
|
IMG_DIR = BASE_DIR / "img"
|
||||||
@@ -32,12 +34,16 @@ CONNECT_SCRIPT = BASE_DIR / "connect_receipt.sh"
|
|||||||
|
|
||||||
BANT_CATALOG_URL = "https://a.4cdn.org/bant/catalog.json"
|
BANT_CATALOG_URL = "https://a.4cdn.org/bant/catalog.json"
|
||||||
BANT_IMAGE_URL = "https://i.4cdn.org/bant/{tim}{ext}"
|
BANT_IMAGE_URL = "https://i.4cdn.org/bant/{tim}{ext}"
|
||||||
UNPRINTABLE_EXTENSIONS = {".gif", ".mp4", ".webm"}
|
PRINTABLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
|
||||||
|
|
||||||
|
|
||||||
def setup_network() -> None:
|
def setup_network(args: argparse.Namespace | None = None) -> None:
|
||||||
"""Bring up the printer's network interface via the connect script."""
|
"""Bring up the printer's network interface via the connect script."""
|
||||||
subprocess.run(["bash", str(CONNECT_SCRIPT)], check=True)
|
env = os.environ.copy()
|
||||||
|
if args and not getattr(args, "usb", False):
|
||||||
|
env["RECEIPT_PRINTER_IP"] = args.ip
|
||||||
|
env["RECEIPT_PRINTER_PORT"] = str(args.port)
|
||||||
|
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True)
|
||||||
|
|
||||||
|
|
||||||
def get_printer(args: argparse.Namespace) -> printer.Escpos:
|
def get_printer(args: argparse.Namespace) -> printer.Escpos:
|
||||||
@@ -71,6 +77,20 @@ def wrap_text(text: str) -> str:
|
|||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _printable(thread: dict) -> bool:
|
||||||
|
"""True when the thread's OP image is safe to cache and print.
|
||||||
|
|
||||||
|
Whitelist the extension (remote data, never trusted) and require a
|
||||||
|
numeric tim so the filename can't escape IMG_DIR.
|
||||||
|
"""
|
||||||
|
tim, ext = thread.get("tim"), thread.get("ext", "")
|
||||||
|
return (
|
||||||
|
isinstance(tim, int)
|
||||||
|
and isinstance(ext, str)
|
||||||
|
and ext.lower() in PRINTABLE_EXTENSIONS
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def download_random_bant_image() -> Path | None:
|
def download_random_bant_image() -> Path | None:
|
||||||
"""Download a random OP image from 4chan's /bant/ catalog.
|
"""Download a random OP image from 4chan's /bant/ catalog.
|
||||||
|
|
||||||
@@ -83,23 +103,27 @@ def download_random_bant_image() -> Path | None:
|
|||||||
catalog = response.json()
|
catalog = response.json()
|
||||||
|
|
||||||
threads = [thread for page in catalog for thread in page["threads"]]
|
threads = [thread for page in catalog for thread in page["threads"]]
|
||||||
image_threads = [
|
image_threads = [t for t in threads if _printable(t)]
|
||||||
t
|
|
||||||
for t in threads
|
|
||||||
if "tim" in t and "ext" in t and t["ext"].lower() not in UNPRINTABLE_EXTENSIONS
|
|
||||||
]
|
|
||||||
if not image_threads:
|
if not image_threads:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
thread = random.choice(image_threads)
|
thread = random.choice(image_threads)
|
||||||
dest = IMG_DIR / f"{thread['tim']}{thread['ext']}"
|
dest = IMG_DIR / f"{thread['tim']}{thread['ext'].lower()}"
|
||||||
if dest.is_file():
|
if dest.is_file():
|
||||||
return dest
|
return dest
|
||||||
|
|
||||||
image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=thread["ext"])
|
image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=thread["ext"])
|
||||||
img_response = requests.get(image_url, timeout=HTTP_TIMEOUT)
|
img_response = requests.get(image_url, timeout=HTTP_TIMEOUT)
|
||||||
img_response.raise_for_status()
|
img_response.raise_for_status()
|
||||||
dest.write_bytes(img_response.content)
|
data = img_response.content
|
||||||
|
if len(data) > MAX_IMAGE_BYTES:
|
||||||
|
print(
|
||||||
|
f"Skipping {dest.name}: {len(data) // 1024} KB exceeds the "
|
||||||
|
f"{MAX_IMAGE_BYTES // 1024} KB cap.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
dest.write_bytes(data)
|
||||||
|
|
||||||
return dest
|
return dest
|
||||||
|
|
||||||
@@ -123,10 +147,10 @@ def print_image(p: printer.Escpos, img_path: Path, args: argparse.Namespace) ->
|
|||||||
prepared = prepare_for_print(img_path)
|
prepared = prepare_for_print(img_path)
|
||||||
try:
|
try:
|
||||||
p.image(prepared, impl="bitImageColumn")
|
p.image(prepared, impl="bitImageColumn")
|
||||||
except Exception as e:
|
except (OSError, escpos_exceptions.Error) as e:
|
||||||
print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
|
print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
|
||||||
if not args.usb:
|
if not args.usb:
|
||||||
setup_network()
|
setup_network(args)
|
||||||
p = get_printer(args)
|
p = get_printer(args)
|
||||||
p.image(prepared, impl="bitImageColumn")
|
p.image(prepared, impl="bitImageColumn")
|
||||||
return p
|
return p
|
||||||
@@ -173,6 +197,7 @@ def cmd_print(p: printer.Escpos, args: argparse.Namespace) -> int:
|
|||||||
def cmd_qr(p: printer.Escpos, args: argparse.Namespace) -> int:
|
def cmd_qr(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||||
if args.message:
|
if args.message:
|
||||||
p.textln(wrap_text(args.message))
|
p.textln(wrap_text(args.message))
|
||||||
|
# Size 8 is the largest module size that reliably fits 576px with quiet zones.
|
||||||
p.qr(args.content, size=8, center=True)
|
p.qr(args.content, size=8, center=True)
|
||||||
p.cut()
|
p.cut()
|
||||||
return 0
|
return 0
|
||||||
@@ -200,7 +225,7 @@ def cmd_reprint(p: printer.Escpos, args: argparse.Namespace) -> int:
|
|||||||
def cmd_status(args: argparse.Namespace) -> int:
|
def cmd_status(args: argparse.Namespace) -> int:
|
||||||
try:
|
try:
|
||||||
if not args.usb:
|
if not args.usb:
|
||||||
setup_network()
|
setup_network(args)
|
||||||
p = get_printer(args)
|
p = get_printer(args)
|
||||||
p.close()
|
p.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -225,15 +250,31 @@ def cmd_list() -> int:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def cmd_clean() -> int:
|
def cmd_clean(yes: bool = False) -> int:
|
||||||
removed = 0
|
"""Remove cached images and the legacy full-width directory.
|
||||||
if IMG_DIR.is_dir():
|
|
||||||
removed = sum(1 for f in IMG_DIR.iterdir() if f.is_file())
|
Unlinks files instead of rmtree so a stray file outside the cache
|
||||||
shutil.rmtree(IMG_DIR)
|
can never be deleted; the dirs are left in place.
|
||||||
if LEGACY_FULLWIDTH_DIR.is_dir():
|
"""
|
||||||
removed += sum(1 for f in LEGACY_FULLWIDTH_DIR.iterdir() if f.is_file())
|
images = cached_images()
|
||||||
shutil.rmtree(LEGACY_FULLWIDTH_DIR)
|
legacy_files = (
|
||||||
print(f"Removed {removed} cached image(s).")
|
list(LEGACY_FULLWIDTH_DIR.iterdir()) if LEGACY_FULLWIDTH_DIR.is_dir() else []
|
||||||
|
)
|
||||||
|
if not images and not legacy_files:
|
||||||
|
print("Nothing to clean.")
|
||||||
|
return 0
|
||||||
|
if not yes:
|
||||||
|
reply = input(
|
||||||
|
f"Delete {len(images) + len(legacy_files)} cached image(s)? [y/N] "
|
||||||
|
)
|
||||||
|
if reply.strip().lower() not in ("y", "yes"):
|
||||||
|
print("Aborted.")
|
||||||
|
return 1
|
||||||
|
for f in images:
|
||||||
|
f.unlink()
|
||||||
|
for f in legacy_files:
|
||||||
|
f.unlink()
|
||||||
|
print(f"Removed {len(images) + len(legacy_files)} cached image(s).")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
@@ -305,7 +346,10 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
|
|
||||||
subparsers.add_parser("status", help="Check whether the printer is reachable")
|
subparsers.add_parser("status", help="Check whether the printer is reachable")
|
||||||
subparsers.add_parser("list", help="List the downloaded image cache")
|
subparsers.add_parser("list", help="List the downloaded image cache")
|
||||||
subparsers.add_parser("clean", help="Delete the downloaded image cache")
|
clean_p = subparsers.add_parser("clean", help="Delete the downloaded image cache")
|
||||||
|
clean_p.add_argument(
|
||||||
|
"-y", "--yes", action="store_true", help="Skip the confirmation prompt"
|
||||||
|
)
|
||||||
subparsers.add_parser("tui", help="Open the interactive terminal UI")
|
subparsers.add_parser("tui", help="Open the interactive terminal UI")
|
||||||
|
|
||||||
return parser
|
return parser
|
||||||
@@ -328,13 +372,13 @@ def main() -> int:
|
|||||||
if args.command == "list":
|
if args.command == "list":
|
||||||
return cmd_list()
|
return cmd_list()
|
||||||
if args.command == "clean":
|
if args.command == "clean":
|
||||||
return cmd_clean()
|
return cmd_clean(args.yes)
|
||||||
if args.command == "status":
|
if args.command == "status":
|
||||||
return cmd_status(args)
|
return cmd_status(args)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if not args.usb:
|
if not args.usb:
|
||||||
setup_network()
|
setup_network(args)
|
||||||
p = get_printer(args)
|
p = get_printer(args)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Could not connect to printer: {e}", file=sys.stderr)
|
print(f"Could not connect to printer: {e}", file=sys.stderr)
|
||||||
@@ -348,7 +392,8 @@ def main() -> int:
|
|||||||
"reprint": cmd_reprint,
|
"reprint": cmd_reprint,
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
return commands[args.command](p, args)
|
with contextlib.closing(p):
|
||||||
|
return commands[args.command](p, args)
|
||||||
except requests.RequestException as e:
|
except requests.RequestException as e:
|
||||||
print(f"Download failed: {e}", file=sys.stderr)
|
print(f"Download failed: {e}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|||||||
+20
-9
@@ -6,9 +6,11 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import contextlib
|
import contextlib
|
||||||
import io
|
import io
|
||||||
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from rich.text import Text
|
||||||
from textual import work
|
from textual import work
|
||||||
from textual.app import App, ComposeResult
|
from textual.app import App, ComposeResult
|
||||||
from textual.containers import Horizontal, Vertical
|
from textual.containers import Horizontal, Vertical
|
||||||
@@ -39,10 +41,13 @@ ACTIONS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def setup_network_quiet() -> None:
|
def setup_network_quiet(args: argparse.Namespace) -> None:
|
||||||
"""Run the connect script with output captured so it can't corrupt the TUI."""
|
"""Run the connect script with output captured so it can't corrupt the TUI."""
|
||||||
|
env = os.environ.copy()
|
||||||
|
env["RECEIPT_PRINTER_IP"] = args.ip
|
||||||
|
env["RECEIPT_PRINTER_PORT"] = str(args.port)
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
["bash", str(receipt.CONNECT_SCRIPT)], capture_output=True, text=True
|
["bash", str(receipt.CONNECT_SCRIPT)], env=env, capture_output=True, text=True
|
||||||
)
|
)
|
||||||
if result.stdout:
|
if result.stdout:
|
||||||
print(result.stdout, end="")
|
print(result.stdout, end="")
|
||||||
@@ -72,13 +77,13 @@ def run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, s
|
|||||||
def _dispatch(command: str, args: argparse.Namespace) -> int:
|
def _dispatch(command: str, args: argparse.Namespace) -> int:
|
||||||
if command == "list":
|
if command == "list":
|
||||||
return receipt.cmd_list()
|
return receipt.cmd_list()
|
||||||
|
# No TTY in the worker thread: the button press is the confirmation.
|
||||||
if command == "clean":
|
if command == "clean":
|
||||||
return receipt.cmd_clean()
|
return receipt.cmd_clean(yes=True)
|
||||||
if command == "status":
|
if command == "status":
|
||||||
return receipt.cmd_status(args)
|
return receipt.cmd_status(args)
|
||||||
if not args.usb:
|
if not args.usb:
|
||||||
setup_network_quiet()
|
setup_network_quiet(args)
|
||||||
p = receipt.get_printer(args)
|
|
||||||
handlers = {
|
handlers = {
|
||||||
"image": receipt.cmd_image,
|
"image": receipt.cmd_image,
|
||||||
"note": receipt.cmd_note,
|
"note": receipt.cmd_note,
|
||||||
@@ -86,7 +91,8 @@ def _dispatch(command: str, args: argparse.Namespace) -> int:
|
|||||||
"qr": receipt.cmd_qr,
|
"qr": receipt.cmd_qr,
|
||||||
"reprint": receipt.cmd_reprint,
|
"reprint": receipt.cmd_reprint,
|
||||||
}
|
}
|
||||||
return handlers[command](p, args)
|
with contextlib.closing(receipt.get_printer(args)) as p:
|
||||||
|
return handlers[command](p, args)
|
||||||
|
|
||||||
|
|
||||||
class ReceiptApp(App):
|
class ReceiptApp(App):
|
||||||
@@ -130,6 +136,7 @@ class ReceiptApp(App):
|
|||||||
def __init__(self, base_args: argparse.Namespace):
|
def __init__(self, base_args: argparse.Namespace):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.base_args = base_args
|
self.base_args = base_args
|
||||||
|
self.last_failure = 0 # exit code of the most recent failed action
|
||||||
|
|
||||||
def compose(self) -> ComposeResult:
|
def compose(self) -> ComposeResult:
|
||||||
yield Header()
|
yield Header()
|
||||||
@@ -257,15 +264,19 @@ class ReceiptApp(App):
|
|||||||
|
|
||||||
def report(self, command: str, rc: int, output: str) -> None:
|
def report(self, command: str, rc: int, output: str) -> None:
|
||||||
if output:
|
if output:
|
||||||
self.log_panel.write(output)
|
# Captured output is arbitrary text; Text() stops stray [..] parsing as markup.
|
||||||
|
self.log_panel.write(Text(output))
|
||||||
if rc == 0:
|
if rc == 0:
|
||||||
self.log_panel.write("[green]done[/green]")
|
self.log_panel.write("[green]done[/green]")
|
||||||
else:
|
else:
|
||||||
self.log_panel.write(f"[red]failed (exit {rc})[/red]")
|
self.log_panel.write(f"[red]failed (exit {rc})[/red]")
|
||||||
|
if rc != 0:
|
||||||
|
self.last_failure = rc
|
||||||
if command in ("image", "clean"):
|
if command in ("image", "clean"):
|
||||||
self.refresh_cache_list()
|
self.refresh_cache_list()
|
||||||
|
|
||||||
|
|
||||||
def run_tui(args: argparse.Namespace) -> int:
|
def run_tui(args: argparse.Namespace) -> int:
|
||||||
ReceiptApp(args).run()
|
app = ReceiptApp(args)
|
||||||
return 0
|
app.run()
|
||||||
|
return app.last_failure
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ class FakePrinter:
|
|||||||
def cut(self):
|
def cut(self):
|
||||||
self.calls.append(("cut", None))
|
self.calls.append(("cut", None))
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.calls.append(("close", None))
|
||||||
|
|
||||||
|
|
||||||
def make_catalog(threads):
|
def make_catalog(threads):
|
||||||
return [{"threads": threads}]
|
return [{"threads": threads}]
|
||||||
|
|||||||
+5
-1
@@ -24,6 +24,9 @@ class FakePrinter:
|
|||||||
def cut(self):
|
def cut(self):
|
||||||
self.calls.append(("cut", None))
|
self.calls.append(("cut", None))
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.calls.append(("close", None))
|
||||||
|
|
||||||
|
|
||||||
def make_base_args(**overrides):
|
def make_base_args(**overrides):
|
||||||
defaults = {
|
defaults = {
|
||||||
@@ -50,7 +53,8 @@ def test_run_action_note(fake_printer):
|
|||||||
|
|
||||||
assert rc == 0
|
assert rc == 0
|
||||||
assert ("textln", "hello") in fake_printer.calls
|
assert ("textln", "hello") in fake_printer.calls
|
||||||
assert fake_printer.calls[-1] == ("cut", None)
|
assert fake_printer.calls[-2] == ("cut", None)
|
||||||
|
assert fake_printer.calls[-1] == ("close", None) # handle released after action
|
||||||
|
|
||||||
|
|
||||||
def test_run_action_qr(fake_printer):
|
def test_run_action_qr(fake_printer):
|
||||||
|
|||||||
Reference in New Issue
Block a user