Make login optional and fix 403 on changes

- CASHBOOK_PASSWORD is now optional; without it there's no login and
  the server logs a warning
- Origin check compares host names only, and also accepts
  X-Forwarded-Host and CASHBOOK_ALLOWED_HOSTS, so changes work when the
  app is reached by IP, on another port or through a proxy; refusals
  are logged with the reason and explained in the error
- Add a favicon so browsers stop requesting a missing /favicon.ico

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-24 17:41:01 +13:00
1 parent 5dac554050
commit 17b48f25e8
4 files changed
+39 -13

No files matched your search

+14 -7
View File
@@ -23,7 +23,7 @@ Everything runs on your machine; nothing is sent anywhere.
### Docker Compose (recommended)
One-time setup, as the user who should own the books (uid 1000 by default).
Create the data folder, then put a login password in `.env`:
Create the data folder, then put a login password in `.env` (optional, see below):
```bash
mkdir -p data
@@ -40,7 +40,8 @@ docker compose up -d --build
```
Open <http://127.0.0.1:8765> and log in as `cashbook` with the password from
`.env`. Compose refuses to start if `CASHBOOK_PASSWORD` isn't set. Stop it with `docker compose down`, and check it with
`.env`. With no `CASHBOOK_PASSWORD` set, there's no login: anyone who can reach the
port can see and change your books, so only do that on a network you trust. Stop it with `docker compose down`, and check it with
`docker compose ps` (it reports `healthy`) or `docker compose logs`.
**What the compose file sets up**
@@ -48,7 +49,7 @@ Open <http://127.0.0.1:8765> and log in as `cashbook` with the password from
- **Data:** `./data` is mounted at `/data` and holds the cashbooks and `statements/`
(uploads go there). Back up this folder.
- **Login:** HTTP Basic auth, with the password from the `CASHBOOK_PASSWORD`
environment variable.
environment variable. Leave it unset to turn the login off.
- **Network:** published on `127.0.0.1:8765` only.
- **Lockdown:**
- read-only container filesystem, with scratch space only in `/tmp` (tmpfs);
@@ -62,17 +63,23 @@ Open <http://127.0.0.1:8765> and log in as `cashbook` with the password from
| Variable | Default | Purpose |
|---|---|---|
| `CASHBOOK_PASSWORD` | *(required)* | login password |
| `CASHBOOK_PASSWORD` | *(none)* | login password; unset means no login |
| `CASHBOOK_USER` | `1000:1000` | uid:gid to run as; it should own `data/`. Use `0:0` with rootless Docker, which maps container root to you. |
| `CASHBOOK_USERNAME` | `cashbook` | login name |
| `CASHBOOK_BIND` | `127.0.0.1` | host address to publish on |
| `CASHBOOK_PORT` | `8765` | host port |
| `CASHBOOK_ALLOWED_HOSTS` | | extra host names you open the app by, comma-separated; see below |
**Reaching it from other machines:** keep it on `127.0.0.1` and put a reverse proxy
with HTTPS in front (Caddy, nginx, Traefik). Basic auth sends the password with every
request, so don't expose it over plain HTTP. The proxy must pass the original `Host`
header through; uploads and changes are refused when the page's origin doesn't match
it. For example, with Caddy:
request, so don't expose it over plain HTTP.
To block other websites from making changes through your login, the app refuses
changes whose page address doesn't match the server's host name. It checks the
`Host` and `X-Forwarded-Host` headers. Caddy passes the original host through. With
nginx, add `proxy_set_header Host $host;`. Otherwise, list the name you use in
`CASHBOOK_ALLOWED_HOSTS`. A refused request shows up in `docker compose logs` with
the reason. A Caddy example:
```
cashbook.example.com {
+5 -2
View File
@@ -15,10 +15,13 @@ services:
ports:
- "${CASHBOOK_BIND:-127.0.0.1}:${CASHBOOK_PORT:-8765}:8765"
# Browser login (HTTP Basic). Set CASHBOOK_PASSWORD in .env; compose won't start without it.
# Browser login (HTTP Basic): set CASHBOOK_PASSWORD in .env. Leave it unset to turn
# the login off; then anyone who can reach the port can see and change your books.
environment:
CASHBOOK_USERNAME: "${CASHBOOK_USERNAME:-cashbook}"
CASHBOOK_PASSWORD: "${CASHBOOK_PASSWORD:?set CASHBOOK_PASSWORD in .env}"
CASHBOOK_PASSWORD: "${CASHBOOK_PASSWORD:-}"
# other host names you reach it by, if the proxy doesn't pass Host through
CASHBOOK_ALLOWED_HOSTS: "${CASHBOOK_ALLOWED_HOSTS:-}"
volumes:
# cashbooks and statements/ (uploads go there too)
+1
View File
@@ -4,6 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cashbook</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%230b6bcb'/%3E%3Ctext x='16' y='23' font-size='19' font-family='sans-serif' font-weight='700' text-anchor='middle' fill='white'%3E$%3C/text%3E%3C/svg%3E">
<style>
:root {
--bg: #f6f7f9; --panel: #ffffff; --text: #1d2330; --muted: #6a7282; --line: #e3e6eb;
+19 -4
View File
@@ -299,6 +299,8 @@ def api(method, path, query, body):
# Optional HTTP Basic auth: set CASHBOOK_PASSWORD, or CASHBOOK_PASSWORD_FILE (e.g. a
# Docker secret). The user name is CASHBOOK_USERNAME (default "cashbook").
AUTH = None
# extra host names the app is reached by (comma-separated), e.g. behind a proxy
ALLOWED_HOSTS = {h.strip().lower() for h in os.environ.get("CASHBOOK_ALLOWED_HOSTS", "").split(",") if h.strip()}
SECURITY_HEADERS = {
"Cache-Control": "no-store",
@@ -347,12 +349,24 @@ class Handler(BaseHTTPRequestHandler):
return given.startswith("Basic ") and hmac.compare_digest(given[6:].strip(), AUTH)
def _same_origin(self):
# browsers send Origin on POST; it must match the host the page was served from
"""Browsers send Origin on POST; refuse ones from other sites.
Compares host names only (ports differ behind Docker port maps and proxies),
against Host, X-Forwarded-Host and CASHBOOK_ALLOWED_HOSTS.
"""
origin = self.headers.get("Origin")
if not origin:
return True
return urlparse(origin).netloc == self.headers.get("Host") or \
urlparse(origin).hostname in ("127.0.0.1", "localhost")
host_of = lambda h: urlparse("//" + h.strip()).hostname
allowed = {"localhost", "127.0.0.1", "::1"} | ALLOWED_HOSTS
for h in [self.headers.get("Host", "")] + self.headers.get("X-Forwarded-Host", "").split(","):
if h.strip():
allowed.add(host_of(h))
if urlparse(origin).hostname in allowed:
return True
print(f"Refused {self.command} {self.path}: Origin {origin} is not one of {sorted(allowed)}. "
"If that's your address, add it to CASHBOOK_ALLOWED_HOSTS.", file=sys.stderr, flush=True)
return False
def _handle(self, method):
url = urlparse(self.path)
@@ -362,7 +376,8 @@ class Handler(BaseHTTPRequestHandler):
return self._send(401, {"error": "login required"},
headers={"WWW-Authenticate": 'Basic realm="Cashbook", charset="UTF-8"'})
if method == "POST" and not self._same_origin():
return self._send(403, {"error": "forbidden"})
return self._send(403, {"error": "Refused: this page's address doesn't match the server's. "
"See the server log, or set CASHBOOK_ALLOWED_HOSTS."})
if method == "GET" and url.path in ("/", "/index.html"):
with open(os.path.join(HERE, "static", "index.html"), "rb") as f:
return self._send(200, f.read(), "text/html; charset=utf-8")