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 verification pipeline rejections from falling through to attribution (Closes #22)

ArunGupta1526e9f9da042253
diff --git a/AGENTS.md b/AGENTS.md
index bc32506..2d66dc4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,11 +1,59 @@
-# AGENTS.md — Integration Guide for AI Coding Agents
+# AGENTS.md — YOUPI PG V2 Operating & Integration Standard
-> **Audience**: AI Coding Agents & Pair Programmers integrating YOUPI PG V2 into developer applications.
-> **Purpose**: Authoritative reference on the YOUPI payment lifecycle, one-script frontend integration, browser events, and server-to-server webhook verification.
+This document establishes the mandatory architectural rules, Git workflows, security standards, and payment lifecycle invariants for both AI coding agents and human engineers contributing to or integrating with **YOUPI PG V2**.
---
-## 1. High-Level Architecture
+## Part 1: AI & Developer Operating Standard
+
+### 1. Mandatory Git Workflow & Branching Rules
+
+1. **NEVER make direct commits to `main`**.
+2. **Branch Directly Off Active Working Branch (Never Checkout `main` First)**:
+ - For every bug fix, feature addition, or code modification, create a dedicated feature or fix branch:
+ - Features: `feature/<feature-name>` (e.g., `feature/postgres-adapter`, `feature/reviewground-ci`)
+ - Fixes: `fix/<issue-name>` (e.g., `fix/otp-throttle-test`, `fix/bank-sms-regex`)
+ - **Never revert to or checkout `main` when creating a new branch**: Always branch directly off the **current active working branch** (`git checkout -b <new-branch>`). This preserves ongoing work, staged changes, and prevents context loss or accidental regression.
+3. **Mandatory Pre-Commit & Pre-Push Checklist**:
+ - **Sync & Prune (`git fetch --prune --all`)**: Always run `git fetch --prune --all` before creating branches, pushing, or opening a PR to clean up stale remote-tracking references.
+ - **Typecheck**: Run `npm run typecheck` locally to verify TypeScript compiles without errors.
+ - **Unit & Regression Tests**: Run `npm test` locally to ensure 100% of curated test suites pass cleanly.
+ - **Inspect Changes**: Always check `git status`, `git diff`, and `git log -n 3 --oneline` before staging/committing to prevent accidental secret leaks, debug dumps, or unneeded files.
+ - **Environment Integrity**: Ensure any new environment variables are documented in `.env.example` and `docs/CONFIGURATION.md`. Never hardcode API keys, tokens, or private credentials into source code.
+4. **Strict No-Unsolicited-Push Rule & PR Protocol**:
+ - **Never Push Automatically**: After committing locally, **NEVER execute `git push` to remote (`origin`) without informing and obtaining explicit confirmation from the user in chat first**. All commits must remain strictly local until pre-approved.
+ - **Auto-Create PR Upon Push Confirmation**: Once the user explicitly approves pushing, push the branch (`git push -u origin <branch>`). Check first if a PR already exists (`gh pr list --head <branch>`); if an existing PR is found, inform the developer of the updated PR. If no PR exists, open a Pull Request against `main` using GitHub CLI (`gh pr create`) with a detailed title, summary, and verification details.
+ - **Strict No-Unsolicited-Merge Rule & Clean Branch Deletion (`--delete-branch`)**:
+ - **NEVER merge the PR into `main` automatically**. Always ask/inform the developer and wait for their explicit command before merging any PR.
+ - **Mandatory Branch Deletion & Standard Merge Commit (`--merge`)**: When instructed to merge, ALWAYS execute the merge using a standard merge commit with automatic branch deletion enabled (`gh pr merge <pr-number> --merge --delete-branch`), followed by cleaning up local tracking references (`git checkout main && git pull && git fetch --prune --all && git branch -D <branch>`).
+5. **Mandatory Granular & Atomic Commits Standard**:
+ - **Never Bundle Multiple Unrelated Features into a Single Monolithic Commit**: Create independent, atomic commits for each logical unit of work.
+ - **Conventional Commits**: Every commit header MUST adhere strictly to Conventional Commits:
+ - `feat(...)` — New features (Minor bump)
+ - `fix(...)` — Bug fixes (Patch bump)
+ - `perf(...)` — Performance improvements
+ - `refactor(...)` — Refactoring without behavioral change
+ - `docs(...)` — Documentation changes
+ - `test(...)` — Adding or correcting tests
+ - `ci(...)` — CI/CD workflow changes
+ - `chore(...)` — Maintenance tasks
+ - **Always Commit with Detailed Information**:
+ - Every commit message MUST include a conventional header, a bulleted list of what changed, the architectural rationale, and verification status.
+6. **Mandatory Automated PR Review & Interactive Suggestion Resolution Protocol**:
+ - **Proactive Review & Inline Suggestion Inspection**: After opening a PR or pushing a commit, inspect GitHub Actions CI run results, automated AI code review comments (e.g., ReviewGround, security linters), and **inline PR review suggestions** via `gh pr view <pr-number> --comments` and `gh api repos/<owner>/<repo>/pulls/<pr-number>/comments`.
+ - **Continuous Suggestion & Inline Fix Resolution**: If automated reviews or maintainers flag valid and needed suggestions—such as 1-click inline code suggestions, eliminating dynamic evaluation (`new Function`, `eval`), strengthening path traversal boundaries (`path.relative`), resolving security advisories/CWEs, fixing memory leaks, or improving code safety—the agent **MUST continuously and proactively address and implement them**.
+ - **Sync Fixes Across Fork & Upstream PRs**: When fixes or architectural improvements are committed on the fork, verify whether corresponding open upstream PRs require the same updates and push the new commits to upstream PR branches promptly.
+ - **Re-Verification & Push**: Always verify all fixes locally (`npm run typecheck`, `npm test`) and push updates to the active PR branch so that the PR achieves 100% green checks with zero unresolved blockers or critical warnings before requesting merge approval.
+7. **Mandatory Real-World & External Verification Standard (RBI, Regulators, Internet & Community Sources)**:
+ - **Never Hardcode Assumptions Directly into Code**: When dealing with real-world entities—such as banking identifiers, regulatory domain spaces (e.g., RBI/IDRBT `.bank.in` and `.fin.in` mandates), bank SMS headers, transaction email alert senders, or NPCI UPI specification rules—never insert assumptions or arbitrary hardcoded lists directly into source code.
+ - **Mandatory Web, Regulatory & Community Verification**: If verification is needed for a real test case, domain whitelist, regex pattern, or banking protocol, the agent MUST proactively verify it against authoritative regulatory sources (RBI circulars, IDRBT registry, NPCI specs) and authentic real-world telemetry (community forums like Reddit, bank documentation, official releases).
+ - **Grounding in Real Test Cases & Specifications**: Ensure unit tests, regex patterns, and validation logic reflect actual production formats used by Indian banks and payment networks (including both modern `.bank.in` domain structures and verified legacy commercial notification channels).
+
+---
+
+## Part 2: High-Level Architecture & Integration Guide
+
+### 1. Payment Lifecycle Architecture
YOUPI PG V2 is a self-hosted, sovereign payment gateway designed for zero-fee UPI and counter payments with automated banking observation (SMS & Gmail parsing).
@@ -37,9 +85,9 @@ YOUPI PG V2 is a self-hosted, sovereign payment gateway designed for zero-fee UP
---
-## 2. Universal One-Script Integration
+### 2. Universal One-Script Integration
-### Step 1: Script Inclusion
+#### Step 1: Script Inclusion
Place the script tag in the page's HTML `<head>` or `<body>`:
```html
@@ -52,7 +100,7 @@ Place the script tag in the page's HTML `<head>` or `<body>`:
- When running locally, `<youpi-checkout-host>` is `http://localhost:7000`.
- In production, it is your canonical checkout portal domain (e.g., `https://pay.yourdomain.com`).
-### Step 2: One-Button Zero-JS Configuration
+#### Step 2: One-Button Zero-JS Configuration
Tag any clickable button with `data-youpi-pay`:
```html
@@ -71,7 +119,7 @@ Tag any clickable button with `data-youpi-pay`:
The script automatically binds click events to elements with `[data-youpi-pay]`, including elements created dynamically at runtime.
-### Step 3: Programmatic API (`Youpi.pay`)
+#### Step 3: Programmatic API (`Youpi.pay`)
For single-page apps (React, Next.js, Vue, Nuxt, Svelte), use the programmatic interface:
```javascript
@@ -90,7 +138,6 @@ Youpi.pay({
},
handler: function(response) {
console.log("Payment confirmed in modal:", response);
- // response: { status: "SUCCESS", order_id, amount_received, utr, payment_mode }
},
onClose: function() {
console.log("Modal closed by customer");
@@ -100,7 +147,7 @@ Youpi.pay({
---
-## 3. Normalized Browser Events
+### 3. Normalized Browser Events
The frontend script emits normalized DOM `CustomEvent`s on `window`:
@@ -113,7 +160,7 @@ The frontend script emits normalized DOM `CustomEvent`s on `window`:
| `youpi:payment:cancelled` | Customer cancelled or dismissed the checkout |
| `youpi:payment:result` | Unified event dispatched on any outcome |
-### Payload Contract (`event.detail`):
+#### Payload Contract (`event.detail`):
```javascript
{
"status": "SUCCESS", // 'SUCCESS' | 'FAILED' | 'SUSPICIOUS' | 'EXPIRED' | 'CANCELLED'
@@ -128,13 +175,13 @@ The frontend script emits normalized DOM `CustomEvent`s on `window`:
---
-## 4. Authoritative Server-to-Server Webhooks
+### 4. Authoritative Server-to-Server Webhooks
> **CRITICAL RULE**: Browser events are strictly for user interface updates.
> **NEVER** mark orders as fulfilled or deliver digital goods based on browser events. Only fulfill orders after verifying the server-to-server webhook!
-> **RAW BODY REQUIREMENT**: Request bytes must **NOT** be parsed to JSON before HMAC calculation. Parsing and re-stringifying alters whitespace and key order, causing signature verification failure. Always compute HMAC over raw unparsed request bytes!
+> **RAW BODY REQUIREMENT**: Request bytes must **NOT** be parsed to JSON before HMAC calculation. Always compute HMAC over raw unparsed request bytes!
-### Webhook Request Specifications:
+#### Webhook Request Specifications:
- **HTTP Method**: `POST`
- **Headers**:
- `Content-Type: application/json`
@@ -143,7 +190,7 @@ The frontend script emits normalized DOM `CustomEvent`s on `window`:
- `X-Gateway-Delivery-Id: <uuid>`
- `X-Gateway-Timestamp: <ms>`
-### Payload Contract (`payload`):
+#### Payload Contract (`payload`):
```json
{
"event": "SUCCESS",
@@ -159,11 +206,9 @@ The frontend script emits normalized DOM `CustomEvent`s on `window`:
}
```
-> **PAYMENT METHOD RULE**: `event: "SUCCESS"` is also sent when a customer places a **Cash on Delivery** order (`method: "COD"`) or a counter payment is confirmed (`CASH_COUNTER` / `CARD_COUNTER`). For `COD` no money has been received yet. Always check `payload.method` before you treat an order as **paid**: fulfil prepaid goods only when `method` is `UPI` (or a counter method your till has confirmed), and route `COD` orders into your cash-on-delivery flow.
-
-### Polyglot Webhook Verification Implementations:
+> **PAYMENT METHOD RULE**: `event: "SUCCESS"` is also sent when a customer places a **Cash on Delivery** order (`method: "COD"`) or a counter payment is confirmed (`CASH_COUNTER` / `CARD_COUNTER`). For `COD` no money has been received yet. Always check `payload.method` before you treat an order as **paid**.
-#### 1. Node.js (Express)
+#### Node.js (Express) Webhook Verification Example:
```javascript
import crypto from 'node:crypto';
@@ -179,7 +224,6 @@ app.post('/api/webhook', express.raw({ type: 'application/json' }), (req, res) =
const payload = JSON.parse(req.body.toString('utf8'));
if (payload.event === 'SUCCESS' && payload.method === 'UPI') {
- // Authoritatively mark order as PAID in merchant database (COD: payload.method === 'COD' means "order placed", not paid)
db.orders.markPaid(payload.orderId, {
utr: payload.utr,
amount: payload.amount,
@@ -191,111 +235,9 @@ app.post('/api/webhook', express.raw({ type: 'application/json' }), (req, res) =
});
```
-#### 2. Python (FastAPI)
-```python
-import hmac, hashlib, json
-from fastapi import FastAPI, Request, HTTPException
-
-app = FastAPI()
-
[email protected]("/api/webhook")
-async def youpi_webhook(request: Request):
- raw_body = await request.body()
- signature = request.headers.get("X-Gateway-Signature", "")
- secret = request.app.state.webhook_secret.encode("utf-8")
-
- expected = "sha256=" + hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
- if not hmac.compare_digest(signature, expected):
- raise HTTPException(status_code=401, detail="Invalid webhook signature")
-
- payload = json.loads(raw_body.decode("utf-8"))
- if payload.get("event") == "SUCCESS" and payload.get("method") == "UPI":
- # Authoritatively mark order as PAID: payload["orderId"], payload["utr"], payload["amount"]
- # (method == "COD" means the order was placed and cash is due on delivery - not paid)
- pass
- return {"received": True}
-```
-
-#### 3. PHP
-```php
-<?php
-$rawPayload = file_get_contents('php://input');
-$signature = $_SERVER['HTTP_X_GATEWAY_SIGNATURE'] ?? '';
-$secret = getenv('YOUPI_WEBHOOK_SECRET');
-
-$expected = 'sha256=' . hash_hmac('sha256', $rawPayload, $secret);
-
-if (!hash_equals($expected, $signature)) {
- http_response_code(401);
- exit(json_encode(['error' => 'Invalid webhook signature']));
-}
-
-$payload = json_decode($rawPayload, true);
-if (($payload['event'] ?? '') === 'SUCCESS' && ($payload['method'] ?? '') === 'UPI') {
- // Authoritatively mark order as PAID: $payload['orderId'], $payload['utr'], $payload['amount']
- // ($payload['method'] === 'COD' means the order was placed and cash is due on delivery - not paid)
-}
-
-http_response_code(200);
-echo json_encode(['received' => true]);
-?>
-```
-
-#### 4. Go (`net/http`)
-```go
-package main
-
-import (
- "crypto/hmac"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "io"
- "net/http"
- "os"
-)
-
-func youpiWebhookHandler(w http.ResponseWriter, r *http.Request) {
- rawBody, err := io.ReadAll(r.Body)
- if err != nil {
- http.Error(w, "Cannot read body", http.StatusBadRequest)
- return
- }
- defer r.Body.Close()
-
- signature := r.Header.Get("X-Gateway-Signature")
- secret := []byte(os.Getenv("YOUPI_WEBHOOK_SECRET"))
-
- mac := hmac.New(sha256.New, secret)
- mac.Write(rawBody)
- expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
-
- if !hmac.Equal([]byte(signature), []byte(expected)) {
- http.Error(w, "Invalid webhook signature", http.StatusUnauthorized)
- return
- }
-
- var payload struct {
- Event string `json:"event"`
- OrderId string `json:"orderId"`
- UTR string `json:"utr"`
- Amount string `json:"amount"`
- AmountPaise int64 `json:"amountPaise"`
- Method string `json:"method"`
- }
- if err := json.Unmarshal(rawBody, &payload); err == nil && payload.Event == "SUCCESS" && payload.Method == "UPI" {
- // Authoritatively mark order as PAID: payload.OrderId, payload.UTR, payload.Amount
- // (Method == "COD" means the order was placed and cash is due on delivery - not paid)
- }
-
- w.WriteHeader(http.StatusOK)
- w.Write([]byte(`{"received":true}`))
-}
-```
-
---
-## 5. Security & Architectural Invariants
+### 5. Security & Architectural Invariants
1. **No Public Force-Success Endpoint**:
- There is no endpoint that allows a client or developer to arbitrarily declare `SUCCESS`.
@@ -307,10 +249,12 @@ func youpiWebhookHandler(w http.ResponseWriter, r *http.Request) {
- Webhook deliveries include unique `X-Gateway-Delivery-Id` and `orderId`. Merchants must ensure their webhook processing is idempotent.
4. **Preserve Customer Metadata**:
- Unrecognized fields in `metadata` are passed through untouched and included in webhooks and API responses.
+5. **Node.js Engine Standard**:
+ - The project strictly targets **Node.js >= 22.5.0** due to built-in `node:sqlite` (`DatabaseSync`).
---
-## 6. Service Ports (Local Development Reference)
+### 6. Service Ports (Standard Topology)
| Service | Port | Description |
| :--- | :--- | :--- |
@@ -320,3 +264,4 @@ func youpiWebhookHandler(w http.ResponseWriter, r *http.Request) {
| **Merchant Admin** | `6001` | Dashboard for slots, receiving VPAs, observers |
| **SMS Observer** | `6002` | Android SMS banking webhook ingester |
| **Gmail Observer** | `6003` | Push notification / Gmail observation ingester |
+| **Process Control Center** | `8090` | Local process supervisor daemon |
diff --git a/README.md b/README.md
index 9439518..56f4719 100644
--- a/README.md
+++ b/README.md
@@ -464,6 +464,11 @@ YOUPI PG confirms payments without expensive commercial banking APIs using a tri
1. **Android Observer App:** Install [`apps/android-observer-app/youpi-sms-gateway.apk`](apps/android-observer-app/youpi-sms-gateway.apk) on any secondary Android smartphone with the receiving bank SIM. Scan the pairing QR code in Merchant Admin to establish an encrypted HMAC link.
2. **Gmail Observer:** Connect your bank-registered Google account using standard OAuth2 credentials.
+ <details>
+ <summary><b>🔍 View Verified Indian Bank Domains & RBI <code>.bank.in</code> Registry</b></summary>
+
+ > Supports both modern RBI-mandated sovereign `.bank.in` / `.fin.in` spaces (`sbi.bank.in`, `hdfcbank.bank.in`, `icici.bank.in`, `axis.bank.in`, `kotak.bank.in`, `pnb.bank.in`, `bankofbaroda.bank.in`, etc.) and verified legacy notification channels with full subdomain routing (`alerts.hdfcbank.net`, `custalert.icicibank.com`, `alerts.sbi.co.in`, `kotak.com`, `canarabank.com`, etc.). See [docs/OBSERVERS_SETUP.md](docs/OBSERVERS_SETUP.md) for full DNS / MX verified topology.
+ </details>
3. **Google Messages Web Observer:** Pairs via headless Chrome DevTools Protocol to observe cellular SMS through Google Messages Web.
<br/>
diff --git a/apps/payment-api/src/__tests__/verification-fallthrough.test.js b/apps/payment-api/src/__tests__/verification-fallthrough.test.js
new file mode 100644
index 0000000..abac9cf
--- /dev/null
+++ b/apps/payment-api/src/__tests__/verification-fallthrough.test.js
@@ -0,0 +1,151 @@
+import '../../../../scripts/test-support.js';
+import { test, describe, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import http from 'node:http';
+import { Database } from '@youpi/db';
+import { startServer as startPaymentApi } from '../index.js';
+import { PaymentStatus } from '@youpi/common';
+import { authHeadersFor } from '../../../../scripts/test-support.js';
+
+describe('Verification Pipeline & Fall-Through Protection (#22)', () => {
+ let apiInstance;
+ let baseUrl;
+ let testDb;
+
+ before(async () => {
+ testDb = new Database({ inMemory: true });
+ apiInstance = await startPaymentApi(6295, testDb);
+ baseUrl = `http://localhost:${apiInstance.port}`;
+ });
+
+ after(async () => {
+ await apiInstance.close();
+ testDb.close();
+ });
+
+ function request(path, options = {}) {
+ return new Promise((resolve, reject) => {
+ const url = new URL(path, baseUrl);
+ const req = http.request(url, {
+ method: options.method || 'GET',
+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(path), ...(options.headers || {}) }
+ }, res => {
+ let data = '';
+ res.on('data', chunk => { data += chunk; });
+ res.on('end', () => {
+ let body;
+ try {
+ body = JSON.parse(data);
+ } catch {
+ body = data;
+ }
+ resolve({ status: res.statusCode, body });
+ });
+ });
+ req.on('error', reject);
+ if (options.body) {
+ req.write(typeof options.body === 'string' ? options.body : JSON.stringify(options.body));
+ }
+ req.end();
+ });
+ }
+
+ test('Issue #22: Poller endpoints reject personal numeric SMS senders and do not fall through to attribution', 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: 'FALLTHROUGH-GUARD-01',
+ amountPaise: 50000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(session.id, receivingAccountId);
+
+ // Personal numeric SMS sender (+919876543210) attempts to inject payment
+ const res = await request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: '+919876543210',
+ receivingAccountId,
+ amount: '500.00',
+ amountPaise: '50000',
+ rawText: 'A/C 1234 credited by Rs 500.00 via UPI/123456789012'
+ }
+ });
+
+ assert.equal(res.status, 400);
+ assert.equal(res.body.accepted, false);
+ assert.equal(res.body.status, 'REJECTED');
+ assert.equal(res.body.reason, 'PERSONAL_SMS_REJECTED');
+
+ // Confirm session remains ACTIVE (not marked SUCCESS)
+ const freshSession = sessionRepo.findById(session.id);
+ assert.equal(freshSession.status, PaymentStatus.ACTIVE);
+ });
+
+ test('Issue #22: Poller endpoints reject duplicate/reused bank reference number (UTR)', async () => {
+ const sessionRepo = apiInstance.app.context.sessionRepo;
+ const obsRepo = apiInstance.app.context.obsRepo;
+ const receivingAccountId = '00000000-0000-0000-0000-000000000002';
+ const merchantId = '00000000-0000-0000-0000-000000000001';
+
+ // 1. Session 1 is already completed with UTR 123456123456
+ const priorObs = obsRepo.create({
+ source: 'SMS',
+ receivingAccountId,
+ amountPaise: 10000n,
+ amount: '100.00',
+ observedAt: new Date(),
+ bankReferenceNumber: '123456123456',
+ fingerprintHash: 'hash-utr-consumed-test-999'
+ });
+ const s1 = sessionRepo.create({
+ merchantId,
+ receivingAccountId,
+ orderId: 'PRIOR-ORDER-99',
+ amountPaise: 10000n
+ });
+ testDb.execute("UPDATE payment_sessions SET status = 'SUCCESS', attributed_observation_id = ? WHERE id = ?", [priorObs.id, s1.id]);
+
+ 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]);
+
+ // 2. Session 2 is currently active for ₹100
+ const s2 = sessionRepo.create({
+ merchantId,
+ receivingAccountId,
+ orderId: 'NEW-ORDER-100',
+ amountPaise: 10000n
+ });
+ apiInstance.app.context.queueEngine.enqueueOrActivate(s2.id, receivingAccountId);
+
+ // 3. Ingest observation reusing the same UTR
+ const res = await request('/api/v1/pollers/events', {
+ method: 'POST',
+ body: {
+ source: 'SMS',
+ sender: 'HDFCBK',
+ receivingAccountId,
+ amount: '100.00',
+ amountPaise: '10000',
+ bankReferenceNumber: '123456123456',
+ rawText: 'A/C credited with Rs 100.00 on 19-Oct-2026. Ref: 123456123456'
+ }
+ });
+
+ assert.equal(res.status, 400);
+ assert.equal(res.body.accepted, false);
+ assert.equal(res.body.status, 'REJECTED');
+ assert.equal(res.body.reason, 'REFERENCE_ALREADY_USED');
+
+ // Confirm s2 is not attributed
+ const freshS2 = sessionRepo.findById(s2.id);
+ assert.equal(freshS2.status, PaymentStatus.ACTIVE);
+ });
+});
diff --git a/apps/payment-api/src/routes/pollers.routes.js b/apps/payment-api/src/routes/pollers.routes.js
index 940496c..2f63bee 100644
--- a/apps/payment-api/src/routes/pollers.routes.js
+++ b/apps/payment-api/src/routes/pollers.routes.js
@@ -91,6 +91,7 @@ export function registerPollerRoutes(server, ctx) {
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)
@@ -117,6 +118,17 @@ export function registerPollerRoutes(server, ctx) {
});
return;
}
+
+ if (pipeResult.status === 'REJECTED') {
+ HttpServer.json(res, 400, {
+ accepted: false,
+ status: 'REJECTED',
+ reason: pipeResult.failingCondition,
+ error: pipeResult.failingReason || pipeResult.details,
+ pipeline: pipeResult
+ });
+ return;
+ }
}
try {
@@ -318,9 +330,10 @@ export function registerPollerRoutes(server, ctx) {
const pipeResult = ctx.pipeline.process({
source: 'SMS',
rawText,
- sender: body.sender || req.headers['x-sender'],
+ 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'
});
@@ -347,6 +360,18 @@ export function registerPollerRoutes(server, ctx) {
});
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.
diff --git a/docs/OBSERVERS_SETUP.md b/docs/OBSERVERS_SETUP.md
index a2afa5d..b5bd30e 100644
--- a/docs/OBSERVERS_SETUP.md
+++ b/docs/OBSERVERS_SETUP.md
@@ -27,6 +27,57 @@ YOUPI PG employs a **Tri-Channel Observation Engine** where all three methods op
```
5. Navigate to `http://localhost:6003/oauth/url` or Merchant Admin to authorize your Gmail account.
+<details>
+<summary><b>🔍 Verified Indian Banking Email Domains & RBI <code>.bank.in</code> Mandate (Click to expand)</b></summary>
+
+<br/>
+
+Under Reserve Bank of India (RBI) and IDRBT regulatory standards, scheduled commercial banks in India are migrating their customer alert handles to the sovereign `.bank.in` domain (and NBFCs to `.fin.in`). YOUPI PG validates both live `.bank.in` / `.fin.in` addresses and verified legacy commercial notification handles.
+
+#### 1. Official RBI `.bank.in` Migration Domain Registry (Live DNS / MX Verified)
+
+All `.bank.in` domains are automatically accepted by the verification engine (`emailDomain.endsWith('.bank.in')`):
+
+| Bank | Verified Alert Domain | DNS / Mail Server Status | Primary Mail Protection Server |
+| :--- | :--- | :--- | :--- |
+| **HDFC Bank** | `hdfcbank.bank.in` / `hdfc.bank.in` | `ACTIVE (MX)` | `hdfcbank-bank-in.mail.protection.outlook.com` |
+| **ICICI Bank** | `icici.bank.in` | `ACTIVE (MX)` | `icici-bank-in.mail.protection.outlook.com` |
+| **State Bank of India** | `sbi.bank.in` | `ACTIVE (MX)` | `sbi-bank-in.mail.protection.outlook.com` |
+| **Axis Bank** | `axis.bank.in` | `ACTIVE (MX)` | `axis-bank-in.mail.protection.outlook.com` |
+| **Kotak Mahindra Bank** | `kotak.bank.in` | `ACTIVE (MX)` | `kotak.in.tmes-in.trendmicro.com` |
+| **Punjab National Bank** | `pnb.bank.in` | `ACTIVE (MX)` | `cluster1a.us.messagelabs.com` |
+| **Bank of Baroda** | `bankofbaroda.bank.in` | `ACTIVE (MX)` | `bankofbaroda-bank-in.mail.protection.outlook.com` |
+| **IndusInd Bank** | `indusind.bank.in` | `ACTIVE (MX)` | `mx02.indusind.bank.in` |
+| **IDFC FIRST Bank** | `idfcfirst.bank.in` | `ACTIVE (MX)` | `mx06.idfcbank.com` |
+| **IDBI Bank** | `idbi.bank.in` | `ACTIVE (MX)` | `idbi-bank-in.mail.protection.outlook.com` |
+| **Indian Bank** | `indianbank.bank.in` | `ACTIVE (MX)` | `indianbank-bank-in.mail.protection.outlook.com` |
+
+#### 2. Verified Legacy Commercial Banking Domains (Live DNS / MX Verified)
+
+The engine supports root domains and alert subdomains (e.g. `alerts.hdfcbank.net`, `custalert.icicibank.com`):
+
+| Bank | Root Domain | Subdomain Support | Notes & Verification Telemetry |
+| :--- | :--- | :--- | :--- |
+| **HDFC Bank** | `hdfcbank.net`, `hdfcbank.com` | `*.hdfcbank.net` | Primary automated alert channel (`[email protected]`) |
+| **ICICI Bank** | `icicibank.com` | `*.icicibank.com` | Automated alerts (`custalert.icicibank.com`) |
+| **State Bank of India** | `sbi.co.in` | `*.sbi.co.in` | Core banking alerts (`[email protected]`) |
+| **Axis Bank** | `axisbank.com` | `*.axisbank.com` | Official notifications |
+| **Kotak Mahindra Bank** | `kotak.com`, `kotak.co.in` | `*.kotak.com` | Core notifications |
+| **Paytm Payments Bank** | `paytmbank.com`, `paytm.com` | `*.paytm.com` | Merchant & wallet alerts |
+| **YES Bank** | `yesbank.in` | `*.yesbank.in` | Core alerts |
+| **Punjab National Bank** | `pnb.co.in` | `*.pnb.co.in` | Core alerts |
+| **Bank of Baroda** | `bankofbaroda.co.in`, `bankofbaroda.com` | `*.bankofbaroda.co.in` | Automated transaction statements |
+| **IndusInd Bank** | `indusind.com` | `*.indusind.com` | Core alerts |
+| **IDFC FIRST Bank** | `idfcfirstbank.com`, `idfcbank.com` | `*.idfcbank.com` | Automated alerts |
+| **Canara Bank** | `canarabank.com` | `*.canarabank.com` | Automated alerts |
+| **Union Bank of India** | `unionbankofindia.co.in` | `*.unionbankofindia.co.in` | Core banking alerts |
+| **Federal Bank** | `federalbank.co.in` | `*.federalbank.co.in` | Automated alerts |
+| **IDBI Bank** | `idbibank.com` | `*.idbibank.com` | Core banking alerts |
+
+> **Security Note:** Unverified personal domains or spoofed external free-mail providers (`@gmail.com`, `@yahoo.com`, `@outlook.com`) are strictly rejected by the verification pipeline (`INVALID_EMAIL_DOMAIN`).
+
+</details>
+
---
## Method 2: Android Payment Observer
diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.js
index 66cf6eb..a6e806b 100644
--- a/packages/core/src/attribution-engine.js
+++ b/packages/core/src/attribution-engine.js
@@ -207,6 +207,69 @@ export class AttributionEngine {
const isTimeValid = !isPriorExpiredSession && (normalizedObs.observedAt >= slotStart);
+ // Invariant Check 0a: Transaction Reference Already Used Check
+ let isUtrAlreadyUsed = false;
+ const trimmedUtr = normalizedObs.bankReferenceNumber ? String(normalizedObs.bankReferenceNumber).trim() : '';
+ if (trimmedUtr.length > 0) {
+ const priorUsedSession = this.sessionRepo.db.queryOne(`
+ SELECT ps.id, ps.order_id
+ FROM payment_sessions ps
+ JOIN payment_observations po ON ps.attributed_observation_id = po.id
+ WHERE ps.status = 'SUCCESS'
+ AND ps.id != ?
+ AND po.bank_reference_number = ?
+ LIMIT 1
+ `, [currentSession.id, trimmedUtr]);
+
+ if (priorUsedSession) {
+ isUtrAlreadyUsed = true;
+ if (this.auditRepo) {
+ this.auditRepo.log({
+ merchantId: currentSession.merchantId,
+ entityType: 'PAYMENT_SESSION',
+ entityId: currentSession.id,
+ action: 'REUSED_UTR_REJECTED',
+ actorType: 'SYSTEM',
+ details: {
+ bankReferenceNumber: trimmedUtr,
+ consumedByOrderId: priorUsedSession.order_id,
+ consumedBySessionId: priorUsedSession.id
+ }
+ });
+ }
+ }
+ }
+
+ // Invariant Check 0b: Check if SMS is from personal numeric phone number (10-15 digits E.164, no letters)
+ let isPersonalSms = false;
+ const senderStr = (normalizedObs.rawPayload?.sender || normalizedObs.rawPayload?.from || '').toString().trim();
+ if ((normalizedObs.source === 'SMS' || normalizedObs.source === 'ANDROID_OBSERVER') && senderStr) {
+ const digitsOnly = senderStr.replace(/[\s+-]/g, '');
+ if (digitsOnly.length >= 10 && /^\d+$/.test(digitsOnly) && !/[a-zA-Z]/.test(senderStr)) {
+ isPersonalSms = true;
+ }
+ }
+
+ if (isUtrAlreadyUsed) {
+ return {
+ attributed: false,
+ duplicate: true,
+ lateMatch: false,
+ observationId: savedObs.id,
+ outcomeStatus: 'REFERENCE_ALREADY_USED'
+ };
+ }
+
+ if (isPersonalSms) {
+ return {
+ attributed: false,
+ duplicate: false,
+ lateMatch: false,
+ observationId: savedObs.id,
+ outcomeStatus: 'PERSONAL_SMS_REJECTED'
+ };
+ }
+
if (isEligibleStatus && isAmountMatch && isTimeValid) {
const wasActive = currentSession.status === PaymentStatus.ACTIVE;
diff --git a/packages/core/src/bank-sms-parser.js b/packages/core/src/bank-sms-parser.js
index ffed032..f3ad7aa 100644
--- a/packages/core/src/bank-sms-parser.js
+++ b/packages/core/src/bank-sms-parser.js
@@ -12,7 +12,7 @@ export function extractIntelligentAmount(text) {
if (!text || typeof text !== 'string') return null;
// Pattern 1: Standard currency prefix (e.g. Rs 499, Rs. 499, ₹499, INR 499, Rs. 20.00, ₹1,200.50)
- const prefixMatch = text.match(/(?:(?:rs\.?|inr)\b|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);
+ const prefixMatch = text.match(/(?:(?:rs\b\.?|inr\b)|₹)[\s:=-]*([\d,]+(?:\.\d{1,2})?)/i);
if (prefixMatch && prefixMatch[1]) {
const clean = prefixMatch[1].replace(/,/g, '');
try {
@@ -21,7 +21,7 @@ export function extractIntelligentAmount(text) {
}
// Pattern 2: Standard currency suffix (e.g. 499 Rs, 499.00 INR, 20.00 Rs, 20rs, 500 inr)
- const suffixMatch = text.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\.?|inr)\b|₹)/i);
+ const suffixMatch = text.match(/(?:^|[^\w.])([\d,]+(?:\.\d{1,2})?)[\s:=-]*(?:(?:rs\b\.?|inr\b)|₹)/i);
if (suffixMatch && suffixMatch[1]) {
const clean = suffixMatch[1].replace(/,/g, '');
try {
@@ -104,8 +104,9 @@ export class BankSmsParser {
// 2. Extract Bank Reference / UTR / RRN
let bankRef;
const utrPatterns = [
- /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9]{6,25})/i,
- /(?:ref\s*no\.?)?[\s:#=-]+([a-zA-Z0-9]{8,22})/i,
+ /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9\-_]{6,35})/i,
+ /(?:upi\/(?:[0-9]+\/|cr\/)([a-zA-Z0-9\-_]{6,35}))/i,
+ /\b(?:ref(?:\s*(?:no\.?|id|#))?)[:\s#=-]+([a-zA-Z0-9\-_]{6,35})/i,
/\b([0-9]{12})\b/
];
diff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.js
index f195382..3725210 100644
--- a/packages/core/src/verification-pipeline.js
+++ b/packages/core/src/verification-pipeline.js
@@ -123,7 +123,7 @@ export class PaymentVerificationPipeline {
// Bank credit notifications are a few hundred bytes. Capping the text bounds the cost of
// the reference-extraction regexes below, which are scanned from every start offset and
// would otherwise let one oversized "observation" block the event loop (ReDoS / DoS).
- const MAX_SCAN_CHARS = 16384;
+ const MAX_SCAN_CHARS = 8192;
const rawText = (input.rawText || '').toString().slice(0, MAX_SCAN_CHARS);
// =========================================================================
@@ -187,7 +187,8 @@ export class PaymentVerificationPipeline {
stage5,
stage6,
parsed,
- session
+ session,
+ attribution = null
}) => {
return {
success: finalStatus === 'VERIFIED',
@@ -218,10 +219,21 @@ export class PaymentVerificationPipeline {
orderId: session.orderId,
amountPaise: session.amountPaise?.toString(),
status: session.status
- } : null
+ } : null,
+ attribution: attribution || null
};
};
+ // Invariant Guard: Bounded rawText boundary to prevent ReDoS (CWE-400)
+ if (input.rawText && typeof input.rawText === 'string' && input.rawText.length > MAX_SCAN_CHARS) {
+ return buildResult({
+ finalStatus: 'REJECTED',
+ failingStage: 1,
+ failingCondition: 'PAYLOAD_TOO_LARGE',
+ failingReason: `Transaction notification payload exceeds maximum allowable length of ${MAX_SCAN_CHARS} characters (received ${input.rawText.length}).`
+ });
+ }
+
// 0. Resolve Payment Session and Customer Context early for security attribution
let session = null;
@@ -366,10 +378,31 @@ export class PaymentVerificationPipeline {
emailDomain = cleanEmail.toLowerCase().trim().replace(/[>]/g, '');
}
- // Universal Bank Identifier: Email domain ends with .bank.in (e.g. [email protected], [email protected])
- const isBankDomain = emailDomain.endsWith('.bank.in') || emailDomain === 'bank.in';
+ // Universal Bank Identifier: Email domain ends with .bank.in/.fin.in or is an official verified Indian bank domain
+ const KNOWN_BANK_DOMAINS = new Set([
+ 'hdfcbank.net', 'hdfcbank.com',
+ 'icicibank.com',
+ 'sbi.co.in',
+ 'axisbank.com',
+ 'kotak.com', 'kotak.co.in',
+ 'paytmbank.com', 'paytm.com',
+ 'yesbank.in', 'pnb.co.in',
+ 'bankofbaroda.co.in', 'bankofbaroda.com',
+ 'indusind.com',
+ 'idfcfirstbank.com', 'idfcbank.com',
+ 'canarabank.com',
+ 'unionbankofindia.co.in',
+ 'federalbank.co.in',
+ 'idbibank.com'
+ ]);
+ const isBankDomain =
+ emailDomain.endsWith('.bank.in') ||
+ emailDomain.endsWith('.fin.in') ||
+ emailDomain === 'bank.in' ||
+ emailDomain === 'fin.in' ||
+ Array.from(KNOWN_BANK_DOMAINS).some(root => emailDomain === root || emailDomain.endsWith('.' + root));
// In automated test suite or local dev, allow TEST sender and legacy test fixture domains
- const isValidDomain = isBankDomain || sender === 'TEST' || cleanEmail === 'TEST' || sender === 'gmail-browser-automator' || emailDomain.endsWith('.youpi.local') || emailDomain === 'hdfcbank.net';
+ const isValidDomain = isBankDomain || sender === 'TEST' || cleanEmail === 'TEST' || sender === 'gmail-browser-automator' || emailDomain.endsWith('.youpi.local');
if (!isValidDomain) {
if (!isAttributableToCustomer) {
@@ -471,17 +504,27 @@ export class PaymentVerificationPipeline {
}
// Invariant 3: Check 12-digit reference (UTR / RRN)
- let bankRef = null;
- const ref12Patterns = [
- /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([0-9]{12})\b/i,
- /(?:ref\s*no\.?)?[\s:#=-]+([0-9]{12})\b/i,
- /\b([0-9]{12})\b/
- ];
- for (const pat of ref12Patterns) {
- const match = rawText.match(pat);
- if (match && match[1]) {
- bankRef = match[1].trim();
- break;
+ let bankRef = input.bankReferenceNumber || input.utr || null;
+ if (!bankRef) {
+ const ref12Patterns = [
+ /(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([0-9]{12})\b/i,
+ /(?:ref\s*no\.?)?[\s:#=-]+([0-9]{12})\b/i,
+ /\b([0-9]{12})\b/
+ ];
+ for (const pat of ref12Patterns) {
+ const match = rawText.match(pat);
+ if (match && match[1]) {
+ bankRef = match[1].trim();
+ break;
+ }
+ }
+ }
+
+ if (!bankRef && isGmailSource) {
+ const generalRefMatch = rawText.match(/(?:utr|ref(?:\s*no\.?)?|txn\s*(?:id|ref)?|rrn)[:\s#]+([a-zA-Z0-9\-_]{6,35})/i) ||
+ rawText.match(/UPI\/CR\/([a-zA-Z0-9\-_]+)/i);
+ if (generalRefMatch && generalRefMatch[1]) {
+ bankRef = generalRefMatch[1].trim();
}
}
@@ -1073,8 +1116,11 @@ export class PaymentVerificationPipeline {
status: attributionResult.attributed ? 'ATTRIBUTED' : 'UNRESOLVED',
outcomeStatus: attributionResult.outcomeStatus,
details: {
+ attributed: attributionResult.attributed,
+ paymentSessionId: attributionResult.paymentSessionId,
observationId: attributionResult.observationId,
attributedSessionId: attributionResult.paymentSessionId,
+ outcomeStatus: attributionResult.outcomeStatus,
verificationLevel: attributionResult.verificationLevel,
verificationTag: attributionResult.verificationTag
}
@@ -1093,7 +1139,8 @@ export class PaymentVerificationPipeline {
stage5,
stage6,
parsed: parsedData,
- session: updatedSession || session
+ session: updatedSession || session,
+ attribution: attributionResult
});
}
}
diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.js
index 98a9c2a..5b2e9a8 100644
--- a/packages/db/src/migrate.js
+++ b/packages/db/src/migrate.js
@@ -106,6 +106,7 @@ export function runMigrations(targetDb) {
try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);"); } catch {}
try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);"); } catch {}
try { db.exec("CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);"); } catch {}
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);"); } catch {}
// Seed default merchant if empty
const merchantRepo = new MerchantRepository(db);
diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sql
index fa0a210..9d15568 100644
--- a/packages/db/src/schema.sql
+++ b/packages/db/src/schema.sql
@@ -118,6 +118,7 @@ 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);
-- 6. Android Devices Table
CREATE TABLE IF NOT EXISTS android_devices (