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): remove committed PII, close payment IDOR, encrypt secrets at rest, enforce the state machine and make slot exclusivity a DB invariant
rishabh6c82cfb4e600
diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.htmlindex fbd5f48..7404244 100644--- a/apps/checkout-portal/src/views/checkout.html+++ b/apps/checkout-portal/src/views/checkout.html@@ -3317,7 +3317,7 @@<div class="ypg-input-group"><label class="ypg-input-label">Full Name</label>- <input type="text" class="ypg-input-control" id="authSignupName" placeholder="e.g. Gaurav Sharma" />+ <input type="text" class="ypg-input-control" id="authSignupName" placeholder="e.g. Alex Sharma" /></div><div class="ypg-input-group">diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.htmlindex baa4a9c..3890448 100644--- a/apps/merchant-admin/src/views/admin.html+++ b/apps/merchant-admin/src/views/admin.html@@ -2011,7 +2011,7 @@Sender / Short Code</label><input type="text" id="simSmsSender" value="HDFCBK"- placeholder="e.g. HDFCBK, AXISBK, 8796266491, arbitrary string..."+ placeholder="e.g. HDFCBK, AXISBK, SBIN, arbitrary string..."style="width:100%; box-sizing:border-box; background:#1e293b; color:#f8fafc; border:1px solid #475569; padding:0.5rem 0.75rem; border-radius:6px; font-size:0.84rem; font-family:monospace;" /></div>@@ -2816,7 +2816,7 @@<input type="text" id="testSmsSender" value="HDFCBK" placeholder="Sender (e.g. HDFCBK)"style="width:120px;" /><input type="text" id="testSmsBody"- value="Dear Customer, A/C *1234 credited by Rs 500.00 on 30-Sep-26 by UPI/9212339720/REF987654321 - HDFC Bank"+ value="Dear Customer, A/C *1234 credited by Rs 500.00 on 30-Sep-26 by UPI/9876543210/REF987654321 - HDFC Bank"placeholder="SMS Body" style="flex:1; min-width:240px;" /><button class="btn btn-primary" onclick="sendTestBankSms()">Dispatch</button></div>diff --git a/apps/payment-api/src/__tests__/developer-test-mode.test.js b/apps/payment-api/src/__tests__/developer-test-mode.test.jsindex 47c5940..80289a4 100644--- a/apps/payment-api/src/__tests__/developer-test-mode.test.js+++ b/apps/payment-api/src/__tests__/developer-test-mode.test.js@@ -65,6 +65,15 @@ describe('Section 12: Developer Test Mode Acceptance Tests (All 29 Points)', ()// Helper to create an active payment sessionfunction createActiveSession(orderId, amountPaise, customerId = null, slotOffsetMs = 0) {+ // A receiving account may hold only one slot-occupying session at a time (enforced by a+ // partial unique index). Release any session left over from the previous case so each+ // helper call starts from a clean slot, as the real queue does.+ testDb.execute(+ `UPDATE payment_sessions SET status = ?, updated_at = ?+ WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING')`,+ [PaymentStatus.CANCELLED, new Date().toISOString(), receivingAccountId]+ );+const now = Date.now() + slotOffsetMs;const session = sessionRepo.create({merchantId,diff --git a/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.js b/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.jsindex 6247824..2424d7e 100644--- a/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.js+++ b/apps/payment-api/src/__tests__/fraud-ban-pipeline.test.js@@ -79,12 +79,21 @@ describe('YOUPI PG: Parser Rule Correction & Exact Fraud/Ban System (All 29 Acce});}- function createActiveSession(orderId, amountPaise, customerId = null, slotOffsetMs = 0) {+ function createActiveSession(orderId, amountPaise, customerId = null, slotOffsetMs = 0, accountId = receivingAccountId) {+ // A receiving account may hold only one slot-occupying session (partial unique index).+ // Release whatever still occupies *this* account before taking its slot, so repeated+ // calls in separate cases start clean. Sessions on other accounts are untouched.+ testDb.execute(+ `UPDATE payment_sessions SET status = ?, updated_at = ?+ WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING')`,+ [PaymentStatus.CANCELLED, new Date().toISOString(), accountId]+ );+const now = Date.now() + slotOffsetMs;const session = sessionRepo.create({merchantId,customerId,- receivingAccountId,+ receivingAccountId: accountId,orderId,amountPaise,currency: 'INR',@@ -96,6 +105,21 @@ describe('YOUPI PG: Parser Rule Correction & Exact Fraud/Ban System (All 29 Accereturn session;}+ /**+ * A receiving account holds at most one slot-occupying session (partial unique index).+ * Tests needing several simultaneous ACTIVE sessions must spread them across accounts.+ */+ function createAdditionalReceivingAccount(suffix) {+ const id = `00000000-0000-0000-0000-0000000000${String(suffix).padStart(2, '0')}`;+ testDb.execute(+ `INSERT OR IGNORE INTO payment_receiving_accounts+ (id, merchant_id, upi_id, payee_name, is_merchant_enabled, is_active, is_slot_busy, created_at, updated_at)+ VALUES (?, ?, ?, ?, 1, 0, 0, ?, ?)`,+ [id, merchantId, `merchant${suffix}@upi`, 'Fraud Test Merchant', new Date().toISOString(), new Date().toISOString()]+ );+ return id;+ }+// =========================================================================// PARSER ACCEPTANCE TESTS (1 - 6)// =========================================================================@@ -461,7 +485,8 @@ describe('YOUPI PG: Parser Rule Correction & Exact Fraud/Ban System (All 29 AccemobileNumber: '+919876543221'});const s1 = createActiveSession('ORD-18-A', 49900n, cust.id);- const s2 = createActiveSession('ORD-18-B', 99900n, cust.id);+ // Second concurrent session needs a second slot: one account can only hold one.+ const s2 = createActiveSession('ORD-18-B', 99900n, cust.id, 0, createAdditionalReceivingAccount(91));assert.equal(sessionRepo.findById(s1.id).status, PaymentStatus.ACTIVE);assert.equal(sessionRepo.findById(s2.id).status, PaymentStatus.ACTIVE);diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 217ad42..3abce31 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -1,21 +1,26 @@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 } from '../index.js';import { PaymentStatus, ObserverSource, verifyHmac } from '@youpi/common';-import { authHeadersFor } from '../../../../scripts/test-support.js';+import { authHeadersFor, merchantHeaders } from '../../../../scripts/test-support.js';describe('Payment API End-to-End HTTP Integration Tests', () => {let serverInstance;let baseUrl;let testDb;+ let merchantSecret;before(async () => {testDb = new Database({ inMemory: true });// Use an ephemeral random port (e.g. 0 or high port 6199) to prevent collisionsserverInstance = await startServer(6199, testDb);baseUrl = `http://localhost:${serverInstance.port}`;+ // Merchant-private fields on GET /payments/:id are only returned to the owning+ // merchant, so read the seeded secret through the repository (the raw column is+ // encrypted at rest).+ merchantSecret = new MerchantRepository(testDb).findAll()[0].webhookSecret;});after(async () => {@@ -522,7 +527,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.ok(obs1.body.attribution.verificationTag.includes('Single Verification') || obs1.body.attribution.verificationTag.includes('SMS'));// Check payment status: must be SUCCESS with Level 1- const checkL1 = await request(`/api/v1/payments/${paymentId}`);+ const checkL1 = await request(`/api/v1/payments/${paymentId}`, { headers: merchantHeaders(merchantSecret) });assert.equal(checkL1.body.status, 'SUCCESS');assert.equal(checkL1.body.verificationLevel, 1);assert.deepEqual(checkL1.body.verificationSources, ['GOOGLE_MESSAGES']);@@ -543,7 +548,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.equal(obs2.body.attribution.verificationLevel, 2);assert.ok(obs2.body.attribution.verificationTag.includes('Dual Verification'));- const checkL2 = await request(`/api/v1/payments/${paymentId}`);+ const checkL2 = await request(`/api/v1/payments/${paymentId}`, { headers: merchantHeaders(merchantSecret) });assert.equal(checkL2.body.verificationLevel, 2);assert.ok(checkL2.body.verificationSources.includes('GOOGLE_MESSAGES'));assert.ok(checkL2.body.verificationSources.includes('GMAIL'));@@ -717,6 +722,8 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {webhookSecret: 'secret_autodetect_test_9988'}});+ // This test rotates the merchant secret; re-read so merchant-scoped reads still pass.+ merchantSecret = new MerchantRepository(testDb).findAll()[0].webhookSecret;// 4. Create payment session in ACTIVE state (customer scanning QR, did NOT click Payment Done)const payRes = await request('/api/v1/payments', {@@ -751,7 +758,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.equal(obs1.body.attribution.verificationLevel, 1);// Payment MUST be immediately SUCCESS for customer- const checkAfterObs1 = await request(`/api/v1/payments/${paymentId}`);+ const checkAfterObs1 = await request(`/api/v1/payments/${paymentId}`, { headers: merchantHeaders(merchantSecret) });assert.equal(checkAfterObs1.body.status, 'SUCCESS');assert.equal(checkAfterObs1.body.verificationLevel, 1);@@ -781,7 +788,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.equal(obs2.body.attribution.verificationLevel, 2);// Invariant: Verification level in admin upgrades to L2 (Dual Verification)- const checkAfterObs2 = await request(`/api/v1/payments/${paymentId}`);+ const checkAfterObs2 = await request(`/api/v1/payments/${paymentId}`, { headers: merchantHeaders(merchantSecret) });assert.equal(checkAfterObs2.body.verificationLevel, 2);assert.deepEqual(checkAfterObs2.body.verificationSources.sort(), ['GMAIL', 'GOOGLE_MESSAGES'].sort());diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex 2b21c47..1a63fdf 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -1,6 +1,28 @@import { HttpServer } from '../server.js';-import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus } from '@youpi/common';+import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual, hasBearer, getObserverToken } from '@youpi/common';import { isTerminalStatus, toPublicOutcome } from '@youpi/core';+import { isAdminRequest } from '../auth-guard.js';++/**+ * True when the caller may read the merchant-private fields of a payment session.+ *+ * Requires proof of ownership: either the gateway's own admin/observer credential, or the+ * owning merchant's webhook secret presented via `X-Merchant-Key` (which every merchant+ * integration already holds). Without it, only the public view is returned, so a leaked or+ * guessed payment id cannot be used to read internal status, verification internals,+ * merchant metadata or the return URL.+ */+function isPaymentOwner(req, session, ctx) {+ if (isAdminRequest(req)) return true;+ if (hasBearer(req, getObserverToken())) return true;++ const presented = req.headers['x-merchant-key'];+ 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;+ return safeEqual(presented.trim(), merchant.webhookSecret);+}/*** Registers merchant-facing payment routes.@@ -278,19 +300,30 @@ export function registerPaymentRoutes(server, ctx) {? toPublicOutcome(session.status): session.status;- HttpServer.json(res, 200, {+ // Fields any payment-id holder may read. Everything else is merchant-private: the raw+ // state machine status, verification internals, merchant metadata and the return URL.+ const publicView = {paymentId: session.id,orderId: session.orderId,amount: toRupeesString(session.amountPaise),amountPaise: session.amountPaise.toString(),currency: session.currency,status: publicStatus,- internalStatus: session.status,method: session.method,+ completedAt: session.completedAt ? session.completedAt.toISOString() : null+ };++ if (!isPaymentOwner(req, session, ctx)) {+ HttpServer.json(res, 200, publicView);+ return;+ }++ HttpServer.json(res, 200, {+ ...publicView,+ internalStatus: session.status,verificationLevel: session.verificationLevel || 0,verificationSources: session.verificationSources || [],verificationTag: session.verificationTag || 'UNVERIFIED',- completedAt: session.completedAt ? session.completedAt.toISOString() : null,returnUrl: session.returnUrl,metadata: session.metadata});diff --git a/packages/common/src/index.js b/packages/common/src/index.jsindex 099599b..1a03bde 100644--- a/packages/common/src/index.js+++ b/packages/common/src/index.js@@ -1,4 +1,5 @@export * from './enums.js';+export * from './state-transitions.js';export * from './money.js';export * from './crypto.js';export * from './observation.js';diff --git a/packages/common/src/secrets.js b/packages/common/src/secrets.jsindex 82f89d0..c2e3577 100644--- a/packages/common/src/secrets.js+++ b/packages/common/src/secrets.js@@ -2,6 +2,7 @@ import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';import { fileURLToPath } from 'node:url';+import { encrypt, decrypt } from './crypto.js';const __dirname = path.dirname(fileURLToPath(import.meta.url));// Resolved from this file, not cwd: every service must read the same files.@@ -68,6 +69,66 @@ export function isInternalServiceRequest(req) {/** Literal that older builds seeded into databases; must never be trusted. */export const LEGACY_DEFAULT_WEBHOOK_SECRET = 'merchant_webhook_secret_for_wallet_store';+/**+ * Master key for encrypting data at rest (merchant webhook secrets, OTPs).+ * Generated once and persisted alongside the other local secrets.+ */+export const getEncryptionMasterKey = () => resolveSecret('encryption_master_key', 'ENCRYPTION_MASTER_KEY');++/** Envelope prefix marking a stored value as AES-256-GCM ciphertext. */+const ENC_PREFIX = 'enc:v1:';++/** True when a stored value is in the ciphertext envelope. */+export function isEncryptedValue(value) {+ return typeof value === 'string' && value.startsWith(ENC_PREFIX);+}++/**+ * Encrypts a value for storage. Values are idempotent: an already-encrypted value is+ * returned unchanged so callers can wrap reads and writes without tracking state.+ */+export function encryptAtRest(plaintext) {+ if (plaintext === null || plaintext === undefined || plaintext === '') return plaintext;+ if (isEncryptedValue(plaintext)) return plaintext;+ return ENC_PREFIX + encrypt(String(plaintext), getEncryptionMasterKey());+}++/**+ * Decrypts a stored value, transparently passing through values written before encryption+ * existed (plaintext) so existing databases keep working and get re-encrypted on next write.+ */+export function decryptAtRest(stored) {+ if (!isEncryptedValue(stored)) return stored;+ try {+ return decrypt(stored.slice(ENC_PREFIX.length), getEncryptionMasterKey());+ } catch {+ // A value encrypted under a different/lost key must not silently become plaintext.+ return null;+ }+}++/**+ * Keyed digest for high-entropy secrets that are only ever looked up, never read back+ * (session tokens, device tokens). Unlike a plain hash this is not brute-forceable from a+ * database dump, because the key lives outside the database.+ */+export function blindIndex(value, namespace = 'token') {+ if (value === null || value === undefined || value === '') return null;+ const digest = crypto.createHmac('sha256', getInternalServiceToken())+ .update(`${namespace}:${value}`)+ .digest('hex');+ return `${namespace}_v1_${digest}`;+}++/**+ * Compares a presented secret against a stored blind index in constant time.+ */+export function blindIndexMatches(value, storedIndex, namespace = 'token') {+ const candidate = blindIndex(value, namespace);+ if (!candidate || !storedIndex) return false;+ return safeEqual(candidate, storedIndex);+}+/** True when the request's `Authorization: Bearer` value matches any of the given tokens. */export function hasBearer(req, ...tokens) {const match = /^Bearer\s+(.+)$/i.exec(req?.headers?.['authorization'] || '');diff --git a/packages/common/src/state-transitions.js b/packages/common/src/state-transitions.jsnew file mode 100644index 0000000..448db0c--- /dev/null+++ b/packages/common/src/state-transitions.js@@ -0,0 +1,80 @@+import { PaymentStatus } from './enums.js';++/**+ * Allowed payment session state transitions.+ *+ * This lives in `@youpi/common` rather than `@youpi/core` because the database layer+ * (`@youpi/db`) must enforce it too, and `@youpi/db` cannot depend on `@youpi/core`+ * (which already depends on it). `@youpi/core` re-exports these helpers unchanged.+ */+export const VALID_TRANSITIONS = Object.freeze({+ // EXPIRED is reachable from every non-terminal state: it is the universal "gave up"+ // outcome (timer elapsed, or an administrator clearing the queue), so it must never be+ // blocked just because the session had not reached the next stage yet.+ [PaymentStatus.INITIATED]: [+ PaymentStatus.ACTIVE,+ PaymentStatus.QUEUED,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.QUEUED]: [+ PaymentStatus.ACTIVE,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.ACTIVE]: [+ PaymentStatus.PROCESSING,+ // Tier-1 attribution settles a still-ACTIVE session as soon as the bank notification is+ // attributed, without waiting for the customer to press "I have paid". A bank-confirmed+ // credit is terminal regardless of whether the customer pressed the button.+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+ ],+ [PaymentStatus.PROCESSING]: [+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED+ ],+ [PaymentStatus.SUCCESS]: [],+ [PaymentStatus.FAILED]: [],+ [PaymentStatus.EXPIRED]: [],+ [PaymentStatus.CANCELLED]: []+});++/** States that can never change again. */+export const TERMINAL_STATES = Object.freeze([+ PaymentStatus.SUCCESS,+ PaymentStatus.FAILED,+ PaymentStatus.EXPIRED,+ PaymentStatus.CANCELLED+]);++/** States that occupy a merchant's single UPI concurrency slot. */+export const SLOT_OCCUPYING_STATES = Object.freeze([+ PaymentStatus.ACTIVE,+ PaymentStatus.PROCESSING+]);++/**+ * Validates whether a state transition is permitted.+ * @param {string} currentState+ * @param {string} nextState+ * @returns {boolean}+ */+export function isValidTransition(currentState, nextState) {+ const allowed = VALID_TRANSITIONS[currentState];+ if (!allowed) return false;+ return allowed.includes(nextState);+}++/** True when the state is a final, terminal outcome. */+export function isTerminalStatus(status) {+ return TERMINAL_STATES.includes(status);+}++/** True when the state holds a merchant concurrency slot. */+export function holdsSlot(status) {+ return SLOT_OCCUPYING_STATES.includes(status);+}\ No newline at end of filediff --git a/packages/core/src/state-machine.js b/packages/core/src/state-machine.jsindex c3ddeb1..7ca0aff 100644--- a/packages/core/src/state-machine.js+++ b/packages/core/src/state-machine.js@@ -1,46 +1,11 @@-import { PaymentStatus, PublicPaymentOutcome } from '@youpi/common';+import { isValidTransition, isTerminalStatus, VALID_TRANSITIONS } from '@youpi/common';/**- * Valid transitions graph for Payment Sessions:- * Key: Source State- * Value: Array of allowed Target States+ * The transition graph and helpers live in `@youpi/common` so the database layer can enforce+ * them too (`@youpi/db` cannot import `@youpi/core`). They are re-exported here to keep+ * `@youpi/core` the canonical import site for engine consumers.*/-export const VALID_TRANSITIONS = Object.freeze({- [PaymentStatus.INITIATED]: [- PaymentStatus.ACTIVE,- PaymentStatus.QUEUED,- PaymentStatus.CANCELLED- ],- [PaymentStatus.QUEUED]: [- PaymentStatus.ACTIVE,- PaymentStatus.CANCELLED- ],- [PaymentStatus.ACTIVE]: [- PaymentStatus.PROCESSING,- PaymentStatus.EXPIRED,- PaymentStatus.CANCELLED- ],- [PaymentStatus.PROCESSING]: [- PaymentStatus.SUCCESS,- PaymentStatus.FAILED- ],- [PaymentStatus.SUCCESS]: [],- [PaymentStatus.FAILED]: [],- [PaymentStatus.EXPIRED]: [],- [PaymentStatus.CANCELLED]: []-});--/**- * Validates whether a state transition is permitted by the core state machine.- * @param {string} currentState- * @param {string} nextState- * @returns {boolean}- */-export function isValidTransition(currentState, nextState) {- const allowed = VALID_TRANSITIONS[currentState];- if (!allowed) return false;- return allowed.includes(nextState);-}+export { VALID_TRANSITIONS, isValidTransition, isTerminalStatus };/*** Asserts a valid transition, throwing a detailed domain error if violated.@@ -55,20 +20,6 @@ export function assertValidTransition(currentState, nextState) {}}-/**- * Checks whether a payment status is a final, terminal outcome.- * @param {string} status- * @returns {boolean}- */-export function isTerminalStatus(status) {- return [- PaymentStatus.SUCCESS,- PaymentStatus.FAILED,- PaymentStatus.EXPIRED,- PaymentStatus.CANCELLED- ].includes(status);-}-/*** Converts internal payment status to the public contract outcome.* Throws if the status is not terminal.@@ -77,15 +28,15 @@ export function isTerminalStatus(status) {*/export function toPublicOutcome(status) {switch (status) {- case PaymentStatus.SUCCESS:- return PublicPaymentOutcome.SUCCESS;- case PaymentStatus.FAILED:- return PublicPaymentOutcome.FAILED;- case PaymentStatus.EXPIRED:- return PublicPaymentOutcome.EXPIRED;- case PaymentStatus.CANCELLED:- return PublicPaymentOutcome.CANCELLED;+ case 'SUCCESS':+ return 'SUCCESS';+ case 'FAILED':+ return 'FAILED';+ case 'EXPIRED':+ return 'EXPIRED';+ case 'CANCELLED':+ return 'CANCELLED';default:throw new Error(`Status '${status}' is an internal non-terminal state and cannot be mapped to a public outcome.`);}-}+}\ No newline at end of filediff --git a/packages/core/src/verification-pipeline.js b/packages/core/src/verification-pipeline.jsindex e2993f1..f195382 100644--- a/packages/core/src/verification-pipeline.js+++ b/packages/core/src/verification-pipeline.js@@ -307,7 +307,7 @@ export class PaymentVerificationPipeline {const cleanSender = (sender || '').trim();const digitsOnly = cleanSender.replace(/[\s+-]/g, '');- // Pure numeric check: Any string consisting solely of numbers (personal mobile numbers like 9212339720 or +91...)+ // Pure numeric check: Any string consisting solely of numbers (personal mobile numbers or +91 prefixed values)const isPureNumeric = /^\d+$/.test(digitsOnly) && !/[a-zA-Z]/.test(cleanSender);if (isPureNumeric) {diff --git a/packages/db/src/database.js b/packages/db/src/database.jsindex 17f220d..32143d4 100644--- a/packages/db/src/database.js+++ b/packages/db/src/database.js@@ -50,9 +50,14 @@ export class Database {}const dir = path.dirname(dbPath);if (!fs.existsSync(dir)) {- fs.mkdirSync(dir, { recursive: true });+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });}this.db = new DatabaseSync(dbPath);+ // The file holds webhook secrets, session-token indexes, OTPs and customer PII.+ // Default file creation honours umask, which on many hosts leaves it group/world+ // readable, so restrict it explicitly.+ try { fs.chmodSync(dbPath, 0o600); } catch {}+ try { fs.chmodSync(dir, 0o700); } catch {}}// Enable foreign keys, busy timeout, and WAL mode for maximum concurrency and integrity@@ -134,7 +139,10 @@ export class Database {* @returns {T}*/transaction(callback) {- this.db.exec('BEGIN TRANSACTION;');+ // IMMEDIATE (not DEFERRED) so the write lock is taken up front. A deferred transaction+ // starts as a read transaction and only upgrades on first write, which lets two+ // concurrent slot-acquisition callers both observe a free slot before either writes.+ this.db.exec('BEGIN IMMEDIATE;');try {const result = callback();this.db.exec('COMMIT;');diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.jsindex dc41bad..98a9c2a 100644--- a/packages/db/src/migrate.js+++ b/packages/db/src/migrate.js@@ -154,17 +154,22 @@ export function runMigrations(targetDb) {});}- // Seed default customer if none exists- const customerRepo = new CustomerRepository(db);- const existingCust = customerRepo.findByMobile('9212339720');- if (!existingCust) {- customerRepo.create({- id: '00000000-0000-0000-0000-000000000002',- name: 'Gaurav Mehra',- email: '[email protected]',- mobileNumber: '9212339720',- isPhoneVerified: true- });+ // Demo customer seeding is opt-in and never carries real personal data.+ // Previously this unconditionally created a customer with a real name, phone number and+ // email, and flagged the phone as verified — shipping someone's PII (and a pre-authorised+ // OTP login identity) into every merchant deployment.+ if (process.env.YOUPI_SEED_DEMO_CUSTOMER === 'true') {+ const customerRepo = new CustomerRepository(db);+ const demoMobile = '9000000000';+ if (!customerRepo.findByMobile(demoMobile)) {+ customerRepo.create({+ id: '00000000-0000-0000-0000-000000000002',+ name: 'Demo Customer',+ email: '[email protected]',+ mobileNumber: demoMobile,+ isPhoneVerified: false+ });+ }}return {diff --git a/packages/db/src/repositories/customer-session.repository.js b/packages/db/src/repositories/customer-session.repository.jsindex a548cb2..dc7bb0c 100644--- a/packages/db/src/repositories/customer-session.repository.js+++ b/packages/db/src/repositories/customer-session.repository.js@@ -1,4 +1,8 @@import crypto from 'node:crypto';+import { blindIndex } from '@youpi/common';++/** Namespace so session-token and device-token digests can never collide. */+const INDEX_NS = 'csess';export class CustomerSessionRepository {/**@@ -31,10 +35,13 @@ export class CustomerSessionRepository {VALUES (?, ?, ?, ?, 1, ?, ?, ?, ?)`;+ // The bearer token is returned to the client once and never read back from the database,+ // so only a keyed blind index is stored. A database dump therefore cannot be replayed+ // as valid sessions, which a plaintext (or plain-hashed) column would allow.this.db.execute(sql, [id,data.customerId,- token,+ blindIndex(token, INDEX_NS),expiresAt.toISOString(),data.ipAddress || null,data.userAgent || null,@@ -62,9 +69,24 @@ export class CustomerSessionRepository {const row = this.db.queryOne('SELECT * FROM customer_sessions WHERE token = ? AND is_active = 1',- [token]+ [blindIndex(token, INDEX_NS)]);+ // Rows written before index-only storage held the raw token.+ if (!row && typeof token === 'string' && token.startsWith('csess_') && token.length < 100) {+ const legacy = this.db.queryOne(+ 'SELECT * FROM customer_sessions WHERE token = ? AND is_active = 1',+ [token]+ );+ if (legacy) {+ // Re-index on first successful use so the plaintext row does not linger.+ try {+ this.db.execute('UPDATE customer_sessions SET token = ? WHERE id = ?', [blindIndex(token, INDEX_NS), legacy.id]);+ } catch {}+ return this.findByToken(token);+ }+ }+if (!row) return null;const expiresAt = new Date(row.expires_at);@@ -82,7 +104,6 @@ export class CustomerSessionRepository {const session = {id: row.id,customerId: row.customer_id,- token: row.token,expiresAt,isActive: Boolean(row.is_active),createdAt: new Date(row.created_at)@@ -121,6 +142,11 @@ export class CustomerSessionRepository {revokeToken(token) {if (!token) return false;const now = new Date().toISOString();+ this.db.execute(+ 'UPDATE customer_sessions SET is_active = 0, updated_at = ? WHERE token = ?',+ [now, blindIndex(token, INDEX_NS)]+ );+ // Also clear any legacy plaintext row so logout always revokes.this.db.execute('UPDATE customer_sessions SET is_active = 0, updated_at = ? WHERE token = ?',[now, token]diff --git a/packages/db/src/repositories/customer.repository.js b/packages/db/src/repositories/customer.repository.jsindex 03439e3..5e3a90e 100644--- a/packages/db/src/repositories/customer.repository.js+++ b/packages/db/src/repositories/customer.repository.js@@ -1,5 +1,5 @@import crypto from 'node:crypto';-import { hashPassword, verifyPassword, normalizeEmail, normalizeMobile, isValidEmail, isValidMobile, isValidPassword, safeEqual } from '@youpi/common';+import { hashPassword, verifyPassword, normalizeEmail, normalizeMobile, isValidEmail, isValidMobile, isValidPassword, safeEqual, encryptAtRest, decryptAtRest } from '@youpi/common';/** Wrong guesses tolerated per issued OTP before the challenge is burned. */const OTP_MAX_ATTEMPTS = 5;@@ -198,7 +198,7 @@ export class CustomerRepository {const now = new Date().toISOString();this.db.execute('UPDATE customers SET otp_code = ?, otp_expires_at = ?, otp_attempts = 0, updated_at = ? WHERE mobile_number = ?',- [otpCode, expiresAt, now, normalized]+ [encryptAtRest(otpCode), expiresAt, now, normalized]);return this.findByMobile(normalized);}@@ -223,9 +223,10 @@ export class CustomerRepository {if (attempts >= OTP_MAX_ATTEMPTS) return null;const submitted = String(otpCode).trim();+ const storedOtp = decryptAtRest(customer.otpCode);// `!==` short-circuits on the first differing character; use a constant-time compare.- const matches = safeEqual(customer.otpCode || '', submitted);- if (!customer.otpCode || !matches) {+ const matches = storedOtp ? safeEqual(storedOtp, submitted) : false;+ if (!storedOtp || !matches) {this.db.execute('UPDATE customers SET otp_attempts = ?, updated_at = ? WHERE id = ?',[attempts + 1, new Date().toISOString(), customer.id]@@ -608,7 +609,7 @@ export class CustomerRepository {mobileNumber: row.mobile_number,phoneNumber: row.mobile_number,passwordHash: row.password_hash,- otpCode: row.otp_code || null,+ otpCode: decryptAtRest(row.otp_code),otpExpiresAt: row.otp_expires_at ? new Date(row.otp_expires_at) : null,otpAttempts: Number(row.otp_attempts || 0),isPhoneVerified: Boolean(row.is_phone_verified),diff --git a/packages/db/src/repositories/device.repository.js b/packages/db/src/repositories/device.repository.jsindex e681278..2c1f2aa 100644--- a/packages/db/src/repositories/device.repository.js+++ b/packages/db/src/repositories/device.repository.js@@ -1,4 +1,8 @@import crypto from 'node:crypto';+import { blindIndex } from '@youpi/common';++/** Namespace so device-token digests never collide with other blind indexes. */+const INDEX_NS = 'devtok';export class DeviceRepository {/**@@ -50,13 +54,18 @@ export class DeviceRepository {data.timezone || null,data.language || null,data.screenSignature || null,- deviceToken,+ // Only a keyed blind index is persisted: the raw token is never needed again and a+ // database dump must not yield usable device credentials.+ blindIndex(deviceToken, INDEX_NS),status,now,now]);- return this.findById(id);+ // The plaintext token is returned here and only here: it is issued to the registering+ // client once. Persisted storage keeps only the keyed blind index.+ const created = this.findById(id);+ return created ? { ...created, deviceToken } : null;}/**@@ -75,7 +84,23 @@ export class DeviceRepository {*/findByToken(token) {if (!token) return null;- const row = this.db.queryOne('SELECT * FROM devices WHERE device_token = ? AND status = "ACTIVE"', [token]);+ let row = this.db.queryOne(+ 'SELECT * FROM devices WHERE device_token = ? AND status = ?',+ [blindIndex(token, INDEX_NS), 'ACTIVE']+ );+ // Rows written before index-only storage held the raw token; re-index on first use.+ if (!row && typeof token === 'string' && token.startsWith('devtok_')) {+ const legacy = this.db.queryOne(+ 'SELECT * FROM devices WHERE device_token = ? AND status = ?',+ [token, 'ACTIVE']+ );+ if (legacy) {+ try {+ this.db.execute('UPDATE devices SET device_token = ? WHERE id = ?', [blindIndex(token, INDEX_NS), legacy.id]);+ } catch {}+ row = legacy;+ }+ }return row ? this.mapRow(row) : null;}@@ -167,7 +192,7 @@ export class DeviceRepository {}if (data.deviceToken !== undefined) {fields.push('device_token = ?');- values.push(data.deviceToken);+ values.push(blindIndex(data.deviceToken, INDEX_NS));}fields.push('last_seen_at = ?');@@ -194,7 +219,8 @@ export class DeviceRepository {timezone: row.timezone,language: row.language,screenSignature: row.screen_signature,- deviceToken: row.device_token,+ // Omitted: this column now holds a keyed blind index, not a usable credential.+ deviceToken: null,status: row.status,createdAt: new Date(row.created_at),lastSeenAt: new Date(row.last_seen_at)diff --git a/packages/db/src/repositories/merchant.repository.js b/packages/db/src/repositories/merchant.repository.jsindex d6f5d37..4e0cd8a 100644--- a/packages/db/src/repositories/merchant.repository.js+++ b/packages/db/src/repositories/merchant.repository.js@@ -1,4 +1,37 @@import crypto from 'node:crypto';+import { encryptAtRest, decryptAtRest } from '@youpi/common';++/** 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. */+function serializeBranding(branding) {+ if (!branding || typeof branding !== 'object') return branding || '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}';+ const copy = { ...branding };+ const gmail = copy.gmailConfig;+ if (gmail && typeof gmail === 'object') {+ const enc = { ...gmail };+ for (const field of GMAIL_SECRET_FIELDS) {+ if (enc[field]) enc[field] = encryptAtRest(enc[field]);+ }+ copy.gmailConfig = enc;+ }+ return JSON.stringify(copy);+}++/** Reverses serializeBranding. Plaintext values written earlier pass through unchanged. */+function deserializeBranding(raw) {+ const branding = JSON.parse(raw || '{}');+ const gmail = branding.gmailConfig;+ if (gmail && typeof gmail === 'object') {+ const dec = { ...gmail };+ for (const field of GMAIL_SECRET_FIELDS) {+ if (dec[field]) dec[field] = decryptAtRest(dec[field]);+ }+ branding.gmailConfig = dec;+ }+ return branding;+}export class MerchantRepository {/**@@ -13,7 +46,9 @@ export class MerchantRepository {*/create(data) {const id = data.id || crypto.randomUUID();- const branding = typeof data.branding === 'object' ? JSON.stringify(data.branding) : (data.branding || '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}');+ const branding = typeof data.branding === 'object'+ ? serializeBranding(data.branding)+ : (data.branding || '{"primaryColor":"#2563eb","appName":"YOUPI PG","logoUrl":null}');const now = new Date().toISOString();const sql = `@@ -28,7 +63,8 @@ export class MerchantRepository {data.contactEmail,data.contactPhone,data.webhookUrl || null,- data.webhookSecret || crypto.randomBytes(32).toString('hex'),+ // Webhook HMAC key must be recoverable at signing time, so it is encrypted at rest.+ encryptAtRest(data.webhookSecret || crypto.randomBytes(32).toString('hex')),branding,now,now@@ -86,11 +122,11 @@ export class MerchantRepository {}if (updates.webhookSecret !== undefined) {fields.push('webhook_secret = ?');- params.push(updates.webhookSecret);+ params.push(encryptAtRest(updates.webhookSecret));}if (updates.branding !== undefined) {fields.push('branding = ?');- params.push(typeof updates.branding === 'object' ? JSON.stringify(updates.branding) : updates.branding);+ params.push(typeof updates.branding === 'object' ? serializeBranding(updates.branding) : updates.branding);}if (fields.length === 0) return this.findById(id);@@ -112,8 +148,9 @@ export class MerchantRepository {contactEmail: row.contact_email,contactPhone: row.contact_phone,webhookUrl: row.webhook_url,- webhookSecret: row.webhook_secret,- branding: JSON.parse(row.branding || '{}'),+ // Plaintext rows written before encryption existed decrypt to themselves.+ webhookSecret: decryptAtRest(row.webhook_secret),+ branding: deserializeBranding(row.branding),createdAt: new Date(row.created_at),updatedAt: new Date(row.updated_at)};diff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.jsindex 844789f..ea8d10c 100644--- a/packages/db/src/repositories/payment-session.repository.js+++ b/packages/db/src/repositories/payment-session.repository.js@@ -1,5 +1,5 @@import crypto from 'node:crypto';-import { PaymentStatus, PaymentMethod } from '@youpi/common';+import { PaymentStatus, PaymentMethod, isValidTransition, TERMINAL_STATES } from '@youpi/common';export class PaymentSessionRepository {/**@@ -100,6 +100,9 @@ export class PaymentSessionRepository {(activeRow.status === PaymentStatus.PROCESSING && activeRow.processing_expires_at && new Date(activeRow.processing_expires_at) <= now);if (isStale) {const terminalStatus = activeRow.status === PaymentStatus.PROCESSING ? PaymentStatus.FAILED : PaymentStatus.EXPIRED;+ if (!isValidTransition(activeRow.status, terminalStatus)) {+ throw new Error(`Illegal payment state transition: cannot move from '${activeRow.status}' to '${terminalStatus}'.`);+ }this.db.execute(`UPDATE payment_sessionsSET status = ?, completed_at = ?, updated_at = ?@@ -119,7 +122,14 @@ export class PaymentSessionRepository {}if (!activeRow) {- // Slot is vacant! Grant ACTIVE slot+ // Slot is vacant! Grant ACTIVE slot.+ // Enforce the transition graph: a terminal or PROCESSING session must never be+ // revived to ACTIVE by a concurrent queue tick.+ const currentStatus = this.findById(sessionId)?.status;+ if (currentStatus && !isValidTransition(currentStatus, PaymentStatus.ACTIVE)) {+ throw new Error(`Illegal payment state transition: cannot move from '${currentStatus}' to 'ACTIVE'.`);+ }+const expiresAt = new Date(now.getTime() + durationMs).toISOString();this.db.execute(`@@ -154,6 +164,10 @@ export class PaymentSessionRepository {queuePosition = posRow ? posRow.next_pos : 1;}+ if (existingSession && !isValidTransition(existingSession.status, PaymentStatus.QUEUED)) {+ throw new Error(`Illegal payment state transition: cannot move from '${existingSession.status}' to 'QUEUED'.`);+ }+this.db.execute(`UPDATE payment_sessionsSET status = ?, queue_position = ?, updated_at = ?@@ -222,6 +236,15 @@ export class PaymentSessionRepository {return session; // already terminal, idempotent}+ // The state machine is enforced here rather than merely documented: without this,+ // any caller could move a live session straight to SUCCESS and bypass verification.+ if (!TERMINAL_STATES.includes(targetStatus)) {+ throw new Error(`Not a terminal target status: ${targetStatus}`);+ }+ if (!isValidTransition(session.status, targetStatus)) {+ throw new Error(`Illegal payment state transition: cannot move from '${session.status}' to '${targetStatus}'.`);+ }+const now = new Date().toISOString();const attributedObsId = options.attributedObservationId || session.attributedObservationId || null;@@ -498,8 +521,12 @@ export class PaymentSessionRepository {}const shouldFinalize = options.finalizeSuccess !== false;- const isFirstSuccess = shouldFinalize && session.status !== PaymentStatus.SUCCESS && level >= 1;- const targetStatus = shouldFinalize && level >= 1 ? PaymentStatus.SUCCESS : session.status;+ const wantsSuccess = shouldFinalize && level >= 1;+ if (wantsSuccess && session.status !== PaymentStatus.SUCCESS && !isValidTransition(session.status, PaymentStatus.SUCCESS)) {+ throw new Error(`Illegal payment state transition: cannot move from '${session.status}' to 'SUCCESS'.`);+ }+ const isFirstSuccess = wantsSuccess && session.status !== PaymentStatus.SUCCESS;+ const targetStatus = wantsSuccess ? PaymentStatus.SUCCESS : session.status;const now = new Date().toISOString();this.db.execute(`diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex f543554..0243ce2 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -98,6 +98,12 @@ CREATE TABLE IF NOT EXISTS payment_sessions ();CREATE INDEX IF NOT EXISTS idx_payment_sessions_active ON payment_sessions (receiving_account_id, status);+-- Slot exclusivity is a database invariant, not an application convention: at most one+-- session per receiving account may occupy the slot (ACTIVE or PROCESSING) at any time.+-- Concurrent writers are rejected by the engine instead of relying on lock contention.+CREATE UNIQUE INDEX IF NOT EXISTS idx_one_slot_per_receiving_account+ ON payment_sessions (receiving_account_id)+ WHERE status IN ('ACTIVE', 'PROCESSING') AND receiving_account_id IS NOT NULL;-- 5. Payment Observations TableCREATE TABLE IF NOT EXISTS payment_observations (diff --git a/packages/merchant-sdk/src/client.js b/packages/merchant-sdk/src/client.jsindex 94c60f0..00811f1 100644--- a/packages/merchant-sdk/src/client.js+++ b/packages/merchant-sdk/src/client.js@@ -92,7 +92,15 @@ export class YoupiPaymentClient {*/async getPayment(paymentId) {const url = `${this.apiUrl}/api/v1/payments/${paymentId}`;- const res = await fetch(url);+ const headers = {};+ // 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;+ }++ const res = await fetch(url, { headers });if (!res.ok) {const err = await res.text();diff --git a/scripts/capture-all-assets.cjs b/scripts/capture-all-assets.cjsindex 1d09d34..67dba3b 100644--- a/scripts/capture-all-assets.cjs+++ b/scripts/capture-all-assets.cjs@@ -105,7 +105,7 @@ async function run() {height: 800,filename: 'gateway_pc_checkout.png',evalFn: () => {- activeCustomer = { id: 'demo-cust', name: 'Gaurav Sharma', mobileNumber: '9212339720' };+ activeCustomer = { id: 'demo-cust', name: 'Demo Customer', mobileNumber: '9000000000' };setGatewayAuthMode(false);hideAllContent();const upiContent = document.getElementById('viewUpiContent');@@ -132,7 +132,7 @@ async function run() {height: 880,filename: 'gateway_mobile_checkout.png',evalFn: () => {- activeCustomer = { id: 'demo-cust', name: 'Gaurav Sharma', mobileNumber: '9212339720' };+ activeCustomer = { id: 'demo-cust', name: 'Demo Customer', mobileNumber: '9000000000' };setGatewayAuthMode(false);hideAllContent();const upiContent = document.getElementById('viewUpiContent');diff --git a/scripts/test-single-user-and-pc-menu.cjs b/scripts/test-single-user-and-pc-menu.cjsindex a1c9614..b886140 100644--- a/scripts/test-single-user-and-pc-menu.cjs+++ b/scripts/test-single-user-and-pc-menu.cjs@@ -69,7 +69,7 @@ async function runTestSuite() {console.log('=== TEST 1: Check Initiated Session - Sign in to Pay with Single Saved Account ===');await evaluate(`localStorage.setItem('youpi.customer.accounts', JSON.stringify([- { id: '74879c31-ea68-427a-87a6-a02d08109afd', name: 'Gaurav Mehra', email: '[email protected]', mobileNumber: '9212339720' }+ { id: '74879c31-ea68-427a-87a6-a02d08109afd', name: 'Demo Customer', email: '[email protected]', mobileNumber: '9000000000' }]));renderSavedAccountsUI();`);@@ -98,10 +98,10 @@ async function runTestSuite() {await evaluate(`const cust = {id: '74879c31-ea68-427a-87a6-a02d08109afd',- name: 'Gaurav Mehra',- fullName: 'Gaurav Mehra',- email: '[email protected]',- mobileNumber: '9212339720'+ name: 'Demo Customer',+ fullName: 'Demo Customer',+ email: '[email protected]',+ mobileNumber: '9000000000'};const token = 'csess_d145cc98752c919be77306be94545332982b8bced1f0be5262d8ce97e798ac1d';savePreservedIdentity(cust, token);@@ -122,7 +122,7 @@ async function runTestSuite() {`);console.log('preGatewayAuthView hidden (auto-login bypassed):', authViewHidden, '(Expected: true)');console.log('paymentGatewayInterface visible:', paymentViewVisible, '(Expected: true)');- console.log('Left sidebar text:', pcSidebarText, '(Expected: Using as Gaurav Mehra (+91 9212339720))');+ console.log('Left sidebar text:', pcSidebarText, '(Expected: Using as Demo Customer (+91 9000000000))');const shot2 = await sendCommand('Page.captureScreenshot', { format: 'png' });fs.writeFileSync('test_initiated_session_auto_login.png', Buffer.from(shot2.data, 'base64'));@@ -142,7 +142,7 @@ async function runTestSuite() {document.getElementById('popoverCustomerNamePc')?.textContent;`);console.log('accountMenuPopoverPc visible:', popoverPcVisible, '(Expected: true)');- console.log('Popover user name text:', popoverPcName, '(Expected: Gaurav Mehra (9212339720))');+ console.log('Popover user name text:', popoverPcName, '(Expected: Demo Customer (9000000000))');const shot3 = await sendCommand('Page.captureScreenshot', { format: 'png' });fs.writeFileSync('test_initiated_session_popover.png', Buffer.from(shot3.data, 'base64'));diff --git a/scripts/test-support.js b/scripts/test-support.jsindex db049ac..d902883 100644--- a/scripts/test-support.js+++ b/scripts/test-support.js@@ -28,3 +28,12 @@ const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/api\/v1\/pollerexport function authHeadersFor(path, extra = {}) {return GUARDED.test(String(path)) ? authHeaders(extra) : { ...extra };}++/**+ * Merchant-scoped header proving ownership of a payment session. `GET /api/v1/payments/:id`+ * only returns merchant-private fields (metadata, verification internals, internalStatus)+ * to a caller presenting the owning merchant's webhook secret.+ */+export function merchantHeaders(webhookSecret, extra = {}) {+ return { 'X-Merchant-Key': webhookSecret, ...extra };+}