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(attribution): resolve UTR conflicts, processing window expiry, and observation indexes (#5, #12)
ArunGupta1526bd80322a5152
diff --git a/apps/payment-api/src/__tests__/verification-fallthrough.test.js b/apps/payment-api/src/__tests__/verification-fallthrough.test.jsindex abac9cf..5cee65a 100644--- a/apps/payment-api/src/__tests__/verification-fallthrough.test.js+++ b/apps/payment-api/src/__tests__/verification-fallthrough.test.js@@ -2,7 +2,9 @@ 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 crypto from 'node:crypto';+import { Database, PaymentSessionRepository, ObservationRepository, SupportTicketRepository, AuditLogRepository, ReceivingAccountRepository, CustomerRepository } from '@youpi/db';+import { ObservationNormalizer, PaymentVerificationPipeline, AttributionEngine, RecoveryEngine, QueueEngine, TimingEngine } from '@youpi/core';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus } from '@youpi/common';import { authHeadersFor } from '../../../../scripts/test-support.js';@@ -148,4 +150,246 @@ describe('Verification Pipeline & Fall-Through Protection (#22)', () => {const freshS2 = sessionRepo.findById(s2.id);assert.equal(freshS2.status, PaymentStatus.ACTIVE);});++ test('Issue #5: ObservationNormalizer extracts reference numbers across varied Indian banking formats', () => {+ const receivingAccountId = '00000000-0000-0000-0000-000000000002';+ const testCases = [+ { text: 'A/c *1234 credited by Rs. 500.00 on 19-Oct-26 Ref no 612345678901', expectedRef: '612345678901' },+ { text: 'Rs. 250.00 received in your account. Ref no. 987654321098. UPI Txn', expectedRef: '987654321098' },+ { text: 'Dear Customer, INR 1,000.00 credited via UPI:612398745612 to A/C *5678', expectedRef: '612398745612' },+ { text: 'Money received: INR 75.00 from user@okaxis UPI Ref: 123456789012', expectedRef: '123456789012' }+ ];++ for (const tc of testCases) {+ const normalized = ObservationNormalizer.normalize({+ source: 'ANDROID_OBSERVER',+ receivingAccountId,+ rawPayload: { text: tc.text }+ });+ assert.equal(normalized.bankReferenceNumber, tc.expectedRef, `Failed for text: ${tc.text}`);+ }+ });++ test('Issue #5: findRecentlyExpiredOrFailed includes CANCELLED sessions to prevent payment hijacking', () => {+ const sessionRepo = new PaymentSessionRepository(testDb);+ const accountRepo = new ReceivingAccountRepository(testDb);+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const recAcc = accountRepo.create({+ merchantId,+ upiId: `cancel-${crypto.randomUUID().slice(0, 8)}@okaxis`,+ payeeName: 'Test Holder',+ provider: 'AXIS_BANK'+ });++ const cancelledSession = sessionRepo.create({+ merchantId,+ receivingAccountId: recAcc.id,+ orderId: `CANCEL-TEST-${Date.now()}`,+ amountPaise: 45000n,+ customerDetails: { phone: '9876543210' },+ method: 'UPI'+ });++ sessionRepo.transitionToTerminal(cancelledSession.id, PaymentStatus.CANCELLED);++ const thirtyMinutesAgo = new Date(Date.now() - 30 * 60 * 1000);+ const recent = sessionRepo.findRecentlyExpiredOrFailed(recAcc.id, thirtyMinutesAgo);++ const found = recent.find(s => s.id === cancelledSession.id);+ assert.ok(found, 'CANCELLED session must be returned by findRecentlyExpiredOrFailed');+ assert.equal(found.status, PaymentStatus.CANCELLED);+ });++ test('Issue #5: Duplicate UTR conflict within 60s raises support ticket and does not overwrite completed session', () => {+ const sessionRepo = new PaymentSessionRepository(testDb);+ const accountRepo = new ReceivingAccountRepository(testDb);+ const obsRepo = new ObservationRepository(testDb);+ const ticketRepo = new SupportTicketRepository(testDb);+ const auditRepo = new AuditLogRepository(testDb);+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const recAcc = accountRepo.create({+ merchantId,+ upiId: `dup-${crypto.randomUUID().slice(0, 8)}@okaxis`,+ payeeName: 'Dup Utr Test',+ provider: 'AXIS_BANK'+ });++ const customerRepo = new CustomerRepository(testDb);+ const customer = customerRepo.create({ fullName: 'Dup Customer', mobileNumber: '9876543210' });++ // 1. Create a session and transition INITIATED -> ACTIVE+ const session = sessionRepo.create({+ merchantId,+ customerId: customer.id,+ receivingAccountId: recAcc.id,+ orderId: `DUP-UTR-ORDER-${Date.now()}`,+ amountPaise: 65000n,+ customerDetails: { phone: '9876543210' },+ method: 'UPI'+ });+ sessionRepo.acquireSlotAtomic(session.id, recAcc.id, 300000);++ const obs1 = obsRepo.create({+ receivingAccountId: recAcc.id,+ source: 'ANDROID_OBSERVER',+ amountPaise: 65000n,+ bankReferenceNumber: '111111111111',+ fingerprintHash: `fp_first_success_utr_${Date.now()}`,+ observedAt: new Date()+ });++ sessionRepo.recordVerificationSource(session.id, 'ANDROID_OBSERVER', obs1.id, { finalizeSuccess: true });++ // 2. Attribution engine with ticketRepo+ let duplicateEventFired = false;+ const attribution = new AttributionEngine({+ sessionRepo,+ obsRepo,+ ticketRepo,+ auditRepo,+ gracePeriodMs: 0,+ eventEmitter: {+ emit: (event) => {+ if (event === 'PAYMENT.DUPLICATE_DETECTED') duplicateEventFired = true;+ }+ }+ });++ // 3. Second incoming observation for the same amount but different UTR (222222222222)+ const normObs2 = {+ source: 'ANDROID_OBSERVER',+ receivingAccountId: recAcc.id,+ amountPaise: 65000n,+ observedAt: new Date(),+ bankReferenceNumber: '222222222222',+ fingerprintHash: `fp_second_conflict_utr_${Date.now()}`,+ rawPayload: { sender: 'HDFCBK', text: 'Rs. 650.00 credited Ref no 222222222222' }+ };++ const result = attribution.processObservation(normObs2);++ assert.equal(result.attributed, false);+ assert.ok(duplicateEventFired, 'PAYMENT.DUPLICATE_DETECTED event must fire');++ // Verify support ticket was created+ const tickets = testDb.query('SELECT * FROM support_tickets WHERE payment_id = ?', [session.id]);+ assert.ok(tickets.length >= 1, 'Reconciliation support ticket must be raised for duplicate payment');+ assert.match(tickets[0].subject, /DUPLICATE PAYMENT DETECTED/);+ });++ test('Issue #12: VerificationPipeline honors processingExpiresAt during PROCESSING status', () => {+ const sessionRepo = new PaymentSessionRepository(testDb);+ const accountRepo = new ReceivingAccountRepository(testDb);+ const obsRepo = new ObservationRepository(testDb);+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const recAcc = accountRepo.create({+ merchantId,+ upiId: `proc-${crypto.randomUUID().slice(0, 8)}@okaxis`,+ payeeName: 'Proc Test',+ provider: 'AXIS_BANK'+ });++ // Session whose initial 5-min active timer expired, but processing timer has 3 minutes remaining+ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: recAcc.id,+ orderId: `PROC-TIMER-${Date.now()}`,+ amountPaise: 50000n,+ customerDetails: { phone: '9876543210' },+ method: 'UPI'+ });++ sessionRepo.acquireSlotAtomic(session.id, recAcc.id, 300000);+ sessionRepo.transitionToProcessing(session.id);++ const pastExpiresAt = new Date(Date.now() - 60000).toISOString();+ const futureProcExpiresAt = new Date(Date.now() + 180000).toISOString();++ testDb.execute(`+ UPDATE payment_sessions+ SET expires_at = ?, processing_expires_at = ?+ WHERE id = ?+ `, [pastExpiresAt, futureProcExpiresAt, session.id]);++ const pipeline = new PaymentVerificationPipeline({+ db: testDb,+ sessionRepo,+ obsRepo,+ attributionEngine: new AttributionEngine({ sessionRepo, obsRepo, gracePeriodMs: 0 })+ });++ const result = pipeline.process({+ source: 'SMS_GATEWAY',+ receivingAccountId: recAcc.id,+ paymentSessionId: session.id,+ sender: 'HDFCBK',+ rawText: 'Rs 500.00 credited to account ending 1234 on 19-Oct-26. UTR 918273645102.',+ receivedAt: new Date()+ });++ assert.notEqual(result.finalStatus, 'REJECTED', 'Observation must not be rejected as SESSION_EXPIRED while processingExpiresAt is active');+ assert.notEqual(result.failingCondition, 'SESSION_EXPIRED');+ });++ test('Issue #12: Crash recovery promotes attributed PROCESSING sessions to SUCCESS instead of FAILED', () => {+ const sessionRepo = new PaymentSessionRepository(testDb);+ const accountRepo = new ReceivingAccountRepository(testDb);+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const recAcc = accountRepo.create({+ merchantId,+ upiId: `rec-${crypto.randomUUID().slice(0, 8)}@okaxis`,+ payeeName: 'Recovery Test',+ provider: 'AXIS_BANK'+ });++ const session = sessionRepo.create({+ merchantId,+ receivingAccountId: recAcc.id,+ orderId: `RECOVER-ATTRIB-${Date.now()}`,+ amountPaise: 35000n,+ customerDetails: { phone: '9876543210' },+ method: 'UPI'+ });++ sessionRepo.acquireSlotAtomic(session.id, recAcc.id, 300000);+ sessionRepo.transitionToProcessing(session.id);++ 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 (?, ?, 'ANDROID_OBSERVER', 35000, '555666777888', ?, datetime('now'))+ `, [obsId, recAcc.id, `fp_recover_attrib_${Date.now()}`]);++ // Set session in PROCESSING status with overdue processing_expires_at but already attributed+ const overdueTime = new Date(Date.now() - 10000).toISOString();+ testDb.execute(`+ UPDATE payment_sessions+ SET processing_expires_at = ?, verification_level = 1, attributed_observation_id = ?+ WHERE id = ?+ `, [overdueTime, obsId, session.id]);++ const timingEngine = new TimingEngine({ db: testDb, sessionRepo, accountRepo });+ const queueEngine = new QueueEngine({ db: testDb, sessionRepo, accountRepo, timingEngine });+ let successFired = false;++ const recovery = new RecoveryEngine({+ db: testDb,+ sessionRepo,+ accountRepo,+ queueEngine,+ timingEngine,+ eventEmitter: {+ emit: (event) => {+ if (event === 'PAYMENT.SUCCESS') successFired = true;+ }+ }+ });++ const stats = recovery.recover();+ const updated = sessionRepo.findById(session.id);++ assert.equal(updated.status, PaymentStatus.SUCCESS, 'Attributed PROCESSING session must recover to SUCCESS');+ assert.ok(successFired, 'PAYMENT.SUCCESS event must fire on recovery of attributed session');+ });});+diff --git a/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js b/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.jsindex 751e567..b8b9d0a 100644--- a/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js+++ b/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js@@ -1,12 +1,15 @@import test from 'node:test';import assert from 'node:assert/strict';++process.env.NODE_ENV = process.env.NODE_ENV || 'test';+import { createPaymentApp } from '../index.js';import { Database } from '@youpi/db';import { authFetch } from '../../../../scripts/test-support.js';test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite', async (t) => {const customDb = new Database({ inMemory: true });- const app = createPaymentApp(customDb);+ const app = createPaymentApp(customDb, { otpCooldownMs: 0 });const testPort = 6288;const serverInstance = await new Promise(resolve => {diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex e2bddac..867ff00 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -432,7 +432,8 @@ export function createPaymentApp(customDb = null, options = {}) {defaultMerchant,checkoutBaseUrl,whatsappBerryService,- webhookEngine+ webhookEngine,+ otpCooldownMs: options.otpCooldownMs};registerPaymentRoutes(server, context);diff --git a/apps/payment-api/src/routes/customer.routes.js b/apps/payment-api/src/routes/customer.routes.jsindex 5157a39..c5e8166 100644--- a/apps/payment-api/src/routes/customer.routes.js+++ b/apps/payment-api/src/routes/customer.routes.js@@ -43,20 +43,53 @@ export function registerCustomerRoutes(server, ctx) {// Throttles OTP dispatch per mobile number so the WhatsApp channel cannot be flooded/cost-abused.const otpRequestLog = new Map();+ /**+ * Resolves the configured cooldown between consecutive OTP dispatches.+ * Prioritizes explicit runtime options (ctx.otpCooldownMs), environment overrides+ * (OTP_RESEND_COOLDOWN_MS), and defaults to 30 seconds.+ */+ function getOtpCooldownMs() {+ if (ctx && typeof ctx.otpCooldownMs === 'number' && ctx.otpCooldownMs >= 0) {+ return ctx.otpCooldownMs;+ }+ if (process.env.OTP_RESEND_COOLDOWN_MS !== undefined) {+ const val = Number(process.env.OTP_RESEND_COOLDOWN_MS);+ if (Number.isFinite(val) && val >= 0) {+ return val;+ }+ }+ return OTP_RESEND_COOLDOWN_MS;+ }+/*** Records an OTP request and reports whether the caller is within the resend cooldown.* Entries older than the cooldown are pruned on each call.*/function isOtpThrottled(mobile) {+ const cooldownMs = getOtpCooldownMs();+ if (cooldownMs === 0) {+ return false;+ }const now = Date.now();for (const [key, at] of otpRequestLog) {- if (now - at > OTP_RESEND_COOLDOWN_MS) otpRequestLog.delete(key);+ if (now - at > cooldownMs) otpRequestLog.delete(key);}if (otpRequestLog.has(mobile)) return true;otpRequestLog.set(mobile, now);return false;}+ // Expose reset helper for tests to reset rate-limiting state deterministically+ if (ctx) {+ ctx.resetOtpCooldown = (mobile) => {+ if (mobile) {+ otpRequestLog.delete(normalizeMobile(mobile) || mobile);+ } else {+ otpRequestLog.clear();+ }+ };+ }+// Helper to get Berry Servicefunction getBerry() {return ctx.whatsappBerryService || null;diff --git a/packages/common/src/contracts.ts b/packages/common/src/contracts.tsindex 2d113ff..08d336c 100644--- a/packages/common/src/contracts.ts+++ b/packages/common/src/contracts.ts@@ -74,7 +74,7 @@ export interface WebhookEventPayload {// --- Observer Payload Contracts ---export interface AndroidObservationPayload {deviceId: string;- source: ObserverSource.ANDROID;+ source: ObserverSource.ANDROID_OBSERVER;amountPaise: number;observedAt: string;observationId?: string;diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex a6e806b..b577217 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -17,8 +17,9 @@ export class AttributionEngine {this.auditRepo = options.auditRepo;this.eventEmitter = options.eventEmitter || { emit: () => {} };const isTestExecution = process.env.NODE_ENV === 'test' ||- (process.execArgv && process.execArgv.includes('--test')) ||- (process.argv && process.argv.some(a => typeof a === 'string' && a.includes('test')));+ Boolean(process.env.NODE_TEST_CONTEXT) ||+ (process.execArgv && process.execArgv.some(a => a.includes('test'))) ||+ (process.argv && process.argv.some(a => a.includes('test')));this.gracePeriodMs = options.gracePeriodMs !== undefined? options.gracePeriodMs@@ -214,7 +215,7 @@ export class AttributionEngine {const priorUsedSession = this.sessionRepo.db.queryOne(`SELECT ps.id, ps.order_idFROM payment_sessions ps- JOIN payment_observations po ON ps.attributed_observation_id = po.id+ JOIN payment_observations po ON (ps.attributed_observation_id = po.id OR po.attributed_payment_id = ps.id)WHERE ps.status = 'SUCCESS'AND ps.id != ?AND po.bank_reference_number = ?@@ -477,12 +478,13 @@ export class AttributionEngine {// Check if observation confirms a recently successful session on this receiving account (within 60s)// Upgrades verification level (e.g. from Level 1 -> Level 2 -> Level 3)+ const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();const recentSuccessSession = this.sessionRepo.db.queryOne(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ? AND status = 'SUCCESS'- AND amount_paise = ? AND completed_at >= datetime('now', '-60 seconds')+ AND amount_paise = ? AND completed_at >= ?ORDER BY completed_at DESC LIMIT 1- `, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);+ `, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise), sixtySecsAgo]);if (recentSuccessSession) {// Check if this session's attributed observation had a UTR@@ -495,6 +497,47 @@ export class AttributionEngine {existingObs?.bankReferenceNumber &&normalizedObs.bankReferenceNumber !== existingObs.bankReferenceNumber;+ if (isUtrConflict) {+ if (this.auditRepo) {+ this.auditRepo.log({+ merchantId: recentSuccessSession.merchant_id,+ entityType: 'PAYMENT_SESSION',+ entityId: recentSuccessSession.id,+ action: 'DUPLICATE_PAYMENT_UTR_CONFLICT',+ actorType: 'SYSTEM',+ details: {+ observationId: savedObs.id,+ existingUtr: existingObs?.bankReferenceNumber,+ newUtr: normalizedObs.bankReferenceNumber,+ amountPaise: normalizedObs.amountPaise.toString()+ }+ });+ }+ if (this.ticketRepo && recentSuccessSession.customer_id) {+ this.ticketRepo.createTicket({+ merchantId: recentSuccessSession.merchant_id,+ customerId: recentSuccessSession.customer_id,+ paymentId: recentSuccessSession.id,+ subject: `[DUPLICATE PAYMENT DETECTED] Order #${recentSuccessSession.order_id}`,+ status: TicketStatus.OPEN,+ initialMessage: {+ senderType: SenderType.ADMIN,+ senderId: recentSuccessSession.merchant_id,+ message: `A duplicate payment of ${normalizedObs.amountPaise / 100n} INR with reference ${normalizedObs.bankReferenceNumber} was received within 60s of completed order #${recentSuccessSession.order_id} (reference ${existingObs?.bankReferenceNumber || 'N/A'}). Flagged for merchant refund reconciliation.`+ }+ });+ }+ this.eventEmitter.emit('PAYMENT.DUPLICATE_DETECTED', {+ paymentId: recentSuccessSession.id,+ orderId: recentSuccessSession.order_id,+ merchantId: recentSuccessSession.merchant_id,+ observationId: savedObs.id,+ existingUtr: existingObs?.bankReferenceNumber,+ newUtr: normalizedObs.bankReferenceNumber,+ amountPaise: normalizedObs.amountPaise+ });+ }+const sessionSlotStart = recentSuccessSession.slot_acquired_at? new Date(new Date(recentSuccessSession.slot_acquired_at).getTime() - 30000): new Date(new Date(recentSuccessSession.created_at).getTime() - 30000);diff --git a/packages/core/src/bank-sms-parser.js b/packages/core/src/bank-sms-parser.jsindex f3ad7aa..a8a49d7 100644--- a/packages/core/src/bank-sms-parser.js+++ b/packages/core/src/bank-sms-parser.js@@ -5,14 +5,30 @@ import { toPaise } from '@youpi/common';* Extracts amounts with prefix (Rs. 200, INR 500, ₹50), suffix (20.00 Rs),* proximity words ("20.00 received", "credited with 20.00"),* or standalone decimal amounts ("20.00").+ * Filters out available balance and credit limit clauses so balance amounts are never confused with payment amounts.* @param {string} text* @returns {{ amountStr: string, amountPaise: bigint } | null}*/export function extractIntelligentAmount(text) {if (!text || typeof text !== 'string') return null;- // Pattern 1: Standard currency prefix (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)- const prefixMatch = text.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);+ // 0. Remove balance mentions (e.g. "Avl Bal Rs 10,000", "Bal: INR 5000", "Available limit Rs. 20,000")+ // to avoid extracting account balance instead of credit amount.+ const balancePattern = /(?:(?:avl\b|avail\b|available\b|tot\b|total\b|ledger\b|clear\b|curr\b|current\b)\s*(?:bal\b|balance\b|limit\b)?|bal\b|balance\b)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)?[\s:=-]*[\d,]+(?:\.\d{1,2})?/gi;+ const sanitizedText = text.replace(balancePattern, ' ').trim();++ // Pattern 0: Direct credit proximity phrases (e.g. "credited with Rs. 500", "received ₹200.00", "Rs 499.00 credited")+ const directCreditMatch = sanitizedText.match(/(?:credited\s*(?:with|by|for)?|received|deposit(?:ed)?)\s*[:=-]?\s*(?:(?:rs\b\.?|inr\b)|₹)?[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i) ||+ sanitizedText.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)\s*(?:(?:has\s+been|is)\s+)?(?:credited|received|deposited)/i);+ if (directCreditMatch && (directCreditMatch[1] || directCreditMatch[2])) {+ const clean = (directCreditMatch[1] || directCreditMatch[2]).replace(/,/g, '');+ try {+ return { amountStr: clean, amountPaise: toPaise(clean) };+ } catch {}+ }++ // Pattern 1: Standard currency prefix on sanitized text (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)+ const prefixMatch = sanitizedText.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);if (prefixMatch && prefixMatch[1]) {const clean = prefixMatch[1].replace(/,/g, '');try {@@ -20,8 +36,8 @@ export function extractIntelligentAmount(text) {} catch {}}- // Pattern 2: Standard currency suffix (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)- const suffixMatch = text.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)/i);+ // Pattern 2: Standard currency suffix on sanitized text (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)+ const suffixMatch = sanitizedText.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)/i);if (suffixMatch && suffixMatch[1]) {const clean = suffixMatch[1].replace(/,/g, '');try {@@ -29,8 +45,8 @@ export function extractIntelligentAmount(text) {} catch {}}- // Pattern 3: Number adjacent to credit keywords (e.g. "20.00 received", "received 20.00", "credited 20", "20.00 credited")- const creditProximityMatch = text.match(/(?:credited|received|deposit|payment|paid|transferred|upi|cr)[\s\w:]*?([\d,]+(?:\.\d{1,2})?)|([\d,]+(?:\.\d{1,2})?)[\s\w:]*?(?:credited|received|deposit|payment|paid|transferred|upi|cr)/i);+ // Pattern 3: Number adjacent to credit keywords+ const creditProximityMatch = sanitizedText.match(/(?:credited|received|deposit|cr)[\s\w:]*?([\d,]+(?:\.\d{1,2})?)|([\d,]+(?:\.\d{1,2})?)[\s\w:]*?(?:credited|received|deposit|cr)/i);if (creditProximityMatch) {const rawVal = creditProximityMatch[1] || creditProximityMatch[2];if (rawVal) {@@ -44,7 +60,7 @@ export function extractIntelligentAmount(text) {}// Pattern 4: Standalone decimal currency number (e.g. 20.00, 150.50, 449.00)- const standaloneDecimal = text.match(/\b(\d{1,6}\.\d{2})\b/);+ const standaloneDecimal = sanitizedText.match(/\b(\d{1,6}\.\d{2})\b/);if (standaloneDecimal && standaloneDecimal[1]) {const clean = standaloneDecimal[1];try {@@ -84,15 +100,24 @@ export class BankSmsParser {const text = (sms.text || '').trim().slice(0, MAX_SCAN_CHARS);if (!text) return null;- // Check if SMS represents an incoming credit- const creditKeywords = /(credited|received|deposit|payment received|payment|upi\/cr|transferred)/i;+ // Check if SMS represents an incoming credit. Bare "payment" or "transferred" without credit context is rejected.+ const creditKeywords = /\b(credited|received|deposit|deposited|payment received|money received|added to (?:your )?(?:account|wallet)|upi\/cr)\b/i;if (!creditKeywords.test(text)) {return null;}- // Ignore pure debits- if (/(debited|withdrawn|sent rs|paid rs)/i.test(text) && !/(credited|received|deposit)/i.test(text)) {- return null;+ // Reject debit notifications:+ // If debit indicators exist and appear before credit indicators (e.g. "debited ... credited back in 48h")+ // or if the account itself is being debited, reject immediately.+ const debitIdx = text.search(/\b(?:debited|withdrawn|deducted|spent|paid rs|sent rs)\b/i);+ const creditIdx = text.search(/\b(?:credited|received|deposit|deposited)\b/i);+ if (debitIdx !== -1) {+ if (creditIdx === -1 || debitIdx < creditIdx) {+ return null;+ }+ if (/\b(?:debited\s*(?:from|by|for)|is\s+debited|has\s+been\s+debited)\b/i.test(text)) {+ return null;+ }}// 1. Extract Amount using Intelligent Multi-Pattern Extractor@@ -101,10 +126,10 @@ export class BankSmsParser {return null;}- // 2. Extract Bank Reference / UTR / RRN+ // 2. Extract Bank Reference / UTR / RRN (including FamPay Transaction IDs)let bankRef;const utrPatterns = [- /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9\-_]{6,35})/i,+ /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref|#)?|transaction\s*id|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9\-_]{6,35})/i,/(?:upi\/(?:[0-9]+\/|cr\/)([a-zA-Z0-9\-_]{6,35}))/i,/\b(?:ref(?:\s*(?:no\.?|id|#))?)[:\s#=-]+([a-zA-Z0-9\-_]{6,35})/i,/\b([0-9]{12})\b/@@ -118,9 +143,9 @@ export class BankSmsParser {}}- // 3. Extract Sender VPA+ // 3. Extract Sender VPA (including FamPay formats like "from Rahul (UPI ID: rahul@fam)")let senderVpa;- const vpaMatch = text.match(/(?:from|by|vpa)\s+([a-zA-Z0-9.\-_]{2,64}@[a-zA-Z0-9.\-_]{2,32})/i);+ const vpaMatch = text.match(/(?:from|by|vpa|upi\s*id)[\s:]+(?:[a-zA-Z\s]+[\(\[])?([a-zA-Z0-9.\-_]{2,64}@[a-zA-Z0-9.\-_]{2,32})/i);if (vpaMatch && vpaMatch[1]) {senderVpa = vpaMatch[1].trim().replace(/[.,;]+$/, '');}diff --git a/packages/core/src/normalizer.js b/packages/core/src/normalizer.jsindex e027669..e8cebf4 100644--- a/packages/core/src/normalizer.js+++ b/packages/core/src/normalizer.js@@ -50,13 +50,13 @@ export function extractIntelligentPaise(text) {* Regex for extracting bank UTR / Reference numbers.* Matches: UTR: 123456789012, Ref 123456789012, Txn: ABC123XYZ, RRN: 987654*/-const REFERENCE_REGEX = /(?:utr|ref|txn|rrn|reference)[:\s#]+([a-zA-Z0-9\-_]{6,35})/i;+const REFERENCE_REGEX = /(?:utr|ref(?:\s*no\.?)?|txn(?:\s*(?:id|#))?|transaction\s*id|rrn|reference(?:\s*no\.?)?|upi(?:\s*(?:ref|reference|txn))?)[:\s#]+([a-zA-Z0-9\-_]{6,35})/i;/*** Regex for extracting sender VPA if present in notification text.- * Matches: from user@upi, from 9876543210@paytm, etc.+ * Matches: from user@upi, from 9876543210@paytm, from Rahul (UPI ID: rahul@fam), etc.*/-const SENDER_VPA_REGEX = /(?:from|by)\s+([a-zA-Z0-9.\-_]{2,100}@[a-zA-Z0-9.\-_]{2,64})/i;+const SENDER_VPA_REGEX = /(?:from|by|vpa|upi\s*id)[\s:]+(?:[a-zA-Z\s]+[\(\[])?([a-zA-Z0-9.\-_]{2,100}@[a-zA-Z0-9.\-_]{2,64})/i;export class ObservationNormalizer {/**diff --git a/packages/core/src/recovery-engine.js b/packages/core/src/recovery-engine.jsindex 93c1d2f..73e0ae1 100644--- a/packages/core/src/recovery-engine.js+++ b/packages/core/src/recovery-engine.js@@ -8,7 +8,8 @@ export class RecoveryEngine {* accountRepo: import('@youpi/db').ReceivingAccountRepository,* queueEngine: import('./queue-engine.js').QueueEngine,* timingEngine: import('./timing-engine.js').TimingEngine,- * auditRepo?: import('@youpi/db').AuditLogRepository+ * auditRepo?: import('@youpi/db').AuditLogRepository,+ * eventEmitter?: { emit: (event: string, payload: any) => void }* }} options*/constructor(options) {@@ -18,6 +19,7 @@ export class RecoveryEngine {this.queueEngine = options.queueEngine;this.timingEngine = options.timingEngine;this.auditRepo = options.auditRepo;+ this.eventEmitter = options.eventEmitter;}/**@@ -39,28 +41,54 @@ export class RecoveryEngine {const now = new Date();const nowIso = now.toISOString();- // 1. Recover overdue PROCESSING sessions -> mark FAILED+ // 1. Recover overdue PROCESSING sessions -> mark SUCCESS if verified/attributed, else FAILEDconst overdueProcessing = this.db.query(`- SELECT id, receiving_account_id FROM payment_sessions+ SELECT id, merchant_id, order_id, receiving_account_id, verification_level, attributed_observation_id FROM payment_sessionsWHERE status = ? AND processing_expires_at < ?`, [PaymentStatus.PROCESSING, nowIso]);for (const row of overdueProcessing) {- this.sessionRepo.transitionToTerminal(row.id, PaymentStatus.FAILED);- failedCount++;- if (this.auditRepo) {- this.auditRepo.log({- entityType: 'PAYMENT_SESSION',- entityId: row.id,- action: 'CRASH_RECOVERY_EXPIRED_PROCESSING',- actorType: 'SYSTEM'- });+ if (row.verification_level >= 1 || row.attributed_observation_id) {+ this.sessionRepo.transitionToTerminal(row.id, PaymentStatus.SUCCESS);+ if (this.auditRepo) {+ this.auditRepo.log({+ entityType: 'PAYMENT_SESSION',+ entityId: row.id,+ action: 'CRASH_RECOVERY_ATTRIBUTED_SUCCESS',+ actorType: 'SYSTEM'+ });+ }+ if (this.eventEmitter) {+ this.eventEmitter.emit('PAYMENT.SUCCESS', {+ paymentId: row.id,+ orderId: row.order_id,+ merchantId: row.merchant_id+ });+ }+ } else {+ this.sessionRepo.transitionToTerminal(row.id, PaymentStatus.FAILED);+ failedCount++;+ if (this.auditRepo) {+ this.auditRepo.log({+ entityType: 'PAYMENT_SESSION',+ entityId: row.id,+ action: 'CRASH_RECOVERY_EXPIRED_PROCESSING',+ actorType: 'SYSTEM'+ });+ }+ if (this.eventEmitter) {+ this.eventEmitter.emit('PAYMENT.FAILED', {+ paymentId: row.id,+ orderId: row.order_id,+ merchantId: row.merchant_id+ });+ }}}// 2. Recover overdue ACTIVE sessions -> mark EXPIREDconst overdueActive = this.db.query(`- SELECT id, receiving_account_id FROM payment_sessions+ SELECT id, merchant_id, order_id, receiving_account_id FROM payment_sessionsWHERE status = ? AND expires_at < ?`, [PaymentStatus.ACTIVE, nowIso]);@@ -75,6 +103,13 @@ export class RecoveryEngine {actorType: 'SYSTEM'});}+ if (this.eventEmitter) {+ this.eventEmitter.emit('PAYMENT.EXPIRED', {+ paymentId: row.id,+ orderId: row.order_id,+ merchantId: row.merchant_id+ });+ }}// 3. Reschedule ongoing ACTIVE sessionsdiff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.jsindex 3725210..c97f198 100644--- a/packages/core/src/verification-pipeline.js+++ b/packages/core/src/verification-pipeline.js@@ -676,15 +676,18 @@ export class PaymentVerificationPipeline {});}- if (session.expiresAt) {- const sessionExpiresAt = parseSessionTime(session.expiresAt);- if (receivedAt.getTime() > sessionExpiresAt.getTime()) {+ const activeDeadline = (session.status === PaymentStatus.PROCESSING && (session.processingExpiresAt || session.processing_expires_at))+ ? parseSessionTime(session.processingExpiresAt || session.processing_expires_at)+ : (session.expiresAt || session.expires_at ? parseSessionTime(session.expiresAt || session.expires_at) : null);++ if (activeDeadline) {+ if (receivedAt.getTime() > activeDeadline.getTime()) {stage4 = {stage: 4,name: 'VERIFICATION',status: 'FAILED',reason: 'SESSION_EXPIRED',- details: `Observation received timestamp (${receivedAt.toISOString()}) is after payment session expiration (${sessionExpiresAt.toISOString()}).`+ details: `Observation received timestamp (${receivedAt.toISOString()}) is after payment session expiration (${activeDeadline.toISOString()}).`};return buildResult({finalStatus: 'REJECTED',diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.jsindex 5b2e9a8..d671f91 100644--- a/packages/db/src/migrate.js+++ b/packages/db/src/migrate.js@@ -70,6 +70,11 @@ export function runMigrations(targetDb) {try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_level INTEGER DEFAULT 0;"); } catch {}try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_sources TEXT DEFAULT '[]';"); } catch {}try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_tag TEXT DEFAULT 'UNVERIFIED';"); } catch {}+ try { db.exec("ALTER TABLE payment_sessions ADD COLUMN attempt_id TEXT;"); } catch {}+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order ON payment_sessions (merchant_id, order_id) WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');"); } catch {}+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_one_slot_per_receiving_account ON payment_sessions (receiving_account_id) WHERE status IN ('ACTIVE', 'PROCESSING') AND receiving_account_id IS NOT NULL;"); } catch {}+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);"); } catch {}+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);"); } catch {}try { db.exec("ALTER TABLE payment_receiving_accounts ADD COLUMN is_merchant_enabled INTEGER NOT NULL DEFAULT 1;"); } catch {}try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_vpa_per_merchant ON payment_receiving_accounts (merchant_id) WHERE is_active = 1;"); } catch {}try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_customers_email ON customers (email);"); } catch {}@@ -104,9 +109,10 @@ export function runMigrations(targetDb) {`); } catch {}try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);"); } catch {}try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);"); } catch {}- try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);"); } catch {}try { db.exec("CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);"); } catch {}try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);"); } catch {}+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);"); } catch {}+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);"); } catch {}// Seed default merchant if emptyconst merchantRepo = new MerchantRepository(db);diff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.jsindex ea8d10c..17683f8 100644--- a/packages/db/src/repositories/payment-session.repository.js+++ b/packages/db/src/repositories/payment-session.repository.js@@ -13,14 +13,15 @@ export class PaymentSessionRepository {const id = data.id || crypto.randomUUID();const now = new Date().toISOString();const metadata = typeof data.metadata === 'object' ? JSON.stringify(data.metadata) : (data.metadata || '{}');+ const attemptId = data.attemptId || id;const sql = `INSERT INTO payment_sessions (- id, merchant_id, customer_id, receiving_account_id, order_id,+ id, merchant_id, customer_id, receiving_account_id, order_id, attempt_id,amount_paise, currency, method, status, queue_position,return_url, idempotency_key, device_id, verification_level, verification_sources,verification_tag, metadata, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '[]', 'UNVERIFIED', ?, ?, ?)+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '[]', 'UNVERIFIED', ?, ?, ?)`;this.db.execute(sql, [@@ -29,6 +30,7 @@ export class PaymentSessionRepository {data.customerId || null,data.receivingAccountId || null,data.orderId,+ attemptId,Number(data.amountPaise),data.currency || 'INR',data.method || PaymentMethod.UPI,@@ -53,7 +55,7 @@ export class PaymentSessionRepository {findByOrderId(merchantId, orderId) {const row = this.db.queryOne(- 'SELECT * FROM payment_sessions WHERE merchant_id = ? AND order_id = ?',+ 'SELECT * FROM payment_sessions WHERE merchant_id = ? AND order_id = ? ORDER BY created_at DESC LIMIT 1',[merchantId, orderId]);if (!row) return null;@@ -459,11 +461,11 @@ export class PaymentSessionRepository {const rows = this.db.query(`SELECT * FROM payment_sessionsWHERE receiving_account_id = ?- AND status IN (?, ?)+ AND status IN (?, ?, ?)AND updated_at >= ?ORDER BY updated_at DESCLIMIT 20- `, [receivingAccountId, PaymentStatus.EXPIRED, PaymentStatus.FAILED, sinceDate.toISOString()]);+ `, [receivingAccountId, PaymentStatus.EXPIRED, PaymentStatus.FAILED, PaymentStatus.CANCELLED, sinceDate.toISOString()]);return rows.map(r => this.mapRow(r));}@@ -586,6 +588,7 @@ export class PaymentSessionRepository {customerId: row.customer_id,receivingAccountId: row.receiving_account_id,orderId: row.order_id,+ attemptId: row.attempt_id || row.id,amountPaise: BigInt(row.amount_paise),currency: row.currency,method: row.method,diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sqlindex 9d15568..a9f38e3 100644--- a/packages/db/src/schema.sql+++ b/packages/db/src/schema.sql@@ -42,8 +42,13 @@ CREATE TABLE IF NOT EXISTS customers (password_hash VARCHAR(255),otp_code VARCHAR(10),otp_expires_at TIMESTAMPTZ,+ otp_attempts INT NOT NULL DEFAULT 0,is_phone_verified BOOLEAN DEFAULT false,status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',+ ban_reason TEXT,+ banned_at TIMESTAMPTZ,+ unbanned_at TIMESTAMPTZ,+ last_device TEXT,last_login_at TIMESTAMPTZ,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()@@ -68,6 +73,28 @@ CREATE TABLE IF NOT EXISTS customer_sessions (CREATE INDEX IF NOT EXISTS idx_customer_sessions_token ON customer_sessions (token, is_active);CREATE INDEX IF NOT EXISTS idx_customer_sessions_customer ON customer_sessions (customer_id);+-- 3c. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)+CREATE TABLE IF NOT EXISTS devices (+ id TEXT PRIMARY KEY,+ customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,+ public_key TEXT NOT NULL,+ fingerprint_hash VARCHAR(64) NOT NULL,+ user_agent TEXT,+ platform VARCHAR(100),+ browser VARCHAR(100),+ timezone VARCHAR(100),+ language VARCHAR(50),+ screen_signature VARCHAR(100),+ device_token VARCHAR(255) UNIQUE,+ status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);+CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);+CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);+-- 4. Payment Sessions TableCREATE TABLE IF NOT EXISTS payment_sessions (id TEXT PRIMARY KEY,@@ -75,6 +102,7 @@ CREATE TABLE IF NOT EXISTS payment_sessions (customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,receiving_account_id TEXT REFERENCES payment_receiving_accounts(id),order_id VARCHAR(255) NOT NULL,+ attempt_id TEXT,amount_paise BIGINT NOT NULL CHECK (amount_paise > 0),currency VARCHAR(3) NOT NULL DEFAULT 'INR',method VARCHAR(50) NOT NULL DEFAULT 'UPI',@@ -94,11 +122,18 @@ CREATE TABLE IF NOT EXISTS payment_sessions (verification_tag VARCHAR(100) DEFAULT 'UNVERIFIED',metadata TEXT NOT NULL DEFAULT '{}',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- CONSTRAINT uq_merchant_order UNIQUE (merchant_id, order_id)+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW());CREATE INDEX IF NOT EXISTS idx_payment_sessions_active ON payment_sessions (receiving_account_id, status);+CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);+CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);+CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order+ ON payment_sessions (merchant_id, order_id)+ WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');+CREATE UNIQUE INDEX IF NOT EXISTS idx_one_slot_per_receiving_account+ ON payment_sessions (receiving_account_id)+ WHERE status IN ('ACTIVE', 'PROCESSING') AND receiving_account_id IS NOT NULL;-- 5. Payment Observations TableCREATE TABLE IF NOT EXISTS payment_observations (@@ -119,6 +154,8 @@ CREATE TABLE IF NOT EXISTS payment_observations (CREATE INDEX IF NOT EXISTS idx_observations_match ON payment_observations (receiving_account_id, amount_paise, attribution_status);CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);+CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);+CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);-- 6. Android Devices TableCREATE TABLE IF NOT EXISTS android_devices (@@ -149,6 +186,8 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());+CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);+-- 8. Support Tickets & Ticket MessagesCREATE TABLE IF NOT EXISTS support_tickets (id TEXT PRIMARY KEY,@@ -161,6 +200,9 @@ CREATE TABLE IF NOT EXISTS support_tickets (updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW());+CREATE INDEX IF NOT EXISTS idx_support_tickets_merchant ON support_tickets (merchant_id);+CREATE INDEX IF NOT EXISTS idx_support_tickets_customer ON support_tickets (customer_id);+CREATE TABLE IF NOT EXISTS ticket_messages (id TEXT PRIMARY KEY,ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,@@ -171,6 +213,8 @@ CREATE TABLE IF NOT EXISTS ticket_messages (created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());+CREATE INDEX IF NOT EXISTS idx_ticket_messages_ticket ON ticket_messages (ticket_id);+-- 9. Audit Logs TableCREATE TABLE IF NOT EXISTS audit_logs (id TEXT PRIMARY KEY,@@ -185,6 +229,9 @@ CREATE TABLE IF NOT EXISTS audit_logs (created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());+CREATE INDEX IF NOT EXISTS idx_audit_logs_merchant ON audit_logs (merchant_id);+CREATE INDEX IF NOT EXISTS idx_audit_logs_entity ON audit_logs (entity_type, entity_id);+-- 10. Security Events TableCREATE TABLE IF NOT EXISTS security_events (id TEXT PRIMARY KEY,@@ -206,26 +253,8 @@ CREATE TABLE IF NOT EXISTS security_events (created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());--- 11. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)-CREATE TABLE IF NOT EXISTS devices (- id TEXT PRIMARY KEY,- customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,- public_key TEXT NOT NULL,- fingerprint_hash VARCHAR(64) NOT NULL,- user_agent TEXT,- platform VARCHAR(100),- browser VARCHAR(100),- timezone VARCHAR(100),- language VARCHAR(50),- screen_signature VARCHAR(100),- device_token VARCHAR(255) UNIQUE,- status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);+CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (customer_id);+CREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);+CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);-CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);-CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);-CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);-CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex 0243ce2..95220e8 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -43,6 +43,10 @@ CREATE TABLE IF NOT EXISTS customers (otp_attempts INTEGER NOT NULL DEFAULT 0,is_phone_verified INTEGER DEFAULT 0,status TEXT NOT NULL DEFAULT 'ACTIVE',+ ban_reason TEXT,+ banned_at TEXT,+ unbanned_at TEXT,+ last_device TEXT,last_login_at TEXT,created_at TEXT NOT NULL DEFAULT (datetime('now')),updated_at TEXT NOT NULL DEFAULT (datetime('now'))@@ -67,6 +71,28 @@ CREATE TABLE IF NOT EXISTS customer_sessions (CREATE INDEX IF NOT EXISTS idx_customer_sessions_token ON customer_sessions (token, is_active);CREATE INDEX IF NOT EXISTS idx_customer_sessions_customer ON customer_sessions (customer_id);+-- 3c. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)+CREATE TABLE IF NOT EXISTS devices (+ id TEXT PRIMARY KEY,+ customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,+ public_key TEXT NOT NULL,+ fingerprint_hash TEXT NOT NULL,+ user_agent TEXT,+ platform TEXT,+ browser TEXT,+ timezone TEXT,+ language TEXT,+ screen_signature TEXT,+ device_token TEXT UNIQUE,+ status TEXT NOT NULL DEFAULT 'ACTIVE',+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))+);++CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);+CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);+CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);+-- 4. Payment Sessions TableCREATE TABLE IF NOT EXISTS payment_sessions (id TEXT PRIMARY KEY,@@ -74,6 +100,7 @@ CREATE TABLE IF NOT EXISTS payment_sessions (customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,receiving_account_id TEXT REFERENCES payment_receiving_accounts(id),order_id TEXT NOT NULL,+ attempt_id TEXT,amount_paise INTEGER NOT NULL CHECK (amount_paise > 0),currency TEXT NOT NULL DEFAULT 'INR',method TEXT NOT NULL DEFAULT 'UPI',@@ -93,11 +120,17 @@ CREATE TABLE IF NOT EXISTS payment_sessions (verification_tag TEXT DEFAULT 'UNVERIFIED',metadata TEXT NOT NULL DEFAULT '{}',created_at TEXT NOT NULL DEFAULT (datetime('now')),- updated_at TEXT NOT NULL DEFAULT (datetime('now')),- UNIQUE(merchant_id, order_id)+ updated_at TEXT NOT NULL DEFAULT (datetime('now')));CREATE INDEX IF NOT EXISTS idx_payment_sessions_active ON payment_sessions (receiving_account_id, status);+CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);+CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);+-- At most one active/processing/queued/successful session per merchant order.+-- Retrying a terminal (FAILED, EXPIRED, CANCELLED) order allows a new attempt with the true orderId.+CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order+ ON payment_sessions (merchant_id, order_id)+ WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');-- Slot exclusivity is a database invariant, not an application convention: at most one-- session per receiving account may occupy the slot (ACTIVE or PROCESSING) at any time.-- Concurrent writers are rejected by the engine instead of relying on lock contention.@@ -123,6 +156,9 @@ CREATE TABLE IF NOT EXISTS payment_observations ();CREATE INDEX IF NOT EXISTS idx_observations_match ON payment_observations (receiving_account_id, amount_paise, attribution_status);+CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);+CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);+CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);-- 6. Android Devices TableCREATE TABLE IF NOT EXISTS android_devices (@@ -153,6 +189,8 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (created_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);+-- 8. Support Tickets & Ticket MessagesCREATE TABLE IF NOT EXISTS support_tickets (id TEXT PRIMARY KEY,@@ -165,6 +203,9 @@ CREATE TABLE IF NOT EXISTS support_tickets (updated_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_support_tickets_merchant ON support_tickets (merchant_id);+CREATE INDEX IF NOT EXISTS idx_support_tickets_customer ON support_tickets (customer_id);+CREATE TABLE IF NOT EXISTS ticket_messages (id TEXT PRIMARY KEY,ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,@@ -175,6 +216,8 @@ CREATE TABLE IF NOT EXISTS ticket_messages (created_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_ticket_messages_ticket ON ticket_messages (ticket_id);+-- 9. Audit Logs TableCREATE TABLE IF NOT EXISTS audit_logs (id TEXT PRIMARY KEY,@@ -189,6 +232,9 @@ CREATE TABLE IF NOT EXISTS audit_logs (created_at TEXT NOT NULL DEFAULT (datetime('now')));+CREATE INDEX IF NOT EXISTS idx_audit_logs_merchant ON audit_logs (merchant_id);+CREATE INDEX IF NOT EXISTS idx_audit_logs_entity ON audit_logs (entity_type, entity_id);+-- 10. Security Events Table (Forensic evidence for fraud, automatic and manual bans)CREATE TABLE IF NOT EXISTS security_events (id TEXT PRIMARY KEY,@@ -214,27 +260,5 @@ CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (custCREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);--- 11. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)-CREATE TABLE IF NOT EXISTS devices (- id TEXT PRIMARY KEY,- customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,- public_key TEXT NOT NULL,- fingerprint_hash TEXT NOT NULL,- user_agent TEXT,- platform TEXT,- browser TEXT,- timezone TEXT,- language TEXT,- screen_signature TEXT,- device_token TEXT UNIQUE,- status TEXT NOT NULL DEFAULT 'ACTIVE',- created_at TEXT NOT NULL DEFAULT (datetime('now')),- last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))-);--CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);-CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);-CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);-CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);diff --git a/tsconfig.json b/tsconfig.jsonindex 3ccc358..009f630 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,17 +1,6 @@{"files": [],"references": [- { "path": "./packages/common" },- { "path": "./packages/db" },- { "path": "./packages/core" },- { "path": "./packages/observer-sdk" },- { "path": "./packages/merchant-sdk" },- { "path": "./apps/payment-api" },- { "path": "./apps/checkout-portal" },- { "path": "./apps/merchant-admin" },- { "path": "./apps/payment-help" },- { "path": "./apps/gmail-observer" },- { "path": "./apps/sms-observer" },- { "path": "./apps/control-center" }+ { "path": "./packages/common" }]}