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
feat(merchant-keys): add merchant API key inspection, rotation, and flexible key resolution (Closes #89)
Harsh6a15b82cda1f
diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.htmlindex 981401d..34f1bbb 100644--- a/apps/merchant-admin/src/views/admin.html+++ b/apps/merchant-admin/src/views/admin.html@@ -2938,13 +2938,36 @@<div class="card"><div class="card-header"><div>- <div class="card-heading">⚡ Webhook Endpoints & Cryptographic Secrets</div>- <div class="card-subtext">Configure where real-time signed payment status events are dispatched via- HMAC-SHA256.</div>+ <div class="card-heading">🔑 Merchant API Keys, Webhook Endpoints & Cryptographic Secrets</div>+ <div class="card-subtext">View, copy, or rotate your Publishable Merchant ID (<code>data-youpi-key</code> / <code>X-Merchant-Id</code>), Secret Merchant API Key (<code>X-Merchant-Key</code>), and HMAC-SHA256 Webhook Signing Secret.</div></div></div><div style="display:flex; flex-direction:column; gap:1.25rem;">+ <div>+ <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Merchant ID / Publishable Key (<code>data-youpi-key</code> & <code>X-Merchant-Id</code>)</label>+ <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">+ <input id="settingMerchantId" type="text" readonly+ style="flex:1; min-width:260px; color:#38bdf8; font-family:monospace; font-weight:600;" />+ <button type="button" class="btn btn-secondary" onclick="copyFieldValue('settingMerchantId', 'Publishable Merchant ID')"+ style="padding:0.55rem 0.9rem; font-size:0.8rem;">📋 Copy</button>+ </div>+ <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Safe to embed in frontend HTML (<code><script src=".../youpi.js" data-youpi-key="..."></code>) and pass as <code>X-Merchant-Id</code> in REST API calls.</span>+ </div>++ <div>+ <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Secret Merchant API Key (<code>X-Merchant-Key</code>)</label>+ <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">+ <input id="settingMerchantApiKey" type="text" readonly+ style="flex:1; min-width:260px; color:#34d399; font-family:monospace; font-weight:600;" />+ <button type="button" class="btn btn-secondary" onclick="copyFieldValue('settingMerchantApiKey', 'Merchant API Key')"+ style="padding:0.55rem 0.9rem; font-size:0.8rem;">📋 Copy</button>+ <button type="button" class="btn btn-secondary" onclick="rotateMerchantApiKey()"+ style="padding:0.55rem 0.9rem; font-size:0.8rem; border-color:#38bdf8; color:#38bdf8;">🔄 Generate / Rotate Key</button>+ </div>+ <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Backend-only secret key used to authenticate server-to-server payment creation and status queries via the <code>X-Merchant-Key</code> header.</span>+ </div>+<div><label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">WebhookDestination URL</label>@@ -2957,8 +2980,15 @@<div><label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Webhook Secret(HMAC-SHA256 Signing)</label>- <input id="settingWebhookSecret" type="text" readonly- style="width:100%; color:#94a3b8; font-family:monospace;" />+ <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">+ <input id="settingWebhookSecret" type="text" readonly+ style="flex:1; min-width:260px; color:#94a3b8; font-family:monospace;" />+ <button type="button" class="btn btn-secondary" onclick="copyFieldValue('settingWebhookSecret', 'Webhook Secret')"+ style="padding:0.55rem 0.9rem; font-size:0.8rem;">📋 Copy</button>+ <button type="button" class="btn btn-secondary" onclick="rotateWebhookSecret()"+ style="padding:0.55rem 0.9rem; font-size:0.8rem;">🔄 Rotate Secret</button>+ </div>+ <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Used to verify <code>X-Gateway-Signature</code> on incoming server-to-server webhooks. Keep strictly on your backend.</span></div><button class="btn btn-primary" style="width:auto; align-self:flex-start;"@@ -4801,6 +4831,8 @@if (el) el.checked = Boolean(checked);};+ setVal('settingMerchantId', mData.publishableKey || mData.merchantId || currentMerchantId);+ setVal('settingMerchantApiKey', mData.merchantKey || branding.merchantApiKey || mData.webhookSecret || '');setVal('settingBusinessName', mData.businessName);setVal('settingWebhookUrl', mData.webhookUrl);setVal('settingWebhookSecret', mData.webhookSecret);@@ -5084,6 +5116,74 @@}}+ function copyFieldValue(inputId, label) {+ const el = document.getElementById(inputId);+ const val = el ? el.value.trim() : '';+ if (!val) {+ showAdminToast(`No ${label || 'value'} available to copy.`, false);+ return;+ }+ if (navigator.clipboard && navigator.clipboard.writeText) {+ navigator.clipboard.writeText(val).then(() => {+ showAdminToast(`${label || 'Value'} copied to clipboard!`);+ }).catch(() => {+ el.select();+ document.execCommand('copy');+ showAdminToast(`${label || 'Value'} copied to clipboard!`);+ });+ } else {+ el.select();+ document.execCommand('copy');+ showAdminToast(`${label || 'Value'} copied to clipboard!`);+ }+ }++ async function rotateMerchantApiKey() {+ if (!confirm('Generate a new Secret Merchant API Key (X-Merchant-Key)? Any backend scripts using the previous key will need to be updated.')) {+ return;+ }+ try {+ const res = await fetch(`${API_BASE}/api/v1/admin/merchant-key/rotate`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ merchantId: currentMerchantId || '00000000-0000-0000-0000-000000000001' })+ });+ const data = await res.json();+ if (res.ok && data.merchantKey) {+ const el = document.getElementById('settingMerchantApiKey');+ if (el) el.value = data.merchantKey;+ showAdminToast('New Secret Merchant API Key generated!');+ } else {+ showAdminToast(data.error || 'Failed to rotate Merchant API Key', false);+ }+ } catch (e) {+ showAdminToast('Network error rotating Merchant API Key.', false);+ }+ }++ async function rotateWebhookSecret() {+ if (!confirm('Rotate the Webhook HMAC Signing Secret? Make sure to update YOUPI_WEBHOOK_SECRET on your backend server.')) {+ return;+ }+ try {+ const res = await fetch(`${API_BASE}/api/v1/admin/webhook-secret/rotate`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ merchantId: currentMerchantId || '00000000-0000-0000-0000-000000000001' })+ });+ const data = await res.json();+ if (res.ok && data.webhookSecret) {+ const el = document.getElementById('settingWebhookSecret');+ if (el) el.value = data.webhookSecret;+ showAdminToast('New Webhook Secret generated!');+ } else {+ showAdminToast(data.error || 'Failed to rotate Webhook Secret', false);+ }+ } catch (e) {+ showAdminToast('Network error rotating Webhook Secret.', false);+ }+ }+// --- CANONICAL CLOUDFLARE TUNNEL ROUTING ---function getCalculatedDomainUrl() {const prefix = (document.getElementById('settingDomainPrefix')?.value || currentDomainPrefix || 'pay').trim().toLowerCase();diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 918652f..48cdac5 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -811,8 +811,9 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {]);assert.equal(attempts.length, 1);- // The engine records the delivery once the response has come back, so- // the row is waited for rather than read once and called a failure.+ // The engine records a write-ahead row before the request and updates+ // attempt_count >= 1 once the response has come back, so wait until+ // the first attempt has finalized.let failedRow = null;const rowDeadline = Date.now() + 5000;while (Date.now() < rowDeadline) {@@ -820,7 +821,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {'SELECT id, attempt_count, is_successful, next_retry_at FROM webhook_deliveries WHERE payment_id = ?',[paymentId]);- if (failedRow) break;+ if (failedRow && failedRow.attempt_count >= 1) break;await new Promise(resolve => setTimeout(resolve, 50));}assert.ok(failedRow, 'the failed delivery was not recorded');@@ -1123,11 +1124,77 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {// Attempt confirm-cod on cancelled session- const codRes = await request(`/api/v1/checkout/${paymentId}/confirm-cod`, {+ const codRes = await request(`/api/v1/checkout/${paymentId}/cancel`, {method: 'POST'});- assert.equal(codRes.status, 400);- assert.ok(codRes.body.error.includes('Cannot place COD order for terminal session'));+ const codAfterCancel = await request(`/api/v1/checkout/${paymentId}/confirm-cod`, {+ method: 'POST'+ });+ assert.equal(codAfterCancel.status, 400);+ assert.ok(codAfterCancel.body.error.includes('Cannot place COD order for terminal session'));+ });++ test('Merchant API Key rotation, inspection, and flexible data-youpi-key / X-Merchant-Id resolution (Issue #89)', async () => {+ // 1. Inspect merchant settings via admin API+ const settingsBefore = await request('/api/v1/admin/merchant-settings');+ assert.equal(settingsBefore.status, 200);+ assert.ok(settingsBefore.body.merchantId);+ assert.equal(settingsBefore.body.publishableKey, settingsBefore.body.merchantId);+ assert.ok(settingsBefore.body.merchantKey, 'merchantKey should be returned in merchant-settings');++ // 2. Rotate Merchant API Key via POST /api/v1/admin/merchant-key/rotate+ const rotateRes = await request('/api/v1/admin/merchant-key/rotate', {+ method: 'POST',+ body: { merchantId: settingsBefore.body.merchantId }+ });+ assert.equal(rotateRes.status, 200);+ assert.equal(rotateRes.body.success, true);+ assert.ok(rotateRes.body.merchantKey.startsWith('mk_live_'), 'rotated key must start with mk_live_');++ // 3. Verify GET /api/v1/admin/merchant-settings reflects the rotated key+ const settingsAfter = await request('/api/v1/admin/merchant-settings');+ assert.equal(settingsAfter.status, 200);+ assert.equal(settingsAfter.body.merchantKey, rotateRes.body.merchantKey);++ // 4. Create payment passing the rotated mk_live_... key in X-Merchant-Key+ const payWithKeyHeader = await request('/api/v1/payments', {+ method: 'POST',+ headers: {+ 'X-Merchant-Id': settingsBefore.body.merchantId,+ 'X-Merchant-Key': rotateRes.body.merchantKey+ },+ body: {+ orderId: 'ORD-MK-HEADER-89',+ amount: '125.00'+ }+ });+ assert.equal(payWithKeyHeader.status, 201);++ // 5. Create payment when developer passes mk_live_... directly in data-youpi-key (sent as X-Merchant-Id by youpi.js)+ const payWithKeyAsId = await request('/api/v1/payments', {+ method: 'POST',+ headers: {+ 'X-Merchant-Id': rotateRes.body.merchantKey+ },+ body: {+ orderId: 'ORD-MK-AS-ID-89',+ amount: '135.00'+ }+ });+ assert.equal(payWithKeyAsId.status, 201);++ // 6. Create payment when developer leaves documentation placeholder YOUR_MERCHANT_KEY in data-youpi-key+ const payWithPlaceholder = await request('/api/v1/payments', {+ method: 'POST',+ headers: {+ 'X-Merchant-Id': 'YOUR_MERCHANT_KEY'+ },+ body: {+ orderId: 'ORD-MK-PLACEHOLDER-89',+ amount: '145.00'+ }+ });+ assert.equal(payWithPlaceholder.status, 201);});});});diff --git a/apps/payment-api/src/routes/admin.routes.js b/apps/payment-api/src/routes/admin.routes.jsindex eab105f..1f0d61f 100644--- a/apps/payment-api/src/routes/admin.routes.js+++ b/apps/payment-api/src/routes/admin.routes.js@@ -660,6 +660,8 @@ export function registerAdminRoutes(server, ctx) {HttpServer.json(res, 200, {merchantId: merchant.id,+ publishableKey: merchant.id,+ merchantKey: merchant.merchantKey || branding.merchantApiKey || merchant.webhookSecret || '',businessName: merchant.businessName,upiId: account ? account.upiId : '',payeeName: account ? account.payeeName : merchant.businessName,@@ -862,6 +864,8 @@ export function registerAdminRoutes(server, ctx) {HttpServer.json(res, 200, {merchantId: merchant.id,+ publishableKey: merchant.id,+ merchantKey: merchant.merchantKey || branding.merchantApiKey || merchant.webhookSecret || '',businessName: merchant.businessName,contactEmail: merchant.contactEmail,contactPhone: merchant.contactPhone,@@ -1049,6 +1053,8 @@ export function registerAdminRoutes(server, ctx) {HttpServer.json(res, 200, {success: true,merchantId: updated.id,+ publishableKey: updated.id,+ merchantKey: updated.merchantKey || updated.branding?.merchantApiKey || updated.webhookSecret || '',businessName: updated.businessName,webhookUrl: updated.webhookUrl || '',webhookSecret: updated.webhookSecret || '',@@ -1070,6 +1076,75 @@ export function registerAdminRoutes(server, ctx) {});});+ // POST /api/v1/admin/merchant-key/rotate (Generate / Rotate Secret Merchant API Key)+ server.post('/api/v1/admin/merchant-key/rotate', async (req, res) => {+ const body = await HttpServer.parseBody(req).catch(() => ({}));+ const merchant = resolveMerchant(req, body.merchantId);+ if (!merchant) {+ HttpServer.json(res, 404, { error: 'Merchant not found' });+ return;+ }++ const rotated = typeof ctx.merchantRepo.rotateApiKey === 'function'+ ? ctx.merchantRepo.rotateApiKey(merchant.id)+ : (() => {+ const newKey = `mk_live_${crypto.randomBytes(24).toString('hex')}`;+ const updated = ctx.merchantRepo.update(merchant.id, {+ apiKey: newKey,+ branding: { ...(merchant.branding || {}), merchantApiKey: newKey }+ });+ return { ...updated, merchantKey: newKey };+ })();++ ctx.auditRepo.log({+ merchantId: merchant.id,+ entityType: 'MERCHANT',+ entityId: merchant.id,+ action: 'MERCHANT_API_KEY_ROTATED',+ actorType: AuditActorType.ADMIN,+ details: { merchantId: merchant.id }+ });++ HttpServer.json(res, 200, {+ success: true,+ merchantId: rotated.id,+ publishableKey: rotated.id,+ merchantKey: rotated.merchantKey+ });+ });++ // POST /api/v1/admin/webhook-secret/rotate (Generate / Rotate Webhook HMAC Signing Secret)+ server.post('/api/v1/admin/webhook-secret/rotate', async (req, res) => {+ const body = await HttpServer.parseBody(req).catch(() => ({}));+ const merchant = resolveMerchant(req, body.merchantId);+ if (!merchant) {+ HttpServer.json(res, 404, { error: 'Merchant not found' });+ return;+ }++ const newWebhookSecret = `whsec_${crypto.randomBytes(24).toString('hex')}`;+ const existingApiKey = merchant.branding?.merchantApiKey;+ const updated = ctx.merchantRepo.update(merchant.id, {+ webhookSecret: newWebhookSecret,+ ...(existingApiKey ? { apiKey: existingApiKey } : {})+ });++ ctx.auditRepo.log({+ merchantId: merchant.id,+ entityType: 'MERCHANT',+ entityId: merchant.id,+ action: 'MERCHANT_WEBHOOK_SECRET_ROTATED',+ actorType: AuditActorType.ADMIN,+ details: { merchantId: merchant.id }+ });++ HttpServer.json(res, 200, {+ success: true,+ merchantId: updated.id,+ webhookSecret: updated.webhookSecret+ });+ });+// GET /api/v1/admin/cod-orders (List Cash on Delivery orders)server.get('/api/v1/admin/cod-orders', async (req, res) => {let merchant = req.query.merchantId ? ctx.merchantRepo.findById(req.query.merchantId) : null;diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex 9a2f0cc..f40019a 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -33,10 +33,31 @@ export function registerPaymentRoutes(server, ctx) {const idempotencyKey = req.headers['idempotency-key'] || body.idempotencyKey;// Resolve merchant (default to first/demo merchant if none passed in header)- const merchantId = req.headers['x-merchant-id'] || body.merchantId;- let merchant;- if (merchantId) {- merchant = ctx.merchantRepo.findById(merchantId);+ const rawMerchantId = (req.headers['x-merchant-id'] || body.merchantId || '').toString().trim();+ const docPlaceholders = new Set([+ 'YOUR_MERCHANT_KEY',+ 'YOUR_MERCHANT_PUBLIC_KEY',+ 'YOUR_PUBLIC_KEY',+ 'MERCHANT_PUBLIC_KEY',+ 'YOUR_MERCHANT_ID'+ ]);+ let merchant = null;+ let matchedViaApiKeyInMerchantId = false;++ if (rawMerchantId && !docPlaceholders.has(rawMerchantId.toUpperCase())) {+ merchant = ctx.merchantRepo.findById(rawMerchantId);+ if (!merchant && typeof ctx.merchantRepo.findBySlug === 'function') {+ merchant = ctx.merchantRepo.findBySlug(rawMerchantId);+ }+ if (!merchant && typeof ctx.merchantRepo.verifyApiKey === 'function') {+ // Support developers who put their secret Merchant API Key (`mk_live_...` / webhookSecret) into `data-youpi-key` / `X-Merchant-Id`+ const allMerchants = ctx.merchantRepo.findAll();+ const byKey = allMerchants.find(m => ctx.merchantRepo.verifyApiKey(m, rawMerchantId));+ if (byKey) {+ merchant = byKey;+ matchedViaApiKeyInMerchantId = true;+ }+ }} else {merchant = ctx.merchantRepo.getDefault ? ctx.merchantRepo.getDefault() : (ctx.merchantRepo.findById('00000000-0000-0000-0000-000000000001') || ctx.merchantRepo.findAll()[0]);}@@ -46,7 +67,9 @@ export function registerPaymentRoutes(server, ctx) {return;}- const presentedMerchantKey = req.headers['x-merchant-key'] || body.merchantKey;+ const presentedMerchantKey = req.headers['x-merchant-key'] !== undefined+ ? req.headers['x-merchant-key']+ : (body.merchantKey !== undefined ? body.merchantKey : (matchedViaApiKeyInMerchantId ? rawMerchantId : undefined));const presentedOrderToken = req.headers['x-order-token'] || body.orderToken;if (presentedMerchantKey !== undefined && presentedMerchantKey !== null) {diff --git a/packages/db/src/repositories/merchant.repository.js b/packages/db/src/repositories/merchant.repository.jsindex dccef4c..9f75393 100644--- a/packages/db/src/repositories/merchant.repository.js+++ b/packages/db/src/repositories/merchant.repository.js@@ -9,10 +9,13 @@ export function hashApiKey(rawKey) {/** Gmail OAuth credentials are nested inside `branding.gmailConfig`; encrypt just those. */const GMAIL_SECRET_FIELDS = ['clientSecret', 'refreshToken', 'apiKey'];-/** Serializes branding, encrypting any nested Gmail OAuth secrets. */+/** Serializes branding, encrypting any nested Gmail OAuth secrets and merchantApiKey. */function serializeBranding(branding) {if (!branding || typeof branding !== 'object') return branding || '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}';const copy = { ...branding };+ if (copy.merchantApiKey && typeof copy.merchantApiKey === 'string') {+ copy.merchantApiKey = encryptAtRest(copy.merchantApiKey);+ }const gmail = copy.gmailConfig;if (gmail && typeof gmail === 'object') {const enc = { ...gmail };@@ -27,6 +30,9 @@ function serializeBranding(branding) {/** Reverses serializeBranding. Plaintext values written earlier pass through unchanged. */function deserializeBranding(raw) {const branding = JSON.parse(raw || '{}');+ if (branding.merchantApiKey && typeof branding.merchantApiKey === 'string') {+ branding.merchantApiKey = decryptAtRest(branding.merchantApiKey);+ }const gmail = branding.gmailConfig;if (gmail && typeof gmail === 'object') {const dec = { ...gmail };@@ -170,13 +176,39 @@ export class MerchantRepository {if (merchant.apiKeyHash && safeEqual(hashApiKey(clean), merchant.apiKeyHash)) {return true;}+ if (merchant.branding?.merchantApiKey && safeEqual(clean, merchant.branding.merchantApiKey)) {+ return true;+ }if (merchant.webhookSecret && safeEqual(clean, merchant.webhookSecret)) {return true;}return false;}+ /**+ * Generates and persists a new Merchant API Key (`mk_live_<48_hex_chars>`) for the merchant.+ */+ rotateApiKey(id) {+ const merchant = this.findById(id);+ if (!merchant) return null;+ const newApiKey = `mk_live_${crypto.randomBytes(24).toString('hex')}`;+ const updatedBranding = {+ ...(merchant.branding || {}),+ merchantApiKey: newApiKey+ };+ const updated = this.update(id, {+ apiKey: newApiKey,+ branding: updatedBranding+ });+ return {+ ...updated,+ merchantKey: newApiKey+ };+ }+mapRow(row) {+ const webhookSecret = decryptAtRest(row.webhook_secret);+ const branding = deserializeBranding(row.branding);return {id: row.id,businessName: row.business_name,@@ -185,9 +217,10 @@ export class MerchantRepository {contactPhone: row.contact_phone,webhookUrl: row.webhook_url,// Plaintext rows written before encryption existed decrypt to themselves.- webhookSecret: decryptAtRest(row.webhook_secret),+ webhookSecret,+ merchantKey: branding?.merchantApiKey || webhookSecret || '',apiKeyHash: row.api_key_hash || null,- branding: deserializeBranding(row.branding),+ branding,createdAt: new Date(row.created_at),updatedAt: new Date(row.updated_at)};