Skip to content

A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.

JavaScript

fix(security): close auth bypass, SSRF, XSS, ReDoS and cross-merchant payment hijack

rishabhaad314f5b01b
diff --git a/apps/checkout-portal/src/index.js b/apps/checkout-portal/src/index.js
index 5e52f46..1f57144 100644
--- a/apps/checkout-portal/src/index.js
+++ b/apps/checkout-portal/src/index.js
@@ -7,8 +7,13 @@ export function startCheckoutServer(port = null, options = {}) {
const checkoutServer = new CheckoutServer(options);
const rawServer = checkoutServer.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[Checkout Portal] Server listening on port ${finalPort}`);
resolve({
port: finalPort,
diff --git a/apps/checkout-portal/src/server.js b/apps/checkout-portal/src/server.js
index cf24f51..4fa3e9f 100644
--- a/apps/checkout-portal/src/server.js
+++ b/apps/checkout-portal/src/server.js
@@ -3,10 +3,49 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { generateQrSvg } from './qr.js';
+import { getInternalServiceToken } from '@youpi/common';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+/** Security headers applied to every response served by the portal. */
+const BASE_SECURITY_HEADERS = Object.freeze({
+ 'X-Content-Type-Options': 'nosniff',
+ 'X-Frame-Options': 'SAMEORIGIN',
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
+ 'Content-Security-Policy': "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
+});
+
+/**
+ * Escapes a value for interpolation into HTML text or attribute context.
+ * Order ids, merchant names and branding fields are attacker-influenced, so they must
+ * never be injected raw into the checkout template.
+ */
+function escapeHtml(value) {
+ return String(value ?? '')
+ .replaceAll('&', '&')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#39;');
+}
+
+/**
+ * Strips hop-by-hop and spoofable internal headers before proxying to the payment core.
+ * Returns a shallow copy so the caller's request object is never mutated.
+ */
+function sanitizedForwardHeaders(req, targetHost) {
+ const headers = { ...req.headers, host: targetHost };
+ for (const name of Object.keys(headers)) {
+ const lower = name.toLowerCase();
+ // Never let a browser claim to be an internal renderer or replay a credential we issue.
+ if (lower === 'x-internal-render' || lower === 'x-internal-token') {
+ delete headers[name];
+ }
+ }
+ return headers;
+}
+
// In production, reliably ensure environment variables from .env are loaded if not already provided
if (!process.env.BASE_PAYMENT_API_URL && typeof process.loadEnvFile === 'function') {
try {
@@ -48,8 +87,8 @@ export class CheckoutServer {
async fetchPaymentState(paymentId) {
try {
const internalPort = process.env.PAYMENT_API_PORT || 6100;
- const res = await fetch(`http://127.0.0.1:${internalPort}/api/v1/checkout/${paymentId}/state`, {
- headers: { 'X-Internal-Render': 'true' }
+ const res = await fetch(`http://127.0.0.1:${internalPort}/api/v1/checkout/${encodeURIComponent(paymentId)}/state`, {
+ headers: { 'X-Internal-Render': 'true', 'X-Internal-Token': getInternalServiceToken() }
});
if (!res.ok) return null;
return await res.json();
@@ -102,33 +141,41 @@ export class CheckoutServer {
const downtimeAltBtnDisplay = ((sellingMode === 'ONLINE' && enabledMethods.includes('COD')) || (sellingMode === 'OFFLINE' && enabledMethods.includes('CASH_COUNTER'))) ? 'inline-block' : 'none';
const downtimeAltBtnLabel = (sellingMode === 'ONLINE') ? 'Pay via Cash on Delivery Instead' : 'Pay by Cash at Till Instead';
- html = html.replaceAll('{{PAYMENT_ID}}', paymentId);
+ // Everything interpolated below is derived from merchant-supplied or customer-supplied data
+ // (order ids, branding, payee names), so it is HTML-escaped. `{{INITIAL_STATE_JSON}}` is
+ // additionally guarded against `<` so it cannot terminate the inline script block.
+ html = html.replaceAll('{{PAYMENT_ID}}', escapeHtml(paymentId));
html = html.replaceAll('{{API_BASE_URL}}', clientApiBase);
- html = html.replaceAll('{{APP_NAME}}', appName);
- html = html.replaceAll('{{PRIMARY_COLOR}}', primaryColor);
- html = html.replaceAll('{{MERCHANT_NAME}}', merchantName);
- html = html.replaceAll('{{ORDER_ID}}', orderId);
- html = html.replaceAll('{{AMOUNT}}', state?.amount || '0.00');
- html = html.replaceAll('{{VPA}}', vpa);
- html = html.replaceAll('{{LOGO_URL}}', logoUrl);
- html = html.replaceAll('{{SIDEBAR_NOTICE}}', sidebarNotice);
- html = html.replaceAll('{{COUNTER_INSTRUCTIONS}}', counterInstructions);
- html = html.replaceAll('{{SERVER_HEALTH_CLASS}}', healthClass);
- html = html.replaceAll('{{SERVER_HEALTH_LABEL}}', healthLabel);
- html = html.replaceAll('{{DOWNTIME_ALERT_STYLE}}', alertStyle);
- html = html.replaceAll('{{DOWNTIME_ALERT_CLASS}}', alertClass);
- html = html.replaceAll('{{DOWNTIME_HEADING}}', alertHeading);
- html = html.replaceAll('{{DOWNTIME_MSG}}', alertMsg);
- html = html.replaceAll('{{METHOD_SELECTOR_DISPLAY}}', showMethodBar);
- html = html.replaceAll('{{TAB_COD_STYLE}}', tabCodStyle);
- html = html.replaceAll('{{TAB_CASH_STYLE}}', tabCashStyle);
- html = html.replaceAll('{{TAB_CARD_STYLE}}', tabCardStyle);
- html = html.replaceAll('{{PC_COD_STYLE}}', pcCodStyle);
- html = html.replaceAll('{{PC_CASH_STYLE}}', pcCashStyle);
- html = html.replaceAll('{{PC_CARD_STYLE}}', pcCardStyle);
- html = html.replaceAll('{{DOWNTIME_ALT_BTN_DISPLAY}}', downtimeAltBtnDisplay);
- html = html.replaceAll('{{DOWNTIME_ALT_BTN_LABEL}}', downtimeAltBtnLabel);
- html = html.replaceAll('{{INITIAL_STATE_JSON}}', JSON.stringify(state || {}).replaceAll('<', '\\u003c'));
+ html = html.replaceAll('{{APP_NAME}}', escapeHtml(appName));
+ html = html.replaceAll('{{PRIMARY_COLOR}}', escapeHtml(primaryColor));
+ html = html.replaceAll('{{MERCHANT_NAME}}', escapeHtml(merchantName));
+ html = html.replaceAll('{{ORDER_ID}}', escapeHtml(orderId));
+ html = html.replaceAll('{{AMOUNT}}', escapeHtml(state?.amount || '0.00'));
+ html = html.replaceAll('{{VPA}}', escapeHtml(vpa));
+ html = html.replaceAll('{{LOGO_URL}}', escapeHtml(logoUrl));
+ html = html.replaceAll('{{SIDEBAR_NOTICE}}', escapeHtml(sidebarNotice));
+ html = html.replaceAll('{{COUNTER_INSTRUCTIONS}}', escapeHtml(counterInstructions));
+ html = html.replaceAll('{{SERVER_HEALTH_CLASS}}', escapeHtml(healthClass));
+ html = html.replaceAll('{{SERVER_HEALTH_LABEL}}', escapeHtml(healthLabel));
+ html = html.replaceAll('{{DOWNTIME_ALERT_STYLE}}', escapeHtml(alertStyle));
+ html = html.replaceAll('{{DOWNTIME_ALERT_CLASS}}', escapeHtml(alertClass));
+ html = html.replaceAll('{{DOWNTIME_HEADING}}', escapeHtml(alertHeading));
+ html = html.replaceAll('{{DOWNTIME_MSG}}', escapeHtml(alertMsg));
+ html = html.replaceAll('{{METHOD_SELECTOR_DISPLAY}}', escapeHtml(showMethodBar));
+ html = html.replaceAll('{{TAB_COD_STYLE}}', escapeHtml(tabCodStyle));
+ html = html.replaceAll('{{TAB_CASH_STYLE}}', escapeHtml(tabCashStyle));
+ html = html.replaceAll('{{TAB_CARD_STYLE}}', escapeHtml(tabCardStyle));
+ html = html.replaceAll('{{PC_COD_STYLE}}', escapeHtml(pcCodStyle));
+ html = html.replaceAll('{{PC_CASH_STYLE}}', escapeHtml(pcCashStyle));
+ html = html.replaceAll('{{PC_CARD_STYLE}}', escapeHtml(pcCardStyle));
+ html = html.replaceAll('{{DOWNTIME_ALT_BTN_DISPLAY}}', escapeHtml(downtimeAltBtnDisplay));
+ html = html.replaceAll('{{DOWNTIME_ALT_BTN_LABEL}}', escapeHtml(downtimeAltBtnLabel));
+ html = html.replaceAll('{{INITIAL_STATE_JSON}}', JSON.stringify(state || {})
+ .replaceAll('<', '\\u003c')
+ .replaceAll('>', '\\u003e')
+ .replaceAll('&', '\\u0026')
+ .replaceAll('\u2028', '\\u2028')
+ .replaceAll('\u2029', '\\u2029'));
return html;
}
@@ -154,8 +201,7 @@ export class CheckoutServer {
path: req.url,
method: req.method,
headers: {
- ...req.headers,
- host: `localhost:${targetPort}`,
+ ...sanitizedForwardHeaders(req, `localhost:${targetPort}`),
'x-forwarded-host': req.headers.host || '',
'x-forwarded-proto': req.headers['x-forwarded-proto'] || 'https'
}
@@ -227,7 +273,8 @@ export class CheckoutServer {
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
'Pragma': 'no-cache',
'Expires': '0',
- 'Access-Control-Allow-Origin': '*'
+ 'Access-Control-Allow-Origin': '*',
+ ...BASE_SECURITY_HEADERS
});
res.end(svg);
return;
@@ -240,13 +287,14 @@ export class CheckoutServer {
const state = await this.fetchPaymentState(paymentId);
const rendered = this.renderHtml(paymentId, state);
- res.writeHead(200, {
- 'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
- 'Pragma': 'no-cache',
- 'Expires': '0',
- 'Access-Control-Allow-Origin': '*'
- });
+res.writeHead(200, {
+ 'Content-Type': 'text/html; charset=utf-8',
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ 'Pragma': 'no-cache',
+ 'Expires': '0',
+ 'Access-Control-Allow-Origin': '*',
+ ...BASE_SECURITY_HEADERS
+ });
res.end(rendered);
return;
}
diff --git a/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js b/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js
index 2eab4ba..49964d1 100644
--- a/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js
+++ b/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js
@@ -1,5 +1,6 @@
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
import http from 'node:http';
import { Database } from '@youpi/db';
import { startServer as startPaymentApi } from '../../../payment-api/src/index.js';
@@ -33,6 +34,16 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {
storeBaseUrl = `http://localhost:${storeInstance.port}`;
});
+ /** Headers the real gateway always sends with every signed delivery. */
+ function gatewayHeaders(payloadString, overrides = {}) {
+ return {
+ 'X-Gateway-Signature': `sha256=${generateHmac(payloadString, storeSecret)}`,
+ 'X-Gateway-Delivery-Id': crypto.randomUUID(),
+ 'X-Gateway-Timestamp': Date.now().toString(),
+ ...overrides
+ };
+ }
+
after(async () => {
await storeInstance.close();
await apiInstance.close();
@@ -120,13 +131,10 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {
};
const payloadString = JSON.stringify(payloadObj);
- const signature = generateHmac(payloadString, storeSecret);
const hookRes = await request('/api/webhook', {
method: 'POST',
- headers: {
- 'X-Gateway-Signature': `sha256=${signature}`
- },
+ headers: gatewayHeaders(payloadString),
body: payloadString
});
@@ -147,14 +155,12 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {
const payloadString = JSON.stringify({ event: 'SUCCESS', orderId: 'FAKE' });
const hookRes = await request('/api/webhook', {
method: 'POST',
- headers: {
- 'X-Gateway-Signature': 'sha256=invalid_fake_signature_hash'
- },
+ headers: gatewayHeaders(payloadString, { 'X-Gateway-Signature': 'sha256=invalid_fake_signature_hash' }),
body: payloadString
});
- assert.equal(hookRes.status, 400);
- assert.ok(hookRes.body.error.includes('signature mismatch'));
+ assert.equal(hookRes.status, 401);
+ assert.ok(hookRes.body.error.includes('signature'));
});
test('GET /wallet renders wallet page with updated balance', async () => {
@@ -201,11 +207,10 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {
};
const payloadString = JSON.stringify(payloadObj);
- const signature = generateHmac(payloadString, storeSecret);
const hookRes = await request('/api/webhook', {
method: 'POST',
- headers: { 'X-Gateway-Signature': `sha256=${signature}` },
+ headers: gatewayHeaders(payloadString),
body: payloadString
});
@@ -240,11 +245,10 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {
metadata: { coins: 1, packName: 'Micro Top-Up' }
};
const payloadString = JSON.stringify(payloadObj);
- const signature = generateHmac(payloadString, storeSecret);
const hookRes = await request('/api/webhook', {
method: 'POST',
- headers: { 'X-Gateway-Signature': `sha256=${signature}` },
+ headers: gatewayHeaders(payloadString),
body: payloadString
});
diff --git a/apps/coin-wallet-store/src/index.js b/apps/coin-wallet-store/src/index.js
index 37d5213..65252b5 100644
--- a/apps/coin-wallet-store/src/index.js
+++ b/apps/coin-wallet-store/src/index.js
@@ -7,8 +7,13 @@ export function startCoinWalletStore(port = null, options = {}) {
const storeServer = new CoinWalletStoreServer(options);
const rawServer = storeServer.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[Coin Wallet Store] Demo Store online at http://localhost:${finalPort}`);
resolve({
server: storeServer,
diff --git a/apps/coin-wallet-store/src/server.js b/apps/coin-wallet-store/src/server.js
index 350ba3d..db64f76 100644
--- a/apps/coin-wallet-store/src/server.js
+++ b/apps/coin-wallet-store/src/server.js
@@ -8,6 +8,56 @@ import { getCoinStoreWebhookSecret } from '@youpi/common';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+/** Security headers applied to every HTML response served by the store. */
+const BASE_SECURITY_HEADERS = Object.freeze({
+ 'X-Content-Type-Options': 'nosniff',
+ 'X-Frame-Options': 'SAMEORIGIN',
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
+ 'Content-Security-Policy': "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
+});
+
+/**
+ * Escapes a value for interpolation into HTML text or attribute context.
+ * Order ids, UTRs and failure reasons arrive from query parameters, so they must never be
+ * injected raw into the order-status templates.
+ */
+function escapeHtml(value) {
+ return String(value ?? '')
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#39;');
+}
+
+/** Upper bound for an unauthenticated JSON request body. */
+const MAX_JSON_BODY_BYTES = 64 * 1024;
+/** Largest single top-up the demo store accepts. */
+const MAX_TOPUP_RUPEES = 100000;
+/** Accepted clock skew for an inbound webhook's X-Gateway-Timestamp. */
+const WEBHOOK_MAX_SKEW_MS = 5 * 60 * 1000;
+
+/** Keeps a client-supplied pack name printable and bounded before it is stored as metadata. */
+function sanitizePackName(value) {
+ const cleaned = String(value ?? '').replace(/[^\w .&()'-]/g, '').trim().slice(0, 60);
+ return cleaned || 'Gamer Pack';
+}
+
+/**
+ * Strips headers that would let a browser claim to be an internal renderer before the
+ * request is relayed to the payment core.
+ */
+function sanitizedForwardHeaders(req, targetHost) {
+ const headers = { ...req.headers, host: targetHost };
+ for (const name of Object.keys(headers)) {
+ const lower = name.toLowerCase();
+ if (lower === 'x-internal-render' || lower === 'x-internal-token') {
+ delete headers[name];
+ }
+ }
+ return headers;
+}
+
// In production, reliably ensure environment variables from .env are loaded if not already provided
if (!process.env.BASE_PAYMENT_API_URL && typeof process.loadEnvFile === 'function') {
try {
@@ -32,9 +82,18 @@ export class CoinWalletStoreServer {
this.merchantId = options.merchantId || '00000000-0000-0000-0000-000000000001';
this.webhookSecret = options.webhookSecret || getCoinStoreWebhookSecret();
+ // Canonical public origin of this store. Post-payment return URLs are built from this
+ // value rather than from the request's Host / X-Forwarded-* headers, which are
+ // attacker-controllable and would otherwise allow redirecting paying customers elsewhere.
+ this.publicBaseUrl = (options.publicBaseUrl || process.env.COIN_STORE_PUBLIC_URL || `http://localhost:${process.env.STORE_PORT || 5000}`)
+ .replace(/\/+$/, '');
+
// orderId -> gateway paymentId for orders this store created (used to verify payments server-side)
this.orderPayments = new Map();
+ // Recently processed X-Gateway-Delivery-Id values, used to reject replayed webhooks.
+ this.seenDeliveryIds = new Map();
+
this.paymentClient = new YoupiPaymentClient({
apiUrl: this.gatewayApiUrl,
merchantId: this.merchantId,
@@ -65,6 +124,15 @@ export class CoinWalletStoreServer {
});
}
+ /** Records a processed delivery id and prunes entries older than the accepted skew window. */
+ rememberDeliveryId(deliveryId) {
+ const now = Date.now();
+ for (const [id, seenAt] of this.seenDeliveryIds) {
+ if (now - seenAt > WEBHOOK_MAX_SKEW_MS * 2) this.seenDeliveryIds.delete(id);
+ }
+ this.seenDeliveryIds.set(deliveryId, now);
+ }
+
createServer() {
return http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
@@ -142,8 +210,7 @@ export class CoinWalletStoreServer {
path: req.url,
method: req.method,
headers: {
- ...req.headers,
- host: `localhost:${portalPort}`,
+ ...sanitizedForwardHeaders(req, `localhost:${portalPort}`),
'x-forwarded-host': req.headers.host || '',
'x-forwarded-proto': req.headers['x-forwarded-proto'] || 'http'
}
@@ -173,8 +240,7 @@ export class CoinWalletStoreServer {
path: req.url,
method: req.method,
headers: {
- ...req.headers,
- host: `${parsedGateway.hostname}:${parsedGateway.port}`,
+ ...sanitizedForwardHeaders(req, `${parsedGateway.hostname}:${parsedGateway.port}`),
'x-forwarded-host': req.headers.host || '',
'x-forwarded-proto': req.headers['x-forwarded-proto'] || 'http'
}
@@ -206,7 +272,8 @@ export class CoinWalletStoreServer {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
'Pragma': 'no-cache',
- 'Expires': '0'
+ 'Expires': '0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(this.storeHtml);
@@ -220,7 +287,8 @@ export class CoinWalletStoreServer {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
'Pragma': 'no-cache',
- 'Expires': '0'
+ 'Expires': '0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(this.walletHtml);
@@ -237,15 +305,16 @@ export class CoinWalletStoreServer {
const timestamp = new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' });
let rendered = this.orderSuccessHtml
- .replaceAll('{{ORDER_ID}}', orderId)
- .replaceAll('{{AMOUNT}}', amount)
- .replaceAll('{{UTR}}', utr)
- .replaceAll('{{MODE}}', mode)
- .replaceAll('{{TIMESTAMP}}', timestamp);
+ .replaceAll('{{ORDER_ID}}', escapeHtml(orderId))
+ .replaceAll('{{AMOUNT}}', escapeHtml(amount))
+ .replaceAll('{{UTR}}', escapeHtml(utr))
+ .replaceAll('{{MODE}}', escapeHtml(mode))
+ .replaceAll('{{TIMESTAMP}}', escapeHtml(timestamp));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(rendered);
@@ -258,13 +327,14 @@ export class CoinWalletStoreServer {
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
const reason = url.searchParams.get('reason') || 'Transaction verification timed out or declined.';
let rendered = this.orderFailedHtml
- .replaceAll('{{ORDER_ID}}', orderId)
- .replaceAll('ORDER-#', orderId)
- .replaceAll('{{REASON}}', reason);
+ .replaceAll('{{ORDER_ID}}', escapeHtml(orderId))
+ .replaceAll('ORDER-#', escapeHtml(orderId))
+ .replaceAll('{{REASON}}', escapeHtml(reason));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(rendered);
@@ -275,11 +345,12 @@ export class CoinWalletStoreServer {
if ((pathname === '/order-suspicious' || pathname === '/suspicious') && (method === 'GET' || method === 'HEAD')) {
try { this.orderSuspiciousHtml = fs.readFileSync(path.join(__dirname, 'order-suspicious.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
- let rendered = this.orderSuspiciousHtml.replaceAll('{{ORDER_ID}}', orderId);
+ let rendered = this.orderSuspiciousHtml.replaceAll('{{ORDER_ID}}', escapeHtml(orderId));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(rendered);
@@ -290,11 +361,12 @@ export class CoinWalletStoreServer {
if ((pathname === '/order-expired' || pathname === '/expired') && (method === 'GET' || method === 'HEAD')) {
try { this.orderExpiredHtml = fs.readFileSync(path.join(__dirname, 'order-expired.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
- let rendered = this.orderExpiredHtml.replaceAll('{{ORDER_ID}}', orderId);
+ let rendered = this.orderExpiredHtml.replaceAll('{{ORDER_ID}}', escapeHtml(orderId));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(rendered);
@@ -305,11 +377,12 @@ export class CoinWalletStoreServer {
if ((pathname === '/order-cancelled' || pathname === '/cancelled') && (method === 'GET' || method === 'HEAD')) {
try { this.orderCancelledHtml = fs.readFileSync(path.join(__dirname, 'order-cancelled.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
- let rendered = this.orderCancelledHtml.replaceAll('{{ORDER_ID}}', orderId);
+ let rendered = this.orderCancelledHtml.replaceAll('{{ORDER_ID}}', escapeHtml(orderId));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ ...BASE_SECURITY_HEADERS
});
if (method === 'HEAD') { res.end(); return; }
res.end(rendered);
@@ -332,22 +405,42 @@ export class CoinWalletStoreServer {
// POST /api/checkout (Customer clicks purchase pack)
if (pathname === '/api/checkout' && method === 'POST') {
let body = '';
- req.on('data', chunk => { body += chunk; });
+ let bodyTooLarge = false;
+ req.on('data', chunk => {
+ if (bodyTooLarge) return;
+ body += chunk;
+ if (body.length > MAX_JSON_BODY_BYTES) { bodyTooLarge = true; body = ''; }
+ });
req.on('end', async () => {
+ if (bodyTooLarge) {
+ res.writeHead(413, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Request body too large' }));
+ return;
+ }
try {
const data = JSON.parse(body || '{}');
const rawVal = data.price !== undefined ? data.price : (data.amount !== undefined ? data.amount : 1.00);
const price = Number(rawVal);
- if (isNaN(price) || price < 1) {
+ if (!Number.isFinite(price) || price < 1 || price > MAX_TOPUP_RUPEES) {
res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Minimum top-up amount is ₹1.00' }));
+ res.end(JSON.stringify({
+ error: price > MAX_TOPUP_RUPEES
+ ? `Maximum top-up amount is ₹${MAX_TOPUP_RUPEES}.00`
+ : 'Minimum top-up amount is ₹1.00'
+ }));
return;
}
const orderId = `COIN-ORD-${Date.now()}`;
const amountStr = price.toFixed(2);
- const proto = req.headers['x-forwarded-proto'] || (req.headers.host?.includes('example.com') ? 'https' : 'http');
- const host = req.headers['x-forwarded-host'] || req.headers.host || 'localhost:5000';
- const returnUrl = `${proto}://${host}/wallet?orderId=${orderId}`;
+
+ // The post-payment return target must be derived from the store's own configured
+ // base URL. Building it from Host / X-Forwarded-* lets an attacker choose where a
+ // paying customer is redirected (phishing after a real payment).
+ const returnUrl = `${this.publicBaseUrl}/wallet?orderId=${encodeURIComponent(orderId)}`;
+
+ // Coin quantity is derived server-side from the amount paid. A client-supplied
+ // `coins` value would let a buyer pay ₹1 and be credited an arbitrary balance.
+ const coins = Math.round(price);
// Call YOUPI Payment Gateway via SDK
const payment = await this.paymentClient.createPayment({
@@ -356,8 +449,8 @@ export class CoinWalletStoreServer {
currency: 'INR',
returnUrl,
metadata: {
- coins: data.coins || Math.round(price),
- packName: data.packName || data.productName || 'Gamer Pack'
+ coins,
+ packName: sanitizePackName(data.packName || data.productName)
}
});
@@ -365,8 +458,8 @@ export class CoinWalletStoreServer {
// Normalize checkoutUrl for localhost development / testing to prevent tunnel offline issues
let resolvedCheckoutUrl = payment.checkoutUrl;
- if (host.includes('localhost') || host.includes('127.0.0.1')) {
- resolvedCheckoutUrl = `${proto}://${host}/checkout/${payment.paymentId}`;
+ if (this.publicBaseUrl.includes('localhost') || this.publicBaseUrl.includes('127.0.0.1')) {
+ resolvedCheckoutUrl = `${this.publicBaseUrl}/checkout/${payment.paymentId}`;
}
res.writeHead(200, {
@@ -380,7 +473,7 @@ export class CoinWalletStoreServer {
}));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: err.message }));
+ res.end(JSON.stringify({ error: 'Unable to create payment' }));
}
});
return;
@@ -389,8 +482,18 @@ export class CoinWalletStoreServer {
// POST /api/verify-payment (Instant confirmation & credit from popup drawer handler)
if (pathname === '/api/verify-payment' && method === 'POST') {
let body = '';
- req.on('data', chunk => { body += chunk; });
+ let bodyTooLarge = false;
+ req.on('data', chunk => {
+ if (bodyTooLarge) return;
+ body += chunk;
+ if (body.length > MAX_JSON_BODY_BYTES) { bodyTooLarge = true; body = ''; }
+ });
req.on('end', async () => {
+ if (bodyTooLarge) {
+ res.writeHead(413, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Request body too large' }));
+ return;
+ }
try {
const data = JSON.parse(body || '{}');
const { orderId: clientOrderId } = data;
@@ -432,8 +535,13 @@ export class CoinWalletStoreServer {
return;
}
- const creditedCoins = Number(session.metadata?.coins) || 100;
- const finalPackName = session.metadata?.packName || 'Coin Pack';
+ // Clamp the credited amount: metadata is written by this server, but a session created
+ // out-of-band could carry an arbitrary coin count.
+ const requestedCoins = Number(session.metadata?.coins);
+ const creditedCoins = (Number.isFinite(requestedCoins) && requestedCoins > 0)
+ ? Math.min(Math.round(requestedCoins), MAX_TOPUP_RUPEES)
+ : 100;
+ const finalPackName = sanitizePackName(session.metadata?.packName || 'Coin Pack');
this.creditCoins(orderId, creditedCoins, finalPackName);
console.log(`[Coin Wallet Store] Verified & credited ${creditedCoins} coins for Order ${orderId}. New balance: ${this.walletCoins}`);
@@ -459,22 +567,52 @@ export class CoinWalletStoreServer {
// POST /api/webhook or /webhook (Signed webhook listener from YOUPI PG)
if ((pathname === '/api/webhook' || pathname === '/webhook') && method === 'POST') {
let rawBody = '';
- req.on('data', chunk => { rawBody += chunk; });
+ let bodyTooLarge = false;
+ req.on('data', chunk => {
+ if (bodyTooLarge) return;
+ rawBody += chunk;
+ if (rawBody.length > MAX_JSON_BODY_BYTES) { bodyTooLarge = true; rawBody = ''; }
+ });
req.on('end', () => {
+ if (bodyTooLarge) {
+ res.writeHead(413, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Payload too large' }));
+ return;
+ }
const signature = req.headers['x-gateway-signature'];
+ const deliveryId = req.headers['x-gateway-delivery-id'] || '';
+ const timestamp = req.headers['x-gateway-timestamp'] || '';
+
+ // Reject a replayed delivery. Without this, one captured request can be resent
+ // indefinitely and re-credited after the in-memory dedupe is lost on restart.
+ const ts = Number(timestamp);
+ if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > WEBHOOK_MAX_SKEW_MS) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Webhook timestamp missing or outside the accepted window.' }));
+ return;
+ }
+ if (deliveryId && this.seenDeliveryIds.has(deliveryId)) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ received: true, duplicate: true }));
+ return;
+ }
try {
- // Verify HMAC-SHA256 signature using merchant SDK
+ // Signature is verified over the RAW body, before any JSON parsing.
const event = this.paymentClient.verifyWebhook(rawBody, signature);
+ if (deliveryId) this.rememberDeliveryId(deliveryId);
const paidMethod = event.method || event.data?.method;
// COD / counter 'SUCCESS' means an order was placed, not that money arrived.
- if ((event.event === 'SUCCESS' || event.status === 'SUCCESS') && (!paidMethod || paidMethod === 'UPI')) {
+ if ((event.event === 'SUCCESS' || event.status === 'SUCCESS') && paidMethod === 'UPI') {
const orderId = event.orderId || event.data?.orderId;
const alreadyCredited = this.transactionHistory.some(t => t.orderId === orderId);
if (!alreadyCredited) {
- const coinsToAdd = Number(event.metadata?.coins || event.data?.metadata?.coins) || 100;
- const packName = event.metadata?.packName || event.data?.metadata?.packName || 'Coin Pack';
+ const requested = Number(event.metadata?.coins || event.data?.metadata?.coins);
+ const coinsToAdd = (Number.isFinite(requested) && requested > 0)
+ ? Math.min(Math.round(requested), MAX_TOPUP_RUPEES)
+ : 100;
+ const packName = sanitizePackName(event.metadata?.packName || event.data?.metadata?.packName);
this.creditCoins(orderId, coinsToAdd, packName);
console.log(`[Coin Wallet Store] Webhook received! Credited ${coinsToAdd} coins for Order ${orderId}. New balance: ${this.walletCoins}`);
}
@@ -484,8 +622,8 @@ export class CoinWalletStoreServer {
res.end(JSON.stringify({ received: true, credited: true }));
} catch (err) {
console.error('[Coin Wallet Store] Webhook verification failed:', err.message);
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: err.message }));
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid webhook signature' }));
}
});
return;
diff --git a/apps/control-center/src/__tests__/control-center.test.js b/apps/control-center/src/__tests__/control-center.test.js
index ef6413f..8d49018 100644
--- a/apps/control-center/src/__tests__/control-center.test.js
+++ b/apps/control-center/src/__tests__/control-center.test.js
@@ -1,9 +1,12 @@
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
+import { getAdminToken } from '@youpi/common';
import { startControlCenter } from '../index.js';
import { ProcessManager } from '../process-manager.js';
+const ADMIN_AUTH = { Authorization: `Bearer ${getAdminToken()}` };
+
describe('Control Center Supervisor Integration Tests', () => {
let ccInstance;
let baseUrl;
@@ -20,9 +23,9 @@ describe('Control Center Supervisor Integration Tests', () => {
await ccInstance.close();
});
- function get(path) {
+ function get(path, headers = {}) {
return new Promise((resolve, reject) => {
- http.get(`${baseUrl}${path}`, res => {
+ http.get(`${baseUrl}${path}`, { headers }, res => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => {
@@ -38,9 +41,9 @@ describe('Control Center Supervisor Integration Tests', () => {
});
}
- function post(path) {
+ function post(path, headers = {}) {
return new Promise((resolve, reject) => {
- const req = http.request(`${baseUrl}${path}`, { method: 'POST' }, res => {
+ const req = http.request(`${baseUrl}${path}`, { method: 'POST', headers }, res => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => {
@@ -74,8 +77,14 @@ describe('Control Center Supervisor Integration Tests', () => {
assert.ok(res.body.includes('Real-Time Aggregate Terminal Logs'));
});
+ test('process control routes require the admin token', async () => {
+ assert.equal((await get('/api/services')).status, 401);
+ assert.equal((await get('/api/logs/stream')).status, 401);
+ assert.equal((await post('/api/services/stop-all')).status, 401);
+ });
+
test('GET /api/services enumerates all modular host services', async () => {
- const res = await get('/api/services');
+ const res = await get('/api/services', ADMIN_AUTH);
assert.equal(res.status, 200);
assert.ok(Array.isArray(res.body));
assert.equal(res.body.length, 6);
@@ -102,7 +111,7 @@ describe('Control Center Supervisor Integration Tests', () => {
});
test('CRITICAL INVARIANT: Stop All strictly stops child processes and NEVER terminates Control Center', async () => {
- const res = await post('/api/services/stop-all');
+ const res = await post('/api/services/stop-all', ADMIN_AUTH);
assert.equal(res.status, 200);
assert.equal(res.body.success, true);
diff --git a/apps/control-center/src/index.js b/apps/control-center/src/index.js
index 38313a0..f727435 100644
--- a/apps/control-center/src/index.js
+++ b/apps/control-center/src/index.js
@@ -9,8 +9,13 @@ export function startControlCenter(port = null, options = {}) {
const server = new ControlCenterServer({ processManager });
const rawServer = server.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[Control Center] Supervisor listening on http://localhost:${finalPort}`);
resolve({
server,
diff --git a/apps/control-center/src/server.js b/apps/control-center/src/server.js
index 226a611..8c0f016 100644
--- a/apps/control-center/src/server.js
+++ b/apps/control-center/src/server.js
@@ -3,10 +3,29 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { ProcessManager } from './process-manager.js';
+import { getAdminToken, safeEqual } from '@youpi/common';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+/** Security headers applied to every response served by the control center. */
+const BASE_SECURITY_HEADERS = Object.freeze({
+ 'X-Content-Type-Options': 'nosniff',
+ 'X-Frame-Options': 'SAMEORIGIN',
+ 'Referrer-Policy': 'no-referrer',
+ 'Content-Security-Policy': "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'"
+});
+
+/** Routes reachable without a credential (liveness probe and the dashboard shell). */
+const PUBLIC_PATHS = new Set(['/health', '/', '/dashboard']);
+
+/** True when the caller presented the admin bearer token in constant time. */
+function hasAdminToken(req) {
+ const match = /^Bearer\s+(.+)$/i.exec(req.headers?.['authorization'] || '');
+ if (!match) return false;
+ return safeEqual(match[1].trim(), getAdminToken());
+}
+
export class ControlCenterServer {
/**
* @param {{ processManager?: ProcessManager }} [options={}]
@@ -49,7 +68,7 @@ export class ControlCenterServer {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type'
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
});
res.end();
return;
@@ -62,6 +81,15 @@ export class ControlCenterServer {
return;
}
+ // Every remaining route controls processes, streams service logs or exposes internal
+ // state. Without a token these are a remote denial-of-service and a log-exfiltration
+ // primitive, so the admin bearer is required.
+ if (!PUBLIC_PATHS.has(pathname) && !hasAdminToken(req)) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
+
// GET /api/services
if (pathname === '/api/services' && method === 'GET') {
res.writeHead(200, {
@@ -139,7 +167,10 @@ export class ControlCenterServer {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
- 'Access-Control-Allow-Origin': '*'
+ // Not wildcard: EventSource cannot send an Authorization header from a browser
+ // dashboard, but the stream still carries every service's stdout/stderr.
+ 'Access-Control-Allow-Origin': 'null',
+ ...BASE_SECURITY_HEADERS
});
// Send existing logs
@@ -164,7 +195,8 @@ export class ControlCenterServer {
if (pathname === '/' || pathname === '/dashboard') {
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-cache'
+ 'Cache-Control': 'no-cache',
+ ...BASE_SECURITY_HEADERS
});
res.end(this.template);
return;
diff --git a/apps/gmail-observer/src/index.js b/apps/gmail-observer/src/index.js
index 1f92b1f..00bc3d8 100644
--- a/apps/gmail-observer/src/index.js
+++ b/apps/gmail-observer/src/index.js
@@ -9,8 +9,13 @@ export function startGmailObserver(port = null, options = {}) {
const observerServer = new GmailObserverServer({ poller, ...options });
const rawServer = observerServer.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[Gmail Observer] Service listening on port ${finalPort}`);
resolve({
poller,
diff --git a/apps/gmail-observer/src/server.js b/apps/gmail-observer/src/server.js
index 9d15644..c55a642 100644
--- a/apps/gmail-observer/src/server.js
+++ b/apps/gmail-observer/src/server.js
@@ -46,7 +46,15 @@ export class GmailObserverServer {
}
// POST /stop
+ // This service is published publicly (Google must reach /oauth/callback), so stopping the
+ // poller must not be reachable by an anonymous caller: it silently disables the bank-email
+ // verification channel and prevents live payments from settling.
if (pathname === '/stop' && method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
this.poller.stop();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, message: 'Gmail poller stopped' }));
@@ -381,6 +389,11 @@ export class GmailObserverServer {
// POST /api/browser/auto-ensure
if (pathname === '/api/browser/auto-ensure' && method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
try {
const result = await this.automator.autoEnsureConnection();
res.writeHead(200, {
@@ -397,6 +410,11 @@ export class GmailObserverServer {
// POST /api/browser/launch-login
if (pathname === '/api/browser/launch-login' && req.method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
try {
const result = this.automator.launchLoginWindow();
res.writeHead(200, {
@@ -413,6 +431,11 @@ export class GmailObserverServer {
// POST /api/sweep (Active sweep trigger during 30-second verification window)
if (pathname === '/api/sweep' && req.method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
try {
await Promise.allSettled([
this.automator.pollInboxEmails().catch(() => {}),
diff --git a/apps/merchant-admin/src/__tests__/merchant-admin.test.js b/apps/merchant-admin/src/__tests__/merchant-admin.test.js
index efcf8c7..e02bd15 100644
--- a/apps/merchant-admin/src/__tests__/merchant-admin.test.js
+++ b/apps/merchant-admin/src/__tests__/merchant-admin.test.js
@@ -2,6 +2,7 @@ import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { Database } from '@youpi/db';
+import { getAdminToken } from '@youpi/common';
import { startAdminServer } from '../index.js';
describe('Merchant Admin Integration Tests', () => {
@@ -20,9 +21,9 @@ describe('Merchant Admin Integration Tests', () => {
testDb.close();
});
- function get(path) {
+ function get(path, headers = {}) {
return new Promise((resolve, reject) => {
- http.get(`${baseUrl}${path}`, res => {
+ http.get(`${baseUrl}${path}`, { headers }, res => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => {
@@ -54,8 +55,11 @@ describe('Merchant Admin Integration Tests', () => {
assert.ok(res.text.includes('Gmail Direct API'));
});
- test('GET /api/admin/tickets returns tickets array', async () => {
- const res = await get('/api/admin/tickets');
+ test('GET /api/admin/tickets requires the admin token', async () => {
+ const anonymous = await get('/api/admin/tickets');
+ assert.equal(anonymous.status, 401);
+
+ const res = await get('/api/admin/tickets', { Authorization: `Bearer ${getAdminToken()}` });
assert.equal(res.status, 200);
const json = JSON.parse(res.text);
assert.ok(Array.isArray(json));
diff --git a/apps/merchant-admin/src/index.js b/apps/merchant-admin/src/index.js
index 9e2e29a..c750aea 100644
--- a/apps/merchant-admin/src/index.js
+++ b/apps/merchant-admin/src/index.js
@@ -12,8 +12,13 @@ export function startAdminServer(port = null, options = {}) {
const adminServer = new AdminServer({ db, ...options });
const rawServer = adminServer.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[Merchant Admin] Server listening on port ${finalPort}`);
resolve({
port: finalPort,
diff --git a/apps/merchant-admin/src/server.js b/apps/merchant-admin/src/server.js
index 39f407d..08f1100 100644
--- a/apps/merchant-admin/src/server.js
+++ b/apps/merchant-admin/src/server.js
@@ -3,10 +3,40 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { getDatabase, MerchantRepository, SupportTicketRepository } from '@youpi/db';
+import { getAdminToken, safeEqual } from '@youpi/common';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+/** Security headers applied to every response served by the merchant admin. */
+const BASE_SECURITY_HEADERS = Object.freeze({
+ 'X-Content-Type-Options': 'nosniff',
+ 'X-Frame-Options': 'SAMEORIGIN',
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
+ 'Content-Security-Policy': "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
+});
+
+/** True when the caller presented the admin bearer token in constant time. */
+function hasAdminToken(req) {
+ const match = /^Bearer\s+(.+)$/i.exec(req.headers?.['authorization'] || '');
+ if (!match) return false;
+ return safeEqual(match[1].trim(), getAdminToken());
+}
+
+/**
+ * Strips headers a browser must not be able to spoof when relaying to an internal service.
+ */
+function sanitizedForwardHeaders(req, targetHost) {
+ const headers = { ...req.headers, host: targetHost };
+ for (const name of Object.keys(headers)) {
+ const lower = name.toLowerCase();
+ if (lower === 'x-internal-render' || lower === 'x-internal-token') {
+ delete headers[name];
+ }
+ }
+ return headers;
+}
+
// In production, reliably ensure environment variables from .env are loaded if not already provided
if (!process.env.BASE_PAYMENT_API_URL && typeof process.loadEnvFile === 'function') {
try {
@@ -70,30 +100,40 @@ export class AdminServer {
// Admin Tickets API: GET /api/admin/tickets
if (pathname === '/api/admin/tickets') {
+ if (!hasAdminToken(req)) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
const merchants = this.merchantRepo.findAll();
const mId = merchants[0]?.id || '00000000-0000-0000-0000-000000000001';
const tickets = this.ticketRepo.findTicketsByMerchant(mId);
res.writeHead(200, {
'Content-Type': 'application/json',
- 'Access-Control-Allow-Origin': '*'
+ 'Access-Control-Allow-Origin': '*',
+ ...BASE_SECURITY_HEADERS
});
res.end(JSON.stringify(tickets));
return;
}
// Merged Control Center Supervisor Proxy: /api/services/* and /api/logs/stream -> Control Center on port 8090
+ // Relaying this unauthenticated would republish process control and every service's
+ // stdout/stderr on the internet-facing admin host, so the admin token is required.
if (pathname.startsWith('/api/services') || pathname === '/api/logs/stream') {
+ if (!hasAdminToken(req)) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
const ccPort = Number(process.env.CONTROL_CENTER_PORT || 8090);
const proxyReq = http.request({
hostname: '127.0.0.1',
port: ccPort,
path: req.url,
method: req.method,
- headers: {
- ...req.headers,
- host: `localhost:${ccPort}`
- }
+ headers: sanitizedForwardHeaders(req, `localhost:${ccPort}`)
}, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
@@ -177,7 +217,8 @@ export class AdminServer {
const html = this.renderHtml();
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-cache'
+ 'Cache-Control': 'no-cache',
+ ...BASE_SECURITY_HEADERS
});
res.end(html);
return;
diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.html
index b63355b..baa4a9c 100644
--- a/apps/merchant-admin/src/views/admin.html
+++ b/apps/merchant-admin/src/views/admin.html
@@ -3979,7 +3979,7 @@
const s = remainingSec % 60;
content.innerHTML = `
<div style="font-size:1.75rem; font-weight:800; color:#38bdf8;">₹${(Number(currentSlot.amountPaise) / 100).toFixed(2)}</div>
- <div style="font-weight:700; margin:0.35rem 0;">Order #${currentSlot.orderId}</div>
+ <div style="font-weight:700; margin:0.35rem 0;">Order #${escapeHtml(currentSlot.orderId)}</div>
<div class="badge badge-info">ACTIVE (⏱ ${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')} remaining)</div>
`;
} else {
@@ -3998,7 +3998,7 @@
const remainingSec = currentSlot.processingExpiresAt ? Math.max(0, Math.ceil((new Date(currentSlot.processingExpiresAt).getTime() - Date.now()) / 1000)) : 0;
content.innerHTML = `
<div style="font-size:1.75rem; font-weight:800; color:#fbbf24;">₹${(Number(currentSlot.amountPaise) / 100).toFixed(2)}</div>
- <div style="font-weight:700; margin:0.35rem 0;">Order #${currentSlot.orderId}</div>
+ <div style="font-weight:700; margin:0.35rem 0;">Order #${escapeHtml(currentSlot.orderId)}</div>
<div class="badge badge-warning">VERIFYING (⏳ ${remainingSec}s remaining)</div>
`;
} else {
@@ -4017,7 +4017,7 @@
tbody.innerHTML = queue.map(q => `
<tr>
<td><strong>#${q.queuePosition}</strong></td>
- <td>Order #${q.orderId}</td>
+ <td>Order #${escapeHtml(q.orderId)}</td>
<td>₹${(Number(q.amountPaise) / 100).toFixed(2)}</td>
<td><span class="badge badge-warning">QUEUED</span></td>
<td>${new Date(q.createdAt).toLocaleTimeString()}</td>
@@ -4096,7 +4096,7 @@
tbody.innerHTML = pending.map(p => `
<tr>
- <td><strong>Order #${p.orderId}</strong></td>
+ <td><strong>Order #${escapeHtml(p.orderId)}</strong></td>
<td><code style="font-size:0.75rem;">${p.id.substring(0, 16)}...</code></td>
<td><strong style="color:#34d399; font-size:1.15rem;">₹${(Number(p.amountPaise) / 100).toFixed(2)}</strong></td>
<td>
@@ -4174,7 +4174,7 @@
}
tbody.innerHTML = orders.map(o => `
<tr>
- <td><strong>Order #${o.orderId}</strong></td>
+ <td><strong>Order #${escapeHtml(o.orderId)}</strong></td>
<td><code style="font-size:0.75rem;">${o.paymentId.substring(0, 16)}...</code></td>
<td><strong style="color:#34d399; font-size:1.15rem;">₹${(Number(o.amountPaise) / 100).toFixed(2)}</strong></td>
<td>${escapeHtml(o.customerName || 'Customer')}</td>
@@ -4215,7 +4215,7 @@
return `
<tr>
- <td><strong>Order #${p.orderId}</strong></td>
+ <td><strong>Order #${escapeHtml(p.orderId)}</strong></td>
<td><code>${p.id}</code></td>
<td>₹${(Number(p.amountPaise) / 100).toFixed(2)}</td>
<td>${p.method}</td>
@@ -4481,12 +4481,12 @@
} else {
actionBtns += `<button class="btn btn-secondary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="toggleVpa('${a.id}')">Deactivate</button>`;
}
- actionBtns += `<button class="btn btn-danger" style="padding:0.35rem 0.65rem; font-size:0.78rem;" onclick="deleteVpa('${a.id}', '${a.upiId}')">Delete</button>`;
+ actionBtns += `<button class="btn btn-danger" style="padding:0.35rem 0.65rem; font-size:0.78rem;" onclick="deleteVpa('${escapeHtml(a.id)}', '${escapeHtml(a.upiId)}')">Delete</button>`;
return `
<tr style="${a.isActive ? 'background:var(--primary-light);' : ''}">
- <td><strong style="color:var(--text-heading);">${a.upiId}</strong></td>
- <td>${a.payeeName}</td>
+ <td><strong style="color:var(--text-heading);">${escapeHtml(a.upiId)}</strong></td>
+ <td>${escapeHtml(a.payeeName)}</td>
<td>${statusBadge}</td>
<td>${slotBadge}</td>
<td style="font-size:0.75rem; color:var(--text-muted);">${new Date(a.createdAt).toLocaleDateString()}</td>
diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.js
index 131d3b4..e2bddac 100644
--- a/apps/payment-api/src/index.js
+++ b/apps/payment-api/src/index.js
@@ -468,7 +468,9 @@ export function startServer(port = null, customDb = null) {
const app = createPaymentApp(customDb);
return new Promise(resolve => {
- const instance = app.rawServer.listen(finalPort, () => {
+ // Loopback by default; reach this service via the local Cloudflare Tunnel, not 0.0.0.0.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+ const instance = app.rawServer.listen(finalPort, bindHost, () => {
console.log(`[Payment API] Server listening on port ${finalPort}`);
resolve({
app,
diff --git a/apps/payment-api/src/routes/admin.routes.js b/apps/payment-api/src/routes/admin.routes.js
index 3058d33..1bded92 100644
--- a/apps/payment-api/src/routes/admin.routes.js
+++ b/apps/payment-api/src/routes/admin.routes.js
@@ -1,6 +1,6 @@
import crypto from 'node:crypto';
import { HttpServer } from '../server.js';
-import { PaymentStatus, PaymentMethod, SellingMode, AuditActorType, isValidVpa, toRupeesString, deriveCloudflareRoutes, resolveRuntimeUrls, resolveGmailRedirectUri, createOAuthState } from '@youpi/common';
+import { PaymentStatus, PaymentMethod, SellingMode, AuditActorType, isValidVpa, toRupeesString, deriveCloudflareRoutes, resolveRuntimeUrls, resolveGmailRedirectUri, createOAuthState, validateOutboundWebhookUrl } from '@youpi/common';
import { PaymentVerificationPipeline } from '@youpi/core';
import { globalTunnelManager } from '../services/tunnel-manager.js';
import { formatQrDataUrl } from '../services/whatsapp-berry.service.js';
@@ -712,6 +712,11 @@ export function registerAdminRoutes(server, ctx) {
updates.businessName = body.businessName.trim();
}
if (body.webhookUrl !== undefined) {
+ const check = validateOutboundWebhookUrl(body.webhookUrl);
+ if (!check.valid && String(body.webhookUrl || '').trim()) {
+ HttpServer.json(res, 400, { error: check.error });
+ return;
+ }
updates.webhookUrl = body.webhookUrl?.trim() || null;
}
if (body.webhookSecret !== undefined && body.webhookSecret.trim()) {
@@ -910,8 +915,14 @@ export function registerAdminRoutes(server, ctx) {
const updates = {};
if (body.businessName && body.businessName.trim()) updates.businessName = body.businessName.trim();
else if (inputBranding.businessName && inputBranding.businessName.trim()) updates.businessName = inputBranding.businessName.trim();
- if (body.webhookUrl !== undefined) updates.webhookUrl = body.webhookUrl?.trim() || null;
- else if (inputBranding.webhookUrl !== undefined) updates.webhookUrl = inputBranding.webhookUrl?.trim() || null;
+ if (body.webhookUrl !== undefined) {
+ const check = validateOutboundWebhookUrl(body.webhookUrl);
+ if (!check.valid && String(body.webhookUrl || '').trim()) {
+ HttpServer.json(res, 400, { error: check.error });
+ return;
+ }
+ updates.webhookUrl = body.webhookUrl?.trim() || null;
+ } else if (inputBranding.webhookUrl !== undefined) updates.webhookUrl = inputBranding.webhookUrl?.trim() || null;
if (body.webhookSecret !== undefined && body.webhookSecret.trim()) updates.webhookSecret = body.webhookSecret.trim();
if (
diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.js
index c417834..f5fc534 100644
--- a/apps/payment-api/src/routes/checkout.routes.js
+++ b/apps/payment-api/src/routes/checkout.routes.js
@@ -1,5 +1,5 @@
import { HttpServer } from '../server.js';
-import { toRupeesString, buildUpiUri, PaymentStatus, PaymentMethod, UPI_PROVIDERS } from '@youpi/common';
+import { toRupeesString, buildUpiUri, PaymentStatus, PaymentMethod, UPI_PROVIDERS, isInternalServiceRequest } from '@youpi/common';
import { validateSessionDeviceAccess } from '@youpi/core';
/**
@@ -14,8 +14,9 @@ function checkSessionDeviceAccess(session, req, body = null, ctx = null) {
return { allowed: true, boundDeviceId: session.deviceId, isTerminal: true };
}
- // Internal server-side HTML render calls bypass device blocking
- if (req.headers['x-internal-render'] === 'true') {
+ // Only a co-located service holding the shared internal token may bypass device blocking.
+ // The `X-Internal-Render` flag on its own is attacker-controlled and proves nothing.
+ if (isInternalServiceRequest(req)) {
return { allowed: true, boundDeviceId: session.deviceId };
}
@@ -955,6 +956,14 @@ export function registerCheckoutRoutes(server, ctx) {
return;
}
+ // Cancelling releases the merchant's scarce UPI slot and ends a live payment, so it is
+ // subject to the same device-binding check as the other state-changing checkout actions.
+ // Without this, anyone holding a payment id could grief an in-flight checkout.
+ const deviceAccess = checkSessionDeviceAccess(session, req, null, ctx);
+ if (!deviceAccess.allowed) {
+ HttpServer.json(res, deviceAccess.statusCode || 409, deviceAccess.body);
+ return;
+ }
const updated = ctx.timingEngine.handleCancel(params.id);
diff --git a/apps/payment-api/src/routes/customer.routes.js b/apps/payment-api/src/routes/customer.routes.js
index 9c54e28..5157a39 100644
--- a/apps/payment-api/src/routes/customer.routes.js
+++ b/apps/payment-api/src/routes/customer.routes.js
@@ -1,6 +1,11 @@
import crypto from 'node:crypto';
import { HttpServer } from '../server.js';
-import { normalizeEmail, normalizeMobile, isValidEmail, isValidMobile, isValidPassword } from '@youpi/common';
+import { normalizeEmail, normalizeMobile, isValidEmail, isValidMobile, isValidPassword, safeEqual } from '@youpi/common';
+
+/** Wrong guesses tolerated per issued OTP challenge. */
+const OTP_MAX_ATTEMPTS = 5;
+/** Minimum gap between OTP requests for the same mobile number. */
+const OTP_RESEND_COOLDOWN_MS = 30 * 1000;
/**
* Registers gateway-owned customer identity and session routes.
@@ -35,6 +40,23 @@ export function registerCustomerRoutes(server, ctx) {
// Pending signup challenges cache: mobileNumber -> { otpCode, expiresAt, name, email }
const pendingOtpChallenges = new Map();
+ // Throttles OTP dispatch per mobile number so the WhatsApp channel cannot be flooded/cost-abused.
+ const otpRequestLog = new Map();
+
+ /**
+ * Records an OTP request and reports whether the caller is within the resend cooldown.
+ * Entries older than the cooldown are pruned on each call.
+ */
+ function isOtpThrottled(mobile) {
+ const now = Date.now();
+ for (const [key, at] of otpRequestLog) {
+ if (now - at > OTP_RESEND_COOLDOWN_MS) otpRequestLog.delete(key);
+ }
+ if (otpRequestLog.has(mobile)) return true;
+ otpRequestLog.set(mobile, now);
+ return false;
+ }
+
// Helper to get Berry Service
function getBerry() {
return ctx.whatsappBerryService || null;
@@ -94,6 +116,13 @@ export function registerCustomerRoutes(server, ctx) {
const existingUser = ctx.customerRepo.findByMobile(cleanMobile);
+ // Throttle before doing any work: otherwise this endpoint can be used to flood a
+ // customer's WhatsApp with OTPs (harassment) or burn merchant messaging credits.
+ if (isOtpThrottled(cleanMobile)) {
+ HttpServer.json(res, 429, { error: `Please wait ${Math.ceil(OTP_RESEND_COOLDOWN_MS / 1000)} seconds before requesting another code.` });
+ return;
+ }
+
// If new user signing up, validate name and email
if (!existingUser && isNewUser) {
if (!name) {
@@ -122,6 +151,7 @@ export function registerCustomerRoutes(server, ctx) {
pendingOtpChallenges.set(cleanMobile, {
otpCode,
expiresAt,
+ attempts: 0,
name: name || `Customer ${cleanMobile.slice(-4)}`,
email: email || `${cleanMobile}@customer.youpi.local`
});
@@ -190,7 +220,14 @@ export function registerCustomerRoutes(server, ctx) {
HttpServer.json(res, 400, { error: 'No active OTP request found. Please request a new OTP.' });
return;
}
- if (pending.otpCode !== otp) {
+ // Budget the guesses: a 6-digit code is brute-forceable within its window otherwise.
+ if ((pending.attempts || 0) >= OTP_MAX_ATTEMPTS) {
+ pendingOtpChallenges.delete(cleanMobile);
+ HttpServer.json(res, 429, { error: 'Too many incorrect attempts. Please request a new OTP.' });
+ return;
+ }
+ if (!safeEqual(pending.otpCode, otp)) {
+ pending.attempts = (pending.attempts || 0) + 1;
HttpServer.json(res, 400, { error: 'Invalid verification code. Please check and try again.' });
return;
}
diff --git a/apps/payment-api/src/routes/pollers.routes.js b/apps/payment-api/src/routes/pollers.routes.js
index 8dcdd54..940496c 100644
--- a/apps/payment-api/src/routes/pollers.routes.js
+++ b/apps/payment-api/src/routes/pollers.routes.js
@@ -4,12 +4,15 @@ 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, resolveSecret, safeEqual } from '@youpi/common';
+import { toRupeesString, toPaise, verifyHmac, resolveRuntimeUrls, resolveSecret, safeEqual, hasBearer, getObserverToken } from '@youpi/common';
import { isAdminRequest } from '../auth-guard.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+/** Upper bound on a single bank notification body accepted by the verification pipeline. */
+const MAX_OBSERVATION_TEXT_CHARS = 64 * 1024;
+
/**
* Registers observation intake routes for SMS Gateway (Android Native Observer)
* and Automated Observers (Gmail Direct API / Web Observers).
@@ -29,6 +32,12 @@ export function registerPollerRoutes(server, ctx) {
// 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) => {
+ // Observer-only. This returns every in-flight session with its exact amount and VPA,
+ // which is precisely the oracle needed to craft a matching synthetic bank observation.
+ if (!isAdminRequest(req) && !hasBearer(req, getObserverToken())) {
+ HttpServer.json(res, 401, { error: 'Unauthorized', code: 'AUTH_REQUIRED' });
+ return;
+ }
const activeSessions = ctx.db.query(`
SELECT id, order_id, receiving_account_id, amount_paise, status, verification_level, expires_at, processing_expires_at, completed_at
FROM payment_sessions
@@ -68,6 +77,13 @@ export function registerPollerRoutes(server, ctx) {
const rawText = body.rawText || body.text || body.message || body.sms || body.body || (typeof body.rawPayload === 'string' ? body.rawPayload : (body.rawPayload?.text || body.rawPayload?.body));
const sender = body.sender || body.from || body.rawPayload?.sender || body.rawPayload?.from;
+ // Bank notifications are small. Reject oversized bodies outright so no single observation
+ // can be used to burn CPU or memory on the verification path.
+ if (typeof rawText === 'string' && rawText.length > MAX_OBSERVATION_TEXT_CHARS) {
+ HttpServer.json(res, 413, { error: `Observation body too large (max ${MAX_OBSERVATION_TEXT_CHARS} characters).` });
+ return;
+ }
+
if (ctx.pipeline && rawText) {
const pipeResult = ctx.pipeline.process({
source: body.source,
diff --git a/apps/payment-api/src/server.js b/apps/payment-api/src/server.js
index ea2acc3..8ead048 100644
--- a/apps/payment-api/src/server.js
+++ b/apps/payment-api/src/server.js
@@ -1,6 +1,13 @@
import http from 'node:http';
import { URL } from 'node:url';
+/** Security headers applied to every response emitted by the gateway. */
+const BASE_SECURITY_HEADERS = Object.freeze({
+ 'X-Content-Type-Options': 'nosniff',
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
+ 'X-Frame-Options': 'SAMEORIGIN'
+});
+
/**
* Lightweight, high-performance HTTP router and server with native SSE and CORS.
*/
@@ -86,7 +93,8 @@ export class HttpServer {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
- 'Access-Control-Allow-Origin': '*'
+ 'Access-Control-Allow-Origin': '*',
+ ...BASE_SECURITY_HEADERS
});
res.write('event: connected\ndata: {"status":"connected"}\n\n');
@@ -126,7 +134,8 @@ export class HttpServer {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Timestamp, X-Signature'
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Timestamp, X-Signature',
+ ...BASE_SECURITY_HEADERS
});
res.end(jsonStr);
}
@@ -173,7 +182,8 @@ export class HttpServer {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Timestamp, X-Signature'
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Timestamp, X-Signature',
+ ...BASE_SECURITY_HEADERS
});
res.end();
return;
@@ -214,8 +224,9 @@ export class HttpServer {
try {
await route.handler(req, res, params);
} catch (err) {
+ // Log the detail server-side; never echo stack/SQL text to an anonymous caller.
console.error(`Route Error [${method} ${pathname}]:`, err);
- HttpServer.json(res, 500, { error: err.message || 'Internal Server Error' });
+ HttpServer.json(res, 500, { error: 'Internal Server Error' });
}
return;
}
diff --git a/apps/payment-help/src/index.js b/apps/payment-help/src/index.js
index 9316074..4e121ba 100644
--- a/apps/payment-help/src/index.js
+++ b/apps/payment-help/src/index.js
@@ -11,8 +11,13 @@ export function startHelpServer(port = null, options = {}) {
const helpServer = new HelpServer({ db, ...options });
const rawServer = helpServer.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[Payment Help Portal] Server listening on port ${finalPort}`);
resolve({
port: finalPort,
diff --git a/apps/sms-observer/src/index.js b/apps/sms-observer/src/index.js
index 85aa99a..dde9b45 100644
--- a/apps/sms-observer/src/index.js
+++ b/apps/sms-observer/src/index.js
@@ -9,8 +9,13 @@ export function startSmsObserver(port = null, options = {}) {
const observerServer = new SmsObserverServer({ service, ...options });
const rawServer = observerServer.createServer();
+ // Bind to loopback unless explicitly overridden. These services hold admin/observer
+ // credentials and are reached through a local Cloudflare Tunnel, so exposing every
+ // network interface is unnecessary.
+ const bindHost = process.env.YOUPI_BIND_HOST || '127.0.0.1';
+
return new Promise(resolve => {
- const instance = rawServer.listen(finalPort, () => {
+ const instance = rawServer.listen(finalPort, bindHost, () => {
console.log(`[SMS Observer] Service listening on port ${finalPort}`);
resolve({
service,
diff --git a/apps/sms-observer/src/server.js b/apps/sms-observer/src/server.js
index f3ec650..be5f178 100644
--- a/apps/sms-observer/src/server.js
+++ b/apps/sms-observer/src/server.js
@@ -61,6 +61,11 @@ export class SmsObserverServer {
// POST /api/browser/auto-ensure
if (pathname === '/api/browser/auto-ensure' && method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
try {
const result = await this.automator.autoEnsureConnection();
res.writeHead(200, {
@@ -77,6 +82,11 @@ export class SmsObserverServer {
// POST /api/browser/launch-pairing
if (pathname === '/api/browser/launch-pairing' && req.method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
try {
const result = this.automator.launchPairingWindow();
res.writeHead(200, {
@@ -93,6 +103,11 @@ export class SmsObserverServer {
// POST /api/sweep (Active sweep trigger during 30-second verification window)
if (pathname === '/api/sweep' && method === 'POST') {
+ if (!hasBearer(req, getObserverToken(), getAdminToken())) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
+ return;
+ }
try {
await this.automator.pollRecentMessages();
res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
diff --git a/packages/common/src/secrets.js b/packages/common/src/secrets.js
index 27313ff..82f89d0 100644
--- a/packages/common/src/secrets.js
+++ b/packages/common/src/secrets.js
@@ -51,17 +51,99 @@ export const getAdminToken = () => resolveSecret('admin_api_token', 'ADMIN_API_T
export const getObserverToken = () => resolveSecret('observer_api_token', 'OBSERVER_API_TOKEN');
export const getCoinStoreWebhookSecret = () => resolveSecret('coin_store_webhook_secret', 'COIN_STORE_WEBHOOK_SECRET');
+/**
+ * Shared credential proving a request originated from a co-located service (server-side render
+ * proxies) rather than a browser. A plain `X-Internal-Render: true` header is attacker-settable,
+ * so the header is only honoured together with this secret.
+ */
+export const getInternalServiceToken = () => resolveSecret('internal_service_token', 'INTERNAL_SERVICE_TOKEN');
+
+/** True only when the caller proves it is a trusted internal service. */
+export function isInternalServiceRequest(req) {
+ const match = /^Bearer\s+(.+)$/i.exec(req?.headers?.['authorization'] || '');
+ const presented = (match ? match[1].trim() : '') || (req?.headers?.['x-internal-token'] || '');
+ return Boolean(presented) && safeEqual(presented, getInternalServiceToken());
+}
+
/** Literal that older builds seeded into databases; must never be trusted. */
export const LEGACY_DEFAULT_WEBHOOK_SECRET = 'merchant_webhook_secret_for_wallet_store';
/** True when the request's `Authorization: Bearer` value matches any of the given tokens. */
export function hasBearer(req, ...tokens) {
- const match = /^Bearer\s+(.+)$/i.exec(req.headers?.['authorization'] || '');
+ const match = /^Bearer\s+(.+)$/i.exec(req?.headers?.['authorization'] || '');
if (!match) return false;
const presented = match[1].trim();
return tokens.some(t => safeEqual(presented, t));
}
+const BLOCKED_HOSTNAMES = new Set(['localhost', 'localhost.localdomain', 'ip6-localhost', 'ip6-loopback']);
+
+/** True for loopback, RFC1918, link-local, CGNAT, multicast and reserved IPv4/IPv6 ranges. */
+function isPrivateAddress(hostname) {
+ const lower = hostname.toLowerCase().replace(/^\[|\]$/g, '');
+ if (lower === '::1' || lower === '::' || lower === '0.0.0.0') return true;
+ if (lower.endsWith('.local') || lower.endsWith('.internal') || lower.endsWith('.localhost')) return true;
+
+ const v4 = lower.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
+ if (!v4) {
+ // Unique-local (fc00::/7) and link-local (fe80::/10) IPv6.
+ return /^f[cd][0-9a-f]{2}:/.test(lower) || /^fe[89ab][0-9a-f]:/.test(lower);
+ }
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
+ if (a === 10 || a === 127 || a === 0) return true;
+ if (a === 172 && b >= 16 && b <= 31) return true;
+ if (a === 192 && b === 168) return true;
+ if (a === 169 && b === 254) return true;
+ if (a === 100 && b >= 64 && b <= 127) return true;
+ if (a >= 224) return true;
+ return false;
+}
+
+/**
+ * Self-hosted merchants legitimately deliver webhooks to a host on their own LAN or loopback,
+ * so those are permitted only when explicitly opted in. Without the opt-in, private, loopback
+ * and link-local targets (including the cloud metadata endpoint) are refused.
+ */
+function privateWebhooksAllowed() {
+ return process.env.YOUPI_ALLOW_PRIVATE_WEBHOOKS === 'true';
+}
+
+/**
+ * Validates an operator-supplied outbound webhook URL.
+ * Rejects non-HTTP(S) schemes, embedded credentials and — unless explicitly opted in —
+ * loopback/private/link-local hosts, so the gateway cannot be pointed at cloud metadata
+ * endpoints or its own internal admin/control-plane services (SSRF).
+ * @param {string} value
+ * @returns {{ valid: boolean, error?: string, url?: URL }}
+ */
+export function validateOutboundWebhookUrl(value) {
+ const raw = typeof value === 'string' ? value.trim() : '';
+ if (!raw) return { valid: false, error: 'Webhook URL is required.' };
+ if (raw.length > 2048) return { valid: false, error: 'Webhook URL is too long.' };
+
+ let url;
+ try {
+ url = new URL(raw);
+ } catch {
+ return { valid: false, error: 'Webhook URL must be a valid absolute URL.' };
+ }
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ return { valid: false, error: 'Webhook URL must use http:// or https://' };
+ }
+ if (url.username || url.password) {
+ return { valid: false, error: 'Webhook URL must not embed credentials.' };
+ }
+ const hostname = (url.hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
+ if (!hostname) return { valid: false, error: 'Webhook URL must include a hostname.' };
+ if (!privateWebhooksAllowed() && (BLOCKED_HOSTNAMES.has(hostname) || isPrivateAddress(hostname))) {
+ return {
+ valid: false,
+ error: 'Webhook URL must not point to a loopback or private network address (set YOUPI_ALLOW_PRIVATE_WEBHOOKS=true for self-hosted LAN targets).'
+ };
+ }
+ return { valid: true, url };
+}
+
const OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
const consumedOAuthStates = new Map();
diff --git a/packages/core/src/__tests__/webhook-engine.test.js b/packages/core/src/__tests__/webhook-engine.test.js
index 81aed64..9839346 100644
--- a/packages/core/src/__tests__/webhook-engine.test.js
+++ b/packages/core/src/__tests__/webhook-engine.test.js
@@ -1,6 +1,7 @@
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
+import '../../../../scripts/test-support.js';
import { Database, runMigrations, MerchantRepository, PaymentSessionRepository } from '@youpi/db';
import { WebhookEngine } from '../webhook-engine.js';
import { verifyHmac } from '@youpi/common';
diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.js
index fce6724..66cf6eb 100644
--- a/packages/core/src/attribution-engine.js
+++ b/packages/core/src/attribution-engine.js
@@ -167,15 +167,19 @@ export class AttributionEngine {
}
}
if (!currentSession) {
- // Fallback: Check if there is an ACTIVE or PROCESSING session matching this exact amount anywhere on the gateway
- const anyActive = this.sessionRepo.db.queryOne(`
+ // Fallback: match the amount, but only inside the receiving account the observer
+ // reported. Matching "any ACTIVE session on the gateway with this amount" could settle a
+ // different merchant's live payment (cross-merchant hijack), so it is intentionally gone.
+ const scopedRow = this.sessionRepo.db.queryOne(`
SELECT * FROM payment_sessions
- WHERE status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?
+ WHERE receiving_account_id = ?
+ AND status IN ('ACTIVE', 'PROCESSING')
+ AND amount_paise = ?
ORDER BY created_at DESC
LIMIT 1
- `, [Number(normalizedObs.amountPaise)]);
- if (anyActive) {
- currentSession = this.sessionRepo.mapRow(anyActive);
+ `, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);
+ if (scopedRow) {
+ currentSession = this.sessionRepo.mapRow(scopedRow);
}
}
diff --git a/packages/core/src/bank-sms-parser.js b/packages/core/src/bank-sms-parser.js
index adb465f..ffed032 100644
--- a/packages/core/src/bank-sms-parser.js
+++ b/packages/core/src/bank-sms-parser.js
@@ -77,7 +77,11 @@ export class BankSmsParser {
* } | null}
*/
static parse(sms) {
- const text = (sms.text || '').trim();
+ // Bank credit SMS are short. Capping the text bounds the cost of the reference-extraction
+ // regexes, which are scanned from every start offset and would otherwise let one
+ // oversized message block the event loop (ReDoS / DoS).
+ const MAX_SCAN_CHARS = 4096;
+ const text = (sms.text || '').trim().slice(0, MAX_SCAN_CHARS);
if (!text) return null;
// Check if SMS represents an incoming credit
@@ -101,7 +105,7 @@ export class BankSmsParser {
let bankRef;
const utrPatterns = [
/(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([a-zA-Z0-9]{6,25})/i,
- /(?:ref(?:\s*no)?\s*[:#\s]?\s*)([a-zA-Z0-9]{8,22})/i,
+ /(?:ref\s*no\.?)?[\s:#=-]+([a-zA-Z0-9]{8,22})/i,
/\b([0-9]{12})\b/
];
diff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.js
index e8217c1..e2993f1 100644
--- a/packages/core/src/verification-pipeline.js
+++ b/packages/core/src/verification-pipeline.js
@@ -120,7 +120,11 @@ export class PaymentVerificationPipeline {
process(input) {
const isTest = Boolean(input.isTest);
const testModeActive = Boolean(input.testModeActive);
- const rawText = (input.rawText || '').toString();
+ // Bank credit notifications are a few hundred bytes. Capping the text bounds the cost of
+ // the reference-extraction regexes below, which are scanned from every start offset and
+ // would otherwise let one oversized "observation" block the event loop (ReDoS / DoS).
+ const MAX_SCAN_CHARS = 16384;
+ const rawText = (input.rawText || '').toString().slice(0, MAX_SCAN_CHARS);
// =========================================================================
// [ STAGE 1 ]: Load + Normalize + Preserve Raw Evidence
@@ -220,6 +224,11 @@ export class PaymentVerificationPipeline {
// 0. Resolve Payment Session and Customer Context early for security attribution
let session = null;
+
+ // The VPA the credit actually landed on. Every fallback below is scoped by it so an
+ // observation can never be attributed to another merchant's in-flight session.
+ const observedVpa = ((rawText.match(/[a-zA-Z0-9._-]{2,64}@[a-zA-Z0-9._-]{2,32}/) || [])[0] || '').toLowerCase() || null;
+
if (input.paymentSessionId) {
session = this.sessionRepo.findById(input.paymentSessionId);
} else if (input.receivingAccountId) {
@@ -235,23 +244,21 @@ export class PaymentVerificationPipeline {
);
if (row) session = this.sessionRepo.mapRow(row);
}
- // 2. If not found (e.g. observer sent dummy ID or account changed), find active session on merchant's active receiving account
- if (!session) {
+ // 2. Otherwise resolve through the VPA named in the message. Scoping by VPA keeps the
+ // lookup inside a single merchant; the previous gateway-wide "any active receiving
+ // account" query could settle an unrelated merchant's live session.
+ if (!session && observedVpa) {
const row = this.db.queryOne(`
SELECT ps.* FROM payment_sessions ps
JOIN payment_receiving_accounts ra ON ps.receiving_account_id = ra.id
- WHERE ra.is_active = 1 AND ps.status IN ('ACTIVE', 'PROCESSING')
+ WHERE LOWER(ra.upi_id) = ? AND ps.status IN ('ACTIVE', 'PROCESSING')
ORDER BY ps.created_at DESC LIMIT 1
- `);
- if (row) session = this.sessionRepo.mapRow(row);
- }
- // 3. Fallback to any latest active or processing session
- if (!session) {
- const row = this.db.queryOne(
- `SELECT * FROM payment_sessions WHERE status IN ('ACTIVE', 'PROCESSING') ORDER BY created_at DESC LIMIT 1`
- );
+ `, [observedVpa]);
if (row) session = this.sessionRepo.mapRow(row);
}
+ // 3. There is deliberately NO gateway-wide fallback. An observation that cannot be tied
+ // to a specific receiving account must not be attributed to whichever session happens
+ // to be in flight on another merchant's VPA.
}
let customer = null;
@@ -467,7 +474,7 @@ export class PaymentVerificationPipeline {
let bankRef = null;
const ref12Patterns = [
/(?:upi\s*ref(?:erence)?\s*(?:no\.?|num)?|utr(?:\s*no\.?)?|rrn(?:\s*no\.?)?|txn\s*(?:id|ref)?|ref\s*no\.?)[\s:=-]+([0-9]{12})\b/i,
- /(?:ref(?:\s*no)?\s*[:#\s]?\s*)([0-9]{12})\b/i,
+ /(?:ref\s*no\.?)?[\s:#=-]+([0-9]{12})\b/i,
/\b([0-9]{12})\b/
];
for (const pat of ref12Patterns) {
@@ -551,13 +558,22 @@ export class PaymentVerificationPipeline {
let stage4;
if (!session && parsedData?.amountPaise) {
- const matchRow = this.db.queryOne(`
- SELECT * FROM payment_sessions
- WHERE status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?
- ORDER BY created_at DESC LIMIT 1
- `, [Number(parsedData.amountPaise)]);
- if (matchRow) {
- session = this.sessionRepo.mapRow(matchRow);
+ // Amount alone is not an identifier: two merchants can legitimately have an identical
+ // in-flight amount. Only fall back on amount when the VPA the credit landed on is known,
+ // and then only within that VPA's merchant.
+ const scopeByVpa = observedVpa || (parsedData.vpa ? String(parsedData.vpa).toLowerCase() : null);
+ if (scopeByVpa) {
+ const matchRow = this.db.queryOne(`
+ SELECT ps.* FROM payment_sessions ps
+ JOIN payment_receiving_accounts ra ON ps.receiving_account_id = ra.id
+ WHERE ps.status IN ('ACTIVE', 'PROCESSING')
+ AND ps.amount_paise = ?
+ AND LOWER(ra.upi_id) = ?
+ ORDER BY ps.created_at DESC LIMIT 1
+ `, [Number(parsedData.amountPaise), scopeByVpa]);
+ if (matchRow) {
+ session = this.sessionRepo.mapRow(matchRow);
+ }
}
}
diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.js
index 7b4b49a..f59384b 100644
--- a/packages/core/src/webhook-engine.js
+++ b/packages/core/src/webhook-engine.js
@@ -1,5 +1,5 @@
import crypto from 'node:crypto';
-import { generateHmac, toRupeesString } from '@youpi/common';
+import { generateHmac, toRupeesString, validateOutboundWebhookUrl } from '@youpi/common';
import { isTerminalStatus, toPublicOutcome } from './state-machine.js';
export class WebhookEngine {
@@ -28,6 +28,13 @@ export class WebhookEngine {
return { delivered: false, deliveryId: '', error: 'No webhook URL configured for merchant.' };
}
+ // Re-validate at dispatch time, not only on write: a URL persisted before validation
+ // existed must not be usable to reach loopback/private addresses (SSRF).
+ const endpointCheck = validateOutboundWebhookUrl(merchant.webhookUrl);
+ if (!endpointCheck.valid) {
+ return { delivered: false, deliveryId: '', error: `Webhook delivery blocked: ${endpointCheck.error}` };
+ }
+
const publicOutcome = isTerminalStatus(event) ? toPublicOutcome(event) : event;
const payloadObj = {
@@ -60,10 +67,12 @@ export class WebhookEngine {
let isSuccessful = false;
try {
- const res = await fetch(merchant.webhookUrl, {
+ const res = await fetch(endpointCheck.url.toString(), {
method: 'POST',
headers,
body: payloadString,
+ // Never follow redirects: a public URL could otherwise 302 into the internal network.
+ redirect: 'manual',
signal: AbortSignal.timeout(10000) // 10s timeout
});
@@ -126,6 +135,10 @@ export class WebhookEngine {
const merchant = this.merchantRepo.findById(item.merchant_id);
if (!merchant || !item.endpoint_url) continue;
+ // Re-validate the stored endpoint before every retry (SSRF guard).
+ const retryEndpoint = validateOutboundWebhookUrl(item.endpoint_url);
+ if (!retryEndpoint.valid) continue;
+
const signature = generateHmac(item.payload, merchant.webhookSecret);
const timestamp = Date.now().toString();
@@ -134,7 +147,7 @@ export class WebhookEngine {
let respBody = null;
try {
- const res = await fetch(item.endpoint_url, {
+ const res = await fetch(retryEndpoint.url.toString(), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -144,6 +157,7 @@ export class WebhookEngine {
'X-Gateway-Timestamp': timestamp
},
body: item.payload,
+ redirect: 'manual',
signal: AbortSignal.timeout(10000)
});
respStatus = res.status;
diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.js
index c024515..dc41bad 100644
--- a/packages/db/src/migrate.js
+++ b/packages/db/src/migrate.js
@@ -52,6 +52,7 @@ export function runMigrations(targetDb) {
try { db.exec("ALTER TABLE customers ADD COLUMN mobile_number TEXT;"); } catch {}
try { db.exec("ALTER TABLE customers ADD COLUMN otp_code TEXT;"); } catch {}
try { db.exec("ALTER TABLE customers ADD COLUMN otp_expires_at TEXT;"); } catch {}
+ try { db.exec("ALTER TABLE customers ADD COLUMN otp_attempts INTEGER NOT NULL DEFAULT 0;"); } catch {}
try { db.exec("ALTER TABLE customers ADD COLUMN is_phone_verified INTEGER DEFAULT 0;"); } catch {}
try { db.exec("ALTER TABLE customers ADD COLUMN ban_reason TEXT;"); } catch {}
try { db.exec("ALTER TABLE customers ADD COLUMN banned_at TEXT;"); } catch {}
diff --git a/packages/db/src/repositories/customer.repository.js b/packages/db/src/repositories/customer.repository.js
index 206f5b1..03439e3 100644
--- a/packages/db/src/repositories/customer.repository.js
+++ b/packages/db/src/repositories/customer.repository.js
@@ -1,5 +1,8 @@
import crypto from 'node:crypto';
-import { hashPassword, verifyPassword, normalizeEmail, normalizeMobile, isValidEmail, isValidMobile, isValidPassword } from '@youpi/common';
+import { hashPassword, verifyPassword, normalizeEmail, normalizeMobile, isValidEmail, isValidMobile, isValidPassword, safeEqual } from '@youpi/common';
+
+/** Wrong guesses tolerated per issued OTP before the challenge is burned. */
+const OTP_MAX_ATTEMPTS = 5;
export class CustomerRepository {
/**
@@ -194,7 +197,7 @@ export class CustomerRepository {
if (!normalized) return null;
const now = new Date().toISOString();
this.db.execute(
- 'UPDATE customers SET otp_code = ?, otp_expires_at = ?, updated_at = ? WHERE mobile_number = ?',
+ 'UPDATE customers SET otp_code = ?, otp_expires_at = ?, otp_attempts = 0, updated_at = ? WHERE mobile_number = ?',
[otpCode, expiresAt, now, normalized]
);
return this.findByMobile(normalized);
@@ -202,6 +205,7 @@ export class CustomerRepository {
/**
* Verifies WhatsApp OTP for customer login/signup.
+ * Enforces a bounded attempt count per challenge and compares the code in constant time.
* Clears the OTP and marks phone as verified on success.
* @param {string} mobileNumber
* @param {string} otpCode
@@ -212,7 +216,20 @@ export class CustomerRepository {
if (!normalized || !otpCode) return null;
const customer = this.findByMobile(normalized);
if (!customer) return null;
- if (!customer.otpCode || customer.otpCode !== String(otpCode).trim()) {
+
+ // A 6-digit code has a 10^6 keyspace and a 5 minute lifetime, so without an attempt
+ // budget it is brute-forceable online. Fail closed once the budget is spent.
+ const attempts = Number(customer.otpAttempts || 0);
+ if (attempts >= OTP_MAX_ATTEMPTS) return null;
+
+ const submitted = String(otpCode).trim();
+ // `!==` short-circuits on the first differing character; use a constant-time compare.
+ const matches = safeEqual(customer.otpCode || '', submitted);
+ if (!customer.otpCode || !matches) {
+ this.db.execute(
+ 'UPDATE customers SET otp_attempts = ?, updated_at = ? WHERE id = ?',
+ [attempts + 1, new Date().toISOString(), customer.id]
+ );
return null;
}
if (customer.otpExpiresAt && new Date() > customer.otpExpiresAt) {
@@ -221,7 +238,7 @@ export class CustomerRepository {
const now = new Date().toISOString();
this.db.execute(
- 'UPDATE customers SET otp_code = NULL, otp_expires_at = NULL, is_phone_verified = 1, last_login_at = ?, updated_at = ? WHERE id = ?',
+ 'UPDATE customers SET otp_code = NULL, otp_expires_at = NULL, otp_attempts = 0, is_phone_verified = 1, last_login_at = ?, updated_at = ? WHERE id = ?',
[now, now, customer.id]
);
return this.findById(customer.id);
@@ -593,6 +610,7 @@ export class CustomerRepository {
passwordHash: row.password_hash,
otpCode: row.otp_code || null,
otpExpiresAt: row.otp_expires_at ? new Date(row.otp_expires_at) : null,
+ otpAttempts: Number(row.otp_attempts || 0),
isPhoneVerified: Boolean(row.is_phone_verified),
status: row.status,
banReason: row.ban_reason || null,
diff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.js
index d362d3a..844789f 100644
--- a/packages/db/src/repositories/payment-session.repository.js
+++ b/packages/db/src/repositories/payment-session.repository.js
@@ -459,6 +459,27 @@ export class PaymentSessionRepository {
const session = this.findById(sessionId);
if (!session) throw new Error(`Payment session not found: ${sessionId}`);
+ // A dead outcome is final. recordVerificationSource is called from the attribution engine
+ // on previously attributed sessions with no status check, so without this guard an
+ // out-of-window or duplicated observation flips an EXPIRED/FAILED/CANCELLED session back
+ // to SUCCESS and emits a webhook for a payment that was never settled.
+ // An already-SUCCESS session is NOT blocked: recording a second channel there is the
+ // legitimate SMS+Gmail verification upgrade, which must not re-emit SUCCESS.
+ const DEAD_STATES = [
+ PaymentStatus.FAILED,
+ PaymentStatus.EXPIRED,
+ PaymentStatus.CANCELLED
+ ];
+ if (DEAD_STATES.includes(session.status)) {
+ return {
+ session,
+ level: session.verificationLevel || 0,
+ sources: session.verificationSources || [],
+ tag: session.verificationTag || 'UNVERIFIED',
+ isFirstSuccess: false
+ };
+ }
+
// Read current verification sources
const sourcesSet = new Set(session.verificationSources || []);
sourcesSet.add(source);
diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sql
index 12cdeee..f543554 100644
--- a/packages/db/src/sqlite-schema.sql
+++ b/packages/db/src/sqlite-schema.sql
@@ -40,6 +40,7 @@ CREATE TABLE IF NOT EXISTS customers (
password_hash TEXT,
otp_code TEXT,
otp_expires_at TEXT,
+ otp_attempts INTEGER NOT NULL DEFAULT 0,
is_phone_verified INTEGER DEFAULT 0,
status TEXT NOT NULL DEFAULT 'ACTIVE',
last_login_at TEXT,
diff --git a/scripts/test-support.js b/scripts/test-support.js
index 3ffba93..db049ac 100644
--- a/scripts/test-support.js
+++ b/scripts/test-support.js
@@ -9,6 +9,8 @@ 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';
+// Webhook suites deliver to a local mock receiver on loopback, which the SSRF guard blocks by default.
+process.env.YOUPI_ALLOW_PRIVATE_WEBHOOKS = 'true';
/** Admin bearer header, optionally merged with extra headers. */
export function authHeaders(extra = {}) {
@@ -20,7 +22,7 @@ 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/;
+const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/api\/v1\/pollers\/active-window|\/simulate-observation/;
/** Admin bearer header only for routes the gateway guards; other routes (customer auth etc.) get none. */
export function authHeadersFor(path, extra = {}) {