Commit Graph
17 Commits
Author SHA1 Message Date
jwinterm 41676fa072 refactor: unify identity resolution on stable user_id (anon_token)
There were two identity systems: SessionManager keyed on the stable, UNIQUE
anon_token, and getOrCreateUser keyed on the mutable, non-unique socket_id.
The latter could create a duplicate "orphan" user row (or resolve the wrong
row) when the socket_id lookup raced the session's socket_id update —
desyncing credits and payouts between the two rows for one human.

- getOrCreateUser now resolves through SessionManager's stable identity first
  (anon_token -> users.id), re-selecting a fresh row by stable id, and only
  falls back to the legacy socket_id lookup when no session exists. The
  last-resort create now warns, since it indicates a missing session.
- gameModeManager.sessionManager is wired in SocketHandlers so the
  session-first path is active in production.
- anon_token is already UNIQUE (migration 003), so the stable-identity
  constraint already exists; no new migration needed.

Re-keying the in-memory activeGames map by user_id is deferred (invasive;
already mitigated by stamping dbUserId on the game in the disconnect fix).

Adds identityResolution.test.js proving no duplicate row is created when a
session exists. Full suite: 17 suites / 136 tests.
2026-05-31 10:15:08 -04:00
jwinterm 34788e5810 fix: credits BIGINT, idempotent migration 010, atomic migration runner
- Migration 018 widens users.credits and credit_transactions.amount/
  balance_after from INTEGER to BIGINT (consistent with the atomic-money
  columns; removes a latent overflow risk on admin-configurable packages).
- Migration 010 rewritten with conname-guarded DO blocks so it is idempotent
  and safe to re-run / recover from a partial apply (bare ADD CONSTRAINT
  previously hard-failed on re-run and could wedge startup).
- The migration runner now applies each migration and records its ledger row
  in a single transaction, so a migration can never be applied-but-unrecorded
  (which would re-run a non-idempotent migration on the next boot).

Verified end-to-end against a throwaway Postgres database: all 18 migrations
apply cleanly, a second run skips via the ledger, credits is bigint, and the
new constraints/indexes are present. Full suite: 16 suites / 134 tests.
2026-05-31 10:07:15 -04:00
jwinterm 2e6f1a6335 fix: admin refund actually sends funds (was calling a nonexistent method)
The admin "send funds" refund path called walletRPCService.sendPayment(),
which does not exist — guarded by a typeof check, so it silently never sent
while still reporting the refund as processed.

Now uses the real processPayout() (validates the address and transfers,
returning { success, txHash }), and refunds the amount the user actually paid
(received_amount, recorded at confirmation) rather than the expected amount,
falling back to expected for older records.
2026-05-31 10:02:19 -04:00
jwinterm ce83ec4b6c fix: retry payout stat-counting and atomic tx_hash write
Two bugs in payoutRetryService.retryPayout:

- The "already on-chain" path guarded the user-stats update with
  NOT EXISTS (... WHERE id = this AND status = 'completed'), but it had just
  marked that same row completed in the same transaction, so the guard was
  always true-negative and stats were never counted. Replaced with a
  conditional UPDATE ... WHERE status <> 'completed' RETURNING, so the row's
  transition drives an exactly-once stat count.
- A successful retry wrote tx_hash in a standalone query and then marked the
  payout completed in a separate transaction; a crash between the two left a
  tx_hash on a non-completed row. Now tx_hash + completion + stats happen in
  one transaction.

Adds payoutRetry.test.js (count-once, no-double-count, atomic completion).
Full suite: 16 suites / 134 tests.
2026-05-31 10:00:51 -04:00
jwinterm f9c6ce59d2 fix: CHECK constraints on money-table statuses; cover processing in payout guard
A typo in a status string (e.g. 'complete' vs 'completed') silently produced
a money row no index/predicate matched, orphaning funds.

- Migration 017 adds idempotent NOT VALID CHECK constraints on payments.status,
  payments.payment_type and payouts.status. NOT VALID enforces all new writes
  without failing on any pre-existing rows; conname guards make it re-runnable.
- The in-code existing-payout guard in completeGame now also covers the
  'processing' status (matching the unique index from migration 015), so a
  duplicate win can't create a second payable row while a payout is mid-flight.

Full suite: 15 suites / 131 tests.
2026-05-31 09:57:56 -04:00
jwinterm 473a4091d4 fix: snapshot payout terms at game start (what-you-saw-is-what-you-get)
Payouts were computed at completion from LIVE config, so an admin changing
multipliers mid-game would change the payout of an already-in-progress game.

- Migration 016 adds payout_escape_amount/payout_treasure_amount (BIGINT) and
  the corresponding multipliers to the games table.
- Both game-start paths stamp the resolved payout amounts (computed from the
  config in effect at entry) onto the game row.
- completeGame pays from the snapshot, falling back to live calculation only
  for legacy games that predate the snapshot columns.

Adds payoutSnapshot.test.js proving a mid-game config change cannot alter an
in-flight payout. Full suite: 15 suites / 131 tests.
2026-05-31 09:55:45 -04:00
jwinterm 24aed355c6 refactor: exact BigInt money math via src/money/atomic.js
Money is integer atomic units, but payout and sum math ran on float64
(`Math.round(base * multiplier)`, `sum + Number(x)`), which silently loses
precision above 2^53 — a real risk for large/credit/XMR amounts.

- Add src/money/atomic.js: the single source of truth for atomic-unit math
  (toBig, toSafe, sum, add, mulByDecimal, format). mulByDecimal multiplies an
  atomic amount by a decimal multiplier using exact integer arithmetic with
  half-up rounding; toSafe narrows to a number only when exactly representable
  and otherwise returns a decimal string.
- calculatePayout now uses money.mulByDecimal/toSafe instead of float math.
- walletRPCService batch total + fee sum use money.sum instead of float reduce.

Adds moneyAtomic.test.js with property tests on amounts above 2^53 proving
exactness where the old float path drifted. Full suite: 14 suites / 129 tests.
2026-05-31 09:45:58 -04:00
jwinterm a664a8bbce security: escape XSS sinks client-side and add CSP + security headers
The client trusted the server to pre-escape chat content and rendered
user-supplied fields via .html()/innerHTML — one server regression away from
stored XSS, and the admin panel injected user-controlled payout addresses
into its authenticated DOM.

- Add a single shared escapeHtml helper (escapes all five HTML-significant
  chars including both quotes); leaderboard now delegates to it.
- Escape chat username + message in onChatBroadcast/onChatHistory.
- Escape user-controlled fields in the admin panel (payout address, socket
  id, player name, status) and make its local escapeHtml quote-safe so values
  in title="..." can't break out.
- Add CSP plus X-Content-Type-Options, X-Frame-Options and Referrer-Policy
  headers via middleware. connect-src 'self' keeps Socket.IO working;
  removing 'unsafe-inline' (nonces) is tracked as a later cleanup.

Full suite: 13 suites / 119 tests.
2026-05-31 09:40:34 -04:00
jwinterm 5c546a1473 fix: recover unconsumed single-game payments; make game preservation deterministic
Two disconnect-related money/UX gaps:

1. A confirmed single_game payment whose game never started (user paid, then
   disconnected) was money-in-nothing-given with no recovery path. recover-
   PendingPayments now detects confirmed single_game payments with no linked
   games row and grants the equivalent credits — idempotently (per-payment
   reason key, row-locked re-check of both the game link and prior recovery).

2. In-progress games could be dropped on disconnect when a fresh getBySocket
   lookup failed. The stable dbUserId is now stamped on the game at creation,
   so suspend/restore keys on it directly without a failure-prone disconnect-
   time lookup. Any game (paid or free) is preserved/reconnectable whenever a
   session exists; the remaining drop-branch is only the true no-session edge
   (e.g. DB unavailable at connect), which is logged for audit rather than
   masked.

Adds singleGameRecovery.test.js. Full suite: 13 suites / 119 tests.
2026-05-31 09:36:09 -04:00
jwinterm 223aa75871 security: move session token to handshake auth and rotate on resume
The anonymous session token is a bearer credential that was sent in the
Socket.IO handshake query string, where it leaks into proxy/access/referer
logs and is easily observed. Anyone holding it becomes that user (credits,
payout address, pending payments).

- Client now sends the token in the handshake `auth` payload instead of the
  query string. Server reads `auth` first and falls back to the query string
  for backward compatibility during rollout.
- The token is rotated on every successful resume, so a leaked/observed
  token is invalidated the next time the legitimate owner reconnects. The
  client already persists the token returned in `session_resumed`.

Adds a security test asserting resume returns a new token and the old token
no longer resumes. Full suite: 12 suites / 116 tests.
2026-05-31 09:29:20 -04:00
jwinterm d07967c3d1 security: fix batch-payout tx_hash collision and double-pay risk
transfer_split sends one on-chain tx to many destinations, so payout rows
in a batch share a tx_hash. The old UNIQUE index on payouts.tx_hash made
the 2nd+ row fail to record, leaving funds sent but rows stranded in
'processing' and re-sendable by the retry service.

- Migration 015 drops the payouts tx_hash unique index (idempotency is
  enforced by idx_payouts_one_per_game) and extends that guard to cover
  'processing' so no second payable row can be inserted mid-flight.
- Batch completion now updates the whole batch in a single transaction via
  id = ANY(...), so rows can't be left half-completed. Per-user stats use
  BIGINT arithmetic in SQL (no JS float).
- Ambiguous batch failures are marked 'needs_review' (which the retry
  service does NOT pick up) instead of 'failed', preventing a double-send
  when transfer_split may have already broadcast. Operator is alerted.

Adds batchPayout.test.js covering the shared-tx_hash completion and the
needs_review failure path. Full suite: 12 suites / 115 tests.
2026-05-31 09:26:14 -04:00
jwinterm 3e6e3b858b security: fix underpayment exploit and make provably-fair real
Phase 0.1 — Underpayment confirmation bug (CRITICAL):
Payment confirmation gated on `status.confirmed`, which checkPaymentStatus
sets for ANY incoming tx regardless of amount, so sending a single atomic
unit granted a full game/credits. Now gate on `status.complete` (received
>= expected). Underpayers are warned once and the payment stays pending so
a top-up can complete it. Persist `received_amount` for single-game and
credits confirmations for reconciliation. Adds an underpayment regression
test.

Phase 0.2 — Provably-fair was decorative (CRITICAL):
The committed seed had zero effect on the dungeon (created seededRNG was
unused; generation used Math.random + a globally-seeded ROT.RNG). Thread a
per-game seeded RNG derived from the committed seed through dungeon
generation (reseed the Digger via seedToInt + replace all Math.random) and
monster movement (seededShuffle). Add DungeonGenerator.regenerateFromSeed
and layoutFingerprint; /api/verify now regenerates the dungeon from the
seed and returns a fingerprint a player can independently reproduce. Adds a
determinism test suite.

Full suite: 11 suites / 113 tests passing.

Plan and progress tracked in docs/REMEDIATION_PLAN.md.
2026-05-31 09:14:21 -04:00
jwinterm f2b107fc5f fix stale smirk and amount bug 2026-03-01 13:56:35 -05:00
jwinterm a61851b0f7 add smirk payments and leaderboard and diff tuning 2026-02-20 13:54:36 -05:00
jwinterm ec3caabf1c feat: initial batch payout logic and output splitting script added 2026-02-18 07:30:46 -05:00
jwinterm f8ae69304a fix smirk login 2026-02-07 11:40:07 -05:00
jwinterm a81c19c936 feat: admin dashboard, alert service, and docs reorganization
- Add alertService.js with Resend email alerts for low balance, disconnects, failed payouts
- Update admin.html with full dashboard UI (stats, charts, tables, payout retry)
- Add wallet balance to /health endpoint
- Add getBalance() and checkTransactionStatus() to walletRPCService
- Fix payoutRetryService query and add alert integration
- Update .env.example with alert config (RESEND_API_KEY, ADMIN_EMAIL, etc)
- Reorganize docs: move TODO.md, LOGS_AND_BACKUP.md to docs/
- Extract deployment guide from README to docs/DEPLOY.md
- Consolidate TEMP_TODO.md into docs/TODO.md
2026-01-31 20:21:28 -05:00