server: harden the surfaces a public deployment leaves exposed
CI & Build / Build now, or wait for Android? (push) Successful in 3s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 9s
CI & Build / Python tests (push) Failing after 11s
CI & Build / Build & push image (push) Successful in 33s

On a LAN the login form is reachable by people you already trust. Exposed, it is
reachable by everyone, and nothing in front of it was counting.

Three credential routes — /login, /register and /device-login — now throttle.
Every attempt is counted against BOTH the account and the calling address, and
either can refuse it. The account key is the one that matters and the one that
cannot be forged: it stops stuffing against a known email no matter how many
addresses the attempts arrive from. The address key bounds one source spraying
many accounts, and is best-effort by nature — behind a proxy it comes from
X-Forwarded-For, which a caller can set to anything if the app is exposed
directly. That is exactly why it isn't the only key.

The check runs BEFORE the password is verified, which is the other half of what
this protects. bcrypt is deliberately slow; an unauthenticated caller who can
trigger it without limit has a CPU exhaustion primitive as well as a guessing
one. Sliding rather than fixed windows, because a fixed one lets twice the limit
through across a boundary. Bucket count is capped so a rotating forged header
can't turn the limiter into the exhaustion it prevents.

A sign-in against an email with no account now spends a real bcrypt against a
throwaway hash first. Without it "no such account" returned in microseconds
while a wrong password took ~100ms, which is a reliable oracle for which emails
are registered here.

Every response carries a CSP with script-src 'self', object-src 'none' and
frame-ancestors 'none', plus nosniff, a referrer policy and a permissions
policy. The app has no inline and no third-party scripts, so this concedes
nothing; the exceptions are honest — inline STYLE (Vue writes it itself for
v-show and the FLIP), and remote images (a link preview renders the og:image of
an arbitrary host, over either scheme, since a LAN install is served over http).
HSTS only where the request already arrived over TLS, and scoped to the one
host: no includeSubDomains, no preload, neither of which is this app's to
commit.

X-Forwarded-Proto detection moved into one `_is_https()` — the session cookie's
Secure flag and HSTS are the same question, and answering it twice is how the
two drift apart.

docs/public-hosting.md is the rest of it: the four things only the operator can
do (close registration, terminate TLS and forward the scheme, stop publishing
the app port, back up the attachment volume as well as the database), and an
honest list of what the app does NOT have — no email verification, no password
reset, no second factor, no per-user quota, no audit log. Those aren't blockers
for an instance whose accounts are people you know. They're the reason not to
leave signups open to strangers.
This commit is contained in:
2026-08-21 22:01:37 -04:00
parent 16f86bef93
commit b6152ec18b
8 changed files with 631 additions and 7 deletions
+77 -4
View File
@@ -31,6 +31,19 @@ STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
mimetypes.add_type("application/manifest+json", ".webmanifest")
def _is_https() -> bool:
"""Whether this request reached us over TLS — directly, or through a proxy that
terminated it and said so in X-Forwarded-Proto.
Shared by the session cookie's Secure flag and by HSTS, because they are the same
question and answering it twice is how the two drift apart.
"""
if not has_request_context():
return False
forwarded = request.headers.get("X-Forwarded-Proto", "").split(",")[0].strip().lower()
return forwarded == "https" or request.is_secure
class _AutoSecureSessionInterface(SecureCookieSessionInterface):
"""Mark the session cookie `Secure` whenever the request arrived over HTTPS —
directly, or via a TLS-terminating reverse proxy that sets X-Forwarded-Proto.
@@ -42,10 +55,7 @@ class _AutoSecureSessionInterface(SecureCookieSessionInterface):
"""
def get_cookie_secure(self, app: Quart) -> bool:
if not has_request_context():
return False
forwarded = request.headers.get("X-Forwarded-Proto", "").split(",")[0].strip().lower()
return forwarded == "https" or request.is_secure
return _is_https()
def create_app() -> Quart:
@@ -101,6 +111,69 @@ def create_app() -> Quart:
with suppress(asyncio.CancelledError):
await task
@app.after_request
async def _security_headers(response):
"""Headers a publicly-reachable instance should be sending.
None of these change how the app behaves for a legitimate caller; they narrow
what a browser will do if something else goes wrong.
The CSP is the substantive one. `script-src 'self'` means that even if some
future path did manage to reflect user text into the page, the browser would
refuse to run it — the app has no inline scripts and no third-party scripts,
so nothing legitimate is given up. The exceptions are honest ones:
- `style-src 'unsafe-inline'` — Vue writes inline styles itself (`v-show`
toggling display, TransitionGroup's FLIP setting transforms). Inline
STYLE is not an execution primitive the way inline script is.
- `img-src https: http:` — link previews render the remote og:image of
whatever was linked, which is an arbitrary host by definition. Both
schemes, because a LAN install is served over http and would otherwise
lose every preview image; on an https instance the browser blocks the
http ones as mixed content anyway, so naming it concedes nothing.
- `blob:`/`data:` — attachment previews and the desktop's blob URI scheme.
`frame-ancestors 'none'` replaces the older X-Frame-Options and is what stops
the app being framed for clickjacking; `form-action 'self'` stops a form from
being pointed at another origin.
"""
response.headers.setdefault(
"Content-Security-Policy",
"default-src 'self'; "
"base-uri 'self'; "
"object-src 'none'; "
"frame-ancestors 'none'; "
"form-action 'self'; "
"script-src 'self'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data: blob: https: http:; "
"font-src 'self' data:; "
"media-src 'self' blob:; "
"connect-src 'self'",
)
# Content-type sniffing turns a file we said was text into whatever the bytes
# look like. The attachment route already sets this; every other response
# deserves it too.
response.headers.setdefault("X-Content-Type-Options", "nosniff")
# Note titles and label names end up in the URL of a search or a label lens,
# and a full Referer would hand them to any site a link preview points at.
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
# Nothing here uses a camera, a microphone or a location, so nothing embedded
# in a page should be able to ask on its behalf.
response.headers.setdefault(
"Permissions-Policy", "camera=(), microphone=(), geolocation=(), interest-cohort=()"
)
# HSTS only where the request already arrived over TLS — the same detection
# the session cookie uses. Sending it on a plain-HTTP LAN install would tell
# the browser to refuse the only scheme that install serves.
#
# Scoped to this host: no `includeSubDomains` and no `preload`, both of which
# commit domains this app does not own. A browser still remembers the policy
# for up to a year after the header stops being sent, which is the point of
# it — worth knowing before putting a hostname behind TLS temporarily.
if _is_https():
response.headers.setdefault("Strict-Transport-Security", "max-age=31536000")
return response
@app.get("/api/health")
async def health():
return jsonify({"status": "ok", "version": app.config["APP_VERSION"]})
+90 -3
View File
@@ -11,7 +11,13 @@ from .common import iso
from .db import session_scope
from .models.device_token import DeviceToken
from .models.user import User
from .security import generate_token, hash_password, hash_token, verify_password
from .ratelimit import (
client_address,
register_by_address,
sign_in_by_account,
sign_in_by_address,
)
from .security import dummy_verify, generate_token, hash_password, hash_token, verify_password
from .settings import get_setting
bp = Blueprint("auth", __name__, url_prefix="/api/auth")
@@ -106,6 +112,52 @@ def require_admin(fn):
return wrapper
def _throttled(retry_after: int):
"""The 429 every throttled credential route returns.
Deliberately says nothing about WHICH limit was hit or how many attempts are
left — that would tell someone probing whether the email they guessed exists.
`Retry-After` is standard and is the one thing a legitimate client (or person)
genuinely needs.
"""
return (
jsonify({"error": "too many attempts — try again shortly"}),
429,
{"Retry-After": str(retry_after)},
)
def _sign_in_block(email: str) -> int | None:
"""Seconds to wait before this sign-in may be attempted, or None to proceed.
Checked BEFORE the password is verified, so a throttled attempt costs no bcrypt
— which is the other half of what this protects: hashing is deliberately slow,
and an unauthenticated caller who can trigger it without limit has a CPU
exhaustion primitive, not just a guessing one.
"""
address = client_address()
waits = [
sign_in_by_address.retry_after(address),
sign_in_by_account.retry_after(email) if email else None,
]
live = [w for w in waits if w is not None]
return max(live) if live else None
def _sign_in_failed(email: str) -> None:
address = client_address()
sign_in_by_address.record(address)
if email:
sign_in_by_account.record(email)
def _sign_in_succeeded(email: str) -> None:
"""Clear the account's history on success. The address keeps its count: one
correct password does not vouch for the other attempts from there."""
if email:
sign_in_by_account.forget(email)
@bp.post("/register")
async def register():
data = await request.get_json(silent=True) or {}
@@ -120,6 +172,14 @@ async def register():
if not display_name:
display_name = email.split("@", 1)[0]
# Counted by attempt rather than by failure: a rejected registration still cost a
# round trip and a uniqueness check, and on an instance with signups open the
# thing worth bounding is how fast accounts can appear at all.
wait = register_by_address.retry_after(client_address())
if wait is not None:
return _throttled(wait)
register_by_address.record(client_address())
async with session_scope() as db:
user_count = await db.scalar(select(func.count()).select_from(User)) or 0
is_first = user_count == 0
@@ -150,10 +210,23 @@ async def login():
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
wait = _sign_in_block(email)
if wait is not None:
return _throttled(wait)
async with session_scope() as db:
user = await db.scalar(select(User).where(User.email == email))
if user is None or not user.password_hash or not verify_password(password, user.password_hash):
if user is None or not user.password_hash:
# Hash anyway. Without this, "no such account" returns in microseconds
# while a wrong password takes bcrypt's deliberate ~100ms, and the
# difference is a reliable oracle for which emails have accounts here.
dummy_verify(password)
_sign_in_failed(email)
return jsonify({"error": "invalid email or password"}), 401
if not verify_password(password, user.password_hash):
_sign_in_failed(email)
return jsonify({"error": "invalid email or password"}), 401
_sign_in_succeeded(email)
session[SESSION_KEY] = str(user.id)
session.permanent = True
return jsonify(_serialize_user(user))
@@ -210,10 +283,24 @@ async def device_login():
password = data.get("password") or ""
if not email or not password:
return jsonify({"error": "email and password are required"}), 400
# Same budget as the web sign-in, and the SAME counters — this route hands out a
# long-lived bearer token, so leaving it unthrottled would just move the guessing
# here from /login.
wait = _sign_in_block(email)
if wait is not None:
return _throttled(wait)
async with session_scope() as db:
user = await db.scalar(select(User).where(User.email == email))
if user is None or not user.password_hash or not verify_password(password, user.password_hash):
if user is None or not user.password_hash:
dummy_verify(password)
_sign_in_failed(email)
return jsonify({"error": "invalid email or password"}), 401
if not verify_password(password, user.password_hash):
_sign_in_failed(email)
return jsonify({"error": "invalid email or password"}), 401
_sign_in_succeeded(email)
row, token = await _issue_device_token(db, user.id, data.get("name") or "")
await db.commit()
return jsonify({"token": token, "device": _serialize_device(row), "user": _serialize_user(user)}), 201
+140
View File
@@ -0,0 +1,140 @@
"""Throttling for the endpoints that a public deployment leaves exposed.
Only the credential endpoints are rate-limited: login, register, and the native
device-link exchange. Everything else already needs a session or a device token to
reach, so an attacker has to get through one of these three first.
## Why in-process is enough here, and where that stops being true
State lives in module-level dicts, so it is per-process. That is correct for how
this image actually serves — one hypercorn worker (see the Dockerfile, and the
same assumption the trash sweeper documents in app.py). If that ever gains
``--workers N``, each worker would keep its own counters and the effective limit
would multiply by N; the fix then is a shared store (the Postgres connection is
already there), not a bigger number here.
## Two keys, on purpose
Every attempt is counted against BOTH the account being tried and the address it
came from, and either one can refuse it:
- **The account** is the key that matters, and the key that cannot be forged. It
is what stops credential stuffing against one known email, no matter how many
addresses the attempts arrive from.
- **The address** bounds the damage from one source spraying many accounts. It is
best-effort by nature — behind a reverse proxy the client address is read from
``X-Forwarded-For``, which a caller can set to anything if the app is exposed
directly. That is precisely why it is not the only key.
Counting is by failure for the sign-in routes and by attempt for registration: a
correct password should never move someone closer to being locked out, but every
registration is a row in the users table whether it succeeds or not.
"""
from __future__ import annotations
import time
from collections import deque
from quart import request
# Failed sign-ins tolerated per account before it stops answering, and for how long.
# Ten is comfortably above a person mistyping a password and far below anything that
# makes a dictionary worth running.
ACCOUNT_LIMIT = 10
ACCOUNT_WINDOW_S = 15 * 60
# Wider, because one address is legitimately many people: a household, an office
# behind NAT, a phone on carrier-grade NAT.
ADDRESS_LIMIT = 50
ADDRESS_WINDOW_S = 15 * 60
# Registration is scarcer than a sign-in — it creates a row, and on a private
# instance the honest number of accounts anyone needs to make is one.
REGISTER_LIMIT = 5
REGISTER_WINDOW_S = 60 * 60
# Never let the bookkeeping become the denial of service: an attacker rotating a
# forged X-Forwarded-For could otherwise mint an unbounded number of buckets. Well
# above any real deployment's distinct-caller count, so a legitimate instance never
# reaches it; when it is reached the oldest buckets are dropped, which at worst
# forgives some attempts.
MAX_BUCKETS = 10_000
class SlidingWindow:
"""Counts events per key over a trailing window.
Sliding rather than a fixed window because a fixed one lets twice the limit
through across a boundary — 10 at 14:59 and 10 at 15:00 — which for a login
limiter is the difference between the number meaning something and not.
"""
def __init__(self, limit: int, window_s: float) -> None:
self.limit = limit
self.window_s = window_s
self._hits: dict[str, deque[float]] = {}
def _prune(self, key: str, now: float) -> deque[float]:
hits = self._hits.get(key)
if hits is None:
hits = deque()
# Insertion-ordered, so the first key is the least recently created.
if len(self._hits) >= MAX_BUCKETS:
self._hits.pop(next(iter(self._hits)), None)
self._hits[key] = hits
cutoff = now - self.window_s
while hits and hits[0] <= cutoff:
hits.popleft()
return hits
def retry_after(self, key: str, now: float | None = None) -> int | None:
"""Seconds until `key` may try again, or None while it is still under the
limit. Read-only — it does not count as an attempt."""
now = time.monotonic() if now is None else now
hits = self._prune(key, now)
if len(hits) < self.limit:
return None
# The window frees up when its OLDEST hit falls out of it.
return max(1, int(hits[0] + self.window_s - now) + 1)
def record(self, key: str, now: float | None = None) -> None:
now = time.monotonic() if now is None else now
self._prune(key, now).append(now)
def forget(self, key: str) -> None:
"""Drop a key's history. Used after a successful sign-in, so someone who
fumbled a password twice and then got it right starts clean rather than
carrying those two for the next quarter of an hour."""
self._hits.pop(key, None)
def clear(self) -> None:
self._hits.clear()
sign_in_by_account = SlidingWindow(ACCOUNT_LIMIT, ACCOUNT_WINDOW_S)
sign_in_by_address = SlidingWindow(ADDRESS_LIMIT, ADDRESS_WINDOW_S)
register_by_address = SlidingWindow(REGISTER_LIMIT, REGISTER_WINDOW_S)
def client_address() -> str:
"""The caller's address, as well as it can be known.
``X-Forwarded-For`` is a list appended to by each hop, so the leftmost entry is
the original client — and also the only entry a client can choose for itself.
It is trusted here anyway, because the alternative behind a reverse proxy is to
see the proxy's address for every request on earth and rate-limit the entire
internet as one caller. The account-keyed limit is the one that holds when this
one is lied to.
"""
forwarded = request.headers.get("X-Forwarded-For", "")
if forwarded:
first = forwarded.split(",")[0].strip()
if first:
return first[:64] # bounded: this becomes a dict key
return (request.remote_addr or "unknown")[:64]
def reset_all() -> None:
"""Drop every counter. For tests — nothing in the app calls this."""
for window in (sign_in_by_account, sign_in_by_address, register_by_address):
window.clear()
+17
View File
@@ -14,6 +14,23 @@ def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8")[:_MAX_BCRYPT_BYTES], bcrypt.gensalt()).decode("utf-8")
# A real bcrypt hash of a value nobody can present, used only to spend the time a
# verification would have. Computed once at import — generating it per call would
# cost a gensalt+hash on top of the checkpw and make the "no such user" path SLOWER
# than the real one, which is the same oracle pointing the other way.
_DUMMY_HASH = bcrypt.hashpw(secrets.token_bytes(32), bcrypt.gensalt())
def dummy_verify(password: str) -> None:
"""Burn one password verification against a throwaway hash.
For the sign-in path when the email has no account: it makes "no such user" cost
what "wrong password" costs, so response time stops answering the question of
which emails are registered here.
"""
bcrypt.checkpw(password.encode("utf-8")[:_MAX_BCRYPT_BYTES], _DUMMY_HASH)
def verify_password(password: str, password_hash: str) -> bool:
try:
return bcrypt.checkpw(password.encode("utf-8")[:_MAX_BCRYPT_BYTES], password_hash.encode("utf-8"))