Commit Graph
30 Commits
Author SHA1 Message Date
davide 0d2fef6502 Delete BUGS.md now that both audits' findings are closed
B-01 … B-49 are all fixed, so the file held no open work — only a history that
git already keeps. CLAUDE.md now explains how to resolve the B-nn markers left
throughout the code against that history, and repeats the caveat the empty list
does not carry on its own: no open findings is not the same as no bugs.

The one remaining reference, in an already-applied migration's docstring, is
left as the historical record it is.
2026-07-27 23:37:02 +02:00
davide e7f844b11f Publish an SSE update from the bet/withdrawal rollback paths (B-49)
_release_failed_bet and _release_failed_withdrawal restored the balance, freed
the reserved UTXOs and (for a bet) removed the participant without calling
broadcaster.publish(), so every dashboard kept showing the phantom bet and the
reduced balance until its next poll — while the success path and the
reconciler's own abandon path both published.

The two regression tests pre-open the round before subscribing: place_bet opens
one itself, and that publish() would otherwise satisfy the assertion whether or
not the rollback published anything.
2026-07-27 23:35:10 +02:00
davide 4c80c1c5bf Cap the number of inputs a transaction may spend (B-48)
select_utxos had no ceiling on input count, so an address fragmented into many
small deposits built an ever-larger transaction whose fee — deducted from the
amount being moved — eroded the bet's share of the pool or the withdrawn amount,
and past a few hundred inputs stopped being standard at all.

MAX_TX_INPUTS (50) now bounds the selection. Reaching the cap without covering
the target is reported as its own "too_many_inputs" code, distinct from having
no funds, with the cap carried in the error params for the 7 translations. The
payout path records the same distinction in its payout_failed audit reason.
2026-07-27 23:30:06 +02:00
davideandClaude Sonnet 5 6a90136b50 Widen raw_tx_hex and payload_json from String to Text (B-47)
Both held arbitrary-length data (a raw signed transaction hex, an audit
payload) in a bare String, which SQLAlchemy compiles to VARCHAR with no
length. SQLite and PostgreSQL accept that; other backends like MySQL
require a length on VARCHAR and would reject it. Add a migration
(verified upgrade/downgrade/upgrade round-trip, and confirmed with
`alembic check` that it leaves no further diff against the models).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 16:24:05 +02:00
davideandClaude Sonnet 5 31bc9a327f Compare admin token as UTF-8 bytes to avoid TypeError on non-ASCII input (B-46)
secrets.compare_digest raises TypeError instead of returning False when a
str argument contains non-ASCII characters, turning a bad admin token into
an unhandled 500 instead of the expected 403. Encode both sides before
comparing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 16:17:40 +02:00
davideandClaude Sonnet 5 6045c89ed0 Bound admin list endpoint limits, add status filter to pending-transactions (B-45)
/admin/rounds and /admin/audit-log accepted any limit, including -1 (which
SQLite treats as "no limit"), and /admin/pending-transactions had no limit
at all -- it grows without end. Add Query(default=..., ge=1, le=500) to all
three, plus an optional status filter on pending-transactions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 16:10:53 +02:00
davideandClaude Sonnet 5 a574db0d93 Align README and running-the-server.md with the Docker-only policy (B-44)
CLAUDE.md declares the server always runs via Docker (dev and prod
alike) with no supported bare-uvicorn workflow, but README's Quick
start and docs/running-the-server.md's "Locale / venv" section still
documented running uvicorn directly — a leftover from before that
policy was adopted. Rewrite both to a single Docker-only path and
update CLAUDE.md's own note about it.

Verified docker compose run --rm app python scripts/generate_master_key.py
against a real build/run to confirm the Quick start's Docker commands
actually work as documented.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 16:04:24 +02:00
davideandClaude Sonnet 5 d60da11603 Add baseline HTTP security headers in Caddy (B-43)
Caddy adds none of these on its own. Add HSTS, X-Content-Type-Options,
X-Frame-Options, Referrer-Policy and a CSP scoped to default-src
'self' plus the one external asset (Google Fonts). script-src/style-src
need 'unsafe-inline' because both SPAs rely on inline onclick handlers
and style="" attributes throughout — removing those is a separate,
larger refactor.

Validated with `caddy validate` and a live container curl check.
Adds a static regression test asserting the header directives stay
present in the Caddyfile, since nothing else in the Python suite
exercises it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:44:47 +02:00
davideandClaude Sonnet 5 22e3cfb2be Disable Swagger/ReDoc/OpenAPI JSON by default (B-42)
They enumerate the entire API surface, admin endpoints included, to
anyone who requests them. Gate them behind a new ENABLE_API_DOCS
setting (off by default) and update README/docs and BUGS.md/CLAUDE.md
open-bug counts accordingly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:34:49 +02:00
davideandClaude Sonnet 5 0b44fe632e Distinguish a pending-only balance from a truly insufficient one (B-37)
request_withdrawal validated against confirmed UTXOs only and answered
a flat insufficient_balance even when the requested amount was covered
by the pending-inclusive balance the UI actually shows (unconfirmed
change from a recent bet/withdrawal) — contradicting what the user was
looking at on screen. Raise balance_pending_confirmation instead when
compute_pending_balance covers the amount, carrying the pending sats
in params, with its error.* string in all 7 languages.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 14:23:00 +02:00
davideandClaude Sonnet 5 7fa26df104 Make a stalled draw wait observable (B-36)
_wait_for_next_block had no timeout, no log, and no audit entry: a
connection that stopped advancing the tip left a round silently frozen
in "drawing" with nothing in /admin to explain why. Log progress
periodically, write a draw_stalled audit entry past a threshold (a few
block-time multiples), and surface the wait via a new Round.drawing_started_at
column, exposed as draw_waiting_since in GET /rounds/current.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 14:12:27 +02:00
davideandClaude Sonnet 5 bb8b71278a Stamp UTC on naive API timestamps before serializing (B-35)
SQLite/aiosqlite returns DateTime columns as naive even though every
value is written in UTC, so a bare .isoformat() dropped the offset and
the frontend's new Date() parsed it as local time. Add a shared
isoformat_utc() helper and use it at every call site that was missing
the fix already applied ad hoc in rounds.py.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 12:20:22 +02:00
davide fe5639a037 Update CLAUDE.md 2026-07-27 11:05:53 +02:00
davideandClaude Opus 5 845ba98409 Record the audit outcome and the architecture it changed
BUGS.md keeps every finding's original description and gains, per entry, what was
actually done and where its regression test lives — including the two entries
fixed differently from the plan (B-15 validates at startup, B-09 kept both
callers plus a bounded retry) and the one only partially fixed by decision (B-16,
where shipping the guide was deferred).

It also gains a Runtime verification section, which is the part worth reading:
what the live Docker deployment actually demonstrated (startup validation on the
real .env, the listener connecting and holding, rounds cycling, the migration
applied, and the reconciler's missing-tx heuristic checked against the real
server's error message) separated from what has no runtime evidence at all —
nothing has spent money since the restart, so the two-phase write, the RBF
retargeting, the reconciler's actual behaviour and the dust path are unit-tested
only. A green suite is not a working deployment, and the file now says so.

CLAUDE.md documents the two things a reader would otherwise have to reverse-
engineer: the transaction lifecycle (why rows are written before broadcasting,
what each PendingTransaction status means, why spent_txid must track the current
txid, and that one-active-round is now a DB invariant) and the Electrum
connection's rotation/keepalive/timeout behaviour. Its Known gaps list is rewritten
to say what is still open now that transaction-level state self-heals but
round-level state does not.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:35:28 +02:00
davideandClaude Opus 5 0cf35147ad Answer user-facing API failures with a machine-readable error code
The dashboard now speaks seven languages but every failure path still showed
the API's raw English text ("insufficient balance", "current password is
incorrect"), which is the most frequent and least forgiving part of the UI to
leave untranslated.

Rather than teach the API about locales, it keeps answering in one language
and hands the client something to translate: `detail` becomes
{code, message, params}, where message stays English for non-dashboard
consumers (curl, tests) and code maps onto `error.<code>` in i18n.js. An
unknown code falls back to message, so a client older or newer than the server
degrades to English instead of a blank toast.

Domain exceptions (BetError, WithdrawalError) subclass the new ApiError and
carry the code from where the failure actually happens; str(exc) is still the
English message, so existing tests keep matching on it. Interpolated values
travel in params rather than baked into the English sentence — amounts as
*_sats, from which the frontend derives a *_plm sibling, so each language can
place them wherever its grammar wants.

admin.js reads detail.message defensively: the admin endpoints still return a
bare string, but the shared auth dependencies now return the structured form.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:44:39 +02:00
davideandClaude Opus 5 7048fe7ea6 Translate the user-facing dashboard into 7 languages
Adds app/static/i18n.js: a flat key -> string table for en/it/es/fr/de/ru/zh,
loaded before app.js so t() is available everywhere. No build step and no
fetch, consistent with the rest of these static pages. Language comes from
localStorage, then navigator.language, then en.

Static markup is translated by attribute (data-i18n and its -html/-placeholder/
-title/-aria-label/-alt variants); anything rendered from server data goes
through t() in app.js and is re-rendered by onLanguageChange(). An element
belongs to one mechanism or the other, never both, or the two overwrite each
other — which is why #bet-btn has no data-i18n: its label carries the
admin-configurable bet amount, so renderBetButton() owns it and reads the
amount from /rounds/current instead of hardcoding "10 PLM" in seven files.

The switcher sits in the chain-bar rather than the navbar because the navbar
is hidden until login, which would leave the landing page and the login form
untranslatable for exactly the users who need to switch. It uses language
names rather than flag emoji: flags don't render on every platform and don't
map one-to-one onto languages.

withLoading now snapshots innerHTML instead of textContent — several of these
buttons wrap an <svg> plus a <span data-i18n>, both of which a textContent
round-trip flattened away, permanently losing the icon and the translation
hook. It re-applies translations to the restored subtree in case the language
changed while the request was in flight.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:43:35 +02:00
davide 8a3dfd4592 Replace flowchart.mmd with per-topic diagrams and a print pipeline
Split the single flowchart.mmd into flowchart/platform-overview.mmd
(all 5 phases) and flowchart/round-lifecycle.mmd (round/draw detail),
plus render-pdf.sh to generate print-ready A4/A3 PDFs with a consistent
theme, header/footer, and legible contrast against the page background.

Also flip the operational policy in CLAUDE.md: the app now always runs
via Docker (dev and prod alike), with the venv reserved for tests,
migration authoring, and one-time secret/key-generation scripts.
2026-07-23 16:24:28 +02:00
davideandClaude Sonnet 5 aae0961c94 Bring docs in sync with recent features (pending balance, SSE, per-player reveal)
CLAUDE.md: bumped the stale test count (54 -> 76), added "Balance display"
and "Real-time updates (SSE)" sections, and rewrote the DRAW section's
frontend-reveal paragraph to describe the actual current behavior (dual
status/result boxes gated by user_played, closes_at-anchored reveal delay,
localStorage persistence, the last-round-result backstop) instead of the
older single-box design. Refined the "no history endpoints" known gap now
that GET /users/me/last-round-result exists (still not general history).

README.md: same test count fix, expanded coverage list.

docs/: fixed a pre-existing broken link in setup.md (admin-guide.md ->
guida-admin.md), added a note in running-the-server.md that editing the
bind-mounted Caddyfile needs an explicit `docker compose restart caddy`
(discovered while adding the SSE Caddy config in a prior change), and
rewrote guida-utente.md's draw/reveal section plus the balance/withdrawal
sections to match what the UI actually does now. guida-admin.md was
reviewed but needed no changes.

app/static/style.css: dropped `.toast.info`, dead since the toast-based
loss notification it styled was replaced by the persistent result box.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 11:05:27 +02:00
davideandClaude Sonnet 5 7b3555f8eb Tie the withdrawal minimum to the bet amount instead of a separate field
RoundConfig.min_amount_sats was an independently-configurable floor that
could drift out of sync with bet_amount_sats for no real reason (deposits
never had a server-side minimum anyway). Drop the field and enforce
amount_sats >= config.bet_amount_sats directly in request_withdrawal.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 19:25:15 +02:00
davideandClaude Sonnet 5 1941f30b10 Add ops scripts to decrypt/re-encrypt the master xprv, and document them
decrypt_master_key.py: prints the existing master xprv after an explicit
confirmation prompt, for disaster-recovery backups. Falls back to
./data/keys/master.xprv.enc (the docker-compose.yml bind-mount path) when
.env's configured MASTER_KEY_PATH doesn't exist locally.

encrypt_master_key.py: the reverse direction — takes an externally-generated
xprv (e.g. created offline/air-gapped) via a hidden getpass prompt, validates
it parses as a private extended key, and encrypts it with the same Fernet
scheme generate_master_key.py uses. Refuses to overwrite an existing key file
unless --overwrite is passed.

Neither script is reachable via any API endpoint or the admin panel, by
design — this is the one secret the entire custodial wallet derives from.
Documented in docs/setup.md (new "Recuperare o portare una xprv esistente"
section) and CLAUDE.md's Commands block.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 16:20:03 +02:00
davideandClaude Sonnet 5 9fa7eec378 Document the three sequential block confirmations behind the draw/payout timing
CLAUDE.md and the user/admin guides only mentioned "a confirmed block" for
the draw, leaving the actual end-to-end timing (why it can take several
minutes after the countdown hits zero) unclear. Spell out the three distinct
confirmations in sequence — last pending bet, draw block, payout tx — and
the resulting best/worst-case wall-clock estimates.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 14:14:09 +02:00
davideandClaude Sonnet 5 7dcf6d2756 Sync round countdown across clients and enforce the bet cutoff on deadline, not scheduler tick
The round timer relied on each client's own wall clock, so two browsers with
skewed local clocks showed different countdowns for the same round; the
server now also returns server_time so the frontend can correct for clock
skew. Also drop out-of-order /rounds/current responses (multiple independent
triggers could resolve late and revert the UI to a stale drawing/result
state) and prune per-round bookkeeping maps on round transitions.

Separately, place_bet only checked status == "open", leaving a window (up to
the scheduler's 5s tick interval) after a round's timer hit zero where a new
bet could still be accepted. place_bet now checks the round's own deadline
directly (round_accepts_bets), acting as an immediate "yellow light" for new
entries while still letting already-broadcast bets confirm before the round
closes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 14:07:09 +02:00
davide 162a63d04a Add a maintenance pause/resume switch and a proper user navbar
RoundConfig gets a paused flag toggled via new POST /admin/pause and
/admin/resume endpoints (audit-logged, surfaced as a "Manutenzione" card in
the admin Parametri view). Pausing only stops the *next* round from opening
once the current one closes — rounds/service.py:open_new_round_if_needed
still lets an in-progress round finish, draw, and pay out its winner
normally. GET /rounds/current exposes lottery_paused so the user page shows
a maintenance banner (even while logged out) instead of silently going idle.

Also replaces the user dashboard's stacked account-bar card + bento-grid
menu with a single sticky navbar (identity row + Deposito/Bet/Prelievo
tabs), and moves the page content into a dedicated .app-shell container so
the navbar itself can span full width.
2026-07-22 10:36:36 +02:00
davideandClaude Sonnet 5 4b510f312f Document the draw animation and win/lose reveal
CLAUDE.md's DRAW architecture bullet now explains draw_animation_seconds
and its decoupling from the real block-wait timing. guida-utente.md
gets a new "Estrazione del vincitore" section describing what a player
sees and when. guida-admin.md's Parametri table and hardcoded-defaults
note include the new field.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 16:04:01 +02:00
davideandClaude Sonnet 5 03cdffb34d Update CLAUDE.md for the admin dashboard, Docker deploy and DB-only config
Ran through the init skill's checklist against the current codebase:
test count (49 -> 54), a new "Admin dashboard and test UI" architecture
section (the two static SPAs, their endpoints, and the deliberate
non-linking between them), two new non-obvious domain decisions (admin
privkey export is intentional not a bug; who pays an RBF fee bump), a
pointer to docs/ for the human-facing guides, and updated Known gaps
(deployment gap resolved and removed; admin-token blast radius and the
Docker auto-restart risk called out; user-facing history gap reworded
now that the admin side has one). MVP business parameters reworded to
distinguish what's admin-configurable (bet amount, min amount) from
what's genuinely hardcoded (70/30 split, 1-conf threshold).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 15:38:17 +02:00
davideandClaude Sonnet 5 0e56f63e63 Document the DB-only config model and the new dashboard sections
CLAUDE.md and docs/guida-admin.md now describe RoundConfig as the sole
source of truth for business parameters, with no env var counterpart —
defaults live as hardcoded model column defaults, not app/config.py.
guida-admin.md documents the four new dashboard sections (Round,
Transazioni pendenti, Audit log alongside Parametri/Utenti). setup.md
points readers to the admin panel instead of .env for those values.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 15:06:51 +02:00
davideandClaude Sonnet 5 f21ecbd4ee Add a cooldown between rounds (ROUND_COOLDOWN_SECONDS)
open_new_round_if_needed now withholds opening the next round until
ROUND_COOLDOWN_SECONDS (default 30) have passed since the previous
round's closed_at, returning None in that window instead of a Round.
Without this, the next round opened within one scheduler tick (~5s) of
the previous payout confirming — not enough time for a player to
notice the round they were in actually resolved.

Callers updated: the scheduler treats None as "nothing to do this
tick", and place_bet raises a "try again shortly" BetError instead of
crashing on a None round.

Not in the original flowchart — a deliberate UX addition on top of it,
documented as such in CLAUDE.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 11:29:59 +02:00
davideandClaude Sonnet 5 6683f197eb Document the Docker + Caddy deployment workflow
Records the docker compose commands (master key bootstrap, up/down,
log tailing) and the SITE_ADDRESS dev-vs-production behavior, plus an
explicit warning: app's restart:unless-stopped means a crash mid-round
auto-restarts into the still-open scheduler-resume gap, so this isn't
unattended-safe yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 11:15:11 +02:00
davideandClaude Sonnet 5 f783cfaf80 Update CLAUDE.md with real commands and known gaps
Records the MVP build as code-complete and unit-tested, documents the
real install/run/test commands now that the project is scaffolded, and
lists known gaps (scheduler restart resume, payout retry, RBF fallback,
missing history endpoints, deployment, admin auth, rate limiting) to
address before treating this as production-ready.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 10:27:12 +02:00
davide bae48c46dc Initial commit 2026-07-20 21:24:31 +02:00