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): repair PR #78 merge defects
rishabhd7b07414d803
diff --git a/README.md b/README.mdindex 6f0a115..1f675f2 100644--- a/README.md+++ b/README.md@@ -343,8 +343,12 @@ window.Youpi.pay({> **CRITICAL SECURITY RULE:** Never fulfill orders based solely on frontend browser events. Always verify the backend HMAC-SHA256 signature! Consumers **MUST** compute the HMAC over the raw, unparsed request bytes before any JSON parsing.#### Webhook Contract:-- **Header**: `X-Gateway-Signature: sha256=<64_char_hex_hash>`-- **Additional Headers**: `X-Gateway-Event: SUCCESS`, `X-Gateway-Delivery-Id: <uuid>`, `X-Gateway-Timestamp: <timestamp_ms>`+- **Header**: `X-Gateway-Signature: sha256=<64_char_hex_hash>` — `HMAC-SHA256(webhookSecret, rawRequestBody)`+- **Additional Headers**:+ - `X-Gateway-Event: SUCCESS`+ - `X-Gateway-Delivery-Id: <uuid>` — stable across retries; use it to deduplicate+ - `X-Gateway-Timestamp: <timestamp_ms>` — the time the delivery was FIRST signed+ - `X-Gateway-Signature-V2: sha256=<64_char_hex_hash>` — `HMAC-SHA256(webhookSecret, "<timestamp_ms>.<rawRequestBody>")`, binds the timestamp into the signature- **Payload Fields**:- `event`: `'SUCCESS'`- `orderId`: Merchant order ID (string)@@ -352,6 +356,15 @@ window.Youpi.pay({- `amountPaise`: Integer amount in Paise, e.g. `49900`- `utr`: 12-digit bank reference number- `paymentId`: Unique gateway payment session UUID+ - `deliveryId`: UUID of this delivery (matches the `X-Gateway-Delivery-Id` header)+ - `timestamp`: Epoch milliseconds the delivery was first signed (matches `X-Gateway-Timestamp`)+ - `verificationTag`, `verificationLevel`: Verification provenance+- **Retries**: a failed delivery is retried with backoff up to 1 hour later. The body is+ resent byte for byte, so `X-Gateway-Timestamp` and `X-Gateway-Delivery-Id` still describe+ the ORIGINAL delivery. Any freshness window you enforce must therefore cover the gateway's+ retry schedule; deduplicate on `deliveryId` rather than on the timestamp.+- **Amount matching**: reusing an `orderId` with a different amount is rejected with+ `409 ORDER_AMOUNT_MISMATCH`.#### Polyglot Webhook Verification Snippets:diff --git a/apps/coin-wallet-store/src/server.js b/apps/coin-wallet-store/src/server.jsindex 8692e5b..5ab5d11 100644--- a/apps/coin-wallet-store/src/server.js+++ b/apps/coin-wallet-store/src/server.js@@ -35,7 +35,12 @@ 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;+// The gateway signs the delivery timestamp into the body and reuses it on every retry, so+// a retried delivery legitimately arrives with an older timestamp. The window therefore+// has to cover the gateway's whole retry schedule (backoffs up to 1 hour), otherwise a+// legitimate retry is rejected as a replay. Replay of the SAME delivery is still caught by+// the delivery-id dedupe below.+const WEBHOOK_MAX_SKEW_MS = 2 * 60 * 60 * 1000;/** Keeps a client-supplied pack name printable and bounded before it is stored as metadata. */function sanitizePackName(value) {diff --git a/apps/control-center/src/server.js b/apps/control-center/src/server.jsindex cafe13a..9a2aa19 100644--- a/apps/control-center/src/server.js+++ b/apps/control-center/src/server.js@@ -25,12 +25,10 @@ function hasAdminToken(req, url = null, pathname = '') {if (match) {return safeEqual(match[1].trim(), getAdminToken());}- if (req.method?.toUpperCase() === 'GET' && pathname === '/api/logs/stream' && url) {- const queryToken = (url.searchParams.get('token') || '').trim();- if (queryToken) {- return safeEqual(queryToken, getAdminToken());- }- }+ // NOTE: the stream token is deliberately NOT accepted from a query parameter. A+ // credential in the URL ends up in access logs, browser history and Referer headers.+ // The dashboards now open the stream with fetch() so the token travels in the+ // Authorization header only.return false;}diff --git a/apps/control-center/src/views/dashboard.html b/apps/control-center/src/views/dashboard.htmlindex 19be007..98b5b33 100644--- a/apps/control-center/src/views/dashboard.html+++ b/apps/control-center/src/views/dashboard.html@@ -439,11 +439,100 @@document.getElementById('terminalLogWindow').innerHTML = '';}++ /**+ * Opens an SSE stream with an Authorization header.+ *+ * EventSource cannot send request headers, which is why the admin token used to be+ * passed as a `?token=` query parameter. That put a credential with write access into+ * the URL, so it landed in access logs, browser history and Referer headers. This uses+ * fetch() with a streaming body instead and keeps the token in the header only.+ *+ * @param {string} url+ * @param {string} token+ * @param {(event: string, data: string) => void} onEvent+ * @param {() => void} onError+ * @returns {{ close: () => void }}+ */+ function openAuthenticatedEventStream(url, token, onEvent, onError) {+ const controller = new AbortController();+ const listeners = new Map();+ let closed = false;++ const emit = (type, data) => {+ const handlers = listeners.get(type) || [];+ for (const handler of handlers) {+ try { handler({ data, type }); } catch (e) { }+ }+ if (onEvent) { try { onEvent(type, data); } catch (e) { } }+ };++ const run = async () => {+ try {+ const res = await fetch(url, {+ headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'text/event-stream' },+ signal: controller.signal+ });+ if (!res.ok || !res.body) throw new Error(`SSE failed: ${res.status}`);++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';++ while (!closed) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });++ let sep;+ while ((sep = buffer.indexOf('\n\n')) !== -1) {+ const raw = buffer.slice(0, sep);+ buffer = buffer.slice(sep + 2);++ let eventName = 'message';+ const dataLines = [];+ for (const line of raw.split('\n')) {+ if (line.startsWith('event:')) eventName = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));+ }+ emit(eventName, dataLines.join('\n'));+ }+ }+ } catch (err) {+ if (!closed) {+ if (typeof apiSse.onerror === 'function') { try { apiSse.onerror(err); } catch (e) { } }+ if (onError) { try { onError(err); } catch (e) { } }+ }+ }+ };++ // Minimal EventSource-compatible surface so existing call sites keep working.+ const apiSse = {+ addEventListener(type, handler) {+ if (!listeners.has(type)) listeners.set(type, []);+ listeners.get(type).push(handler);+ },+ removeEventListener(type, handler) {+ const arr = listeners.get(type) || [];+ const i = arr.indexOf(handler);+ if (i !== -1) arr.splice(i, 1);+ },+ close() {+ closed = true;+ try { controller.abort(); } catch (e) { }+ },+ onerror: null+ };++ run();+ return apiSse;+ }+function connectLogsSse() {if (sse) sse.close();const token = window.__youpiAdminAuth ? window.__youpiAdminAuth.token() : '';if (!token) return;- sse = new EventSource(`/api/logs/stream?token=${encodeURIComponent(token)}`);+ sse = openAuthenticatedEventStream('/api/logs/stream', token, null, null);sse.addEventListener('log', (e) => {try {diff --git a/apps/merchant-admin/src/server.js b/apps/merchant-admin/src/server.jsindex 4f2a75d..66e1b18 100644--- a/apps/merchant-admin/src/server.js+++ b/apps/merchant-admin/src/server.js@@ -22,12 +22,10 @@ function hasAdminToken(req, url = null, pathname = '') {if (match) {return safeEqual(match[1].trim(), getAdminToken());}- if (req.method?.toUpperCase() === 'GET' && pathname === '/api/logs/stream' && url) {- const queryToken = (url.searchParams.get('token') || '').trim();- if (queryToken) {- return safeEqual(queryToken, getAdminToken());- }- }+ // NOTE: the stream token is deliberately NOT accepted from a query parameter. A+ // credential in the URL ends up in access logs, browser history and Referer headers.+ // The dashboards now open the stream with fetch() so the token travels in the+ // Authorization header only.return false;}diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.htmlindex 4443878..981401d 100644--- a/apps/merchant-admin/src/views/admin.html+++ b/apps/merchant-admin/src/views/admin.html@@ -4147,26 +4147,116 @@// --- LIVE AGGREGATE TERMINAL LOGS (SSE) ---let rawLogsBuffer = [];++ /**+ * Opens an SSE stream with an Authorization header.+ *+ * EventSource cannot send request headers, which is why the admin token used to be+ * passed as a `?token=` query parameter. That put a credential with write access into+ * the URL, so it landed in access logs, browser history and Referer headers. This uses+ * fetch() with a streaming body instead and keeps the token in the header only.+ *+ * @param {string} url+ * @param {string} token+ * @param {(event: string, data: string) => void} onEvent+ * @param {() => void} onError+ * @returns {{ close: () => void }}+ */+ function openAuthenticatedEventStream(url, token, onEvent, onError) {+ const controller = new AbortController();+ const listeners = new Map();+ let closed = false;++ const emit = (type, data) => {+ const handlers = listeners.get(type) || [];+ for (const handler of handlers) {+ try { handler({ data, type }); } catch (e) { }+ }+ if (onEvent) { try { onEvent(type, data); } catch (e) { } }+ };++ const run = async () => {+ try {+ const res = await fetch(url, {+ headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'text/event-stream' },+ signal: controller.signal+ });+ if (!res.ok || !res.body) throw new Error(`SSE failed: ${res.status}`);++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';++ while (!closed) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });++ let sep;+ while ((sep = buffer.indexOf('\n\n')) !== -1) {+ const raw = buffer.slice(0, sep);+ buffer = buffer.slice(sep + 2);++ let eventName = 'message';+ const dataLines = [];+ for (const line of raw.split('\n')) {+ if (line.startsWith('event:')) eventName = line.slice(6).trim();+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));+ }+ emit(eventName, dataLines.join('\n'));+ }+ }+ } catch (err) {+ if (!closed) {+ if (typeof apiSse.onerror === 'function') { try { apiSse.onerror(err); } catch (e) { } }+ if (onError) { try { onError(err); } catch (e) { } }+ }+ }+ };++ // Minimal EventSource-compatible surface so existing call sites keep working.+ const apiSse = {+ addEventListener(type, handler) {+ if (!listeners.has(type)) listeners.set(type, []);+ listeners.get(type).push(handler);+ },+ removeEventListener(type, handler) {+ const arr = listeners.get(type) || [];+ const i = arr.indexOf(handler);+ if (i !== -1) arr.splice(i, 1);+ },+ close() {+ closed = true;+ try { controller.abort(); } catch (e) { }+ },+ onerror: null+ };++ run();+ return apiSse;+ }+function connectServicesLogsSse() {if (servicesLogsSse) return;const token = window.__youpiAdminAuth ? window.__youpiAdminAuth.token() : '';if (!token) return;try {- servicesLogsSse = new EventSource(`/api/logs/stream?token=${encodeURIComponent(token)}`);- servicesLogsSse.addEventListener('log', (e) => {- try {- const entry = JSON.parse(e.data);- appendLogEntry(entry);- } catch { }- });- servicesLogsSse.addEventListener('status_change', () => {- loadServices();- });- servicesLogsSse.onerror = () => {- servicesLogsSse.close();- servicesLogsSse = null;- setTimeout(connectServicesLogsSse, 5000);- };+ servicesLogsSse = openAuthenticatedEventStream(+ '/api/logs/stream',+ token,+ (eventName, data) => {+ if (eventName === 'log') {+ try { appendLogEntry(JSON.parse(data)); } catch { }+ } else if (eventName === 'status_change') {+ loadServices();+ }+ },+ () => {+ servicesLogsSse.close();+ servicesLogsSse = null;+ setTimeout(connectServicesLogsSse, 5000);+ }+ );} catch (e) { }}@@ -5852,24 +5942,30 @@function connectAdminEventsSse() {try {- // EventSource cannot send an Authorization header, so the stream accepts ?token= (GET only).- if (!window.__youpiAdminAuth.token()) return; // reconnected right after the token is entered+ const adminToken = window.__youpiAdminAuth.token();+ if (!adminToken) return; // reconnected right after the token is enteredif (window.__adminSse) { try { window.__adminSse.close(); } catch (e) {} }- const adminSse = window.__adminSse = new EventSource(`${API_BASE}/api/v1/admin/stream?token=${encodeURIComponent(window.__youpiAdminAuth.token())}`);- adminSse.addEventListener('counter_payment_requested', (event) => {- pollGlobalCounterPending();- fetchLiveData();- if (typeof fetchCounterPayments === 'function') fetchCounterPayments();- try {- const payload = event.data ? JSON.parse(event.data) : null;- const isCash = payload?.method === 'CASH_COUNTER';- const amt = payload?.amountPaise ? `₹${(Number(payload.amountPaise) / 100).toFixed(2)}` : '';- const ord = payload?.orderId ? `(Order #${payload.orderId})` : '';- showAdminToast(`🔔 Cashier Prompt: Customer requested ${isCash ? '💵 Cash at Till' : '💳 Card at POS'} ${amt} ${ord}!`);- } catch (e) {- showAdminToast('🔔 Cashier Prompt: In-store customer selected Cash/Card payment!');- }- });+ const adminSse = window.__adminSse = openAuthenticatedEventStream(+ `${API_BASE}/api/v1/admin/stream`,+ adminToken,+ (eventName, data) => {+ if (eventName !== 'counter_payment_requested') return;+ const event = { data };+ pollGlobalCounterPending();+ fetchLiveData();+ if (typeof fetchCounterPayments === 'function') fetchCounterPayments();+ try {+ const payload = event.data ? JSON.parse(event.data) : null;+ const isCash = payload?.method === 'CASH_COUNTER';+ const amt = (payload?.amountPaise) ? `₹${(Number(payload.amountPaise) / 100).toFixed(2)}` : '';+ const ord = (payload?.orderId) ? `(Order #${payload.orderId})` : '';+ showAdminToast(`🔔 Cashier Prompt: Customer requested ${isCash ? '💵 Cash at Till' : '💳 Card at POS'} ${amt} ${ord}!`);+ } catch (e) {+ showAdminToast('🔔 Cashier Prompt: In-store customer selected Cash/Card payment!');+ }+ },+ () => { /* the caller reconnects */ }+ );adminSse.addEventListener('status_change', () => {pollGlobalCounterPending();fetchLiveData();diff --git a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.jsindex 2ea6a5d..85af595 100644--- a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js@@ -661,7 +661,9 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2const 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+ // 1. Completely unauthenticated request naming the DEFAULT merchant -> allowed.+ // The public one-script integration (the browser SDK) cannot carry a merchant+ // secret, so this path has to stay open for the gateway's own merchant.const url = new URL('/api/v1/payments', baseUrl);const unauthRes = await new Promise((resolve, reject) => {const req = http.request(url, {@@ -676,8 +678,31 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2req.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');+ assert.equal(unauthRes.status, 201);++ // 1b. An unauthenticated request naming a DIFFERENT merchant -> 401, so an anonymous+ // caller still cannot inject sessions into another tenant.+ const otherMerchant = merchantRepo.create({+ businessName: 'Other Tenant',+ slug: 'other-tenant',+ contactEmail: '[email protected]',+ contactPhone: '9876543210'+ });+ const crossTenantRes = await new Promise((resolve, reject) => {+ const req = http.request(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'x-merchant-id': otherMerchant.id }+ }, (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: `XTENANT-${Date.now()}`, amount: '100.00' }));+ req.end();+ });+ assert.equal(crossTenantRes.status, 401);+ assert.equal(crossTenantRes.body.code, 'MISSING_MERCHANT_KEY');// 2. Request with valid dedicated API key (verified against api_key_hash) -> 201const orderId = `KEY-OK-${Date.now()}`;diff --git a/apps/payment-api/src/auth-guard.js b/apps/payment-api/src/auth-guard.jsindex 95471b5..8d25139 100644--- a/apps/payment-api/src/auth-guard.js+++ b/apps/payment-api/src/auth-guard.js@@ -7,9 +7,6 @@ const PUBLIC_ADMIN_PATHS = new Set(['/api/v1/admin/sms-gateway/download-apk']);/** Admin-prefixed routes the local observer processes call with the observer token. */const OBSERVER_ADMIN_PATHS = new Set(['/api/v1/admin/gmail/credentials']);-/** SSE cannot send headers from EventSource, so these accept `?token=` on GET. */-const QUERY_TOKEN_PATHS = new Set(['/api/v1/admin/stream']);-function bearerToken(req) {const header = req.headers['authorization'] || '';const match = /^Bearer\s+(.+)$/i.exec(header);@@ -52,10 +49,11 @@ export function authGuard(req, res, pathname, url) {const level = requiredLevel(method, pathname);if (!level) return false;- let presented = bearerToken(req);- if (!presented && method === 'GET' && QUERY_TOKEN_PATHS.has(pathname)) {- presented = url.searchParams.get('token') || '';- }+ // The token is only ever accepted from the Authorization header. Accepting it from a+ // query parameter put an admin credential into access logs, browser history and Referer+ // headers; the admin dashboard now opens its streams with fetch() so the credential+ // travels in the header only.+ const presented = bearerToken(req);const ok = presented && (safeEqual(presented, getAdminToken()) ||diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex 2da4a57..b167bbc 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, isInternalServiceRequest, isValidTransition } from '@youpi/common';+import { toRupeesString, buildUpiUri, PaymentStatus, PaymentMethod, UPI_PROVIDERS, isInternalServiceRequest, isValidTransition, getObserverToken } from '@youpi/common';import { validateSessionDeviceAccess, verifyRegisteredDeviceCredentials } from '@youpi/core';import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';@@ -236,7 +236,10 @@ async function checkUpiServerHealth(ctx, enabledMethods = [], sellingMode = 'OFFif (!smsHealthy) {try {const smsPort = Number(process.env.SMS_OBSERVER_PORT || 6002);- const res = await fetch(`http://127.0.0.1:${smsPort}/api/browser/status`, { signal: AbortSignal.timeout(800) });+ const res = await fetch(`http://127.0.0.1:${smsPort}/api/browser/status`, {+ headers: { 'Authorization': `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(800)+ });if (res.ok) {const data = await res.json();const isRecent = data.lastSeenAt && (Date.now() - new Date(data.lastSeenAt).getTime() < 300000);@@ -271,7 +274,10 @@ async function checkUpiServerHealth(ctx, enabledMethods = [], sellingMode = 'OFFif (!pollerActive) {try {- const res = await fetch(`http://127.0.0.1:${gmailPort}/api/browser/status`, { signal: AbortSignal.timeout(800) });+ const res = await fetch(`http://127.0.0.1:${gmailPort}/api/browser/status`, {+ headers: { 'Authorization': `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(800)+ });if (res.ok) {const data = await res.json();if (data.isLoggedIn || data.status === 'CONNECTED' || data.isPolling) {@@ -303,7 +309,10 @@ async function checkUpiServerHealth(ctx, enabledMethods = [], sellingMode = 'OFF// Check if browser-based Gmail automator is actively logged intry {const gmailPort = Number(process.env.GMAIL_OBSERVER_PORT || 6003);- const res = await fetch(`http://127.0.0.1:${gmailPort}/api/browser/status`, { signal: AbortSignal.timeout(800) });+ const res = await fetch(`http://127.0.0.1:${gmailPort}/api/browser/status`, {+ headers: { 'Authorization': `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(800)+ });if (res.ok) {const data = await res.json();if (data.isLoggedIn === true && data.status === 'CONNECTED') {diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex ad3e45d..9a2f0cc 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -72,11 +72,21 @@ export function registerPaymentRoutes(server, ctx) {return;}} else if (!isAdminRequest(req)) {- HttpServer.json(res, 401, {- error: 'Merchant API key is required (X-Merchant-Key).',- code: 'MISSING_MERCHANT_KEY'- });- return;+ // No credential was presented. The public one-script integration (the browser SDK)+ // cannot carry a merchant secret, so this path stays open - but only for the+ // gateway's own default merchant. Naming a different merchant requires that+ // merchant's key (or an order token), so an anonymous caller still cannot inject+ // sessions into another tenant's queue.+ const defaultMerchant = ctx.merchantRepo.getDefault+ ? ctx.merchantRepo.getDefault()+ : (ctx.merchantRepo.findById('00000000-0000-0000-0000-000000000001') || ctx.merchantRepo.findAll()[0]);+ if (!defaultMerchant || merchant.id !== defaultMerchant.id) {+ HttpServer.json(res, 401, {+ error: 'Merchant API key is required (X-Merchant-Key) for this merchant.',+ code: 'MISSING_MERCHANT_KEY'+ });+ return;+ }}if (!body.orderId || !body.amount) {diff --git a/data/test_whatsapp_session.json b/data/test_whatsapp_session.jsonnew file mode 100644index 0000000..e7f04a6--- /dev/null+++ b/data/test_whatsapp_session.json@@ -0,0 +1,7 @@+{+ "status": "CONNECTING",+ "phoneNumber": "918796266491",+ "sessionId": "youpi_berry_1792647996969",+ "platform": "BerryProtocol v0.1.10",+ "updatedAt": "2026-10-22T05:46:36.969Z"+}\ No newline at end of filediff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex c42c695..4e051f8 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -60,6 +60,19 @@ prove which merchant it is. There are three accepted credentials:Affected routes: `GET /api/v1/payments/:id`, `GET /api/v1/payments/:id/cod`,`GET /api/v1/orders/:orderId/cod` and `GET /api/v1/checkout/:id/state`.+### On `POST /api/v1/payments`++`X-Merchant-Key` is **optional** here, and the request is refused with+`401 MISSING_MERCHANT_KEY` only when it names a merchant other than the gateway's+default one. The public one-script integration (the browser SDK) cannot carry a+merchant secret — a secret in browser JavaScript is public — so the default-merchant+path has to stay open. Use `X-Merchant-Key` (or `X-Order-Token`) whenever a request+targets a specific tenant, and reuse an `orderId` only with the same amount: a+mismatch is rejected with `409 ORDER_AMOUNT_MISMATCH`.++`autoActivate: true` is restricted to admin-authenticated requests or to+`NODE_ENV=test`; elsewhere it is refused with `403 AUTOACTIVATE_FORBIDDEN`.+**Without a credential these routes return a redacted public view** — status, amount,currency, method and order id only. Customer name, email and phone number are neverdisclosed to an anonymous caller that merely holds a payment id.diff --git a/packages/core/src/__tests__/webhook-engine.test.js b/packages/core/src/__tests__/webhook-engine.test.jsindex fa44448..7b96272 100644--- a/packages/core/src/__tests__/webhook-engine.test.js+++ b/packages/core/src/__tests__/webhook-engine.test.js@@ -211,6 +211,50 @@ describe('Webhook Engine Integration Tests', () => {assert.equal(verifyHmac(JSON.stringify(retried.body), merchant.webhookSecret, retrySig), true);});+ test('a retried delivery keeps the timestamp and delivery id of the original body', async () => {+ const merchant = merchantRepo.create({+ businessName: 'Retry Consistency Store',+ slug: 'retry-consistency-store',+ contactEmail: '[email protected]',+ contactPhone: '9876543210',+ webhookUrl: `http://localhost:${receiverPort}/webhook-retry-consistency`,+ webhookSecret: 'test_secret_for_retry_consistency_123'+ });++ const session = sessionRepo.create({+ merchantId: merchant.id,+ orderId: 'HOOK-ORD-RETRY-CONSISTENCY',+ amountPaise: 70000n+ });++ receivedWebhooks = [];+ shouldReceiverFail = false;++ const result = await webhookEngine.dispatch('SUCCESS', session);+ assert.equal(result.delivered, true);+ const first = receivedWebhooks[receivedWebhooks.length - 1];+ const firstBody = first.body;+ assert.ok(firstBody.timestamp, 'payload must carry a timestamp');+ assert.ok(firstBody.deliveryId, 'payload must carry a delivery id');++ // The retry resends the SAME body, so the headers must describe that same body.+ db.execute('UPDATE webhook_deliveries SET next_retry_at = ? WHERE id = ?', [+ new Date(Date.now() - 60000).toISOString(), result.deliveryId+ ]);+ await webhookEngine.retryPending();++ const retried = receivedWebhooks[receivedWebhooks.length - 1];+ assert.equal(String(retried.headers['x-gateway-timestamp']), String(firstBody.timestamp),+ 'a retry must not recompute the timestamp, or it disagrees with the signed body');+ assert.equal(String(retried.headers['x-gateway-delivery-id']), String(firstBody.deliveryId),+ 'a retry must keep the delivery id of the body it resends');+ assert.equal(JSON.stringify(retried.body), JSON.stringify(first.body), 'a retry must resend the identical body');++ // And the merchant's verifier must accept the retried delivery.+ const rawSig = retried.headers['x-gateway-signature'].replace('sha256=', '');+ assert.equal(verifyHmac(JSON.stringify(retried.body), merchant.webhookSecret, rawSig), true);+ });+test('persists delivery failure record when merchant webhookSecret is missing', async () => {const merchantNoSecret = merchantRepo.create({businessName: 'No Secret Store',diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 24fb6fb..8ca9fc8 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -234,7 +234,23 @@ export class WebhookEngine {continue;}- const timestamp = Date.now().toString();+ // The retry resends the ORIGINAL body byte for byte, so the headers must describe+ // that same body. Recomputing a fresh timestamp here would make the header disagree+ // with the timestamp embedded in the payload, and the merchant's verification (which+ // cross-checks the two) would reject every retry.+ let storedTimestamp = null;+ let storedDeliveryId = item.id;+ try {+ const storedPayload = JSON.parse(item.payload);+ if (storedPayload && storedPayload.timestamp !== undefined && storedPayload.timestamp !== null) {+ storedTimestamp = String(storedPayload.timestamp);+ }+ if (storedPayload && storedPayload.deliveryId) {+ storedDeliveryId = String(storedPayload.deliveryId);+ }+ } catch {}++ const timestamp = storedTimestamp || Date.now().toString();const signature = generateHmac(item.payload, merchant.webhookSecret);const timestampedSignature = generateHmac(`${timestamp}.${item.payload}`, merchant.webhookSecret);@@ -250,7 +266,7 @@ export class WebhookEngine {'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-Delivery-Id': storedDeliveryId,'X-Gateway-Timestamp': timestamp},body: item.payload,diff --git a/packages/merchant-sdk/src/client.js b/packages/merchant-sdk/src/client.jsindex 38ccebc..73d6d97 100644--- a/packages/merchant-sdk/src/client.js+++ b/packages/merchant-sdk/src/client.js@@ -160,7 +160,12 @@ export class YoupiPaymentClient {}const actualSignature = signatureHeader.replace('sha256=', '');- const toleranceMs = Number.isFinite(opts.toleranceMs) ? opts.toleranceMs : 5 * 60 * 1000;+ // The gateway signs the delivery timestamp into the body and reuses it on every retry,+ // so a retried delivery legitimately arrives with an older timestamp. The default window+ // therefore covers the gateway's whole retry schedule (backoffs up to 1 hour); without+ // that, a legitimate retry is rejected as a replay. Replay of the SAME delivery is+ // still caught by deduplicating on the delivery id.+ const toleranceMs = Number.isFinite(opts.toleranceMs) ? opts.toleranceMs : 2 * 60 * 60 * 1000;// Validate timestamp header freshness if supplied (or explicitly required via 4-arg call)if (timestampHeader !== null || options !== null) {