From 2f08a2523a32b750fc488bd8cd31a137dc7dcad3 Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 21:07:40 +0530 Subject: [PATCH 1/7] fix(finance): harden infrastructure fee accounting and verification queue - Add upfront idempotency check in recordBookingFeeEntry to prevent double-counting of fee payable and duplicate invoice lines - Prevent cross-organiser invoice allocations and invalid invoice status in confirmFeePayment - Enforce strict ownership check on invoiceId/paymentReference in submitFeePayment - Validate evidence screenshot URLs against URL injection / unsafe schemes - Add state machine guards against re-rejecting or investigating settled/rejected claims - Add rate limits on organiser finance endpoints and CSV statement export - Add proof evidence preview column in admin payment verification queue - Add comprehensive automated tests covering all hardened security and accounting scenarios --- lib/handlers/organiser.js | 4 + lib/services/finance.js | 72 +++++++++++- public/js/admin.js | 10 ++ test/infrastructure-fee-accounting.test.js | 125 ++++++++++++++++++++- 4 files changed, 207 insertions(+), 4 deletions(-) diff --git a/lib/handlers/organiser.js b/lib/handlers/organiser.js index 1ac659f..722645f 100644 --- a/lib/handlers/organiser.js +++ b/lib/handlers/organiser.js @@ -489,6 +489,7 @@ export async function guestTicket(ctx) { export async function organiserFinance(ctx) { const user = await organiser(ctx); + await rateLimit(`org:finance:${user.id}`, 60, 60); const data = await getOrganiserFinanceSummary(user.id); sendJson(ctx.res, 200, { ok: true, ...data }); } @@ -497,6 +498,7 @@ export async function eventFinance(ctx) { const user = await requireUser(ctx.req); const eventId = id(ctx.params.id); await authorize(user, 'event.manage', { eventId }); + await rateLimit(`org:evtfinance:${user.id}`, 60, 60); const data = await getOrganiserFinanceSummary(user.id); const eventData = data.events.find((e) => e.eventId === eventId); if (!eventData) throw new HttpError(404, 'event_not_found', 'Event finance record not found'); @@ -522,6 +524,7 @@ const SubmitPaymentBody = z.object({ export async function submitOrganiserFeePayment(ctx) { const user = await organiser(ctx, { write: true, scope: 'fee_payment' }); + await rateLimit(`org:feepay:${user.id}`, 20, 600); const body = parse(SubmitPaymentBody, await readJson(ctx.req)); const res = await submitFeePayment({ organiserId: user.id, @@ -538,6 +541,7 @@ export async function submitOrganiserFeePayment(ctx) { export async function downloadOrganiserStatement(ctx) { const user = await organiser(ctx); + await rateLimit(`org:statement:${user.id}`, 15, 60); const csv = await generateOrganiserStatementCsv(user.id); ctx.res.setHeader('Content-Type', 'text/csv; charset=utf-8'); ctx.res.setHeader('Content-Disposition', 'attachment; filename="nightlifez-financial-statement.csv"'); diff --git a/lib/services/finance.js b/lib/services/finance.js index 09a947d..077b3e2 100644 --- a/lib/services/finance.js +++ b/lib/services/finance.js @@ -32,6 +32,33 @@ export function isValidUtr(ref) { return true; } +/** + * Validates screenshot or evidence proof URLs. + * Allows valid https:// URLs or local relative paths in /uploads/ or /media/. + * Strictly forbids javascript:, data:, file:, and control characters. + */ +export function isValidEvidenceUrl(url) { + if (!url || typeof url !== 'string') return false; + const trimmed = url.trim(); + if (trimmed.length > 2048) return false; + if (/[\r\n\t\0]/.test(trimmed)) return false; + if (/^(javascript|data|file|vbscript):/i.test(trimmed)) return false; + + // Allow relative upload paths e.g. /uploads/evidence.jpg + if (/^\/(uploads|media|assets)\/[A-Za-z0-9_\-./]+$/.test(trimmed)) { + if (trimmed.includes('..')) return false; + return true; + } + + // Allow absolute https URLs + try { + const parsed = new URL(trimmed); + return parsed.protocol === 'https:' && !parsed.username && !parsed.password; + } catch { + return false; + } +} + /** * Verifies finance or super_admin authorization from an active admin_users row. */ @@ -222,6 +249,15 @@ export async function recordBookingFeeEntry(booking, event, tier, c = db) { return null; } + // 0. Upfront Idempotency Check: if an entry already exists for this booking, return immediately + const existingEntry = (await c.query( + `SELECT * FROM infrastructure_fee_entries WHERE booking_id = $1`, + [booking.id] + )).rows[0]; + if (existingEntry) { + return { feeEntry: existingEntry, duplicate: true }; + } + const snapshot = { ruleId: activeRule.id, feePercentage: feePct, @@ -503,6 +539,14 @@ export async function submitFeePayment({ throw new HttpError(400, 'validation', 'Please enter a valid 12-character bank UTR reference number'); } + let cleanScreenshotUrl = null; + if (screenshotUrl) { + cleanScreenshotUrl = String(screenshotUrl).trim(); + if (!isValidEvidenceUrl(cleanScreenshotUrl)) { + throw new HttpError(400, 'validation', 'Invalid screenshot URL: only HTTPS or safe upload paths are permitted'); + } + } + return c.tx(async (tx) => { // 1. Prevent duplicate UTR const dupSubmission = (await tx.query( @@ -528,11 +572,17 @@ export async function submitFeePayment({ `SELECT * FROM organiser_fee_invoices WHERE id = $1 AND organiser_id = $2`, [invoiceId, organiserId] )).rows[0]; + if (!inv) { + throw new HttpError(404, 'invoice_not_found', 'Invoice not found or does not belong to this organiser'); + } } else if (paymentReference) { inv = (await tx.query( `SELECT * FROM organiser_fee_invoices WHERE payment_reference = $1 AND organiser_id = $2`, [paymentReference, organiserId] )).rows[0]; + if (!inv) { + throw new HttpError(404, 'invoice_not_found', 'Payment reference not found or does not belong to this organiser'); + } } const ref = inv?.payment_reference || paymentReference || generatePaymentReference(); @@ -560,7 +610,7 @@ export async function submitFeePayment({ cleanUtr, payerUpiId ? String(payerUpiId).trim() : null, notes ? String(notes).trim() : null, - screenshotUrl || null + cleanScreenshotUrl ] )).rows[0]; @@ -735,6 +785,14 @@ export async function confirmFeePayment({ if (!inv) throw new HttpError(404, 'invoice_not_found', `Invoice ${alloc.invoiceId} not found`); + if (inv.organiser_id !== submission.organiser_id) { + throw new HttpError(400, 'cross_organiser_allocation', `Invoice ${inv.invoice_number} does not belong to the payment organiser`); + } + + if (inv.status === 'cancelled') { + throw new HttpError(400, 'invalid_invoice_status', `Cannot allocate payment to cancelled invoice ${inv.invoice_number}`); + } + if (alloc.amountPaise > inv.outstanding_amount_paise) { throw new HttpError(400, 'excess_allocation', `Allocation of ₹${(alloc.amountPaise / 100).toFixed(2)} exceeds invoice ${inv.invoice_number} outstanding amount of ₹${(inv.outstanding_amount_paise / 100).toFixed(2)}`); } @@ -868,6 +926,10 @@ export async function rejectFeePayment({ submissionId, reason, adminUser }, c = throw new HttpError(409, 'already_verified', 'Cannot reject an already confirmed and verified payment'); } + if (sub.status === 'rejected') { + throw new HttpError(409, 'already_rejected', 'This payment submission has already been rejected'); + } + const updated = (await tx.query( `UPDATE organiser_fee_payment_submissions SET status = 'rejected', @@ -930,6 +992,14 @@ export async function investigateFeePayment({ submissionId, notes, adminUser }, throw new HttpError(404, 'not_found', 'Payment submission not found'); } + if (sub.status === 'verified') { + throw new HttpError(409, 'already_verified', 'Cannot investigate an already verified and settled payment'); + } + + if (sub.status === 'rejected') { + throw new HttpError(409, 'already_rejected', 'Cannot investigate an already rejected payment'); + } + const updated = (await tx.query( `UPDATE organiser_fee_payment_submissions SET status = 'under_investigation', diff --git a/public/js/admin.js b/public/js/admin.js index cb40890..b278fb9 100644 --- a/public/js/admin.js +++ b/public/js/admin.js @@ -692,6 +692,16 @@ ['Bank UTR Reference', function (s) { return el('code', { text: s.utr_number }); }], ['Submitted On', function (s) { return fmtDT(s.created_at); }], ['Outstanding Before', function (s) { return rupees(s.outstanding_before_confirmation_paise); }], + ['Proof', function (s) { + if (!s.screenshot_url) return el('span', { class: 'muted small', text: 'None' }); + return el('a', { + href: s.screenshot_url, + target: '_blank', + rel: 'noopener noreferrer', + class: 'link-subtle small', + text: 'View Proof ↗' + }); + }], ['Status', function (s) { return pill(s.status); }], ['', function (s) { if (s.status === 'verified') return el('span', { class: 'muted small', text: 'Verified' }); diff --git a/test/infrastructure-fee-accounting.test.js b/test/infrastructure-fee-accounting.test.js index fc11ca1..1be3098 100644 --- a/test/infrastructure-fee-accounting.test.js +++ b/test/infrastructure-fee-accounting.test.js @@ -538,9 +538,9 @@ test('12. Organiser isolation: cannot view or pay another organiser\'s finances' amountPaise: 5000, utrNumber: `HACK-UTR-${Date.now()}` }); - // Does not affect Organiser A's invoice - const subCreated = (await db.query(`SELECT * FROM organiser_fee_payment_submissions WHERE id = $1`, [hackRes.json.submission.id])).rows[0]; - assert.equal(subCreated.invoice_id, null, 'Invoice ID must be ignored if owned by another organiser'); + // Must reject with 404 because invoice is not owned by Organiser B + assert.equal(hackRes.status, 404, 'Must strictly reject submitting payments against another organiser\'s invoice'); + assert.equal(hackRes.json.error, 'invoice_not_found'); }); test('13. Non-finance admin cannot confirm or reject payments', async () => { @@ -703,3 +703,122 @@ test('19. Admin deadline extension updates invoice due date and records audit tr assert.ok(auditLog); assert.equal(auditLog.actor_id, financeClient.admin.id); }); + +test('20. Accrual idempotency: repeated recordBookingFeeEntry calls do not duplicate balance or invoice lines', async () => { + const feeEntryRow = (await db.query(`SELECT * FROM infrastructure_fee_entries LIMIT 1`)).rows[0]; + const booking = (await db.query(`SELECT * FROM bookings WHERE id = $1`, [feeEntryRow.booking_id])).rows[0]; + const event = (await db.query(`SELECT * FROM events WHERE id = $1`, [feeEntryRow.event_id])).rows[0]; + const tier = (await db.query(`SELECT * FROM ticket_types WHERE id = $1`, [feeEntryRow.ticket_type_id])).rows[0]; + + const accBefore = (await db.query(`SELECT * FROM organiser_fee_accounts WHERE organiser_id = $1`, [event.organiser_user_id])).rows[0]; + const linesBefore = (await db.query(`SELECT COUNT(*)::int AS count FROM organiser_fee_invoice_lines WHERE fee_entry_id = $1`, [feeEntryRow.id])).rows[0].count; + + // Re-run recordBookingFeeEntry for the same booking + const duplicateResult = await recordBookingFeeEntry(booking, event, tier); + assert.ok(duplicateResult); + assert.equal(duplicateResult.duplicate, true); + + const accAfter = (await db.query(`SELECT * FROM organiser_fee_accounts WHERE organiser_id = $1`, [event.organiser_user_id])).rows[0]; + const linesAfter = (await db.query(`SELECT COUNT(*)::int AS count FROM organiser_fee_invoice_lines WHERE fee_entry_id = $1`, [feeEntryRow.id])).rows[0].count; + + assert.equal(accAfter.total_fee_payable_paise, accBefore.total_fee_payable_paise, 'Payable balance must not increase on duplicate call'); + assert.equal(linesAfter, linesBefore, 'Invoice lines must not be duplicated on duplicate call'); +}); + +test('21. Cross-organiser invoice allocation is strictly rejected with 400', async () => { + const invA = (await db.query(`SELECT * FROM organiser_fee_invoices WHERE organiser_id = $1 LIMIT 1`, [organiserAClient.user.id])).rows[0]; + const invB = (await db.query(`SELECT * FROM organiser_fee_invoices WHERE organiser_id = $1 LIMIT 1`, [organiserBClient.user.id])).rows[0]; + + const sub = await submitFeePayment({ + organiserId: organiserAClient.user.id, + invoiceId: invA.id, + amountPaise: 5000, + utrNumber: `CROSS-ALLOC-${Date.now()}` + }); + + // Finance admin attempts to allocate Organiser A's bank payment to Organiser B's invoice + await assert.rejects( + async () => { + await confirmFeePayment({ + submissionId: sub.submission.id, + bankTxId: `BANK-TX-CROSS-${Date.now()}`, + verifiedAmountPaise: 5000, + adminUser: financeClient.user, + allocations: [{ invoiceId: invB.id, amountPaise: 5000 }] + }); + }, + (err) => { + assert.equal(err.status, 400); + assert.equal(err.code, 'cross_organiser_allocation'); + return true; + } + ); +}); + +test('22. Malicious screenshot URLs in payment submission are rejected with 400', async () => { + const invA = (await db.query(`SELECT * FROM organiser_fee_invoices WHERE organiser_id = $1 LIMIT 1`, [organiserAClient.user.id])).rows[0]; + + // JavaScript scheme + const jsRes = await organiserAClient.post('/api/organiser/finance/submit-payment', { + invoiceId: invA.id, + amountPaise: 5000, + utrNumber: `XSS-JS-${Date.now()}`, + screenshotUrl: 'javascript:alert(document.cookie)' + }); + assert.equal(jsRes.status, 400); + assert.equal(jsRes.json.error, 'validation'); + + // Data URI scheme + const dataRes = await organiserAClient.post('/api/organiser/finance/submit-payment', { + invoiceId: invA.id, + amountPaise: 5000, + utrNumber: `XSS-DATA-${Date.now()}`, + screenshotUrl: 'data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==' + }); + assert.equal(dataRes.status, 400); + assert.equal(dataRes.json.error, 'validation'); + + // Valid HTTPS URL succeeds + const validRes = await organiserAClient.post('/api/organiser/finance/submit-payment', { + invoiceId: invA.id, + amountPaise: 5000, + utrNumber: `VALID-URL-${Date.now()}`, + screenshotUrl: 'https://images.nightlifez.in/uploads/payment-receipt-123.png' + }); + assert.equal(validRes.status, 201); + assert.equal(validRes.json.ok, true); +}); + +test('23. State machine guards: cannot re-reject or investigate already terminal submissions', async () => { + // Find a rejected submission + const rejSub = (await db.query(`SELECT * FROM organiser_fee_payment_submissions WHERE status = 'rejected' LIMIT 1`)).rows[0]; + assert.ok(rejSub, 'Must have a rejected submission from earlier tests'); + + // Attempting to re-reject + const reRejectRes = await financeClient.post('/api/admin/finance/reject-payment', { + submissionId: rejSub.id, + reason: 'Second rejection attempt' + }); + assert.equal(reRejectRes.status, 409); + assert.equal(reRejectRes.json.error, 'already_rejected'); + + // Attempting to investigate an already rejected submission + const rejInvestigateRes = await financeClient.post('/api/admin/finance/investigate-payment', { + submissionId: rejSub.id, + notes: 'Investigating rejected claim' + }); + assert.equal(rejInvestigateRes.status, 409); + assert.equal(rejInvestigateRes.json.error, 'already_rejected'); + + // Find a verified submission + const verSub = (await db.query(`SELECT * FROM organiser_fee_payment_submissions WHERE status = 'verified' LIMIT 1`)).rows[0]; + assert.ok(verSub, 'Must have a verified submission from earlier tests'); + + // Attempting to investigate an already verified submission + const verInvestigateRes = await financeClient.post('/api/admin/finance/investigate-payment', { + submissionId: verSub.id, + notes: 'Investigating confirmed claim' + }); + assert.equal(verInvestigateRes.status, 409); + assert.equal(verInvestigateRes.json.error, 'already_verified'); +}); From e9f7d748131784749f32570114e8e3258154f2de Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 21:29:35 +0530 Subject: [PATCH 2/7] fix(upi): limit organiser infrastructure fee calculation to events with organiser_user_id - Align createUpiPaymentIntent with recordBookingFeeEntry by only accruing 5% infrastructure fee for organiser-managed events - Preserve existing internal/feed event and direct platform ticket checkout amounts - Fixes CI test failure in test/upi-checkout.test.js --- lib/services/upi-payments.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/lib/services/upi-payments.js b/lib/services/upi-payments.js index c25fba0..4a0fba0 100644 --- a/lib/services/upi-payments.js +++ b/lib/services/upi-payments.js @@ -292,13 +292,25 @@ export async function createUpiPaymentIntent({ } } - // 4. Generate Order ID, calculate transparent 5% platform fee & call Payment Adapter + // 4. Generate Order ID, calculate transparent 5% platform fee for organiser events & call Payment Adapter const orderId = newUpiOrderId(); const guestToken = crypto.randomBytes(24).toString('base64url'); const baseAmountPaise = tier.price_paise * qty; - const activeRule = await getActiveFeeRule(c); - const feePct = Number(activeRule?.fee_percentage ?? DEFAULT_FEE_PERCENTAGE); - const calc = calculateInfrastructureFee(baseAmountPaise, feePct); + let feePct = 0; + let feeRuleId = null; + let calc = { + basePaise: baseAmountPaise, + feePaise: 0, + totalPaise: baseAmountPaise, + feePercentage: 0 + }; + + if (event.organiser_user_id) { + const activeRule = await getActiveFeeRule(c); + feePct = Number(activeRule?.fee_percentage ?? DEFAULT_FEE_PERCENTAGE); + feeRuleId = activeRule?.id || null; + calc = calculateInfrastructureFee(baseAmountPaise, feePct); + } const amountPaise = calc.totalPaise; const adapter = getAdapter(); @@ -356,7 +368,7 @@ export async function createUpiPaymentIntent({ feePaise: calc.feePaise, totalAmountPaise: calc.totalPaise, feePercentage: feePct, - feeRuleId: activeRule?.id || null, + feeRuleId: feeRuleId, organiserUpiId: event.organiser_upi_id || null }) ] From 21267bba7a440838edbc4a8b3c731d783ddc4352 Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 21:36:00 +0530 Subject: [PATCH 3/7] test(personas): align super_admin console tabs assertion with finance tab --- test/personas.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/personas.test.js b/test/personas.test.js index ef97aa6..8c8d95b 100644 --- a/test/personas.test.js +++ b/test/personas.test.js @@ -309,7 +309,7 @@ test('admin: denied — demoting themselves, writes without CSRF', async () => { test('admin console renders only the tabs each role can load', async () => { const tabs = async (p) => [...(await (await as(p)).get('/admin')).text.matchAll(/data-tab="(\w+)"/g)].map((m) => m[1]); assert.deepEqual(await tabs('admin'), - ['overview', 'insights', 'discovery', 'events', 'bookings', 'orders', 'memberships', 'leads', 'media', 'tiers', 'integrations', 'admins']); + ['overview', 'insights', 'discovery', 'events', 'finance', 'bookings', 'orders', 'memberships', 'leads', 'media', 'tiers', 'integrations', 'admins']); assert.deepEqual(await tabs('staff'), ['overview', 'events', 'bookings', 'orders', 'memberships', 'leads', 'tiers']); assert.deepEqual(await tabs('organiser'), [], 'not an admin: no console'); }); From 54eb381eb7576067ca7e4973c5c6768f9e1d28ea Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 21:43:22 +0530 Subject: [PATCH 4/7] test(e2e): align automated checkout intent amount assertion with 5% platform fee --- test/automated-checkout-e2e.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/automated-checkout-e2e.test.js b/test/automated-checkout-e2e.test.js index 625d23e..822be64 100644 --- a/test/automated-checkout-e2e.test.js +++ b/test/automated-checkout-e2e.test.js @@ -124,7 +124,7 @@ test('End-to-end automated checkout: Intent -> Webhook -> Pass issuance -> Whats }); assert.ok(intent.orderId); - assert.equal(intent.amountPaise, 129900); + assert.equal(intent.amountPaise, 136395); // 129,900 + 5% platform fee (6,495) assert.ok(intent.upiIntentUrl); // Seat hold is active @@ -139,7 +139,7 @@ test('End-to-end automated checkout: Intent -> Webhook -> Pass issuance -> Whats merchantId: 'PGTESTPAYUAT', merchantTransactionId: intent.orderId, transactionId: `TXN_${crypto.randomBytes(6).toString('hex')}`, - amount: 129900, + amount: intent.amountPaise, currency: 'INR', state: 'COMPLETED', responseCode: 'SUCCESS', From bbe478119aedf32c1a7a04ef0d4bf87473e4e929 Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 22:05:42 +0530 Subject: [PATCH 5/7] fix(e2e): prevent 320px finance button overflow and update wizard payment notice assertion --- e2e/multi-date-wizard.spec.js | 2 +- public/css/organiser.css | 1 + public/js/organiser.js | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/e2e/multi-date-wizard.spec.js b/e2e/multi-date-wizard.spec.js index b26082a..fcf5e64 100644 --- a/e2e/multi-date-wizard.spec.js +++ b/e2e/multi-date-wizard.spec.js @@ -86,7 +86,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => // Verify Payment contradiction notice const payNotice = page.locator('.notice-warn'); await expect(payNotice).toBeVisible(); - await expect(payNotice).toContainText('Online payment is not configured yet'); + await expect(payNotice).toContainText(/Online payment is (?:pending gateway configuration|not configured yet)/); // Verify quick-add chips exist and are accessible const quickAddGeneral = page.locator('button.chip[data-act="add-tier"][data-preset="general"]'); diff --git a/public/css/organiser.css b/public/css/organiser.css index 089346f..04d271f 100644 --- a/public/css/organiser.css +++ b/public/css/organiser.css @@ -437,6 +437,7 @@ .org-fin-table { width: 100%; border-collapse: collapse; font-size: 0.88rem; } .org-fin-table th, .org-fin-table td { padding: 10px 12px; text-align: left; border-bottom: 1px solid var(--line); } .org-fin-table th { color: var(--muted); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.05em; } +.org-fin-btn, .org-fin-card a.btn, .org-fin-card button.btn { max-width: 100%; white-space: normal; text-align: center; word-break: break-word; } .pill-ok { background: rgba(0, 255, 136, 0.15); border-color: rgba(0, 255, 136, 0.4); color: var(--neon-green, #00FF88); } .pill-info { background: rgba(0, 217, 255, 0.15); border-color: rgba(0, 217, 255, 0.4); color: var(--neon-cyan, #00D9FF); } .pill-warn { background: rgba(255, 184, 0, 0.15); border-color: rgba(255, 184, 0, 0.4); color: #ffb800; } diff --git a/public/js/organiser.js b/public/js/organiser.js index f128f85..1519409 100644 --- a/public/js/organiser.js +++ b/public/js/organiser.js @@ -109,7 +109,7 @@ '
Outstanding Balance' + money(acc.outstandingBalancePaise) + '
' + '' + '
' + - '📥 Download Financial Statement (CSV)' + + '📥 Download Statement (CSV)' + 'Manage and settle event fees directly from each event\'s Manage tab.' + '
' + ''; @@ -298,7 +298,7 @@ h += '
' + '
' + '

Payment Claims & History

' + - '📥 Download Financial Statement (CSV)' + + '📥 Download Statement (CSV)' + '
'; if (!subs.length) { From f4be63a597a2a80008195dca082b292a0e9d3903 Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 22:25:25 +0530 Subject: [PATCH 6/7] test(e2e): align wizard draft ticket pill assertion with gateway pending text --- e2e/multi-date-wizard.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/multi-date-wizard.spec.js b/e2e/multi-date-wizard.spec.js index fcf5e64..6ffa259 100644 --- a/e2e/multi-date-wizard.spec.js +++ b/e2e/multi-date-wizard.spec.js @@ -101,7 +101,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => // Check that paid tier displays draft indicator and warning const draftPill = page.locator('.pill-draft').first(); await expect(draftPill).toBeVisible(); - await expect(draftPill).toContainText('Draft — External Checkout Pending'); + await expect(draftPill).toContainText(/Paid \((?:Gateway Pending|Draft — External Checkout Pending)\)/); // Capture Step 2 evidence await page.screenshot({ path: path.join(ARTIFACT_DIR, 'multi-date-tickets-draft-state.png'), fullPage: true }); From 2634876590870c27971f3b4a8d1c865d2664c3fc Mon Sep 17 00:00:00 2001 From: Satelink Network Date: Sun, 22 Nov 2026 23:40:32 +0530 Subject: [PATCH 7/7] fix(finance): enforce production UPI fail-closed guards, disable unconfigured settlement claims, and add regression tests --- lib/services/finance.js | 26 ++++- public/js/organiser.js | 54 +++++---- test/infrastructure-fee-accounting.test.js | 122 ++++++++++++++++++++- 3 files changed, 172 insertions(+), 30 deletions(-) diff --git a/lib/services/finance.js b/lib/services/finance.js index 077b3e2..24ad129 100644 --- a/lib/services/finance.js +++ b/lib/services/finance.js @@ -6,16 +6,28 @@ import crypto from 'node:crypto'; import { db } from '../db.js'; import { HttpError } from '../http.js'; import { logger } from '../logger.js'; -import { env } from '../config.js'; +import { env, isProductionRuntime } from '../config.js'; export const DEFAULT_FEE_PERCENTAGE = 5.00; export function getPlatformFinanceUpi() { - return env('NIGHTLIFEZ_FINANCE_UPI_ID') || 'nightlifez.finance@icici'; + const configured = env('NIGHTLIFEZ_FINANCE_UPI_ID'); + if (isProductionRuntime()) { + // In production runtime, development fallback, placeholder, mock, or test VPAs are strictly prohibited. + if (!configured || configured === 'nightlifez.finance@icici') return null; + if (/^(test|dummy|mock|placeholder|fake|none|null)/i.test(configured)) return null; + return configured; + } + return configured || 'nightlifez.finance@icici'; } export function getPlatformFinanceName() { - return env('NIGHTLIFEZ_FINANCE_NAME') || 'NIGHTLIFEZ Experiences Private Limited'; + const configured = env('NIGHTLIFEZ_FINANCE_NAME'); + if (isProductionRuntime()) { + // In production, do not silently fabricate a legal entity name + return configured || null; + } + return configured || 'NIGHTLIFEZ Experiences Private Limited'; } /** @@ -534,6 +546,10 @@ export async function submitFeePayment({ throw new HttpError(400, 'validation', 'Submitted amount must be greater than zero'); } + if (isProductionRuntime() && !getPlatformFinanceUpi()) { + throw new HttpError(503, 'platform_upi_not_configured', 'Official platform settlement UPI is not configured. Direct fee submission claims are disabled until the official platform account is active.'); + } + const cleanUtr = String(utrNumber || '').trim(); if (!isValidUtr(cleanUtr)) { throw new HttpError(400, 'validation', 'Please enter a valid 12-character bank UTR reference number'); @@ -1204,12 +1220,12 @@ export async function getOrganiserFinanceSummary(organiserId, c = db) { platformUpi: { vpa: getPlatformFinanceUpi(), name: getPlatformFinanceName(), - instructions: [ + instructions: getPlatformFinanceUpi() ? [ '1. Transfer the exact fee amount via UPI or Net Banking to our official NIGHTLIFEZ UPI ID.', '2. Add your unique Payment Reference in the transaction remarks/notes.', '3. Enter the 12-digit bank UTR reference number below and submit your claim.', '4. Our finance team verifies the incoming credit with our bank before marking the invoice settled.' - ] + ] : [] } }; } diff --git a/public/js/organiser.js b/public/js/organiser.js index 1519409..69b8594 100644 --- a/public/js/organiser.js +++ b/public/js/organiser.js @@ -263,30 +263,36 @@ if (ev.outstandingPaise > 0) { h += '
' + '

💳 Pay NIGHTLIFEZ Infrastructure Fee

' + - '

Transfer the outstanding fee to our official platform account and submit your bank transaction UTR reference below.

' + - - '
' + - '

Official Platform UPI ID: ' + esc(upi.vpa) + '

' + - '

Account Name: ' + esc(upi.name) + '

' + - '

Unique Payment Reference: ' + esc(ev.paymentReference) + '

' + - '

Please include your Payment Reference in the payment remarks/notes when completing the transfer.

' + - '
' + - - '
' + - '' + - '' + - '
' + - '' + - '' + - '' + - '
' + - '' + - '' + - '

Notice: Organiser-submitted UTRs and screenshots are payment claims only. They must never automatically clear the outstanding balance. Balance updates only after our finance admin verifies the incoming credit with the bank.

' + - '' + - '' + - '
' + - '
'; + '

Transfer the outstanding fee to our official platform account and submit your bank transaction UTR reference below.

'; + + if (upi && upi.vpa) { + h += '
' + + '

Official Platform UPI ID: ' + esc(upi.vpa) + '

' + + (upi.name ? '

Account Name: ' + esc(upi.name) + '

' : '') + + '

Unique Payment Reference: ' + esc(ev.paymentReference) + '

' + + '

Please include your Payment Reference in the payment remarks/notes when completing the transfer.

' + + '
' + + '
' + + '' + + '' + + '
' + + '' + + '' + + '' + + '
' + + '' + + '' + + '

Notice: Organiser-submitted UTRs and screenshots are payment claims only. They must never automatically clear the outstanding balance. Balance updates only after our finance admin verifies the incoming credit with the bank.

' + + '' + + '' + + '
'; + } else { + h += '
' + + '

Official platform settlement account is pending administrative configuration.

' + + '

Direct fee collection via official UPI is temporarily inactive. Please contact NIGHTLIFEZ administration or your account manager for verified settlement instructions. Your unique payment reference is ' + esc(ev.paymentReference) + '.

' + + '
'; + } + h += '
'; } else { h += '
' + '

✓ Infrastructure Fee Fully Settled

' + diff --git a/test/infrastructure-fee-accounting.test.js b/test/infrastructure-fee-accounting.test.js index 1be3098..16501f1 100644 --- a/test/infrastructure-fee-accounting.test.js +++ b/test/infrastructure-fee-accounting.test.js @@ -17,7 +17,9 @@ import { getOrganiserFinanceSummary, getAdminFinanceOverview, extendPaymentDeadline, - DEFAULT_FEE_PERCENTAGE + DEFAULT_FEE_PERCENTAGE, + getPlatformFinanceUpi, + getPlatformFinanceName } from '../lib/services/finance.js'; import { createDraft, @@ -822,3 +824,121 @@ test('23. State machine guards: cannot re-reject or investigate already terminal assert.equal(verInvestigateRes.status, 409); assert.equal(verInvestigateRes.json.error, 'already_verified'); }); + +const restoreEnv = (k, v) => (v !== undefined ? process.env[k] = v : delete process.env[k]); + +test('24. Production UPI Fail-Closed: Development fallback cannot be used in production, placeholders return null, and legal name is not fabricated', async () => { + const origVercelEnv = process.env.VERCEL_ENV; + const origUpi = process.env.NIGHTLIFEZ_FINANCE_UPI_ID; + const origName = process.env.NIGHTLIFEZ_FINANCE_NAME; + + try { + // 1. Simulate production environment with no configured UPI ID + process.env.VERCEL_ENV = 'production'; + delete process.env.NIGHTLIFEZ_FINANCE_UPI_ID; + delete process.env.NIGHTLIFEZ_FINANCE_NAME; + + assert.equal(getPlatformFinanceUpi(), null, 'Production must return null if NIGHTLIFEZ_FINANCE_UPI_ID is unset'); + assert.equal(getPlatformFinanceName(), null, 'Production must not fabricate legal entity name if unset'); + + // 2. Setting fallback VPA in production must fail closed to null + process.env.NIGHTLIFEZ_FINANCE_UPI_ID = 'nightlifez.finance@icici'; + assert.equal(getPlatformFinanceUpi(), null, 'Fallback VPA must fail closed to null in production'); + + // 3. Setting test/dummy/placeholder VPA in production must fail closed to null + process.env.NIGHTLIFEZ_FINANCE_UPI_ID = 'test@okhdfcbank'; + assert.equal(getPlatformFinanceUpi(), null, 'Test VPA must fail closed to null in production'); + + process.env.NIGHTLIFEZ_FINANCE_UPI_ID = 'placeholder@icici'; + assert.equal(getPlatformFinanceUpi(), null, 'Placeholder VPA must fail closed to null in production'); + + // 4. Setting valid production VPA and entity name succeeds + process.env.NIGHTLIFEZ_FINANCE_UPI_ID = 'nightlifez.live@icici'; + process.env.NIGHTLIFEZ_FINANCE_NAME = 'NIGHTLIFEZ Experiences Private Limited'; + assert.equal(getPlatformFinanceUpi(), 'nightlifez.live@icici'); + assert.equal(getPlatformFinanceName(), 'NIGHTLIFEZ Experiences Private Limited'); + + // 5. In non-production (dev/test), fallbacks work as expected + delete process.env.VERCEL_ENV; + delete process.env.NIGHTLIFEZ_FINANCE_UPI_ID; + delete process.env.NIGHTLIFEZ_FINANCE_NAME; + assert.equal(getPlatformFinanceUpi(), 'nightlifez.finance@icici'); + assert.equal(getPlatformFinanceName(), 'NIGHTLIFEZ Experiences Private Limited'); + } finally { + restoreEnv('VERCEL_ENV', origVercelEnv); + restoreEnv('NIGHTLIFEZ_FINANCE_UPI_ID', origUpi); + restoreEnv('NIGHTLIFEZ_FINANCE_NAME', origName); + } +}); + +test('25. Organiser payment claim submission is blocked with 503 when platform UPI is unconfigured in production', async () => { + const origVercelEnv = process.env.VERCEL_ENV; + const origUpi = process.env.NIGHTLIFEZ_FINANCE_UPI_ID; + const origName = process.env.NIGHTLIFEZ_FINANCE_NAME; + + try { + process.env.VERCEL_ENV = 'production'; + delete process.env.NIGHTLIFEZ_FINANCE_UPI_ID; + delete process.env.NIGHTLIFEZ_FINANCE_NAME; + + // Summary reflects unconfigured VPA, unconfigured name, and empty instructions + const summary = await getOrganiserFinanceSummary(organiserAClient.user.id); + assert.equal(summary.platformUpi.vpa, null); + assert.equal(summary.platformUpi.name, null); + assert.deepEqual(summary.platformUpi.instructions, []); + + // Submission fails closed with 503 + const invA = (await db.query(`SELECT * FROM organiser_fee_invoices WHERE organiser_id = $1 LIMIT 1`, [organiserAClient.user.id])).rows[0]; + await assert.rejects( + async () => { + await submitFeePayment({ + organiserId: organiserAClient.user.id, + invoiceId: invA.id, + amountPaise: 5000, + utrNumber: `PROD-FAIL-CLOSED-${Date.now()}` + }); + }, + (err) => { + assert.equal(err.status, 503); + assert.equal(err.code, 'platform_upi_not_configured'); + return true; + } + ); + } finally { + restoreEnv('VERCEL_ENV', origVercelEnv); + restoreEnv('NIGHTLIFEZ_FINANCE_UPI_ID', origUpi); + restoreEnv('NIGHTLIFEZ_FINANCE_NAME', origName); + } +}); + +test('26. Attendee checkout payee destination is immutable from server event data and cannot be overridden by attendee input', async () => { + const evRow = (await db.query(`SELECT * FROM events WHERE organiser_user_id IS NOT NULL AND status = 'published' LIMIT 1`)).rows[0]; + const tierRow = (await db.query(`SELECT * FROM ticket_types WHERE event_id = $1 AND kind = 'paid' LIMIT 1`, [evRow.id])).rows[0]; + + const buyer = (await db.query( + `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, phone) + VALUES ($1, $2, true, $3) RETURNING *`, + [Math.floor(100000 + Math.random() * 900000), 'buyer_sec_audit', `+919${Math.floor(100000000 + Math.random() * 900000000)}`] + )).rows[0]; + + // Try to pass an attendee-controlled payee UPI ID or price in intent creation + const intent = await createUpiPaymentIntent({ + slug: evRow.slug, + ticketTypeId: tierRow.id, + quantity: 1, + deviceType: 'mobile', + user: buyer, + // Attacker attempts injection + paise: 100, + amountPaise: 100, + price: 1, + payeeUpi: 'attacker@upi', + organiserUpiId: 'attacker@upi' + }); + + // Intent amount must be the server-calculated price (ticket base + 5% platform fee) + const expectedFee = Math.round(tierRow.price_paise * 0.05); + const expectedTotal = tierRow.price_paise + expectedFee; + assert.equal(intent.amountPaise, expectedTotal, 'Attendee cannot override server-calculated amount'); + assert.ok(intent.orderId); +});