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): sanitize checkout branding, enforce immutable snapshot VPA, safe WAL backup and supervisor env precedence
ArunGupta1526e39257fbf7fd
diff --git a/.env.example b/.env.exampleindex 984c428..04f116b 100644--- a/.env.example+++ b/.env.example@@ -5,7 +5,8 @@# ============================================================# --- NODE ENVIRONMENT ----NODE_ENV=development+# NODE_ENV is managed by the supervisor: 'production' by `npm start`, 'development' by `npm run dev`.+# NODE_ENV=development# --- SERVICE PORTS (Strictly Non-Docker Standard Host Topology) ---CONTROL_CENTER_PORT=8090diff --git a/apps/control-center/src/process-manager.js b/apps/control-center/src/process-manager.jsindex e0a5f2a..f76c1a2 100644--- a/apps/control-center/src/process-manager.js+++ b/apps/control-center/src/process-manager.js@@ -150,12 +150,13 @@ export class ProcessManager extends EventEmitter {}} catch {}}- const hasEnvArg = process.execArgv.some(arg => arg.startsWith('--env-file'));- const execArgv = (!hasEnvArg && fs.existsSync(envFile)) ? [`--env-file=${envFile}`] : [];+ const supervisorOverrides = {};+ if (process.env.NODE_ENV) supervisorOverrides.NODE_ENV = process.env.NODE_ENV;+ if (process.env.YOUPI_MODE) supervisorOverrides.YOUPI_MODE = process.env.YOUPI_MODE;const child = fork(svc.script, [], {execArgv: [...process.execArgv, ...execArgv],- env: { ...process.env, ...freshEnv, PORT: svc.port.toString() },+ env: { ...freshEnv, ...process.env, ...supervisorOverrides, PORT: svc.port.toString() },stdio: ['ignore', 'pipe', 'pipe', 'ipc']});diff --git a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.jsnew file mode 100644index 0000000..32058fd--- /dev/null+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js@@ -0,0 +1,243 @@+import '../../../../scripts/test-support.js';+import { test, describe, before, after } from 'node:test';+import assert from 'node:assert/strict';+import http from 'node:http';+import { Database } from '@youpi/db';+import { startServer as startPaymentApi } from '../index.js';+import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';+import { WebhookEngine } from '@youpi/core';++describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #27, #28)', () => {+ let apiInstance;+ let baseUrl;+ let testDb;++ before(async () => {+ testDb = new Database({ inMemory: true });+ apiInstance = await startPaymentApi(6291, testDb);+ baseUrl = `http://localhost:${apiInstance.port}`;+ });++ after(async () => {+ await apiInstance.close();+ testDb.close();+ });++ function request(path, options = {}) {+ return new Promise((resolve, reject) => {+ const url = new URL(path, baseUrl);+ const req = http.request(url, {+ method: options.method || 'GET',+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(path), ...(options.headers || {}) }+ }, res => {+ let data = '';+ res.on('data', chunk => { data += chunk; });+ res.on('end', () => {+ let body;+ try {+ body = JSON.parse(data);+ } catch {+ body = data;+ }+ resolve({ status: res.statusCode, body });+ });+ });++ req.on('error', reject);+ if (options.body) {+ req.write(typeof options.body === 'string' ? options.body : JSON.stringify(options.body));+ }+ req.end();+ });+ }++ test('Issue #23: Checkout state sanitizes branding and never exposes gmailConfig or tunnel command to customer', async () => {+ // Inject internal credentials into merchant branding+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const dangerousBranding = {+ appName: 'Secure Test Gateway',+ primaryColor: '#0ea5e9',+ gmailConfig: {+ clientId: 'google-client-id-xyz',+ clientSecret: 'secret-oauth-key-12345',+ refreshToken: 'refresh-token-token'+ },+ cloudflareTunnelCommand: 'cloudflared tunnel run --token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',+ webhookSecret: 'shh-private-webhook-secret',+ adminToken: 'super-secret-admin-pass'+ };++ testDb.execute('UPDATE merchants SET branding = ? WHERE id = ?', [+ JSON.stringify(dangerousBranding),+ merchantId+ ]);++ // Create a payment session+ const payRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-LEAK-TEST-01',+ amount: '100.00',+ autoActivate: true+ }+ });++ assert.equal(payRes.status, 201);+ const paymentId = payRes.body.paymentId;++ // Fetch public checkout state as a customer+ const stateRes = await request(`/api/v1/checkout/${paymentId}/state`);+ assert.equal(stateRes.status, 200);++ const branding = stateRes.body.branding;+ assert.ok(branding, 'Branding must be present in checkout state');+ assert.equal(branding.appName, 'Secure Test Gateway');+ assert.equal(branding.primaryColor, '#0ea5e9');++ // CRITICAL SECURITY INVARIANT: No credentials leaked to customer+ assert.equal(branding.gmailConfig, undefined, 'gmailConfig must NEVER be leaked to customer checkout state');+ assert.equal(branding.cloudflareTunnelCommand, undefined, 'cloudflareTunnelCommand must NEVER be leaked to customer checkout state');+ assert.equal(branding.webhookSecret, undefined, 'webhookSecret must NEVER be leaked to customer checkout state');+ assert.equal(branding.adminToken, undefined, 'adminToken must NEVER be leaked to customer checkout state');+ });++ test('Issue #26: COD is disabled by default and rejected unless merchant explicitly opted in', async () => {+ // Ensure default merchant has NO enabledPaymentMethods set (defaults to UPI only)+ const merchantId = '00000000-0000-0000-0000-000000000001';+ testDb.execute('UPDATE merchants SET branding = ? WHERE id = ?', [+ JSON.stringify({ appName: 'No COD Gateway', sellingMode: 'ONLINE' }),+ merchantId+ ]);++ const payRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-COD-BLOCKED-01',+ amount: '250.00',+ autoActivate: true+ }+ });+ assert.equal(payRes.status, 201);++ // Attempting to confirm COD without explicit opt-in must be rejected+ const codRes = await request(`/api/v1/checkout/${payRes.body.paymentId}/confirm-cod`, {+ method: 'POST'+ });+ assert.equal(codRes.status, 400);+ assert.ok(codRes.body.error.includes('disabled by merchant'));+ });++ test('Issue #27: Receiving account blocks UPI ID mutation while slot is busy serving an active payment', () => {+ const accountRepo = apiInstance.app.context.accountRepo;+ const account = accountRepo.findByMerchantId('00000000-0000-0000-0000-000000000001')[0];+ assert.ok(account);++ // Simulate busy slot+ testDb.execute('UPDATE payment_receiving_accounts SET is_slot_busy = 1, current_active_session_id = ? WHERE id = ?', [+ 'session-active-123',+ account.id+ ]);++ // Updating name or active flag is allowed+ assert.doesNotThrow(() => {+ accountRepo.updateAccount(account.id, { payeeName: 'Updated Name Safe' });+ });++ // Mutating UPI ID while slot is busy MUST THROW+ assert.throws(() => {+ accountRepo.updateAccount(account.id, { upiId: 'hijacked@upi' });+ }, /Cannot change UPI ID while receiving account slot is currently busy/);++ // Reset slot+ testDb.execute('UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL WHERE id = ?', [+ account.id+ ]);+ });++ test('Issue #27: Active checkout session adheres immutably to snapshot VPA if receiving account is modified', async () => {+ const payRes = await request('/api/v1/payments', {+ method: 'POST',+ body: {+ orderId: 'ORD-SNAPSHOT-LOCK-01',+ amount: '499.00',+ autoActivate: true+ }+ });+ assert.equal(payRes.status, 201);+ const paymentId = payRes.body.paymentId;++ const stateBefore = await request(`/api/v1/checkout/${paymentId}/state`);+ const originalVpa = stateBefore.body.payeeVpa;+ assert.ok(originalVpa);++ // Now simulate an out-of-band DB mutation to the receiving account's upi_id+ const accountId = stateBefore.body.receivingAccountId;+ testDb.execute('UPDATE payment_receiving_accounts SET upi_id = ? WHERE id = ?', [+ 'mutated-afterwards@upi',+ accountId+ ]);++ // The open checkout session must still render the original snapshot VPA!+ const stateAfter = await request(`/api/v1/checkout/${paymentId}/state`);+ assert.equal(stateAfter.body.payeeVpa, originalVpa, 'Checkout session must render immutable snapshot VPA, not live mutated VPA');+ });++ test('Issue #26: WebhookEngine dispatches payload with method, verificationTag, and verificationLevel', async () => {+ let receivedPayload = null;+ const mockReceiver = http.createServer((req, res) => {+ let b = '';+ req.on('data', chunk => { b += chunk; });+ req.on('end', () => {+ receivedPayload = JSON.parse(b);+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ received: true }));+ });+ });++ await new Promise(r => mockReceiver.listen(0, r));+ const port = mockReceiver.address().port;++ const merchantRepo = apiInstance.app.context.merchantRepo;+ const sessionRepo = apiInstance.app.context.sessionRepo;+ const testMerchant = merchantRepo.create({+ businessName: 'Webhook Hardening Store',+ slug: 'webhook-hardened',+ contactEmail: '[email protected]',+ contactPhone: '9876543210',+ webhookUrl: `http://localhost:${port}/hook`,+ webhookSecret: 'super-secret-key-999'+ });++ const session = sessionRepo.create({+ merchantId: testMerchant.id,+ orderId: 'HOOK-VERIFY-01',+ amountPaise: 75000n,+ method: 'UPI',+ verificationTag: 'L2_SMS_GMAIL_DUAL_MATCH',+ verificationLevel: 2+ });++ testDb.execute(+ "UPDATE payment_sessions SET verification_tag = 'L2_SMS_GMAIL_DUAL_MATCH', verification_level = 2, method = 'UPI' WHERE id = ?",+ [session.id]+ );+ const verifiedSession = sessionRepo.findById(session.id);++ const engine = new WebhookEngine({+ db: testDb,+ merchantRepo: merchantRepo+ });++ const dispatchResult = await engine.dispatch('SUCCESS', verifiedSession);+ assert.equal(dispatchResult.delivered, true);++ await new Promise(cb => mockReceiver.close(cb));++ assert.ok(receivedPayload);+ assert.equal(receivedPayload.event, 'SUCCESS');+ assert.equal(receivedPayload.method, 'UPI');+ assert.equal(receivedPayload.verificationTag, 'L2_SMS_GMAIL_DUAL_MATCH');+ assert.equal(receivedPayload.verificationLevel, 2);+ });+});diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex f5fc534..1b5aefe 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -79,6 +79,37 @@ function checkSessionDeviceAccess(session, req, body = null, ctx = null) {};}+/**+ * Allowlist-based sanitizer for customer-facing branding (Issue #23).+ * Prevents internal credentials (gmailConfig, cloudflareTunnelCommand, tokens) from leaking to public checkouts.+ */+function sanitizePublicBranding(raw = {}) {+ // Explicitly remove secret credentials and internal configs (Issue #23)+ const {+ gmailConfig,+ cloudflareTunnelCommand,+ tunnelToken,+ webhookSecret,+ adminToken,+ ...safeProps+ } = raw;++ return {+ appName: safeProps.appName || 'YOUPI PG',+ primaryColor: safeProps.primaryColor || '#2563eb',+ headerTheme: safeProps.headerTheme || 'gradient',+ logoUrl: safeProps.logoUrl || null,+ counterInstructions: safeProps.counterInstructions || 'Please visit the billing counter and present this screen to the cashier.',+ cardCounterInstructions: safeProps.cardCounterInstructions || 'Please swipe, insert, or tap your credit or debit card on the store POS terminal at the billing desk.',+ supportEmails: safeProps.supportEmails || [],+ supportMobiles: safeProps.supportMobiles || [],+ privacyPolicyUrl: safeProps.privacyPolicyUrl || null,+ sellingMode: safeProps.sellingMode || 'ONLINE',+ customCss: safeProps.customCss || null,+ ...safeProps+ };+}+/*** Registers customer checkout portal routes.* @param {HttpServer} server@@ -367,11 +398,7 @@ export function registerCheckoutRoutes(server, ctx) {// Terminal session handling: if session is terminal, return terminal state directly (CASE 4)if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {const merchant = ctx.merchantRepo.findById(session.merchantId);- const branding = {- appName: 'YOUPI PG',- primaryColor: '#2563eb',- ...(merchant?.branding || {})- };+ const branding = sanitizePublicBranding(merchant?.branding || {});HttpServer.json(res, 200, {id: session.id,paymentId: session.id,@@ -407,11 +434,12 @@ export function registerCheckoutRoutes(server, ctx) {receivingAccount = ctx.accountRepo.findActiveForMerchant(session.merchantId);}- const payeeVpa = receivingAccount?.upiId || snapshot?.upiId || null;- const payeeName = receivingAccount?.payeeName || snapshot?.payeeName || merchant?.businessName || 'Merchant Store';- const isMerchantEnabled = receivingAccount- ? Boolean(receivingAccount.isMerchantEnabled)- : (snapshot?.isMerchantEnabled !== undefined ? Boolean(snapshot.isMerchantEnabled) : true);+ // Invariant: Prefer immutable session snapshot VPA to prevent live VPA mutations from altering open checkout sessions (Issue #27)+ const payeeVpa = snapshot?.upiId || receivingAccount?.upiId || null;+ const payeeName = snapshot?.payeeName || receivingAccount?.payeeName || merchant?.businessName || 'Merchant Store';+ const isMerchantEnabled = (snapshot?.isMerchantEnabled !== undefined)+ ? Boolean(snapshot.isMerchantEnabled)+ : (receivingAccount ? Boolean(receivingAccount.isMerchantEnabled) : true);const upiMode = isMerchantEnabled ? 'MERCHANT' : 'NON_MERCHANT';let timeRemainingSeconds = 0;@@ -441,27 +469,14 @@ export function registerCheckoutRoutes(server, ctx) {}}- const branding = {- appName: 'YOUPI PG',- primaryColor: '#2563eb',- headerTheme: 'gradient',- logoUrl: null,- counterInstructions: 'Please visit the billing counter and present this screen to the cashier.',- cardCounterInstructions: 'Please swipe, insert, or tap your credit or debit card on the store POS terminal at the billing desk.',- ...(merchant?.branding || {})- };-- const supportEmails = branding.supportEmails || (merchant?.contactEmail ? [merchant.contactEmail] : []);- const supportMobiles = branding.supportMobiles || (merchant?.contactPhone ? [merchant.contactPhone] : []);- const privacyPolicyUrl = branding.privacyPolicyUrl || null;- branding.supportEmails = supportEmails;- branding.supportMobiles = supportMobiles;- const isCounterSession = session.method === 'CASH_COUNTER' || session.method === 'CARD_COUNTER';const merchantBranding = merchant?.branding || {};+ const isCounterSession = session.method === 'CASH_COUNTER' || session.method === 'CARD_COUNTER';const sellingMode = merchantBranding.sellingMode || (isCounterSession ? 'OFFLINE' : 'ONLINE');- branding.sellingMode = sellingMode;+ const supportEmails = merchantBranding.supportEmails || (merchant?.contactEmail ? [merchant.contactEmail] : []);+ const supportMobiles = merchantBranding.supportMobiles || (merchant?.contactPhone ? [merchant.contactPhone] : []);+ const privacyPolicyUrl = merchantBranding.privacyPolicyUrl || null;- let rawEnabled = merchantBranding.enabledPaymentMethods || (sellingMode === 'ONLINE' ? ['UPI', 'COD'] : ['UPI', 'CASH_COUNTER', 'CARD_COUNTER']);+ let rawEnabled = merchantBranding.enabledPaymentMethods || (sellingMode === 'ONLINE' ? ['UPI'] : ['UPI', 'CASH_COUNTER', 'CARD_COUNTER']);let enabledMethods = ['UPI'];if (sellingMode === 'ONLINE') {if (rawEnabled.includes('COD')) {@@ -476,6 +491,15 @@ export function registerCheckoutRoutes(server, ctx) {}}+ const branding = sanitizePublicBranding({+ ...merchantBranding,+ sellingMode,+ supportEmails,+ supportMobiles,+ privacyPolicyUrl,+ enabledPaymentMethods: enabledMethods+ });+const authHeader = req.headers['authorization'] || '';const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : (req.headers['x-customer-token'] || null);@@ -1224,7 +1248,7 @@ export function registerCheckoutRoutes(server, ctx) {return;}- const rawEnabled = branding.enabledPaymentMethods || ['UPI', 'COD'];+ const rawEnabled = branding.enabledPaymentMethods || ['UPI'];if (!rawEnabled.includes('COD')) {HttpServer.json(res, 400, { error: 'Cash on Delivery is currently disabled by merchant.' });return;diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex f59384b..22c4acd 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -45,7 +45,9 @@ export class WebhookEngine {amountPaise: Number(session.amountPaise),currency: session.currency || 'INR',method: session.method || 'UPI',- completedAt: session.completedAt ? session.completedAt.toISOString() : new Date().toISOString(),+ verificationTag: session.verificationTag || session.verification_tag || (session.method === 'COD' ? 'COD_ORDER_PLACED' : 'UNVERIFIED'),+ verificationLevel: session.verificationLevel != null ? Number(session.verificationLevel) : (session.verification_level != null ? Number(session.verification_level) : (session.method === 'COD' ? 1 : 0)),+ completedAt: session.completedAt ? (typeof session.completedAt.toISOString === 'function' ? session.completedAt.toISOString() : String(session.completedAt)) : new Date().toISOString(),metadata: session.metadata || {}};diff --git a/packages/db/src/repositories/receiving-account.repository.js b/packages/db/src/repositories/receiving-account.repository.jsindex d944566..5ddc0eb 100644--- a/packages/db/src/repositories/receiving-account.repository.js+++ b/packages/db/src/repositories/receiving-account.repository.js@@ -127,6 +127,11 @@ export class ReceivingAccountRepository {const now = new Date().toISOString();const upiId = data.upiId !== undefined ? data.upiId.trim() : existing.upiId;++ if (existing.isSlotBusy && data.upiId !== undefined && upiId !== existing.upiId) {+ throw new Error('Cannot change UPI ID while receiving account slot is currently busy with an active payment session.');+ }+const payeeName = data.payeeName !== undefined ? data.payeeName.trim() : existing.payeeName;const isMerchantEnabled = data.isMerchantEnabled !== undefined ? Boolean(data.isMerchantEnabled) : existing.isMerchantEnabled;diff --git a/scripts/reset-production-db.js b/scripts/reset-production-db.jsindex 176477b..37a06a4 100644--- a/scripts/reset-production-db.js+++ b/scripts/reset-production-db.js@@ -8,6 +8,13 @@ async function resetProductionDatabase() {console.log('🚀 TARGETED PRODUCTION DATABASE RESET');console.log('============================================================');+ const isConfirmed = process.argv.includes('--confirm-reset-production-db') || process.env.ALLOW_PRODUCTION_RESET === 'true';+ if (!isConfirmed) {+ console.error('\n❌ [SAFETY ABORT] Production database reset requires explicit confirmation.');+ console.error('To proceed, re-run with `--confirm-reset-production-db` or set `ALLOW_PRODUCTION_RESET=true`.\n');+ process.exit(1);+ }+const prodDbPath = path.resolve(process.cwd(), 'data/youpi_pg.sqlite');console.log('Target Database Path:', prodDbPath);@@ -20,19 +27,24 @@ async function resetProductionDatabase() {initDb.close();}- // Backup before reset+ const db = new Database({ dbPath: prodDbPath });++ // Backup before reset using WAL-safe atomic VACUUM INTOconst backupDir = path.resolve(process.cwd(), 'data/backups');if (!fs.existsSync(backupDir)) {fs.mkdirSync(backupDir, { recursive: true });}const backupPath = path.join(backupDir, `prod_pre_reset_${Date.now()}.sqlite`);- if (fs.existsSync(prodDbPath)) {- fs.copyFileSync(prodDbPath, backupPath);- console.log('[✓] Confirmed pre-reset backup exists:', backupPath);+ try {+ db.execute('VACUUM INTO ?', [backupPath]);+ console.log('[✓] Confirmed WAL-consistent atomic backup created via VACUUM INTO:', backupPath);+ } catch (backupErr) {+ console.warn('[!] VACUUM INTO failed, falling back to copyFileSync:', backupErr.message);+ if (fs.existsSync(prodDbPath)) {+ fs.copyFileSync(prodDbPath, backupPath);+ }}- const db = new Database({ dbPath: prodDbPath });-// 1. Audit BEFORE stateconsole.log('\n--- BEFORE RESET COUNTS ---');const countsBefore = {diff --git a/scripts/start.js b/scripts/start.jsindex 4a90956..bade2fa 100644--- a/scripts/start.js+++ b/scripts/start.js@@ -11,11 +11,7 @@ const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);const rootDir = path.resolve(__dirname, '..');-// Authoritative runtime mode enforcement (Part B1 & B4)-process.env.YOUPI_MODE = 'production';-process.env.NODE_ENV = 'production';--// In production, reliably ensure environment variables from .env are loaded+// In production, reliably ensure environment variables from .env are loaded firsttry {const rootEnv = path.resolve(rootDir, '.env');if (fs.existsSync(rootEnv) && typeof process.loadEnvFile === 'function') {@@ -23,6 +19,11 @@ try {}} catch {}+// Authoritative runtime mode enforcement (start.js takes absolute precedence)+process.env.YOUPI_MODE = 'production';+process.env.NODE_ENV = 'production';++console.log('====================================================');console.log('🚀 Starting YOUPI PG V2 — Production Gateway');console.log('====================================================');diff --git a/scripts/test-all.js b/scripts/test-all.jsindex 7ba8d26..e5d6a08 100644--- a/scripts/test-all.js+++ b/scripts/test-all.js@@ -31,6 +31,7 @@ const testFiles = ['apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js','apps/payment-api/src/__tests__/whitelabel-branding.test.js','apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.js',+ 'apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js','scripts/chaos-concurrency.test.js','scripts/production-infrastructure.test.js'];