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
feat(engine): enforce Node.js >=24.22.1 LTS security baseline and modernize system architecture diagrams
ArunGupta1526ca18a1ca80fd
diff --git a/AGENTS.md b/AGENTS.mdindex 2d66dc4..074d410 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -88,31 +88,34 @@ YOUPI PG V2 is a self-hosted, sovereign payment gateway designed for zero-fee UP### 2. Universal One-Script Integration#### Step 1: Script Inclusion+Place the script tag in the page's HTML `<head>` or `<body>`:```html-<script- src="https://<youpi-checkout-host>/youpi.js"- data-youpi-key="YOUR_MERCHANT_KEY">-</script>+<script+ src="https://<youpi-checkout-host>/youpi.js"+ data-youpi-key="YOUR_MERCHANT_KEY"+></script>```- 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+Tag any clickable button with `data-youpi-pay`:```html-<button- data-youpi-pay- data-order-id="ORDER-1001"+<button+ data-youpi-pay+ data-order-id="ORDER-1001"data-amount="499"data-currency="INR"data-customer-name="Mohit"data-customer-email="[email protected]"data-customer-phone="9876543210"- data-metadata='{"sku":"TSHIRT-01"}'>+ data-metadata='{"sku":"TSHIRT-01"}'+>Buy Now</button>```@@ -120,28 +123,29 @@ 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`)+For single-page apps (React, Next.js, Vue, Nuxt, Svelte), use the programmatic interface:```javascriptYoupi.pay({order_id: "ORDER-1001",- amount: 499.00,+ amount: 499.0,currency: "INR",customer: {name: "Mohit",email: "[email protected]",- phone: "9876543210"+ phone: "9876543210",},metadata: {sku: "TSHIRT-01",- cart_id: "CART-99"+ cart_id: "CART-99",},- handler: function(response) {+ handler: function (response) {console.log("Payment confirmed in modal:", response);},- onClose: function() {+ onClose: function () {console.log("Modal closed by customer");- }+ },});```@@ -151,16 +155,17 @@ Youpi.pay({The frontend script emits normalized DOM `CustomEvent`s on `window`:-| Event Name | Trigger Condition |-| :--- | :--- |-| `youpi:payment:success` | Payment verified by banking observers |-| `youpi:payment:failed` | Payment declined, wrong amount, or verification timeout |-| `youpi:payment:suspicious` | Payment flagged by security/risk engine |-| `youpi:payment:expired` | 5-minute active payment window expired |-| `youpi:payment:cancelled` | Customer cancelled or dismissed the checkout |-| `youpi:payment:result` | Unified event dispatched on any outcome |+| Event Name | Trigger Condition |+| :------------------------- | :------------------------------------------------------ |+| `youpi:payment:success` | Payment verified by banking observers |+| `youpi:payment:failed` | Payment declined, wrong amount, or verification timeout |+| `youpi:payment:suspicious` | Payment flagged by security/risk engine |+| `youpi:payment:expired` | 5-minute active payment window expired |+| `youpi:payment:cancelled` | Customer cancelled or dismissed the checkout |+| `youpi:payment:result` | Unified event dispatched on any outcome |#### Payload Contract (`event.detail`):+```javascript{"status": "SUCCESS", // 'SUCCESS' | 'FAILED' | 'SUSPICIOUS' | 'EXPIRED' | 'CANCELLED'@@ -182,6 +187,7 @@ The frontend script emits normalized DOM `CustomEvent`s on `window`:> **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:+- **HTTP Method**: `POST`- **Headers**:- `Content-Type: application/json`@@ -191,6 +197,7 @@ The frontend script emits normalized DOM `CustomEvent`s on `window`:- `X-Gateway-Timestamp: <ms>`#### Payload Contract (`payload`):+```json{"event": "SUCCESS",@@ -209,30 +216,39 @@ 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**.#### Node.js (Express) Webhook Verification Example:+```javascript-import crypto from 'node:crypto';--app.post('/api/webhook', express.raw({ type: 'application/json' }), (req, res) => {- const signature = req.headers['x-gateway-signature'] || '';- const secret = process.env.YOUPI_WEBHOOK_SECRET;- const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(req.body).digest('hex');-- if (signature.length !== expected.length ||- !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {- return res.status(401).json({ error: 'Invalid webhook signature' });- }-- const payload = JSON.parse(req.body.toString('utf8'));- if (payload.event === 'SUCCESS' && payload.method === 'UPI') {- db.orders.markPaid(payload.orderId, {- utr: payload.utr,- amount: payload.amount,- amountPaise: payload.amountPaise- });- }-- res.status(200).json({ received: true });-});+import crypto from "node:crypto";++app.post(+ "/api/webhook",+ express.raw({ type: "application/json" }),+ (req, res) => {+ const signature = req.headers["x-gateway-signature"] || "";+ const secret = process.env.YOUPI_WEBHOOK_SECRET;+ const expected =+ "sha256=" ++ crypto.createHmac("sha256", secret).update(req.body).digest("hex");++ if (+ signature.length !== expected.length ||+ !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))+ ) {+ return res.status(401).json({ error: "Invalid webhook signature" });+ }++ const payload = JSON.parse(req.body.toString("utf8"));+ if (payload.event === "SUCCESS" && payload.method === "UPI") {+ db.orders.markPaid(payload.orderId, {+ utr: payload.utr,+ amount: payload.amount,+ amountPaise: payload.amountPaise,+ });+ }++ res.status(200).json({ received: true });+ },+);```---@@ -250,18 +266,18 @@ app.post('/api/webhook', express.raw({ type: 'application/json' }), (req, res) =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`).+ - The project strictly targets **Node.js >= 24.22.1** (Active LTS "Krypton") due to built-in `node:sqlite` (`DatabaseSync` Release Candidate with defensive mode) and security hardening against October 2026 CVEs (CVE-2026-111497 Brotli RCE, CVE-2026-105482 DNS truncation, and CVE-2026-105483 TLS bypass).---### 6. Service Ports (Standard Topology)-| Service | Port | Description |-| :--- | :--- | :--- |-| **Coin Wallet Demo Store** | `5000` | Reference merchant implementation & store |-| **Payment Core REST API** | `6100` | Core gateway engine, state machine, queue |-| **Checkout Portal** | `7000` | Serves `youpi.js`, iframe `/checkout/:id`, API proxy |-| **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 |+| Service | Port | Description |+| :------------------------- | :----- | :--------------------------------------------------- |+| **Coin Wallet Demo Store** | `5000` | Reference merchant implementation & store |+| **Payment Core REST API** | `6100` | Core gateway engine, state machine, queue |+| **Checkout Portal** | `7000` | Serves `youpi.js`, iframe `/checkout/:id`, API proxy |+| **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/ARCHITECTURE.md b/ARCHITECTURE.mdindex 32bb7ad..4eb74dd 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -1,9 +1,9 @@# ARCHITECTURE.md — Canonical System Architecture & Engineering Blueprint> **YOUPI PG V2**-> *Sovereign • Self-Hosted • Zero-Fee • Deterministic UPI Payment Gateway Suite*+> _Sovereign • Self-Hosted • Zero-Fee • Deterministic UPI Payment Gateway Suite_> **Architecture Reference:** Production Specification V2-> **Runtime Target:** Node.js `>= 20.0.0` (ESM Native) • SQLite WAL • Android Kotlin+> **Runtime Target:** Node.js `>= 24.22.1` Active LTS ("Krypton", ESM Native) • SQLite WAL • Android Kotlin---@@ -12,14 +12,18 @@**YOUPI PG** is a sovereign, self-hosted, white-label UPI and multi-modal payment gateway engineered for small-scale merchants, digital creators, and independent businesses in India.### The Problem It Solves+Traditional Indian payment aggregators (Razorpay, Cashfree, PayU, Paytm) impose:+1. **Aggressive Fees:** 2.0% to 3.0% + 18% GST per transaction.2. **Delayed Settlements:** T+2 to T+3 business day settlement cycles that choke operational cash flow.3. **Arbitrary Account Freezes:** Unilateral merchant fund withholding and sudden KYC lockdowns.4. **Phone Spoofing & Fraud:** Fraudulent orders placed using arbitrary fake phone numbers.### The YOUPI PG Solution+YOUPI PG eliminates the aggregator intermediary completely:+- **0% Transaction Fees Forever:** Payments are settled directly into the merchant's bank account via peer-to-peer (P2P) UPI rails.- **Sub-Second Direct Settlement:** Zero holdbacks. Funds land in the merchant's account instantly.- **Deterministic Bank Observation:** Uses incoming cellular Bank SMS and Gmail notifications to verify payment credits cryptographically without official banking API licenses.@@ -33,43 +37,58 @@ YOUPI PG eliminates the aggregator intermediary completely:Every subsystem in YOUPI PG adheres to eight strict mathematical and operational invariants:### Invariant 1 — Deterministic Amount-Only Attribution+Payment attribution enforces a strict equality invariant:$$\text{expected\_amount} == \text{observed\_amount}$$The system never uses fuzzy matching, probabilistic scoring, or guesswork. A payment session transitions to `SUCCESS` if and only if an observed banking credit exactly matches the session's expected amount on the assigned receiving account.### Invariant 2 — Exclusive Single-Active-Slot FIFO Queue+Because standard P2P UPI transfers do not carry programmatic merchant transaction IDs in bank SMS alerts, multiple simultaneous transactions of identical amounts on the same VPA would cause attribution ambiguity.+- **The Invariant:** Exactly **ONE** customer payment session can occupy an `ACTIVE` or `PROCESSING` state on a given receiving VPA at any instant.- **Concurrency Management:** Additional concurrent customers are serialized into a database-backed **FIFO Queue** (`QUEUED` state).- **Live Promotion:** As soon as the active session succeeds, fails, or expires, the queue arbiter atomically promotes customer #1 to `ACTIVE` and pushes real-time Server-Sent Events (SSE) to update the customer's browser.### Invariant 3 — Server-Authoritative Decoupled Dual Timers+Timing is governed exclusively by the backend state machine, not client-side JavaScript:+1. **5-Minute Payment Window (`ACTIVE`):** Countdown for the customer to scan the QR code and pay. Remains immutable across browser refreshes and server reboots.-2. **30-Second Verification Window (`PROCESSING`):** Triggered when the customer clicks *"PAYMENT DONE — CHECK MY PAYMENT"*. Decoupled from the 5-minute timer to allow dedicated, high-frequency observer polling.+2. **30-Second Verification Window (`PROCESSING`):** Triggered when the customer clicks _"PAYMENT DONE — CHECK MY PAYMENT"_. Decoupled from the 5-minute timer to allow dedicated, high-frequency observer polling.### Invariant 4 — Pure Vector SVG QR Code Engine+Generates mathematically genuine ISO/IEC 18004 compliant vector SVG QR codes for standard UPI URIs (`upi://pay?pa=...&pn=...&am=...&cu=INR&tn=...`).+- Zero reliance on external Google Charts or third-party image generation APIs.- Sub-second vector generation that scales crisply to any resolution.### Invariant 5 — Integer Minor Units (Paise) Arithmetic+All financial calculations, database fields, and API contracts represent money strictly as 64-bit integer minor units (**Paise**).+- ₹1.00 = `100` paise | ₹499.00 = `49900` paise.- Zero floating-point representation (`0.1 + 0.2` rounding errors are mathematically impossible).### Invariant 6 — Gateway-Owned Pre-Checkout Identity+The Payment Gateway is the exclusive owner of customer authentication. Merchandising storefronts do not collect or verify customer mobile credentials:+- Customers authenticate via **WhatsApp OTP** powered by Berry Protocol / Baileys multi-device socket.- Eliminates phone number spoofing, unauthenticated bot sessions, and fake orders before slot allocation.### Invariant 7 — Pure Source & SQLite WAL Architecture+The active production persistence layer uses Node.js native `node:sqlite` (`DatabaseSync`) operating in Write-Ahead Logging (`WAL`) mode with foreign key constraints enabled (`PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`).+- Zero external database daemon dependencies.- Zero Docker container overhead.### Invariant 8 — Zero-Config Database Auto-Provisioning+On first system boot or after cloning, YOUPI PG guarantees zero-config database provisioning:+- Automatically detects if `data/youpi_pg.sqlite` and core tables exist (`SELECT count(*) FROM sqlite_master WHERE type='table' AND name='merchants'`).- If missing, creates the parent directory `data/` and runs all schema DDL and baseline seeds idempotently before accepting HTTP traffic.- Eliminates manual database creation scripts and avoids runtime `SqliteError: no such table` crashes entirely.@@ -131,17 +150,20 @@ flowchart TBQueueEngine --> SQLiteDBTimingEngine --> SQLiteDB- AndroidAPK -->|POST /api/v1/observers/sms (Signed)| APIEndpoints- GmailObserver -->|POST /api/v1/observers/gmail| APIEndpoints- SMSObserver -->|POST /api/v1/observers/sms| APIEndpoints+ AndroidAPK -->|"POST /api/v1/observers/sms (Signed)"| APIEndpoints+ GmailObserver -->|"POST /api/v1/observers/gmail"| APIEndpoints+ SMSObserver -->|"POST /api/v1/observers/sms"| APIEndpointsAttributionEngine --> SQLiteDBAttributionEngine --> WebhookEngineWebhookEngine -->|Signed HMAC Webhook| MerchantStore- ControlCenter -.->|Supervises PIDs| CoreBackend- ControlCenter -.->|Supervises PIDs| GatewayFrontend- ControlCenter -.->|Supervises PIDs| ObservationMesh+ ControlCenter -.->|Supervises PIDs| APIEndpoints+ ControlCenter -.->|Supervises PIDs| CheckoutPortal+ ControlCenter -.->|Supervises PIDs| AdminDashboard+ ControlCenter -.->|Supervises PIDs| DemoStore+ ControlCenter -.->|Supervises PIDs| SMSObserver+ ControlCenter -.->|Supervises PIDs| GmailObserver```---@@ -149,6 +171,7 @@ flowchart TB## 4. Subsystem Deep-Dive### 4.1 Invariant Single-Slot Queue Engine+The queue engine guarantees serialized, non-conflicting payment slot assignment.```mermaid@@ -156,19 +179,19 @@ stateDiagram-v2[*] --> INITIATED : Merchant creates checkout sessionINITIATED --> AUTH_PENDING : Customer arrives at portalAUTH_PENDING --> AUTHENTICATED : WhatsApp OTP verified-+AUTHENTICATED --> ACTIVE : Slot available (is_slot_busy = 0)AUTHENTICATED --> QUEUED : Slot occupied (assigned FIFO position #1, #2...)-+QUEUED --> ACTIVE : Prior session completes or expires-+ACTIVE --> PROCESSING : Customer clicks "Payment Done" (30s timer)ACTIVE --> EXPIRED : 5:00 payment window elapsesACTIVE --> CANCELLED : Customer cancels session-+PROCESSING --> SUCCESS : Bank credit verified (L1/L2/L3)PROCESSING --> FAILED : 30s expires with zero credit match-+SUCCESS --> [*]FAILED --> [*]EXPIRED --> [*]@@ -176,34 +199,49 @@ stateDiagram-v2```#### Atomic Slot Acquisition Logic+```javascript// packages/core/src/queue-engine.js (Abstracted Schema)-db.exec('BEGIN IMMEDIATE TRANSACTION');-const account = db.prepare('SELECT is_slot_busy FROM payment_receiving_accounts WHERE id = ?').get(accountId);+db.exec("BEGIN IMMEDIATE TRANSACTION");+const account = db+ .prepare("SELECT is_slot_busy FROM payment_receiving_accounts WHERE id = ?")+ .get(accountId);if (!account.is_slot_busy) {// Acquire Slot Immediately- db.prepare('UPDATE payment_receiving_accounts SET is_slot_busy = 1 WHERE id = ?').run(accountId);- db.prepare(`UPDATE payment_sessions SET+ db.prepare(+ "UPDATE payment_receiving_accounts SET is_slot_busy = 1 WHERE id = ?",+ ).run(accountId);+ db.prepare(+ `UPDATE payment_sessions SETstatus = 'ACTIVE',expires_at = datetime('now', '+5 minutes'),activated_at = datetime('now')- WHERE id = ?`).run(sessionId);+ WHERE id = ?`,+ ).run(sessionId);} else {// Enqueue Customer- const nextPos = db.prepare('SELECT COALESCE(MAX(queue_position), 0) + 1 AS pos FROM payment_sessions WHERE receiving_account_id = ? AND status = "QUEUED"').get(accountId).pos;- db.prepare(`UPDATE payment_sessions SET+ const nextPos = db+ .prepare(+ 'SELECT COALESCE(MAX(queue_position), 0) + 1 AS pos FROM payment_sessions WHERE receiving_account_id = ? AND status = "QUEUED"',+ )+ .get(accountId).pos;+ db.prepare(+ `UPDATE payment_sessions SETstatus = 'QUEUED',queue_position = ?- WHERE id = ?`).run(nextPos, sessionId);+ WHERE id = ?`,+ ).run(nextPos, sessionId);}-db.exec('COMMIT');+db.exec("COMMIT");```---### 4.2 Customer Pre-Gateway WhatsApp Authentication Engine+To prevent phone spoofing, bots, and unauthenticated slot exhaustion, customer identity is owned exclusively by the gateway before payment timers begin:+1. **Step 1 — Mobile Input:** Customer enters 10-digit Indian mobile number.2. **Step 2 — User Check:** Gateway checks `customers` table. If existing, dispatches OTP immediately; if new, captures full name and optional email first.3. **Step 3 — 6-Digit WhatsApp OTP:** The gateway's Baileys multi-device socket generates a cryptographically secure 6-digit numeric OTP and delivers it directly to the customer's WhatsApp app.@@ -212,16 +250,19 @@ To prevent phone spoofing, bots, and unauthenticated slot exhaustion, customer i---### 4.3 Tri-Channel Banking Observation Engine+YOUPI PG captures bank credit alerts across three redundant layers:-| Layer | Component | Mechanism | Security & Integrity |-| :--- | :--- | :--- | :--- |+| Layer | Component | Mechanism | Security & Integrity |+| :---------- | :-------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || **Layer 1** | **Native Android APK** (`com.youpi.observer`) | Intercepts cellular SMS (`android.provider.Telephony.SMS_RECEIVED`) and bank push notifications via `NotificationListenerService`. | Paired via ephemeral QR enrollment token. Dispatches payloads to `/api/v1/observers/sms` signed with **HMAC-SHA256(deviceSecret)** and anti-replay timestamp drift protection ($<60$s). |-| **Layer 2** | **Gmail Observer** (Port 6003) | Google Cloud OAuth2 API polling (`users.messages.list`) or headless CDP Chrome inbox scraper (`@youpi/observer-sdk`). | Scans incoming bank transaction emails matching regex patterns (HDFC, ICICI, SBI, Axis, Kotak, PNB). |-| **Layer 3** | **SMS Observer** (Port 6002) | Headless Chrome CDP automation pairing with Google Messages for Web (`messages.google.com/web`). | Real-time DOM text parsing extracting incoming SMS banking alerts without physical phone cables. |+| **Layer 2** | **Gmail Observer** (Port 6003) | Google Cloud OAuth2 API polling (`users.messages.list`) or headless CDP Chrome inbox scraper (`@youpi/observer-sdk`). | Scans incoming bank transaction emails matching regex patterns (HDFC, ICICI, SBI, Axis, Kotak, PNB). |+| **Layer 3** | **SMS Observer** (Port 6002) | Headless Chrome CDP automation pairing with Google Messages for Web (`messages.google.com/web`). | Real-time DOM text parsing extracting incoming SMS banking alerts without physical phone cables. |#### Unified Normalization & Deduplication+Every incoming observation passes through `ObservationNormalizer`:+- Extracts normalized fields: `amountPaise`, `receivingAccount`, `utr`, `senderVpa`, `timestamp`.- Computes observation cluster fingerprint:$$\text{hash} = \text{SHA-256}(\text{receivingAccount} + \text{amountPaise} + \text{utr} + \text{timeBucket})$$@@ -235,17 +276,17 @@ Every incoming observation passes through `ObservationNormalizer`:### 4.4 Dual Operational Modalities```mermaid-graph TD- GatewayMode[Operational Modality]-- GatewayMode --> OnlineMode[Online Selling Mode]- OnlineMode --> OnlineUPI[UPI Vector QR Code]- OnlineMode --> OnlineCOD[Cash on Delivery with WhatsApp Pre-Verification]-- GatewayMode --> OfflineMode[Offline Store Counter Mode]- OfflineMode --> OfflineUPI[Customer-Facing Dynamic QR]- OfflineMode --> OfflineCash[Cash at Till Desk - CASH_COUNTER]- OfflineMode --> OfflineCard[Card at POS Terminal - CARD_COUNTER]+flowchart TD+ GatewayMode["Operational Modality"]++ GatewayMode --> OnlineMode["Online Selling Mode"]+ OnlineMode --> OnlineUPI["UPI Vector QR Code"]+ OnlineMode --> OnlineCOD["Cash on Delivery (WhatsApp Pre-Verified)"]++ GatewayMode --> OfflineMode["Offline Store Counter Mode"]+ OfflineMode --> OfflineUPI["Customer-Facing Dynamic QR"]+ OfflineMode --> OfflineCash["Cash at Till Desk (CASH_COUNTER)"]+ OfflineMode --> OfflineCard["Card at POS Terminal (CARD_COUNTER)"]```1. **Online Selling Mode:**@@ -263,40 +304,51 @@ graph TDYOUPI PG distributes a single, framework-independent universal browser bundle: [`/youpi.js`](apps/checkout-portal/src/sdk/youpi.js).#### 1. Zero-JS Declarative Button Embedding+Merchants add the script and declarative attributes to any HTML button:-```html-<script src="https://pay.yourdomain.com/youpi.js" data-youpi-key="MERCHANT_PUBLIC_KEY"></script>-<button data-youpi-pay- data-order-id="ORD-1001"- data-amount="499.00"- data-currency="INR">+```html+<script+ src="https://pay.yourdomain.com/youpi.js"+ data-youpi-key="MERCHANT_PUBLIC_KEY"+></script>++<button+ data-youpi-pay+ data-order-id="ORD-1001"+ data-amount="499.00"+ data-currency="INR"+>Buy Now with YOUPI PG</button>```#### 2. Programmatic Invocation (`Youpi.pay`)+For SPAs (React, Next.js, Vue, Nuxt, Angular):+```javascriptwindow.Youpi.pay({checkoutUrl: session.checkoutUrl,- order_id: 'ORD-1001',- amount: 499.00,- currency: 'INR',- name: 'Acme Store',- description: 'Digital License Top-Up',- handler: function(response) {+ order_id: "ORD-1001",+ amount: 499.0,+ currency: "INR",+ name: "Acme Store",+ description: "Digital License Top-Up",+ handler: function (response) {// response: { status: 'SUCCESS', order_id, amount_received, utr }- console.log('Payment Confirmed! UTR:', response.utr);+ console.log("Payment Confirmed! UTR:", response.utr);+ },+ onClose: function () {+ console.log("Customer dismissed modal");},- onClose: function() {- console.log('Customer dismissed modal');- }});```#### 3. Standardized Browser DOM CustomEvents+Driven directly on `window` for reactive UI animations:+- `youpi:payment:success` (`e.detail: { order_id, amount_received, utr }`)- `youpi:payment:failed` (`e.detail: { order_id, reason }`)- `youpi:payment:suspicious` (`e.detail: { order_id }`)@@ -304,6 +356,7 @@ Driven directly on `window` for reactive UI animations:- `youpi:payment:cancelled` (`e.detail: { order_id }`)#### 4. Authoritative Webhook Security Contract+Frontend browser events are never trusted for order fulfillment or provisioning digital goods. Order completion requires verifying the authoritative server-to-server webhook:- **Cryptographic Signature:** Generated via HMAC-SHA256 using the merchant's `webhookSecret` and delivered in header `X-Gateway-Signature: sha256=<64_char_hex_hash>`.@@ -312,30 +365,40 @@ Frontend browser events are never trusted for order fulfillment or provisioning- **Replay Protection & Idempotency:** Every delivery carries an `X-Gateway-Timestamp` (millisecond epoch) and unique `X-Gateway-Delivery-Id` (UUIDv4) to guarantee idempotent order fulfillment and prevent replay attacks.```javascript-import crypto from 'node:crypto';--app.post('/api/youpi-webhook', express.raw({ type: 'application/json' }), (req, res) => {- const signature = req.headers['x-gateway-signature'] || '';- const secret = process.env.YOUPI_WEBHOOK_SECRET;- const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(req.body).digest('hex');-- if (signature.length !== expected.length ||- !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {- return res.status(401).json({ error: 'Signature mismatch' });- }-- const event = JSON.parse(req.body.toString('utf8'));- if (event.event === 'SUCCESS') {- fulfillOrder(event.orderId, event.utr, event.amount);- }- res.json({ received: true });-});+import crypto from "node:crypto";++app.post(+ "/api/youpi-webhook",+ express.raw({ type: "application/json" }),+ (req, res) => {+ const signature = req.headers["x-gateway-signature"] || "";+ const secret = process.env.YOUPI_WEBHOOK_SECRET;+ const expected =+ "sha256=" ++ crypto.createHmac("sha256", secret).update(req.body).digest("hex");++ if (+ signature.length !== expected.length ||+ !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))+ ) {+ return res.status(401).json({ error: "Signature mismatch" });+ }++ const event = JSON.parse(req.body.toString("utf8"));+ if (event.event === "SUCCESS") {+ fulfillOrder(event.orderId, event.utr, event.amount);+ }+ res.json({ received: true });+ },+);```---### 4.6 5 Standardized Merchant Outcome Pages+To prevent broken 404 links and inconsistent customer experiences, YOUPI PG provides 5 canonical outcome pages served from Port 5000:+1. **`/order-success`:** Confirmed bank credit, displays verified UTR, provisions license/digital product.2. **`/order-failed`:** Informs buyer that verification timed out and confirms zero funds were deducted.3. **`/order-suspicious`:** Flagged by fraud heuristics; order held for manual merchant audit.@@ -345,7 +408,9 @@ To prevent broken 404 links and inconsistent customer experiences, YOUPI PG prov---### 4.7 White-Label Customization Engine+Configured via Tab 5 of the Merchant Admin dashboard and persisted in `merchants.branding` JSON:+- **Merchant Brand Name & Subtitle**- **Custom Logo URL & Favicon**- **Custom Accent Color (`--primary`) & Header Gradients**@@ -357,16 +422,16 @@ Configured via Tab 5 of the Merchant Admin dashboard and persisted in `merchants## 5. Network Topology & Port Bindings-| Service | Port | Process Entrypoint | Health Route | Primary Purpose |-| :--- | :---: | :--- | :--- | :--- |-| **Payment Core API** | `6100` | `apps/payment-api/src/index.js` | `GET /health` | State machine, atomic DB transactions, REST API, SSE streams |-| **Checkout Portal** | `7000` | `apps/checkout-portal/src/index.js` | `GET /health` | Customer iframe checkout, dynamic Vector QR, SDK bundle |-| **Merchant Admin** | `6001` | `apps/merchant-admin/src/index.js` | `GET /health` | Admin dashboard, cashier desk, branding customizer, WhatsApp pairing |-| **Showcase Demo Store** | `5000` | `apps/coin-wallet-store/src/index.js` | `GET /health` | Reference enterprise merchant store, outcome pages showcase, SDK testbed |-| **Control Center** | `8090` | `apps/control-center/src/index.js` | `GET /health` | Local process supervisor for starting, stopping, and logging all services |-| **SMS Observer** | `6002` | `apps/sms-observer/src/index.js` | `GET /health` | Google Messages Web CDP automation for cellular SMS parsing |-| **Gmail Observer** | `6003` | `apps/gmail-observer/src/index.js` | `GET /health` | Google Cloud OAuth2 API & Chrome CDP inbox monitoring |-| **Android SMS APK** | N/A | Native Android Device (Foreground) | N/A | Captures incoming cellular banking SMS & push notifications |+| Service | Port | Process Entrypoint | Health Route | Primary Purpose |+| :---------------------- | :----: | :------------------------------------ | :------------ | :------------------------------------------------------------------------ |+| **Payment Core API** | `6100` | `apps/payment-api/src/index.js` | `GET /health` | State machine, atomic DB transactions, REST API, SSE streams |+| **Checkout Portal** | `7000` | `apps/checkout-portal/src/index.js` | `GET /health` | Customer iframe checkout, dynamic Vector QR, SDK bundle |+| **Merchant Admin** | `6001` | `apps/merchant-admin/src/index.js` | `GET /health` | Admin dashboard, cashier desk, branding customizer, WhatsApp pairing |+| **Showcase Demo Store** | `5000` | `apps/coin-wallet-store/src/index.js` | `GET /health` | Reference enterprise merchant store, outcome pages showcase, SDK testbed |+| **Control Center** | `8090` | `apps/control-center/src/index.js` | `GET /health` | Local process supervisor for starting, stopping, and logging all services |+| **SMS Observer** | `6002` | `apps/sms-observer/src/index.js` | `GET /health` | Google Messages Web CDP automation for cellular SMS parsing |+| **Gmail Observer** | `6003` | `apps/gmail-observer/src/index.js` | `GET /health` | Google Cloud OAuth2 API & Chrome CDP inbox monitoring |+| **Android SMS APK** | N/A | Native Android Device (Foreground) | N/A | Captures incoming cellular banking SMS & push notifications |---@@ -391,10 +456,13 @@ data/youpi_pg.sqlite## 7. Verification & Quality Assurance SuiteYOUPI PG enforces zero regression via a unified test runner:+```bashnode scripts/test-all.js```-The suite executes **31 curated test suites** across packages, applications, and chaos-concurrency harnesses in under 18 seconds:++The suite executes **39 curated test suites** across packages, applications, and chaos-concurrency harnesses in under 18 seconds:+- **Common & Contracts:** Types, enums, paise minor units, UPI URIs, crypto builders.- **Database & Repositories:** SQLite migrations, foreign keys, transaction rollbacks, auth matrix.- **Core Engine:** Queue arbitration, dual timers, attribution normalizer, webhooks.diff --git a/README.md b/README.mdindex 1f675f2..3c86890 100644--- a/README.md+++ b/README.md@@ -1,23 +1,23 @@<div align="center">```-██╗ ██╗ ██████╗ ██╗ ██╗██████╗ ██╗ ██████╗ ██████╗-╚██╗ ██╔╝██╔═══██╗██║ ██║██╔══██╗██║ ██╔══██╗██╔════╝+██╗ ██╗ ██████╗ ██╗ ██╗██████╗ ██╗ ██████╗ ██████╗+╚██╗ ██╔╝██╔═══██╗██║ ██║██╔══██╗██║ ██╔══██╗██╔════╝╚████╔╝ ██║ ██║██║ ██║██████╔╝██║ ██████╔╝██║ ███╗╚██╔╝ ██║ ██║██║ ██║██╔═══╝ ██║ ██╔═══╝ ██║ ██║██║ ╚██████╔╝╚██████╔╝██║ ██║ ██║ ╚██████╔╝- ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝+ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝```-# YOUPI PG V2+# YOUPI PG V2### A Self-Hosted UPI Payment Gateway for Merchants-**Originally created by [Gaurav](https://github.com/gxurav1710). The project is now maintained by [Zenuxs](https://zenuxs.in).****0% Gateway Fees • Direct-to-Bank Settlement • WhatsApp Pre-Checkout OTP • Bank SMS & Gmail Observers**> [!IMPORTANT]+>> ## Research Project — Experimental Use Only>> **YOUPI PG V2 is an independent, experimental research and learning project. It is not represented as a certified, bank-approved, NPCI-approved, audited, or production-ready payment gateway.** It is published primarily for external developers to study, test, review, and contribute to.@@ -33,7 +33,6 @@>> Read the applicable bank terms and current official UPI requirements before any real-money use. See the [NPCI UPI FAQ](https://www.npci.org.in/what-we-do/upi/faqs) for merchant onboarding context. This notice is informational and is not legal advice.-<br/>[](https://nodejs.org)@@ -65,13 +64,13 @@<br/>-## Live Product Demos+## Live Product DemosSee **YOUPI PG V2** live in action across Desktop and Mobile checkout flows:-| Desktop Modal Flow | Mobile Drawer & App Switcher |-| :---: | :---: |-| <img src="assets/desktop-demo.gif" width="100%" alt="Desktop Checkout Demo" /><br/><sub>*Full end-to-end checkout: One-script modal, WhatsApp OTP, dynamic vector QR & bank observation.*</sub> | <img src="assets/mobile-demo.gif" width="60%" alt="Mobile Checkout Demo" /><br/><sub>*Ultra-responsive bottom drawer with 1-tap deep-link intent for GPay, PhonePe, Paytm & CRED.*</sub> |+| Desktop Modal Flow | Mobile Drawer & App Switcher |+| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |+| <img src="assets/desktop-demo.gif" width="100%" alt="Desktop Checkout Demo" /><br/><sub>_Full end-to-end checkout: One-script modal, WhatsApp OTP, dynamic vector QR & bank observation._</sub> | <img src="assets/mobile-demo.gif" width="60%" alt="Mobile Checkout Demo" /><br/><sub>_Ultra-responsive bottom drawer with 1-tap deep-link intent for GPay, PhonePe, Paytm & CRED._</sub> || • **Zero-JS One-Script Trigger**: Auto-binds to `[data-youpi-pay]`<br/>• **WhatsApp Pre-Checkout OTP**: Real-time 6-digit phone verification<br/>• **Dynamic Vector SVG QR**: Pure vector QR code with dual timers<br/>• **Experimental observer-based payment detection**: Instant credit via bank SMS/Gmail | • **Responsive Bottom Drawer**: Native app-feel mobile UI<br/>• **Direct UPI App Deep-Linking**: GPay, PhonePe, Paytm, CRED<br/>• **Real-Time Payment Polling**: Instant status reflection<br/>• **Counter Desk Modalities**: Configurable Cash & Card fallback |<br/>@@ -82,27 +81,27 @@ See **YOUPI PG V2** live in action across Desktop and Mobile checkout flows:----## Overview+## OverviewTraditional payment gateways (Razorpay, Cashfree, PayU, Stripe) lock your revenue into high fees, multi-day settlement delays, and sudden compliance freezes:-| Comparison Metric | Traditional Aggregators (Razorpay / Cashfree) | YOUPI PG (Self-Hosted Sovereign) |-| :--- | :--- | :--- |-| **Transaction Fee** | **2.0% – 3.0% + 18% GST** per transaction | **0.0% (Zero Fees Forever)** |-| **Settlement Speed** | **T+2 to T+3 Business Days** (Holdbacks) | **Direct transfer; timing and availability depend on the bank and UPI rails** |-| **Account / Service Risk** | Depends on provider, bank, and circumstances | **Not eliminated**; banks can still restrict accounts and this project has no guarantee against holds or review |-| **Customer Authentication** | SMS OTP (Costly SMS gateway bills, phone spoofing) | **WhatsApp OTP** (Zero spoofing, verified mobile) |-| **Payment Verification** | Aggregator proprietary webhooks | **Bank SMS & Gmail Alerts** parsed in real time |-| **Queue & Mismatch Prevention** | Aggregator pooled virtual accounts | **Invariant Single-Slot FIFO UPI Queue** |-| **Branding Control** | "Secured by Razorpay" badges mandatory | **100% White-Label** (Your brand, your domain, zero mentions) |-| **Offline Retail Till Desk** | Expensive add-ons / dedicated POS hardware | **Built-in POS Cash & Card at Till Billing Mode** |-| **Deployment Simplicity** | Proprietary SaaS lock-in | **Native Node.js host process** (Zero Docker mandatory) |+| Comparison Metric | Traditional Aggregators (Razorpay / Cashfree) | YOUPI PG (Self-Hosted Sovereign) |+| :------------------------------ | :------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |+| **Transaction Fee** | **2.0% – 3.0% + 18% GST** per transaction | **0.0% (Zero Fees Forever)** |+| **Settlement Speed** | **T+2 to T+3 Business Days** (Holdbacks) | **Direct transfer; timing and availability depend on the bank and UPI rails** |+| **Account / Service Risk** | Depends on provider, bank, and circumstances | **Not eliminated**; banks can still restrict accounts and this project has no guarantee against holds or review |+| **Customer Authentication** | SMS OTP (Costly SMS gateway bills, phone spoofing) | **WhatsApp OTP** (Zero spoofing, verified mobile) |+| **Payment Verification** | Aggregator proprietary webhooks | **Bank SMS & Gmail Alerts** parsed in real time |+| **Queue & Mismatch Prevention** | Aggregator pooled virtual accounts | **Invariant Single-Slot FIFO UPI Queue** |+| **Branding Control** | "Secured by Razorpay" badges mandatory | **100% White-Label** (Your brand, your domain, zero mentions) |+| **Offline Retail Till Desk** | Expensive add-ons / dedicated POS hardware | **Built-in POS Cash & Card at Till Billing Mode** |+| **Deployment Simplicity** | Proprietary SaaS lock-in | **Native Node.js host process** (Zero Docker mandatory) |<br/>----## Architecture at a Glance+## Architecture at a GlanceYOUPI PG is designed to use standard Indian personal or business UPI receiving accounts for payment collection by coupling **pure vector SVG QR codes** with an **automated multi-channel banking observation mesh**.@@ -151,44 +150,57 @@ flowchart LR----## Key Features+## Key Features++### 1. No Gateway Fee in the Self-Hosted Model (Not a Reliability or Compliance Guarantee)-### 1. No Gateway Fee in the Self-Hosted Model (Not a Reliability or Compliance Guarantee)Every rupee paid goes straight from your customer's bank account to your bank account via standard NPCI UPI rails. This design does not itself provide regulated payment aggregation or guarantee uninterrupted access to a bank account. Confirm your intended use with your bank and qualified advisers.-### 2. WhatsApp Pre-Checkout Authentication (Berry Protocol)+### 2. WhatsApp Pre-Checkout Authentication (Berry Protocol)+No more fake orders, bot spam, or fraudulent phone numbers. Before a customer can enter the checkout queue, the gateway delivers a cryptographically random 6-digit OTP directly to their WhatsApp app using the embedded Baileys/Berry Protocol socket. Verified customer profiles are remembered in browser `localStorage`.-### 3. Deterministic Single-Slot FIFO Queue Engine+### 3. Deterministic Single-Slot FIFO Queue Engine+Because standard UPI alerts do not carry arbitrary merchant metadata, multiple concurrent transactions with identical amounts could create attribution confusion. YOUPI PG solves this with a mathematical invariant:+- **Only ONE customer can pay on a VPA at a time.**- Other buyers wait in a database-backed FIFO queue with live position streaming.- This queue design is intended to reduce ambiguity when matching incoming payments.-### 4. Native Android Observer APK (`com.youpi.observer`)+### 4. Native Android Observer APK (`com.youpi.observer`)+A lightweight, battery-optimized Android foreground service that captures:+- Cellular banking SMS (`android.provider.Telephony.SMS_RECEIVED`).- Real-time bank push notifications via `NotificationListenerService`.- Enrolls securely via ephemeral QR code and signs all observation payloads with **HMAC-SHA256**.-### 5. Automated Gmail & Google Messages Ingestion+### 5. Automated Gmail & Google Messages Ingestion+Dual backup observation channels:+- **Gmail Observer (Port 6003):** Polls Google Cloud OAuth2 API or automated headless Chrome CDP inbox monitoring.- **SMS Observer (Port 6002):** Connects to Google Messages for Web via Chrome DevTools Protocol (CDP).-### 6. Dual Operational Modalities+### 6. Dual Operational Modalities+- **Online Selling Mode:** UPI Vector QR + Cash on Delivery (COD) with customer pre-purchase verification and decoupled address lifecycle.- **Offline Store Counter Mode:** Designed for physical retail stores. Supports UPI QR, Cash at Till (`CASH_COUNTER`), and Card at POS Terminal (`CARD_COUNTER`) with an interactive real-time cashier till dock and instant SSE customer approval.-### 7. White-Label Configuration+### 7. White-Label Configuration+Rebrand the checkout portal completely through the Merchant Admin Panel:+- Custom app name, logo URL, and browser favicon.- Tailored color palettes, custom gradients, and trust badges.- Custom domain binding via Cloudflare Tunnels (`pay.yourbrand.com`).- Complete removal of any "Powered by YouPI PG" attribution.-### 8. 5 Standardized Merchant Outcome Pages+### 8. 5 Standardized Merchant Outcome Pages+The application includes the following customer outcome pages:+- `/order-success` — Payment verified by observers, order marked paid and provisioned.- `/order-failed` — Verification timed out, reassuring customer no money was lost.- `/order-suspicious` — Flagged by fraud heuristics, held for manual compliance review.@@ -231,13 +243,13 @@ This section is a practical project warning, not a certification, compliance che----## Quickstart in 60 Seconds-+## Quickstart in 60 Seconds+### Prerequisites-- **Node.js `>= 22.13.0` LTS** (Recommended: Node 24 LTS, `node -v`) for native `node:sqlite` (`DatabaseSync`) engine.- `node:sqlite` was added in Node 22.5.0 but only unflagged in **22.13.0**, so 22.5.0–22.12.x cannot run this project without `--experimental-sqlite`.++- **Node.js `>= 24.22.1` Active LTS ("Krypton")** (verify with `node -v`) for native `node:sqlite` (`DatabaseSync` Release Candidate with defensive mode enabled) and hardened protection against October 2026 security advisories (CVE-2026-111497 Brotli RCE, CVE-2026-105482 DNS truncation, and CVE-2026-105483 TLS bypass).- Standard Linux, macOS, or Windows host-- *External database services (PostgreSQL/Redis) are completely optional!*+- _External database services (PostgreSQL/Redis) are completely optional!_> **Note:** Containerisation is not included in this repository yet — there is no `Dockerfile` or> `docker-compose.yml`. Run the services on a native Node.js host as described below.@@ -245,7 +257,9 @@ This section is a practical project warning, not a certification, compliance che### Native Host Quickstart#### 1. Clone & Install Dependencies+Standard `npm install` works out-of-the-box across all packages and apps without any protocol issues:+```bashgit clone https://github.com/youpi-pg/YouPI-PG.git youpi-pgcd youpi-pg@@ -253,13 +267,17 @@ npm install```#### 2. Configure Environment+```bashcp .env.example .env```-*(The default `.env` is pre-configured for localhost out of the box).*++_(The default `.env` is pre-configured for localhost out of the box)._### 3. Start the Services+On first launch, YOUPI PG automatically provisions `data/youpi_pg.sqlite`, creates the directory if missing, and executes idempotent migrations and baseline seeds. No manual database setup is required:+```bashnpm run dev# or@@ -267,17 +285,21 @@ npm start```The services can then be accessed at the following local addresses:-- **Control Center Supervisor:** [`http://localhost:8090`](http://localhost:8090)-- **Merchant Admin Panel:** [`http://localhost:6001`](http://localhost:6001)-- **YOUPI Showcase Demo Store:** [`http://localhost:5000`](http://localhost:5000)-- **Payment REST API:** [`http://localhost:6100`](http://localhost:6100)-- **Customer Checkout Portal:** [`http://localhost:7000`](http://localhost:7000)++- **Control Center Supervisor:** [`http://localhost:8090`](http://localhost:8090)+- **Merchant Admin Panel:** [`http://localhost:6001`](http://localhost:6001)+- **YOUPI Showcase Demo Store:** [`http://localhost:5000`](http://localhost:5000)+- **Payment REST API:** [`http://localhost:6100`](http://localhost:6100)+- **Customer Checkout Portal:** [`http://localhost:7000`](http://localhost:7000)### 4. Run the Full Regression Test Suite+Verify all **31 test suites** across packages, apps, and chaos harnesses:+```bashnpm test```+```text============================================================YOUPI PG V2 — FULL REGRESSION TEST RUNNER@@ -295,54 +317,64 @@ Running 31 curated test suites...----## Universal Merchant Integration+## Universal Merchant IntegrationYOUPI PG can be integrated into a website, web application, or e-commerce store using the following steps.### Step 1: Add the Universal Script to your `<head>`+```html<!-- Official YOUPI PG Universal Integration Script -->-<script src="https://pay.yourdomain.com/youpi.js"- data-youpi-key="YOUR_MERCHANT_PUBLIC_KEY"- data-currency="INR">-</script>+<script+ src="https://pay.yourdomain.com/youpi.js"+ data-youpi-key="YOUR_MERCHANT_PUBLIC_KEY"+ data-currency="INR"+></script>```### Step 2: Declarative Button (Zero JavaScript Required!)+Add `data-youpi-pay` attributes to any existing HTML button:+```html-<button data-youpi-pay- data-order-id="ORDER-1001"- data-amount="499.00"- data-currency="INR">- Buy Now with YOUPI PG+<button+ data-youpi-pay+ data-order-id="ORDER-1001"+ data-amount="499.00"+ data-currency="INR"+>+ Buy Now with YOUPI PG</button>```-*The script automatically intercepts the click, opens a centered desktop modal (or mobile slide-up bottom sheet), and launches the checkout session!*++_The script automatically intercepts the click, opens a centered desktop modal (or mobile slide-up bottom sheet), and launches the checkout session!_### Step 3: Programmatic API (For React, Vue, Next.js, Nuxt)+```javascriptwindow.Youpi.pay({- order_id: 'ORDER-1001',- amount: 499.00,- currency: 'INR',- name: 'Acme Digital Store',- description: 'Pro Subscription Top-Up',- handler: function(response) {+ order_id: "ORDER-1001",+ amount: 499.0,+ currency: "INR",+ name: "Acme Digital Store",+ description: "Pro Subscription Top-Up",+ handler: function (response) {// response: { status: 'SUCCESS', order_id, amount_received, utr }console.log(`Payment confirmed! UTR: ${response.utr}`);window.location.href = `/order-success?order_id=${response.order_id}&utr=${response.utr}`;},- onClose: function() {- console.log('Customer closed payment modal');- }+ onClose: function () {+ console.log("Customer closed payment modal");+ },});```### Step 4: Authoritative Server-to-Server Webhook Verification-> **CRITICAL SECURITY RULE:** Never fulfill orders based solely on frontend browser events. Always verify the backend HMAC-SHA256 signature! Consumers **MUST** compute the HMAC over the raw, unparsed request bytes before any JSON parsing.++> **CRITICAL SECURITY RULE:** Never fulfill orders based solely on frontend browser events. Always verify the backend HMAC-SHA256 signature! Consumers **MUST** compute the HMAC over the raw, unparsed request bytes before any JSON parsing.#### Webhook Contract:+- **Header**: `X-Gateway-Signature: sha256=<64_char_hex_hash>` — `HMAC-SHA256(webhookSecret, rawRequestBody)`- **Additional Headers**:- `X-Gateway-Event: SUCCESS`@@ -369,28 +401,38 @@ window.Youpi.pay({#### Polyglot Webhook Verification Snippets:##### 1. Node.js (Express)+```javascript-import crypto from 'node:crypto';--app.post('/api/youpi-webhook', express.raw({ type: 'application/json' }), (req, res) => {- const signature = req.headers['x-gateway-signature'] || '';- const secret = process.env.YOUPI_WEBHOOK_SECRET;- const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(req.body).digest('hex');-- if (signature.length !== expected.length ||- !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {- return res.status(401).json({ error: 'Invalid webhook signature' });- }-- const payload = JSON.parse(req.body.toString('utf8'));- if (payload.event === 'SUCCESS') {- // Fulfill order: payload.orderId, payload.utr, payload.amount, payload.amountPaise- }- res.status(200).json({ received: true });-});+import crypto from "node:crypto";++app.post(+ "/api/youpi-webhook",+ express.raw({ type: "application/json" }),+ (req, res) => {+ const signature = req.headers["x-gateway-signature"] || "";+ const secret = process.env.YOUPI_WEBHOOK_SECRET;+ const expected =+ "sha256=" ++ crypto.createHmac("sha256", secret).update(req.body).digest("hex");++ if (+ signature.length !== expected.length ||+ !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))+ ) {+ return res.status(401).json({ error: "Invalid webhook signature" });+ }++ const payload = JSON.parse(req.body.toString("utf8"));+ if (payload.event === "SUCCESS") {+ // Fulfill order: payload.orderId, payload.utr, payload.amount, payload.amountPaise+ }+ res.status(200).json({ received: true });+ },+);```##### 2. Python (FastAPI)+```pythonimport hmac, hashlib, jsonfrom fastapi import FastAPI, Request, HTTPException@@ -415,6 +457,7 @@ async def youpi_webhook(request: Request):```##### 3. PHP+```php<?php$rawPayload = file_get_contents('php://input');@@ -439,6 +482,7 @@ echo json_encode(['received' => true]);```##### 4. Go (`net/http`)+```gopackage main@@ -492,42 +536,43 @@ func youpiWebhookHandler(w http.ResponseWriter, r *http.Request) {----## Tri-Channel Observation Mesh+## Tri-Channel Observation MeshYOUPI PG confirms payments without expensive commercial banking APIs using a triple-layer observation pipeline:-```text- CUSTOMER SCANS & PAYS VIA UPI- │- ▼- RECEIVING BANK ACCOUNT- │- ┌──────────────────┼──────────────────┐- ▼ ▼ ▼-┌───────────────┐ ┌───────────────┐ ┌───────────────┐-│ CELLULAR SMS │ │ BANK PUSH │ │ GMAIL CREDIT │-│ ALERT ON SIM │ │ NOTIFICATION │ │ ALERT EMAIL │-└───────┬───────┘ └───────┬───────┘ └───────┬───────┘- │ │ │- ▼ ▼ │-┌──────────────────────────────────┐ │-│ NATIVE ANDROID OBSERVER APK │ │-│ com.youpi.observer (Foreground) │ │-│ HMAC-SHA256 Signed Payload │ │-└─────────────────┬────────────────┘ │- │ ▼- │ ┌───────────────────┐- │ │ GMAIL OBSERVER │- │ │ Google Cloud API │- │ └─────────┬─────────┘- │ │- └─────────────┬─────────────┘- ▼- PAYMENT CORE REST ENGINE- Exact Amount & UTR Normalization- │- ▼- SUCCESS CONFIRMED+```mermaid+flowchart TD+ Customer["Customer Scans & Pays via UPI"]+ Bank["Receiving Bank Account"]++ Customer --> Bank++ subgraph Alerts["Bank Notification Broadcast Channels"]+ SMS["Cellular SMS Alert on SIM"]+ Push["Bank Push Notification"]+ Gmail["Gmail Credit Alert Email"]+ end++ Bank --> SMS+ Bank --> Push+ Bank --> Gmail++ subgraph Observers["Sovereign Banking Observers"]+ AndroidAPK["Native Android Observer APK<br/>com.youpi.observer (Foreground)<br/>HMAC-SHA256 Signed Payload"]+ GmailNode["Gmail Observer Node (Port 6003)<br/>Google Cloud OAuth2 & Web CDP"]+ end++ SMS --> AndroidAPK+ Push --> AndroidAPK+ Gmail --> GmailNode++ Core["Payment Core REST Engine (Port 6100)<br/>Exact Amount & UTR Normalization"]++ AndroidAPK -->|"POST /api/v1/observers/sms (Signed)"| Core+ GmailNode -->|"POST /api/v1/observers/gmail"| Core++ Success["Payment Status: SUCCESS<br/>Authoritative Webhook Dispatched"]+ Core --> Success```1. **Android Observer App:** Install [`apps/android-observer-app/youpi-sms-gateway.apk`](apps/android-observer-app/youpi-sms-gateway.apk) (Certified SHA-256: `959218223e75da4784744c16afaf7bc121cff377dff04f041875237042f51601`) on any secondary Android smartphone with the receiving bank SIM. Scan the pairing QR code in Merchant Admin to establish an encrypted HMAC link.@@ -536,31 +581,33 @@ YOUPI PG confirms payments without expensive commercial banking APIs using a tri<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/>----## Port Topology & Microservices Map+## Port Topology & Microservices Map-| Service | Port | Directory | Entrypoint | Responsibility |-| :--- | :---: | :--- | :--- | :--- |-| **Payment API** | `6100` | [`apps/payment-api`](apps/payment-api) | `src/index.js` | Core REST API, state machine, DB transactions & SSE stream |-| **Checkout Portal** | `7000` | [`apps/checkout-portal`](apps/checkout-portal) | `src/index.js` | Customer iframe checkout, dynamic vector QR, SDK bundle |-| **Merchant Admin** | `6001` | [`apps/merchant-admin`](apps/merchant-admin) | `src/index.js` | Operations panel, till billing desk, branding customizer |-| **Showcase Store** | `5000` | [`apps/coin-wallet-store`](apps/coin-wallet-store) | `src/index.js` | Reference enterprise merchant PDP, 5 outcome demonstrations |-| **Control Center** | `8090` | [`apps/control-center`](apps/control-center) | `src/index.js` | Process supervisor for starting, stopping, and logging all services |-| **SMS Observer** | `6002` | [`apps/sms-observer`](apps/sms-observer) | `src/index.js` | Google Messages Web automation via Chrome CDP |-| **Gmail Observer** | `6003` | [`apps/gmail-observer`](apps/gmail-observer) | `src/index.js` | Gmail Web CDP automation & Google OAuth2 poller |-| **Android APK** | N/A | [`apps/android-observer-app`](apps/android-observer-app) | Android OS | Intercepts cellular banking SMS and notifications |+| Service | Port | Directory | Entrypoint | Responsibility |+| :------------------ | :----: | :------------------------------------------------------- | :------------- | :------------------------------------------------------------------ |+| **Payment API** | `6100` | [`apps/payment-api`](apps/payment-api) | `src/index.js` | Core REST API, state machine, DB transactions & SSE stream |+| **Checkout Portal** | `7000` | [`apps/checkout-portal`](apps/checkout-portal) | `src/index.js` | Customer iframe checkout, dynamic vector QR, SDK bundle |+| **Merchant Admin** | `6001` | [`apps/merchant-admin`](apps/merchant-admin) | `src/index.js` | Operations panel, till billing desk, branding customizer |+| **Showcase Store** | `5000` | [`apps/coin-wallet-store`](apps/coin-wallet-store) | `src/index.js` | Reference enterprise merchant PDP, 5 outcome demonstrations |+| **Control Center** | `8090` | [`apps/control-center`](apps/control-center) | `src/index.js` | Process supervisor for starting, stopping, and logging all services |+| **SMS Observer** | `6002` | [`apps/sms-observer`](apps/sms-observer) | `src/index.js` | Google Messages Web automation via Chrome CDP |+| **Gmail Observer** | `6003` | [`apps/gmail-observer`](apps/gmail-observer) | `src/index.js` | Gmail Web CDP automation & Google OAuth2 poller |+| **Android APK** | N/A | [`apps/android-observer-app`](apps/android-observer-app) | Android OS | Intercepts cellular banking SMS and notifications |<br/>----## Security & Reliability Architecture+## Security & Reliability Architecture- **64-Bit Integer Minor Units (Paise):** Financial values are strictly represented as integers (`49900` paise = ₹499.00). Floating-point rounding drift is mathematically impossible.- **Server-Authoritative Timers:** Timers are calculated strictly from SQLite state timestamps. Client-side browser tampering cannot manipulate countdowns.@@ -572,27 +619,27 @@ YOUPI PG confirms payments without expensive commercial banking APIs using a tri----## Documentation Hub+## Documentation HubDeep-dive engineering manuals and operational runbooks are available in the [`/docs`](docs) directory:-| Document | Description |-| :--- | :--- |-| [`ARCHITECTURE.md`](ARCHITECTURE.md) | **Canonical System Architecture & Engineering Blueprint** |-| [`docs/INSTALLATION.md`](docs/INSTALLATION.md) | Host installation, prerequisites & environment setup |-| [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md) | Environment configuration variables & secret management |-| [`docs/ANDROID_MOBILE_APP.md`](docs/ANDROID_MOBILE_APP.md) | Native Android Kotlin Observer APK guide & permissions |-| [`docs/OBSERVERS_SETUP.md`](docs/OBSERVERS_SETUP.md) | Complete setup for Gmail, Google Messages & Android |-| [`docs/MERCHANT_INTEGRATION.md`](docs/MERCHANT_INTEGRATION.md) | Full developer integration guide, SDK methods & webhooks |-| [`docs/WHITE_LABEL.md`](docs/WHITE_LABEL.md) | White-label branding customizer, domains & Cloudflare |-| [`docs/OPERATIONS_TROUBLESHOOTING.md`](docs/OPERATIONS_TROUBLESHOOTING.md) | Production operations, logs, diagnostics & troubleshooting |-| [`openapi.yaml`](openapi.yaml) | Official OpenAPI 3.0 REST API specification |+| Document | Description |+| :------------------------------------------------------------------------- | :--------------------------------------------------------- |+| [`ARCHITECTURE.md`](ARCHITECTURE.md) | **Canonical System Architecture & Engineering Blueprint** |+| [`docs/INSTALLATION.md`](docs/INSTALLATION.md) | Host installation, prerequisites & environment setup |+| [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md) | Environment configuration variables & secret management |+| [`docs/ANDROID_MOBILE_APP.md`](docs/ANDROID_MOBILE_APP.md) | Native Android Kotlin Observer APK guide & permissions |+| [`docs/OBSERVERS_SETUP.md`](docs/OBSERVERS_SETUP.md) | Complete setup for Gmail, Google Messages & Android |+| [`docs/MERCHANT_INTEGRATION.md`](docs/MERCHANT_INTEGRATION.md) | Full developer integration guide, SDK methods & webhooks |+| [`docs/WHITE_LABEL.md`](docs/WHITE_LABEL.md) | White-label branding customizer, domains & Cloudflare |+| [`docs/OPERATIONS_TROUBLESHOOTING.md`](docs/OPERATIONS_TROUBLESHOOTING.md) | Production operations, logs, diagnostics & troubleshooting |+| [`openapi.yaml`](openapi.yaml) | Official OpenAPI 3.0 REST API specification |<br/>----## License+## LicenseSee [`LICENSE`](LICENSE) for the actual license terms. A license to use the code does not imply regulatory approval, bank approval, security certification, or permission to operate a regulated payment service.@@ -600,7 +647,8 @@ See [`LICENSE`](LICENSE) for the actual license terms. A license to use the code<div align="center">-### YOUPI PG+### YOUPI PG+**Self-hosted payment infrastructure with direct UPI settlement.**⭐ **Contributions and feedback are welcome.**diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.mdindex b572b3d..389de5f 100644--- a/docs/INSTALLATION.md+++ b/docs/INSTALLATION.md@@ -1,13 +1,14 @@# Installation & Host Environment Setup Guide## 1. Operating Environment+YOUPI PG is distributed as source code and is engineered to run directly as native host processes on standard Linux (Ubuntu, Debian, RHEL, CentOS) and Windows 10/11 environments.**Zero Docker Requirement:** Docker, Docker Compose, and external container engines are completely optional and not required. Standard `npm install` works out-of-the-box across all workspace packages.### Prerequisites-- **Node.js:** v22.13.0 or higher (v24 LTS recommended) for native `node:sqlite` (`DatabaseSync`)- (22.5.0–22.12.x cannot run this project: `node:sqlite` is unflagged only from 22.13.0)++- **Node.js:** v24.22.1 Active LTS ("Krypton") or higher (verify with `node -v`) for native `node:sqlite` (`DatabaseSync` Release Candidate with defensive mode) and essential protection against October 2026 security CVEs (CVE-2026-111497, CVE-2026-105482, CVE-2026-105483).- **Database:** Built-in zero-dependency SQLite WAL with automatic schema provisioning (or optional PostgreSQL v14+)- **Java/JDK (Optional, for Android APK build):** OpenJDK 17+- **Docker & Docker Compose (Optional):** For containerized zero-setup execution@@ -67,7 +68,7 @@ npm start## 4. Windows 10 / 11 Setup```powershell-# 1. Verify Node.js (>= v20.0.0)+# 1. Verify Node.js (>= v24.22.1 LTS)node -v# 2. Install dependenciesdiff --git a/package.json b/package.jsonindex 32a8eb4..867b8f7 100644--- a/package.json+++ b/package.json@@ -29,7 +29,7 @@"typescript": "^7.0.2"},"engines": {- "node": ">=24.0.0"+ "node": ">=24.22.1"},"author": "Antigravity Systems","license": "Commercial"