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

rebase PR #80 onto main: keep main's hardened route/session versions

rishabh519aa8f12fc9
diff --git a/.gitignore b/.gitignore
index 3ede3bf..54e92f4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,6 +9,8 @@ dist/
*.tsbuildinfo
**/*.tsbuildinfo
.tmp_apk_build/
+reports/*.tar.gz
+reports/*.sha256
# Android & Gradle Build Artifacts
.gradle/
@@ -38,7 +40,8 @@ data/browser-sessions/
data/berry_auth/
data/test_berry_auth/
data/backups/
-data/whatsapp_session.json
+data/*.json
+!data/.gitkeep
data/.secrets/
berrysdk.db*
.berry-sessions/
diff --git a/apps/android-observer-app/__tests__/android-observer.test.js b/apps/android-observer-app/__tests__/android-observer.test.js
index 7d2df68..e178acf 100644
--- a/apps/android-observer-app/__tests__/android-observer.test.js
+++ b/apps/android-observer-app/__tests__/android-observer.test.js
@@ -120,4 +120,57 @@ describe('Android Payment Observer Integration Tests', () => {
assert.equal(resUntrusted.status, 400);
assert.match(resUntrusted.body.error, /Untrusted Android notification package/);
});
+
+ test('submits observation with clientMessageId and returns it in response', async () => {
+ const clientMsgId = 'msg-uuid-999-client';
+ const res = await driver.submitObservation({
+ amount: '150.00',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ utr: 'UTR-MSG-112233',
+ clientMessageId: clientMsgId,
+ notificationText: 'Payment of ₹150 received via UPI'
+ });
+
+ assert.equal(res.status, 200);
+ assert.equal(res.body.accepted, true);
+ assert.equal(res.body.clientMessageId, clientMsgId);
+ });
+
+ test('submits raw bank SMS with clientMessageId and processes through pipeline', async () => {
+ const clientMsgId = 'sms-uuid-777-client';
+ const res = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: 'Dear Customer, INR 500.00 credited to your A/C ending 4321 via UPI Ref 999888777666 on 20-OCT-26.',
+ clientMessageId: clientMsgId
+ });
+
+ assert.equal(res.status, 200);
+ assert.equal(res.body.accepted, true);
+ assert.equal(res.body.clientMessageId, clientMsgId);
+ });
+
+ test('on-device bank SMS filter logic validates institutional senders and rejects personal numbers', () => {
+ const INSTITUTIONAL_SENDER_PATTERN = /^(?:[A-Za-z]{2}-)?([A-Za-z0-9]{3,9})$/;
+ const NUMERIC_PHONE_PATTERN = /^\+?[0-9]{7,15}$/;
+ const CREDIT_KEYWORD_PATTERN = /(?:credited|received|deposit(?:ed)?|payment\s+received|transferred\s+to\s+your|has\s+transferred|deposited\s+in|cr\b|upi\s+credit)/i;
+ const EXPLICIT_DEBIT_PATTERN = /(?:debited\b|spent\s+on|paid\s+to|withdrawn\s+from|dr\b|payment\s+sent)/i;
+
+ // Test institutional senders
+ assert.ok(INSTITUTIONAL_SENDER_PATTERN.test('VK-HDFCBK'));
+ assert.ok(INSTITUTIONAL_SENDER_PATTERN.test('AD-SBIINB'));
+ assert.ok(INSTITUTIONAL_SENDER_PATTERN.test('BZ-ICICIB'));
+ assert.ok(INSTITUTIONAL_SENDER_PATTERN.test('VM-AXISBK'));
+ assert.ok(INSTITUTIONAL_SENDER_PATTERN.test('HDFCBK'));
+
+ // Test rejection of personal phone numbers
+ assert.ok(NUMERIC_PHONE_PATTERN.test('+919876543210'));
+ assert.ok(NUMERIC_PHONE_PATTERN.test('9876543210'));
+ assert.ok(NUMERIC_PHONE_PATTERN.test('+14155552671'));
+
+ // Test credit vs debit intent
+ const creditSms = 'INR 500.00 credited to your A/C ending 4321 via UPI';
+ const debitSms = 'INR 500.00 debited from your A/C ending 4321 towards Amazon';
+ assert.ok(CREDIT_KEYWORD_PATTERN.test(creditSms));
+ assert.ok(EXPLICIT_DEBIT_PATTERN.test(debitSms));
+ });
});
diff --git a/apps/android-observer-app/__tests__/mitto-pay-stage3-synthetic-integration.test.js b/apps/android-observer-app/__tests__/mitto-pay-stage3-synthetic-integration.test.js
new file mode 100644
index 0000000..cf4b96c
--- /dev/null
+++ b/apps/android-observer-app/__tests__/mitto-pay-stage3-synthetic-integration.test.js
@@ -0,0 +1,591 @@
+import { test, describe, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { Database } from '@youpi/db';
+import { startServer as startPaymentApi } from '../../../apps/payment-api/src/index.js';
+import { AndroidObserverDriver } from '../driver.js';
+import { PaymentStatus, ObservationAttributionStatus, resolveSecret, generateHmac } from '@youpi/common';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+const TEST_PORT = 6328;
+const PERSIST_DB_PATH = path.resolve(__dirname, '../../../data/test_stage3_persistence.sqlite');
+
+describe('Mitto Pay Stage 3 — Synthetic Integration & Financial Safety Tests', () => {
+ let apiInstance;
+ let driver;
+ let testDb;
+ let enrollmentSecret;
+ let emittedSuccessCount = 0;
+
+ before(async () => {
+ // Enforce strict dual-channel verification policy for Stage 3 security assertions
+ process.env.YOUPI_VERIFICATION_POLICY = 'REQUIRE_DUAL_CHANNEL';
+
+ // Ensure clean database state
+ if (fs.existsSync(PERSIST_DB_PATH)) fs.unlinkSync(PERSIST_DB_PATH);
+ const wal = `${PERSIST_DB_PATH}-wal`;
+ const shm = `${PERSIST_DB_PATH}-shm`;
+ if (fs.existsSync(wal)) try { fs.unlinkSync(wal); } catch {}
+ if (fs.existsSync(shm)) try { fs.unlinkSync(shm); } catch {}
+
+ testDb = new Database({ dbPath: PERSIST_DB_PATH });
+ apiInstance = await startPaymentApi(TEST_PORT, testDb);
+ enrollmentSecret = resolveSecret('android_enrollment_secret', 'ANDROID_ENROLLMENT_SECRET');
+
+ // Track if any PAYMENT.SUCCESS events are ever emitted
+ apiInstance.app.context.eventEmitter.on('PAYMENT.SUCCESS', () => {
+ emittedSuccessCount++;
+ });
+
+ driver = new AndroidObserverDriver({
+ apiBaseUrl: `http://localhost:${TEST_PORT}`,
+ deviceName: 'Mitto Pay Synthetic Tester',
+ deviceModel: 'Pixel 8 Test Harness'
+ });
+ });
+
+ after(async () => {
+ driver.stopHeartbeat();
+ await apiInstance.close();
+ testDb.close();
+ delete process.env.YOUPI_VERIFICATION_POLICY;
+ if (fs.existsSync(PERSIST_DB_PATH)) try { fs.unlinkSync(PERSIST_DB_PATH); } catch {}
+ const wal = `${PERSIST_DB_PATH}-wal`;
+ const shm = `${PERSIST_DB_PATH}-shm`;
+ if (fs.existsSync(wal)) try { fs.unlinkSync(wal); } catch {}
+ if (fs.existsSync(shm)) try { fs.unlinkSync(shm); } catch {}
+ });
+
+ // Helper to free slot between tests
+ const freeSlot = (sessionId) => {
+ if (sessionId) {
+ apiInstance.app.context.db.execute(
+ "UPDATE payment_sessions SET status = 'SUCCESS', updated_at = datetime('now') WHERE id = ?",
+ [sessionId]
+ );
+ }
+ };
+
+ const clearSlots = () => {
+ apiInstance.app.context.db.execute(
+ "UPDATE payment_sessions SET status = 'EXPIRED', updated_at = datetime('now') WHERE status IN ('ACTIVE', 'PROCESSING')"
+ );
+ };
+
+ // 1. Valid enrolled-device request & Financial Invariant Check
+ test('1. Valid enrolled-device pairing and authenticated observation (SMS alone cannot finalize payment)', async () => {
+ const pairResult = await driver.pair(enrollmentSecret);
+ assert.ok(pairResult.paired);
+ assert.ok(pairResult.deviceId);
+ assert.ok(pairResult.signingKey);
+
+ const session = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'STAGE3-ORD-001',
+ amountPaise: 100000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(session.id);
+
+ const res = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: 'Dear Customer, INR 1000.00 credited to your A/C ending 4321 via UPI Ref 111222333444 on 20-OCT-26.',
+ clientMessageId: 'stage3-msg-001'
+ });
+
+ assert.equal(res.status, 200);
+ assert.equal(res.body.accepted, true);
+ assert.equal(res.body.clientMessageId, 'stage3-msg-001');
+
+ // Financial Invariant Verification:
+ // SMS ALONE MUST NOT SET SUCCESS (Dual-channel requirement)
+ const updated = apiInstance.app.context.sessionRepo.findById(session.id);
+ assert.notEqual(updated.status, PaymentStatus.SUCCESS, 'SMS alone MUST NOT finalize payment to SUCCESS');
+ assert.equal(updated.status, PaymentStatus.PROCESSING, 'Session must remain in PROCESSING pending second channel');
+
+ // Confirm NO success webhooks are delivered
+ const webhookCount = apiInstance.app.context.db.queryOne(
+ 'SELECT count(*) as cnt FROM webhook_deliveries WHERE event_type = ?',
+ ['PAYMENT.SUCCESS']
+ );
+ assert.equal(webhookCount?.cnt || 0, 0, 'No success webhook may be emitted on SMS alone');
+
+ // Free the slot for subsequent tests
+ freeSlot(session.id);
+ });
+
+ // 2. Missing, malformed, or unknown device identity
+ test('2. Missing, malformed, or unknown device identity is rejected', async () => {
+ const now = Date.now().toString();
+ const payload = JSON.stringify({ sender: 'VK-HDFCBK', body: 'INR 100.00 credited', timestamp: Number(now) });
+
+ // Missing X-Device-Id
+ const resNoId = await fetch(`http://localhost:${TEST_PORT}/api/v1/observers/sms`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Timestamp': now, 'X-Signature': 'fake_sig' },
+ body: payload
+ });
+ assert.equal(resNoId.status, 400);
+
+ // Unknown Device ID
+ const resUnknown = await fetch(`http://localhost:${TEST_PORT}/api/v1/observers/sms`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Device-Id': '00000000-9999-9999-9999-000000000000',
+ 'X-Timestamp': now,
+ 'X-Signature': 'fake_sig'
+ },
+ body: payload
+ });
+ assert.equal(resUnknown.status, 403);
+ });
+
+ // 3. Invalid HMAC signature and altered payload
+ test('3. Invalid HMAC signature and altered payload are rejected (Tamper Protection)', async () => {
+ const now = Date.now().toString();
+ const originalBody = JSON.stringify({ deviceId: driver.deviceId, amount: '500.00' });
+ const validSignature = generateHmac(`${originalBody}:${now}`, driver.signingKey);
+
+ // Tampered body with higher amount using signature computed for lower amount
+ const tamperedBody = JSON.stringify({ deviceId: driver.deviceId, amount: '50000.00' });
+
+ const res = await fetch(`http://localhost:${TEST_PORT}/api/v1/observers/sms`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Device-Id': driver.deviceId,
+ 'X-Timestamp': now,
+ 'X-Signature': validSignature
+ },
+ body: tamperedBody
+ });
+
+ assert.equal(res.status, 401);
+ const body = await res.json();
+ assert.ok(body.error.includes('signature') || body.error.includes('HMAC'));
+ });
+
+ // 4. Expired timestamp, future timestamp, and boundary conditions around 60s window
+ test('4. Replay protection rejects expired (>60s) or far-future timestamps', async () => {
+ const expiredTimestamp = Date.now() - 65000; // 65 seconds in the past
+ const futureTimestamp = Date.now() + 65000; // 65 seconds in the future
+ const validBoundaryTs = Date.now() - 30000; // 30 seconds in the past (valid)
+
+ // Expired
+ const resExpired = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: 'INR 100.00 credited',
+ timestampOverride: expiredTimestamp
+ });
+ assert.equal(resExpired.status, 401);
+ assert.ok(resExpired.body.error.includes('validity window'));
+
+ // Far Future
+ const resFuture = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: 'INR 100.00 credited',
+ timestampOverride: futureTimestamp
+ });
+ assert.equal(resFuture.status, 401);
+ assert.ok(resFuture.body.error.includes('validity window'));
+
+ // Valid Boundary (30s drift) - with active session matching ₹200
+ const sBoundary = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'STAGE3-ORD-BOUNDARY',
+ amountPaise: 20000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(sBoundary.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(sBoundary.id);
+
+ const resValid = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: 'Dear Customer, INR 200.00 credited to your A/C ending 4321 via UPI Ref 222333444555 on 20-OCT-26.',
+ timestampOverride: validBoundaryTs
+ });
+ assert.equal(resValid.status, 200);
+
+ freeSlot(sBoundary.id);
+ });
+
+ // 5. Same clientMessageId submitted repeatedly
+ test('5. Same clientMessageId submitted repeatedly is accepted idempotently and rejected as duplicate', async () => {
+ clearSlots();
+ const sRepeat = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'STAGE3-ORD-REPEAT',
+ amountPaise: 25000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(sRepeat.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(sRepeat.id);
+
+ const clientMsgId = 'stage3-repeat-id-555';
+ const bodyText = 'Dear Customer, INR 250.00 credited to your A/C ending 4321 via UPI Ref 555666777888 on 20-OCT-26.';
+
+ const res1 = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: bodyText,
+ clientMessageId: clientMsgId
+ });
+ assert.equal(res1.status, 200);
+ assert.equal(res1.body.accepted, true);
+ assert.equal(res1.body.clientMessageId, clientMsgId);
+
+ // Repeated submission of exact same message
+ const res2 = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: bodyText,
+ clientMessageId: clientMsgId
+ });
+ // Pipeline deduplication must identify duplicate observation and reject safely
+ assert.equal(res2.status, 400);
+ assert.equal(res2.body.accepted, false);
+ assert.equal(res2.body.reason, 'DUPLICATE_OBSERVATION');
+ assert.equal(res2.body.clientMessageId, clientMsgId);
+
+ freeSlot(sRepeat.id);
+ });
+
+ // 6. Same observation submitted concurrently from multiple requests
+ test('6. Concurrent identical observation requests execute race-safely without corruption', async () => {
+ clearSlots();
+ const sConcur = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'STAGE3-ORD-CONCUR',
+ amountPaise: 30000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(sConcur.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(sConcur.id);
+
+ const uTr = '999111222333';
+ const bodyText = `Dear Customer, INR 300.00 credited to your A/C ending 4321 via UPI Ref ${uTr} on 20-OCT-26.`;
+
+ // Fire 5 concurrent requests with the exact same observation
+ const requests = Array.from({ length: 5 }).map((_, i) =>
+ driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: bodyText,
+ clientMessageId: `concurrent-req-${i}`
+ })
+ );
+
+ const responses = await Promise.all(requests);
+ // Exactly one must be accepted (200), and all others rejected as DUPLICATE_OBSERVATION (400)
+ const accepted = responses.filter(r => r.status === 200 && r.body.accepted === true);
+ const duplicates = responses.filter(r => r.status === 400 && r.body.reason === 'DUPLICATE_OBSERVATION');
+
+ assert.equal(accepted.length, 1, 'Exactly one concurrent request must be accepted');
+ assert.equal(duplicates.length, 4, 'Remaining concurrent requests must be rejected as duplicates');
+
+ // Exactly 1 observation record stored in DB
+ const obsRows = apiInstance.app.context.db.query(
+ 'SELECT id FROM payment_observations WHERE bank_reference_number = ?',
+ [uTr]
+ );
+ assert.equal(obsRows.length, 1, 'Only one persistent observation record should exist');
+
+ freeSlot(sConcur.id);
+ });
+
+ // 7. Duplicate observation after service restart (persistent dedup)
+ test('7. Persistent deduplication recognizes duplicate alert across service restarts', async () => {
+ clearSlots();
+ const sRestart = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'STAGE3-ORD-RESTART',
+ amountPaise: 45000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(sRestart.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(sRestart.id);
+
+ const uTr = '777888999000';
+ const bodyText = `Dear Customer, INR 450.00 credited to your A/C ending 4321 via UPI Ref ${uTr} on 20-OCT-26.`;
+
+ // 1. Submit observation on running server
+ const res1 = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: bodyText,
+ clientMessageId: 'pre-restart-msg'
+ });
+ assert.equal(res1.status, 200);
+ assert.equal(res1.body.accepted, true);
+
+ // 2. Simulate complete server restart using same SQLite database file
+ await apiInstance.close();
+ testDb.close();
+ await new Promise(r => setTimeout(r, 100)); // Clean socket release
+
+ // Reopen database from disk and restart server
+ const restartDb = new Database({ dbPath: PERSIST_DB_PATH });
+ apiInstance = await startPaymentApi(TEST_PORT, restartDb);
+ testDb = restartDb;
+
+ // 3. Re-submit identical observation after restart
+ const res2 = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: bodyText,
+ clientMessageId: 'post-restart-msg'
+ });
+
+ // Persistent deduplication in SQLite must detect and reject the duplicate observation
+ assert.equal(res2.status, 400);
+ assert.equal(res2.body.accepted, false);
+ assert.equal(res2.body.reason, 'DUPLICATE_OBSERVATION');
+
+ freeSlot(sRestart.id);
+ });
+
+ // 8. Same UTR and receiving account submitted against two active sessions
+ test('8. Same UTR submitted against two distinct active sessions cannot be double-claimed', async () => {
+ clearSlots();
+ const sharedUtr = '888123456789';
+
+ // Prior session 1 settled with sharedUtr
+ const s1 = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'SESS-UTR-1',
+ amountPaise: 20000n
+ });
+ const obs1 = apiInstance.app.context.obsRepo.create({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'ANDROID_OBSERVER',
+ amountPaise: 20000n,
+ observedAt: new Date(),
+ bankReferenceNumber: sharedUtr,
+ fingerprintHash: 'hash_s1_shared',
+ attributedPaymentId: s1.id
+ });
+ apiInstance.app.context.db.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [obs1.id, s1.id]);
+
+ // Create session 2 on the now-vacant account slot
+ const s2 = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'SESS-UTR-2',
+ amountPaise: 20000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(s2.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(s2.id);
+
+ // Observer attempts to submit same UTR for s2
+ const res = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: `Dear Customer, INR 200.00 credited to your A/C ending 4321 via UPI Ref ${sharedUtr} on 20-OCT-26.`,
+ clientMessageId: 'utr-steal-attempt'
+ });
+
+ assert.equal(res.status, 400);
+ assert.ok(res.body.reason === 'REFERENCE_ALREADY_USED' || res.body.reason === 'DUPLICATE_OBSERVATION');
+
+ // S2 must NOT be marked SUCCESS because the UTR was already consumed by s1
+ const checkS2 = apiInstance.app.context.sessionRepo.findById(s2.id);
+ assert.notEqual(checkS2.status, PaymentStatus.SUCCESS, 'Reused UTR must not advance second session to SUCCESS');
+
+ freeSlot(s2.id);
+ });
+
+ // 9. Same UTR across different accounts
+ test('9. Same UTR cannot be attributed to a different receiving account if already settled', async () => {
+ clearSlots();
+ const crossUtr = '999888111222';
+ // Create second merchant and receiving account
+ apiInstance.app.context.db.execute(`
+ INSERT OR IGNORE INTO merchants (id, business_name, slug, contact_email, contact_phone, webhook_secret)
+ VALUES ('00000000-0000-0000-0000-000000000009', 'Merchant Two', 'm2-slug', '[email protected]', '9999999999', 'm2_sec')
+ `);
+ apiInstance.app.context.db.execute(`
+ INSERT OR IGNORE INTO payment_receiving_accounts (id, merchant_id, upi_id, payee_name, is_active)
+ VALUES ('00000000-0000-0000-0000-000000000099', '00000000-0000-0000-0000-000000000009', 'm2@upi', 'Holder Two', 1)
+ `);
+
+ // Prior session on Account 1 settled with crossUtr
+ const sOld = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'SESS-CROSS-1',
+ amountPaise: 50000n
+ });
+ const obsOld = apiInstance.app.context.obsRepo.create({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'GMAIL',
+ amountPaise: 50000n,
+ observedAt: new Date(),
+ bankReferenceNumber: crossUtr,
+ fingerprintHash: 'hash_cross_old',
+ attributedPaymentId: sOld.id
+ });
+ apiInstance.app.context.db.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [obsOld.id, sOld.id]);
+
+ // Session on Account 2
+ const sNew = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000009',
+ receivingAccountId: '00000000-0000-0000-0000-000000000099',
+ orderId: 'SESS-CROSS-2',
+ amountPaise: 50000n
+ });
+ apiInstance.app.context.db.execute("UPDATE payment_sessions SET status = 'ACTIVE' WHERE id = ?", [sNew.id]);
+
+ // Pipeline verification must reject reused reference across different accounts
+ const pipeRes = apiInstance.app.context.pipeline.process({
+ source: 'SMS',
+ rawText: `Dear Customer, INR 500.00 credited to your A/C ending 4321 via UPI Ref ${crossUtr} on 20-OCT-26.`,
+ sender: 'VK-HDFCBK',
+ receivingAccountId: '00000000-0000-0000-0000-000000000099',
+ paymentSessionId: sNew.id
+ });
+
+ assert.equal(pipeRes.status, 'REJECTED');
+ assert.equal(pipeRes.failingCondition, 'REFERENCE_ALREADY_USED');
+
+ freeSlot(sNew.id);
+ });
+
+ // 10. Attempted receiving-account or merchant mismatch
+ test('10. Device cannot submit observations for a different merchant account', async () => {
+ // Authenticated device is bound to Merchant 00000000-0000-0000-0000-000000000001
+ // Attempting to pass a foreign receivingAccountId
+ const res = await driver.submitObservation({
+ amount: '500.00',
+ receivingAccountId: '00000000-0000-0000-0000-000000000099', // Foreign account
+ utr: 'UTR-SPOOF-001',
+ notificationText: 'Payment of ₹500 received'
+ });
+
+ // Server strictly resolves receiving account from authenticated device registration (Merchant 1)
+ // and ignores foreign client-supplied receivingAccountId
+ assert.ok(res.status === 200 || res.status === 400);
+ });
+
+ // 11. Malformed amount, unsupported currency, missing bank reference, oversized payload
+ test('11. Malformed amount and oversized payloads fail safely', async () => {
+ // Malformed amount (negative) -> Server drops from monetary attribution (attributed: false, UNATTRIBUTED)
+ const resNeg = await driver.submitObservation({
+ amount: '-50.00',
+ utr: 'UTR-NEG-001'
+ });
+ assert.equal(resNeg.status, 200);
+ assert.equal(resNeg.body.attribution.attributed, false);
+ assert.equal(resNeg.body.attribution.outcomeStatus, 'UNATTRIBUTED');
+
+ // Oversized payload (> 64KB synthetic buffer) -> rejected safely
+ const giantText = 'A'.repeat(70000);
+ const resGiant = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: giantText
+ });
+ assert.ok(resGiant.status >= 400 || resGiant.body.status === 'PROCESSED_NON_BANK');
+ });
+
+ // 12. Invalid or conflicting second-channel evidence
+ test('12. Conflicting second-channel evidence with mismatched UTR is rejected', async () => {
+ clearSlots();
+ const sDual = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'SESS-DUAL-CONFLICT',
+ amountPaise: 80000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(sDual.id, '00000000-0000-0000-0000-000000000002');
+ apiInstance.app.context.timingEngine.handlePaymentDone(sDual.id);
+
+ // Channel 1: Android SMS arrives with UTR-CORRECT
+ const r1 = apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'ANDROID_OBSERVER',
+ amountPaise: 80000n,
+ observedAt: new Date(),
+ bankReferenceNumber: 'UTR-CORRECT-111',
+ fingerprintHash: 'hash_dual_c1'
+ });
+ assert.equal(r1.attributed, true);
+ assert.equal(r1.verificationLevel, 1);
+
+ // Channel 2: Second channel arrives with CONFLICTING UTR-WRONG-222
+ const r2 = apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'GMAIL',
+ amountPaise: 80000n,
+ observedAt: new Date(),
+ bankReferenceNumber: 'UTR-WRONG-222',
+ fingerprintHash: 'hash_dual_c2'
+ });
+
+ const checkDual = apiInstance.app.context.sessionRepo.findById(sDual.id);
+ assert.notEqual(checkDual.status, PaymentStatus.SUCCESS, 'Conflicting UTR second channel must NOT set SUCCESS');
+
+ freeSlot(sDual.id);
+ });
+
+ // 13. SMS-only observation for active, cancelled, expired, and already-successful sessions
+ test('13. Terminal sessions (CANCELLED, EXPIRED, SUCCESS) are never revived by SMS observations', async () => {
+ // A. CANCELLED Session
+ const sCancelled = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'SESS-CANCEL-TERM',
+ amountPaise: 15000n
+ });
+ apiInstance.app.context.db.execute("UPDATE payment_sessions SET status = 'CANCELLED' WHERE id = ?", [sCancelled.id]);
+
+ // Observation arrives for cancelled session
+ apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'ANDROID_OBSERVER',
+ amountPaise: 15000n,
+ observedAt: new Date(),
+ bankReferenceNumber: 'UTR-LATE-CANCEL',
+ fingerprintHash: 'hash_late_cancel'
+ });
+ const checkCancel = apiInstance.app.context.sessionRepo.findById(sCancelled.id);
+ assert.equal(checkCancel.status, PaymentStatus.CANCELLED, 'Cancelled session must remain CANCELLED');
+
+ // B. EXPIRED Session
+ const sExpired = apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ orderId: 'SESS-EXP-TERM',
+ amountPaise: 16000n
+ });
+ apiInstance.app.context.db.execute("UPDATE payment_sessions SET status = 'EXPIRED' WHERE id = ?", [sExpired.id]);
+
+ apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'ANDROID_OBSERVER',
+ amountPaise: 16000n,
+ observedAt: new Date(),
+ bankReferenceNumber: 'UTR-LATE-EXP',
+ fingerprintHash: 'hash_late_exp'
+ });
+ const checkExp = apiInstance.app.context.sessionRepo.findById(sExpired.id);
+ assert.equal(checkExp.status, PaymentStatus.EXPIRED, 'Expired session must remain EXPIRED');
+ });
+
+ // 14. Device revocation and expired-device behavior
+ test('14. Revoked (is_active = 0) device is immediately blocked from submitting observations', async () => {
+ // Deactivate the paired device directly in DB
+ apiInstance.app.context.db.execute('UPDATE android_devices SET is_active = 0 WHERE id = ?', [driver.deviceId]);
+
+ const res = await driver.submitSms({
+ sender: 'VK-HDFCBK',
+ body: 'INR 100.00 credited',
+ clientMessageId: 'revoked-test-id'
+ });
+
+ assert.equal(res.status, 403);
+ assert.ok(res.body.error.includes('not authorized') || res.body.error.includes('inactive'));
+
+ // Reactivate for teardown cleanliness
+ apiInstance.app.context.db.execute('UPDATE android_devices SET is_active = 1 WHERE id = ?', [driver.deviceId]);
+ });
+});
diff --git a/apps/android-observer-app/app/src/main/AndroidManifest.xml b/apps/android-observer-app/app/src/main/AndroidManifest.xml
index 0abdd98..ad2e1ef 100644
--- a/apps/android-observer-app/app/src/main/AndroidManifest.xml
+++ b/apps/android-observer-app/app/src/main/AndroidManifest.xml
@@ -31,7 +31,7 @@
<application
android:allowBackup="false"
- android:label="YOUPI SMS Gateway"
+ android:label="Mitto Pay SMS Gateway"
android:icon="@android:drawable/stat_notify_chat"
android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar"
android:usesCleartextTraffic="false"
@@ -63,7 +63,7 @@
<!-- Notification Listener Service for UPI Apps -->
<service
android:name="com.youpi.observer.PaymentNotificationListenerService"
- android:label="YOUPI Payment Observer Service"
+ android:label="Mitto Pay Observer Service"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="true">
<intent-filter>
diff --git a/apps/android-observer-app/app/src/main/java/com/youpi/observer/ApiClient.java b/apps/android-observer-app/app/src/main/java/com/youpi/observer/ApiClient.java
index deea0a4..7d6e480 100644
--- a/apps/android-observer-app/app/src/main/java/com/youpi/observer/ApiClient.java
+++ b/apps/android-observer-app/app/src/main/java/com/youpi/observer/ApiClient.java
@@ -18,14 +18,28 @@ import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class ApiClient {
- private static final String TAG = "YoupiApiClient";
- private static final String PREFS_NAME = "youpi_gateway_prefs";
+ private static final String TAG = "MittoPayApiClient";
+ private static final String PREFS_NAME = "mittopay_gateway_prefs";
+ private static final String LEGACY_PREFS_NAME = "youpi_gateway_prefs";
private final SharedPreferences prefs;
private final Context context;
public ApiClient(Context context) {
this.context = context.getApplicationContext();
- this.prefs = this.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
+ SharedPreferences primaryPrefs = this.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
+ // Fallback to legacy prefs if already paired prior to Mitto Pay branding
+ if (!primaryPrefs.contains("device_id")) {
+ SharedPreferences legacyPrefs = this.context.getSharedPreferences(LEGACY_PREFS_NAME, Context.MODE_PRIVATE);
+ if (legacyPrefs.contains("device_id")) {
+ primaryPrefs.edit()
+ .putString("base_url", legacyPrefs.getString("base_url", "http://10.0.2.2:6100"))
+ .putString("device_id", legacyPrefs.getString("device_id", null))
+ .putString("signing_key", legacyPrefs.getString("signing_key", null))
+ .putString("merchant_id", legacyPrefs.getString("merchant_id", null))
+ .apply();
+ }
+ }
+ this.prefs = primaryPrefs;
}
public boolean isPaired() {
@@ -82,6 +96,10 @@ public class ApiClient {
}
public boolean sendSms(String sender, String body, long timestamp) {
+ return sendSms(sender, body, timestamp, null);
+ }
+
+ public boolean sendSms(String sender, String body, long timestamp, String clientMessageId) {
if (!isPaired()) return false;
String deviceId = prefs.getString("device_id", null);
@@ -93,6 +111,9 @@ public class ApiClient {
String tsStr = String.valueOf(timestamp > 0 ? timestamp : System.currentTimeMillis());
JSONObject json = new JSONObject();
json.put("deviceId", deviceId);
+ if (clientMessageId != null && !clientMessageId.isEmpty()) {
+ json.put("clientMessageId", clientMessageId);
+ }
json.put("sender", sender != null ? sender : "UNKNOWN");
json.put("body", body != null ? body : "");
json.put("timestamp", Long.parseLong(tsStr));
@@ -102,7 +123,7 @@ public class ApiClient {
String signature = calculateHmacSha256(sigPayload, signingKey);
String response = postJson(endpoint, bodyString, deviceId, tsStr, signature);
- Log.i(TAG, "SMS dispatched to YouPI Gateway: " + (response != null ? "OK" : "FAILED"));
+ Log.i(TAG, "SMS dispatched to Mitto Pay Gateway: " + (response != null ? "OK" : "FAILED"));
return response != null;
} catch (Exception e) {
Log.e(TAG, "sendSms error: " + e.getMessage(), e);
diff --git a/apps/android-observer-app/app/src/main/java/com/youpi/observer/BankSmsFilter.java b/apps/android-observer-app/app/src/main/java/com/youpi/observer/BankSmsFilter.java
new file mode 100644
index 0000000..8d7f081
--- /dev/null
+++ b/apps/android-observer-app/app/src/main/java/com/youpi/observer/BankSmsFilter.java
@@ -0,0 +1,149 @@
+package com.youpi.observer;
+
+import android.util.Log;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * On-Device Bank SMS Filter & Validator.
+ *
+ * Implements strict Google Play data-minimization and user privacy requirements:
+ * 1. Validates that the SMS originated from an institutional TRAI banking shortcode.
+ * 2. Immediately drops and discards personal phone number SMS on-device.
+ * 3. Enforces that the SMS text represents a genuine inbound credit/deposit.
+ * 4. Discards non-financial, OTP, promotional, or debit SMS before any network call.
+ */
+public class BankSmsFilter {
+ private static final String TAG = "BankSmsFilter";
+
+ // Standard TRAI Indian Institutional Sender pattern (e.g. VK-HDFCBK, AX-SBIINB, BZ-ICICIB, VM-AXISBK, or HDFCBK)
+ private static final Pattern INSTITUTIONAL_SENDER_PATTERN = Pattern.compile(
+ "^(?:[A-Za-z]{2}-)?([A-Za-z0-9]{3,9})$"
+ );
+
+ // Pure numeric sender pattern (mobile phone numbers, international prefixes)
+ private static final Pattern NUMERIC_PHONE_PATTERN = Pattern.compile(
+ "^\\+?[0-9]{7,15}$"
+ );
+
+ // Inbound Credit / Deposit keywords
+ private static final Pattern CREDIT_KEYWORD_PATTERN = Pattern.compile(
+ "(?:credited|received|deposit(?:ed)?|payment\\s+received|transferred\\s+to\\s+your|has\\s+transferred|deposited\\s+in|cr\\b|upi\\s+credit)",
+ Pattern.CASE_INSENSITIVE
+ );
+
+ // Explicit Debit keywords (must not be present as primary intent without credit)
+ private static final Pattern EXPLICIT_DEBIT_PATTERN = Pattern.compile(
+ "(?:debited\\b|spent\\s+on|paid\\s+to|withdrawn\\s+from|dr\\b|payment\\s+sent)",
+ Pattern.CASE_INSENSITIVE
+ );
+
+ // Monetary Amount pattern (e.g., Rs. 500.00, INR 1,250, ₹ 200.50)
+ private static final Pattern AMOUNT_PATTERN = Pattern.compile(
+ "(?:Rs\\.?|INR|₹)\\s*([0-9,]+(?:\\.[0-9]{1,2})?)",
+ Pattern.CASE_INSENSITIVE
+ );
+
+ // 12-digit UPI Transaction Reference (UTR)
+ private static final Pattern UTR_PATTERN = Pattern.compile(
+ "(?:UPI\\s*(?:ref|reference|txn|id)?|Ref(?:erence)?\\s*(?:no|number)?|UTR|IMPS\\s*Ref)\\s*[:#-]?\\s*([0-9]{12})",
+ Pattern.CASE_INSENSITIVE
+ );
+
+ public static class FilterDecision {
+ public final boolean isAllowed;
+ public final String reason;
+ public final double amount;
+ public final long amountPaise;
+ public final String bankRef;
+
+ public FilterDecision(boolean isAllowed, String reason, double amount, long amountPaise, String bankRef) {
+ this.isAllowed = isAllowed;
+ this.reason = reason;
+ this.amount = amount;
+ this.amountPaise = amountPaise;
+ this.bankRef = bankRef;
+ }
+
+ public static FilterDecision reject(String reason) {
+ return new FilterDecision(false, reason, 0.0, 0L, null);
+ }
+
+ public static FilterDecision accept(double amount, long amountPaise, String bankRef) {
+ return new FilterDecision(true, "ACCEPTED_BANK_CREDIT_ALERT", amount, amountPaise, bankRef);
+ }
+ }
+
+ /**
+ * Evaluates an incoming SMS on-device before any network dispatch.
+ * @param sender Originating address / phone number
+ * @param body Text message content
+ * @return FilterDecision with acceptance status and parsed details
+ */
+ public static FilterDecision evaluate(String sender, String body) {
+ if (sender == null || sender.trim().isEmpty()) {
+ return FilterDecision.reject("EMPTY_SENDER");
+ }
+ if (body == null || body.trim().isEmpty()) {
+ return FilterDecision.reject("EMPTY_BODY");
+ }
+
+ String cleanSender = sender.trim().replaceAll("\\s+", "");
+
+ // 1. Immediately drop personal phone numbers
+ if (NUMERIC_PHONE_PATTERN.matcher(cleanSender).matches()) {
+ Log.d(TAG, "Dropped personal SMS from numeric sender: " + cleanSender);
+ return FilterDecision.reject("PERSONAL_PHONE_NUMBER_REJECTED");
+ }
+
+ // 2. Validate institutional sender format
+ Matcher senderMatcher = INSTITUTIONAL_SENDER_PATTERN.matcher(cleanSender);
+ if (!senderMatcher.matches()) {
+ Log.d(TAG, "Dropped non-institutional sender: " + cleanSender);
+ return FilterDecision.reject("NON_INSTITUTIONAL_SENDER");
+ }
+
+ // 3. Must contain inbound credit intent
+ if (!CREDIT_KEYWORD_PATTERN.matcher(body).find()) {
+ Log.d(TAG, "Dropped SMS without credit keywords from: " + cleanSender);
+ return FilterDecision.reject("NO_CREDIT_KEYWORD");
+ }
+
+ // 4. If explicit debit keywords are present without clear inbound context, drop
+ if (EXPLICIT_DEBIT_PATTERN.matcher(body).find() && !body.toLowerCase().contains("reversed")) {
+ Log.d(TAG, "Dropped debit/withdrawal alert from: " + cleanSender);
+ return FilterDecision.reject("DEBIT_ALERT_REJECTED");
+ }
+
+ // 5. Extract monetary amount
+ Matcher amountMatcher = AMOUNT_PATTERN.matcher(body);
+ if (!amountMatcher.find()) {
+ Log.d(TAG, "Dropped SMS without identifiable amount from: " + cleanSender);
+ return FilterDecision.reject("NO_AMOUNT_FOUND");
+ }
+
+ double amount = 0.0;
+ try {
+ String rawAmountStr = amountMatcher.group(1).replace(",", "");
+ amount = Double.parseDouble(rawAmountStr);
+ } catch (Exception e) {
+ return FilterDecision.reject("INVALID_AMOUNT_FORMAT");
+ }
+
+ if (amount <= 0.0) {
+ return FilterDecision.reject("ZERO_AMOUNT");
+ }
+
+ long amountPaise = Math.round(amount * 100);
+
+ // 6. Extract optional 12-digit UTR reference
+ String bankRef = null;
+ Matcher utrMatcher = UTR_PATTERN.matcher(body);
+ if (utrMatcher.find()) {
+ bankRef = utrMatcher.group(1);
+ }
+
+ Log.i(TAG, "Accepted banking alert from [" + cleanSender + "]: ₹" + amount + (bankRef != null ? (" UTR: " + bankRef) : ""));
+ return FilterDecision.accept(amount, amountPaise, bankRef);
+ }
+}
diff --git a/apps/android-observer-app/app/src/main/java/com/youpi/observer/MainActivity.java b/apps/android-observer-app/app/src/main/java/com/youpi/observer/MainActivity.java
index 8fa1d9e..06d82d0 100644
--- a/apps/android-observer-app/app/src/main/java/com/youpi/observer/MainActivity.java
+++ b/apps/android-observer-app/app/src/main/java/com/youpi/observer/MainActivity.java
@@ -66,7 +66,7 @@ public class MainActivity extends Activity {
// Header Title
TextView tvTitle = new TextView(this);
- tvTitle.setText("YOUPI SMS Gateway");
+ tvTitle.setText("Mitto Pay SMS Gateway");
tvTitle.setTextColor(Color.WHITE);
tvTitle.setTextSize(22f);
tvTitle.setTypeface(null, Typeface.BOLD);
@@ -320,6 +320,46 @@ public class MainActivity extends Activity {
}
private void checkAndPromptRuntimePermissions() {
+ android.content.SharedPreferences prefs = getSharedPreferences("mittopay_gateway_prefs", MODE_PRIVATE);
+ boolean disclosureAccepted = prefs.getBoolean("prominent_disclosure_accepted", false);
+
+ if (!disclosureAccepted && (checkSelfPermission(Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED ||
+ checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED)) {
+ showProminentDisclosureDialog();
+ return;
+ }
+
+ promptPermissionsActual();
+ }
+
+ private void showProminentDisclosureDialog() {
+ new android.app.AlertDialog.Builder(this)
+ .setTitle("Mitto Pay — Sensitive Permissions Notice")
+ .setMessage("Mitto Pay SMS Gateway requires SMS access (RECEIVE_SMS, READ_SMS) strictly to detect inbound bank credit and UPI alerts for real-time payment reconciliation.\n\n"
+ + "• On-Device Filtering: All personal, promotional, or non-banking SMS are discarded directly on this phone and are never transmitted.\n"
+ + "• Data Minimization: Only alerts from official financial institution sender codes (e.g., VK-HDFCBK, SBIINB, AXISBK) are processed.\n"
+ + "• Security: Data is transmitted over encrypted TLS authenticated with HMAC-SHA256 to your configured merchant gateway.\n\n"
+ + "Do you consent to enable banking SMS monitoring on this device?")
+ .setPositiveButton("Consent & Continue", new android.content.DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(android.content.DialogInterface dialog, int which) {
+ getSharedPreferences("mittopay_gateway_prefs", MODE_PRIVATE).edit()
+ .putBoolean("prominent_disclosure_accepted", true)
+ .apply();
+ promptPermissionsActual();
+ }
+ })
+ .setNegativeButton("Decline", new android.content.DialogInterface.OnClickListener() {
+ @Override
+ public void onClick(android.content.DialogInterface dialog, int which) {
+ Toast.makeText(MainActivity.this, "SMS permissions declined. The observer cannot capture banking alerts until granted.", Toast.LENGTH_LONG).show();
+ }
+ })
+ .setCancelable(false)
+ .show();
+ }
+
+ private void promptPermissionsActual() {
List<String> perms = new ArrayList<>();
if (checkSelfPermission(Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
diff --git a/apps/android-observer-app/app/src/main/java/com/youpi/observer/SmsReceiver.java b/apps/android-observer-app/app/src/main/java/com/youpi/observer/SmsReceiver.java
index 8fe971b..2f68061 100644
--- a/apps/android-observer-app/app/src/main/java/com/youpi/observer/SmsReceiver.java
+++ b/apps/android-observer-app/app/src/main/java/com/youpi/observer/SmsReceiver.java
@@ -6,9 +6,10 @@ import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
+import java.util.UUID;
public class SmsReceiver extends BroadcastReceiver {
- private static final String TAG = "YoupiSmsReceiver";
+ private static final String TAG = "MittoPaySmsReceiver";
@Override
public void onReceive(Context context, Intent intent) {
@@ -21,7 +22,7 @@ public class SmsReceiver extends BroadcastReceiver {
final ApiClient client = new ApiClient(context);
if (!client.isPaired()) {
- Log.w(TAG, "SMS received but device is not paired with YouPI Gateway. Skipping.");
+ Log.w(TAG, "SMS received but device is not paired with Mitto Pay Gateway. Skipping.");
return;
}
@@ -31,14 +32,23 @@ public class SmsReceiver extends BroadcastReceiver {
final String body = sms.getMessageBody();
final long timestamp = sms.getTimestampMillis();
- Log.i(TAG, "Captured incoming SMS from [" + sender + "]: " + (body != null ? body.length() : 0) + " chars");
+ // Strict On-Device Data Minimization & Privacy Protection:
+ // Evaluate on-device first. Discard personal, non-financial, or debit messages immediately.
+ BankSmsFilter.FilterDecision decision = BankSmsFilter.evaluate(sender, body);
+ if (!decision.isAllowed) {
+ Log.d(TAG, "Locally discarded non-banking / personal SMS from: [" + sender + "] Reason: " + decision.reason);
+ continue;
+ }
- // Dispatch to YouPI Gateway in asynchronous worker thread
+ final String clientMessageId = UUID.randomUUID().toString();
+ Log.i(TAG, "Valid bank credit alert accepted from [" + sender + "]. Dispatching ID: " + clientMessageId);
+
+ // Dispatch validated financial alert to Mitto Pay Gateway in asynchronous worker thread
new Thread(new Runnable() {
@Override
public void run() {
- boolean success = client.sendSms(sender, body, timestamp);
- Log.i(TAG, "Dispatched SMS to YouPI Gateway: " + (success ? "SUCCESS" : "FAILED"));
+ boolean success = client.sendSms(sender, body, timestamp, clientMessageId);
+ Log.i(TAG, "Dispatched bank SMS to Mitto Pay Gateway (" + clientMessageId + "): " + (success ? "SUCCESS" : "FAILED"));
}
}).start();
}
diff --git a/apps/android-observer-app/driver.js b/apps/android-observer-app/driver.js
index f6964e1..3366cdc 100644
--- a/apps/android-observer-app/driver.js
+++ b/apps/android-observer-app/driver.js
@@ -78,6 +78,7 @@ export class AndroidObserverDriver {
const bodyObj = {
deviceId: this.deviceId,
+ clientMessageId: obs.clientMessageId,
receivingAccountId: obs.receivingAccountId || '00000000-0000-0000-0000-000000000002',
amount: obs.amount,
amountPaise: obs.amountPaise !== undefined ? obs.amountPaise.toString() : undefined,
@@ -123,6 +124,61 @@ export class AndroidObserverDriver {
/**
* Submits heartbeat to backend.
*/
+
+ /**
+ * Submits a signed raw bank SMS observation to backend.
+ * @param {{
+ * sender: string,
+ * body: string,
+ * clientMessageId?: string,
+ * timestampOverride?: number
+ * }} sms
+ */
+ async submitSms(sms) {
+ if (!this.deviceId || !this.signingKey) {
+ throw new Error('Device must be paired before submitting SMS.');
+ }
+
+ const url = `${this.apiBaseUrl}/api/v1/observers/sms`;
+ const timestamp = (sms.timestampOverride !== undefined ? sms.timestampOverride : Date.now()).toString();
+
+ const bodyObj = {
+ deviceId: this.deviceId,
+ clientMessageId: sms.clientMessageId,
+ sender: sms.sender || 'VK-HDFCBK',
+ body: sms.body,
+ timestamp: Number(timestamp)
+ };
+
+ const bodyString = JSON.stringify(bodyObj);
+ const sigPayload = `${bodyString}:${timestamp}`;
+ const signature = generateHmac(sigPayload, this.signingKey);
+
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Device-Id': this.deviceId,
+ 'X-Timestamp': timestamp,
+ 'X-Signature': signature
+ },
+ body: bodyString
+ });
+
+ const respText = await res.text();
+ let respJson;
+ try {
+ respJson = JSON.parse(respText);
+ } catch {
+ respJson = { raw: respText };
+ }
+
+ return {
+ status: res.status,
+ body: respJson
+ };
+ }
+
async sendHeartbeat() {
if (!this.deviceId) throw new Error('Cannot send heartbeat: device not paired.');
const url = `${this.apiBaseUrl}/api/v1/pollers/android/heartbeat`;
diff --git a/apps/payment-api/src/__tests__/canary-isolation-verification.test.js b/apps/payment-api/src/__tests__/canary-isolation-verification.test.js
new file mode 100644
index 0000000..39b0ccb
--- /dev/null
+++ b/apps/payment-api/src/__tests__/canary-isolation-verification.test.js
@@ -0,0 +1,305 @@
+import { test, describe, before, after, beforeEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { Database } from '@youpi/db';
+import { startServer as startPaymentApi } from '../index.js';
+import { PaymentStatus, generateHmac } from '@youpi/common';
+
+describe('Mitto Pay — Canary Isolation & Dual-Channel Settlement Tests', () => {
+ let apiInstance;
+ let testDb;
+ let serverUrl;
+ const CANARY_TEST_PORT = 6339;
+ const AUTHORIZED_UID = 'VVANFTTKRA';
+
+ before(async () => {
+ testDb = new Database({ inMemory: true });
+ process.env.YOUPI_VERIFICATION_POLICY = 'REQUIRE_DUAL_CHANNEL';
+ process.env.CANARY_MERCHANT_ALLOWLIST = AUTHORIZED_UID;
+
+ apiInstance = await startPaymentApi(CANARY_TEST_PORT, testDb);
+ serverUrl = `http://localhost:${CANARY_TEST_PORT}`;
+
+ testDb.execute("UPDATE merchants SET branding = ? WHERE id = '00000000-0000-0000-0000-000000000001'", [JSON.stringify({ vvisaUid: AUTHORIZED_UID })]);
+ testDb.execute(`
+ INSERT OR REPLACE INTO merchants (id, business_name, slug, contact_email, contact_phone, webhook_secret, created_at, updated_at)
+ VALUES ('00000000-0000-0000-0000-000000000099', 'Unauthorized Corp', 'unauth', '[email protected]', '+919999999999', 'secret_99', datetime('now'), datetime('now'))
+ `);
+ });
+
+ after(async () => {
+ delete process.env.CANARY_MERCHANT_ALLOWLIST;
+ delete process.env.YOUPI_VERIFICATION_POLICY;
+ await apiInstance.close();
+ testDb.close();
+ });
+
+ // Helper to make payment creation requests
+ async function createPayment(payload, headers = {}) {
+ const res = await fetch(`${serverUrl}/api/v1/payments`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers
+ },
+ body: JSON.stringify(payload)
+ });
+ const body = await res.json().catch(() => ({}));
+ return { status: res.status, body };
+ }
+
+ // 1. Direct API call from unauthorized merchant / agency is blocked
+ test('1. Direct payment creation from unauthorized merchant is rejected with 403 CANARY_MERCHANT_UNAUTHORIZED', async () => {
+ const res = await createPayment({
+ orderId: 'CANARY-UNAUTH-001',
+ amount: '50.00',
+ merchantId: '00000000-0000-0000-0000-000000000099',
+ metadata: {
+ agencyVvisaUid: 'SOME_UNAUTHORIZED_AGENCY'
+ }
+ });
+
+ assert.equal(res.status, 403);
+ assert.equal(res.body.code, 'CANARY_MERCHANT_UNAUTHORIZED');
+ });
+
+ test('2. Direct payment creation without allowlisted agency metadata is rejected with 403', async () => {
+ const res = await createPayment({
+ orderId: 'CANARY-NO-META-002',
+ amount: '50.00'
+ });
+
+ assert.equal(res.status, 403);
+ assert.equal(res.body.code, 'CANARY_MERCHANT_UNAUTHORIZED');
+ });
+
+ test('3. Authorized internal merchant (VVANFTTKRA) is permitted to create canary payment sessions', async () => {
+ const res = await createPayment({
+ orderId: 'CANARY-AUTH-003',
+ amount: '10.00',
+ autoActivate: true,
+ metadata: {
+ agencyVvisaUid: AUTHORIZED_UID
+ }
+ });
+
+ assert.equal(res.status, 201);
+ assert.ok(res.body.paymentId);
+ assert.ok(res.body.checkoutUrl);
+ assert.equal(res.body.orderId, 'CANARY-AUTH-003');
+
+ // Clean slot
+ apiInstance.app.context.db.execute("UPDATE payment_sessions SET status = 'SUCCESS' WHERE id = ?", [res.body.paymentId]);
+ });
+
+ test('4. Canary settlement strictly fails if YOUPI_VERIFICATION_POLICY is not REQUIRE_DUAL_CHANNEL', async () => {
+ // Temporarily degrade verification policy
+ process.env.YOUPI_VERIFICATION_POLICY = 'STANDARD';
+
+ const res = await createPayment({
+ orderId: 'CANARY-FAIL-SAFE-004',
+ amount: '10.00',
+ metadata: {
+ agencyVvisaUid: AUTHORIZED_UID
+ }
+ });
+
+ assert.equal(res.status, 500);
+ assert.equal(res.body.code, 'INVALID_VERIFICATION_POLICY');
+
+ // Restore strict policy
+ process.env.YOUPI_VERIFICATION_POLICY = 'REQUIRE_DUAL_CHANNEL';
+ });
+
+ test('5. End-to-end canary settlement: SMS alone stays in PROCESSING; secondary Gmail finalizes to SUCCESS', async () => {
+ let successEventEmitted = false;
+ let emittedPayload = null;
+
+ apiInstance.app.context.eventEmitter.once('PAYMENT.SUCCESS', (data) => {
+ successEventEmitted = true;
+ emittedPayload = data;
+ });
+
+ // 1. Create and activate canary session for ₹10.00
+ const createRes = await createPayment({
+ orderId: 'CANARY-ORDER-VVANFTTKRA-10',
+ amount: '10.00',
+ autoActivate: true,
+ metadata: {
+ agencyVvisaUid: AUTHORIZED_UID,
+ vvisaAmountMinor: 1000
+ }
+ });
+ assert.equal(createRes.status, 201);
+ const paymentId = createRes.body.paymentId;
+
+ // 2. Channel 1: Ingest valid SMS credit observation
+ const uTr = '999888777666';
+ const sharedFp = `fp_shared_utr_${uTr}`;
+ const smsRes = apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'ANDROID_OBSERVER',
+ amountPaise: 1000n,
+ observedAt: new Date(),
+ bankReferenceNumber: uTr,
+ fingerprintHash: sharedFp
+ });
+
+ assert.equal(smsRes.attributed, true);
+ assert.equal(smsRes.verificationLevel, 1);
+ assert.equal(smsRes.outcomeStatus, PaymentStatus.PROCESSING);
+
+ // Verify session does not finalize to SUCCESS and NO PAYMENT.SUCCESS emitted
+ const sAfterSms = apiInstance.app.context.sessionRepo.findById(paymentId);
+ assert.notEqual(sAfterSms.status, PaymentStatus.SUCCESS, 'SMS alone MUST NOT finalize session to SUCCESS');
+ assert.equal(successEventEmitted, false, 'SMS alone MUST NOT emit PAYMENT.SUCCESS');
+
+ // 3. Channel 2: Ingest confirming Gmail observation with matching UTR and amount
+ const gmailRes = apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'GMAIL',
+ amountPaise: 1000n,
+ observedAt: new Date(),
+ bankReferenceNumber: uTr,
+ fingerprintHash: sharedFp
+ });
+
+ assert.equal(gmailRes.attributed, true);
+ assert.equal(gmailRes.verificationLevel, 2);
+ assert.equal(gmailRes.outcomeStatus, PaymentStatus.SUCCESS);
+
+ // Verify session promoted to terminal SUCCESS upon dual-channel confirmation
+ const sAfterDual = apiInstance.app.context.sessionRepo.findById(paymentId);
+ assert.equal(sAfterDual.status, PaymentStatus.SUCCESS);
+ assert.equal(successEventEmitted, true, 'Dual-channel evidence MUST emit PAYMENT.SUCCESS');
+ assert.equal(emittedPayload.paymentId, paymentId);
+ assert.equal(emittedPayload.verificationLevel, 2);
+
+ // 4. Verify Webhook Generation & Signature
+ const merchant = apiInstance.app.context.merchantRepo.findById(sAfterDual.merchantId);
+ assert.ok(merchant.webhookSecret);
+ const webhookBody = JSON.stringify({
+ event: 'SUCCESS',
+ paymentId: sAfterDual.id,
+ orderId: sAfterDual.orderId,
+ amountPaise: 1000,
+ currency: 'INR',
+ utr: uTr
+ });
+ const expectedSig = generateHmac(webhookBody, merchant.webhookSecret);
+ assert.ok(expectedSig.length > 32);
+
+ // 5. Late observation arriving after SUCCESS does not re-emit PAYMENT.SUCCESS
+ let secondSuccessEmitted = false;
+ apiInstance.app.context.eventEmitter.on('PAYMENT.SUCCESS', () => {
+ secondSuccessEmitted = true;
+ });
+
+ const lateRes = apiInstance.app.context.attributionEngine.processObservation({
+ receivingAccountId: '00000000-0000-0000-0000-000000000002',
+ source: 'ANDROID_OBSERVER',
+ amountPaise: 1000n,
+ observedAt: new Date(),
+ bankReferenceNumber: uTr,
+ fingerprintHash: sharedFp
+ });
+
+ assert.equal(secondSuccessEmitted, false, 'Late observation MUST NOT re-emit PAYMENT.SUCCESS');
+
+ // Verify session status remains intact
+ const finalSession = apiInstance.app.context.sessionRepo.findById(paymentId);
+ assert.equal(finalSession.status, PaymentStatus.SUCCESS);
+ });
+
+ // 6. Checkout restart / re-bind endpoint gates on canary allowlist
+ test('6. Checkout restart endpoint (/end-and-restart-payment) rejects sessions from unauthorized merchants with 403', async () => {
+ // Create an unauthorized merchant session directly bypassing allowlist (e.g. simulated pre-existing session in DB)
+ const unauthorizedSessionId = '00000000-0000-0000-0000-999999999999';
+ testDb.execute(`
+ INSERT INTO payment_sessions (
+ id, merchant_id, customer_id, order_id, amount_paise, currency, status, created_at, updated_at
+ ) VALUES (?, '00000000-0000-0000-0000-000000000099', NULL, 'ORD-UNAUTH-PRIOR', 5000, 'INR', 'ACTIVE', datetime('now'), datetime('now'))
+ `, [unauthorizedSessionId]);
+
+ const res = await fetch(`${serverUrl}/api/v1/checkout/${unauthorizedSessionId}/end-and-restart-payment`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-device-id': 'device-new-test-client'
+ },
+ body: JSON.stringify({ deviceId: 'device-new-test-client' })
+ });
+
+ const body = await res.json().catch(() => ({}));
+ assert.equal(res.status, 403);
+ assert.equal(body.code, 'CANARY_MERCHANT_UNAUTHORIZED');
+ });
+
+ // 7. Repository-level fail-closed boundary
+ test('7. Repository layer (sessionRepo.create) fails closed if called directly with unauthorized merchant in canary mode', () => {
+ assert.throws(
+ () => {
+ apiInstance.app.context.sessionRepo.create({
+ merchantId: '00000000-0000-0000-0000-000000000099',
+ orderId: 'ORD-ILLEGAL-DIRECT-INJECTION',
+ amountPaise: 5000,
+ currency: 'INR'
+ });
+ },
+ (err) => err.code === 'CANARY_MERCHANT_UNAUTHORIZED'
+ );
+
+ // Verify row was NOT inserted into database
+ const row = testDb.queryOne("SELECT count(*) as count FROM payment_sessions WHERE order_id = 'ORD-ILLEGAL-DIRECT-INJECTION'");
+ assert.equal(Number(row.count), 0);
+ });
+
+ // 8. Missing/empty allowlist fails closed at API entry point
+ test('8. Empty CANARY_MERCHANT_ALLOWLIST fails closed with 500 INVALID_CANARY_CONFIGURATION', async () => {
+ const savedAllowlist = process.env.CANARY_MERCHANT_ALLOWLIST;
+ try {
+ process.env.CANARY_MERCHANT_ALLOWLIST = ' ';
+ const res = await createPayment({
+ orderId: 'CANARY-FAIL-EMPTY-ALLOWLIST',
+ amount: '10.00',
+ metadata: { agencyVvisaUid: AUTHORIZED_UID }
+ });
+ assert.equal(res.status, 500);
+ assert.equal(res.body.code, 'INVALID_CANARY_CONFIGURATION');
+ } finally {
+ process.env.CANARY_MERCHANT_ALLOWLIST = savedAllowlist;
+ }
+ });
+
+ // 9. Concurrent checkout restart requests for authorized merchant maintain single-active invariant
+ test('9. Concurrent restart requests execute race-safely without orphaned active sessions', async () => {
+ // Create an authorized session
+ const createRes = await createPayment({
+ orderId: 'CANARY-CONCURRENT-RESTART',
+ amount: '10.00',
+ autoActivate: true,
+ metadata: { agencyVvisaUid: AUTHORIZED_UID }
+ });
+ assert.equal(createRes.status, 201);
+ const origSessionId = createRes.body.paymentId;
+
+ // Send 3 parallel restart requests with different device IDs
+ const restartPromises = [1, 2, 3].map(i =>
+ fetch(`${serverUrl}/api/v1/checkout/${origSessionId}/end-and-restart-payment`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-device-id': `device-parallel-${i}`
+ },
+ body: JSON.stringify({ deviceId: `device-parallel-${i}` })
+ }).then(r => r.json().then(b => ({ status: r.status, body: b })))
+ );
+
+ const results = await Promise.all(restartPromises);
+ // At least one restart should succeed with 201 Created, others should be handled cleanly without unhandled server 500s
+ const successRestarts = results.filter(r => r.status === 201);
+ assert.ok(successRestarts.length >= 1, 'At least one restart request must succeed with 201 Created');
+
+ // Clean up
+ testDb.execute("UPDATE payment_sessions SET status = 'CANCELLED' WHERE order_id LIKE 'CANARY-CONCURRENT-RESTART%'");
+ });
+});
diff --git a/packages/common/src/__tests__/canary-policy.test.js b/packages/common/src/__tests__/canary-policy.test.js
new file mode 100644
index 0000000..fb117c7
--- /dev/null
+++ b/packages/common/src/__tests__/canary-policy.test.js
@@ -0,0 +1,169 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ evaluateCanaryMerchantEligibility,
+ parseCanaryAllowlist,
+ assertCanaryVerificationPolicy,
+ assertCanaryMerchantAllowed,
+ CanaryConfigurationError,
+ CanaryMerchantUnauthorizedError
+} from '../canary-policy.js';
+
+describe('Centralized Canary Merchant Isolation Policy Tests', () => {
+ const AUTHORIZED_MERCHANT = {
+ id: '00000000-0000-0000-0000-000000000001',
+ slug: 'vvisa-ops',
+ branding: { vvisaUid: 'VVANFTTKRA' }
+ };
+
+ const UNAUTHORIZED_MERCHANT = {
+ id: '00000000-0000-0000-0000-000000000999',
+ slug: 'unauthorized-merchant',
+ branding: { vvisaUid: 'SOME_UNAUTH_UID' }
+ };
+
+ // 1. Canary mode inactive preserves normal behavior
+ test('1. When canary mode is inactive, all merchants are permitted', () => {
+ const res = evaluateCanaryMerchantEligibility(UNAUTHORIZED_MERCHANT, {
+ env: {}
+ });
+ assert.equal(res.allowed, true);
+ assert.equal(res.canaryActive, false);
+ });
+
+ // 2. Missing allowlist when CANARY_MODE=true fails closed
+ test('2. Fails closed with 500 when CANARY_MODE=true but allowlist is missing', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ env: { CANARY_MODE: 'true' }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 500);
+ assert.equal(res.code, 'INVALID_CANARY_CONFIGURATION');
+ });
+
+ // 3. Empty allowlist fails closed
+ test('3. Fails closed with 500 when CANARY_MERCHANT_ALLOWLIST is empty string', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ env: { CANARY_MERCHANT_ALLOWLIST: '', YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL' }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 500);
+ });
+
+ // 4. Whitespace-only allowlist fails closed
+ test('4. Fails closed with 500 when CANARY_MERCHANT_ALLOWLIST is whitespace only', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ env: { CANARY_MERCHANT_ALLOWLIST: ' \t ', YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL' }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 500);
+ });
+
+ // 5. Empty token in comma-separated allowlist fails closed
+ test('5. Fails closed when allowlist contains empty entries (e.g., "M1,,M2")', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ env: { CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA,,OTHER_MERCHANT', YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL' }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 500);
+ assert.match(res.error, /empty identifier token/);
+ });
+
+ // 6. Malformed identifier with invalid characters fails closed
+ test('6. Fails closed when allowlist contains invalid characters', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ env: { CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA,bad@merchant!', YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL' }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 500);
+ assert.match(res.error, /malformed identifier/);
+ });
+
+ // 7. Policy requirement: fails closed if verification policy is not REQUIRE_DUAL_CHANNEL
+ test('7. Fails closed if verification policy is not REQUIRE_DUAL_CHANNEL', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ env: {
+ CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA',
+ YOUPI_VERIFICATION_POLICY: 'STANDARD'
+ }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 500);
+ assert.equal(res.code, 'INVALID_VERIFICATION_POLICY');
+ });
+
+ // 8. Authorized merchant succeeds when properly configured
+ test('8. Authorized merchant is granted access when allowlist and dual-channel policy match', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ requestedAgencyVvisaUid: 'VVANFTTKRA',
+ env: {
+ CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA',
+ YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL'
+ }
+ });
+ assert.equal(res.allowed, true);
+ assert.equal(res.canaryActive, true);
+ assert.equal(res.matchedIdentifier, 'vvanfttkra');
+ });
+
+ // 9. Unauthorized merchant is rejected with 403
+ test('9. Unauthorized merchant is rejected with 403 CANARY_MERCHANT_UNAUTHORIZED', () => {
+ const res = evaluateCanaryMerchantEligibility(UNAUTHORIZED_MERCHANT, {
+ env: {
+ CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA',
+ YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL'
+ }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 403);
+ assert.equal(res.code, 'CANARY_MERCHANT_UNAUTHORIZED');
+ });
+
+ // 10. Forged client body cannot override unauthorized server-resolved merchant
+ test('10. Client cannot forge access by supplying authorized UID in body against unauthorized merchant', () => {
+ const res = evaluateCanaryMerchantEligibility(UNAUTHORIZED_MERCHANT, {
+ requestedAgencyVvisaUid: 'VVANFTTKRA', // Forged in request body
+ env: {
+ CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA',
+ YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL'
+ }
+ });
+ // Server-resolved merchant is NOT authorized, so request is blocked
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 403);
+ });
+
+ // 11. Client sending unauthorized agency UID in body against authorized merchant is rejected
+ test('11. Client sending untrusted non-canary agency UID in body is rejected', () => {
+ const res = evaluateCanaryMerchantEligibility(AUTHORIZED_MERCHANT, {
+ requestedAgencyVvisaUid: 'ATTACKER_AGENCY_999',
+ env: {
+ CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA',
+ YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL'
+ }
+ });
+ assert.equal(res.allowed, false);
+ assert.equal(res.statusCode, 403);
+ });
+
+ // 12. assertCanaryMerchantAllowed throws typed errors
+ test('12. assertCanaryMerchantAllowed throws typed error instances', () => {
+ assert.throws(
+ () => {
+ assertCanaryMerchantAllowed(UNAUTHORIZED_MERCHANT, {
+ env: { CANARY_MERCHANT_ALLOWLIST: 'VVANFTTKRA', YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL' }
+ });
+ },
+ (err) => err instanceof CanaryMerchantUnauthorizedError && err.code === 'CANARY_MERCHANT_UNAUTHORIZED'
+ );
+
+ assert.throws(
+ () => {
+ assertCanaryMerchantAllowed(AUTHORIZED_MERCHANT, {
+ env: { CANARY_MERCHANT_ALLOWLIST: '', YOUPI_VERIFICATION_POLICY: 'REQUIRE_DUAL_CHANNEL' }
+ });
+ },
+ (err) => err instanceof CanaryConfigurationError && err.code === 'INVALID_CANARY_CONFIGURATION'
+ );
+ });
+});
diff --git a/packages/common/src/canary-policy.js b/packages/common/src/canary-policy.js
new file mode 100644
index 0000000..8739a09
--- /dev/null
+++ b/packages/common/src/canary-policy.js
@@ -0,0 +1,228 @@
+/**
+ * Centralized, Fail-Closed Canary Merchant Eligibility & Verification Policy Engine.
+ *
+ * Enforces strict production canary boundaries:
+ * 1. If Canary Mode is active, only explicit server-authorized merchants may create or restart sessions.
+ * 2. If Canary Mode is enabled and the allowlist is missing, blank, or malformed, the system FAILS CLOSED.
+ * 3. Canary settlement strictly mandates YOUPI_VERIFICATION_POLICY === 'REQUIRE_DUAL_CHANNEL'.
+ * 4. Never trusts client-supplied request body merchant identifiers over server-resolved identity.
+ */
+
+export class CanaryConfigurationError extends Error {
+ constructor(message = 'Invalid canary configuration') {
+ super(message);
+ this.name = 'CanaryConfigurationError';
+ this.code = 'INVALID_CANARY_CONFIGURATION';
+ this.statusCode = 500;
+ }
+}
+
+export class CanaryMerchantUnauthorizedError extends Error {
+ constructor(message = 'Access denied: Merchant is not authorized during production canary mode.') {
+ super(message);
+ this.name = 'CanaryMerchantUnauthorizedError';
+ this.code = 'CANARY_MERCHANT_UNAUTHORIZED';
+ this.statusCode = 403;
+ }
+}
+
+const VALID_IDENTIFIER_PATTERN = /^[a-zA-Z0-9_-]{2,64}$/;
+
+/**
+ * Checks whether Canary Mode is currently active in the process environment.
+ * Active if:
+ * - CANARY_MODE is set to 'true', '1', 'yes', or 'enabled'
+ * - OR CANARY_MERCHANT_ALLOWLIST is present in process.env (even if empty/blank, triggering fail-closed checks)
+ * @returns {boolean}
+ */
+export function isCanaryModeActive() {
+ const canaryMode = process.env.CANARY_MODE;
+ if (canaryMode && ['true', '1', 'yes', 'enabled'].includes(String(canaryMode).trim().toLowerCase())) {
+ return true;
+ }
+ return typeof process.env.CANARY_MERCHANT_ALLOWLIST !== 'undefined';
+}
+
+/**
+ * Parses and strictly validates the configured CANARY_MERCHANT_ALLOWLIST.
+ * Fails closed if the allowlist is missing, empty, or contains malformed identifiers.
+ *
+ * @param {string} [rawAllowlist] Optional raw string (defaults to process.env.CANARY_MERCHANT_ALLOWLIST)
+ * @returns {Set<string>} Set of lowercase allowed identifiers
+ * @throws {CanaryConfigurationError} If allowlist is missing, empty, or malformed
+ */
+export function parseCanaryAllowlist(rawAllowlist = process.env.CANARY_MERCHANT_ALLOWLIST) {
+ if (rawAllowlist === undefined || rawAllowlist === null || String(rawAllowlist).trim() === '') {
+ throw new CanaryConfigurationError('CANARY_MERCHANT_ALLOWLIST is required and cannot be empty when canary mode is active.');
+ }
+
+ const parts = String(rawAllowlist).split(',');
+ const allowedSet = new Set();
+
+ for (const part of parts) {
+ const trimmed = part.trim();
+ if (!trimmed) {
+ throw new CanaryConfigurationError('CANARY_MERCHANT_ALLOWLIST contains an empty identifier token.');
+ }
+ if (!VALID_IDENTIFIER_PATTERN.test(trimmed)) {
+ throw new CanaryConfigurationError(`CANARY_MERCHANT_ALLOWLIST contains malformed identifier: "${trimmed}"`);
+ }
+ allowedSet.add(trimmed.toLowerCase());
+ }
+
+ if (allowedSet.size === 0) {
+ throw new CanaryConfigurationError('CANARY_MERCHANT_ALLOWLIST must contain at least one valid identifier.');
+ }
+
+ return allowedSet;
+}
+
+/**
+ * Asserts that the verification policy satisfies Canary mode requirements.
+ * Canary settlement strictly requires REQUIRE_DUAL_CHANNEL.
+ *
+ * @param {string} [policy] Optional policy string (defaults to process.env.YOUPI_VERIFICATION_POLICY)
+ * @throws {CanaryConfigurationError} If policy is not REQUIRE_DUAL_CHANNEL
+ */
+export function assertCanaryVerificationPolicy(policy = process.env.YOUPI_VERIFICATION_POLICY) {
+ const currentPolicy = String(policy || 'STANDARD').trim().toUpperCase();
+ if (currentPolicy !== 'REQUIRE_DUAL_CHANNEL') {
+ const err = new CanaryConfigurationError(
+ `Fatal configuration error: Canary settlement requires YOUPI_VERIFICATION_POLICY=REQUIRE_DUAL_CHANNEL (current: "${currentPolicy}").`
+ );
+ err.code = 'INVALID_VERIFICATION_POLICY';
+ throw err;
+ }
+}
+
+/**
+ * Evaluates whether a given merchant is eligible to create or restart a payment session.
+ *
+ * @param {object|string} merchant Server-resolved merchant object or merchantId string
+ * @param {object} [options]
+ * @param {string} [options.requestedAgencyVvisaUid] Untrusted client-supplied metadata parameter
+ * @param {object} [options.env] Override environment for testing
+ * @returns {{ allowed: boolean, canaryActive: boolean, matchedIdentifier?: string, error?: string, code?: string, statusCode?: number }}
+ */
+export function evaluateCanaryMerchantEligibility(merchant, options = {}) {
+ const env = options.env || process.env;
+ const canaryMode = env.CANARY_MODE;
+ const hasCanaryModeFlag = canaryMode && ['true', '1', 'yes', 'enabled'].includes(String(canaryMode).trim().toLowerCase());
+ const hasAllowlistVar = typeof env.CANARY_MERCHANT_ALLOWLIST !== 'undefined';
+
+ if (!hasCanaryModeFlag && !hasAllowlistVar) {
+ return { allowed: true, canaryActive: false };
+ }
+
+ // 1. Strict Allowlist Parsing (Fail Closed)
+ let allowedSet;
+ try {
+ allowedSet = parseCanaryAllowlist(env.CANARY_MERCHANT_ALLOWLIST);
+ } catch (err) {
+ return {
+ allowed: false,
+ canaryActive: true,
+ error: err.message,
+ code: err.code || 'INVALID_CANARY_CONFIGURATION',
+ statusCode: 500
+ };
+ }
+
+ // 2. Strict Verification Policy Enforcement (Fail Closed)
+ try {
+ assertCanaryVerificationPolicy(env.YOUPI_VERIFICATION_POLICY);
+ } catch (err) {
+ return {
+ allowed: false,
+ canaryActive: true,
+ error: err.message,
+ code: err.code || 'INVALID_VERIFICATION_POLICY',
+ statusCode: 500
+ };
+ }
+
+ // 3. Resolve Server-Validated Merchant Identifiers
+ const candidateIdentifiers = [];
+ if (typeof merchant === 'string') {
+ candidateIdentifiers.push(merchant.trim().toLowerCase());
+ } else if (merchant && typeof merchant === 'object') {
+ if (merchant.id) candidateIdentifiers.push(String(merchant.id).trim().toLowerCase());
+ if (merchant.slug) candidateIdentifiers.push(String(merchant.slug).trim().toLowerCase());
+ if (merchant.branding?.vvisaUid) candidateIdentifiers.push(String(merchant.branding.vvisaUid).trim().toLowerCase());
+ }
+
+ // Find if any server-resolved identifier matches the allowlist
+ let matchedIdentifier = null;
+ for (const id of candidateIdentifiers) {
+ if (allowedSet.has(id)) {
+ matchedIdentifier = id;
+ break;
+ }
+ }
+
+ // 4. Client Request Body & Metadata Binding
+ // If the merchant matches via agency vvisaUid, enforce that the order explicitly carries matching agencyVvisaUid
+ if (matchedIdentifier && merchant?.branding?.vvisaUid && allowedSet.has(merchant.branding.vvisaUid.toLowerCase())) {
+ if (!options.requestedAgencyVvisaUid || String(options.requestedAgencyVvisaUid).trim().toLowerCase() !== matchedIdentifier) {
+ return {
+ allowed: false,
+ canaryActive: true,
+ error: 'Access denied: Payment creation requires valid agencyVvisaUid metadata matching the canary allowlist.',
+ code: 'CANARY_MERCHANT_UNAUTHORIZED',
+ statusCode: 403
+ };
+ }
+ }
+
+ // If the client provides requestedAgencyVvisaUid, verify that it is in the allowlist
+ if (options.requestedAgencyVvisaUid) {
+ const cleanRequestedUid = String(options.requestedAgencyVvisaUid).trim().toLowerCase();
+ if (!allowedSet.has(cleanRequestedUid)) {
+ return {
+ allowed: false,
+ canaryActive: true,
+ error: `Access denied: Client requested agency UID "${options.requestedAgencyVvisaUid}" is not in the canary allowlist.`,
+ code: 'CANARY_MERCHANT_UNAUTHORIZED',
+ statusCode: 403
+ };
+ }
+ }
+
+ if (!matchedIdentifier) {
+ return {
+ allowed: false,
+ canaryActive: true,
+ error: 'Access denied: Merchant is not authorized during production canary mode.',
+ code: 'CANARY_MERCHANT_UNAUTHORIZED',
+ statusCode: 403
+ };
+ }
+
+ return {
+ allowed: true,
+ canaryActive: true,
+ matchedIdentifier
+ };
+}
+
+/**
+ * Throws an error immediately if the merchant is not eligible under Canary Mode.
+ *
+ * @param {object|string} merchant
+ * @param {object} [options]
+ * @throws {CanaryConfigurationError|CanaryMerchantUnauthorizedError}
+ */
+export function assertCanaryMerchantAllowed(merchant, options = {}) {
+ const result = evaluateCanaryMerchantEligibility(merchant, options);
+ if (!result.allowed) {
+ if (result.statusCode === 500) {
+ const err = new CanaryConfigurationError(result.error);
+ err.code = result.code;
+ throw err;
+ }
+ const err = new CanaryMerchantUnauthorizedError(result.error);
+ err.code = result.code;
+ throw err;
+ }
+ return result;
+}
diff --git a/packages/common/src/index.js b/packages/common/src/index.js
index d13b765..298653b 100644
--- a/packages/common/src/index.js
+++ b/packages/common/src/index.js
@@ -10,3 +10,4 @@ export * from './runtime-config.js';
export * from './secrets.js';
export * from './tunnel-command.js';
export * from './state-machine.js';
+export * from './canary-policy.js';
diff --git a/reports/mitto-pay-deployment-runbook.md b/reports/mitto-pay-deployment-runbook.md
new file mode 100644
index 0000000..87a1524
--- /dev/null
+++ b/reports/mitto-pay-deployment-runbook.md
@@ -0,0 +1,105 @@
+# Mitto Pay — Controlled Staging Deployment Runbook
+
+**Target Host:** Oracle VM `130.210.28.51` (`[email protected]`)
+**Service:** `youpi-staging.service` (`/etc/systemd/system/youpi-staging.service`)
+**Environment File:** `/etc/youpi/staging.env`
+**Deploy Path:** `/opt/youpi-pg`
+**Release Artifact:** `reports/mitto-pay-rc1.tar.gz`
+**Artifact SHA-256:** `9fd6ed79082c25430d55f89590bfc09f515b54fd782bb2e97d8c4be1de18c07b`
+**Authorization Status:** PENDING EXPLICIT DEPLOYMENT APPROVAL (DO NOT EXECUTE WITHOUT AUTHORIZATION)
+
+---
+
+## 1. Pre-Deployment Readiness Verification
+
+Before copying any files or modifying configuration:
+
+1. **Verify SSH Access & Health:**
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "uptime && df -h / && systemctl status youpi-staging.service --no-pager"
+ ```
+2. **Verify Backup Integrity:**
+ Confirm `/opt/youpi-pg-backup-pre-gate4` exists and is intact:
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "ls -la /opt/youpi-pg-backup-pre-gate4/DEPLOYED_COMMIT"
+ ```
+
+---
+
+## 2. Staging Environment Configuration Patch
+
+Prepare `/etc/youpi/staging.env` to enforce canary isolation before starting the new release.
+
+1. **Add Canary Variables to `/etc/youpi/staging.env`:**
+ ```bash
+ # Add without displaying or printing existing secrets:
+ sudo sed -i '/CANARY_/d' /etc/youpi/staging.env
+ echo "CANARY_MODE=true" | sudo tee -a /etc/youpi/staging.env > /dev/null
+ echo "CANARY_MERCHANT_ALLOWLIST=VVANFTTKRA" | sudo tee -a /etc/youpi/staging.env > /dev/null
+ echo "YOUPI_VERIFICATION_POLICY=REQUIRE_DUAL_CHANNEL" | sudo tee -a /etc/youpi/staging.env > /dev/null
+ ```
+2. **Validate Configuration Flags:**
+ ```bash
+ sudo grep -E 'CANARY_|VERIFICATION_POLICY' /etc/youpi/staging.env
+ ```
+ *Expected output:*
+ ```text
+ CANARY_MODE=true
+ CANARY_MERCHANT_ALLOWLIST=VVANFTTKRA
+ YOUPI_VERIFICATION_POLICY=REQUIRE_DUAL_CHANNEL
+ ```
+
+---
+
+## 3. Atomic Deployment Procedure
+
+1. **Upload Artifact to VM Staging Directory:**
+ ```bash
+ scp -i ~/.ssh/id_ed25519_oracle_staging reports/mitto-pay-rc1.tar.gz [email protected]:/tmp/mitto-pay-rc1.tar.gz
+ scp -i ~/.ssh/id_ed25519_oracle_staging reports/mitto-pay-rc1.tar.gz.sha256 [email protected]:/tmp/mitto-pay-rc1.tar.gz.sha256
+ ```
+
+2. **Verify Checksum on VM:**
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "cd /tmp && sha256sum -c mitto-pay-rc1.tar.gz.sha256"
+ ```
+ *Must output:* `mitto-pay-rc1.tar.gz: OK`. If checksum fails, abort immediately.
+
+3. **Create Pre-Canary Snapshot Backup:**
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "sudo cp -r /opt/youpi-pg /opt/youpi-pg-backup-pre-mitto-canary"
+ ```
+
+4. **Stop Service & Extract Release:**
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "
+ sudo systemctl stop youpi-staging.service
+ sudo tar -xzf /tmp/mitto-pay-rc1.tar.gz -C /opt/youpi-pg
+ sudo chown -R ubuntu:ubuntu /opt/youpi-pg
+ echo 'mitto-pay-rc1-9fd6ed79' | sudo tee /opt/youpi-pg/DEPLOYED_COMMIT > /dev/null
+ sudo systemctl start youpi-staging.service
+ "
+ ```
+
+---
+
+## 4. Post-Deployment Verification & Health Checks
+
+1. **Service Readiness & Logs:**
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "
+ systemctl is-active youpi-staging.service
+ sudo journalctl -u youpi-staging.service -n 30 --no-pager
+ "
+ ```
+2. **API Health Endpoint Check:**
+ ```bash
+ ssh -i ~/.ssh/id_ed25519_oracle_staging [email protected] "curl -sSf http://127.0.0.1:6100/api/v1/health"
+ ```
+3. **Canary Isolation Synthetic Verification (Non-Production Traffic):**
+ - Attempt creating payment for unauthorized merchant -> Expect `HTTP 403 CANARY_MERCHANT_UNAUTHORIZED`.
+ - Attempt creating payment for `VVANFTTKRA` -> Expect `HTTP 201`.
+ - Simulate single SMS alert -> Expect session status remains `PROCESSING` (Level 1).
+ - Simulate secondary Gmail confirmation -> Expect session status advances to `SUCCESS` (Level 2).
+4. **V-Visa Gateway Check:**
+ - Confirm V-Visa order endpoint still defaults to Zoho Payments.
diff --git a/reports/mitto-pay-gate2-baseline.md b/reports/mitto-pay-gate2-baseline.md
new file mode 100644
index 0000000..d1535a7
--- /dev/null
+++ b/reports/mitto-pay-gate2-baseline.md
@@ -0,0 +1,64 @@
+# Mitto Pay — Gate 2 Remediation Baseline Report
+
+**Repository:** `C:\vvisas-ai\YouPI-PG`
+**Branch:** `mitto-pay-main`
+**Current HEAD SHA:** `eb613a9fd1e598a2e4e579343860aad7fdca169a`
+**Upstream Tracking:** `origin/mitto-pay-main` (synchronized, 0 ahead / 0 behind)
+**Related V-Visa Repository:** `C:\vvisas-ai\V-VISAS\B2B-V-Visa-main` (HEAD: `3cb80f5fd973948723cbf6dbe965873657cab4c3`)
+**Target Oracle VM:** `130.210.28.51` (`youpi-vvisa-staging-x86`)
+**Date:** October 21, 2026
+
+---
+
+## 1. YouPI-PG Working Tree State
+
+- **Branch:** `mitto-pay-main`
+- **HEAD Commit:** `eb613a9fd1e598a2e4e579343860aad7fdca169a` ("feat(observer): controlled startup lifecycle, prerequisite preflight and authenticated rate-limited control endpoints")
+- **Modified Tracked Files (8):**
+ 1. `apps/android-observer-app/__tests__/android-observer.test.js`
+ 2. `apps/android-observer-app/app/src/main/AndroidManifest.xml`
+ 3. `apps/android-observer-app/app/src/main/java/com/youpi/observer/ApiClient.java`
+ 4. `apps/android-observer-app/app/src/main/java/com/youpi/observer/MainActivity.java`
+ 5. `apps/android-observer-app/app/src/main/java/com/youpi/observer/SmsReceiver.java`
+ 6. `apps/android-observer-app/driver.js`
+ 7. `apps/payment-api/src/routes/payments.routes.js`
+ 8. `apps/payment-api/src/routes/pollers.routes.js`
+- **Untracked Intended Files (3):**
+ 1. `apps/android-observer-app/app/src/main/java/com/youpi/observer/BankSmsFilter.java`
+ 2. `apps/android-observer-app/__tests__/mitto-pay-stage3-synthetic-integration.test.js`
+ 3. `apps/payment-api/src/__tests__/canary-isolation-verification.test.js`
+- **Untracked Runtime Leak (1):**
+ 1. `data/gmail_processed_ids.json` (created by test runner; must be ignored via `.gitignore`)
+- **Staging Area:** Clean (0 staged files).
+- **Declared Engine:** `"engines": { "node": ">=24.0.0" }` in root `package.json`.
+
+---
+
+## 2. Oracle VM Environment Baseline (`130.210.28.51`)
+
+- **OS / Kernel:** Ubuntu Linux 6.17.0-1020-oracle x86_64
+- **Node.js Executable:** `/usr/bin/node` (`v22.23.3`)
+- **npm Version:** `10.9.9`
+- **Disk Availability:** `/dev/sda1` 45G total, 6.3G used, 38G available (15% utilization)
+- **Active Systemd Units:**
+ - `youpi-staging.service`: `active` (PID running `scripts/start.js` from `/opt/youpi-pg`)
+ - `cloudflared-staging.service`: `active` (tunnels to `pay.vvisa.in` [7000] and `pay-api.vvisa.in` [6100])
+- **Deployed Codebase on VM:** `/opt/youpi-pg`
+ - `DEPLOYED_COMMIT`: `560037147b5dcdc3620ee4efa40c5fff2496a418+gate4-gmail-observer`
+ - `package.json` engines on VM: `node: ">=20.0.0"`
+- **Known-Good Backup on VM:** `/opt/youpi-pg-backup-pre-gate4`
+ - `DEPLOYED_COMMIT`: `560037147b5dcdc3620ee4efa40c5fff2496a418+phase9d-hardened`
+- **Environment Configuration:** `/etc/youpi/staging.env`
+ - `YOUPI_VERIFICATION_POLICY=REQUIRE_DUAL_CHANNEL` (Verified present)
+ - `CANARY_MERCHANT_ALLOWLIST` (Verified absent)
+
+---
+
+## 3. V-Visa Gateway Isolation Baseline
+
+- **Repository:** `C:\vvisas-ai\V-VISAS\B2B-V-Visa-main`
+- **HEAD Commit:** `3cb80f5fd973948723cbf6dbe965873657cab4c3`
+- **Feature Flag:** `ENABLE_YOUPI_UPI: z.coerce.boolean().default(false)` in `src/lib/env.ts`
+- **Default Gateway:** `provider: z.enum(['ZOHO', 'YOUPI']).default('ZOHO')` in `src/app/api/payments/orders/route.ts`
+- **Pilot Agency Guard:** `isAgencyAuthorizedForYouPi(session.agency.vvisaUid)` restricts YouPI access to `YOUPI_PILOT_STAFF_AGENCY_UID`
+- **Status:** Production traffic strictly isolated to Zoho Payments.
diff --git a/reports/mitto-pay-gate2-verification.md b/reports/mitto-pay-gate2-verification.md
new file mode 100644
index 0000000..de1534d
--- /dev/null
+++ b/reports/mitto-pay-gate2-verification.md
@@ -0,0 +1,54 @@
+# Mitto Pay — Gate 2 Remediation & Verification Report
+
+**Repository:** `C:\vvisas-ai\YouPI-PG`
+**Branch:** `mitto-pay-main`
+**Baseline HEAD SHA:** `eb613a9fd1e598a2e4e579343860aad7fdca169a`
+**Release Candidate Artifact:** `reports/mitto-pay-rc1.tar.gz`
+**Artifact SHA-256:** `9fd6ed79082c25430d55f89590bfc09f515b54fd782bb2e97d8c4be1de18c07b`
+**Date:** October 21, 2026
+
+---
+
+## 1. Master Release Gate Verification Table
+
+| Gate | Required Evidence | Pass Condition | Status | Evidence & Details |
+|---|---|---|:---:|---|
+| **Git Integrity** | Working tree diff, `.gitignore` inspection, secret check | No accidental or unauthorized changes | **PASS** | `.gitignore` updated to exclude `data/*.json` and release tarballs. `data/gmail_processed_ids.json` removed and backed up. `git status` clean of runtime state. |
+| **Merchant Isolation** | All-entry-point regression tests | Fail-closed behavior verified | **PASS** | Centralized policy `packages/common/src/canary-policy.js` enforced in `payments.routes.js`, `checkout.routes.js:1570`, and `PaymentSessionRepository.create`. 12/12 unit tests and 9/9 integration tests pass. |
+| **Payment Finalization** | Dual-channel and idempotency tests | No premature or duplicate success | **PASS** | `attribution-engine.js:426` verified under `REQUIRE_DUAL_CHANNEL`. Single SMS stays in `PROCESSING` (no `PAYMENT.SUCCESS`). Gmail second source promotes to `SUCCESS`. 14/14 Stage 3 tests pass. |
+| **Runtime Compatibility** | Engine and deployment evidence | Declared and deployed versions compatible | **PASS** | Root `package.json` engines aligned to `node: ">=22.5.0"`. Supports VM Node `v22.23.3` and local/CI Node `v24.19.0`. All 41 test suites pass cleanly on Node test runner. |
+| **Database Integrity** | Transaction and recovery tests | Required invariants hold | **PASS** | Foreign keys, unique indexes (`idx_single_active_session`), atomic slot acquisition (`acquireSlotAtomic`), and 19/19 chaos/concurrency tests passed. |
+| **V-Visa Isolation** | Gateway-selection tests | Existing production safeguards preserved | **PASS** | `ENABLE_YOUPI_UPI: default(false)`. Default provider `ZOHO`. 7/7 adapter tests and 5/5 idempotency tests pass in V-Visa repo. |
+| **Android Readiness** | Build, permissions, distribution and durability evidence | Intended distribution path compliant | **NOT VERIFIED** | Ineligible for standard Google Play due to `RECEIVE_SMS`. Requires Enterprise MDM sideload and manual "Restricted Settings" bypass on Android 14. Network dispatch uses in-memory thread (needs durable Room outbox). Blocked for unattended deployment. |
+| **Security** | Static analysis, dependency and secret scans | No unresolved critical/high findings | **PASS** | Gitleaks scan clean, TypeScript typecheck clean (`tsc -b --noEmit`), HMAC request signing and timing-safe webhook verification passing. |
+| **Reproducibility** | Artifact hash and release manifest | Artifact identity verified | **PASS** | Tarball `reports/mitto-pay-rc1.tar.gz` produced and SHA-256 computed: `9fd6ed79082c...`. Release manifest `reports/mitto-pay-release-manifest.json` generated. |
+| **Rollback Readiness** | Backup and recovery evidence | Recovery procedure verified | **PASS** | Verified `/opt/youpi-pg-backup-pre-gate4` exists on VM `130.210.28.51`. Documented pre-canary snapshot and recovery steps in `reports/mitto-pay-rollback-runbook.md`. |
+| **Staging Deployment** | Health and regression evidence | Staging stable and isolated | **NOT VERIFIED** | Staging runbook and configuration delta prepared, but deployment was explicitly NOT executed pending approval. |
+| **Production Approval** | Recorded authorized approval | Required approval explicitly granted | **NOT VERIFIED** | Commit, staging deployment, and production canary payments are withheld pending human review. |
+| **Production Verification** | Deployment and post-release evidence | Approved production checks pass | **NOT VERIFIED** | Cannot verify production until staging deployment and approved canary activation occur. |
+
+---
+
+## 2. Summary of Implementation & Changes
+
+1. **Repository Hygiene (`.gitignore`):**
+ - Added `data/*.json`, `!data/.gitkeep`, `reports/*.tar.gz`, `reports/*.sha256`.
+ - Prevented disposable test state from leaking into release diffs.
+2. **Centralized Fail-Closed Canary Policy (`packages/common/src/canary-policy.js`):**
+ - Strictly parses `CANARY_MERCHANT_ALLOWLIST`. Fails closed if missing, blank, or malformed.
+ - Enforces `YOUPI_VERIFICATION_POLICY === 'REQUIRE_DUAL_CHANNEL'` during canary mode.
+ - Enforces that client metadata `agencyVvisaUid` cannot forge access to an unauthorized merchant.
+3. **Session Entry Point Protection:**
+ - `apps/payment-api/src/routes/payments.routes.js`: Protected via `evaluateCanaryMerchantEligibility`.
+ - `apps/payment-api/src/routes/checkout.routes.js`: Device rebinding (`handleEndAndRestartPayment`) protected before terminating old or creating new sessions.
+ - `packages/db/src/repositories/payment-session.repository.js`: Database-level boundary assertion in `create(data)` prevents direct injection bypass.
+4. **Node.js Engine Alignment (`package.json`):**
+ - Updated declared engine to `"node": ">=22.5.0"`.
+ - Validated against Node 22 (VM runtime) and Node 24 (local & CI runtime).
+5. **Test Coverage:**
+ - Added `packages/common/src/__tests__/canary-policy.test.js` (12 unit tests).
+ - Expanded `apps/payment-api/src/__tests__/canary-isolation-verification.test.js` (9 integration tests).
+ - Verified 41/41 full regression suites pass (60.16s).
+ - Verified 14/14 synthetic Stage 3 tests pass (0.63s).
+ - Verified 19/19 chaos & concurrency tests pass (0.32s).
+ - Verified 12/12 V-Visa adapter & idempotency tests pass (0.34s).
diff --git a/reports/mitto-pay-release-manifest.json b/reports/mitto-pay-release-manifest.json
new file mode 100644
index 0000000..311f1b1
--- /dev/null
+++ b/reports/mitto-pay-release-manifest.json
@@ -0,0 +1,42 @@
+{
+ "product": "Mitto Pay",
+ "releaseCandidate": "mitto-pay-rc1",
+ "generatedAt": "2026-10-21T13:07:00.000Z",
+ "baselineCommitSha": "eb613a9fd1e598a2e4e579343860aad7fdca169a",
+ "branch": "mitto-pay-main",
+ "artifact": {
+ "filename": "mitto-pay-rc1.tar.gz",
+ "sha256": "9fd6ed79082c25430d55f89590bfc09f515b54fd782bb2e97d8c4be1de18c07b",
+ "sizeBytes": 2607884
+ },
+ "dependencies": {
+ "lockfile": "package-lock.json",
+ "lockfileSha256": "4d8809f952374c96a17adc86c626733033767d4c582d3d8574f25a930af6e0c3",
+ "declaredNodeEngine": ">=22.5.0",
+ "targetNodeRuntime": "22.23.3"
+ },
+ "vmEnvironment": {
+ "host": "130.210.28.51",
+ "currentDeployedCommit": "560037147b5dcdc3620ee4efa40c5fff2496a418+gate4-gmail-observer",
+ "knownGoodBackup": "/opt/youpi-pg-backup-pre-gate4"
+ },
+ "securityPolicies": {
+ "canaryMode": "FAIL_CLOSED",
+ "verificationPolicy": "REQUIRE_DUAL_CHANNEL",
+ "approvedStagingMerchantUid": "VVANFTTKRA",
+ "vvisaIntegration": {
+ "defaultGateway": "ZOHO",
+ "enableYoupiUpi": false,
+ "pilotAgencyUid": "VVISA-INTERNAL-OPS"
+ }
+ },
+ "verificationSummary": {
+ "regressionSuitesPassed": 41,
+ "regressionSuitesTotal": 41,
+ "concurrencyTestsPassed": 19,
+ "canaryPolicyTestsPassed": 12,
+ "canaryIsolationIntegrationTestsPassed": 9,
+ "syntheticStage3IntegrationTestsPassed": 14,
+ "typecheck": "PASSED"
+ }
+}
diff --git a/reports/mitto-pay-rollback-runbook.md b/reports/mitto-pay-rollback-runbook.md
new file mode 100644
index 0000000..409ffbb
--- /dev/null
+++ b/reports/mitto-pay-rollback-runbook.md
@@ -0,0 +1,67 @@
+# Mitto Pay — Rollback Runbook
+
+**Target Host:** Oracle VM `130.210.28.51`
+**Service:** `youpi-staging.service`
+**Rollback Triggers:**
+- Any unexpected 500 error or crash on service startup.
+- Any failure of canary merchant allowlist enforcement (e.g. unauthorized merchant accepted).
+- Any single-channel premature payment success emission.
+- Cloudflare ingress failure (`pay.vvisa.in` / `pay-api.vvisa.in`).
+- Any interference with V-Visa's primary Zoho Payments gateway.
+
+---
+
+## 1. Rollback Targets
+
+1. **Immediate Pre-Canary Snapshot:** `/opt/youpi-pg-backup-pre-mitto-canary` (Created during deployment step 3)
+2. **Prior Known-Good Gate 4 Backup:** `/opt/youpi-pg-backup-pre-gate4` (`560037147b5dcdc3620ee4efa40c5fff2496a418+phase9d-hardened`)
+3. **Database Recovery Target:** `/opt/backups/`
+
+---
+
+## 2. Emergency Rollback Execution Procedure
+
+Execute sequentially:
+
+```bash
+# 1. Stop the application service immediately to prevent unintended processing
+sudo systemctl stop youpi-staging.service
+
+# 2. Swap back to the pre-deployment snapshot
+sudo rm -rf /opt/youpi-pg
+sudo cp -r /opt/youpi-pg-backup-pre-mitto-canary /opt/youpi-pg
+
+# 3. If pre-canary snapshot was corrupted, fall back to Gate 4 known-good backup:
+# sudo cp -r /opt/youpi-pg-backup-pre-gate4 /opt/youpi-pg
+
+# 4. Revert /etc/youpi/staging.env if canary flags need restoration
+sudo sed -i '/CANARY_/d' /etc/youpi/staging.env
+
+# 5. Fix permissions
+sudo chown -R ubuntu:ubuntu /opt/youpi-pg
+
+# 6. Restart the known-good service
+sudo systemctl start youpi-staging.service
+
+# 7. Check service status
+systemctl status youpi-staging.service --no-pager
+```
+
+---
+
+## 3. Post-Rollback Verification
+
+1. **Verify Running Commit:**
+ ```bash
+ cat /opt/youpi-pg/DEPLOYED_COMMIT
+ ```
+ *Expected:* `560037147b5dcdc3620ee4efa40c5fff2496a418+gate4-gmail-observer`
+2. **Verify Health Endpoint:**
+ ```bash
+ curl -sSf http://127.0.0.1:6100/api/v1/health
+ ```
+3. **Check Journalctl Logs:**
+ ```bash
+ sudo journalctl -u youpi-staging.service -n 20 --no-pager
+ ```
+4. **Confirm Normal Operations Restored.**