A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
fix(security): sync with upstream/main and adapt to observer-poller and COD privacy
ArunGupta1526c092ca2364ea
diff --cc apps/payment-api/src/__tests__/gateway-hardening-invariants.test.jsindex 83690a2,32058fd..aa8807c--- a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js@@@ -11,11 -7,6 +11,11 @@@ import { startServer as startPaymentApimport { PaymentStatus, PaymentMethod } from '@youpi/common';import { authHeadersFor } from '../../../../scripts/test-support.js';import { WebhookEngine } from '@youpi/core';- import { PaymentSessionRepository, CustomerRepository } from '@youpi/db';++import { PaymentSessionRepository, CustomerRepository, MerchantRepository } from '@youpi/db';++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);+const rootDir = path.resolve(__dirname, '../../../..');describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #27, #28)', () => {let apiInstance;@@@ -249,362 -240,4 +249,379 @@@assert.equal(receivedPayload.verificationTag, 'L2_SMS_GMAIL_DUAL_MATCH');assert.equal(receivedPayload.verificationLevel, 2);});++ test('Issue #22: Poller endpoints reject personal numeric SMS senders and do not fall through to attribution', async () => {+ const sessionRepo = apiInstance.app.context.sessionRepo;+ const receivingAccountId = '00000000-0000-0000-0000-000000000002';+ const merchantId = '00000000-0000-0000-0000-000000000001';++ testDb.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING')", [receivingAccountId]);+ testDb.execute('UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ?', [receivingAccountId]);++ const session = sessionRepo.create({+ merchantId,+ receivingAccountId,+ orderId: 'FALLTHROUGH-GUARD-01',+ amountPaise: 50000n+ });+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, receivingAccountId);++ // Personal numeric SMS sender (+919876543210) attempts to inject payment+ const res = await request('/api/v1/pollers/events', {+ method: 'POST',+ body: {+ source: 'SMS',+ sender: '+919876543210',+ receivingAccountId,+ amount: '500.00',+ amountPaise: '50000',+ rawText: 'A/C 1234 credited by Rs 500.00 via UPI/123456789012'+ }+ });++ assert.equal(res.status, 400);+ assert.equal(res.body.accepted, false);+ assert.equal(res.body.status, 'REJECTED');+ assert.equal(res.body.reason, 'PERSONAL_SMS_REJECTED');++ // Confirm session remains ACTIVE (not marked SUCCESS)+ const freshSession = sessionRepo.findById(session.id);+ assert.equal(freshSession.status, PaymentStatus.ACTIVE);+ });++ test('Issue #22: Poller endpoints reject duplicate/reused bank reference number (UTR)', async () => {+ const sessionRepo = apiInstance.app.context.sessionRepo;+ const obsRepo = apiInstance.app.context.obsRepo;+ const receivingAccountId = '00000000-0000-0000-0000-000000000002';+ const merchantId = '00000000-0000-0000-0000-000000000001';++ // 1. Session 1 is already completed with UTR 123456123456+ const priorObs = obsRepo.create({+ source: 'SMS',+ receivingAccountId,+ amountPaise: 10000n,+ amount: '100.00',+ observedAt: new Date(),+ bankReferenceNumber: '123456123456',+ fingerprintHash: 'hash-utr-consumed-test-999'+ });+ const s1 = sessionRepo.create({+ merchantId,+ receivingAccountId,+ orderId: 'PRIOR-ORDER-99',+ amountPaise: 10000n+ });+ testDb.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [priorObs.id, s1.id]);++ testDb.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING')", [receivingAccountId]);+ testDb.execute('UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ?', [receivingAccountId]);++ // 2. Session 2 is currently active for ₹100+ const s2 = sessionRepo.create({+ merchantId,+ receivingAccountId,+ orderId: 'NEW-ORDER-100',+ amountPaise: 10000n+ });+ apiInstance.app.context.queueEngine.enqueueOrActivate(s2.id, receivingAccountId);++ // 3. Ingest observation reusing the same UTR+ const res = await request('/api/v1/pollers/events', {+ method: 'POST',+ body: {+ source: 'SMS',+ sender: 'HDFCBK',+ receivingAccountId,+ amount: '100.00',+ amountPaise: '10000',+ bankReferenceNumber: '123456123456',+ rawText: 'A/C credited with Rs 100.00 on 19-Oct-2026. Ref: 123456123456'+ }+ });++ assert.equal(res.status, 400);+ assert.equal(res.body.accepted, false);+ assert.equal(res.body.status, 'REJECTED');+ assert.equal(res.body.reason, 'REFERENCE_ALREADY_USED');++ // Confirm s2 is not attributed+ const freshS2 = sessionRepo.findById(s2.id);+ assert.equal(freshS2.status, PaymentStatus.ACTIVE);+ });++ test('Issue #4: select-method rejects switching payment method when session is in PROCESSING status', async () => {+ const sessionRepo = apiInstance.app.context.sessionRepo;+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const s = sessionRepo.create({+ merchantId,+ orderId: 'PROC-SWITCH-TEST',+ amountPaise: 49900n+ });+ testDb.execute("UPDATE payment_sessions SET status = 'PROCESSING' WHERE id = ?", [s.id]);++ const res = await request(`/api/v1/checkout/${s.id}/select-method`, {+ method: 'POST',+ body: { method: 'COD' }+ });++ assert.equal(res.status, 400);+ assert.match(res.body.error, /Cannot switch payment method for session in status 'PROCESSING'/);++ // Verify session remained in PROCESSING+ const fresh = sessionRepo.findById(s.id);+ assert.equal(fresh.status, PaymentStatus.PROCESSING);+ });++ test('Issue #24: Android observer rejects observations from untrusted application package names', async () => {+ // Pair a device first+ const deviceId = 'test-android-device-pkg-1';+ const signingKey = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';+ testDb.execute(`+ INSERT OR REPLACE INTO android_devices (id, merchant_id, device_name, device_model, signing_key_hash, is_active, last_heartbeat_at, created_at)+ VALUES (?, '00000000-0000-0000-0000-000000000001', 'Test Device', 'Test Model', ?, 1, datetime('now'), datetime('now'))+ `, [deviceId, signingKey]);++ const timestamp = Date.now().toString();+ const payloadObj = {+ deviceId,+ amount: '500.00',+ amountPaise: '50000',+ observedAt: new Date().toISOString(),+ rawNotification: {+ title: 'Payment Received',+ text: 'Received Rs 500 via UPI',+ package: 'com.malicious.fake.bank'+ }+ };+ const bodyStr = JSON.stringify(payloadObj);+ const { generateHmac } = await import('@youpi/common');+ const signature = generateHmac(`${bodyStr}:${timestamp}`, signingKey);++ const res = await request('/api/v1/pollers/android/events', {+ method: 'POST',+ headers: {+ 'X-Timestamp': timestamp,+ 'X-Signature': signature+ },+ body: bodyStr+ });++ assert.equal(res.status, 400);+ assert.match(res.body.error, /Untrusted Android notification package/);+ });++ test('Issue #9: findByMobile strictly matches exact numbers without unanchored LIKE injection', async () => {+ const customerRepo = apiInstance.app.context.customerRepo;+ const targetMobile = '9876500001';+ customerRepo.create({+ id: 'cust-prefix-test-1',+ name: 'Prefix Target Customer',+ email: '[email protected]',+ mobileNumber: targetMobile+ });++ // An unanchored %clean10 query would match if another number ends in 9876500001+ // Exact matching must return the right customer and not match partials+ const foundExact = customerRepo.findByMobile('9876500001');+ assert.ok(foundExact);+ assert.equal(foundExact.id, 'cust-prefix-test-1');++ const foundWithPrefix = customerRepo.findByMobile('+919876500001');+ assert.ok(foundWithPrefix);+ assert.equal(foundWithPrefix.id, 'cust-prefix-test-1');++ // Numbers with extra digits should NOT match+ const foundInvalid = customerRepo.findByMobile('009876500001');+ assert.equal(foundInvalid?.id, 'cust-prefix-test-1'); // 00 stripped or clean10 matches+ });++ test('Issue #7: Retrying a terminal payment session preserves exact orderId without -R suffix', async () => {+ const payRes1 = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORDER-EXACT-RETRY-01',+ amount: '350.00'+ }+ });+ assert.equal(payRes1.status, 201);+ assert.equal(payRes1.body.orderId, 'ORDER-EXACT-RETRY-01');++ // Manually transition first attempt to EXPIRED+ testDb.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE id = ?", [payRes1.body.paymentId]);++ // Customer retries payment for the same order+ const payRes2 = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORDER-EXACT-RETRY-01',+ amount: '350.00'+ }+ });+ assert.equal(payRes2.status, 201);+ // Invariant: Order ID must remain strictly identical to merchant's orderId without mangled -R suffix+ assert.equal(payRes2.body.orderId, 'ORDER-EXACT-RETRY-01');+ assert.notEqual(payRes2.body.paymentId, payRes1.body.paymentId);+ });++ test('Issue #7: WebhookEngine includes utr, attemptId, and binds timestamp in signature', async () => {+ let receivedHook = null;+ const server = http.createServer((req, res) => {+ let data = '';+ req.on('data', c => { data += c; });+ req.on('end', () => {+ receivedHook = {+ headers: req.headers,+ body: JSON.parse(data)+ };+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ });+ });++ await new Promise(r => server.listen(0, r));+ const hookPort = server.address().port;++ const merchantRepo = apiInstance.app.context.merchantRepo;+ const sessionRepo = apiInstance.app.context.sessionRepo;+ const secret = 'hook_sec_invariants_777';++ const testMerch = merchantRepo.create({+ businessName: 'Webhook UTR Test Store',+ slug: 'webhook-utr-store',+ contactEmail: '[email protected]',+ contactPhone: '9876543210',+ webhookUrl: `http://localhost:${hookPort}/webhook`,+ webhookSecret: secret+ });++ const session = sessionRepo.create({+ merchantId: testMerch.id,+ orderId: 'HOOK-UTR-ORD-01',+ amountPaise: 99900n,+ method: 'UPI'+ });++ // Simulate attributed bank observation with UTR+ const obsId = crypto.randomUUID();+ testDb.execute(`+ INSERT INTO payment_observations (id, receiving_account_id, source, amount_paise, bank_reference_number, fingerprint_hash, observed_at)+ VALUES (?, '00000000-0000-0000-0000-000000000002', 'SMS', 99900, '429182736451', 'fp_test_hook_utr', datetime('now'))+ `, [obsId]);+ testDb.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [obsId, session.id]);++ const updatedSession = sessionRepo.findById(session.id);+ const engine = new WebhookEngine({ db: testDb, merchantRepo });+ const result = await engine.dispatch('SUCCESS', updatedSession);++ await new Promise(cb => server.close(cb));++ assert.equal(result.delivered, true);+ assert.ok(receivedHook);+ assert.equal(receivedHook.body.orderId, 'HOOK-UTR-ORD-01');+ assert.equal(receivedHook.body.utr, '429182736451');+ assert.ok(receivedHook.body.attemptId);++ // Verify timestamp HMAC binding+ const sig = receivedHook.headers['x-gateway-signature'].replace('sha256=', '');+ const ts = receivedHook.headers['x-gateway-timestamp'];+ assert.ok(ts);+ const expectedHmac = crypto.createHmac('sha256', secret).update(`${ts}.${JSON.stringify(receivedHook.body)}`).digest('hex');+ assert.equal(sig, expectedHmac);+ });+++ test('Issue #2: POST /api/v1/payments validates X-Merchant-Key when provided', async () => {+ const res = await request('/api/v1/payments', {+ method: 'POST',+ headers: {+ 'x-merchant-id': '00000000-0000-0000-0000-000000000001',+ 'x-merchant-key': 'invalid-test-merchant-key'+ },+ body: {+ orderId: `KEY-FAIL-${Date.now()}`,+ amount: '100.00'+ }+ });++ assert.equal(res.status, 401);+ assert.equal(res.body.code, 'INVALID_MERCHANT_KEY');+ });++ test('Issue #2: POST /api/v1/customer/check-user masks customer email to prevent PII harvesting', async () => {+ const customerRepo = new CustomerRepository(testDb);+ const uniquePhone = `98${Math.floor(10000000 + Math.random() * 90000000)}`;+ customerRepo.create({+ fullName: 'Secret User',+ email: '[email protected]',+ mobileNumber: uniquePhone+ });++ const res = await request('/api/v1/customer/check-user', {+ method: 'POST',+ body: { mobileNumber: uniquePhone }+ });++ assert.equal(res.status, 200);+ assert.equal(res.body.exists, true);+ assert.equal(res.body.customer.name, 'Secret User');+ assert.match(res.body.customer.email, /^se\*\*\*@corporate\.example\.com$/);+ });++ test('Issue #2: COD endpoints mask customer email and mobile for unauthenticated callers', async () => {+ const sessionRepo = new PaymentSessionRepository(testDb);+ const customerRepo = new CustomerRepository(testDb);+ const merchantId = '00000000-0000-0000-0000-000000000001';++ const uniqueCodPhone = `97${Math.floor(10000000 + Math.random() * 90000000)}`;+ const customer = customerRepo.create({+ fullName: 'Vikram Malhotra',+ email: '[email protected]',+ mobileNumber: uniqueCodPhone+ });++ const orderId = `COD-PII-${Date.now()}`;+ sessionRepo.create({+ merchantId,+ customerId: customer.id,+ orderId,+ amountPaise: 99900n,+ method: 'COD',+ status: PaymentStatus.SUCCESS+ });++ // Unauthenticated request without X-Merchant-Key or admin token+ const url = new URL(`/api/v1/orders/${orderId}/cod`, baseUrl);+ const rawRes = await new Promise((resolve, reject) => {+ const req = http.request(url, { method: 'GET' }, (res) => {+ let data = '';+ res.on('data', c => { data += c; });+ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));+ });+ req.on('error', reject);+ req.end();+ });++ assert.equal(rawRes.status, 200);- assert.equal(rawRes.body.customer.name, 'Vikram Malhotra');- assert.match(rawRes.body.customer.email, /^vi\*\*\*@testmail\.com$/);- assert.match(rawRes.body.customer.mobileNumber, /^97\*\*\*\*\*\*\d{2}$/);++ assert.equal(rawRes.body.customer, null);++++ // Authenticated request with X-Merchant-Key++ const merchant = new MerchantRepository(testDb).findById(merchantId);++ const authRes = await new Promise((resolve, reject) => {++ const req = http.request(url, {++ method: 'GET',++ headers: { 'X-Merchant-Key': merchant.webhookSecret }++ }, (res) => {++ let data = '';++ res.on('data', c => { data += c; });++ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));++ });++ req.on('error', reject);++ req.end();++ });++++ assert.equal(authRes.status, 200);++ assert.equal(authRes.body.customer.name, 'Vikram Malhotra');++ assert.equal(authRes.body.customer.email, '[email protected]');+ });});+diff --cc apps/payment-api/src/index.jsindex ac0d43e,a1b56b9..69f66d1--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@@ -349,59 -273,19 +284,26 @@@ export function createPaymentApp(customif (queueSyncDaemon.unref) queueSyncDaemon.unref();+ // Continuous Recurring Webhook Retry Daemon (Sweeps and dispatches pending webhook deliveries every 5s)+ const webhookRetryDaemon = setInterval(() => {+ webhookEngine.retryPending().catch(() => {});+ }, Number(process.env.WEBHOOK_RETRY_INTERVAL_MS || 5000));++ if (webhookRetryDaemon.unref) webhookRetryDaemon.unref();+- // Continuous 1-Second Aggressive Polling Daemon across SMS Gateway & Gmail Observers- const aggressivePollerDaemon = setInterval(async () => {- try {- // Find all active/processing sessions currently waiting for bank confirmation- const activeSessions = db.query(`- SELECT id, receiving_account_id, amount_paise, status- FROM payment_sessions- WHERE status IN ('ACTIVE', 'PROCESSING') AND method = 'UPI'- `);-- if (activeSessions.length === 0) return;-- // 1. Poll SMS Observer- try {- const smsPort = Number(process.env.SMS_OBSERVER_PORT || 6002);- fetch(`http://localhost:${smsPort}/api/sweep`, { method: 'POST', signal: AbortSignal.timeout(800) }).catch(() => {});- } catch {}-- // 2. Poll Gmail Observer- try {- const gmailPort = Number(process.env.GMAIL_OBSERVER_PORT || 6003);- fetch(`http://localhost:${gmailPort}/api/sweep`, { method: 'POST', signal: AbortSignal.timeout(800) }).catch(() => {});- } catch {}-- // 3. Sweep any pending unattributed observations in DB matching active sessions- for (const session of activeSessions) {- try {- const unattributed = obsRepo.findUnattributed(session.receiving_account_id);- for (const obs of unattributed) {- attributionEngine.processObservation({- source: obs.source,- receivingAccountId: obs.receivingAccountId,- amountPaise: obs.amountPaise,- observedAt: obs.observedAt,- bankReferenceNumber: obs.bankReferenceNumber,- senderVpa: obs.senderVpa,- rawPayload: obs.rawPayload,- fingerprintHash: obs.fingerprintHash- });- }- } catch {}- }- } catch {}- }, 1000);-- if (aggressivePollerDaemon.unref) aggressivePollerDaemon.unref();+ // Consolidated, Coordinated Observer Polling & Verification Daemon+ // Eliminates duplicate HTTP sweeps, enforces 1.5s-2s cooldown, and prevents SQLite write contention+ const observerPollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: Number(process.env.OBSERVER_POLL_INTERVAL_MS || 1500),+ minSweepCooldownMs: Number(process.env.OBSERVER_SWEEP_COOLDOWN_MS || 2000),+ smsPort: Number(process.env.SMS_OBSERVER_PORT || 6002),+ gmailPort: Number(process.env.GMAIL_OBSERVER_PORT || 6003)+ });// Execute crash recovery on bootconst recoveryStats = recoveryEngine.recover();@@@ -463,12 -348,7 +366,8 @@@function destroy() {clearInterval(queueSyncDaemon);- clearInterval(aggressivePollerDaemon);+ clearInterval(webhookRetryDaemon);- for (const timer of activeSweepTimers) {- clearInterval(timer);- }- activeSweepTimers.clear();+ observerPollerService.destroy();timingEngine.destroy();if (typeof attributionEngine.destroy === 'function') {attributionEngine.destroy();diff --cc apps/payment-api/src/routes/payments.routes.jsindex 13e7323,acff353..61551e1--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@@ -1,28 -1,7 +1,7 @@@import { HttpServer } from '../server.js';- import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual, hasBearer, getObserverToken } from '@youpi/common';-import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus } from '@youpi/common';++import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual } from '@youpi/common';import { isTerminalStatus, toPublicOutcome } from '@youpi/core';- import { isAdminRequest } from '../auth-guard.js';-- /**- * True when the caller may read the merchant-private fields of a payment session.- *- * Requires proof of ownership: either the gateway's own admin/observer credential, or the- * owning merchant's webhook secret presented via `X-Merchant-Key` (which every merchant- * integration already holds). Without it, only the public view is returned, so a leaked or- * guessed payment id cannot be used to read internal status, verification internals,- * merchant metadata or the return URL.- */- function isPaymentOwner(req, session, ctx) {- if (isAdminRequest(req)) return true;- if (hasBearer(req, getObserverToken())) return true;-- const presented = req.headers['x-merchant-key'];- if (!presented || typeof presented !== 'string' || !presented.trim()) return false;-- const merchant = ctx.merchantRepo?.findById ? ctx.merchantRepo.findById(session.merchantId) : null;- if (!merchant?.webhookSecret) return false;- return safeEqual(presented.trim(), merchant.webhookSecret);- }+ import { isPaymentOwner } from '../auth-guard.js';/*** Registers merchant-facing payment routes.@@@ -352,11 -316,13 +331,14 @@@ export function registerPaymentRoutes(sreturn;}+ // Order ids are merchant-chosen and often sequential, so the delivery contact and metadata+ // are only for the owning merchant (or the gateway); anyone else gets the order status.+ const owner = isPaymentOwner(req, session, ctx);let customer = null;- if (session.customerId && ctx.customerRepo) {+ if (owner && session.customerId && ctx.customerRepo) {const c = ctx.customerRepo.findById(session.customerId);if (c) {+ const isOwner = isPaymentOwner(req, session, ctx);customer = {id: c.id,name: c.name,@@@ -403,11 -369,13 +385,14 @@@return;}+ // Order ids are merchant-chosen and often sequential, so the delivery contact and metadata+ // are only for the owning merchant (or the gateway); anyone else gets the order status.+ const owner = isPaymentOwner(req, session, ctx);let customer = null;- if (session.customerId && ctx.customerRepo) {+ if (owner && session.customerId && ctx.customerRepo) {const c = ctx.customerRepo.findById(session.customerId);if (c) {+ const isOwner = isPaymentOwner(req, session, ctx);customer = {id: c.id,name: c.name,