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 merchant API key on payment creation, verify order amounts, and harden webhooks & hooks (#63, #69)
Harsh8d96fc3ef6e0
diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.htmlindex c19125d..0e40a14 100644--- a/apps/checkout-portal/src/views/checkout.html+++ b/apps/checkout-portal/src/views/checkout.html@@ -330,10 +330,14 @@});} catch { }+ const sessionToken = typeof getStoredSessionToken === 'function' ? getStoredSessionToken() : null;+ const headers = typeof getApiHeaders === 'function'+ ? getApiHeaders({ 'Content-Type': 'application/json', ...(sessionToken ? { 'x-customer-token': sessionToken } : {}) })+ : { 'Content-Type': 'application/json', ...(sessionToken ? { 'x-customer-token': sessionToken } : {}) };fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/trigger-hook`, {method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ action, details })+ headers,+ body: JSON.stringify({ action, details, ...(sessionToken ? { token: sessionToken } : {}) })}).catch(() => { });}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.jsindex 29e0539..f9317c2 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@@ -116,6 +116,16 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {test('POST /api/webhook processes signed SUCCESS event and credits wallet coins', async () => {const initialCoins = storeInstance.server.walletCoins;+ storeInstance.server.orders.set('COIN-ORD-555', {+ orderId: 'COIN-ORD-555',+ paymentId: 'pay_coin_test_123',+ amountPaise: 44900,+ coins: 550,+ packName: 'Gamer Pack',+ createdAt: Date.now()+ });+ storeInstance.server.orderPayments.set('COIN-ORD-555', 'pay_coin_test_123');+const payloadObj = {event: 'SUCCESS',paymentId: 'pay_coin_test_123',@@ -151,6 +161,74 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {assert.equal(balanceRes.body.history[0].orderId, 'COIN-ORD-555');});+ test('POST /api/webhook rejects unknown orders and mismatched amounts, and ignores inflated metadata.coins', async () => {+ const before = storeInstance.server.walletCoins;++ // 1. Unknown orderId rejected with 404+ const unknownPayload = JSON.stringify({+ event: 'SUCCESS',+ paymentId: 'pay_unknown_999',+ orderId: 'COIN-ORD-UNKNOWN-999',+ amount: '1.00',+ amountPaise: 100,+ currency: 'INR',+ method: 'UPI',+ metadata: { coins: 99999 }+ });+ const unknownRes = await request('/api/webhook', {+ method: 'POST',+ headers: gatewayHeaders(unknownPayload),+ body: unknownPayload+ });+ assert.equal(unknownRes.status, 404);+ assert.equal(storeInstance.server.walletCoins, before);++ // 2. Mismatched amountPaise rejected with 400+ const checkout = await request('/api/checkout', {+ method: 'POST',+ body: { packName: 'Ten Rupee Pack', price: 10.00 }+ });+ assert.equal(checkout.status, 200);+ const { orderId, paymentId } = checkout.body;++ const mismatchPayload = JSON.stringify({+ event: 'SUCCESS',+ paymentId,+ orderId,+ amount: '1.00',+ amountPaise: 100,+ currency: 'INR',+ method: 'UPI',+ metadata: { coins: 99999 }+ });+ const mismatchRes = await request('/api/webhook', {+ method: 'POST',+ headers: gatewayHeaders(mismatchPayload),+ body: mismatchPayload+ });+ assert.equal(mismatchRes.status, 400);+ assert.equal(storeInstance.server.walletCoins, before);++ // 3. Matching amountPaise credits local order.coins (10), ignoring inflated metadata.coins (99999)+ const validPayload = JSON.stringify({+ event: 'SUCCESS',+ paymentId,+ orderId,+ amount: '10.00',+ amountPaise: 1000,+ currency: 'INR',+ method: 'UPI',+ metadata: { coins: 99999 }+ });+ const validRes = await request('/api/webhook', {+ method: 'POST',+ headers: gatewayHeaders(validPayload),+ body: validPayload+ });+ assert.equal(validRes.status, 200);+ assert.equal(storeInstance.server.walletCoins, before + 10);+ });+test('POST /api/webhook rejects fraudulent signature', async () => {const payloadString = JSON.stringify({ event: 'SUCCESS', orderId: 'FAKE' });const hookRes = await request('/api/webhook', {diff --git a/apps/coin-wallet-store/src/server.js b/apps/coin-wallet-store/src/server.jsindex 4d84030..8692e5b 100644--- a/apps/coin-wallet-store/src/server.js+++ b/apps/coin-wallet-store/src/server.js@@ -104,6 +104,8 @@ export class CoinWalletStoreServer {// orderId -> gateway paymentId for orders this store created (used to verify payments server-side)this.orderPayments = new Map();+ // orderId -> { orderId, paymentId, amountPaise, coins, packName, createdAt }+ this.orders = new Map();// Recently processed X-Gateway-Delivery-Id values, used to reject replayed webhooks.this.seenDeliveryIds = new Map();@@ -466,6 +468,8 @@ export class CoinWalletStoreServer {// 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);+ const amountPaise = Math.round(price * 100);+ const packName = sanitizePackName(data.packName || data.productName);// Call YOUPI Payment Gateway via SDKconst payment = await this.paymentClient.createPayment({@@ -475,11 +479,19 @@ export class CoinWalletStoreServer {returnUrl,metadata: {coins,- packName: sanitizePackName(data.packName || data.productName)+ packName}});this.orderPayments.set(orderId, payment.paymentId);+ this.orders.set(orderId, {+ orderId,+ paymentId: payment.paymentId,+ amountPaise,+ coins,+ packName,+ createdAt: Date.now()+ });// Normalize checkoutUrl for localhost development / testing to prevent tunnel offline issueslet resolvedCheckoutUrl = payment.checkoutUrl;@@ -528,14 +540,15 @@ export class CoinWalletStoreServer {};// The payment id comes from the order this server created, never from the browser.- const paymentId = clientOrderId ? this.orderPayments.get(clientOrderId) : undefined;+ const localOrder = clientOrderId ? this.orders.get(clientOrderId) : undefined;+ const paymentId = localOrder?.paymentId || (clientOrderId ? this.orderPayments.get(clientOrderId) : undefined);if (!paymentId) {sendJson(404, { error: 'Unknown order' });return;}// Never trust the browser: ask the gateway whether this payment really succeeded,- // and take the order id and coin amount from the gateway session, not from the request.+ // and take the order id and coin amount from the local order record, not from the request.let session;try {session = await this.paymentClient.getPayment(paymentId);@@ -553,6 +566,10 @@ export class CoinWalletStoreServer {sendJson(400, { error: 'orderId does not match payment' });return;}+ if (localOrder && Number(session.amountPaise) !== Number(localOrder.amountPaise)) {+ sendJson(400, { error: 'Payment amount does not match order' });+ return;+ }const orderId = session.orderId;if (this.transactionHistory.some(t => t.orderId === orderId)) {@@ -560,13 +577,14 @@ export class CoinWalletStoreServer {return;}- // 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');+ // Always derive credited coins from the authoritative local order record (or paid amountPaise),+ // never from untrusted client parameters or out-of-band metadata.+ const paidPaise = Number(localOrder?.amountPaise ?? session.amountPaise);+ const derivedFromAmount = Number.isFinite(paidPaise) && paidPaise > 0+ ? Math.min(Math.max(1, Math.round(paidPaise / 100)), MAX_TOPUP_RUPEES)+ : 1;+ const creditedCoins = localOrder ? localOrder.coins : derivedFromAmount;+ const finalPackName = sanitizePackName(localOrder?.packName || 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}`);@@ -624,25 +642,40 @@ export class CoinWalletStoreServer {try {// Signature is verified over the RAW body, before any JSON parsing.- const event = this.paymentClient.verifyWebhook(rawBody, signature);- if (deliveryId) this.rememberDeliveryId(deliveryId);+ const event = this.paymentClient.verifyWebhook(rawBody, signature, timestamp, {+ toleranceMs: WEBHOOK_MAX_SKEW_MS,+ allowUnsignedTimestampHeader: true+ });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 === 'UPI') {const orderId = event.orderId || event.data?.orderId;+ const localOrder = orderId ? this.orders.get(orderId) : undefined;+ if (!localOrder && (!orderId || !this.orderPayments.has(orderId))) {+ res.writeHead(404, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Unknown order' }));+ return;+ }+ const eventAmountPaise = Number(event.amountPaise ?? event.data?.amountPaise);+ if (localOrder && (!Number.isFinite(eventAmountPaise) || eventAmountPaise !== Number(localOrder.amountPaise))) {+ res.writeHead(400, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({ error: 'Webhook amount does not match order' }));+ return;+ }+const alreadyCredited = this.transactionHistory.some(t => t.orderId === orderId);if (!alreadyCredited) {- 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);+ const coinsToAdd = localOrder+ ? localOrder.coins+ : Math.min(Math.max(1, Math.round(eventAmountPaise / 100)), MAX_TOPUP_RUPEES);+ const packName = sanitizePackName(localOrder?.packName || 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}`);}}+ if (deliveryId) this.rememberDeliveryId(deliveryId);res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ received: true, credited: true }));} catch (err) {diff --git a/apps/payment-api/src/__tests__/auth-guard.test.js b/apps/payment-api/src/__tests__/auth-guard.test.jsindex 6f5a889..f061428 100644--- a/apps/payment-api/src/__tests__/auth-guard.test.js+++ b/apps/payment-api/src/__tests__/auth-guard.test.js@@ -95,6 +95,7 @@ describe('Auth guard: admin, observer and force-success endpoints', () => {test('counter-confirm cannot settle a UPI session, even with the admin token', async () => {const created = await call('/api/v1/payments', {method: 'POST',+ token: TEST_ADMIN_TOKEN,body: { orderId: 'UPI-NO-FORCE-1', amount: '100.00', method: PaymentMethod.UPI, autoActivate: true }});assert.equal(created.status, 201);@@ -114,6 +115,7 @@ describe('Auth guard: admin, observer and force-success endpoints', () => {test('a counter session can be confirmed once, and not again', async () => {const created = await call('/api/v1/payments', {method: 'POST',+ token: TEST_ADMIN_TOKEN,body: { orderId: 'CASH-OK-1', amount: '50.00', method: PaymentMethod.CASH_COUNTER }});const { paymentId } = await created.json();diff --git a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.jsindex f40b3fa..2ea6a5d 100644--- a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js@@ -654,5 +654,88 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2assert.equal(authRes.body.customer.name, 'Vikram Malhotra');assert.equal(authRes.body.customer.email, '[email protected]');});++ test('Issue #63 & #69: POST /api/v1/payments rejects requests without merchant key, accepts hashed API key, and restricts autoActivate', async () => {+ const merchantRepo = new MerchantRepository(testDb);+ const merchantId = '00000000-0000-0000-0000-000000000001';+ const dedicatedApiKey = 'mk_live_dedicated_merchant_api_key_6369';+ merchantRepo.update(merchantId, { apiKey: dedicatedApiKey });++ // 1. Completely unauthenticated request (no Authorization, no X-Merchant-Key) -> 401 MISSING_MERCHANT_KEY+ const url = new URL('/api/v1/payments', baseUrl);+ const unauthRes = await new Promise((resolve, reject) => {+ const req = http.request(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'x-merchant-id': merchantId }+ }, (res) => {+ let data = '';+ res.on('data', c => { data += c; });+ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));+ });+ req.on('error', reject);+ req.write(JSON.stringify({ orderId: `UNAUTH-${Date.now()}`, amount: '100.00' }));+ req.end();+ });+ assert.equal(unauthRes.status, 401);+ assert.equal(unauthRes.body.code, 'MISSING_MERCHANT_KEY');++ // 2. Request with valid dedicated API key (verified against api_key_hash) -> 201+ const orderId = `KEY-OK-${Date.now()}`;+ const keyRes = await new Promise((resolve, reject) => {+ const req = http.request(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'x-merchant-id': merchantId,+ 'x-merchant-key': dedicatedApiKey+ }+ }, (res) => {+ let data = '';+ res.on('data', c => { data += c; });+ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));+ });+ req.on('error', reject);+ req.write(JSON.stringify({ orderId, amount: '250.00', currency: 'INR' }));+ req.end();+ });+ assert.equal(keyRes.status, 201);+ assert.equal(keyRes.body.orderId, orderId);++ // 3. Reusing the same orderId with a different amount -> 409 ORDER_AMOUNT_MISMATCH+ const mismatchRes = await request('/api/v1/payments', {+ method: 'POST',+ headers: { 'x-merchant-id': merchantId, 'x-merchant-key': dedicatedApiKey },+ body: { orderId, amount: '1.00', currency: 'INR' }+ });+ assert.equal(mismatchRes.status, 409);+ assert.equal(mismatchRes.body.code, 'ORDER_AMOUNT_MISMATCH');++ // 4. In production mode, non-admin caller with autoActivate: true -> 403 AUTOACTIVATE_FORBIDDEN+ const prevEnv = process.env.NODE_ENV;+ process.env.NODE_ENV = 'production';+ try {+ const prodAutoRes = await new Promise((resolve, reject) => {+ const req = http.request(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'x-merchant-id': merchantId,+ 'x-merchant-key': dedicatedApiKey+ }+ }, (res) => {+ let data = '';+ res.on('data', c => { data += c; });+ res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));+ });+ req.on('error', reject);+ req.write(JSON.stringify({ orderId: `PROD-AUTO-${Date.now()}`, amount: '100.00', autoActivate: true }));+ req.end();+ });+ assert.equal(prodAutoRes.status, 403);+ assert.equal(prodAutoRes.body.code, 'AUTOACTIVATE_FORBIDDEN');+ } finally {+ process.env.NODE_ENV = prevEnv;+ }+ });});diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex e1f0573..918652f 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -391,9 +391,20 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {});assert.equal(ownerState.body.customer.phoneNumber, '9111222333');- // 5. Test action trigger hook+ // 5. Test action trigger hook (rejects unauthenticated requests, succeeds with customer token)+ const unauthHookRes = await request(`/api/v1/checkout/${paymentId}/trigger-hook`, {+ method: 'POST',+ body: {+ action: 'CANCEL_CLICKED',+ details: { reason: 'changed_mind' }+ }+ });+ assert.equal(unauthHookRes.status, 401);+ assert.equal(unauthHookRes.body.code, 'CUSTOMER_SESSION_REQUIRED');+const hookRes = await request(`/api/v1/checkout/${paymentId}/trigger-hook`, {method: 'POST',+ headers: { 'x-customer-token': regRes.body.token },body: {action: 'CANCEL_CLICKED',details: { reason: 'changed_mind' }diff --git a/apps/payment-api/src/auth-guard.js b/apps/payment-api/src/auth-guard.jsindex b5dbd62..95471b5 100644--- a/apps/payment-api/src/auth-guard.js+++ b/apps/payment-api/src/auth-guard.js@@ -90,6 +90,10 @@ export function isPaymentOwner(req, session, ctx) {if (!presented || typeof presented !== 'string' || !presented.trim()) return false;const merchant = ctx.merchantRepo?.findById ? ctx.merchantRepo.findById(session.merchantId) : null;- if (!merchant?.webhookSecret) return false;+ if (!merchant) return false;+ if (typeof ctx.merchantRepo?.verifyApiKey === 'function') {+ return ctx.merchantRepo.verifyApiKey(merchant, presented.trim());+ }+ if (!merchant.webhookSecret) return false;return safeEqual(presented.trim(), merchant.webhookSecret);}diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex edce3f5..2da4a57 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -1,7 +1,7 @@import { HttpServer } from '../server.js';import { toRupeesString, buildUpiUri, PaymentStatus, PaymentMethod, UPI_PROVIDERS, isInternalServiceRequest, isValidTransition } from '@youpi/common';import { validateSessionDeviceAccess, verifyRegisteredDeviceCredentials } from '@youpi/core';-import { isPaymentOwner } from '../auth-guard.js';+import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';/*** Validates device access to an active payment session.@@ -15,9 +15,9 @@ function checkSessionDeviceAccess(session, req, body = null, ctx = null) {return { allowed: true, boundDeviceId: session.deviceId, isTerminal: true };}- // Only a co-located service on loopback holding the shared internal token may bypass device blocking.+ // Only a co-located service on loopback holding the shared internal token (or an admin) may bypass device blocking.// The `X-Internal-Render` flag on its own is attacker-controlled and proves nothing.- if (isInternalServiceRequest(req)) {+ if (isInternalServiceRequest(req) || isAdminRequest(req)) {return { allowed: true, boundDeviceId: session.deviceId };}@@ -710,19 +710,28 @@ export function registerCheckoutRoutes(server, ctx) {// Require a valid customer session token; never accept a bare client-asserted customerId!if (!token || typeof token !== 'string' || !ctx.customerSessionRepo) {- HttpServer.json(res, 401, { error: 'A valid customer session token is required to bind a customer identity.' });+ HttpServer.json(res, 401, {+ error: 'A valid customer session token is required to bind a customer identity.',+ code: 'CUSTOMER_SESSION_REQUIRED'+ });return;}const authContext = ctx.customerSessionRepo.findByToken(token.trim());if (!authContext || !authContext.customer) {- HttpServer.json(res, 401, { error: 'Invalid or expired customer session token.' });+ HttpServer.json(res, 401, {+ error: 'Invalid or expired customer session token.',+ code: 'CUSTOMER_SESSION_REQUIRED'+ });return;}const customer = authContext.customer;if (customerId && customerId !== customer.id) {- HttpServer.json(res, 401, { error: 'Customer ID does not match authenticated session token.' });+ HttpServer.json(res, 401, {+ error: 'Customer ID does not match authenticated session token.',+ code: 'CUSTOMER_SESSION_MISMATCH'+ });return;}@@ -1539,6 +1548,34 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ const deviceAccess = checkSessionDeviceAccess(session, req, body, ctx);+ if (!deviceAccess.allowed) {+ HttpServer.json(res, deviceAccess.statusCode || 409, deviceAccess.body);+ return;+ }++ const token = body.token ||+ body.sessionToken ||+ req.headers['x-customer-token'] ||+ ((req.headers['authorization'] || '').startsWith('Bearer ') ? req.headers['authorization'].slice(7).trim() : null);+ const authContext = (token && typeof token === 'string' && ctx.customerSessionRepo)+ ? ctx.customerSessionRepo.findByToken(token.trim())+ : null;++ const hasValidCustomerToken = Boolean(+ authContext?.customer && (!session.customerId || authContext.customer.id === session.customerId)+ );+ const hasVerifiedDevice = Boolean(deviceAccess.boundDeviceId);+ const hasOwnerAuth = isPaymentOwner(req, session, ctx);++ if (!hasValidCustomerToken && !hasVerifiedDevice && !hasOwnerAuth) {+ HttpServer.json(res, 401, {+ error: 'A valid customer session token or bound device credential is required to trigger checkout hooks.',+ code: 'CUSTOMER_SESSION_REQUIRED'+ });+ return;+ }+if (ctx.auditRepo) {ctx.auditRepo.log({merchantId: session.merchantId,diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex dfa0b41..ad3e45d 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -1,7 +1,7 @@import { HttpServer } from '../server.js';-import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual } from '@youpi/common';+import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual, verifyHmac } from '@youpi/common';import { isTerminalStatus, toPublicOutcome, verifyRegisteredDeviceCredentials } from '@youpi/core';-import { isPaymentOwner } from '../auth-guard.js';+import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';/*** Registers merchant-facing payment routes.@@ -46,11 +46,37 @@ export function registerPaymentRoutes(server, ctx) {return;}- if (req.headers['x-merchant-key']) {- if (!merchant.webhookSecret || !safeEqual(req.headers['x-merchant-key'].trim(), merchant.webhookSecret)) {+ const presentedMerchantKey = req.headers['x-merchant-key'] || body.merchantKey;+ const presentedOrderToken = req.headers['x-order-token'] || body.orderToken;++ if (presentedMerchantKey !== undefined && presentedMerchantKey !== null) {+ const keyValid = typeof ctx.merchantRepo.verifyApiKey === 'function'+ ? ctx.merchantRepo.verifyApiKey(merchant, String(presentedMerchantKey))+ : (Boolean(merchant.webhookSecret) && safeEqual(String(presentedMerchantKey).trim(), merchant.webhookSecret));+ if (!keyValid) {HttpServer.json(res, 401, { error: 'Invalid merchant key', code: 'INVALID_MERCHANT_KEY' });return;}+ } else if (presentedOrderToken) {+ let tokenAmountPaise;+ try {+ tokenAmountPaise = toPaise(body.amount);+ } catch {+ tokenAmountPaise = -1n;+ }+ const tokenCurrency = (body.currency || 'INR').toUpperCase();+ const canonicalOrderPayload = `${merchant.id}:${body.orderId || ''}:${tokenAmountPaise.toString()}:${tokenCurrency}`;+ const rawTokenSig = String(presentedOrderToken).replace(/^sha256=/, '').trim();+ if (!merchant.webhookSecret || !verifyHmac(canonicalOrderPayload, merchant.webhookSecret, rawTokenSig)) {+ HttpServer.json(res, 401, { error: 'Invalid order token', code: 'INVALID_ORDER_TOKEN' });+ return;+ }+ } else if (!isAdminRequest(req)) {+ HttpServer.json(res, 401, {+ error: 'Merchant API key is required (X-Merchant-Key).',+ code: 'MISSING_MERCHANT_KEY'+ });+ return;}if (!body.orderId || !body.amount) {@@ -58,6 +84,30 @@ export function registerPaymentRoutes(server, ctx) {return;}+ let amountPaise;+ try {+ amountPaise = toPaise(body.amount);+ } catch (err) {+ HttpServer.json(res, 400, { error: err.message });+ return;+ }+ const requestedCurrency = (body.currency || 'INR').toUpperCase();++ const isExplicitTestAutoActivate = body.autoActivate === true || body.autoActivate === 'true';+ if (isExplicitTestAutoActivate) {+ const autoActivateAllowed =+ process.env.NODE_ENV === 'test' ||+ process.env.ALLOW_TEST_AUTOACTIVATE === 'true' ||+ isAdminRequest(req);+ if (!autoActivateAllowed) {+ HttpServer.json(res, 403, {+ error: 'autoActivate is restricted to admin or test environments.',+ code: 'AUTOACTIVATE_FORBIDDEN'+ });+ return;+ }+ }+// returnUrl is echoed back to the customer's browser as a redirect target after// payment, so only absolute http(s) URLs are ever stored. This is the write-side// complement to the checkout page's sanitizeRedirectUrl.@@ -105,6 +155,16 @@ export function registerPaymentRoutes(server, ctx) {// Check idempotency & active session stateconst existing = ctx.sessionRepo.findByOrderId(merchant.id, body.orderId);if (existing) {+ const existingCurrency = (existing.currency || 'INR').toUpperCase();+ if (existing.amountPaise !== amountPaise || existingCurrency !== requestedCurrency) {+ HttpServer.json(res, 409, {+ error: 'ORDER_AMOUNT_MISMATCH',+ code: 'ORDER_AMOUNT_MISMATCH',+ message: `Order ${body.orderId} already exists with a different amount or currency.`+ });+ return;+ }+// If SUCCESS: order is already paid, return existing completed sessionif (existing.status === PaymentStatus.SUCCESS) {HttpServer.json(res, 200, {@@ -178,14 +238,6 @@ export function registerPaymentRoutes(server, ctx) {body.orderId = body.orderId.replace(/-R\d+$/, '');}- let amountPaise;- try {- amountPaise = toPaise(body.amount);- } catch (err) {- HttpServer.json(res, 400, { error: err.message });- return;- }-const isCounterPayment = body.method === 'CASH_COUNTER' || body.method === 'CARD_COUNTER';let receivingAccountId = null;@@ -254,7 +306,6 @@ export function registerPaymentRoutes(server, ctx) {// Digital UPI payments MUST ALWAYS start in status INITIATED without acquiring a concurrency slot or timer.// Only physical counter payments (CASH_COUNTER, CARD_COUNTER) start as ACTIVE (they do not use UPI slots).// The only exception for UPI auto-activation is explicit developer test suite flag: body.autoActivate === true.- const isExplicitTestAutoActivate = body.autoActivate === true || body.autoActivate === 'true';const shouldActivateNow = isCounterPayment || isExplicitTestAutoActivate;const initialStatus = isCounterPayment ? PaymentStatus.ACTIVE : PaymentStatus.INITIATED;diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 58946b5..24fb6fb 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -88,8 +88,14 @@ export class WebhookEngine {} catch {}}+ const deliveryId = crypto.randomUUID();+ const timestampNum = Date.now();+ const timestamp = timestampNum.toString();+const payloadObj = {event: publicOutcome,+ deliveryId,+ timestamp: timestampNum,paymentId: session.id,orderId: session.orderId,attemptId: session.attemptId || session.id,@@ -106,13 +112,13 @@ export class WebhookEngine {const payloadString = JSON.stringify(payloadObj);const signature = generateHmac(payloadString, merchant.webhookSecret);- const deliveryId = crypto.randomUUID();- const timestamp = Date.now().toString();+ const timestampedSignature = generateHmac(`${timestamp}.${payloadString}`, merchant.webhookSecret);const headers = {'Content-Type': 'application/json','X-Gateway-Event': publicOutcome,'X-Gateway-Signature': `sha256=${signature}`,+ 'X-Gateway-Signature-V2': `sha256=${timestampedSignature}`,'X-Gateway-Delivery-Id': deliveryId,'X-Gateway-Timestamp': timestamp};@@ -229,11 +235,8 @@ export class WebhookEngine {}const timestamp = Date.now().toString();- // The signature must cover exactly the transmitted body, using the same formula as- // dispatch(). Signing `${timestamp}.${payload}` here meant a retried delivery carried a- // different MAC than the first attempt, so the merchant's verification (HMAC over the- // raw body, per the documented contract) rejected every retry.const signature = generateHmac(item.payload, merchant.webhookSecret);+ const timestampedSignature = generateHmac(`${timestamp}.${item.payload}`, merchant.webhookSecret);let isSuccess = false;let respStatus = null;@@ -246,6 +249,7 @@ export class WebhookEngine {'Content-Type': 'application/json','X-Gateway-Event': item.event_type,'X-Gateway-Signature': `sha256=${signature}`,+ 'X-Gateway-Signature-V2': `sha256=${timestampedSignature}`,'X-Gateway-Delivery-Id': item.id,'X-Gateway-Timestamp': timestamp},diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.jsindex 51d16f9..ab78b02 100644--- a/packages/db/src/migrate.js+++ b/packages/db/src/migrate.js@@ -48,6 +48,7 @@ export function runMigrations(targetDb) {}// Fallback alter columns if customers/sessions table exists without new columns+ try { db.exec("ALTER TABLE merchants ADD COLUMN api_key_hash TEXT;"); } catch {}try { db.exec("ALTER TABLE customers ADD COLUMN email TEXT;"); } catch {}try { db.exec("ALTER TABLE customers ADD COLUMN mobile_number TEXT;"); } catch {}try { db.exec("ALTER TABLE customers ADD COLUMN otp_code TEXT;"); } catch {}diff --git a/packages/db/src/repositories/merchant.repository.js b/packages/db/src/repositories/merchant.repository.jsindex 4e0cd8a..dccef4c 100644--- a/packages/db/src/repositories/merchant.repository.js+++ b/packages/db/src/repositories/merchant.repository.js@@ -1,5 +1,10 @@import crypto from 'node:crypto';-import { encryptAtRest, decryptAtRest } from '@youpi/common';+import { encryptAtRest, decryptAtRest, safeEqual } from '@youpi/common';++/** Computes a deterministic SHA-256 hex digest for storing and verifying merchant API keys. */+export function hashApiKey(rawKey) {+ return crypto.createHash('sha256').update(String(rawKey)).digest('hex');+}/** Gmail OAuth credentials are nested inside `branding.gmailConfig`; encrypt just those. */const GMAIL_SECRET_FIELDS = ['clientSecret', 'refreshToken', 'apiKey'];@@ -50,10 +55,12 @@ export class MerchantRepository {? serializeBranding(data.branding): (data.branding || '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}');const now = new Date().toISOString();+ const rawWebhookSecret = data.webhookSecret || crypto.randomBytes(32).toString('hex');+ const apiKeyHash = data.apiKeyHash || (data.apiKey ? hashApiKey(data.apiKey) : hashApiKey(rawWebhookSecret));const sql = `- INSERT INTO merchants (id, business_name, slug, contact_email, contact_phone, webhook_url, webhook_secret, branding, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ INSERT INTO merchants (id, business_name, slug, contact_email, contact_phone, webhook_url, webhook_secret, api_key_hash, branding, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;this.db.execute(sql, [@@ -64,7 +71,8 @@ export class MerchantRepository {data.contactPhone,data.webhookUrl || null,// Webhook HMAC key must be recoverable at signing time, so it is encrypted at rest.- encryptAtRest(data.webhookSecret || crypto.randomBytes(32).toString('hex')),+ encryptAtRest(rawWebhookSecret),+ apiKeyHash,branding,now,now@@ -123,6 +131,17 @@ export class MerchantRepository {if (updates.webhookSecret !== undefined) {fields.push('webhook_secret = ?');params.push(encryptAtRest(updates.webhookSecret));+ if (updates.apiKey === undefined && updates.apiKeyHash === undefined) {+ fields.push('api_key_hash = ?');+ params.push(hashApiKey(updates.webhookSecret));+ }+ }+ if (updates.apiKey !== undefined) {+ fields.push('api_key_hash = ?');+ params.push(hashApiKey(updates.apiKey));+ } else if (updates.apiKeyHash !== undefined) {+ fields.push('api_key_hash = ?');+ params.push(updates.apiKeyHash);}if (updates.branding !== undefined) {fields.push('branding = ?');@@ -140,6 +159,23 @@ export class MerchantRepository {return this.findById(id);}+ /**+ * Verifies a candidate merchant API key against the merchant's stored SHA-256 apiKeyHash+ * (or webhookSecret for backward compatibility) in constant time.+ */+ verifyApiKey(merchant, candidateKey) {+ if (!merchant || !candidateKey || typeof candidateKey !== 'string') return false;+ const clean = candidateKey.trim();+ if (!clean) return false;+ if (merchant.apiKeyHash && safeEqual(hashApiKey(clean), merchant.apiKeyHash)) {+ return true;+ }+ if (merchant.webhookSecret && safeEqual(clean, merchant.webhookSecret)) {+ return true;+ }+ return false;+ }+mapRow(row) {return {id: row.id,@@ -150,6 +186,7 @@ export class MerchantRepository {webhookUrl: row.webhook_url,// Plaintext rows written before encryption existed decrypt to themselves.webhookSecret: decryptAtRest(row.webhook_secret),+ apiKeyHash: row.api_key_hash || null,branding: deserializeBranding(row.branding),createdAt: new Date(row.created_at),updatedAt: new Date(row.updated_at)diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sqlindex 2610b61..344fb6c 100644--- a/packages/db/src/schema.sql+++ b/packages/db/src/schema.sql@@ -12,6 +12,7 @@ CREATE TABLE IF NOT EXISTS merchants (contact_phone VARCHAR(20) NOT NULL,webhook_url VARCHAR(1024),webhook_secret VARCHAR(255) NOT NULL,+ api_key_hash VARCHAR(64),branding TEXT NOT NULL DEFAULT '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex faec951..0a02841 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -10,6 +10,7 @@ CREATE TABLE IF NOT EXISTS merchants (contact_phone TEXT NOT NULL,webhook_url TEXT,webhook_secret TEXT NOT NULL,+ api_key_hash TEXT,branding TEXT NOT NULL DEFAULT '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}',created_at TEXT NOT NULL DEFAULT (datetime('now')),updated_at TEXT NOT NULL DEFAULT (datetime('now'))diff --git a/packages/merchant-sdk/src/__tests__/merchant-sdk.test.js b/packages/merchant-sdk/src/__tests__/merchant-sdk.test.jsindex 381c290..c5c6aaa 100644--- a/packages/merchant-sdk/src/__tests__/merchant-sdk.test.js+++ b/packages/merchant-sdk/src/__tests__/merchant-sdk.test.js@@ -113,5 +113,45 @@ describe('Merchant SDK Integration Tests', () => {/invalid signature header format/);});++ test('verifies timestamped webhook signatures and rejects stale or mismatched timestamps', () => {+ const now = Date.now();+ const payloadObj = {+ event: 'SUCCESS',+ deliveryId: 'deliv_1001',+ timestamp: now,+ paymentId: 'pay_1001',+ orderId: 'ORD-1001',+ amount: '300.00',+ amountPaise: 30000,+ currency: 'INR'+ };+ const rawString = JSON.stringify(payloadObj);+ const sig = `sha256=${generateHmac(rawString, merchantSecret)}`;++ // Valid fresh timestamp matching signed payload+ const verified = client.verifyWebhook(rawString, sig, String(now), { toleranceMs: 300000 });+ assert.equal(verified.orderId, 'ORD-1001');++ // Also supports `${timestamp}.${rawBody}` signature scheme+ const bodyWithoutEmbeddedTs = JSON.stringify({ event: 'SUCCESS', orderId: 'ORD-1002' });+ const tsSig = `sha256=${generateHmac(`${now}.${bodyWithoutEmbeddedTs}`, merchantSecret)}`;+ const verifiedV2 = client.verifyWebhook(bodyWithoutEmbeddedTs, tsSig, String(now), { toleranceMs: 300000 });+ assert.equal(verifiedV2.orderId, 'ORD-1002');++ // Stale timestamp outside tolerance window is rejected+ const staleTs = String(now - 10 * 60 * 1000);+ const staleSig = `sha256=${generateHmac(`${staleTs}.${bodyWithoutEmbeddedTs}`, merchantSecret)}`;+ assert.throws(+ () => client.verifyWebhook(bodyWithoutEmbeddedTs, staleSig, staleTs, { toleranceMs: 300000 }),+ /timestamp missing or outside tolerance window/+ );++ // Mismatched timestamp header vs signed payload timestamp is rejected+ assert.throws(+ () => client.verifyWebhook(rawString, sig, String(now + 1000), { toleranceMs: 300000 }),+ /timestamp header does not match signed payload timestamp/+ );+ });});});diff --git a/packages/merchant-sdk/src/client.js b/packages/merchant-sdk/src/client.jsindex 00811f1..38ccebc 100644--- a/packages/merchant-sdk/src/client.js+++ b/packages/merchant-sdk/src/client.js@@ -5,13 +5,15 @@ export class YoupiPaymentClient {* @param {{* apiUrl?: string,* merchantId?: string,- * webhookSecret?: string+ * webhookSecret?: string,+ * apiKey?: string* }} options*/constructor(options = {}) {this.apiUrl = (options.apiUrl || process.env.BASE_PAYMENT_API_URL || 'http://localhost:6100').replace(/\/+$/, '');this.merchantId = options.merchantId || null;this.webhookSecret = options.webhookSecret || null;+ this.apiKey = options.apiKey || null;}/**@@ -44,6 +46,12 @@ export class YoupiPaymentClient {if (this.merchantId) {headers['X-Merchant-Id'] = this.merchantId;}+ if (this.apiKey || this.webhookSecret) {+ headers['X-Merchant-Key'] = this.apiKey || this.webhookSecret;+ }+ if (params.orderToken) {+ headers['X-Order-Token'] = params.orderToken;+ }if (params.idempotencyKey) {headers['Idempotency-Key'] = params.idempotencyKey;}@@ -96,8 +104,8 @@ export class YoupiPaymentClient {// Present the merchant secret so the gateway returns the merchant-private fields// (metadata, verification internals, returnUrl). Without it the caller gets the// redacted public view, which is all an unauthenticated holder of a payment id sees.- if (this.webhookSecret) {- headers['X-Merchant-Key'] = this.webhookSecret;+ if (this.apiKey || this.webhookSecret) {+ headers['X-Merchant-Key'] = this.apiKey || this.webhookSecret;}const res = await fetch(url, { headers });@@ -111,13 +119,37 @@ export class YoupiPaymentClient {}/**- * Cryptographically verifies an incoming webhook payload using HMAC-SHA256.+ * Cryptographically verifies an incoming webhook payload using HMAC-SHA256+ * and enforces timestamp freshness / replay protection when a timestamp is present.+ ** @param {string} rawPayloadString Raw request body text (unparsed)* @param {string} signatureHeader Value of 'X-Gateway-Signature' header (e.g. 'sha256=...')- * @param {string} [customSecret] Optional override secret+ * @param {string | number | { secret?: string, timestamp?: string | number, toleranceMs?: number, deliveryId?: string }} [customSecretOrTimestamp]+ * @param {{ secret?: string, timestamp?: string | number, toleranceMs?: number, deliveryId?: string }} [options]* @returns {any} Validated parsed webhook event payload*/- verifyWebhook(rawPayloadString, signatureHeader, customSecret = null) {+ verifyWebhook(rawPayloadString, signatureHeader, customSecretOrTimestamp = null, options = null) {+ let customSecret = null;+ let timestampHeader = null;+ let opts = options && typeof options === 'object' ? options : {};++ if (customSecretOrTimestamp && typeof customSecretOrTimestamp === 'object') {+ opts = customSecretOrTimestamp;+ customSecret = opts.secret || null;+ timestampHeader = opts.timestamp !== undefined ? opts.timestamp : null;+ } else if (options !== null && options !== undefined) {+ // 4-argument form: verifyWebhook(rawBody, signatureHeader, timestampHeader, options)+ timestampHeader = customSecretOrTimestamp;+ customSecret = opts.secret || null;+ } else if (+ typeof customSecretOrTimestamp === 'number' ||+ (typeof customSecretOrTimestamp === 'string' && /^\d{10,16}$/.test(customSecretOrTimestamp.trim()))+ ) {+ timestampHeader = customSecretOrTimestamp;+ } else if (typeof customSecretOrTimestamp === 'string') {+ customSecret = customSecretOrTimestamp;+ }+const secret = customSecret || this.webhookSecret;if (!secret) {throw new Error('Webhook verification failed: webhookSecret is not configured.');@@ -128,12 +160,48 @@ export class YoupiPaymentClient {}const actualSignature = signatureHeader.replace('sha256=', '');- const isValid = verifyHmac(rawPayloadString, secret, actualSignature);+ const toleranceMs = Number.isFinite(opts.toleranceMs) ? opts.toleranceMs : 5 * 60 * 1000;++ // Validate timestamp header freshness if supplied (or explicitly required via 4-arg call)+ if (timestampHeader !== null || options !== null) {+ const tsNum = Number(timestampHeader);+ if (!timestampHeader || !Number.isFinite(tsNum) || Math.abs(Date.now() - tsNum) > toleranceMs) {+ throw new Error('Webhook verification failed: timestamp missing or outside tolerance window.');+ }+ }- if (!isValid) {+ const matchesRawBody = verifyHmac(rawPayloadString, secret, actualSignature);+ const matchesTimestampedBody = timestampHeader !== null &&+ verifyHmac(`${timestampHeader}.${rawPayloadString}`, secret, actualSignature);++ if (!matchesRawBody && !matchesTimestampedBody) {throw new Error('Webhook verification failed: signature mismatch.');}- return JSON.parse(rawPayloadString);+ const parsed = JSON.parse(rawPayloadString);++ // If the signed JSON payload embeds a timestamp (standard for WebhookEngine), verify its freshness+ // and ensure any X-Gateway-Timestamp header matches the signed payload timestamp.+ if (parsed && parsed.timestamp !== undefined && parsed.timestamp !== null) {+ const bodyTs = Number(parsed.timestamp);+ if (!Number.isFinite(bodyTs) || Math.abs(Date.now() - bodyTs) > toleranceMs) {+ throw new Error('Webhook verification failed: signed payload timestamp outside tolerance window.');+ }+ if (timestampHeader !== null && String(timestampHeader).trim() !== String(parsed.timestamp).trim()) {+ throw new Error('Webhook verification failed: timestamp header does not match signed payload timestamp.');+ }+ } else if (timestampHeader !== null && !matchesTimestampedBody) {+ // If the JSON body did not contain a signed timestamp, a caller verifying a timestampHeader+ // must have the timestamp bound into `${timestamp}.${rawBody}` unless opts.allowUnsignedTimestampHeader is set.+ if (!opts.allowUnsignedTimestampHeader) {+ throw new Error('Webhook verification failed: timestamp is not bound by signature.');+ }+ }++ if (opts.deliveryId && parsed && parsed.deliveryId && String(opts.deliveryId) !== String(parsed.deliveryId)) {+ throw new Error('Webhook verification failed: deliveryId header does not match signed payload deliveryId.');+ }++ return parsed;}}diff --git a/scripts/test-support.js b/scripts/test-support.jsindex d902883..5721e94 100644--- a/scripts/test-support.js+++ b/scripts/test-support.js@@ -22,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|\/api\/v1\/pollers\/active-window|\/simulate-observation/;+const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/api\/v1\/pollers\/active-window|\/simulate-observation|\/api\/v1\/payments(\?|$)/;/** Admin bearer header only for routes the gateway guards; other routes (customer auth etc.) get none. */export function authHeadersFor(path, extra = {}) {