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): authenticate observers, harden Android pairing and Gmail OAuth callback
Abhi Pareek897fa05122bf
diff --git a/apps/android-observer-app/__tests__/android-observer.test.js b/apps/android-observer-app/__tests__/android-observer.test.jsindex 339fd6e..73cb8d9 100644--- a/apps/android-observer-app/__tests__/android-observer.test.js+++ b/apps/android-observer-app/__tests__/android-observer.test.js@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../../../apps/payment-api/src/index.js';import { AndroidObserverDriver } from '../driver.js';-import { PaymentStatus } from '@youpi/common';+import { PaymentStatus, resolveSecret } from '@youpi/common';describe('Android Payment Observer Integration Tests', () => {let apiInstance;@@ -34,7 +34,7 @@ describe('Android Payment Observer Integration Tests', () => {});test('successfully pairs Android device with valid enrollment token', async () => {- const enrollmentSecret = process.env.ANDROID_ENROLLMENT_SECRET || 'android_pairing_enrollment_secret_key_32_chars';+ const enrollmentSecret = resolveSecret('android_enrollment_secret', 'ANDROID_ENROLLMENT_SECRET');const pairResult = await driver.pair(enrollmentSecret);assert.ok(pairResult.paired);diff --git a/apps/android-observer-app/simulate-notification.js b/apps/android-observer-app/simulate-notification.jsindex e04d156..67584d5 100644--- a/apps/android-observer-app/simulate-notification.js+++ b/apps/android-observer-app/simulate-notification.js@@ -1,4 +1,5 @@import { AndroidObserverDriver } from './driver.js';+import { resolveSecret } from '@youpi/common';/*** Android Notification Push Simulator CLI.@@ -7,7 +8,7 @@ import { AndroidObserverDriver } from './driver.js';*/const API_BASE = process.env.BASE_PAYMENT_API_URL || 'http://localhost:6100';-const ENROLLMENT_SECRET = process.env.ANDROID_ENROLLMENT_SECRET || 'android_pairing_enrollment_secret_key_32_chars';+const ENROLLMENT_SECRET = resolveSecret('android_enrollment_secret', 'ANDROID_ENROLLMENT_SECRET');async function main() {console.log('========================================================');diff --git a/apps/gmail-observer/src/__tests__/gmail-observer.test.js b/apps/gmail-observer/src/__tests__/gmail-observer.test.jsindex bb20c32..93a18d6 100644--- a/apps/gmail-observer/src/__tests__/gmail-observer.test.js+++ b/apps/gmail-observer/src/__tests__/gmail-observer.test.js@@ -5,7 +5,8 @@ import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../../../payment-api/src/index.js';import { startGmailObserver } from '../index.js';import { BankEmailParser } from '../parser.js';-import { PaymentStatus } from '@youpi/common';+import { PaymentStatus, createOAuthState } from '@youpi/common';+import { TEST_OBSERVER_TOKEN } from '../../../../scripts/test-support.js';describe('Gmail Payment Observer Integration Tests', () => {let apiInstance;@@ -29,9 +30,9 @@ describe('Gmail Payment Observer Integration Tests', () => {testDb.close();});- function get(path) {+ function get(path, headers = {}) {return new Promise((resolve, reject) => {- http.get(`${gmailBaseUrl}${path}`, res => {+ http.get(`${gmailBaseUrl}${path}`, { headers }, res => {let data = '';res.on('data', chunk => { data += chunk; });res.on('end', () => {@@ -91,12 +92,31 @@ describe('Gmail Payment Observer Integration Tests', () => {assert.equal(json.service, 'gmail-observer');});- test('GET /oauth/url returns valid Google OAuth URL', async () => {- const res = await get('/oauth/url');+ test('GET /oauth/url requires a token and returns a Google OAuth URL carrying a signed state', async () => {+ assert.equal((await get('/oauth/url')).status, 401);++ const res = await get('/oauth/url', { Authorization: `Bearer ${TEST_OBSERVER_TOKEN}` });assert.equal(res.status, 200);const json = JSON.parse(res.text);assert.ok(json.authUrl.includes('accounts.google.com/o/oauth2/v2/auth'));assert.ok(json.authUrl.includes('gmail.readonly'));+ assert.ok(new URL(json.authUrl).searchParams.get('state'));+ assert.ok(!json.redirectUri.includes('gauravtesting'));+ });++ test('GET /oauth/callback rejects a missing, forged or reused state', async () => {+ const bad = await get('/oauth/callback?code=abc');+ assert.equal(bad.status, 400);+ assert.ok(bad.text.includes('Invalid or expired OAuth state'));++ const forged = await get('/oauth/callback?code=abc&state=aaaa.9999999999999.bbbb');+ assert.ok(forged.text.includes('Invalid or expired OAuth state'));++ const state = createOAuthState();+ const first = await get(`/oauth/callback?code=abc&state=${encodeURIComponent(state)}`);+ assert.ok(!first.text.includes('Invalid or expired OAuth state')); // passes the state check, fails later (no credentials)+ const replay = await get(`/oauth/callback?code=abc&state=${encodeURIComponent(state)}`);+ assert.ok(replay.text.includes('Invalid or expired OAuth state'));});test('End-to-End: processing bank email confirms active payment session in Payment API', async () => {diff --git a/apps/gmail-observer/src/gmail-poller.js b/apps/gmail-observer/src/gmail-poller.jsindex b798ab5..e66dc98 100644--- a/apps/gmail-observer/src/gmail-poller.js+++ b/apps/gmail-observer/src/gmail-poller.js@@ -1,4 +1,5 @@import { PaymentObserverClient } from '@youpi/observer-sdk';+import { getObserverToken } from '@youpi/common';import { BankEmailParser } from './parser.js';function extractBodyFromGmailPayload(payload) {@@ -68,7 +69,7 @@ export class GmailPoller {async fetchCredentialsFromPaymentApi() {try {- const res = await fetch(`${this.apiBaseUrl}/api/v1/admin/gmail/credentials`);+ const res = await fetch(`${this.apiBaseUrl}/api/v1/admin/gmail/credentials`, { headers: { Authorization: `Bearer ${getObserverToken()}` } });if (res.ok) {const data = await res.json();const conf = data.gmailConfig || data;diff --git a/apps/gmail-observer/src/server.js b/apps/gmail-observer/src/server.jsindex ede3f5f..9d15644 100644--- a/apps/gmail-observer/src/server.js+++ b/apps/gmail-observer/src/server.js@@ -1,4 +1,5 @@import http from 'node:http';+import { hasBearer, getObserverToken, getAdminToken, createOAuthState, consumeOAuthState, resolveGmailRedirectUri } from '@youpi/common';import { GmailPoller } from './gmail-poller.js';import { GmailBrowserAutomator } from './browser-automator.js';@@ -54,13 +55,21 @@ export class GmailObserverServer {// GET /oauth/urlif (pathname === '/oauth/url') {+ // The `state` minted here authorises a later callback, so only trusted callers may request it.+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {+ res.writeHead(401, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Unauthorized' }));+ return;+ }let clientId = '';+ let configuredRedirectUri = '';const apiBase = (this.poller.apiBaseUrl && !this.poller.apiBaseUrl.includes('gauravtesting.online')) ? this.poller.apiBaseUrl : `http://127.0.0.1:${process.env.PAYMENT_API_PORT || 6100}`;try {- const credRes = await fetch(`${apiBase}/api/v1/admin/gmail/credentials`);+ const credRes = await fetch(`${apiBase}/api/v1/admin/gmail/credentials`, { headers: { Authorization: `Bearer ${getObserverToken()}` } });if (credRes.ok) {const credData = await credRes.json();clientId = credData.clientId || credData.gmailConfig?.clientId || '';+ configuredRedirectUri = credData.redirectUri || '';}} catch {}@@ -70,9 +79,9 @@ export class GmailObserverServer {: (process.env.GMAIL_CLIENT_ID || 'mock-youpi-client-id.apps.googleusercontent.com');}- const finalRedirectUri = 'https://pay-gmail.gauravtesting.online/oauth/callback';+ const finalRedirectUri = configuredRedirectUri || resolveGmailRedirectUri();const scope = encodeURIComponent('https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/userinfo.email');- const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(finalRedirectUri)}&response_type=code&scope=${scope}&access_type=offline&prompt=consent&include_granted_scopes=true`;+ const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(finalRedirectUri)}&response_type=code&scope=${scope}&access_type=offline&prompt=consent&include_granted_scopes=true&state=${encodeURIComponent(createOAuthState())}`;res.writeHead(200, {'Content-Type': 'application/json',@@ -87,9 +96,16 @@ export class GmailObserverServer {const code = url.searchParams.get('code');const error = url.searchParams.get('error');+ // Reject callbacks that did not start from an authenticated admin action (login CSRF).+ if (!consumeOAuthState(url.searchParams.get('state'))) {+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });+ res.end('<h1>Invalid or expired OAuth state</h1><p>Start the Google connection again from the Merchant Admin panel.</p>');+ return;+ }+if (error) {res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });- res.end(`<h1>Google OAuth Authorization Error</h1><p>${error}</p>`);+ res.end(`<h1>Google OAuth Authorization Error</h1><p>${String(error).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)}</p>`);return;}@@ -102,14 +118,16 @@ export class GmailObserverServer {try {let clientId = '';let clientSecret = '';+ let callbackRedirectUri = '';const apiBase = (this.poller.apiBaseUrl && !this.poller.apiBaseUrl.includes('gauravtesting.online')) ? this.poller.apiBaseUrl : `http://127.0.0.1:${process.env.PAYMENT_API_PORT || 6100}`;try {- const credRes = await fetch(`${apiBase}/api/v1/admin/gmail/credentials`);+ const credRes = await fetch(`${apiBase}/api/v1/admin/gmail/credentials`, { headers: { Authorization: `Bearer ${getObserverToken()}` } });if (credRes.ok) {const credData = await credRes.json();clientId = credData.clientId || credData.gmailConfig?.clientId || '';clientSecret = credData.clientSecret || credData.gmailConfig?.clientSecret || '';+ callbackRedirectUri = credData.redirectUri || '';}} catch (e) {console.warn('[Gmail Observer] Failed to fetch credentials from Payment API:', e.message);@@ -133,7 +151,7 @@ export class GmailObserverServer {return;}- const redirectUri = 'https://pay-gmail.gauravtesting.online/oauth/callback';+ const redirectUri = callbackRedirectUri || resolveGmailRedirectUri();console.log(`[Gmail Observer] Exchanging OAuth code for tokens with Client ID: ${clientId.substring(0, 15)}... and Redirect URI: ${redirectUri}`);const tokenRes = await fetch('https://oauth2.googleapis.com/token', {@@ -183,7 +201,7 @@ export class GmailObserverServer {try {await fetch(`${apiBase}/api/v1/admin/gmail/credentials`, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getObserverToken()}` },body: JSON.stringify({clientId,clientSecret,@@ -411,6 +429,12 @@ export class GmailObserverServer {// POST /process-email (Direct email ingestion / test injection)if (pathname === '/process-email' && req.method === 'POST') {+ // Direct ingestion feeds the payment pipeline: only the local operator/test tooling may call it.+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {+ res.writeHead(401, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Unauthorized' }));+ return;+ }let body = '';req.on('data', chunk => { body += chunk; });req.on('end', async () => {diff --git a/apps/merchant-admin/src/server.js b/apps/merchant-admin/src/server.jsindex 127a281..39f407d 100644--- a/apps/merchant-admin/src/server.js+++ b/apps/merchant-admin/src/server.js@@ -43,7 +43,6 @@ export class AdminServer {// This completely eliminates CORS errors, tunnel downtime 530s, and cross-origin failures.const clientApiBase = '';html = html.replaceAll('{{API_BASE_URL}}', clientApiBase);- html = html.replaceAll('{{ANDROID_ENROLLMENT_SECRET}}', process.env.ANDROID_ENROLLMENT_SECRET || 'android_pairing_enrollment_secret_key_32_chars');return html;}diff --git a/apps/payment-api/src/routes/pollers.routes.js b/apps/payment-api/src/routes/pollers.routes.jsindex 257d39e..8dcdd54 100644--- a/apps/payment-api/src/routes/pollers.routes.js+++ b/apps/payment-api/src/routes/pollers.routes.js@@ -4,7 +4,8 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { HttpServer } from '../server.js';import { ObservationNormalizer, BankSmsParser, BankEmailParser, generateQrSvg } from '@youpi/core';-import { toRupeesString, toPaise, verifyHmac, resolveRuntimeUrls } from '@youpi/common';+import { toRupeesString, toPaise, verifyHmac, resolveRuntimeUrls, resolveSecret, safeEqual } from '@youpi/common';+import { isAdminRequest } from '../auth-guard.js';const __filename = fileURLToPath(import.meta.url);const __dirname = path.dirname(__filename);@@ -23,7 +24,8 @@ const __dirname = path.dirname(__filename);* }} ctx*/export function registerPollerRoutes(server, ctx) {- const enrollmentSecret = process.env.ANDROID_ENROLLMENT_SECRET || 'android_pairing_enrollment_secret_key_32_chars';+ // No public fallback: env value, else a random secret persisted in data/.secrets/.+ const enrollmentSecret = resolveSecret('android_enrollment_secret', 'ANDROID_ENROLLMENT_SECRET');// GET /api/v1/pollers/active-window (Enables deep intelligent DOM scanning for active amounts and dual-layer verification)server.get('/api/v1/pollers/active-window', async (req, res) => {@@ -73,8 +75,9 @@ export function registerPollerRoutes(server, ctx) {sender,receivingAccountId: body.receivingAccountId,paymentSessionId: body.paymentSessionId,- isTest: Boolean(body.isTest),- testModeActive: Boolean(body.testModeActive)+ // Test flags relax verification: honour them only for the admin credential, never for observers.+ isTest: Boolean(body.isTest) && isAdminRequest(req),+ testModeActive: Boolean(body.testModeActive) && isAdminRequest(req)});if (pipeResult.status === 'REJECTED' && pipeResult.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION') {@@ -151,7 +154,7 @@ export function registerPollerRoutes(server, ctx) {const deviceModel = body.deviceModel || 'Android Device';// Verify enrollment token against system secret or merchant token- if (!token || (token !== enrollmentSecret && token !== `pair_${merchantId.slice(0, 8)}` && token !== 'youpi_sms_pair_token_secure')) {+ if (!token || !safeEqual(String(token), enrollmentSecret)) {HttpServer.json(res, 401, { error: 'Invalid or expired device pairing enrollment token.' });return;}@@ -231,11 +234,17 @@ export function registerPollerRoutes(server, ctx) {return;}- // Verify HMAC Signature & Replay Drift Protection if headers are present+ // Verify HMAC Signature & Replay Drift Protectionconst timestampStr = req.headers['x-timestamp'];const signature = req.headers['x-signature'];- if (timestampStr && signature && device.signing_key_hash) {+ // Signature is mandatory: omitting the headers must not skip verification.+ if (!device.signing_key_hash || !timestampStr || !signature) {+ HttpServer.json(res, 401, { error: 'Missing X-Timestamp / X-Signature headers.' });+ return;+ }++ {const ts = Number(timestampStr);const now = Date.now();if (isNaN(ts) || Math.abs(now - ts) > 60000) {@@ -296,7 +305,7 @@ export function registerPollerRoutes(server, ctx) {sender: body.sender || req.headers['x-sender'],receivingAccountId,paymentSessionId: body.paymentSessionId,- isTest: Boolean(body.isTest),+ isTest: false, // device-supplied flags must never relax verificationdeviceInfo: device ? `${device.device_name} (${device.device_model})` : 'Android SMS Gateway'});diff --git a/apps/sms-observer/src/__tests__/sms-observer.test.js b/apps/sms-observer/src/__tests__/sms-observer.test.jsindex bf06838..a435a43 100644--- a/apps/sms-observer/src/__tests__/sms-observer.test.js+++ b/apps/sms-observer/src/__tests__/sms-observer.test.js@@ -6,6 +6,7 @@ import { startServer as startPaymentApi } from '../../../payment-api/src/index.jimport { startSmsObserver } from '../index.js';import { BankSmsParser } from '../sms-parser.js';import { PaymentStatus } from '@youpi/common';+import { TEST_OBSERVER_TOKEN } from '../../../../scripts/test-support.js';describe('Google Messages / SMS Payment Observer Integration Tests', () => {let apiInstance;@@ -41,6 +42,26 @@ describe('Google Messages / SMS Payment Observer Integration Tests', () => {});}+ describe('Direct ingestion endpoint', () => {+ const post = (headers) => new Promise((resolve, reject) => {+ const req = http.request(`${smsBaseUrl}/process-sms`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers } }, res => {+ res.resume();+ res.on('end', () => resolve(res.statusCode));+ });+ req.on('error', reject);+ req.end(JSON.stringify({ text: 'Rs 500 credited UTR 612345678901', sender: 'HDFCBK' }));+ });++ test('POST /process-sms rejects anonymous and wrong-token callers', async () => {+ assert.equal(await post({}), 401);+ assert.equal(await post({ Authorization: 'Bearer wrong' }), 401);+ });++ test('POST /process-sms accepts the observer token', async () => {+ assert.notEqual(await post({ Authorization: `Bearer ${TEST_OBSERVER_TOKEN}` }), 401);+ });+ });+describe('Bank SMS Parser', () => {test('correctly parses credit SMS with amount, UTR, and sender VPA', () => {const sms = {diff --git a/apps/sms-observer/src/server.js b/apps/sms-observer/src/server.jsindex b5d9fde..f3ec650 100644--- a/apps/sms-observer/src/server.js+++ b/apps/sms-observer/src/server.js@@ -1,4 +1,5 @@import http from 'node:http';+import { hasBearer, getObserverToken, getAdminToken } from '@youpi/common';import { SmsObserverService } from './sms-service.js';import { GoogleMessagesAutomator } from './browser-automator.js';@@ -105,6 +106,12 @@ export class SmsObserverServer {// POST /process-sms (Direct SMS intake / Google Messages Web bridge)if (pathname === '/process-sms' && req.method === 'POST') {+ // Direct ingestion feeds the payment pipeline: only the local operator/test tooling may call it.+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {+ res.writeHead(401, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Unauthorized' }));+ return;+ }let body = '';req.on('data', chunk => { body += chunk; });req.on('end', async () => {diff --git a/packages/observer-sdk/src/client.js b/packages/observer-sdk/src/client.jsindex 3594a68..3c2390e 100644--- a/packages/observer-sdk/src/client.js+++ b/packages/observer-sdk/src/client.js@@ -1,4 +1,4 @@-import { generateHmac } from '@youpi/common';+import { generateHmac, getObserverToken } from '@youpi/common';export class PaymentObserverClient {/**@@ -42,7 +42,7 @@ export class PaymentObserverClient {const res = await fetch(url, {method: 'POST',- headers: { 'Content-Type': 'application/json' },+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getObserverToken()}` },body: JSON.stringify(payload)});