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): require authentication on admin and force-success endpoints
Abhi Pareek6d55b7f61ce6
diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.htmlindex 9bec5e4..b63355b 100644--- a/apps/merchant-admin/src/views/admin.html+++ b/apps/merchant-admin/src/views/admin.html@@ -3171,7 +3171,7 @@<li>In <strong>Google Cloud Console</strong> > <em>Credentials</em>, add this exact redirect URI:<codestyle="color:#38bdf8; display:block; margin:0.2rem 0; background:#020617; padding:2px 6px; border-radius:4px;"- id="guideProdUri">https://pay-gmail.gauravtesting.online/oauth/callback</code>+ id="guideProdUri">(loaded from your configured domain)</code></li><li>Under <em>OAuth consent screen</em> > <em>Test users</em>, ensure your personal Gmail address isadded.</li>@@ -3375,6 +3375,85 @@<div id="cashierFloatingDock" class="cashier-floating-dock"></div><script>+ // --- Admin API authentication ---------------------------------------------------------+ // /api/v1/admin/* requires the admin token (ADMIN_API_TOKEN, or the generated file+ // data/.secrets/admin_api_token on the server). It is kept in sessionStorage for this tab only.+ window.__youpiAdminAuth = (function () {+ const KEY = 'youpi_admin_token';+ const nativeFetch = window.fetch.bind(window);+ let pending = null;++ const read = () => { try { return sessionStorage.getItem(KEY) || ''; } catch (e) { return ''; } };+ const write = (t) => { try { sessionStorage.setItem(KEY, t); } catch (e) {} };+ const clear = () => { try { sessionStorage.removeItem(KEY); } catch (e) {} };++ function isProtected(url) {+ return /\/api\/v1\/admin\//.test(url) && !/\/admin\/sms-gateway\/download-apk/.test(url);+ }++ function prompt(message) {+ if (pending) return pending;+ pending = new Promise((resolve) => {+ const overlay = document.createElement('div');+ overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,.85);display:flex;align-items:center;justify-content:center;padding:16px;font-family:system-ui,sans-serif';+ const box = document.createElement('form');+ box.style.cssText = 'background:#fff;color:#0f172a;border-radius:12px;padding:24px;max-width:420px;width:100%;box-shadow:0 20px 50px rgba(0,0,0,.4)';+ const title = document.createElement('h3');+ title.textContent = 'Admin token required';+ title.style.margin = '0 0 8px';+ const hint = document.createElement('p');+ hint.textContent = message || 'Enter the admin API token (ADMIN_API_TOKEN, or the contents of data/.secrets/admin_api_token on the server).';+ hint.style.cssText = 'margin:0 0 12px;font-size:14px;color:#475569';+ const input = document.createElement('input');+ input.type = 'password';+ input.autocomplete = 'off';+ input.required = true;+ input.style.cssText = 'width:100%;box-sizing:border-box;padding:10px;border:1px solid #cbd5e1;border-radius:8px;margin-bottom:12px';+ const btn = document.createElement('button');+ btn.type = 'submit';+ btn.textContent = 'Unlock';+ btn.style.cssText = 'width:100%;padding:10px;border:0;border-radius:8px;background:#2563eb;color:#fff;font-weight:600;cursor:pointer';+ box.append(title, hint, input, btn);+ overlay.appendChild(box);+ document.body.appendChild(overlay);+ input.focus();+ box.addEventListener('submit', (ev) => {+ ev.preventDefault();+ write(input.value.trim());+ overlay.remove();+ pending = null;+ resolve();+ });+ });+ return pending;+ }++ async function authedFetch(input, init) {+ const url = typeof input === 'string' ? input : (input && input.url) || '';+ if (!isProtected(url)) return nativeFetch(input, init);+ if (!read()) {+ await prompt();+ if (typeof connectAdminEventsSse === 'function') connectAdminEventsSse();+ }+ const attempt = () => {+ const headers = new Headers((init && init.headers) || (input && input.headers) || {});+ headers.set('Authorization', 'Bearer ' + read());+ return nativeFetch(input, Object.assign({}, init, { headers }));+ };+ let res = await attempt();+ if (res.status === 401) {+ clear();+ await prompt('That token was rejected. Enter the admin API token again.');+ res = await attempt();+ if (res.ok && typeof connectAdminEventsSse === 'function') connectAdminEventsSse();+ }+ return res;+ }++ window.fetch = authedFetch;+ return { token: read, ensure: () => (read() ? Promise.resolve() : prompt()) };+ })();+const API_BASE = "{{API_BASE_URL}}";let currentEnvMode = 'localhost';let currentDomainPrefix = 'pay';@@ -5019,7 +5098,7 @@// --- GMAIL DIRECT API & AUTOMATED GOOGLE LOGIN ---function copyGmailRedirectUri() {- const uri = document.getElementById('gmailRedirectUriInput')?.value || 'https://pay-gmail.gauravtesting.online/oauth/callback';+ const uri = document.getElementById('gmailRedirectUriInput')?.value || 'http://localhost:6003/oauth/callback';navigator.clipboard.writeText(uri).then(() => {showAdminToast('Redirect URI copied to clipboard!');});@@ -5149,7 +5228,7 @@if (document.getElementById('gmailClientSecretInput')) document.getElementById('gmailClientSecretInput').value = cfg.clientSecret || data.clientSecret || '';if (document.getElementById('gmailRefreshTokenInput')) document.getElementById('gmailRefreshTokenInput').value = cfg.refreshToken || '';- const redirectUri = data.redirectUri || 'https://pay-gmail.gauravtesting.online/oauth/callback';+ const redirectUri = data.redirectUri || 'http://localhost:6003/oauth/callback';if (document.getElementById('gmailRedirectUriInput')) document.getElementById('gmailRedirectUriInput').value = redirectUri;if (document.getElementById('guideProdUri')) document.getElementById('guideProdUri').textContent = redirectUri;@@ -5436,7 +5515,10 @@function connectAdminEventsSse() {try {- const adminSse = new EventSource(`${API_BASE}/api/v1/admin/stream`);+ // EventSource cannot send an Authorization header, so the stream accepts ?token= (GET only).+ if (!window.__youpiAdminAuth.token()) return; // reconnected right after the token is entered+ if (window.__adminSse) { try { window.__adminSse.close(); } catch (e) {} }+ const adminSse = window.__adminSse = new EventSource(`${API_BASE}/api/v1/admin/stream?token=${encodeURIComponent(window.__youpiAdminAuth.token())}`);adminSse.addEventListener('counter_payment_requested', (event) => {pollGlobalCounterPending();fetchLiveData();diff --git a/apps/payment-api/src/__tests__/auth-guard.test.js b/apps/payment-api/src/__tests__/auth-guard.test.jsnew file mode 100644index 0000000..6f5a889--- /dev/null+++ b/apps/payment-api/src/__tests__/auth-guard.test.js@@ -0,0 +1,144 @@+import { test, describe, before, after } from 'node:test';+import assert from 'node:assert/strict';+import net from 'node:net';+import { Database } from '@youpi/db';+import { startServer as startPaymentApi } from '../index.js';+import { PaymentMethod } from '@youpi/common';+import { TEST_ADMIN_TOKEN, TEST_OBSERVER_TOKEN } from '../../../../scripts/test-support.js';++describe('Auth guard: admin, observer and force-success endpoints', () => {+ let api;+ let baseUrl;+ let db;++ const call = (path, { method = 'GET', token, body } = {}) =>+ fetch(`${baseUrl}${path}`, {+ method,+ headers: {+ 'Content-Type': 'application/json',+ ...(token ? { Authorization: `Bearer ${token}` } : {})+ },+ body: body ? JSON.stringify(body) : undefined+ });++ before(async () => {+ db = new Database({ inMemory: true });+ api = await startPaymentApi(6197, db);+ baseUrl = `http://localhost:${api.port}`;+ });++ after(async () => {+ await api.close();+ db.close();+ });++ test('admin routes reject missing and wrong tokens, accept the admin token', async () => {+ assert.equal((await call('/api/v1/admin/merchant-settings')).status, 401);+ assert.equal((await call('/api/v1/admin/merchant-settings', { token: 'wrong' })).status, 401);+ assert.equal((await call('/api/v1/admin/merchant-settings', { token: TEST_OBSERVER_TOKEN })).status, 401);+ assert.equal((await call('/api/v1/admin/merchant-settings', { token: TEST_ADMIN_TOKEN })).status, 200);+ });++ test('tunnel/start and counter-confirm are not reachable anonymously', async () => {+ const tunnel = await call('/api/v1/admin/tunnel/start', { method: 'POST', body: { command: 'calc.exe' } });+ assert.equal(tunnel.status, 401);+ const confirm = await call('/api/v1/admin/counter-confirm', { method: 'POST', body: { paymentId: 'x', operatorId: 'y' } });+ assert.equal(confirm.status, 401);+ });++ test('tunnel/start refuses a command that contains no tunnel token (nothing is executed)', async () => {+ const res = await call('/api/v1/admin/tunnel/start', {+ method: 'POST',+ token: TEST_ADMIN_TOKEN,+ body: { command: 'calc.exe & echo pwned' }+ });+ assert.equal(res.status, 500);+ assert.match((await res.json()).error, /No valid Cloudflare tunnel token/);+ });++ test('pollers/events needs the observer (or admin) token', async () => {+ const payload = { source: 'GOOGLE_MESSAGES', receivingAccountId: 'nope', rawText: 'Rs 10 credited UTR 123456789012', sender: 'HDFCBK' };+ assert.equal((await call('/api/v1/pollers/events', { method: 'POST', body: payload })).status, 401);+ assert.equal((await call('/api/v1/pollers/events', { method: 'POST', token: 'wrong', body: payload })).status, 401);+ const withObserver = await call('/api/v1/pollers/events', { method: 'POST', token: TEST_OBSERVER_TOKEN, body: payload });+ assert.notEqual(withObserver.status, 401);+ });++ test('simulate-observation is admin-only', async () => {+ const res = await call('/api/v1/checkout/any-id/simulate-observation', {+ method: 'POST',+ body: { rawText: 'Rs 500 credited Ref 612345678901', sender: 'HDFCBK' }+ });+ assert.equal(res.status, 401);+ });++ test('dev test-mode and simulator are admin-only', async () => {+ assert.equal((await call('/api/v1/admin/dev/test-mode', { method: 'POST', body: { enabled: true } })).status, 401);+ assert.equal((await call('/api/v1/admin/dev/simulator/inject', { method: 'POST', body: {} })).status, 401);+ });++ test('developer simulators are disabled in production, even for the admin token', async () => {+ const previous = process.env.NODE_ENV;+ process.env.NODE_ENV = 'production';+ try {+ for (const path of ['/api/v1/admin/dev/test-mode', '/api/v1/admin/dev/simulator/inject', '/api/v1/checkout/x/simulate-observation']) {+ const res = await call(path, { method: 'POST', token: TEST_ADMIN_TOKEN, body: {} });+ assert.equal(res.status, 403, path);+ }+ // Reads and unrelated admin routes keep working.+ assert.equal((await call('/api/v1/admin/merchant-settings', { token: TEST_ADMIN_TOKEN })).status, 200);+ } finally {+ process.env.NODE_ENV = previous;+ }+ });++ test('counter-confirm cannot settle a UPI session, even with the admin token', async () => {+ const created = await call('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'UPI-NO-FORCE-1', amount: '100.00', method: PaymentMethod.UPI, autoActivate: true }+ });+ assert.equal(created.status, 201);+ const { paymentId } = await created.json();++ const res = await call('/api/v1/admin/counter-confirm', {+ method: 'POST',+ token: TEST_ADMIN_TOKEN,+ body: { paymentId, operatorId: 'op1' }+ });+ assert.equal(res.status, 400);++ const state = await (await call(`/api/v1/payments/${paymentId}`)).json();+ assert.notEqual(state.internalStatus, 'SUCCESS');+ });++ test('a counter session can be confirmed once, and not again', async () => {+ const created = await call('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'CASH-OK-1', amount: '50.00', method: PaymentMethod.CASH_COUNTER }+ });+ const { paymentId } = await created.json();+ const first = await call('/api/v1/admin/counter-confirm', { method: 'POST', token: TEST_ADMIN_TOKEN, body: { paymentId, operatorId: 'op1' } });+ assert.equal(first.status, 200);+ const second = await call('/api/v1/admin/counter-confirm', { method: 'POST', token: TEST_ADMIN_TOKEN, body: { paymentId, operatorId: 'op1' } });+ assert.equal(second.status, 409);+ });++ test('the APK download stays public', async () => {+ const apk = await call('/api/v1/admin/sms-gateway/download-apk');+ assert.notEqual(apk.status, 401);+ });++ test('a malformed Host header does not crash the server', async () => {+ const reply = await new Promise((resolve, reject) => {+ const socket = net.connect(api.port, 'localhost', () => {+ socket.write('GET /api/v1/payments/none HTTP/1.1\r\nHost: a b[\r\nConnection: close\r\n\r\n');+ });+ let data = '';+ socket.on('data', c => { data += c; });+ socket.on('close', () => resolve(data));+ socket.on('error', reject);+ });+ assert.match(reply, /^HTTP\/1\.1 (400|404)/);+ assert.equal((await call('/api/v1/payments/none')).status, 404);+ });+});diff --git a/apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.js b/apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.jsindex d579f96..26030c9 100644--- a/apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.js+++ b/apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.js@@ -4,6 +4,7 @@ import http from 'node:http';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('COD Parallel Timer & UPI Queue Decoupling Suite', () => {let apiInstance;@@ -60,7 +61,7 @@ describe('COD Parallel Timer & UPI Queue Decoupling Suite', () => {method: options.method || 'GET',headers: {'Content-Type': 'application/json',- ...(options.headers || {})+ ...authHeadersFor(path), ...(options.headers || {})}},res => {diff --git a/apps/payment-api/src/__tests__/counter-payments.test.js b/apps/payment-api/src/__tests__/counter-payments.test.jsindex e18f676..e78344f 100644--- a/apps/payment-api/src/__tests__/counter-payments.test.js+++ b/apps/payment-api/src/__tests__/counter-payments.test.js@@ -4,6 +4,7 @@ import http from 'node:http';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('Phase 15: Counter Payments (Cash & Card at Counter)', () => {let apiInstance;@@ -26,7 +27,7 @@ describe('Phase 15: Counter Payments (Cash & Card at Counter)', () => {const url = new URL(path, baseUrl);const req = http.request(url, {method: options.method || 'GET',- headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(path), ...(options.headers || {}) }}, res => {let data = '';res.on('data', chunk => { data += chunk; });diff --git a/apps/payment-api/src/__tests__/developer-payment-simulator.test.js b/apps/payment-api/src/__tests__/developer-payment-simulator.test.jsindex 4373765..7c102aa 100644--- a/apps/payment-api/src/__tests__/developer-payment-simulator.test.js+++ b/apps/payment-api/src/__tests__/developer-payment-simulator.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import http from 'node:http';import { Database, CustomerRepository, CustomerSessionRepository, PaymentSessionRepository, MerchantRepository } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('Feature 65: Developer Payment Simulator Integration & Acceptance Suite', () => {let apiInstance;@@ -44,7 +45,7 @@ describe('Feature 65: Developer Payment Simulator Integration & Acceptance Suiteconst url = new URL(path, baseUrl);const headers = {'Content-Type': 'application/json',- ...(options.headers || {})+ ...authHeadersFor(path), ...(options.headers || {})};if (options.merchantAuth !== false && !headers['x-merchant-id']) {headers['x-merchant-id'] = merchantId;@@ -104,7 +105,7 @@ describe('Feature 65: Developer Payment Simulator Integration & Acceptance Suiteassert.equal(unauthRes.status, 401);assert.equal(unauthRes.body.success, false);- // 2. Customer token without merchant auth -> 403+ // 2. A customer session token is not an admin credential -> 401const cust = customerRepo.create({merchantId,name: 'Regular Customer',@@ -122,8 +123,7 @@ describe('Feature 65: Developer Payment Simulator Integration & Acceptance Suite'Authorization': `Bearer ${custToken}`}});- assert.equal(custRes.status, 403);- assert.equal(custRes.body.success, false);+ assert.equal(custRes.status, 401);});test('1, 2, 3. Developer can search existing customer, list sessions, and identify active session', async () => {diff --git a/apps/payment-api/src/__tests__/developer-test-mode.test.js b/apps/payment-api/src/__tests__/developer-test-mode.test.jsindex fa85c02..47c5940 100644--- a/apps/payment-api/src/__tests__/developer-test-mode.test.js+++ b/apps/payment-api/src/__tests__/developer-test-mode.test.js@@ -4,6 +4,7 @@ import http from 'node:http';import { Database, CustomerRepository, PaymentSessionRepository, MerchantRepository } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('Section 12: Developer Test Mode Acceptance Tests (All 29 Points)', () => {let apiInstance;@@ -38,7 +39,7 @@ describe('Section 12: Developer Test Mode Acceptance Tests (All 29 Points)', ()headers: {'Content-Type': 'application/json','x-merchant-id': merchantId,- ...(options.headers || {})+ ...authHeadersFor(path), ...(options.headers || {})}}, res => {let data = '';diff --git a/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.js b/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.jsindex f636bb5..36b4a55 100644--- a/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.js+++ b/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import http from 'node:http';import { Database, CustomerRepository, PaymentSessionRepository, MerchantRepository } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {let apiInstance;@@ -37,7 +38,7 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {headers: {'Content-Type': 'application/json','x-merchant-id': merchantId,- ...(options.headers || {})+ ...authHeadersFor(path), ...(options.headers || {})}}, res => {let data = '';diff --git a/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.js b/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.jsindex f579444..6247824 100644--- a/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.js+++ b/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.js@@ -5,6 +5,7 @@ import { Database, CustomerRepository, PaymentSessionRepository, MerchantRepositimport { extractIntelligentAmount, BankSmsParser, PaymentVerificationPipeline } from '@youpi/core';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('YOUPI PG: Parser Rule Correction & Exact Fraud/Ban System (All 29 Acceptance Tests)', () => {let apiInstance;@@ -54,7 +55,7 @@ describe('YOUPI PG: Parser Rule Correction & Exact Fraud/Ban System (All 29 Acceheaders: {'Content-Type': 'application/json','x-merchant-id': merchantId,- ...(options.headers || {})+ ...authHeadersFor(path), ...(options.headers || {})}}, res => {let data = '';diff --git a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.jsindex ddf8a9e..803670d 100644--- a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js+++ b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js@@ -4,6 +4,7 @@ import http from 'node:http';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod, SellingMode } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & Clean VPA Config', () => {let apiInstance;@@ -26,7 +27,7 @@ describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & Cconst url = new URL(path, baseUrl);const req = http.request(url, {method: options.method || 'GET',- headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(path), ...(options.headers || {}) }}, res => {let data = '';res.on('data', chunk => { data += chunk; });diff --git a/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js b/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.jsindex 6c99e25..e981ba2 100644--- a/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js+++ b/apps/payment-api/src/__tests__/sms-gmail-verification-levels.test.js@@ -4,6 +4,7 @@ import crypto from 'node:crypto';import { Database } from '@youpi/db';import { PaymentStatus, PaymentMethod } from '@youpi/common';import { startServer } from '../index.js';+import { authFetch } from '../../../../scripts/test-support.js';describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests', () => {let apiInstance;@@ -51,7 +52,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',});apiInstance.app.context.queueEngine.enqueueOrActivate(sQ2.id, receivingAccountId);- const clearRes = await fetch(`${baseUrl}/api/v1/admin/queue/clear`, {+ const clearRes = await authFetch(`${baseUrl}/api/v1/admin/queue/clear`, {method: 'POST'});assert.equal(clearRes.status, 200);@@ -101,7 +102,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',});// Check state of session 2 via API- const res = await fetch(`${baseUrl}/api/v1/checkout/${session2.id}/state`);+ const res = await authFetch(`${baseUrl}/api/v1/checkout/${session2.id}/state`);assert.equal(res.status, 200);const state = await res.json();@@ -110,7 +111,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',assert.equal(state.conflictingSession.id, session1.id);// Retrying new payment clears old conflict- const retryRes = await fetch(`${baseUrl}/api/v1/checkout/${session2.id}/retry-new-payment`, {+ const retryRes = await authFetch(`${baseUrl}/api/v1/checkout/${session2.id}/retry-new-payment`, {method: 'POST'});assert.equal(retryRes.status, 200);@@ -124,13 +125,13 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',test('Android SMS Gateway pairs via QR, sends HMAC-signed bank SMS and completes payment', async () => {// 1. Get pairing QR from admin- const qrRes = await fetch(`${baseUrl}/api/v1/admin/sms-gateway/pair-qr`);+ const qrRes = await authFetch(`${baseUrl}/api/v1/admin/sms-gateway/pair-qr`);assert.equal(qrRes.status, 200);const qrData = await qrRes.json();assert.ok(qrData.enrollmentToken);// 2. Mobile app pairs- const pairRes = await fetch(`${baseUrl}/api/v1/observers/sms/pair`, {+ const pairRes = await authFetch(`${baseUrl}/api/v1/observers/sms/pair`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -168,7 +169,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',const sigPayload = `${bodyStr}:${timestamp}`;const signature = crypto.createHmac('sha256', pairData.signingKey).update(sigPayload).digest('hex');- const smsRes = await fetch(`${baseUrl}/api/v1/observers/sms`, {+ const smsRes = await authFetch(`${baseUrl}/api/v1/observers/sms`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -189,7 +190,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',assert.equal(smsResult.attribution.verificationLevel, 1);// 2nd hit arrives from Gmail poller within 5s grace window -> upgrades to Level 2 Dual Verification- const gmailRes = await fetch(`${baseUrl}/api/v1/pollers/events`, {+ const gmailRes = await authFetch(`${baseUrl}/api/v1/pollers/events`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -214,7 +215,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',});test('Gmail credentials can be saved and connection tested via Admin API', async () => {- const saveRes = await fetch(`${baseUrl}/api/v1/admin/gmail/credentials`, {+ const saveRes = await authFetch(`${baseUrl}/api/v1/admin/gmail/credentials`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -228,13 +229,13 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',assert.equal(saveData.success, true);assert.equal(saveData.status, 'CONFIGURED');- const getRes = await fetch(`${baseUrl}/api/v1/admin/gmail/credentials`);+ const getRes = await authFetch(`${baseUrl}/api/v1/admin/gmail/credentials`);assert.equal(getRes.status, 200);const getData = await getRes.json();assert.equal(getData.gmailConfig.clientId, 'test-client-id.apps.googleusercontent.com');// Test connection endpoint- const testRes = await fetch(`${baseUrl}/api/v1/admin/gmail/test`, {+ const testRes = await authFetch(`${baseUrl}/api/v1/admin/gmail/test`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -245,7 +246,7 @@ describe('2-Level Verification (SMS Gateway + Gmail) & Queue Management Tests',});test('Downloads standalone Android APK binary from Payment API', async () => {- const res = await fetch(`${baseUrl}/api/v1/admin/sms-gateway/download-apk`);+ const res = await authFetch(`${baseUrl}/api/v1/admin/sms-gateway/download-apk`);assert.equal(res.status, 200);assert.equal(res.headers.get('content-type'), 'application/vnd.android.package-archive');const buf = await res.arrayBuffer();diff --git a/apps/payment-api/src/__tests__/upi-server-health-and-pc-ui.test.js b/apps/payment-api/src/__tests__/upi-server-health-and-pc-ui.test.jsindex a3c6148..8409668 100644--- a/apps/payment-api/src/__tests__/upi-server-health-and-pc-ui.test.js+++ b/apps/payment-api/src/__tests__/upi-server-health-and-pc-ui.test.js@@ -4,6 +4,7 @@ import http from 'node:http';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { authHeadersFor } from '../../../../scripts/test-support.js';describe('UPI Server Health Indicator & Checkout State Invariants', () => {let apiInstance;@@ -33,7 +34,7 @@ describe('UPI Server Health Indicator & Checkout State Invariants', () => {const url = new URL(path, baseUrl);const req = http.request(url, {method: options.method || 'GET',- headers: { 'Content-Type': 'application/json', ...(options.headers || {}) }+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(path), ...(options.headers || {}) }}, res => {let data = '';res.on('data', chunk => { data += chunk; });diff --git a/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js b/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.jsindex b1964fd..751e567 100644--- a/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js+++ b/apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js@@ -2,6 +2,7 @@ import test from 'node:test';import assert from 'node:assert/strict';import { createPaymentApp } from '../index.js';import { Database } from '@youpi/db';+import { authFetch } from '../../../../scripts/test-support.js';test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite', async (t) => {const customDb = new Database({ inMemory: true });@@ -20,7 +21,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',const apiBase = `http://localhost:${testPort}`;await t.test('1. POST /api/v1/customer/check-user identifies new unregistered mobile', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/check-user`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/check-user`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mobileNumber: '9123456789' })@@ -34,7 +35,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('2. POST /api/v1/customer/check-user rejects malformed phone numbers', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/check-user`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/check-user`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mobileNumber: '123' })@@ -47,7 +48,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',let signupOtp = null;await t.test('3. POST /api/v1/customer/send-otp creates challenge for new customer signup', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/send-otp`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/send-otp`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -67,7 +68,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('4. POST /api/v1/customer/verify-otp rejects incorrect OTP code', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/verify-otp`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/verify-otp`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -84,7 +85,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',let customerId = null;await t.test('5. POST /api/v1/customer/verify-otp completes signup and issues session token', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/verify-otp`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/verify-otp`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -105,7 +106,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('6. POST /api/v1/customer/check-user detects now-existing customer', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/check-user`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/check-user`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mobileNumber: '9123456789' })@@ -120,7 +121,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',let loginOtp = null;await t.test('7. POST /api/v1/customer/send-otp dispatches WhatsApp OTP for existing user', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/send-otp`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/send-otp`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ mobileNumber: '9123456789' })@@ -133,7 +134,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('8. POST /api/v1/customer/verify-otp logs in existing user', async () => {- const res = await fetch(`${apiBase}/api/v1/customer/verify-otp`, {+ const res = await authFetch(`${apiBase}/api/v1/customer/verify-otp`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -149,7 +150,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('9. Merchant WhatsApp status API responds with BerryProtocol metadata', async () => {- const res = await fetch(`${apiBase}/api/v1/admin/whatsapp/status`);+ const res = await authFetch(`${apiBase}/api/v1/admin/whatsapp/status`);assert.equal(res.status, 200);const data = await res.json();assert.equal(data.success, true);@@ -158,7 +159,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('10. Merchant WhatsApp reconnect API triggers pairing QR code generation', async () => {- const res = await fetch(`${apiBase}/api/v1/admin/whatsapp/reconnect`, {+ const res = await authFetch(`${apiBase}/api/v1/admin/whatsapp/reconnect`, {method: 'POST',headers: { 'Content-Type': 'application/json' }});@@ -169,7 +170,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('11. Merchant WhatsApp pairing-code API accepts phone and returns 8-digit code', async () => {- const res = await fetch(`${apiBase}/api/v1/admin/whatsapp/pairing-code`, {+ const res = await authFetch(`${apiBase}/api/v1/admin/whatsapp/pairing-code`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ phoneNumber: '918796266491' })@@ -181,7 +182,7 @@ test('WhatsApp Berry Protocol OTP Customer Auth & Merchant Configuration Suite',});await t.test('12. Merchant WhatsApp disconnect API safely clears session', async () => {- const res = await fetch(`${apiBase}/api/v1/admin/whatsapp/disconnect`, {+ const res = await authFetch(`${apiBase}/api/v1/admin/whatsapp/disconnect`, {method: 'POST',headers: { 'Content-Type': 'application/json' }});diff --git a/apps/payment-api/src/__tests__/whitelabel-branding.test.js b/apps/payment-api/src/__tests__/whitelabel-branding.test.jsindex c52eec2..6f03aa0 100644--- a/apps/payment-api/src/__tests__/whitelabel-branding.test.js+++ b/apps/payment-api/src/__tests__/whitelabel-branding.test.js@@ -2,6 +2,7 @@ import { describe, it, before, after } from 'node:test';import assert from 'node:assert/strict';import { Database } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';+import { authFetch } from '../../../../scripts/test-support.js';describe('White-Label Branding & Visual Gateway Customizer Test Suite', () => {let apiInstance;@@ -25,7 +26,7 @@ describe('White-Label Branding & Visual Gateway Customizer Test Suite', () => {});it('1. GET /api/v1/admin/merchant-settings returns baseline white-label branding', async () => {- const res = await fetch(`${baseUrl}/api/v1/admin/merchant-settings?merchantId=${merchantId}`);+ const res = await authFetch(`${baseUrl}/api/v1/admin/merchant-settings?merchantId=${merchantId}`);assert.strictEqual(res.status, 200);const body = await res.json();assert.ok(body.branding, 'Branding object must be present');@@ -53,7 +54,7 @@ describe('White-Label Branding & Visual Gateway Customizer Test Suite', () => {privacyPolicyUrl: 'https://aurapay.io/privacy'};- const updateRes = await fetch(`${baseUrl}/api/v1/admin/merchant-settings`, {+ const updateRes = await authFetch(`${baseUrl}/api/v1/admin/merchant-settings`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({@@ -67,7 +68,7 @@ describe('White-Label Branding & Visual Gateway Customizer Test Suite', () => {assert.strictEqual(updateBody.success, true);// Read back and assert all fields- const getRes = await fetch(`${baseUrl}/api/v1/admin/merchant-settings?merchantId=${merchantId}`);+ const getRes = await authFetch(`${baseUrl}/api/v1/admin/merchant-settings?merchantId=${merchantId}`);const getData = await getRes.json();const b = getData.branding;@@ -90,7 +91,7 @@ describe('White-Label Branding & Visual Gateway Customizer Test Suite', () => {it('3. Checkout state endpoint propagates updated branding to customer checkout', async () => {// Initiate payment session- const initRes = await fetch(`${baseUrl}/api/v1/payments`, {+ const initRes = await authFetch(`${baseUrl}/api/v1/payments`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -107,7 +108,7 @@ describe('White-Label Branding & Visual Gateway Customizer Test Suite', () => {assert.ok(initData.paymentId);// Fetch checkout state- const stateRes = await fetch(`${baseUrl}/api/v1/checkout/${initData.paymentId}/state`);+ const stateRes = await authFetch(`${baseUrl}/api/v1/checkout/${initData.paymentId}/state`);assert.strictEqual(stateRes.status, 200);const state = await stateRes.json();diff --git a/apps/payment-api/src/auth-guard.js b/apps/payment-api/src/auth-guard.jsnew file mode 100644index 0000000..0d40a6a--- /dev/null+++ b/apps/payment-api/src/auth-guard.js@@ -0,0 +1,74 @@+import { getAdminToken, getObserverToken, safeEqual } from '@youpi/common';+import { HttpServer } from './server.js';++/** Admin-prefixed routes that are intentionally public (static APK download for pairing). */+const PUBLIC_ADMIN_PATHS = new Set(['/api/v1/admin/sms-gateway/download-apk']);++/** Admin-prefixed routes the local observer processes call with the observer token. */+const OBSERVER_ADMIN_PATHS = new Set(['/api/v1/admin/gmail/credentials']);++/** SSE cannot send headers from EventSource, so these accept `?token=` on GET. */+const QUERY_TOKEN_PATHS = new Set(['/api/v1/admin/stream']);++function bearerToken(req) {+ const header = req.headers['authorization'] || '';+ const match = /^Bearer\s+(.+)$/i.exec(header);+ return match ? match[1].trim() : '';+}++function isDevTool(pathname) {+ return pathname.startsWith('/api/v1/admin/dev/') || /^\/api\/v1\/checkout\/[^/]+\/simulate-observation$/.test(pathname);+}++/**+ * Decides which credential a request needs.+ * @returns {null | 'admin' | 'observer'} null = public, 'observer' = admin OR observer token+ */+function requiredLevel(method, pathname) {+ if (pathname.startsWith('/api/v1/admin/')) {+ if (PUBLIC_ADMIN_PATHS.has(pathname)) return null;+ if (OBSERVER_ADMIN_PATHS.has(pathname)) return 'observer';+ return 'admin';+ }+ if (method === 'POST' && pathname === '/api/v1/pollers/events') return 'observer';+ // Injects a synthetic bank message into the real verification pipeline.+ if (method === 'POST' && /^\/api\/v1\/checkout\/[^/]+\/simulate-observation$/.test(pathname)) return 'admin';+ return null;+}++/**+ * Guard for HttpServer.use(). Admin credential = ADMIN_API_TOKEN (or data/.secrets/admin_api_token).+ * Observer credential = OBSERVER_API_TOKEN (or data/.secrets/observer_api_token); admin token also satisfies it.+ */+export function authGuard(req, res, pathname, url) {+ const method = req.method.toUpperCase();++ // Developer simulators push synthetic bank messages into the real pipeline and can settle live sessions.+ if (method !== 'GET' && isDevTool(pathname) && process.env.NODE_ENV === 'production' && process.env.YOUPI_ALLOW_DEV_TOOLS !== 'true') {+ HttpServer.json(res, 403, { error: 'Developer tools are disabled in production.', code: 'DEV_TOOLS_DISABLED' });+ return true;+ }++ const level = requiredLevel(method, pathname);+ if (!level) return false;++ let presented = bearerToken(req);+ if (!presented && method === 'GET' && QUERY_TOKEN_PATHS.has(pathname)) {+ presented = url.searchParams.get('token') || '';+ }++ const ok = presented && (+ safeEqual(presented, getAdminToken()) ||+ (level === 'observer' && safeEqual(presented, getObserverToken()))+ );+ if (ok) return false;++ HttpServer.json(res, 401, { error: 'Unauthorized', code: 'AUTH_REQUIRED' });+ return true;+}++/** True only when the request carries the admin token (observer token is not enough). */+export function isAdminRequest(req) {+ const presented = bearerToken(req);+ return Boolean(presented) && safeEqual(presented, getAdminToken());+}diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex 9ab8083..131d3b4 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -40,6 +40,7 @@ import {PaymentVerificationPipeline} from '@youpi/core';import { HttpServer } from './server.js';+import { authGuard } from './auth-guard.js';import { registerPaymentRoutes } from './routes/payments.routes.js';import { registerCheckoutRoutes } from './routes/checkout.routes.js';import { registerPollerRoutes } from './routes/pollers.routes.js';@@ -112,6 +113,7 @@ export function createPaymentApp(customDb = null, options = {}) {});const server = new HttpServer();+ server.use(authGuard);let checkoutBaseUrl = process.env.BASE_CHECKOUT_URL || 'http://localhost:7000';try {const rootEnv = path.resolve(__dirname, '../../../.env');diff --git a/apps/payment-api/src/server.js b/apps/payment-api/src/server.jsindex fab6c18..ea2acc3 100644--- a/apps/payment-api/src/server.js+++ b/apps/payment-api/src/server.js@@ -7,6 +7,7 @@ import { URL } from 'node:url';export class HttpServer {constructor() {this.routes = [];+ this.guards = [];this.sseClients = new Map(); // sessionId -> Set of res objects}@@ -31,6 +32,15 @@ export class HttpServer {});}+ /**+ * Registers a guard that runs before routing. Return true when the guard has+ * already answered the request (e.g. 401), so no route handler runs.+ * @param {(req: any, res: any, pathname: string, url: URL) => boolean|Promise<boolean>} guard+ */+ use(guard) {+ this.guards.push(guard);+ }+get(pattern, handler) {this.register('GET', pattern, handler);}@@ -127,13 +137,18 @@ export class HttpServer {static async parseBody(req) {return new Promise((resolve, reject) => {let body = '';+ let tooLarge = false;req.on('data', chunk => {+ if (tooLarge) return;body += chunk;if (body.length > 2 * 1024 * 1024) { // 2MB limit+ tooLarge = true;+ body = '';reject(new Error('Payload Too Large'));}});req.on('end', () => {+ if (tooLarge) return;if (!body.trim()) {resolve({});return;@@ -164,10 +179,27 @@ export class HttpServer {return;}- const parsedUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);+ let parsedUrl;+ try {+ // Fixed base: the Host header is attacker-controlled and can make URL parsing throw.+ parsedUrl = new URL(req.url, 'http://localhost');+ } catch {+ HttpServer.json(res, 400, { error: 'Malformed request URL' });+ return;+ }const pathname = parsedUrl.pathname;const method = req.method.toUpperCase();+ try {+ for (const guard of this.guards) {+ if (await guard(req, res, pathname, parsedUrl)) return;+ }+ } catch (err) {+ console.error(`Guard Error [${method} ${pathname}]:`, err);+ HttpServer.json(res, 500, { error: 'Internal Server Error' });+ return;+ }+for (const route of this.routes) {if (route.method === method) {const match = pathname.match(route.regex);diff --git a/packages/db/src/__tests__/auth-matrix.test.js b/packages/db/src/__tests__/auth-matrix.test.jsindex e3786a2..1c65c40 100644--- a/packages/db/src/__tests__/auth-matrix.test.js+++ b/packages/db/src/__tests__/auth-matrix.test.js@@ -30,6 +30,7 @@ import {import { startServer as startPaymentApi } from '../../../../apps/payment-api/src/index.js';import { CoinWalletStoreServer } from '../../../../apps/coin-wallet-store/src/server.js';import { YoupiPaymentClient } from '@youpi/merchant-sdk';+import { authHeadersFor } from '../../../../scripts/test-support.js';test('Full 53-Point Customer Identity, Authentication & Payment Invariant Matrix', async () => {const testDb = new Database({ inMemory: true });@@ -88,6 +89,7 @@ test('Full 53-Point Customer Identity, Authentication & Payment Invariant Matrixconst postData = body ? JSON.stringify(body) : null;const reqHeaders = {'Content-Type': 'application/json',+ ...authHeadersFor(url),...headers};if (postData) {diff --git a/scripts/test-all.js b/scripts/test-all.jsindex 9d8fe73..7ba8d26 100644--- a/scripts/test-all.js+++ b/scripts/test-all.js@@ -19,6 +19,7 @@ const testFiles = ['apps/android-observer-app/__tests__/android-observer.test.js','apps/control-center/src/__tests__/control-center.test.js','apps/payment-api/src/__tests__/payment-api.test.js',+ 'apps/payment-api/src/__tests__/auth-guard.test.js','apps/payment-api/src/__tests__/counter-payments.test.js','apps/payment-api/src/__tests__/selling-modes-and-cod.test.js','apps/payment-api/src/__tests__/developer-payment-simulator.test.js',diff --git a/scripts/test-support.js b/scripts/test-support.jsnew file mode 100644index 0000000..3ffba93--- /dev/null+++ b/scripts/test-support.js@@ -0,0 +1,28 @@+/**+ * Shared test credentials. Importing this module sets the env vars the services read lazily,+ * so in-process servers started by tests accept the tokens below.+ */+export const TEST_ADMIN_TOKEN = 'test-admin-token-0123456789abcdef0123456789abcdef';+export const TEST_OBSERVER_TOKEN = 'test-observer-token-0123456789abcdef0123456789abcd';++process.env.ADMIN_API_TOKEN = TEST_ADMIN_TOKEN;+process.env.OBSERVER_API_TOKEN = TEST_OBSERVER_TOKEN;+// Lets the OTP suites read the code from the response instead of WhatsApp.+process.env.YOUPI_EXPOSE_DEV_OTP = 'true';++/** Admin bearer header, optionally merged with extra headers. */+export function authHeaders(extra = {}) {+ return { Authorization: `Bearer ${TEST_ADMIN_TOKEN}`, ...extra };+}++/** fetch() that carries the admin bearer token on guarded routes (caller headers win). */+export function authFetch(url, init = {}) {+ return fetch(url, { ...init, headers: { ...authHeadersFor(url), ...(init.headers || {}) } });+}++const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/simulate-observation/;++/** Admin bearer header only for routes the gateway guards; other routes (customer auth etc.) get none. */+export function authHeadersFor(path, extra = {}) {+ return GUARDED.test(String(path)) ? authHeaders(extra) : { ...extra };+}