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.
This commit is contained in:
jwinterm
2026-05-31 09:14:21 -04:00
parent 82fdcc0203
commit 3e6e3b858b
10 changed files with 468 additions and 148 deletions
+122 -113
View File
@@ -2,139 +2,148 @@ const QueueManager = require('../src/network/queueManager');
const PaymentHandlers = require('../src/network/paymentHandlers');
/**
* Integration-style test to ensure a payment that confirms AFTER a block event
* (where the entry was still unconfirmed) results in an immediate game start
* without waiting for the next block.
* Integration-style tests for the payment confirmation flow.
*
* 1. A payment that confirms AFTER a block event (entry still unconfirmed) results
* in an immediate game start without waiting for the next block.
* 2. (Phase 0.1 security gate) A payment that is confirmed but UNDERPAID
* (received < expected) must NOT start a game or grant anything.
*/
const blockHeight = 100;
const socketId = 'sock-int';
/**
* Build a fresh PaymentHandlers + QueueManager harness with controllable wallet
* monitoring. Returns the pieces the tests need.
*/
function buildHarness() {
const events = [];
const activeGames = new Map();
const io = {
to: () => ({ emit: (event, data) => events.push({ event, data }) })
};
const broadcastManager = {
sendStatusUpdate: (id, type, message) => events.push({ event: 'status', data: { type, message } }),
broadcastChatMessage: () => {}
};
const debugManager = {
CONSOLE_LOGGING: false,
getCurrentBlockHeight: () => blockHeight
};
const userObj = { id: socketId, clientId: 'client-int', payout_address: 'wow1address' };
const getUserBySocket = (id) => (id === socketId ? userObj : null);
const createGameForUser = (user) => {
const game = {
getState: () => ({ player: { x: 0, y: 0 }, lighting: {}, torches: [], started: true })
};
activeGames.set(user.id, game);
return game;
};
const gameModeManager = {
gameMode: 'PAID_SINGLE',
cryptoType: 'WOW',
currencyDecimals: 11,
singleGamePrice: 1000,
creditsPayoutEnabled: false,
formatAtomicHuman: () => '0.001',
getOrCreateUser: async () => ({ id: socketId, payout_address: 'wow1address', clientId: 'client-int' }),
createPaymentRequest: async () => ({
id: 'pay-1',
address: 'addr-1',
amount: 1000,
amountFormatted: '0.001',
expiresAt: new Date(Date.now() + 60000)
}),
processGameStart: async () => ({ success: true, effectiveMode: 'PAID_SINGLE' }),
db: {
query: async (sql) => {
if (sql && sql.includes('UPDATE payments') && sql.includes('RETURNING')) {
return { rows: [{ id: 'pay-1' }] };
}
return { rows: [] };
}
}
};
let monitorCallback;
const walletService = {
startPaymentMonitoring: (address, cb) => { monitorCallback = cb; },
stopPaymentMonitoring: () => {}
};
const queueManager = new QueueManager({
debugManager, broadcastManager, io, createGameForUser, getUserBySocket,
activeGames, gameModeManager, consoleLogging: false
});
const paymentHandlers = new PaymentHandlers({
io, gameModeManager, walletService, debugManager, queueManager, broadcastManager
});
const fakeSocket = { id: socketId, emit: (event, data) => events.push({ event, data }) };
return {
events, queueManager, paymentHandlers, fakeSocket,
getMonitorCallback: () => monitorCallback
};
}
describe('Payment flow integration: confirm-after-block immediate start', () => {
test('unconfirmed at block tick then confirmed triggers immediate game', async () => {
const events = [];
const activeGames = new Map();
const socketId = 'sock-int';
const blockHeight = 100;
const { events, queueManager, paymentHandlers, fakeSocket, getMonitorCallback } = buildHarness();
// Mock IO emitter
const io = {
to: () => ({
emit: (event, data) => {
events.push({ event, data });
}
})
};
// Minimal broadcast manager stub
const broadcastManager = {
sendStatusUpdate: () => {},
broadcastChatMessage: () => {}
};
// Debug manager mock
const debugManager = {
CONSOLE_LOGGING: false,
getCurrentBlockHeight: () => blockHeight
};
// User lookup
const userObj = { id: socketId, clientId: 'client-int', payout_address: 'wow1address' };
const getUserBySocket = (id) => id === socketId ? userObj : null;
// createGameForUser mock (records active game & returns state)
const createGameForUser = (user) => {
const game = {
getState: () => ({ player: { x:0, y:0 }, lighting: {}, torches: [], started: true })
};
activeGames.set(user.id, game);
return game;
};
// Game mode manager mock (paid single game mode)
const gameModeManager = {
gameMode: 'PAID_SINGLE',
cryptoType: 'WOW',
currencyDecimals: 11,
singleGamePrice: 1000,
creditsPayoutEnabled: false,
formatAtomicHuman: () => '0.001',
getOrCreateUser: async () => ({ id: socketId, payout_address: 'wow1address', clientId: 'client-int' }),
createPaymentRequest: async () => ({
id: 'pay-1',
address: 'addr-1',
amount: 1000,
amountFormatted: '0.001',
expiresAt: new Date(Date.now()+60000)
}),
// Mock processGameStart for QueueManager.startGameImmediately
processGameStart: async () => ({ success: true, effectiveMode: 'PAID_SINGLE' }),
// Mock db for PaymentHandlers DB update on confirmation
// The security fix requires UPDATE to return rows to confirm the payment was updated
db: {
query: async (sql) => {
// If this is the UPDATE payments query, return a row to indicate success
if (sql && sql.includes('UPDATE payments') && sql.includes('RETURNING')) {
return { rows: [{ id: 'pay-1' }] };
}
return { rows: [] };
}
}
};
// Wallet service mock with manual callback control
let monitorCallback;
const walletService = {
startPaymentMonitoring: (address, cb) => { monitorCallback = cb; },
stopPaymentMonitoring: () => {}
};
// Instantiate real QueueManager & PaymentHandlers
const queueManager = new QueueManager({
debugManager,
broadcastManager,
io,
createGameForUser,
getUserBySocket,
activeGames,
gameModeManager,
consoleLogging: false
});
const paymentHandlers = new PaymentHandlers({
io,
gameModeManager,
walletService,
debugManager,
queueManager,
broadcastManager
});
// Fake socket object with id
const fakeSocket = { id: socketId, emit: (event, data) => events.push({ event, data }) };
// Create payment request (does NOT queue yet) and start monitoring
await paymentHandlers.createAndShowPaymentRequest(fakeSocket);
const monitorCallback = getMonitorCallback();
expect(monitorCallback).toBeDefined();
// Simulate mempool detection first (callback is async, so we need to await it)
// Simulate mempool detection first
await monitorCallback({ in_mempool: true, confirmed: false, amount: 1000, confirmations: 0 });
// Should have queued the player but not started a game
expect(queueManager.getQueueLength()).toBe(1);
expect(events.filter(e => e.event === 'game_start').length).toBe(0);
// Simulate block tick BEFORE confirmation (should skip unconfirmed)
// Block tick BEFORE confirmation (should skip unconfirmed)
await queueManager.startGamesForWaiting(blockHeight);
expect(events.filter(e => e.event === 'game_start').length).toBe(0);
// Entry should still be in queue (re-queued)
expect(queueManager.getQueueLength()).toBe(1);
// Now simulate confirmation after the block (await the async callback)
await monitorCallback({ in_mempool: true, confirmed: true, amount: 1000, confirmations: 1 });
// Confirmation after the block. `complete: true` means the received amount covers
// the expected amount — required for a game to start (Phase 0.1 gate).
await monitorCallback({ in_mempool: true, confirmed: true, complete: true, amount: 1000, required: 1000, confirmations: 1 });
// Immediate game start expected
const gameStarts = events.filter(e => e.event === 'game_start');
expect(gameStarts.length).toBe(1);
expect(gameStarts[0].data.blockHeight).toBe(blockHeight);
// Queue should now be empty
expect(queueManager.getQueueLength()).toBe(0);
});
test('confirmed but UNDERPAID does not start a game or grant anything', async () => {
const { events, queueManager, paymentHandlers, fakeSocket, getMonitorCallback } = buildHarness();
await paymentHandlers.createAndShowPaymentRequest(fakeSocket);
const monitorCallback = getMonitorCallback();
expect(monitorCallback).toBeDefined();
// Mempool detection queues the player (queueing is gated on confirmation downstream)
await monitorCallback({ in_mempool: true, confirmed: false, amount: 1, confirmations: 0 });
// Confirmed on-chain, but only 1 of 1000 atomic units received → complete is false.
await monitorCallback({ in_mempool: true, confirmed: true, complete: false, amount: 1, required: 1000, confirmations: 1 });
// No game must start, and the user must be warned about the underpayment.
expect(events.filter(e => e.event === 'game_start').length).toBe(0);
expect(events.filter(e => e.event === 'payment_underpaid').length).toBe(1);
const underpaid = events.find(e => e.event === 'payment_underpaid');
expect(underpaid.data.received).toBe(1);
expect(underpaid.data.required).toBe(1000);
expect(underpaid.data.shortfall).toBe(999);
// Repeated underpaid polls must not spam the user (notify once).
await monitorCallback({ in_mempool: true, confirmed: true, complete: false, amount: 1, required: 1000, confirmations: 2 });
expect(events.filter(e => e.event === 'payment_underpaid').length).toBe(1);
});
});
+88
View File
@@ -0,0 +1,88 @@
/**
* Provably-fair determinism tests (Phase 0.2).
*
* The committed seed must deterministically generate the dungeon and drive monster
* behaviour, so that:
* - the same seed always reproduces the exact same dungeon (verifiability), and
* - the server cannot craft a different/unfair dungeon after seeing the seed.
*/
const DungeonGenerator = require('../src/game/dungeon');
const Monster = require('../src/game/monster');
const { createSeededRNG, hashSeed, verifyGame } = require('../src/game/provablyFair');
const SEED_A = 'a'.repeat(64);
const SEED_B = 'b'.repeat(64);
describe('Provably fair: deterministic dungeon generation', () => {
test('same seed regenerates an identical dungeon layout', () => {
const d1 = DungeonGenerator.regenerateFromSeed(SEED_A, 'WOW');
const d2 = DungeonGenerator.regenerateFromSeed(SEED_A, 'WOW');
expect(DungeonGenerator.layoutFingerprint(d1))
.toBe(DungeonGenerator.layoutFingerprint(d2));
expect(d1.entrance).toEqual(d2.entrance);
expect(d1.exit).toEqual(d2.exit);
expect(d1.treasure).toEqual(d2.treasure);
expect(d1.map).toEqual(d2.map);
});
test('regeneration is stable even when interleaved with another seed (no global RNG bleed)', () => {
const a1 = DungeonGenerator.layoutFingerprint(DungeonGenerator.regenerateFromSeed(SEED_A, 'WOW'));
// Generate a different seed's dungeon in between — must not affect SEED_A's output.
DungeonGenerator.regenerateFromSeed(SEED_B, 'WOW');
const a2 = DungeonGenerator.layoutFingerprint(DungeonGenerator.regenerateFromSeed(SEED_A, 'WOW'));
expect(a1).toBe(a2);
});
test('different seeds produce different layouts', () => {
const fpA = DungeonGenerator.layoutFingerprint(DungeonGenerator.regenerateFromSeed(SEED_A, 'WOW'));
const fpB = DungeonGenerator.layoutFingerprint(DungeonGenerator.regenerateFromSeed(SEED_B, 'WOW'));
expect(fpA).not.toBe(fpB);
});
test('verifyGame confirms the seed/commitment relationship', () => {
const commitment = hashSeed(SEED_A);
expect(verifyGame(SEED_A, commitment).valid).toBe(true);
expect(verifyGame(SEED_B, commitment).valid).toBe(false);
});
});
describe('Provably fair: deterministic monster movement', () => {
// A small open room so the monster always has somewhere to wander.
function buildDungeon() {
const map = Array.from({ length: 7 }, () => Array(7).fill("'1"));
for (let i = 0; i < 7; i++) { map[0][i] = '#'; map[6][i] = '#'; map[i][0] = '#'; map[i][6] = '#'; }
return { map };
}
test('wandering is reproducible from the same seeded RNG sequence', () => {
const dungeon = buildDungeon();
const run = () => {
const rng = createSeededRNG(SEED_A);
const m = new Monster(3, 3, { visionRange: 5 });
const path = [];
for (let i = 0; i < 20; i++) {
m.moveTowardPlayer(null, dungeon, rng); // no player => wander using rng
path.push([m.x, m.y]);
}
return path;
};
expect(run()).toEqual(run());
});
test('different seeds yield different wander paths', () => {
const dungeon = buildDungeon();
const walk = (seed) => {
const rng = createSeededRNG(seed);
const m = new Monster(3, 3, { visionRange: 5 });
const path = [];
for (let i = 0; i < 20; i++) {
m.moveTowardPlayer(null, dungeon, rng);
path.push([m.x, m.y]);
}
return JSON.stringify(path);
};
expect(walk(SEED_A)).not.toBe(walk(SEED_B));
});
});