diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31c7d8e..fec6345 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,8 @@ jobs: JWT_SECRET: ci_jwt_secret_not_for_production PAYSTACK_SECRET_KEY: sk_test_ci_placeholder NODE_ENV: test + # Safe only because this workflow creates a fresh disposable PostgreSQL service. + ALLOW_DESTRUCTIVE_TEST: '1' steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 diff --git a/backend/middleware/throttle.js b/backend/middleware/throttle.js index 3b4b59d..b44be5c 100644 --- a/backend/middleware/throttle.js +++ b/backend/middleware/throttle.js @@ -34,8 +34,10 @@ function limiter({ limit, windowMs, key }) { } return next(); } catch (e) { - console.error('[throttle]', e.message); - return next(); + // Fail closed: if the shared limiter cannot be checked, do not allow + // login or registration attempts to bypass the configured rate limit. + console.error('[throttle] rate-limit storage unavailable:', e.message); + return res.status(503).json({ success: false, error: 'Authentication is temporarily unavailable. Please try again shortly.' }); } }; } diff --git a/backend/routes/transfers.js b/backend/routes/transfers.js index 295db2b..1f50b7d 100644 --- a/backend/routes/transfers.js +++ b/backend/routes/transfers.js @@ -11,9 +11,20 @@ r.post('/simulated', auth, async (req, res, next) => { try { await initDb(); const { bankCode, accountNumber, accountName, description } = req.body || {}; const amount = Number(req.body && req.body.amount); const idemKey = (req.get('Idempotency-Key') || '').trim().slice(0, 128) || null; const pool = getPool(); - if (idemKey) { const prior = await pool.query('SELECT ' + TX_COLUMNS + ' FROM transactions WHERE user_id=$1 AND idempotency_key=$2', [req.user.id, idemKey]); if (prior.rows[0]) return res.json({ success: true, simulated: true, replayed: true, transaction: prior.rows[0] }); } if (!bankCode || !/^[0-9]{10}$/.test(accountNumber || '') || !accountName) return res.status(400).json({ success: false, error: 'Complete valid transfer details are required' }); - if (!Number.isFinite(amount) || amount <= 0 || amount > MAX_TRANSFER) return res.status(400).json({ success: false, error: `Amount must be between ₦1 and ₦${MAX_TRANSFER.toLocaleString('en-NG')}` }); + if (!Number.isFinite(amount) || amount < 1 || amount > MAX_TRANSFER) return res.status(400).json({ success: false, error: `Amount must be between ₦1 and ₦${MAX_TRANSFER.toLocaleString('en-NG')}` }); + if (idemKey) { + const prior = await pool.query('SELECT ' + TX_COLUMNS + ' FROM transactions WHERE user_id=$1 AND idempotency_key=$2', [req.user.id, idemKey]); + if (prior.rows[0]) { + const previous = prior.rows[0]; + const sameRequest = Math.round(Number(previous.amount) * 100) === Math.round(amount * 100) + && String(previous.accountNumber || '') === String(accountNumber) + && String(previous.bankCode || '') === String(bankCode) + && norm(previous.accountName) === norm(accountName); + if (!sameRequest) return res.status(409).json({ success: false, error: 'Idempotency key was already used for a different transfer. Use a new key for a new transfer.' }); + return res.json({ success: true, simulated: true, replayed: true, transaction: previous }); + } + } let bank; try { bank = await findBank(bankCode); } catch (e) { console.error('[transfers:banks]', e.message); return res.status(/not configured/i.test(e.message) ? 503 : 502).json({ success: false, error: 'Bank list unavailable, cannot validate bank code' }); } if (!bank) return res.status(400).json({ success: false, error: 'Unknown or inactive bank code' }); let resolved; try { resolved = await resolveAccount(accountNumber, bankCode); } catch (e) { console.error('[transfers:resolve]', e.message); return res.status(502).json({ success: false, error: 'Account could not be verified with the bank' }); } diff --git a/backend/routes/wallet.js b/backend/routes/wallet.js index 782a4bc..ec6acc7 100644 --- a/backend/routes/wallet.js +++ b/backend/routes/wallet.js @@ -9,7 +9,7 @@ r.get('/', auth, async (req, res, next) => { try { await initDb(); const { rows r.post('/fund-simulated', auth, async (req, res, next) => { try { await initDb(); const amount = Number(req.body && req.body.amount); - if (!Number.isFinite(amount) || amount <= 0 || amount > MAX_SINGLE_FUNDING) return res.status(400).json({ success: false, error: `Funding amount must be between ₦1 and ₦${MAX_SINGLE_FUNDING.toLocaleString('en-NG')}` }); + if (!Number.isFinite(amount) || amount < 1 || amount > MAX_SINGLE_FUNDING) return res.status(400).json({ success: false, error: `Funding amount must be between ₦1 and ₦${MAX_SINGLE_FUNDING.toLocaleString('en-NG')}` }); const kobo = Math.round(amount * 100), client = await getPool().connect(); try { await client.query('BEGIN'); diff --git a/verify.e2e.js b/verify.e2e.js index 89b6581..eb92493 100644 --- a/verify.e2e.js +++ b/verify.e2e.js @@ -1,7 +1,21 @@ -const DB_URL = process.env.TEST_DATABASE_URL || 'postgresql://postgres:pass@127.0.0.1:5432/flash_simulator_test'; +const DB_URL = process.env.TEST_DATABASE_URL; +if (!DB_URL) { + console.error('REFUSING TO RUN: set TEST_DATABASE_URL to a dedicated disposable PostgreSQL test database.'); + process.exit(3); +} let dbName = ''; -try { dbName = new URL(DB_URL).pathname.replace(/^\//, ''); } catch (_) { console.error(`TEST_DATABASE_URL is not a valid URL: ${DB_URL}`); process.exit(3); } -if (!/test|ci|sim/i.test(dbName) && process.env.ALLOW_DESTRUCTIVE_TEST !== '1') { console.error(`REFUSING TO RUN: database "${dbName}" does not look like a test database.`); process.exit(3); } +try { dbName = new URL(DB_URL).pathname.replace(/^\//, ''); } catch (_) { + console.error('TEST_DATABASE_URL is not a valid URL.'); + process.exit(3); +} +if (!/test|ci/i.test(dbName)) { + console.error('REFUSING TO RUN: database name must contain "test" or "ci".'); + process.exit(3); +} +if (process.env.ALLOW_DESTRUCTIVE_TEST !== '1') { + console.error('REFUSING TO RUN: this test drops database tables. Set ALLOW_DESTRUCTIVE_TEST=1 only for a disposable test database.'); + process.exit(3); +} process.env.DATABASE_URL = DB_URL; process.env.JWT_SECRET = process.env.JWT_SECRET || 'verification_secret_key_only'; process.env.PAYSTACK_SECRET_KEY = process.env.PAYSTACK_SECRET_KEY || 'sk_test_stub'; @@ -57,6 +71,10 @@ const log = (name, ok, detail) => R.push(`${ok ? 'PASS' : 'FAIL'} ${name} ${de const c1 = await req('/api/transfers/simulated', { method: 'POST', headers: { ...H, 'Idempotency-Key': key }, body }); const c2 = await req('/api/transfers/simulated', { method: 'POST', headers: { ...H, 'Idempotency-Key': key }, body }); log('idempotency replay', c1.d.transaction.reference === c2.d.transaction.reference && c2.d.replayed === true, 'same reference'); + const changed = await req('/api/transfers/simulated', { method: 'POST', headers: { ...H, 'Idempotency-Key': key }, body: JSON.stringify({ ...base, amount: 25 }) }); + log('idempotency key rejects changed amount', changed.s === 409 && /different transfer/i.test(changed.d.error), `HTTP ${changed.s}`); + const afterReplay = await req('/api/wallet', { headers: H }); + log('idempotent replay does not debit twice', afterReplay.d.wallet.balance === 650, `balance=${afterReplay.d.wallet.balance}`); x = await req('/api/notifications', { headers: H }); log('notifications', x.s === 200 && Array.isArray(x.d.notifications), `count=${x.d.notifications?.length}`); const entry = require('./api/index.js'); log('api/index.js exports Express app', typeof entry === 'function', typeof entry); console.log(R.join('\n')); const fails = R.filter((r) => r.startsWith('FAIL')); console.log(`PASS ${R.length - fails.length} FAIL ${fails.length}`); server.close(); await getPool().end(); process.exit(fails.length ? 1 : 0);