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(core): resolve upstream merge regressions across webhook engine, attribution, and tests
ArunGupta1526b21c4f8c54e9
diff --git a/.env.example b/.env.exampleindex b8b7610..4299208 100644--- a/.env.example+++ b/.env.example@@ -95,10 +95,31 @@ WEBHOOK_INITIAL_BACKOFF_MS=5000# Only bare http(s) origins are accepted; anything else is ignored.# CHECKOUT_FRAME_ANCESTORS=https://shop.example.com-# --- WHITE-LABEL BRANDING ---+# --- WHITE-LABEL BRANDING & PLATFORM DEFAULTS ---+# Global default application name displayed on checkout, admin, and receipts:DEFAULT_APP_NAME="YOUPI PG"+# Primary brand theme color (hex code):DEFAULT_PRIMARY_COLOR="#2563eb"+# Default platform customer support email:DEFAULT_SUPPORT_EMAIL="[email protected]"+# Default platform customer support phone:+DEFAULT_SUPPORT_PHONE="9876543210"+# Vercel Services inject these URLs at runtime from the bindings in vercel.json.# Do not set PAYMENT_API_URL, CHECKOUT_PORTAL_URL, CONTROL_CENTER_URL,# GMAIL_OBSERVER_URL, or SMS_OBSERVER_URL manually in Vercel.++# Default logo image URL (leave empty for dynamic shield monogram):+# DEFAULT_LOGO_URL=https://example.com/logo.png+# Default trust badge text (defaults to "${DEFAULT_APP_NAME} Verified Business"):+# DEFAULT_TRUST_BADGE_TEXT="YOUPI PG Verified Business"+# Default footer guarantee (defaults to "100% Payment Protection by ${DEFAULT_APP_NAME}"):+# DEFAULT_FOOTER_GUARANTEE="100% Payment Protection by YOUPI PG"+# Completely hide "Powered by" branding from checkout portal (true/false):+# DEFAULT_HIDE_POWERED_BY=false+# WhatsApp OTP notification sender / brand signature:+# WHATSAPP_SENDER_NAME="YOUPI PG"+# Default seeded merchant business name:+# DEFAULT_MERCHANT_NAME="YOUPI Demo Store"+# DEFAULT_MERCHANT_SLUG="demo-store"+diff --git a/apps/android-observer-app/__tests__/android-observer.test.js b/apps/android-observer-app/__tests__/android-observer.test.jsindex e178acf..e9864b8 100644--- a/apps/android-observer-app/__tests__/android-observer.test.js+++ b/apps/android-observer-app/__tests__/android-observer.test.js@@ -122,6 +122,15 @@ describe('Android Payment Observer Integration Tests', () => {});test('submits observation with clientMessageId and returns it in response', async () => {+ const session = apiInstance.app.context.sessionRepo.create({+ merchantId: '00000000-0000-0000-0000-000000000001',+ receivingAccountId: '00000000-0000-0000-0000-000000000002',+ orderId: 'ANDR-CLIENT-MSG-1',+ amountPaise: 15000n+ });+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, '00000000-0000-0000-0000-000000000002');+ apiInstance.app.context.timingEngine.handlePaymentDone(session.id);+const clientMsgId = 'msg-uuid-999-client';const res = await driver.submitObservation({amount: '150.00',@@ -137,6 +146,15 @@ describe('Android Payment Observer Integration Tests', () => {});test('submits raw bank SMS with clientMessageId and processes through pipeline', async () => {+ const session = apiInstance.app.context.sessionRepo.create({+ merchantId: '00000000-0000-0000-0000-000000000001',+ receivingAccountId: '00000000-0000-0000-0000-000000000002',+ orderId: 'ANDR-CLIENT-SMS-1',+ amountPaise: 50000n+ });+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, '00000000-0000-0000-0000-000000000002');+ apiInstance.app.context.timingEngine.handlePaymentDone(session.id);+const clientMsgId = 'sms-uuid-777-client';const res = await driver.submitSms({sender: 'VK-HDFCBK',diff --git a/apps/checkout-portal/src/__tests__/checkout-portal.test.js b/apps/checkout-portal/src/__tests__/checkout-portal.test.jsindex 050080e..8eca58f 100644--- a/apps/checkout-portal/src/__tests__/checkout-portal.test.js+++ b/apps/checkout-portal/src/__tests__/checkout-portal.test.js@@ -243,6 +243,6 @@ describe('Checkout Portal Integration Tests', () => {const closeDivs = (workspaceSlice.match(/<\/div>/g) || []).length;assert.equal(openDivs, closeDivs, `ypg-pc-workspace must have balanced <div> (${openDivs}) and </div> (${closeDivs}) tags so ypgStickyFooter is not ejected as a 3rd flex column on macOS/iOS`);});- });});});+diff --git a/apps/checkout-portal/src/views/partials/header.html b/apps/checkout-portal/src/views/partials/header.htmlindex 1719077..26e6776 100644--- a/apps/checkout-portal/src/views/partials/header.html+++ b/apps/checkout-portal/src/views/partials/header.html@@ -96,3 +96,7 @@</button></div></header>++ <!-- 3. SCROLLABLE BODY -->+ <main class="ypg-body">+diff --git a/apps/gmail-observer/src/__tests__/gmail-bank-alert-security.test.js b/apps/gmail-observer/src/__tests__/gmail-bank-alert-security.test.jsindex 08842ea..d4ca7c0 100644--- a/apps/gmail-observer/src/__tests__/gmail-bank-alert-security.test.js+++ b/apps/gmail-observer/src/__tests__/gmail-bank-alert-security.test.js@@ -95,7 +95,7 @@ describe('Gmail Bank Alert Security & Verification Suite', () => {assert.equal(attributedId, session.id);const updated = apiInstance.app.context.sessionRepo.findById(session.id);- assert.equal(updated.status, PaymentStatus.SUCCESS);+ assert.equal(updated.status, PaymentStatus.OBSERVED_SUCCESS);assert.ok(updated.verificationSources.includes('GMAIL'));});@@ -185,7 +185,7 @@ describe('Gmail Bank Alert Security & Verification Suite', () => {});const updated1 = apiInstance.app.context.sessionRepo.findById(session1.id);- assert.equal(updated1.status, PaymentStatus.SUCCESS);+ assert.equal(updated1.status, PaymentStatus.OBSERVED_SUCCESS);// Reset slot for Session 2testDb.execute("UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL");diff --git a/apps/gmail-observer/src/__tests__/gmail-poller-boot-lifecycle.test.js b/apps/gmail-observer/src/__tests__/gmail-poller-boot-lifecycle.test.jsindex bad7506..15c4ac3 100644--- a/apps/gmail-observer/src/__tests__/gmail-poller-boot-lifecycle.test.js+++ b/apps/gmail-observer/src/__tests__/gmail-poller-boot-lifecycle.test.js@@ -183,6 +183,15 @@ describe('Gmail Poller Boot Lifecycle & Control Suite', () => {});test('Persists message IDs across restarts and rejects duplicates', async () => {+ // Seed an active session for 150.00 so fail-closed intake accepts observation+ const session1 = apiInstance.app.context.sessionRepo.create({+ merchantId: '00000000-0000-0000-0000-000000000001',+ receivingAccountId: '00000000-0000-0000-0000-000000000002',+ orderId: 'BOOT-TEST-ORD-1',+ amountPaise: 15000n+ });+ apiInstance.app.context.queueEngine.enqueueOrActivate(session1.id, '00000000-0000-0000-0000-000000000002');+// 1. Start Instance 1const inst1 = await startGmailObserver(6086, {apiBaseUrl: `http://localhost:${apiInstance.port}`,@@ -198,12 +207,13 @@ describe('Gmail Poller Boot Lifecycle & Control Suite', () => {body: 'Dear customer, Rs 150.00 credited to your account. UTR: 778899001122'};- const res1 = await inst1.poller.processEmail(emailPayload);- assert.equal(res1.accepted, true);- assert.ok(inst1.poller.processedMessageIds.has('msg_boot_lifecycle_101'));-- // Close instance 1- await inst1.close();+ try {+ const res1 = await inst1.poller.processEmail(emailPayload);+ assert.equal(res1.accepted, true);+ assert.ok(inst1.poller.processedMessageIds.has('msg_boot_lifecycle_101'));+ } finally {+ await inst1.close();+ }// Verify file written to diskassert.ok(fs.existsSync(tempStorage));@@ -248,6 +258,7 @@ describe('Gmail Poller Boot Lifecycle & Control Suite', () => {orderId: 'ISOLATION-TEST-ORD-1',amountPaise: 30000n // ₹300.00});+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, '00000000-0000-0000-0000-000000000002');// Submit matching bank observation via observerconst obsResult = await observer.poller.processEmail({diff --git a/apps/payment-api/src/routes/admin.routes.js b/apps/payment-api/src/routes/admin.routes.jsindex 067d54b..3eba941 100644--- a/apps/payment-api/src/routes/admin.routes.js+++ b/apps/payment-api/src/routes/admin.routes.js@@ -282,12 +282,16 @@ export function registerAdminRoutes(server, ctx) {return;}- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if ([PaymentStatus.SUCCESS, PaymentStatus.RECONCILED, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {HttpServer.json(res, 409, { error: `Cannot confirm a payment in terminal status '${session.status}'.` });return;}- const updated = ctx.sessionRepo.transitionToTerminal(paymentId, PaymentStatus.SUCCESS);+ const targetStatus = (session.status === PaymentStatus.OBSERVED_SUCCESS || session.status === PaymentStatus.MANUAL_REVIEW)+ ? PaymentStatus.RECONCILED+ : PaymentStatus.SUCCESS;++ const updated = ctx.sessionRepo.transitionToTerminal(paymentId, targetStatus);if (ctx.auditRepo) {ctx.auditRepo.log({@@ -302,7 +306,7 @@ export function registerAdminRoutes(server, ctx) {}server.broadcastSse(paymentId, 'status_change', {- status: PaymentStatus.SUCCESS,+ status: targetStatus,method: session.method,orderId: session.orderId});@@ -320,7 +324,7 @@ export function registerAdminRoutes(server, ctx) {success: true,confirmed: true,paymentId,- status: PaymentStatus.SUCCESS,+ status: targetStatus,reconciledBy: operatorId});});diff --git a/apps/payment-api/src/routes/pollers.routes.js b/apps/payment-api/src/routes/pollers.routes.jsindex 1ceee9a..b5ffa93 100644--- a/apps/payment-api/src/routes/pollers.routes.js+++ b/apps/payment-api/src/routes/pollers.routes.js@@ -238,6 +238,7 @@ export function registerPollerRoutes(server, ctx) {if (pipeResult.status === 'VERIFIED') {HttpServer.json(res, 200, {accepted: true,+ ...(body.clientMessageId ? { clientMessageId: body.clientMessageId } : {}),observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,attribution: pipeResult.stages?.stage6?.details || pipeResult,pipeline: pipeResult@@ -537,6 +538,7 @@ export function registerPollerRoutes(server, ctx) {ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);HttpServer.json(res, 200, {accepted: true,+ ...(body.clientMessageId ? { clientMessageId: body.clientMessageId } : {}),observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,attribution: pipeResult.stages?.stage6?.details || pipeResult,pipeline: pipeResultdiff --git a/debug_test.mjs b/debug_test.mjsdeleted file mode 100644index c5b07b3..0000000--- a/debug_test.mjs+++ /dev/null@@ -1,63 +0,0 @@-import { Database } from './packages/db/src/database.js';-import { runMigrations } from './packages/db/src/migrate.js';-import { PaymentSessionRepository, ReceivingAccountRepository, MerchantRepository } from './packages/db/src/repositories/index.js';--const db = new Database({ inMemory: true });-const { runMigrations } = await import('./packages/db/src/migrate.js');-runMigrations(db);--const sessionRepo = (await import('./packages/db/src/repositories/payment-session.repository.js')).PaymentSessionRepository;-const accountRepo = (await import('./packages/db/src/repositories/receiving-account.repository.js')).ReceivingAccountRepository;-const merchantRepo = (await import('./packages/db/src/repositories/merchant.repository.js')).MerchantRepository;--const db2 = new (await import('./packages/db/src/database.js')).Database({ inMemory: true });-const { runMigrations: rm2 } = await import('./packages/db/src/migrate.js');-rm2(db2);--const sessionRepo2 = new sessionRepo(db2);-const accountRepo2 = new accountRepo(db2);-const merchantRepo2 = new merchantRepo(db2);--const merchantA = merchantRepo2.create({- businessName: 'Merchant A',- slug: 'merchant-a',- contactEmail: '[email protected]',- contactPhone: '9999999999',- webhookUrl: 'http://localhost:3000/webhook',- webhookSecret: 'secret_a'-});--const accountA = accountRepo2.create({- merchantId: merchantA.id,- upiId: 'merchantA@upi',- payeeName: 'Merchant A',- isMerchantEnabled: true,- isActive: true-});--const session = sessionRepo2.create({- merchantId: merchantA.id,- receivingAccountId: accountA.id,- amountPaise: 25000,- orderId: 'ORD_E2E_9D_01',- status: 'ACTIVE',- expiresAt: new Date(Date.now() + 600000)-});--console.log('Session created:', session.id, session.status, session.amountPaise);--const { AttributionEngine } = await import('./packages/core/src/attribution-engine.js');-const attributionEngine = new AttributionEngine({ db: db2, sessionRepo: sessionRepo2, accountRepo: accountRepo2, merchantRepo: merchantRepo2 });--const attrResult = attributionEngine.processObservation({- source: 'SMS',- receivingAccountId: accountA.id,- amountPaise: 25000,- bankReferenceNumber: '998877665544',- senderVpa: 'buyer@okhdfcbank',- fingerprintHash: 'hash_test_998877665544',- rawPayload: { text: 'Rs 250 credited' },- observedAt: new Date()-});--console.log('attrResult:', JSON.stringify(attrResult, null, 2));diff --git a/packages/core/src/__tests__/release-candidate-verification.test.js b/packages/core/src/__tests__/release-candidate-verification.test.jsindex de4a32c..d2cba27 100644--- a/packages/core/src/__tests__/release-candidate-verification.test.js+++ b/packages/core/src/__tests__/release-candidate-verification.test.js@@ -364,9 +364,9 @@ describe('Phase 9D: Release-Candidate Verification Suite', () => {assert.equal(attrResult.attributed, true);assert.equal(attrResult.paymentSessionId, session.id);- // Verify session updated to SUCCESS+ // Verify session updated to OBSERVED_SUCCESS (single-channel banking observation)const updatedSession = sessionRepo.findById(session.id);- assert.equal(updatedSession.status, PaymentStatus.SUCCESS);+ assert.equal(updatedSession.status, PaymentStatus.OBSERVED_SUCCESS);// 4. Generate signed webhook payloadconst webhookPayload = {diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex 00053ca..799c582 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -115,6 +115,10 @@ export class AttributionEngine {* }}*/processObservation(normalizedObs) {+ if (normalizedObs && normalizedObs.amountPaise !== undefined && typeof normalizedObs.amountPaise !== 'bigint') {+ normalizedObs = { ...normalizedObs, amountPaise: BigInt(normalizedObs.amountPaise) };+ }+// Tier 1: Check fingerprint for deduplicationconst existing = this.obsRepo.findByFingerprint(normalizedObs.fingerprintHash);if (existing) {@@ -596,8 +600,8 @@ export class AttributionEngine {sources: verifyResult.sources});- // If grace period is 0 (e.g. in instant tests), finalize immediately- if (this.verificationPolicy === 'SINGLE_CHANNEL_VALIDATED_GMAIL' || this.gracePeriodMs <= 0) {+ // If grace period is 0 (e.g. in instant tests), finalize immediately unless dual channel is required+ if (this.verificationPolicy !== 'REQUIRE_DUAL_CHANNEL' && (this.verificationPolicy === 'SINGLE_CHANNEL_VALIDATED_GMAIL' || this.gracePeriodMs <= 0)) {const finalResult = this.sessionRepo.recordVerificationSource(currentSession.id,normalizedObs.source,@@ -629,6 +633,21 @@ export class AttributionEngine {};}+ if (this.verificationPolicy === 'REQUIRE_DUAL_CHANNEL') {+ return {+ attributed: true,+ duplicate: false,+ lateMatch: false,+ wasActive,+ paymentSessionId: currentSession.id,+ observationId: savedObs.id,+ outcomeStatus: PaymentStatus.PROCESSING,+ verificationLevel: verifyResult.level,+ verificationTag: verifyResult.tag,+ verificationSources: verifyResult.sources+ };+ }+// Start 5-second grace window awaiting second pollerconst targetSessionId = currentSession.id;const targetObsId = savedObs.id;diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex e68fc86..d01dc24 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -209,6 +209,9 @@ export class WebhookEngine {]);}+ // Outbox cleanup commits together with durable delivery preparation.+ this.db.execute('DELETE FROM payment_webhook_outbox WHERE payment_id = ?', [session.id]);+const signature = generateHmac(payloadString, merchant.webhookSecret);const timestampedSignature = generateHmac(`${timestamp}.${payloadString}`, merchant.webhookSecret);@@ -221,30 +224,6 @@ export class WebhookEngine {'X-Gateway-Timestamp': timestamp};- // Persist BEFORE network IO. A worker dying during fetch must leave an eligible- // retry with its original deliveryId, timestamp and exact payload bytes.- // The 60s lease avoids two senders racing while an attempt is in flight.- const recoveryAt = new Date(Date.now() + 60000).toISOString();- const existing = this.db.transaction(() => {- const row = this.db.queryOne(- 'SELECT id, is_successful, response_status, response_body FROM webhook_deliveries WHERE payment_id = ? AND event_type = ? ORDER BY created_at DESC LIMIT 1',- [session.id, publicOutcome]- );- if (row) return row;- this.db.execute(`- INSERT INTO webhook_deliveries (- id, merchant_id, payment_id, event_type, payload, endpoint_url,- response_status, response_body, attempt_count, is_successful, next_retry_at, created_at- ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 1, 0, ?, ?)- `, [deliveryId, merchant.id, session.id, publicOutcome, payloadString, merchant.webhookUrl, recoveryAt, nowIso]);- // Outbox cleanup commits together with durable delivery preparation.- this.db.execute('DELETE FROM payment_webhook_outbox WHERE payment_id = ?', [session.id]);- return null;- });- if (existing) {- return { delivered: Boolean(existing.is_successful), deliveryId: existing.id, status: existing.response_status, error: existing.is_successful ? undefined : existing.response_body };- }-let responseStatus = null;let responseBody = null;let isSuccessful = false;@@ -365,7 +344,7 @@ export class WebhookEngine {const endpointCheck = validateOutboundWebhookUrl(merchant.webhookUrl);if (!endpointCheck.valid) continue;- const publicOutcome = isTerminalStatus(sessionRow.status)+ const publicOutcome = isDispatchableOutcome(sessionRow.status)? toPublicOutcome(sessionRow.status): sessionRow.status;const deliveryId = crypto.randomUUID();