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 the remaining COD customer-contact leak
rishabhba081bb069c6
diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 6ec0dfb..9b252d5 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -355,9 +355,22 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.equal(bindRes.body.success, true);assert.equal(bindRes.body.customer.phoneNumber, '9111222333');- // 4. Inspect state: customer is attached!+ // 4. Inspect state: the customer is attached, but their contact details are NOT+ // disclosed to an anonymous caller that only holds the payment id.const stateRes = await request(`/api/v1/checkout/${paymentId}/state`);- assert.equal(stateRes.body.customer.phoneNumber, '9111222333');+ assert.equal(stateRes.body.customer, null);++ // The customer themselves, presenting their own session token, do see their profile.+ const selfState = await request(`/api/v1/checkout/${paymentId}/state`, {+ headers: { 'x-customer-token': regRes.body.token }+ });+ assert.equal(selfState.body.customer.phoneNumber, '9111222333');++ // The owning merchant, presenting its secret, sees the customer too.+ const ownerState = await request(`/api/v1/checkout/${paymentId}/state`, {+ headers: { 'X-Merchant-Key': merchantSecret }+ });+ assert.equal(ownerState.body.customer.phoneNumber, '9111222333');// 5. Test action trigger hookconst hookRes = await request(`/api/v1/checkout/${paymentId}/trigger-hook`, {diff --git a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.jsindex baf4e50..e61e690 100644--- a/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js+++ b/apps/payment-api/src/__tests__/selling-modes-and-cod.test.js@@ -1,7 +1,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 { Database, MerchantRepository } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { PaymentStatus, PaymentMethod, SellingMode } from '@youpi/common';import { authHeaders, authHeadersFor } from '../../../../scripts/test-support.js';@@ -10,11 +10,13 @@ describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & Clet apiInstance;let baseUrl;let testDb;+ let merchantSecret;before(async () => {testDb = new Database({ inMemory: true });apiInstance = await startPaymentApi(6195, testDb);baseUrl = `http://localhost:${apiInstance.port}`;+ merchantSecret = new MerchantRepository(testDb).findAll()[0].webhookSecret;});after(async () => {@@ -293,4 +295,64 @@ describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & Cconst stateCardOff = await request(`/api/v1/checkout/${paymentId}/state`);assert.deepEqual(stateCardOff.body.enabledMethods, ['UPI', 'CASH_COUNTER']);});++ test('SECURITY: customer contact is not disclosed to anonymous callers of the COD routes', async () => {+ const reg = await request('/api/v1/customer/register', {+ method: 'POST',+ body: { phoneNumber: '9111000099', fullName: 'COD PII Subject', email: '[email protected]', password: 'Password123!' }+ });+ assert.equal(reg.status, 201);+ const customerToken = reg.body.token;++ const pay = await request('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'COD-PII-ORDER-1', amount: '55.00' }+ });+ const paymentId = pay.body.paymentId;++ await request(`/api/v1/checkout/${paymentId}/bind-customer`, {+ method: 'POST',+ body: { customerId: reg.body.customerId }+ });++ // 1. Anonymous callers learn nothing about the customer.+ for (const path of [+ `/api/v1/payments/${paymentId}/cod`,+ `/api/v1/orders/COD-PII-ORDER-1/cod`,+ `/api/v1/checkout/${paymentId}/cod`+ ]) {+ const res = await request(path);+ assert.equal(res.status, 200, path);+ assert.equal(res.body.customer, null, `${path} leaked customer`);+ assert.equal(res.body.metadata, undefined, `${path} leaked metadata`);+ }++ // 2. The checkout state endpoint must not expose the customer to an anonymous holder+ // of the payment id either.+ const anonState = await request(`/api/v1/checkout/${paymentId}/state`);+ assert.equal(anonState.status, 200);+ assert.equal(anonState.body.customer, null, 'checkout state leaked customer');+ assert.deepEqual(anonState.body.metadata, {}, 'checkout state leaked metadata');++ // 3. The owning merchant does get the full view.+ const ownerRes = await request(`/api/v1/payments/${paymentId}/cod`, {+ headers: { 'X-Merchant-Key': merchantSecret }+ });+ assert.equal(ownerRes.status, 200);+ assert.equal(ownerRes.body.customer.mobileNumber, '9111000099');++ // 4. The customer themselves see their own profile.+ const selfRes = await request(`/api/v1/checkout/${paymentId}/state`, {+ headers: { 'x-customer-token': customerToken }+ });+ assert.equal(selfRes.status, 200);+ assert.equal(selfRes.body.customer.mobileNumber, '9111000099');++ // 5. A wrong merchant key is rejected like an anonymous caller.+ const wrongKey = await request(`/api/v1/payments/${paymentId}/cod`, {+ headers: { 'X-Merchant-Key': 'not-the-merchant-secret' }+ });+ assert.equal(wrongKey.status, 200);+ assert.equal(wrongKey.body.customer, null);+ });});diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex a724bc7..8927da7 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -505,8 +505,17 @@ export function registerCheckoutRoutes(server, ctx) {const authHeader = req.headers['authorization'] || '';const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : (req.headers['x-customer-token'] || null);+ // Customer PII is only disclosed to a party that is entitled to it:+ // - the owning merchant (admin/observer credential or X-Merchant-Key),+ // - the co-located checkout renderer,+ // - the customer themselves, presenting their own customer session token.+ // An anonymous holder of a payment id must not receive name/email/phone.+ const isOwnerCaller = isPaymentOwner(req, session, ctx) || isInternalServiceRequest(req);+ const tokenAuth = (bearerToken && ctx.customerSessionRepo) ? ctx.customerSessionRepo.findByToken(bearerToken) : null;+ const isSelfCaller = Boolean(tokenAuth?.customer && session.customerId && tokenAuth.customer.id === session.customerId);+let customer = null;- if (session.customerId && ctx.customerRepo) {+ if (session.customerId && ctx.customerRepo && (isOwnerCaller || isSelfCaller)) {const c = ctx.customerRepo.findById(session.customerId);if (c) {customer = {@@ -518,21 +527,22 @@ export function registerCheckoutRoutes(server, ctx) {phoneNumber: c.mobileNumber};}- } else if (!customer && bearerToken && ctx.customerSessionRepo) {- const authContext = ctx.customerSessionRepo.findByToken(bearerToken);- if (authContext?.customer) {- const c = authContext.customer;- customer = {- id: c.id,- name: c.name,- email: c.email,- mobileNumber: c.mobileNumber,- fullName: c.name,- phoneNumber: c.mobileNumber- };- }+ } else if (!customer && tokenAuth?.customer) {+ const c = tokenAuth.customer;+ customer = {+ id: c.id,+ name: c.name,+ email: c.email,+ mobileNumber: c.mobileNumber,+ fullName: c.name,+ phoneNumber: c.mobileNumber+ };}+ // Merchant metadata is merchant-private: only the owner (or the internal renderer)+ // may read it. The cancellation reason is exposed separately for the customer UI.+ const publicMetadata = isOwnerCaller ? (session.metadata || {}) : {};+// Single active payment session check (Section 1 & 2)const requestingDeviceId = req.headers['x-device-id'] || session.deviceId || null;let hasActiveSessionConflict = false;@@ -602,7 +612,7 @@ export function registerCheckoutRoutes(server, ctx) {status: session.status,reason: session.metadata?.cancelledReason || null,cancelledReason: session.metadata?.cancelledReason || null,- metadata: session.metadata || {},+ metadata: publicMetadata,method: session.method,verificationLevel: session.verificationLevel || 0,verificationSources: session.verificationSources || [],diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex b1bf78e..7bad9ec 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -29,6 +29,42 @@| `GMAIL_REDIRECT_URI` | derived | Gmail OAuth redirect URI. Defaults to `<gmail host from your configured domain>/oauth/callback` || `ANDROID_HEARTBEAT_TIMEOUT_MS` | `180000` | Inactivity window before Android device is marked DISCONNECTED || `CHECKOUT_FRAME_ANCESTORS` | `*` | `frame-ancestors` CSP for the checkout page. Set it to your storefront origins (for example `https://shop.example.com`) to stop other sites framing the checkout page. |+| `YOUPI_ALLOW_PRIVATE_WEBHOOKS` | unset | Set to `true` to permit merchant webhook URLs on loopback/private networks. Required for self-hosted LAN targets; blocked by default as an SSRF guard |++---++## 1b. Merchant API Authentication (`X-Merchant-Key`)++Endpoints that expose merchant-private or customer-contact data require the caller to+prove which merchant it is. There are three accepted credentials:++| Credential | Header | Grants |+| :--- | :--- | :--- |+| Merchant webhook secret | `X-Merchant-Key: <merchant webhook secret>` | Full merchant-private view of that merchant's own sessions: `metadata`, `internalStatus`, `verificationLevel` / `verificationSources` / `verificationTag`, `returnUrl`, and customer contact details |+| Admin bearer token | `Authorization: Bearer <ADMIN_API_TOKEN>` | Full access to every merchant's data (operator tooling) |+| Observer bearer token | `Authorization: Bearer <OBSERVER_API_TOKEN>` | Full access to every merchant's data (local observer processes) |++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`.++**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 never+disclosed to an anonymous caller that merely holds a payment id.++The official SDK sends `X-Merchant-Key` automatically when the merchant secret is+configured, so existing integrations receive the full view with no code change:++```javascript+const client = new YoupiPaymentClient({+ apiUrl: 'https://pay-api.example.com',+ merchantId: '00000000-0000-0000-0000-000000000001',+ webhookSecret: 'your-merchant-webhook-secret' // enables the merchant-scoped view+});+```++A customer browsing the checkout page sees their own profile because the checkout client+sends the customer session token (`x-customer-token`), not because the payment id is+enough to unlock it.---