Skip to content

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): prevent unresolved pipeline fallthrough and enforce unique UTR index (#60)

ArunGupta15263f5acc417ffb
diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.js
index 9b252d5..d11015b 100644
--- a/apps/payment-api/src/__tests__/payment-api.test.js
+++ b/apps/payment-api/src/__tests__/payment-api.test.js
@@ -132,6 +132,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {
receivingAccountId: '00000000-0000-0000-0000-000000000002',
amount: '200.00',
utr: 'UTR-HTTP-999',
+ rawText: 'A/C 1234 credited by Rs 200.00 via UPI/UTR-HTTP-999',
observedAt: new Date().toISOString()
}
});
@@ -530,6 +531,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {
receivingAccountId: '00000000-0000-0000-0000-000000000002',
amount: '650.00',
utr: 'UTR-TIER-001',
+ rawText: 'A/C 1234 credited by Rs 650.00 via UPI/UTR-TIER-001',
observedAt: new Date().toISOString()
}
});
@@ -553,6 +555,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {
receivingAccountId: '00000000-0000-0000-0000-000000000002',
amount: '650.00',
utr: 'UTR-TIER-001',
+ rawText: 'Dear Customer, INR 650.00 credited to your account via UPI/UTR-TIER-001',
observedAt: new Date().toISOString()
}
});
@@ -763,6 +766,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {
receivingAccountId: '00000000-0000-0000-0000-000000000002',
amount: '320.00',
utr: 'UTR-NOCLICK-999',
+ rawText: 'A/C 1234 credited by Rs 320.00 via UPI/UTR-NOCLICK-999',
observedAt: new Date().toISOString()
}
});
@@ -794,6 +798,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {
receivingAccountId: '00000000-0000-0000-0000-000000000002',
amount: '320.00',
utr: 'UTR-NOCLICK-999',
+ rawText: 'Dear Customer, INR 320.00 credited to your account via UPI/UTR-NOCLICK-999',
observedAt: new Date().toISOString()
}
});
diff --git a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js
index a2263eb..8601539 100644
--- a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js
+++ b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js
@@ -330,7 +330,8 @@ describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & C
source: 'GOOGLE_MESSAGES',
receivingAccountId: accountId,
amount: '42.00',
- utr: 'UTR-PAID-ORD-RESTART'
+ utr: 'UTR-PAID-ORD-RESTART',
+ rawText: 'A/C 1234 credited by Rs 42.00 via UPI/UTR-PAID-ORD-RESTART'
}
});
await new Promise(r => setTimeout(r, 6500));
diff --git a/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js b/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js
index e981ba2..6e08d37 100644
--- a/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js
+++ b/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js
@@ -198,6 +198,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',
receivingAccountId,
amountPaise: '45000',
amount: '450.00',
+ rawText: 'Dear Customer, INR 450.00 credited to A/C *4321. Ref: REF99887766 - HDFC Bank',
observedAt: new Date().toISOString()
})
});
diff --git a/apps/payment-api/src/__tests__/verification-fallthrough.test.js b/apps/payment-api/src/__tests__/verification-fallthrough.test.js
index 5cee65a..e888bd2 100644
--- a/apps/payment-api/src/__tests__/verification-fallthrough.test.js
+++ b/apps/payment-api/src/__tests__/verification-fallthrough.test.js
@@ -391,5 +391,157 @@ describe('Verification Pipeline & Fall-Through Protection (#22)', () => {
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');
});
+
+ test('Issue #60: Missing rawText is rejected with HTTP 400 and does not bypass pipeline', 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: 'MISSING-RAWTEXT-01',
+ amountPaise: 75000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, receivingAccountId);
+
+ // Caller attempts to bypass pipeline by sending amount and UTR without rawText
+ const res = await request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: 'HDFCBK',
+ receivingAccountId,
+ amount: '750.00',
+ amountPaise: '75000',
+ bankReferenceNumber: '750750750750'
+ }
+ });
+
+ assert.equal(res.status, 400);
+ assert.equal(res.body.accepted, false);
+ assert.equal(res.body.status, 'REJECTED');
+ assert.equal(res.body.reason, 'MISSING_RAW_TEXT');
+
+ // Confirm session is NOT marked SUCCESS
+ const freshSession = sessionRepo.findById(session.id);
+ assert.equal(freshSession.status, PaymentStatus.ACTIVE);
+ });
+
+ test('Issue #60: UNRESOLVED pipeline result is rejected with HTTP 400 and never falls through to attribution', async () => {
+ const accountRepo = new ReceivingAccountRepository(testDb);
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+
+ const unassignedAcc = accountRepo.create({
+ merchantId,
+ upiId: `unresolved-${crypto.randomUUID().slice(0, 8)}@okaxis`,
+ payeeName: 'Unresolved Holder',
+ provider: 'AXIS_BANK'
+ });
+
+ // Ingest observation for an account with no active or processing session -> Stage 4 returns UNRESOLVED
+ const res = await request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: 'HDFCBK',
+ receivingAccountId: unassignedAcc.id,
+ amount: '999.00',
+ amountPaise: '99900',
+ bankReferenceNumber: '999111222333',
+ rawText: 'A/C 1234 credited with Rs 999.00 on 21-Oct-2026. Ref: 999111222333'
+ }
+ });
+
+ assert.equal(res.status, 400);
+ assert.equal(res.body.accepted, false);
+ assert.equal(res.body.status, 'UNRESOLVED');
+ });
+
+ test('Issue #60: Concurrent requests with identical UTR are rejected and prevent double-attribution', async () => {
+ const sessionRepo = apiInstance.app.context.sessionRepo;
+ const accountRepo = new ReceivingAccountRepository(testDb);
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+
+ // Account A and Account B
+ const recAcc1 = accountRepo.create({
+ merchantId,
+ upiId: `race1-${crypto.randomUUID().slice(0, 8)}@okaxis`,
+ payeeName: 'Race Holder 1',
+ provider: 'AXIS_BANK'
+ });
+ const recAcc2 = accountRepo.create({
+ merchantId,
+ upiId: `race2-${crypto.randomUUID().slice(0, 8)}@okaxis`,
+ payeeName: 'Race Holder 2',
+ provider: 'AXIS_BANK'
+ });
+
+ const s1 = sessionRepo.create({
+ merchantId,
+ receivingAccountId: recAcc1.id,
+ orderId: `RACE-ORD-1-${Date.now()}`,
+ amountPaise: 88800n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(s1.id, recAcc1.id);
+
+ const s2 = sessionRepo.create({
+ merchantId,
+ receivingAccountId: recAcc2.id,
+ orderId: `RACE-ORD-2-${Date.now()}`,
+ amountPaise: 88800n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(s2.id, recAcc2.id);
+
+ const sharedUtr = `RACEUTR${Date.now()}`.slice(0, 12).padEnd(12, '0');
+
+ // Fire two requests concurrently with the same UTR
+ const [res1, res2] = await Promise.all([
+ request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: 'HDFCBK',
+ receivingAccountId: recAcc1.id,
+ amount: '888.00',
+ amountPaise: '88800',
+ bankReferenceNumber: sharedUtr,
+ rawText: `A/C 1234 credited with Rs 888.00 on 21-Oct-2026. Ref: ${sharedUtr}`
+ }
+ }),
+ request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: 'HDFCBK',
+ receivingAccountId: recAcc2.id,
+ amount: '888.00',
+ amountPaise: '88800',
+ bankReferenceNumber: sharedUtr,
+ rawText: `A/C 5678 credited with Rs 888.00 on 21-Oct-2026. Ref: ${sharedUtr}`
+ }
+ })
+ ]);
+
+ const statuses = [res1.status, res2.status].sort();
+ assert.deepEqual(statuses, [200, 400], 'Exactly one request must succeed and the other must be rejected');
+
+ const successRes = res1.status === 200 ? res1 : res2;
+ const failedRes = res1.status === 400 ? res1 : res2;
+
+ assert.equal(successRes.body.accepted, true);
+ assert.equal(failedRes.body.accepted, false);
+ assert.equal(failedRes.body.status, 'REJECTED');
+ assert.equal(failedRes.body.reason, 'REFERENCE_ALREADY_USED');
+
+ // Verify exactly one session is SUCCESS and one is ACTIVE
+ const s1Fresh = sessionRepo.findById(s1.id);
+ const s2Fresh = sessionRepo.findById(s2.id);
+ const sessionStatuses = [s1Fresh.status, s2Fresh.status].sort();
+ assert.deepEqual(sessionStatuses, [PaymentStatus.ACTIVE, PaymentStatus.SUCCESS]);
+ });
});
diff --git a/apps/payment-api/src/routes/pollers.routes.js b/apps/payment-api/src/routes/pollers.routes.js
index 4df12f0..4ec35c4 100644
--- a/apps/payment-api/src/routes/pollers.routes.js
+++ b/apps/payment-api/src/routes/pollers.routes.js
@@ -78,6 +78,17 @@ export function registerPollerRoutes(server, ctx) {
const rawText = body.rawText || body.text || body.message || body.sms || body.body || (typeof body.rawPayload === 'string' ? body.rawPayload : (body.rawPayload?.text || body.rawPayload?.body));
const sender = body.sender || body.from || body.rawPayload?.sender || body.rawPayload?.from;
+ // Reject missing or blank observation rawText
+ if (!rawText || (typeof rawText === 'string' && !rawText.trim())) {
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: 'MISSING_RAW_TEXT',
+ error: 'Observation rawText is required for verification.'
+ });
+ return;
+ }
+
// Bank notifications are small. Reject oversized bodies outright so no single observation
// can be used to burn CPU or memory on the verification path.
if (typeof rawText === 'string' && rawText.length > MAX_OBSERVATION_TEXT_CHARS) {
@@ -85,93 +96,65 @@ export function registerPollerRoutes(server, ctx) {
return;
}
- if (ctx.pipeline && rawText) {
- const pipeResult = ctx.pipeline.process({
- source: body.source,
- rawText,
- sender,
- receivingAccountId: body.receivingAccountId,
- paymentSessionId: body.paymentSessionId,
- bankReferenceNumber: body.bankReferenceNumber || body.utr,
- // Test flags relax verification: honour them only for the admin credential, never for observers.
- isTest: Boolean(body.isTest) && isAdminRequest(req),
- testModeActive: Boolean(body.testModeActive) && isAdminRequest(req)
- });
-
- if (pipeResult.status === 'REJECTED' && pipeResult.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION') {
- HttpServer.json(res, 403, {
- accepted: false,
- status: 'REJECTED',
- reason: 'FRAUDULENT_PAYMENT_INJECTION',
- threatDetected: true,
- banned: true,
- error: 'FRAUDULENT_PAYMENT_INJECTION: Positive identification of fake payment message. Customer account banned and session terminated.'
- });
- return;
- }
-
- if (pipeResult.status === 'VERIFIED') {
- HttpServer.json(res, 200, {
- accepted: true,
- observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,
- attribution: pipeResult.stages?.stage6?.details || pipeResult,
- pipeline: pipeResult
- });
- return;
- }
-
- if (pipeResult.status === 'REJECTED') {
- HttpServer.json(res, 400, {
- accepted: false,
- status: 'REJECTED',
- reason: pipeResult.failingCondition,
- error: pipeResult.failingReason || pipeResult.details,
- pipeline: pipeResult
- });
- return;
- }
+ if (!ctx.pipeline) {
+ HttpServer.json(res, 500, { error: 'Verification pipeline is not configured on this server.' });
+ return;
}
- try {
- let amountPaise = body.amountPaise ? BigInt(body.amountPaise) : undefined;
- let bankRef = body.bankReferenceNumber || body.utr;
- let senderVpa = body.senderVpa;
- const observedAt = body.observedAt ? new Date(body.observedAt) : new Date();
-
- if (rawText && (!amountPaise || !bankRef)) {
- const isEmail = body.source === 'GMAIL' || body.source === 'EMAIL';
- const parsed = isEmail
- ? BankEmailParser.parse({ subject: body.subject || body.rawPayload?.subject || '', body: rawText, date: observedAt, from: sender })
- : BankSmsParser.parse({ text: rawText, sender, timestamp: observedAt });
- if (parsed) {
- if (!amountPaise) amountPaise = parsed.amountPaise;
- if (!bankRef && parsed.bankReferenceNumber) bankRef = parsed.bankReferenceNumber;
- if (!senderVpa && parsed.senderVpa) senderVpa = parsed.senderVpa;
- }
- }
+ const pipeResult = ctx.pipeline.process({
+ source: body.source,
+ rawText,
+ sender,
+ receivingAccountId: body.receivingAccountId,
+ paymentSessionId: body.paymentSessionId,
+ bankReferenceNumber: body.bankReferenceNumber || body.utr,
+ // Test flags relax verification: honour them only for the admin credential, never for observers.
+ isTest: Boolean(body.isTest) && isAdminRequest(req),
+ testModeActive: Boolean(body.testModeActive) && isAdminRequest(req)
+ });
- const normalized = ObservationNormalizer.normalize({
- source: body.source,
- receivingAccountId: body.receivingAccountId,
- rawPayload: body.rawPayload || body,
- amountPaise,
- amount: body.amount || (amountPaise ? (Number(amountPaise) / 100).toFixed(2) : undefined),
- observedAt,
- senderVpa,
- bankReferenceNumber: bankRef
+ if (pipeResult.status === 'REJECTED' && pipeResult.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION') {
+ HttpServer.json(res, 403, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: 'FRAUDULENT_PAYMENT_INJECTION',
+ threatDetected: true,
+ banned: true,
+ error: 'FRAUDULENT_PAYMENT_INJECTION: Positive identification of fake payment message. Customer account banned and session terminated.'
});
+ return;
+ }
- const result = ctx.attributionEngine.processObservation(normalized);
-
+ if (pipeResult.status === 'VERIFIED') {
HttpServer.json(res, 200, {
accepted: true,
- observationId: result.observationId,
- attribution: result
+ observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,
+ attribution: pipeResult.stages?.stage6?.details || pipeResult,
+ pipeline: pipeResult
});
- } catch (err) {
- console.error('[Poller Ingest Error]:', err.message);
- HttpServer.json(res, 400, { error: err.message });
+ return;
+ }
+
+ if (pipeResult.status === 'REJECTED') {
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: pipeResult.failingCondition,
+ error: pipeResult.failingReason || pipeResult.details,
+ pipeline: pipeResult
+ });
+ return;
}
+
+ // Invert check: if status is not VERIFIED, return 4xx and NEVER fall through to direct attribution
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: pipeResult.status || 'UNRESOLVED',
+ reason: pipeResult.stages?.stage6?.outcomeStatus || pipeResult.failingCondition || 'UNRESOLVED_OBSERVATION',
+ observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,
+ error: pipeResult.failingReason || 'Payment observation could not be verified or attributed.',
+ pipeline: pipeResult
+ });
});
// --- ANDROID SMS GATEWAY PAIRING HANDLER ---
@@ -335,6 +318,16 @@ export function registerPollerRoutes(server, ctx) {
// Check for raw SMS text inside body or rawNotification
const rawText = body.body || body.sms || body.rawSms || body.message || body.text || body.rawNotification?.text;
+ if (!rawText || (typeof rawText === 'string' && !rawText.trim())) {
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: 'MISSING_RAW_TEXT',
+ error: 'Observation rawText is required for verification.'
+ });
+ return;
+ }
+
if (rawText && (!amountPaise || !bankRef)) {
const parsedSms = BankSmsParser.parse({
text: rawText,
@@ -356,58 +349,61 @@ export function registerPollerRoutes(server, ctx) {
}
// Evaluate through Security & Fraud Verification Pipeline for Android Ingest
- if (ctx.pipeline && rawText) {
- const pipeResult = ctx.pipeline.process({
- source: 'SMS',
- rawText,
- sender: body.sender || req.headers['x-sender'] || body.rawNotification?.package,
- receivingAccountId,
- paymentSessionId: body.paymentSessionId,
- bankReferenceNumber: bankRef,
- isTest: false, // device-supplied flags must never relax verification
- deviceInfo: device ? `${device.device_name} (${device.device_model})` : 'Android SMS Gateway'
- });
+ if (!ctx.pipeline) {
+ HttpServer.json(res, 500, { error: 'Verification pipeline is not configured on this server.' });
+ return;
+ }
- if (pipeResult.status === 'REJECTED' && pipeResult.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION') {
- HttpServer.json(res, 403, {
- accepted: false,
- status: 'REJECTED',
- reason: 'FRAUDULENT_PAYMENT_INJECTION',
- threatDetected: true,
- banned: true,
- error: 'FRAUDULENT_PAYMENT_INJECTION: Fake SMS detected. Associated customer identity banned and session terminated.'
- });
- return;
- }
+ const pipeResult = ctx.pipeline.process({
+ source: 'SMS',
+ rawText,
+ sender: body.sender || req.headers['x-sender'] || body.rawNotification?.package,
+ receivingAccountId,
+ paymentSessionId: body.paymentSessionId,
+ bankReferenceNumber: bankRef,
+ isTest: false, // device-supplied flags must never relax verification
+ deviceInfo: device ? `${device.device_name} (${device.device_model})` : 'Android SMS Gateway'
+ });
- if (pipeResult.status === 'VERIFIED') {
- ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);
- HttpServer.json(res, 200, {
- accepted: true,
- observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,
- attribution: pipeResult.stages?.stage6?.details || pipeResult,
- pipeline: pipeResult
- });
- return;
- }
+ if (pipeResult.status === 'REJECTED' && pipeResult.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION') {
+ HttpServer.json(res, 403, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: 'FRAUDULENT_PAYMENT_INJECTION',
+ threatDetected: true,
+ banned: true,
+ error: 'FRAUDULENT_PAYMENT_INJECTION: Fake SMS detected. Associated customer identity banned and session terminated.'
+ });
+ return;
+ }
- if (pipeResult.status === 'REJECTED') {
- ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);
- HttpServer.json(res, 400, {
- accepted: false,
- status: 'REJECTED',
- reason: pipeResult.failingCondition,
- error: pipeResult.failingReason || pipeResult.details,
- pipeline: pipeResult
- });
- return;
- }
+ if (pipeResult.status === 'VERIFIED') {
+ ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);
+ HttpServer.json(res, 200, {
+ accepted: true,
+ observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,
+ attribution: pipeResult.stages?.stage6?.details || pipeResult,
+ pipeline: pipeResult
+ });
+ return;
+ }
+
+ if (pipeResult.status === 'REJECTED') {
+ ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: pipeResult.failingCondition,
+ error: pipeResult.failingReason || pipeResult.details,
+ pipeline: pipeResult
+ });
+ return;
}
// Transport Only Contract (Part D): The Android observer forwards all raw SMS.
// If no monetary amount is extracted (e.g. personal, promotional, non-bank SMS),
// update observation timestamp on device and return 200 PROCESSED_NON_BANK.
- if (!amountPaise) {
+ if (!amountPaise && pipeResult.status === 'UNRESOLVED') {
ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);
HttpServer.json(res, 200, {
accepted: true,
@@ -418,32 +414,16 @@ export function registerPollerRoutes(server, ctx) {
return;
}
- try {
- const normalized = ObservationNormalizer.normalize({
- source: 'ANDROID_OBSERVER', // Maps to Android SMS Observer source in system enums
- receivingAccountId,
- rawPayload: body,
- amountPaise,
- amount: body.amount || (Number(amountPaise) / 100).toFixed(2),
- observedAt,
- senderVpa,
- bankReferenceNumber: bankRef
- });
-
- const result = ctx.attributionEngine.processObservation(normalized);
-
- // Update device last observation timestamp
- ctx.db.execute('UPDATE android_devices SET last_observation_at = datetime(\'now\') WHERE id = ?', [deviceId]);
-
- HttpServer.json(res, 200, {
- accepted: true,
- observationId: result.observationId,
- attribution: result
- });
- } catch (err) {
- console.error('[Android SMS Ingest Error]:', err.message);
- HttpServer.json(res, 400, { error: err.message });
- }
+ // Invert check: if status is not VERIFIED, return 4xx and NEVER fall through to direct attribution
+ ctx.db.execute("UPDATE android_devices SET last_observation_at = datetime('now') WHERE id = ?", [deviceId]);
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: pipeResult.status || 'UNRESOLVED',
+ reason: pipeResult.stages?.stage6?.outcomeStatus || pipeResult.failingCondition || 'UNRESOLVED_OBSERVATION',
+ observationId: pipeResult.messageId || pipeResult.stages?.stage6?.details?.observationId,
+ error: pipeResult.failingReason || 'Payment observation could not be verified or attributed.',
+ pipeline: pipeResult
+ });
};
server.post('/api/v1/pollers/android/events', handleAndroidSmsEvents);
diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.js
index 95a21e4..db8b0df 100644
--- a/packages/core/src/attribution-engine.js
+++ b/packages/core/src/attribution-engine.js
@@ -137,13 +137,36 @@ export class AttributionEngine {
}
const savedObs = this.obsRepo.create(normalizedObs);
- const verifyResult = this.sessionRepo.recordVerificationSource(
- existing.attributedPaymentId,
- normalizedObs.source,
- savedObs.id,
- { finalizeSuccess: true }
- );
- this.obsRepo.markAttributed(savedObs.id, existing.attributedPaymentId);
+ let verifyResult;
+ try {
+ verifyResult = this.sessionRepo.recordVerificationSource(
+ existing.attributedPaymentId,
+ normalizedObs.source,
+ savedObs.id,
+ { finalizeSuccess: true }
+ );
+ if (existing.bankReferenceNumber && savedObs.bankReferenceNumber && String(existing.bankReferenceNumber).trim() === String(savedObs.bankReferenceNumber).trim()) {
+ this.obsRepo.db.execute(`
+ UPDATE payment_observations
+ SET attribution_status = ?
+ WHERE id = ?
+ `, [ObservationAttributionStatus.ATTRIBUTED, savedObs.id]);
+ } else {
+ this.obsRepo.markAttributed(savedObs.id, existing.attributedPaymentId);
+ }
+ } catch (dbErr) {
+ const errMsg = dbErr?.message || '';
+ if (errMsg.includes('UNIQUE constraint failed') || errMsg.includes('duplicate key value') || errMsg.includes('idx_observations_unique_attributed_bank_ref') || errMsg.includes('idx_payment_sessions_attributed_obs')) {
+ return {
+ attributed: false,
+ duplicate: true,
+ lateMatch: false,
+ observationId: savedObs.id,
+ outcomeStatus: 'REFERENCE_ALREADY_USED'
+ };
+ }
+ throw dbErr;
+ }
if (this.auditRepo) {
this.auditRepo.log({
@@ -265,7 +288,7 @@ export class AttributionEngine {
SELECT ps.id, ps.order_id
FROM payment_sessions ps
JOIN payment_observations po ON (ps.attributed_observation_id = po.id OR po.attributed_payment_id = ps.id)
- WHERE ps.status = 'SUCCESS'
+ WHERE ps.status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED')
AND ps.id != ?
AND po.bank_reference_number = ?
LIMIT 1
@@ -330,13 +353,49 @@ export class AttributionEngine {
this.pendingGraceTimers.delete(currentSession.id);
// Second source confirmed within 5-second grace window -> LEVEL 2 DUAL VERIFICATION!
- const verifyResult = this.sessionRepo.recordVerificationSource(
- currentSession.id,
- normalizedObs.source,
- savedObs.id,
- { finalizeSuccess: true }
- );
- this.obsRepo.markAttributed(savedObs.id, currentSession.id);
+ let verifyResult;
+ try {
+ verifyResult = this.sessionRepo.recordVerificationSource(
+ currentSession.id,
+ normalizedObs.source,
+ savedObs.id,
+ { finalizeSuccess: true }
+ );
+
+ // Check if primary observation already holds the attributed bank_reference_number
+ const primaryObs = currentSession.attributedObservationId
+ ? this.obsRepo.findById(currentSession.attributedObservationId)
+ : null;
+ const sameUtrAsPrimary = Boolean(
+ primaryObs &&
+ primaryObs.bankReferenceNumber &&
+ savedObs.bankReferenceNumber &&
+ String(primaryObs.bankReferenceNumber).trim() === String(savedObs.bankReferenceNumber).trim()
+ );
+
+ if (!sameUtrAsPrimary) {
+ this.obsRepo.markAttributed(savedObs.id, currentSession.id);
+ } else {
+ // Secondary dual-verification observation corroborates existing attributed UTR
+ this.obsRepo.db.execute(`
+ UPDATE payment_observations
+ SET attribution_status = ?
+ WHERE id = ?
+ `, [ObservationAttributionStatus.ATTRIBUTED, savedObs.id]);
+ }
+ } catch (dbErr) {
+ const errMsg = dbErr?.message || '';
+ if (errMsg.includes('UNIQUE constraint failed') || errMsg.includes('duplicate key value') || errMsg.includes('idx_observations_unique_attributed_bank_ref') || errMsg.includes('idx_payment_sessions_attributed_obs')) {
+ return {
+ attributed: false,
+ duplicate: true,
+ lateMatch: false,
+ observationId: savedObs.id,
+ outcomeStatus: 'REFERENCE_ALREADY_USED'
+ };
+ }
+ throw dbErr;
+ }
if (this.auditRepo) {
this.auditRepo.log({
@@ -390,14 +449,42 @@ export class AttributionEngine {
// FIRST SOURCE CONFIRMATION:
// Record Level 1 verification source without immediate finalization (start 5-second grace window)
- const verifyResult = this.sessionRepo.recordVerificationSource(
- currentSession.id,
- normalizedObs.source,
- savedObs.id,
- { finalizeSuccess: false }
- );
+ let verifyResult;
+ try {
+ verifyResult = this.sessionRepo.recordVerificationSource(
+ currentSession.id,
+ normalizedObs.source,
+ savedObs.id,
+ { finalizeSuccess: false }
+ );
- this.obsRepo.markAttributed(savedObs.id, currentSession.id);
+ this.obsRepo.markAttributed(savedObs.id, currentSession.id);
+ } catch (dbErr) {
+ const errMsg = dbErr.message || '';
+ if (errMsg.includes('UNIQUE constraint failed') || errMsg.includes('duplicate key value') || errMsg.includes('idx_observations_unique_attributed_bank_ref') || errMsg.includes('idx_payment_sessions_attributed_obs')) {
+ if (this.auditRepo) {
+ this.auditRepo.log({
+ merchantId: currentSession.merchantId,
+ entityType: 'PAYMENT_SESSION',
+ entityId: currentSession.id,
+ action: 'REUSED_UTR_REJECTED',
+ actorType: 'SYSTEM',
+ details: {
+ bankReferenceNumber: trimmedUtr,
+ error: 'Concurrent UTR or observation attribution race prevented by database unique constraint.'
+ }
+ });
+ }
+ return {
+ attributed: false,
+ duplicate: true,
+ lateMatch: false,
+ observationId: savedObs.id,
+ outcomeStatus: 'REFERENCE_ALREADY_USED'
+ };
+ }
+ throw dbErr;
+ }
if (this.auditRepo) {
this.auditRepo.log({
diff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.js
index c97f198..9c0fa66 100644
--- a/packages/core/src/verification-pipeline.js
+++ b/packages/core/src/verification-pipeline.js
@@ -268,9 +268,15 @@ export class PaymentVerificationPipeline {
`, [observedVpa]);
if (row) session = this.sessionRepo.mapRow(row);
}
- // 3. There is deliberately NO gateway-wide fallback. An observation that cannot be tied
- // to a specific receiving account must not be attributed to whichever session happens
- // to be in flight on another merchant's VPA.
+ // 3. Check for recently completed session on this receiving account for dual verification upgrade
+ if (!session && input.receivingAccountId) {
+ const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();
+ const row = this.db.queryOne(
+ `SELECT * FROM payment_sessions WHERE receiving_account_id = ? AND status = 'SUCCESS' AND completed_at >= ? ORDER BY completed_at DESC LIMIT 1`,
+ [input.receivingAccountId, sixtySecsAgo]
+ );
+ if (row) session = this.sessionRepo.mapRow(row);
+ }
}
let customer = null;
@@ -729,7 +735,16 @@ export class PaymentVerificationPipeline {
// 4. Duplicate Check
const receivingAccountId = session.receivingAccountId || input.receivingAccountId || '00000000-0000-0000-0000-000000000002';
- const observerSourceEnum = source === 'GMAIL' ? ObserverSource.GMAIL : ObserverSource.SMS_GATEWAY;
+ let observerSourceEnum;
+ if (isGmailSource) {
+ observerSourceEnum = ObserverSource.GMAIL;
+ } else if (rawNormalizedSource === ObserverSource.GOOGLE_MESSAGES) {
+ observerSourceEnum = ObserverSource.GOOGLE_MESSAGES;
+ } else if (rawNormalizedSource === ObserverSource.ANDROID_OBSERVER) {
+ observerSourceEnum = ObserverSource.ANDROID_OBSERVER;
+ } else {
+ observerSourceEnum = ObserverSource.SMS_GATEWAY;
+ }
const fingerprint = calculateObservationFingerprint({
receivingAccountId,
amountPaise: parsedData.amountPaise,
diff --git a/packages/db/src/__tests__/schema-parity.test.js b/packages/db/src/__tests__/schema-parity.test.js
index 0d434d9..785be8d 100644
--- a/packages/db/src/__tests__/schema-parity.test.js
+++ b/packages/db/src/__tests__/schema-parity.test.js
@@ -76,8 +76,10 @@ describe('Database Schema Parity & Integrity (Postgres vs SQLite) (#13)', () =>
'idx_payment_sessions_device',
'idx_single_active_session_per_order',
'idx_one_slot_per_receiving_account',
+ 'idx_payment_sessions_attributed_obs',
'idx_observations_match',
'idx_observations_bank_ref',
+ 'idx_observations_unique_attributed_bank_ref',
'idx_observations_fingerprint',
'idx_observations_attributed_payment',
'idx_webhook_deliveries_retry',
diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.js
index d671f91..51d16f9 100644
--- a/packages/db/src/migrate.js
+++ b/packages/db/src/migrate.js
@@ -110,7 +110,9 @@ export function runMigrations(targetDb) {
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_payment_sessions_device ON payment_sessions (device_id);"); } catch {}
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_payment_sessions_attributed_obs ON payment_sessions (attributed_observation_id) WHERE attributed_observation_id IS NOT NULL;"); } catch {}
try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);"); } catch {}
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_observations_unique_attributed_bank_ref ON payment_observations (bank_reference_number) WHERE bank_reference_number IS NOT NULL AND attributed_payment_id IS NOT NULL;"); } 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 {}
diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sql
index a9f38e3..2610b61 100644
--- a/packages/db/src/schema.sql
+++ b/packages/db/src/schema.sql
@@ -134,6 +134,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order
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;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_payment_sessions_attributed_obs
+ ON payment_sessions (attributed_observation_id)
+ WHERE attributed_observation_id IS NOT NULL;
-- 5. Payment Observations Table
CREATE TABLE IF NOT EXISTS payment_observations (
@@ -154,6 +157,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 UNIQUE INDEX IF NOT EXISTS idx_observations_unique_attributed_bank_ref
+ ON payment_observations (bank_reference_number)
+ WHERE bank_reference_number IS NOT NULL AND attributed_payment_id IS NOT NULL;
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);
diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sql
index 95220e8..faec951 100644
--- a/packages/db/src/sqlite-schema.sql
+++ b/packages/db/src/sqlite-schema.sql
@@ -137,6 +137,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order
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;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_payment_sessions_attributed_obs
+ ON payment_sessions (attributed_observation_id)
+ WHERE attributed_observation_id IS NOT NULL;
-- 5. Payment Observations Table
CREATE TABLE IF NOT EXISTS payment_observations (
@@ -157,6 +160,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 UNIQUE INDEX IF NOT EXISTS idx_observations_unique_attributed_bank_ref
+ ON payment_observations (bank_reference_number)
+ WHERE bank_reference_number IS NOT NULL AND attributed_payment_id IS NOT NULL;
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);