Commit Graph
228 Commits
Author SHA1 Message Date
DorianandClaude 41f1b93e9e feat(bots): AI-answer settings + claim-winnings UI for existing bots
Two gaps found while answering "where can I change the API key for
existing users from a webhook":

1. The AI-answer API key ("let BotFights answer for me") could only
   ever be set at the exact moment of bot creation on JoinBoutPage,
   because that's the only place the bot's own secret is ever in the
   browser's hands (Authorization: Bot <id>:<secret> was the sole auth
   path for POST/GET/DELETE /api/bots/ai-config). An existing bot's
   owner had no way back in to add, change, or remove their key later.

   Fixed: new owner-scoped routes at /api/bots/:name/ai-config
   (GET/POST/DELETE), authorized via verifyBotOwner (nostr JWT OR the
   bot's own secret — see bot-auth.ts), reusing the same underlying
   ai-bot-config storage. Wired into BotProfilePage's existing
   owner-only settings area, mirroring the webhook-management section's
   UX pattern (collapsed toggle, provider picker, masked key input,
   configured/remove state).

2. Investigating the payout side of the same question ("can we confirm
   the fighter wins all the cashu sats into their node wallet
   automatically") surfaced that GET /winnings/:botId and POST
   /claim/:paymentId existed on the backend but had NO frontend caller
   anywhere — a Cashu payout (the common case: winner has no NWC/
   Lightning-address wallet linked) minted a token that was completely
   invisible in the UI.

   Added a "claim your winnings" section to BotProfilePage, shown
   proactively (not behind a toggle — it's the owner's own money):
   lists unclaimed payouts with a CLAIM button, reveals the bearer
   token once claimed with a copy-to-clipboard action and guidance to
   paste it into any Cashu wallet (there's no "auto-deposit" for a
   bearer token the way NWC allows for Lightning — no destination
   address to push to).

Route-shadowing note: /:name/ai-config is a different segment count
than the existing bare /ai-config and /:name routes, so it can't
collide with either (unlike the /poll vs /:id and /ai-config vs /:name
bugs fixed earlier this session) — confirmed via the full route table.

13 new/updated tests in ai-config.test.ts (owner-JWT auth, wrong-owner
403, bot-secret still works via verifyBotOwner, no-auth 401). Full
server suite: 815/816 passing (only the same pre-existing CPU-load-
sensitive constant-time-comparison flake, confirmed unrelated and
passing in isolation). tsc --noEmit clean (server + frontend).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-31 14:54:40 -04:00
DorianandClaude c162d5ebe9 fix(security): five more IDOR/missing-auth bugs in payments + queue (same class as f5f57e6)
While wiring the ai-config settings UI, found the same "trust a
client-supplied pubkey" pattern repeated across every payment-moving
route in the app — not an isolated bug. Fixed all of them:

- GET /api/payments/winnings/:botId (CRITICAL): had NO auth check at
  all AND returned the raw, spendable Cashu bearer token in the list
  response. botId is public (every fight/profile URL), so anyone could
  list any bot's unclaimed winnings and get the live token back before
  the real winner claimed it — direct fund theft, zero auth required.
  Fixed: require JWT-derived ownership of botId; the list endpoint no
  longer returns the token at all (only paymentId + amountSats) — the
  token is now only ever revealed once, via the explicit claim below.

- POST /api/payments/connect-wallet (CRITICAL): trusted a
  client-supplied pubkey with NO ownership check whatsoever. Anyone
  could attach an attacker-controlled NWC connection string or
  Lightning Address to ANY victim bot by pubkey, silently redirecting
  all future fight-winnings payouts to the attacker's wallet.

- POST /api/payments/claim/:paymentId: same pubkey-trust pattern,
  hands back a live spendable Cashu token — the single most sensitive
  check in the file.

- DELETE /api/payments/disconnect-wallet: trusted pubkey with no
  ownership check (DoS: anyone could kill a victim's payout wallet).

- POST /api/queue/join-ranked/:botId: compared a client-supplied
  pubkey directly against bot.publicKey with no signature/JWT
  verification. pubkeys are public by design in nostr (shown on every
  bot's own profile page), so this was not an ownership check at all.

Also hardened (lower severity, same fix for consistency):
POST /create-invoice, POST /confirm/:paymentId, GET /wallet-status.

Fix pattern, consistent with auth.ts (f5f57e6): pubkey is now always
derived from extractPubkeyFromAuth(Authorization: Bearer <jwt>), never
trusted from a request body or query string. Added a shared
verifyBotOwner() helper in bot-auth.ts for the dual-audience routes
(nostr-signed-in owners AND anonymous poll-mode bots via
Authorization: Bot <id>:<secret>). Schemas (connectWalletSchema,
createInvoiceSchema, joinRankedSchema, disconnectWalletSchema) no
longer declare a pubkey field — removing the field is itself a guard
against the pattern regressing. Frontend callers already used
authFetch (attaches the Bearer JWT automatically) for every one of
these, so no behavior change for legitimate callers — only closes the
hole for illegitimate ones.

Root-caused test failures this surfaced: a leaked mockReturnValueOnce
queue value cascaded through payments.test.ts once earlier tests
started 401-ing before consuming their queued mock (disconnect-wallet
-> zap Attack3 -> Attack4 -> claim Attack7). Fixed by giving each
newly-auth-gated test a real JWT (createJwt, not mocked) instead of
loosening the auth requirement.

Full server suite: 806-815/810-829 passing depending on run (only
pre-existing CPU-load-sensitive timing/throughput benchmarks flake,
all confirmed passing in isolation and confirmed untouched by this
diff — bot-auth.ts constant-time variance, lifecycle.ts fight
throughput, shutdown.ts timeout, fights.mock dev-check). tsc --noEmit
clean (server + frontend).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-31 13:00:08 -04:00
DorianandClaude f5f57e60d9 fix(security): POST /api/auth/update trusted a client-supplied pubkey (IDOR)
Found live while wiring the "existing bot" AI-config settings UI: this
route parsed `pubkey` from the request body and used it directly to
select which bot row to update, with no check that it matched the
caller's actual authenticated identity. Any unauthenticated caller
could POST an arbitrary victim's pubkey plus a malicious webhookUrl,
profilePicUrl, or customization payload and silently hijack that bot
(e.g. redirect its webhook to an attacker-controlled endpoint).

Contrast with GET /me and POST /regenerate-secret, which both
correctly derive pubkey from the verified JWT via
extractPubkeyFromAuth and never trust a client-claimed identity — this
was the one route that didn't follow that pattern.

Fixed by deriving pubkey from the JWT exclusively; updateBotSchema no
longer declares a pubkey field at all (was the only schema-level
signal that the vulnerable code path existed). Frontend callers
updated to stop sending a pubkey they no longer need. Added a
regression suite (auth-update.test.ts) covering: 401 with no/garbage
auth, hijack-attempt-via-body-pubkey now 404s and leaves the victim's
row untouched, and legitimate self-updates still work when the body
happens to carry an unrelated pubkey field (ignored, not trusted).

Full server suite: 829/829 passing. tsc --noEmit clean (server +
frontend).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-31 12:06:36 -04:00
DorianandClaude Fable 5 6464231f5d feat(payments): wire Cashu as the primary entry-fee UX, fix anonymous-bot ranked auth
CI / check (push) Has been cancelled
Two pieces, both user-directed, completing what 7341ca0 only configured:

1. WalletConnect.vue: Cashu token paste is now the PRIMARY entry-fee path
   (submitCashuToken() already existed in useWallet.ts but was never called
   from any UI — added the missing wiring). Lightning/NWC is now secondary,
   behind an explicit "or connect a Lightning wallet instead" toggle.
   Emits `cashu-paid` with the redeemed paymentId; JoinBoutPage.vue's
   fightRanked() uses it directly instead of calling payEntryFee()
   (Lightning-only) when present — no duplicate invoice/charge.

2. queue.ts's POST /join-ranked/:botId required a nostr pubkey for
   ownership verification, full stop. Confirmed live during testing:
   anonymous poll-mode bots (the primary registration path for AI agents
   per BOTFIGHTS.md) have publicKey: null — staked fights were completely
   unusable for that entire audience, silently. Now accepts EITHER a
   pubkey OR Authorization: Bot <id>:<secret> (same bot-auth every other
   anonymous-bot endpoint already uses) as proof of ownership.

Verified: full server typecheck clean; payments.test.ts (23) and
queue.test.ts (8) unchanged and passing; full frontend suite (101 tests,
13 files) passing, including useWallet.test.ts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 10:10:55 -04:00
DorianandClaude Fable 5 877d1f6389 fix: broken profile images (CSP img-src), AI-answer discoverability, arena compose tag
CI / check (push) Failing after 6m10s
1. server/src/app.ts: CSP img-src only allowed 'self'/data:/blob: — nostr
   profile pictures come from kind:0 metadata, a URL the user sets via their
   own client, hosted on whatever domain they picked. There's no central
   image host for a decentralized identity system, so every external
   profile pic was CSP-blocked and rendered as a broken image. Added
   https: (broad) — safe here since images can't execute script even from
   an untrusted origin, unlike script-src which stays locked to 'self'.

2. frontend/src/pages/JoinBoutPage.vue: the new AI-answer option (1.2.7)
   was reported as invisible — it was gated behind picking POLLING (not the
   default WEBHOOK) AND behind a collapsed toggle within that. Changed:
   POLLING is now the default mode (also the documented default in
   BOTFIGHTS.md), the AI section is expanded by default instead of
   collapsed, and the POLLING button's own description now mentions the
   option so it's visible without any extra click.

3. docker-compose.arena.yml: image tag 1.2.1 -> 1.2.7, matching what's
   actually deployed on the canonical arena (rolled live via
   ssh+docker compose pull/up this session — this commit just brings the
   repo's copy of the compose file back in sync with reality).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 08:52:21 -04:00
DorianandClaude Fable 5 ca5b63468e feat: "let BotFights answer for me" — server-side AI bot (poll mode), + Latest Bouts short-viewport fix
CI / check (push) Failing after 6m8s
New feature, requested live during demo prep: an operator can paste their
own Anthropic or OpenAI API key and have the server itself answer fight
challenges for their poll-mode bot, instead of running an external script.

Storage (server/src/engine/ai-bot-config.ts): one 0600 JSON file per bot
under this app's own data volume — deliberately mirrors Archipelago's own
node-level pattern for the identical class of secret (system.settings.set
"claude_api_key" in core/archipelago/src/api/rpc/system/handlers.rs): never
returns the raw key on GET, only whether one is configured and which
provider. This is a human operator opting in for their own bot via the
app's own UI — a different trust boundary from the unified prompt's "never
ask an AI agent for its API key" rule (BOTFIGHTS.md), not a violation of it.

Execution (server/src/engine/orchestrator.ts): purely additive hook inside
the existing isPollingBot branch of getBotResponse(). waitForPollResponse()
(unchanged) registers the pending challenge synchronously before returning;
right after, answerWithAiIfConfigured() fires a fire-and-forget async LLM
call that races to call submitPollResponse() — the exact function an
external poller already calls — before that promise's own timeout. No AI
config = instant no-op. LLM error/timeout = the existing timeout path
handles it identically to a human forgetting to poll. No new failure mode,
no change to scoring/round timing for any other bot.

Adapter (server/src/engine/llm-adapter.ts): both providers, one call shape
each (Anthropic /v1/messages + x-api-key, OpenAI /v1/chat/completions +
Bearer), same competitive system prompt already documented in BOTFIGHTS.md
for operator-run bots.

API (server/src/routes/bots.ts): POST/GET/DELETE /api/bots/ai-config,
authenticated via the bot's own Authorization: Bot <id>:<secret> (same as
/api/fights/poll). Registered BEFORE GET /:name — same route-shadowing bug
class already found once in fights.ts's /poll route (09-05); a bare /:name
registered first would have swallowed /ai-config as a bot-name lookup.
Covered by a new test (ai-config.test.ts) that asserts the real contract
shape, not just a 200, specifically to catch that regression.

UI (frontend/src/pages/JoinBoutPage.vue): collapsible section in the
bot-setup step, poll mode only (webhook mode already assumes the operator
runs their own infra) — provider picker, password-type key input, links to
get a key from either provider, key cleared from page state immediately
after saving.

Explicitly deferred (not built here): "use this node's key" as an
alternative to pasting your own — the node already has one configured for
AIUI (found live, /opt/archipelago/claude-api-proxy.py), but wiring a
cross-container secret share from the archy orchestrator into this
container needs a manifest change and another catalog signing cycle, which
this session isn't improvising under demo time pressure.

Also: HomePage.vue "Latest Bouts" section hidden on short viewports
([@media(max-height:700px)]:hidden) — the hero layout is a vertically-
centered flex column with overflow-hidden and no scroll by design, so on a
short viewport (embedded node dashboard iframes, small kiosk screens) this
last/least-essential section was what silently clipped, reported live as
"it looks cut off on node screens often".

Fixed a regression-test violation this batch would have introduced
(BUG-F2: no silent .catch(() => {})) in the DocsPage.vue proxy-URL-resolve
fix from the previous commit — both catches now log a warning instead of
swallowing silently.

Verified: full server typecheck clean; orchestrator.test.ts (23) +
poll-responses.test.ts (10) unchanged and passing — the new hook doesn't
alter existing poll-mode behavior; new ai-config.test.ts (7) passing,
including the route-shadowing regression check; regression.test.ts (43,
including the newly-fixed BUG-F2) passing. lifecycle.test.ts/scoring.test.ts
perf-timing failures are pre-existing, documented, unrelated flakiness
under this shared machine's CPU load (see archy's 09-01 deferred-items.md
item 2) — not caused by this change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 08:06:02 -04:00
DorianandClaude Fable 5 2512265113 fix: nostr-provider.js 404, DocsPage proxy-unaware URL, round-jump on late viewer join
CI / check (push) Failing after 6m9s
Three more fixes found during live demo verification:

1. server/src/app.ts: the previous commit added <script src="/nostr-provider.js">
   to index.html and shipped the file into server/public/, but this app's
   static file serving is an explicit per-route allowlist, not a catch-all —
   there was no route registered for it, so it 404'd and the signer bridge
   silently never loaded. Added the missing app.get('/nostr-provider.js', ...)
   route.

2. DocsPage.vue: promptUrl (the displayed "give this URL to your AI" copy
   button) was built from window.location.origin — same root-cause bug class
   as the JoinBoutPage/BotProfilePage fix (ffd4dfd), just for a link instead
   of fetched content. Now resolves the real arena origin from the fetched
   prompt's own content (which IS correctly proxy-resolved server-side via
   arena-proxy) instead of the browser's current address.

3. FightPage.vue: opening a fight already in progress (e.g. a background
   poll-mode bot kept answering challenges while nobody had the viewer open)
   showed nothing until the next live round arrived — reads as "the fight
   jumped straight to round N". loadFight() always fetched the completed
   rounds (data.rounds) but nothing backfilled the visible log from them;
   only live SSE round_end events ever pushed into liveLogItems. Added
   backfillCompletedRounds(), called once on mount before wireSSE() connects,
   that renders a compact (non-animated — no scene/TTS replay) summary of
   every already-completed round and sets HP/round-counter to current state
   immediately.

4. BOTFIGHTS.md: documented the webhook_test signature exception (see ffd4dfd
   commit for the same fix already applied to the live doc endpoint's
   underlying example) — this file is frontend/public/docs/BOTFIGHTS.md,
   the static copy that predates today's /api/docs/prompt-only rendering
   fix; keeping both in sync since some flows may still reference the path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 07:16:24 -04:00
DorianandClaude Fable 5 8eb27ed9b4 fix(security-headers): allow iframe embedding when ARCHY_EMBEDDED=1
CI / check (push) Failing after 6m22s
secureHeaders() defaulted to X-Frame-Options: SAMEORIGIN, added as part of
the NIP-98/JWT auth hardening. This unconditionally blocked the Archipelago
node dashboard's iframe (a different origin by port) — 1.1.0 never sent
this header at all, so this was a hard regression for the platform's normal
embedded-app UX.

Fix: X-Frame-Options is now conditional on ARCHY_EMBEDDED=1, an env var the
archy manifest sets for the node-installed instance (first-party, trusted
embedding on the same host). Standalone/public-arena instances keep the
default SAMEORIGIN clickjacking protection unchanged.

Verified: with ARCHY_EMBEDDED=1 no X-Frame-Options header is sent; without
it, X-Frame-Options: SAMEORIGIN is still sent as before.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 05:38:48 -04:00
DorianandClaude Fable 5 12d4b35404 fix(09-05): GET /api/fights/poll was shadowed by GET /:id, always 404d
server/src/routes/fights.ts registered the dynamic GET /:id route before
the static GET /poll route. Hono resolves same-shape single-segment
routes in registration order, so any GET /api/fights/poll request was
matched as a fight-id lookup for id="poll" and always returned
404 {"error":"Fight not found."} instead of the poll handler's
{"pending":false}/{"pending":true,...} response.

This meant the polling protocol — one of the two bot integration modes
BOT-02's unified prompt documents — never actually worked. Found while
verifying bot auth against the freshly-rolled 1.2.0 arena (plan 09-05
Task 2 acceptance criterion), reproduced independently on a throwaway
container with a fresh DB to confirm it wasn't an artifact of the
arena's seeded data.

Fix: move the /poll and /poll/respond route registrations above /:id.
No other GET route in this router collides in shape with /:id (verified
by listing every registered path/method pair).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 23:21:34 -04:00
DorianandClaude Fable 5 2a343ac746 feat(09-02): retire the bare-pubkey session path (BOT-01)
CI / check (push) Failing after 6m11s
Client: useNostr.ts's auto-restore now calls GET /api/auth/me (a plain
authFetch, no body) instead of POSTing {pubkey} to /api/auth/login —
identity is derived server-side from the JWT alone, never claimed by
the client.

Server: POST /login is reduced to a pure, documented-deprecated read.
Removed the creator auto-create branch and the creator auto-upgrade
db.update block — an unauthenticated request can no longer mutate the
database via this endpoint. The identical creator auto-create/upgrade
logic already exists, correctly gated behind NIP-98 verification, in
POST /nostr/session, so a creator signing in with a real signer still
gets the same row created/upgraded. Added a handler doc comment plus a
new auth.test.ts case asserting an unregistered creator pubkey now
returns exists:false and leaves the bots table row count unchanged.

e2e/helpers/auth.ts: doc comments updated to describe loginWithPubkey
as a read-only test lookup helper, not a login; request/signature
unchanged so existing e2e specs keep working.

Verification: auth.test.ts + auth-edge.test.ts + auth-audit.test.ts +
auth-me.test.ts = 56/56 pass. Full server suite (bypassing pnpm's
install-gate via ./node_modules/.bin/vitest, since this environment's
pnpm needs an interactive build-approval step unrelated to this task)
= 810/817 pass, remaining 7 are pre-existing timing/perf flakes under
CPU load (lifecycle/speed-meta/tier-balance/bot-auth constant-time),
none touching auth. tsc (server) and vue-tsc (frontend) both exit 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 22:31:26 -04:00
Dorian a0809565f2 feat(09-03): serve the unified AI bot-setup prompt at GET /api/docs/prompt
CI / check (push) Has been cancelled
- New docsRouter.get('/prompt') resolves the shipped container path
  (server/public/docs/BOTFIGHTS.md) then falls back to the dev-checkout
  path (frontend/public/docs/BOTFIGHTS.md), matching app.ts's publicDir
  derivation pattern
- Substitutes {{ARENA_URL}} with PUBLIC_ARENA_URL when set, otherwise the
  request's own origin, so a cloud agent that curls the prompt gets
  working examples pointed back at the arena it fetched from
- Responds as text/markdown so an agent can pipe the response straight
  into its context
- 5 new Vitest cases: 200+content-type, no leftover {{ARENA_URL}} token,
  PUBLIC_ARENA_URL precedence, origin fallback, YOUR_BOT_ID placeholder
  preserved for the in-app substitution flow
2026-07-30 22:23:20 -04:00
DorianandClaude Fable 5 bf240cef9e fix(09-02): sync migrate.ts DDL with schema.ts — fixes 15 pre-existing auth/tournament test failures
CI / check (push) Failing after 6m12s
Deviation (Rule 1 — auto-fix bug), out-of-scope-but-cheap per plan 09-02's
explicit allowance. server/src/db/migrate.ts (the standalone `pnpm migrate`
CLI script) had drifted from server/src/db/schema.ts: it was missing 7
tables (payments, wallet_connections, bets, tournaments, tournament_entries,
analytics, tournament_matches) and several bots/fights columns (sats_won,
sats_wagered, has_wallet, zaps_received, bot_type, mode, pot_sats,
payout_status, current_season). server/src/db/startup.ts's runMigrations()
(the one actually called from index.ts at server boot) already had the
correct, up-to-date DDL — migrate.ts was the stale duplicate. Brought it
back in sync, column-for-column and table-for-table, against schema.ts.

Route-level tests (auth.test.ts, auth-audit.test.ts, auth-edge.test.ts,
tournaments.test.ts) hit the real db/index.ts singleton against the
on-disk, gitignored server/data/botfights.db, which only startup.ts or
this migrate.ts script populate — vitest itself never runs a migration.
Running `pnpm --filter server migrate` against a fresh DB with the fixed
script now creates all tables/columns; full server suite went from
15 failed / 789 passed to 6 failed / 798 passed, with the remaining 6
all pre-existing timing/perf flakes unrelated to auth (answers.test.ts,
lifecycle.test.ts x2, bot-auth.test.ts, docs.test.ts x2 — CPU-contention
sensitive, matches deferred-items.md's documented flake class).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 22:11:29 -04:00
DorianandClaude Fable 5 635ee39373 feat(09-02): GET /api/auth/me — identity from JWT, never a claimed pubkey (BOT-01)
CI / check (push) Has been cancelled
Adds a JWT-gated, read-only session-restore route. Mirrors POST /login's
projection and 200 body shape exactly so normalizeBotData on the client
is unchanged. extractPubkeyFromAuth (already imported later in the file
for /regenerate-secret) covers missing/malformed/forged/expired/
blacklisted tokens via verifyJwt; deduped the now-redundant import at
the /nostr/session section. All 7 auth-me.test.ts cases pass; tsc clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 22:09:11 -04:00
DorianandClaude Fable 5 e824f4ca7f test(09-02): add failing test for GET /api/auth/me (BOT-01)
Covers missing / malformed / forged / blacklisted / unregistered / valid
JWT cases for the JWT-only identity route that replaces the bare-pubkey
auto-restore path. Route does not exist yet — 6/7 fail as expected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 22:03:18 -04:00
DorianandClaude Fable 5 a95cadaf9e test(09-01): verify x-forwarded-for over a real socket, not just presence
CI / check (push) Failing after 6m14s
The prior test drove the proxying app via Hono's in-process app.request()
harness, which has no real Node socket — so it could only assert the header
was non-empty-or-absent, not that the real client IP round-trips. Spin the
proxying app up with @hono/node-server (real loopback socket) and assert the
upstream actually receives 127.0.0.1/::1, exercising the same
remoteAddress lookup arenaProxy uses in production.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 21:34:13 -04:00
DorianandClaude Fable 5 0511b97cb9 feat(09-01): arena-proxy survives SSE, client-IP forwarding, upstream-down
CI / check (push) Has been cancelled
- Forward client IP via x-forwarded-for/x-real-ip so the canonical arena's
  per-IP rate limiting isn't collapsed to one bucket per node.
- 30s AbortSignal.timeout on non-stream requests; SSE fight streams
  (/api/fights/:id/stream) are exempt (long-lived by design).
- On upstream fetch failure, log and return 502 {error} instead of a
  buffered hang or a 500 stack trace.
- fights.ts: set X-Accel-Buffering: no on the SSE stream response so an
  nginx-fronted arena (nginx-proxy-manager) doesn't buffer live fight events.
- docker-compose.yml: document ARENA_UPSTREAM_URL / TRUSTED_PROXY (commented,
  no active value set here — the canonical arena gets its own compose file
  in a later plan).

TDD: added the SSE/XFF/502 tests, confirmed the 502 test failed against the
prior implementation, then implemented to green (9/9 arena-proxy tests,
17/17 combined with rate-limit.test.ts).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 21:32:57 -04:00
DorianandClaude Fable 5 143ca808e8 feat(09-01): arena-proxy middleware — REST forwarding to canonical arena
CI / check (push) Has been cancelled
Hono middleware that forwards /api/* to ARENA_UPSTREAM_URL when set, with
standalone mode (env unset) and /api/health untouched. Verified end-to-end
against a real second HTTP server: register a bot upstream, read it back
through the proxy, method/query/JSON body forwarded unchanged, inbound Host
header dropped, response content-encoding/content-length stripped.

TDD: 6 tests written first and confirmed failing (module didn't exist),
then implemented to green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 21:30:24 -04:00
Dorian 32e6c19f72 stuff 2026-04-11 19:46:37 +01:00
DorianandClaude Opus 4.6 18e4b05399 fix: practice fights send challenges to polling/webhook bots instead of forcing human mode
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 23:23:37 +00:00
DorianandClaude Opus 4.6 8076d860c7 fix: creator auto-creates as bot (poll mode), auto-upgrade existing human records
The creator was being registered with webhookUrl='http://human.local/' and
isHuman=true. Now uses poll.local and isHuman=false. The auto-upgrade logic
on login also converts any existing creator record from human to bot mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 22:28:43 +00:00
DorianandClaude Opus 4.6 2e7a039b8b fix: serve /docs/*.md as static files, not SPA fallback
- Add /docs/* route to serve markdown setup guides
- Add md to MIME map and SPA catch-all exclusion
- Normalize BOTFIGHTS.md placeholders to YOUR_BOT_ID/YOUR_BOT_SECRET

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 16:16:44 +00:00
DorianandClaude Opus 4.6 60dd6893be fix: replace download with inline copy-paste setup guide, fix CSP for WASM + Nostr relays
- Replace file download with collapsible inline guide + COPY ALL button
- Guide content has bot_id/secret pre-filled from credentials
- JoinBoutPage: "COPY GUIDE + CREDENTIALS" eagerly loads guide content
- BotProfilePage: webhook/polling guide selector with copy after secret regen
- CSP: add wasm-unsafe-eval to scriptSrc (fixes Kokoro TTS WASM)
- CSP: add wss://relay.damus.io, wss://relay.nostr.band, wss://nos.lol to connectSrc

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 14:06:34 +00:00
DorianandClaude Opus 4.6 cef9f4188f feat: fix setup guide download with embedded credentials + profile page regenerate secret
- downloadSetupGuide() now triggers a real file download with bot_id/secret injected
- Add POST /api/auth/regenerate-secret endpoint (JWT auth, 3/hour rate limit)
- Add "Download Setup Guide" section to BotProfilePage with secret regeneration flow
- Old secret immediately invalidated on regeneration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 13:35:48 +00:00
DorianandClaude Opus 4.6 2f5fe4f350 test: add regression tests for BUG-4, BUG-6, BUG-7, BUG-F2
Source pattern verification tests:
- BUG-6: webhook calls wrapped in Promise.all (parallel, not sequential)
- BUG-7: SSE maps (spectatorCounts, fightReactions, ssePerIp) cleaned on disconnect
- BUG-4: no raw setTimeout in game code (all use trackedTimeout)
- BUG-F2: no silent .catch(() => {}) in frontend source
43 regression tests total, all passing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 12:35:48 +00:00
DorianandClaude Opus 4.6 a358374d71 test: verify all E2E specs pass, fix flaky tests and creative scoring
- Fix E2E Playwright config: correct port 5173→9101, increase webServer timeout
- Fix signup-bot and signup-human specs: add missing nsec backup step
- Implement scoreCreativeAnswer() heuristic for creative round scoring
- Pass DB ELO to generateMockBotResponse for non-MOCK_BOTS integration tests
- Update challenges tests: all 16 types are now factual (no creative types)
- Fix lifecycle test flakiness: widen ELO correlation tolerance, add timeout
- All 11 E2E specs pass, 770 unit/integration tests pass

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 12:28:39 +00:00
DorianandClaude Opus 4.6 42d79487a1 test: add odds calculation and retro-moves coverage — 50 tests
Odds: eloProbability, calculateOdds, fractional/American display,
payout calculation, bet validation (30 tests).
Retro moves: RETRO_MOVES data, lookupMove, scoreRetroResponse,
generateRetroChallenge, mock response generation (20 tests).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:46:03 +00:00
DorianandClaude Opus 4.6 2c83858115 fix: correct challenge audit test assertions — actual distribution and crit rates
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:38:26 +00:00
DorianandClaude Opus 4.6 cae8f0b83e test: add comprehensive auth audit — 28 tests verify endpoint protection
Covers all 7 admin endpoints (403 without creator pubkey), polling
endpoints (bot auth required), tournament mutations (creator-only),
ranked queue (pubkey ownership), NIP-98 session (signature required),
and 10 public endpoint accessibility checks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:37:46 +00:00
DorianandClaude Opus 4.6 18b92fbbdf test: API auth audit — 18 tests verify auth, rate limiting, validation, error sanitization
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:34:08 +00:00
DorianandClaude Opus 4.6 eac8539825 fix: update hono 4.7.6→4.12.6, @hono/node-server 1.14.1→1.19.10, override tar/serialize-javascript
Resolves 6 high audit vulnerabilities (Hono auth bypass, serveStatic, JWK confusion,
node-tar symlink traversal, serialize-javascript RCE).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:30:56 +00:00
DorianandClaude Opus 4.6 321ccdec7b test: add 39 regression tests covering BUG-1 through BUG-S9
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:25:07 +00:00
DorianandClaude Opus 4.6 6a00cfe324 test: add soak and stress tests — 1000 fights, 50 concurrent queue joins
Soak: 1000 random fights verify zero crashes, ELO bell curve around
1200, and bounded heap growth. Stress: 50 concurrent queue joins
verify no races, no duplicates, correct rejoin behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:20:50 +00:00
DorianandClaude Opus 4.6 27b3b89424 test: add payment/betting edge cases — concurrent bets, draw refunds, validation
17 tests covering: simultaneous bet placement, draw refund mechanics,
bet validation bounds, extreme ELO odds, Cashu token rejection, and
escrow lifecycle leak prevention.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:17:55 +00:00
DorianandClaude Opus 4.6 f15504b400 test: add auth registration edge cases — concurrent names, expired JWT, NIP-98 tampering
Tests concurrent same-name registration (exactly one succeeds),
case-insensitive name collisions, expired JWT rejection, NIP-98
pubkey mismatch, and duplicate pubkey prevention.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:15:13 +00:00
DorianandClaude Opus 4.6 5799ff60d3 test: auth & registration edge cases — unicode names, shared URLs
8 new tests: unicode/emoji/diacritics in bot names rejected, special
chars rejected, same webhook URL allowed, pubkey hex validation,
missing required fields rejected.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:11:12 +00:00
DorianandClaude Opus 4.6 2dd09fb954 test: add simultaneous KO and negative ELO edge cases
Adds tests for both-bots-at-0-HP tiebreaker asymmetry (botA penalized
first) and verifies ELO can go negative when 0-rated bot loses.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:10:49 +00:00
DorianandClaude Opus 4.6 ffad432e5b test: 10-round double timeout simulation — draw, equal HP, no loops
Simulates both bots timing out every round for 10 rounds. Verifies
zero damage per round, HP unchanged at 200, draw outcome.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:10:15 +00:00
DorianandClaude Opus 4.6 9346b6b260 test: add ELO extremes and challenge rotation edge cases
ELO: 0v0, 9999v1 upset, 9999v1 expected, NaN/Infinity check.
Challenge rotation: 16 unique types, reset after exhaustion,
filter exclusion works. Total: 24 edge case tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:09:36 +00:00
DorianandClaude Opus 4.6 135bf644fa test: add 17 fight engine edge case tests
Covers: identical answers (speed tiebreaker), 2000-char answers,
null/empty/whitespace answers, unicode/emoji, HTTP errors, double
timeout/error, both-wrong draws, correct-beats-wrong regardless of
speed, speed advantage margin, arena modifier damage, combo stacks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:07:20 +00:00
DorianandClaude Opus 4.6 3c5c6c6b95 fix: improve graceful shutdown — stop loop, drain fights, clear all state
Shutdown now: stops background fight loop, waits up to 15s for active
fights to drain (polling every 500ms), clears human + poll pending
challenges, clears bet escrow. Added clearEscrow() to betting.ts and
5 tests verifying cleanup functions and correct shutdown order.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:54:10 +00:00
DorianandClaude Opus 4.6 4134a27ea6 feat: improve graceful shutdown — stop bg loop, drain fights, clear state
Shutdown now: 1) stops background fight loop, 2) waits up to 15s for
active fights to finish, 3) cancels pending human + poll challenges,
4) clears bet escrow. Added clearEscrow() to betting.ts. Tests verify
each cleanup function and shutdown sequence ordering.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:53:39 +00:00
DorianandClaude Opus 4.6 023a1a58a9 test: verify orphaned fight cleanup cancels stale live fights
Add 3 tests for cleanupOrphanedFights: verifies db.update sets
status='cancelled' with endedAt on stale live fights, returns 0
on success, and propagates DB errors correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:49:27 +00:00
DorianandClaude Opus 4.6 9b0d251d1c fix: sanitize error responses to prevent internal detail leakage
Add sanitizeError() helper that strips file paths, stack traces, SQLite
errors, and system errors from messages before returning them to clients.
Applied to all route-level catch blocks in payments, queue, fights, and
admin routes. Includes 12 tests for the sanitizer and static analysis
test verifying no route files leak raw err.message.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:46:38 +00:00
DorianandClaude Opus 4.6 1b1f9eb2d7 chore: add composite (is_active, elo_rating) index for leaderboard queries
All individual indexes from plan already existed. Added missing composite
index that covers WHERE is_active=1 ORDER BY elo_rating DESC pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:41:30 +00:00
DorianandClaude Opus 4.6 d3bb00c5c8 feat: add per-phase timing instrumentation to fight orchestration
Log timing for each round phase: webhook calls, scoring, DB operations,
and total round time. Also log finalize transaction time. Uses logger
with 'perf' category for easy filtering.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:35:42 +00:00
DorianandClaude Opus 4.6 dc9884e27e test: verify wallet disconnect wipes connection data from DB
Add test confirming disconnect-wallet deletes walletConnections rows
and sets hasWallet=false on the bot record.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:33:50 +00:00
DorianandClaude Opus 4.6 b1e86843a7 test: audit AES-256-GCM crypto with 7 test cases
Verify random IV (same plaintext encrypts differently), ciphertext
format (iv:authTag:encrypted), auth tag tamper detection, encrypted
data tamper detection, empty string handling, and unicode support.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:33:08 +00:00
DorianandClaude Opus 4.6 c5744f5984 test: pentest payment edge cases with 10 attack vector tests
Cover amount=0, over-max (999999999), zap non-winner, zap unfinished
fight, invalid wallet method, empty cashu token, claim nonexistent
payment, confirm already-confirmed, confirm outbound payment, claim
payment with no token.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:32:19 +00:00
DorianandClaude Opus 4.6 2fea2bf8c9 test: verify error responses never leak stack traces or file paths
Add tests confirming production error handler sanitizes all internal
errors (ENOENT, stack traces, file paths). Add static analysis test
verifying no route file passes err.stack to c.json() responses.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:30:55 +00:00
DorianandClaude Opus 4.6 21bb46c1b0 test: verify admin endpoints require creator pubkey on all routes
Test all 7 admin endpoints (stats, bots, deactivate, activate,
reset-elo, fights, backup) reject non-creator pubkeys and missing
pubkeys with 403. Verifies global middleware guard works correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 09:29:08 +00:00