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): harden device binding, credential verification, and session lifecycle guards (closes #8)
Harshe865a0316df6
diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.htmlindex 905dcdf..b52a2c0 100644--- a/apps/checkout-portal/src/views/checkout.html+++ b/apps/checkout-portal/src/views/checkout.html@@ -1190,7 +1190,7 @@}, () => {const el = document.getElementById('codTimerText');if (el) el.textContent = 'Expired';- fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST' }).catch(() => { });+ fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST', headers: getApiHeaders() }).catch(() => { });loadState();});} else if (method === 'UPI') {@@ -1202,7 +1202,7 @@}, () => {const el = document.getElementById('activeTimerText');if (el) el.textContent = 'Expired';- fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST' }).catch(() => { });+ fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST', headers: getApiHeaders() }).catch(() => { });loadState();});} else if (resData.status === 'QUEUED') {@@ -1236,7 +1236,7 @@try {const res = await fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/confirm-cod`, {method: 'POST',- headers: { 'Content-Type': 'application/json' }+ headers: getApiHeaders({ 'Content-Type': 'application/json' })});const data = await res.json();if (res.ok) {@@ -2078,7 +2078,7 @@}, () => {const el = document.getElementById('codTimerText');if (el) el.textContent = 'Expired';- fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST' }).catch(() => { });+ fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST', headers: getApiHeaders() }).catch(() => { });loadState();}, data.expiresAt);} else if (currentSelectedMethod === 'CASH_COUNTER') {@@ -2129,7 +2129,7 @@if (tText) tText.textContent = 'Expired';if (btnContinue) btnContinue.style.display = 'none';closeProcessingModal();- fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST' }).catch(() => { });+ fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/expire`, { method: 'POST', headers: getApiHeaders() }).catch(() => { });loadState();}, targetExpiry);}@@ -2392,7 +2392,8 @@try {const res = await fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/payment-done`, {- method: 'POST'+ method: 'POST',+ headers: getApiHeaders()});if (res.ok) {loadState();@@ -2574,13 +2575,7 @@try {await DeviceIdentity.getOrRegister();- const headers = { 'Content-Type': 'application/json' };- if (DeviceIdentity.currentDeviceId) {- headers['X-Device-Id'] = DeviceIdentity.currentDeviceId;- }- if (DeviceIdentity.currentDeviceToken) {- headers['X-Device-Token'] = DeviceIdentity.currentDeviceToken;- }+ const headers = getApiHeaders({ 'Content-Type': 'application/json' });const conflictingSessionId = lastDuplicateSessionPayload?.conflicting_session_id || activeConflictSessionId || null;@@ -2589,6 +2584,7 @@headers,body: JSON.stringify({deviceId: DeviceIdentity.currentDeviceId,+ deviceToken: DeviceIdentity.currentDeviceToken,conflictingSessionId})});@@ -2621,8 +2617,11 @@}try {- const devQuery = DeviceIdentity.currentDeviceId ? `?deviceId=${encodeURIComponent(DeviceIdentity.currentDeviceId)}` : '';- const streamUrl = `${API_BASE}/api/v1/checkout/${PAYMENT_ID}/stream${devQuery}`;+ const params = new URLSearchParams();+ if (DeviceIdentity.currentDeviceId) params.set('deviceId', DeviceIdentity.currentDeviceId);+ if (DeviceIdentity.currentDeviceToken) params.set('deviceToken', DeviceIdentity.currentDeviceToken);+ const qs = params.toString();+ const streamUrl = `${API_BASE}/api/v1/checkout/${PAYMENT_ID}/stream${qs ? '?' + qs : ''}`;sse = new EventSource(streamUrl);const handleRealtimePayload = (event) => {diff --git a/apps/merchant-admin/src/server.js b/apps/merchant-admin/src/server.jsindex 08f1100..7b3405b 100644--- a/apps/merchant-admin/src/server.js+++ b/apps/merchant-admin/src/server.js@@ -162,9 +162,8 @@ export class AdminServer {path: req.url,method: req.method,headers: {- ...req.headers,+ ...sanitizedForwardHeaders(req, `localhost:${targetPort}`),'x-merchant-id': req.headers['x-merchant-id'] || defaultMerchantId,- host: `localhost:${targetPort}`,'x-forwarded-host': req.headers.host || '','x-forwarded-proto': req.headers['x-forwarded-proto'] || 'http'}diff --git a/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.js b/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.jsindex 36b4a55..30d9530 100644--- a/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.js+++ b/apps/payment-api/src/__tests__/device-binding-duplicate-session.test.js@@ -1,7 +1,8 @@import { test, describe, before, after } from 'node:test';import assert from 'node:assert/strict';import http from 'node:http';-import { Database, CustomerRepository, PaymentSessionRepository, MerchantRepository } from '@youpi/db';+import crypto from 'node:crypto';+import { Database, CustomerRepository, CustomerSessionRepository, PaymentSessionRepository, MerchantRepository } from '@youpi/db';import { startServer as startPaymentApi } from '../index.js';import { authHeadersFor } from '../../../../scripts/test-support.js';@@ -12,6 +13,8 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {let merchantRepo;let sessionRepo;let customerRepo;+ let customerSessionRepo;+ let dev1TokenShared;const merchantId = '00000000-0000-0000-0000-000000000001';const receivingAccountId = '00000000-0000-0000-0000-000000000002';@@ -20,6 +23,7 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {merchantRepo = new MerchantRepository(testDb);sessionRepo = new PaymentSessionRepository(testDb);customerRepo = new CustomerRepository(testDb);+ customerSessionRepo = new CustomerSessionRepository(testDb);apiInstance = await startPaymentApi(6201, testDb);baseUrl = `http://localhost:${apiInstance.port}`;@@ -109,6 +113,7 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {});const dev1Id = regRes1.body.deviceId;const dev1Token = regRes1.body.deviceToken;+ dev1TokenShared = dev1Token;// Device 1 accesses the checkout session stateconst stateRes1 = await request(`/api/v1/checkout/${sessionId}/state`, {@@ -132,16 +137,22 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {const sessionId = row.id;const dev1Id = row.device_id;- // Access again with device 1+ // Access again with device 1 and valid tokenconst res = await request(`/api/v1/checkout/${sessionId}/state`, {- headers: { 'x-device-id': dev1Id }+ headers: {+ 'x-device-id': dev1Id,+ 'x-device-token': dev1TokenShared+ }});assert.equal(res.status, 200);- // Select payment method with device 1+ // Select payment method with device 1 and valid tokenconst methodRes = await request(`/api/v1/checkout/${sessionId}/select-method`, {method: 'POST',- headers: { 'x-device-id': dev1Id },+ headers: {+ 'x-device-id': dev1Id,+ 'x-device-token': dev1TokenShared+ },body: { method: 'UPI' }});assert.equal(methodRes.status, 200);@@ -202,13 +213,25 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {const row = testDb.db.prepare('SELECT id, device_id FROM payment_sessions WHERE order_id = ?').get('ORDER_DEV_001');const oldSessionId = row.id;- const newDevId = 'dev_recovery_replacement_888';+ const regNew = await request('/api/v1/devices/register', {+ method: 'POST',+ body: {+ publicKey: 'dev-recovery-replacement-888-pubkey',+ signals: { userAgent: 'Recovery-Device-Agent' }+ }+ });+ assert.equal(regNew.status, 201);+ const newDevId = regNew.body.deviceId;+ const newDevToken = regNew.body.deviceToken;- // Call POST /api/v1/checkout/:id/end-and-restart-payment with new device+ // Call POST /api/v1/checkout/:id/end-and-restart-payment with registered new deviceconst restartRes = await request(`/api/v1/checkout/${oldSessionId}/end-and-restart-payment`, {method: 'POST',- headers: { 'x-device-id': newDevId },- body: { deviceId: newDevId }+ headers: {+ 'x-device-id': newDevId,+ 'x-device-token': newDevToken+ },+ body: { deviceId: newDevId, deviceToken: newDevToken }});assert.equal(restartRes.status, 201);@@ -230,20 +253,24 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// Verify new device can seamlessly load new session stateconst newStateRes = await request(`/api/v1/checkout/${restartRes.body.newSessionId}/state`, {- headers: { 'x-device-id': newDevId }+ headers: {+ 'x-device-id': newDevId,+ 'x-device-token': newDevToken+ }});assert.equal(newStateRes.status, 200);assert.equal(newStateRes.body.paymentId, restartRes.body.newSessionId);});test('7. If a customer binds to a session, another session for the same customer triggers active session conflict', async () => {- // Create customer+ // Create customer & session tokenconst cust = customerRepo.create({merchantId,name: 'Concurrent User',email: '[email protected]',mobileNumber: '+919999888877'});+ const custSess = customerSessionRepo.create({ customerId: cust.id });// Create session 1const s1Res = await request('/api/v1/payments', {@@ -261,8 +288,9 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// Bind customer to session 1const bind1Res = await request(`/api/v1/checkout/${s1Id}/bind-customer`, {method: 'POST',- body: { customerId: cust.id }+ body: { customerId: cust.id, token: custSess.token }});+ assert.equal(bind1Res.status, 200);// Create session 2 for same customerconst s2Res = await request('/api/v1/payments', {@@ -280,7 +308,7 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// Bind customer to session 2 -> conflict detected!const bind2Res = await request(`/api/v1/checkout/${s2Id}/bind-customer`, {method: 'POST',- body: { customerId: cust.id }+ body: { customerId: cust.id, token: custSess.token }});assert.equal(bind2Res.body.hasActiveSessionConflict, true);@@ -293,31 +321,36 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {testDb.execute("UPDATE payment_sessions SET status = 'CANCELLED' WHERE status IN ('ACTIVE', 'PROCESSING', 'QUEUED')");testDb.execute("UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL");- const devLaptopId = 'dev_laptop_prompt64_alpha';- const devMobileId = 'dev_mobile_prompt64_beta';-// 1. Register devices- await request('/api/v1/devices/register', {+ const regLaptop = await request('/api/v1/devices/register', {method: 'POST',body: { publicKey: 'key_laptop_p64', signals: { userAgent: 'Laptop Chrome' } }});- await request('/api/v1/devices/register', {+ const regMobile = await request('/api/v1/devices/register', {method: 'POST',body: { publicKey: 'key_mobile_p64', signals: { userAgent: 'Mobile Safari' } }});+ const devLaptopId = regLaptop.body.deviceId;+ const devLaptopToken = regLaptop.body.deviceToken;+ const devMobileId = regMobile.body.deviceId;+ const devMobileToken = regMobile.body.deviceToken;- // 2. Create customer+ // 2. Create customer & session tokenconst custP64 = customerRepo.create({merchantId,name: 'Mohit Laptop User',email: '[email protected]',mobileNumber: '+918796266491'});+ const custP64Sess = customerSessionRepo.create({ customerId: custP64.id });// 3. Create Session A with autoActivate: trueconst createRes = await request('/api/v1/payments', {method: 'POST',- headers: { 'x-device-id': devLaptopId },+ headers: {+ 'x-device-id': devLaptopId,+ 'x-device-token': devLaptopToken+ },body: {orderId: 'ORDER_P64_ALPHA',amount: 499.00,@@ -335,8 +368,11 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// Bind Session A to Laptop deviceconst bindResA = await request(`/api/v1/checkout/${sessionAId}/bind-customer`, {method: 'POST',- headers: { 'x-device-id': devLaptopId },- body: { customerId: custP64.id }+ headers: {+ 'x-device-id': devLaptopId,+ 'x-device-token': devLaptopToken+ },+ body: { customerId: custP64.id, token: custP64Sess.token }});assert.equal(bindResA.status, 200);@@ -352,7 +388,10 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 4. Device B attempts to access Session A -> triggers DUPLICATE_SESSION_DETECTED (HTTP 409)const accessResB = await request(`/api/v1/checkout/${sessionAId}/state`, {- headers: { 'x-device-id': devMobileId }+ headers: {+ 'x-device-id': devMobileId,+ 'x-device-token': devMobileToken+ }});assert.equal(accessResB.status, 409);assert.equal(accessResB.body.error, 'DUPLICATE_SESSION_DETECTED');@@ -362,9 +401,13 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 5. Device B chooses "End Session & Start New Payment"const restartRes = await request(`/api/v1/checkout/${sessionAId}/end-and-restart-payment`, {method: 'POST',- headers: { 'x-device-id': devMobileId },+ headers: {+ 'x-device-id': devMobileId,+ 'x-device-token': devMobileToken+ },body: {deviceId: devMobileId,+ deviceToken: devMobileToken,conflictingSessionId: sessionAId}});@@ -398,7 +441,10 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 7. Device B loads state for new session seamlesslyconst stateB = await request(`/api/v1/checkout/${restartRes.body.newSessionId}/state`, {- headers: { 'x-device-id': devMobileId }+ headers: {+ 'x-device-id': devMobileId,+ 'x-device-token': devMobileToken+ }});assert.equal(stateB.status, 200);assert.equal(stateB.body.status, 'ACTIVE');@@ -411,14 +457,33 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {testDb.execute("UPDATE payment_sessions SET status = 'CANCELLED' WHERE status IN ('ACTIVE', 'PROCESSING', 'QUEUED')");testDb.execute("UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL");- const devLId = 'dev_laptop_p64_q9';- const devMId = 'dev_mobile_p64_q9';- const devCId = 'dev_other_customer_q9';+ const regL = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_laptop_p64_q9', signals: { userAgent: 'Laptop Q9' } }+ });+ const regM = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_mobile_p64_q9', signals: { userAgent: 'Mobile Q9' } }+ });+ const regC = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_other_customer_q9', signals: { userAgent: 'Customer C Q9' } }+ });++ const devLId = regL.body.deviceId;+ const devLToken = regL.body.deviceToken;+ const devMId = regM.body.deviceId;+ const devMToken = regM.body.deviceToken;+ const devCId = regC.body.deviceId;+ const devCToken = regC.body.deviceToken;// 1. Create active Session A on devLIdconst sARes = await request('/api/v1/payments', {method: 'POST',- headers: { 'x-device-id': devLId },+ headers: {+ 'x-device-id': devLId,+ 'x-device-token': devLToken+ },body: {orderId: 'ORDER_P64_Q9_A',amount: 500.00,@@ -437,7 +502,10 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 2. Customer C arrives concurrently and gets queuedconst sCRes = await request('/api/v1/payments', {method: 'POST',- headers: { 'x-device-id': devCId },+ headers: {+ 'x-device-id': devCId,+ 'x-device-token': devCToken+ },body: {orderId: 'ORDER_P64_Q9_C',amount: 300.00,@@ -455,9 +523,13 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 3. User A moves from Laptop (devLId) to Mobile (devMId) and ends Session Aconst restartRes = await request(`/api/v1/checkout/${sAId}/end-and-restart-payment`, {method: 'POST',- headers: { 'x-device-id': devMId },+ headers: {+ 'x-device-id': devMId,+ 'x-device-token': devMToken+ },body: {deviceId: devMId,+ deviceToken: devMToken,conflictingSessionId: sAId}});@@ -493,13 +565,26 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {testDb.execute("UPDATE payment_sessions SET status = 'CANCELLED' WHERE status IN ('ACTIVE', 'PROCESSING', 'QUEUED')");testDb.execute("UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL");- const devA = 'dev_admin_sync_A';- const devB = 'dev_admin_sync_B';+ const regA = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_admin_sync_A', signals: { userAgent: 'Admin Sync A' } }+ });+ const regB = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_admin_sync_B', signals: { userAgent: 'Admin Sync B' } }+ });+ const devA = regA.body.deviceId;+ const devAToken = regA.body.deviceToken;+ const devB = regB.body.deviceId;+ const devBToken = regB.body.deviceToken;// 1. Create session from scratchconst createRes = await request('/api/v1/payments', {method: 'POST',- headers: { 'x-device-id': devA },+ headers: {+ 'x-device-id': devA,+ 'x-device-token': devAToken+ },body: {orderId: 'ORDER_ADMIN_SYNC_001',amount: 750.00,@@ -518,7 +603,10 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 2. Duplicate session detected on Device Bconst conflictRes = await request(`/api/v1/checkout/${session1Id}/state`, {- headers: { 'x-device-id': devB }+ headers: {+ 'x-device-id': devB,+ 'x-device-token': devBToken+ }});assert.equal(conflictRes.status, 409);assert.equal(conflictRes.body.error, 'DUPLICATE_SESSION_DETECTED');@@ -526,9 +614,13 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {// 3. Device B clicks "End Session & Start New Payment"const restartRes = await request(`/api/v1/checkout/${session1Id}/end-and-restart-payment`, {method: 'POST',- headers: { 'x-device-id': devB },+ headers: {+ 'x-device-id': devB,+ 'x-device-token': devBToken+ },body: {deviceId: devB,+ deviceToken: devBToken,conflictingSessionId: session1Id}});@@ -546,4 +638,264 @@ describe('YOUPI PG: Device Binding & Duplicate Session Detection', () => {assert.equal(qRes2.body.currentSlot.orderId, restartRes.body.orderId, 'Admin queue must show new session order ID');assert.ok(qRes2.body.currentSlot.expiresAt, 'Admin queue must have active timer expiresAt');});++ test('11. Issue #8 Security: Device binding cannot be bypassed by omitting X-Device-Id, X-Device-Token, or sending unregistered device IDs', async () => {+ const reg = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_issue8_bound_dev', signals: { userAgent: 'Issue8 Bound Agent' } }+ });+ const boundId = reg.body.deviceId;+ const boundToken = reg.body.deviceToken;++ // 1. Unregistered deviceId in POST /api/v1/payments is rejected (no adhoc_ auto-creation)+ const spoofPay = await request('/api/v1/payments', {+ method: 'POST',+ headers: { 'x-device-id': 'dev_unregistered_spoof_123' },+ body: { orderId: 'ORDER_ISSUE8_SPOOF', amount: 100.00 }+ });+ assert.equal(spoofPay.status, 401);+ const adhocRow = testDb.db.prepare('SELECT id FROM devices WHERE id = ?').get('dev_unregistered_spoof_123');+ assert.equal(adhocRow, undefined, 'Must not auto-create adhoc_ device row');++ // 2. Registered deviceId without deviceToken in POST /api/v1/payments is rejected+ const missingTokenPay = await request('/api/v1/payments', {+ method: 'POST',+ headers: { 'x-device-id': boundId },+ body: { orderId: 'ORDER_ISSUE8_NOTOK', amount: 100.00 }+ });+ assert.equal(missingTokenPay.status, 401);++ // 3. Create valid device-bound session+ const validPay = await request('/api/v1/payments', {+ method: 'POST',+ headers: { 'x-device-id': boundId, 'x-device-token': boundToken },+ body: { orderId: 'ORDER_ISSUE8_BOUND_1', amount: 299.00, autoActivate: true }+ });+ assert.equal(validPay.status, 201);+ const sid = validPay.body.paymentId;++ // 4. Omitting X-Device-Id on a device-bound session is rejected with 409 DUPLICATE_SESSION_DETECTED+ const omitIdState = await request(`/api/v1/checkout/${sid}/state`);+ assert.equal(omitIdState.status, 409);+ assert.equal(omitIdState.body.error, 'DUPLICATE_SESSION_DETECTED');++ // 5. Sending X-Device-Id without X-Device-Token on a device-bound session is rejected with 409+ const omitTokenState = await request(`/api/v1/checkout/${sid}/state`, {+ headers: { 'x-device-id': boundId }+ });+ assert.equal(omitTokenState.status, 409);+ assert.equal(omitTokenState.body.error, 'DUPLICATE_SESSION_DETECTED');++ // 6. Spoofing X-Internal-Render: true without internal token is rejected with 409+ const spoofInternal = await request(`/api/v1/checkout/${sid}/state`, {+ headers: { 'x-internal-render': 'true' }+ });+ assert.equal(spoofInternal.status, 409);+ assert.equal(spoofInternal.body.error, 'DUPLICATE_SESSION_DETECTED');++ // 7. Re-calling POST /api/v1/payments for the same order while omitting deviceId is rejected with 409+ const omitIdReCreate = await request('/api/v1/payments', {+ method: 'POST',+ body: { orderId: 'ORDER_ISSUE8_BOUND_1', amount: 299.00 }+ });+ assert.equal(omitIdReCreate.status, 409);+ assert.equal(omitIdReCreate.body.error, 'DUPLICATE_SESSION_DETECTED');+ });++ test('12. Issue #8 Security: /devices/register does not leak deviceToken for existing publicKey without signed challenge, and /devices/verify requires valid credentials and nonce+timestamp signatures', async () => {+ // Generate real ECDSA P-256 keypair+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', {+ namedCurve: 'prime256v1'+ });+ const publicKeySpkiBase64 = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');++ // 1. Initial registration succeeds and returns deviceToken+ const reg1 = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: publicKeySpkiBase64, signals: { userAgent: 'ECDSA-Agent' } }+ });+ assert.equal(reg1.status, 201);+ const deviceId = reg1.body.deviceId;+ const token1 = reg1.body.deviceToken;+ assert.ok(token1);++ // 2. Re-registering the same publicKey without a signed challenge returns 409 and NO deviceToken+ const regDup = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: publicKeySpkiBase64, signals: { userAgent: 'Attacker-Replay' } }+ });+ assert.equal(regDup.status, 409);+ assert.equal(regDup.body.error, 'DEVICE_ALREADY_REGISTERED');+ assert.equal(regDup.body.deviceToken, undefined);+ assert.ok(regDup.body.challenge);++ // 3. Signing the challenge with the ECDSA private key rotates and returns a new deviceToken+ const challengePayload = JSON.stringify({+ deviceId,+ challenge: regDup.body.challenge,+ nonce: crypto.randomBytes(12).toString('hex'),+ timestamp: Date.now()+ });+ const challengeSig = crypto.sign('SHA256', Buffer.from(challengePayload, 'utf8'), {+ key: privateKey,+ dsaEncoding: 'ieee-p1363'+ }).toString('base64');++ const regRotated = await request('/api/v1/devices/register', {+ method: 'POST',+ body: {+ publicKey: publicKeySpkiBase64,+ challenge: regDup.body.challenge,+ payload: challengePayload,+ signature: challengeSig+ }+ });+ assert.equal(regRotated.status, 200);+ assert.ok(regRotated.body.deviceToken);+ assert.notEqual(regRotated.body.deviceToken, token1);+ const activeToken = regRotated.body.deviceToken;++ // 4. /devices/verify with no credential returns 401 { valid: false }+ const verifyEmpty = await request('/api/v1/devices/verify', {+ method: 'POST',+ body: { deviceId }+ });+ assert.equal(verifyEmpty.status, 401);+ assert.equal(verifyEmpty.body.valid, false);++ // 5. /devices/verify with old rotated token fails (401) and with new active token succeeds (200)+ const verifyOld = await request('/api/v1/devices/verify', {+ method: 'POST',+ body: { deviceId, deviceToken: token1 }+ });+ assert.equal(verifyOld.status, 401);+ assert.equal(verifyOld.body.valid, false);++ const verifyNew = await request('/api/v1/devices/verify', {+ method: 'POST',+ body: { deviceId, deviceToken: activeToken }+ });+ assert.equal(verifyNew.status, 200);+ assert.equal(verifyNew.body.valid, true);++ // 6. /devices/verify with signature lacking nonce/timestamp is rejected (401)+ const staticPayload = 'static-message-without-nonce-or-timestamp';+ const staticSig = crypto.sign('SHA256', Buffer.from(staticPayload, 'utf8'), {+ key: privateKey,+ dsaEncoding: 'ieee-p1363'+ }).toString('base64');+ const verifyStatic = await request('/api/v1/devices/verify', {+ method: 'POST',+ body: { deviceId, payload: staticPayload, signature: staticSig }+ });+ assert.equal(verifyStatic.status, 401);+ assert.equal(verifyStatic.body.valid, false);++ // 7. /devices/verify with fresh nonce + timestamp succeeds once, and replay of same nonce is rejected+ const freshPayload = JSON.stringify({+ deviceId,+ nonce: crypto.randomBytes(12).toString('hex'),+ timestamp: Date.now()+ });+ const freshSig = crypto.sign('SHA256', Buffer.from(freshPayload, 'utf8'), {+ key: privateKey,+ dsaEncoding: 'ieee-p1363'+ }).toString('base64');++ const verifySig1 = await request('/api/v1/devices/verify', {+ method: 'POST',+ body: { deviceId, payload: freshPayload, signature: freshSig }+ });+ assert.equal(verifySig1.status, 200);+ assert.equal(verifySig1.body.valid, true);++ const verifySigReplay = await request('/api/v1/devices/verify', {+ method: 'POST',+ body: { deviceId, payload: freshPayload, signature: freshSig }+ });+ assert.equal(verifySigReplay.status, 401);+ assert.equal(verifySigReplay.body.valid, false);+ });++ test('13. Issue #8 Security: bind-customer rejects bare customerId, and cancel / retry / end-and-restart reject PROCESSING sessions and unauthenticated body.customerId', async () => {+ testDb.execute("UPDATE payment_sessions SET status = 'CANCELLED' WHERE status IN ('ACTIVE', 'PROCESSING', 'QUEUED')");+ testDb.execute("UPDATE payment_receiving_accounts SET is_slot_busy = 0, current_active_session_id = NULL");++ const regDev = await request('/api/v1/devices/register', {+ method: 'POST',+ body: { publicKey: 'key_issue8_proc_guard', signals: { userAgent: 'ProcGuard Agent' } }+ });+ const devId = regDev.body.deviceId;+ const devToken = regDev.body.deviceToken;++ const cust = customerRepo.create({+ merchantId,+ name: 'Protected Customer',+ email: '[email protected]',+ mobileNumber: '+919777666555'+ });++ const payRes = await request('/api/v1/payments', {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken },+ body: { orderId: 'ORDER_ISSUE8_PROC_1', amount: 199.00, autoActivate: true }+ });+ assert.equal(payRes.status, 201);+ const sid = payRes.body.paymentId;++ // 1. bind-customer with bare customerId (no session token) is rejected with 401+ const bareBind = await request(`/api/v1/checkout/${sid}/bind-customer`, {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken },+ body: { customerId: cust.id }+ });+ assert.equal(bareBind.status, 401);++ // 2. Transition session to PROCESSING via payment-done+ const doneRes = await request(`/api/v1/checkout/${sid}/payment-done`, {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken }+ });+ assert.equal(doneRes.status, 200);+ assert.equal(doneRes.body.status, 'PROCESSING');++ // 3. cancel on PROCESSING session is rejected with 409 SESSION_PROCESSING+ const cancelRes = await request(`/api/v1/checkout/${sid}/cancel`, {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken }+ });+ assert.equal(cancelRes.status, 409);+ assert.equal(cancelRes.body.error, 'SESSION_PROCESSING');++ // 4. retry-new-payment on PROCESSING session is rejected with 409 SESSION_PROCESSING+ const retryRes = await request(`/api/v1/checkout/${sid}/retry-new-payment`, {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken }+ });+ assert.equal(retryRes.status, 409);+ assert.equal(retryRes.body.error, 'SESSION_PROCESSING');++ // 5. end-and-restart-payment on PROCESSING session is rejected with 409 SESSION_PROCESSING+ const restartProc = await request(`/api/v1/checkout/${sid}/end-and-restart-payment`, {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken },+ body: { deviceId: devId, deviceToken: devToken }+ });+ assert.equal(restartProc.status, 409);+ assert.equal(restartProc.body.error, 'SESSION_PROCESSING');++ // Verify session is still in PROCESSING in DB+ const dbRow = testDb.db.prepare('SELECT status FROM payment_sessions WHERE id = ?').get(sid);+ assert.equal(dbRow.status, 'PROCESSING');++ // 6. end-and-restart-payment with bare customerId in body (no customer token) is rejected with 401+ testDb.execute("UPDATE payment_sessions SET status = 'ACTIVE' WHERE id = ?", [sid]);+ const restartBareCust = await request(`/api/v1/checkout/${sid}/end-and-restart-payment`, {+ method: 'POST',+ headers: { 'x-device-id': devId, 'x-device-token': devToken },+ body: { deviceId: devId, deviceToken: devToken, customerId: cust.id }+ });+ assert.equal(restartBareCust.status, 401);+ assert.equal(restartBareCust.body.error, 'CUSTOMER_AUTH_REQUIRED');+ });});diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 9b252d5..472d5e5 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -349,7 +349,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {// 3. Bind customer to payment sessionconst bindRes = await request(`/api/v1/checkout/${paymentId}/bind-customer`, {method: 'POST',- body: { customerId }+ body: { customerId, token: regRes.body.token }});assert.equal(bindRes.status, 200);assert.equal(bindRes.body.success, true);@@ -426,7 +426,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {// 4. User logs in and binds customer to payment sessionconst bindRes = await request(`/api/v1/checkout/${paymentId}/bind-customer`, {method: 'POST',- body: { customerId }+ body: { customerId, token: regRes.body.token }});assert.equal(bindRes.status, 200);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 a2263eb..433a01d 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@@ -366,7 +366,7 @@ describe('Architectural Update: Selling Modes (Online vs Offline), COD Flow, & Cawait request(`/api/v1/checkout/${paymentId}/bind-customer`, {method: 'POST',- body: { customerId: reg.body.customerId }+ body: { customerId: reg.body.customerId, token: customerToken }});// 1. Anonymous callers learn nothing about the customer.diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex ab65b87..edce3f5 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -1,21 +1,21 @@import { HttpServer } from '../server.js';import { toRupeesString, buildUpiUri, PaymentStatus, PaymentMethod, UPI_PROVIDERS, isInternalServiceRequest, isValidTransition } from '@youpi/common';-import { validateSessionDeviceAccess } from '@youpi/core';+import { validateSessionDeviceAccess, verifyRegisteredDeviceCredentials } from '@youpi/core';import { isPaymentOwner } from '../auth-guard.js';/*** Validates device access to an active payment session.* Enforces:- * 1. If session has no device binding yet, binds to requesting device if provided.- * 2. If session is bound to Device A, Device B receives DUPLICATE_SESSION_DETECTED (HTTP 409).+ * 1. If session has no device binding yet, binds to requesting device only if it is registered and presents valid credentials.+ * 2. If session is bound to Device A, any request omitting Device A's credentials or presenting Device B receives DUPLICATE_SESSION_DETECTED (HTTP 409).*/function checkSessionDeviceAccess(session, req, body = null, ctx = null) {// If session is already in a terminal state, allow access so terminal status can be rendered- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {+ if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED, PaymentStatus.SUSPICIOUS].includes(session.status)) {return { allowed: true, boundDeviceId: session.deviceId, isTerminal: true };}- // Only a co-located service holding the shared internal token may bypass device blocking.+ // Only a co-located service on loopback holding the shared internal token may bypass device blocking.// The `X-Internal-Render` flag on its own is attacker-controlled and proves nothing.if (isInternalServiceRequest(req)) {return { allowed: true, boundDeviceId: session.deviceId };@@ -25,23 +25,45 @@ function checkSessionDeviceAccess(session, req, body = null, ctx = null) {body?.deviceId ||(req.query && req.query.deviceId) ||null;+ const deviceToken = req.headers['x-device-token'] ||+ body?.deviceToken ||+ (req.query && req.query.deviceToken) ||+ null;+ const deviceSignature = req.headers['x-device-signature'] ||+ body?.deviceSignature ||+ null;+ const signaturePayload = req.headers['x-device-payload'] ||+ body?.signaturePayload ||+ null;// If session does not have a device binding yet:if (!session.deviceId) {if (requestingDeviceId) {+ const credCheck = verifyRegisteredDeviceCredentials({+ deviceId: requestingDeviceId,+ deviceToken,+ deviceSignature,+ signaturePayload,+ deviceRepo: ctx?.deviceRepo+ });+ if (!credCheck.valid) {+ return {+ allowed: false,+ statusCode: 409,+ body: {+ error: credCheck.error === 'DEVICE_SIGNATURE_INVALID' ? 'DEVICE_SIGNATURE_INVALID' : 'DUPLICATE_SESSION_DETECTED',+ code: credCheck.error,+ session_id: session.id,+ conflicting_session_id: session.id,+ action: 'END_SESSION_AND_CREATE_NEW',+ message: credCheck.message || 'Unregistered or unverified device identity.',+ boundDeviceId: null,+ requestingDeviceId+ }+ };+ }if (ctx?.deviceRepo) {- let dev = ctx.deviceRepo.findById(requestingDeviceId);- if (!dev) {- try {- ctx.deviceRepo.create({- id: requestingDeviceId,- publicKey: `adhoc_${requestingDeviceId}`,- fingerprintHash: `fp_${requestingDeviceId}`- });- } catch {}- } else {- ctx.deviceRepo.touch(requestingDeviceId);- }+ ctx.deviceRepo.touch(requestingDeviceId);}if (ctx?.sessionRepo) {try {@@ -55,29 +77,32 @@ function checkSessionDeviceAccess(session, req, body = null, ctx = null) {return { allowed: true, boundDeviceId: session.deviceId };}- // If session HAS a bound device:- // Allow if requesting device matches bound device OR if requesting device is omitted on same session- if (!requestingDeviceId || requestingDeviceId === session.deviceId) {- if (requestingDeviceId && ctx?.deviceRepo) {- ctx.deviceRepo.touch(requestingDeviceId);- }- return { allowed: true, boundDeviceId: session.deviceId };+ // Session HAS a bound device:+ // Require matching deviceId AND valid cryptographic credential (token or signature).+ const validation = validateSessionDeviceAccess({+ session,+ requestingDeviceId,+ deviceToken,+ deviceSignature,+ signaturePayload,+ deviceRepo: ctx?.deviceRepo+ });++ if (!validation.allowed) {+ return {+ allowed: false,+ statusCode: 409,+ body: {+ ...validation,+ conflicting_session_id: session.id+ }+ };}- // Device mismatch: only reject if an explicitly DIFFERENT device ID was provided!- return {- allowed: false,- statusCode: 409,- body: {- error: 'DUPLICATE_SESSION_DETECTED',- session_id: session.id,- conflicting_session_id: session.id,- action: 'END_SESSION_AND_CREATE_NEW',- message: 'This payment session was created on another device. For security reasons, this session cannot be continued from this device.',- boundDeviceId: session.deviceId,- requestingDeviceId- }- };+ if (ctx?.deviceRepo) {+ ctx.deviceRepo.touch(session.deviceId);+ }+ return { allowed: true, boundDeviceId: session.deviceId };}/**@@ -552,19 +577,19 @@ export function registerCheckoutRoutes(server, ctx) {const publicMetadata = isOwnerCaller ? (session.metadata || {}) : {};// Single active payment session check (Section 1 & 2)- const requestingDeviceId = req.headers['x-device-id'] || session.deviceId || null;+ const requestingDeviceId = req.headers['x-device-id'] || null;let hasActiveSessionConflict = false;let conflictingSession = null;const conflictingActive = ctx.sessionRepo.findConflictingActiveSession? ctx.sessionRepo.findConflictingActiveSession({customerId: session.customerId,- deviceId: requestingDeviceId,+ deviceId: requestingDeviceId || session.deviceId || null,excludeSessionId: session.id}): null;if (conflictingActive && conflictingActive.id !== session.id && [PaymentStatus.INITIATED, PaymentStatus.ACTIVE, PaymentStatus.QUEUED].includes(session.status)) {- if (requestingDeviceId && conflictingActive.deviceId && requestingDeviceId !== conflictingActive.deviceId) {+ if (conflictingActive.deviceId && (!requestingDeviceId || requestingDeviceId !== conflictingActive.deviceId)) {// CASE 3: Active session on another device -> DUPLICATE_SESSION_DETECTEDHttpServer.json(res, 409, {error: 'DUPLICATE_SESSION_DETECTED',@@ -662,29 +687,42 @@ export function registerCheckoutRoutes(server, ctx) {// POST /api/v1/checkout/:id/bind-customerserver.post('/api/v1/checkout/:id/bind-customer', async (req, res, params) => {const body = await HttpServer.parseBody(req);- const token = body.token || body.sessionToken || ((req.headers['authorization'] || '').startsWith('Bearer ') ? req.headers['authorization'].slice(7).trim() : null);+ const token = body.token ||+ body.sessionToken ||+ req.headers['x-customer-token'] ||+ ((req.headers['authorization'] || '').startsWith('Bearer ') ? req.headers['authorization'].slice(7).trim() : null);const { customerId } = body;- let customer = null;- if (token && ctx.customerSessionRepo) {- const authContext = ctx.customerSessionRepo.findByToken(token);- if (!authContext) {- HttpServer.json(res, 401, { error: 'Invalid or expired customer session token.' });- return;- }- customer = authContext.customer;- } else if (customerId && ctx.customerRepo) {- customer = ctx.customerRepo.findById(customerId);+ const session = ctx.sessionRepo.findById(params.id);+ if (!session) {+ HttpServer.json(res, 404, { error: `Payment session not found: ${params.id}` });+ return;}- if (!customer) {- HttpServer.json(res, 400, { error: 'A valid customer session token or customerId is required.' });+ // INVARIANT: Payment session identity is IMMUTABLE once bound!+ // Cannot mutate or hijack an active session to another customer identity.+ if (session.customerId && customerId && session.customerId !== customerId) {+ HttpServer.json(res, 409, {+ error: 'Payment session is already bound to another customer identity and cannot be mutated or reassigned.'+ });return;}- const session = ctx.sessionRepo.findById(params.id);- if (!session) {- HttpServer.json(res, 404, { error: `Payment session not found: ${params.id}` });+ // Require a valid customer session token; never accept a bare client-asserted customerId!+ if (!token || typeof token !== 'string' || !ctx.customerSessionRepo) {+ HttpServer.json(res, 401, { error: 'A valid customer session token is required to bind a customer identity.' });+ return;+ }++ const authContext = ctx.customerSessionRepo.findByToken(token.trim());+ if (!authContext || !authContext.customer) {+ HttpServer.json(res, 401, { error: 'Invalid or expired customer session token.' });+ return;+ }++ const customer = authContext.customer;+ if (customerId && customerId !== customer.id) {+ HttpServer.json(res, 401, { error: 'Customer ID does not match authenticated session token.' });return;}@@ -698,8 +736,6 @@ export function registerCheckoutRoutes(server, ctx) {try { ctx.deviceRepo.associateCustomer(deviceAccess.boundDeviceId, customer.id); } catch {}}- // INVARIANT: Payment session identity is IMMUTABLE once bound!- // Cannot mutate or hijack an active session to another customer identity.if (session.customerId && session.customerId !== customer.id) {HttpServer.json(res, 409, {error: 'Payment session is already bound to another customer identity and cannot be mutated or reassigned.'@@ -756,8 +792,8 @@ export function registerCheckoutRoutes(server, ctx) {// INVARIANT: Single Active Payment Session per Customerif (otherActive && otherActive.id !== params.id) {- const requestingDeviceId = req.headers['x-device-id'] || null;- if (requestingDeviceId && otherActive.deviceId && requestingDeviceId !== otherActive.deviceId) {+ const requestingDeviceId = req.headers['x-device-id'] || body?.deviceId || null;+ if (otherActive.deviceId && (!requestingDeviceId || requestingDeviceId !== otherActive.deviceId)) {// CASE 3: Active session on another device -> DUPLICATE_SESSION_DETECTEDHttpServer.json(res, 409, {error: 'DUPLICATE_SESSION_DETECTED',@@ -847,6 +883,14 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ if (session.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Cannot retry payment while session is in PROCESSING status.'+ });+ return;+ }+if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {HttpServer.json(res, 400, { error: `Cannot retry payment for terminal session in status '${session.status}'` });return;@@ -855,10 +899,27 @@ export function registerCheckoutRoutes(server, ctx) {const customerId = session.customerId;const requestingDeviceId = req.headers['x-device-id'] || session.deviceId || null;- // Find all conflicting active/processing/queued sessions for this customer OR device+ // Never cancel a session that is in PROCESSING (in-flight bank verification).+ const processingConflict = ctx.db.query(`+ SELECT id FROM payment_sessions+ WHERE id != ? AND status = 'PROCESSING'+ AND (+ (? IS NOT NULL AND customer_id = ?)+ OR (? IS NOT NULL AND device_id = ?)+ )+ `, [session.id, customerId, customerId, requestingDeviceId, requestingDeviceId]);+ if (processingConflict.length > 0) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Another payment session for this customer or device is currently in bank verification (PROCESSING) and cannot be cancelled.'+ });+ return;+ }++ // Find all conflicting active/queued sessions for this customer OR deviceconst conflicting = ctx.db.query(`SELECT id, receiving_account_id, status FROM payment_sessions- WHERE id != ? AND status IN ('ACTIVE', 'PROCESSING', 'QUEUED')+ WHERE id != ? AND status IN ('ACTIVE', 'QUEUED')AND ((? IS NOT NULL AND customer_id = ?)OR (? IS NOT NULL AND device_id = ?)@@ -1005,6 +1066,14 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ if (session.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Cannot cancel a payment session while bank verification is in progress (PROCESSING).'+ });+ return;+ }+// Cancelling releases the merchant's scarce UPI slot and ends a live payment, so it is// subject to the same device-binding check as the other state-changing checkout actions.// Without this, anyone holding a payment id could grief an in-flight checkout.@@ -1575,13 +1644,12 @@ export function registerCheckoutRoutes(server, ctx) {}const sourceSession = (conflictingSessionId ? ctx.sessionRepo.findById(conflictingSessionId) : null) || targetSession;- const customerId = body?.customerId || sourceSession?.customerId || targetSession.customerId || null;// A settled order must not be restarted. The restarted session deliberately reuses the// merchant's order reference, and the unique (merchant_id, order_id) index rejects a// second row for an order that already succeeded — which surfaced as a 500. Refuse with a// clear conflict instead of attempting the duplicate.- const paidSession = [sourceSession, targetSession].find(s => s && s.status === PaymentStatus.SUCCESS);+ const paidSession = [sourceSession, targetSession, session].find(s => s && s.status === PaymentStatus.SUCCESS);if (paidSession) {HttpServer.json(res, 409, {error: 'ORDER_ALREADY_PAID',@@ -1592,16 +1660,89 @@ export function registerCheckoutRoutes(server, ctx) {return;}- // 1. Identify ALL sessions on old/other devices that must be cancelled+ const processingSession = [sourceSession, targetSession, session].find(s => s && s.status === PaymentStatus.PROCESSING);+ if (processingSession) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Cannot terminate or restart a payment session while bank verification is in progress (PROCESSING).',+ sessionId: processingSession.id,+ status: PaymentStatus.PROCESSING+ });+ return;+ }++ const newDeviceToken = req.headers['x-device-token'] || body?.deviceToken || null;+ const newDeviceSignature = req.headers['x-device-signature'] || body?.deviceSignature || null;+ const newSignaturePayload = req.headers['x-device-payload'] || body?.signaturePayload || null;++ const credCheck = verifyRegisteredDeviceCredentials({+ deviceId: newDeviceId,+ deviceToken: newDeviceToken,+ deviceSignature: newDeviceSignature,+ signaturePayload: newSignaturePayload,+ deviceRepo: ctx.deviceRepo+ });+ if (!credCheck.valid) {+ HttpServer.json(res, 401, {+ error: credCheck.error || 'DEVICE_CREDENTIALS_INVALID',+ message: credCheck.message || 'A registered device and valid device credential are required.'+ });+ return;+ }++ // Never accept an unverified customerId from the request body!+ const rawCustToken = body?.token ||+ body?.sessionToken ||+ req.headers['x-customer-token'] ||+ ((req.headers['authorization'] || '').startsWith('Bearer ') ? req.headers['authorization'].slice(7).trim() : null);+ const authCtx = (rawCustToken && ctx.customerSessionRepo)+ ? ctx.customerSessionRepo.findByToken(String(rawCustToken).trim())+ : null;+ const authenticatedCustomerId = authCtx?.customer?.id || null;++ if (body?.customerId && (!authenticatedCustomerId || body.customerId !== authenticatedCustomerId)) {+ HttpServer.json(res, 401, {+ error: 'CUSTOMER_AUTH_REQUIRED',+ message: 'Customer identity cannot be supplied in the request body without a matching valid customer session token.'+ });+ return;+ }++ if (authenticatedCustomerId && sourceSession?.customerId && sourceSession.customerId !== authenticatedCustomerId) {+ HttpServer.json(res, 403, {+ error: 'CUSTOMER_MISMATCH',+ message: 'Authenticated customer does not match the payment session owner.'+ });+ return;+ }++ const customerId = authenticatedCustomerId || sourceSession?.customerId || targetSession.customerId || null;++ // 1. Identify ALL sessions on old/other devices that must be cancelled (excluding PROCESSING and terminal states)+ const NON_CANCELLABLE_STATES = [+ PaymentStatus.PROCESSING,+ PaymentStatus.CANCELLED,+ PaymentStatus.EXPIRED,+ PaymentStatus.FAILED,+ PaymentStatus.SUCCESS,+ PaymentStatus.SUSPICIOUS+ ];const sessionsToTerminate = new Map();- if (![PaymentStatus.CANCELLED, PaymentStatus.EXPIRED, PaymentStatus.FAILED, PaymentStatus.SUCCESS].includes(targetSession.status)) {+ if (!NON_CANCELLABLE_STATES.includes(targetSession.status)) {sessionsToTerminate.set(targetSession.id, targetSession);}if (conflictingSessionId) {const confSess = ctx.sessionRepo.findById(conflictingSessionId);- if (confSess && ![PaymentStatus.CANCELLED, PaymentStatus.EXPIRED, PaymentStatus.FAILED, PaymentStatus.SUCCESS].includes(confSess.status)) {+ if (confSess?.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Conflicting payment session is currently in bank verification (PROCESSING) and cannot be terminated.'+ });+ return;+ }+ if (confSess && !NON_CANCELLABLE_STATES.includes(confSess.status)) {sessionsToTerminate.set(confSess.id, confSess);}}@@ -1609,7 +1750,14 @@ export function registerCheckoutRoutes(server, ctx) {if (customerId && ctx.sessionRepo.findAllActiveOrPendingForCustomer) {const custSessions = ctx.sessionRepo.findAllActiveOrPendingForCustomer(customerId);for (const cs of custSessions) {- if (![PaymentStatus.CANCELLED, PaymentStatus.EXPIRED, PaymentStatus.FAILED, PaymentStatus.SUCCESS].includes(cs.status)) {+ if (cs.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Another payment session for this customer is currently in bank verification (PROCESSING) and cannot be terminated.'+ });+ return;+ }+ if (!NON_CANCELLABLE_STATES.includes(cs.status)) {if (!cs.deviceId || cs.deviceId !== newDeviceId || cs.id === targetSession.id) {sessionsToTerminate.set(cs.id, cs);}@@ -1617,7 +1765,7 @@ export function registerCheckoutRoutes(server, ctx) {}}- if (session && session.id !== targetSession.id && ![PaymentStatus.CANCELLED, PaymentStatus.EXPIRED, PaymentStatus.FAILED, PaymentStatus.SUCCESS].includes(session.status)) {+ if (session && session.id !== targetSession.id && !NON_CANCELLABLE_STATES.includes(session.status)) {sessionsToTerminate.set(session.id, session);}@@ -1629,6 +1777,13 @@ export function registerCheckoutRoutes(server, ctx) {const cleanTargetOrder = targetSession.orderId ? targetSession.orderId.replace(/-R\d+$/, '') : '';const cleanActiveOrder = activeOnAcc.orderId ? activeOnAcc.orderId.replace(/-R\d+$/, '') : '';if ((cleanTargetOrder && cleanTargetOrder === cleanActiveOrder) || (customerId && activeOnAcc.customerId === customerId)) {+ if (activeOnAcc.status === PaymentStatus.PROCESSING) {+ HttpServer.json(res, 409, {+ error: 'SESSION_PROCESSING',+ message: 'Active payment session for this order is currently in bank verification (PROCESSING) and cannot be terminated.'+ });+ return;+ }sessionsToTerminate.set(activeOnAcc.id, activeOnAcc);}}@@ -1712,20 +1867,9 @@ export function registerCheckoutRoutes(server, ctx) {// 4. Preserve merchant's exact order reference from sourceSessionconst newOrderId = sourceSession.orderId ? sourceSession.orderId.replace(/-R\d+$/, '') : `ORD-${Date.now()}`;- // 5. Ensure device exists and register+ // 5. Touch verified deviceif (newDeviceId && ctx.deviceRepo) {- let dev = ctx.deviceRepo.findById(newDeviceId);- if (!dev) {- try {- ctx.deviceRepo.create({- id: newDeviceId,- publicKey: `adhoc_${newDeviceId}`,- fingerprintHash: `fp_${newDeviceId}`- });- } catch {}- } else {- ctx.deviceRepo.touch(newDeviceId);- }+ ctx.deviceRepo.touch(newDeviceId);}// 6. Create fresh payment session bound to newDeviceIddiff --git a/apps/payment-api/src/routes/device.routes.js b/apps/payment-api/src/routes/device.routes.jsindex b42abfc..7331034 100644--- a/apps/payment-api/src/routes/device.routes.js+++ b/apps/payment-api/src/routes/device.routes.js@@ -1,5 +1,28 @@import { HttpServer } from '../server.js';-import { generateFingerprintHash, normalizeDeviceSignals, verifyDeviceSignature } from '@youpi/core';+import {+ generateFingerprintHash,+ normalizeDeviceSignals,+ verifyDeviceSignature,+ createDeviceChallenge,+ consumeDeviceChallenge+} from '@youpi/core';++/**+ * Resolves a verified customer ID strictly from a valid customer session token.+ */+function resolveAuthenticatedCustomerId(req, body, ctx) {+ if (!ctx.customerSessionRepo) return null;+ let token = body?.token || req.headers['x-customer-token'] || null;+ if (!token) {+ const authHeader = req.headers['authorization'] || '';+ if (authHeader.startsWith('Bearer ')) {+ token = authHeader.slice(7).trim();+ }+ }+ if (!token || typeof token !== 'string') return null;+ const authCtx = ctx.customerSessionRepo.findByToken(token.trim());+ return authCtx?.customer?.id || null;+}/*** Registers device identity and cryptographic binding routes.@@ -7,23 +30,56 @@ import { generateFingerprintHash, normalizeDeviceSignals, verifyDeviceSignature* @param {{* deviceRepo: import('@youpi/db').DeviceRepository,* customerRepo: import('@youpi/db').CustomerRepository,+ * customerSessionRepo?: import('@youpi/db').CustomerSessionRepository,* auditRepo?: import('@youpi/db').AuditLogRepository* }} ctx*/export function registerDeviceRoutes(server, ctx) {+ // 0. POST /api/v1/devices/challenge+ server.post('/api/v1/devices/challenge', async (req, res) => {+ const body = await HttpServer.parseBody(req).catch(() => ({}));+ const { publicKey, deviceId } = body;++ if (!publicKey && !deviceId) {+ HttpServer.json(res, 400, { error: 'publicKey or deviceId is required' });+ return;+ }++ const existing = publicKey+ ? ctx.deviceRepo.findByPublicKey(String(publicKey).trim())+ : ctx.deviceRepo.findById(String(deviceId).trim());++ if (!existing || existing.status !== 'ACTIVE') {+ HttpServer.json(res, 404, { error: 'Device not found or inactive' });+ return;+ }++ const challenge = createDeviceChallenge(existing.id);+ HttpServer.json(res, 200, {+ success: true,+ deviceId: existing.id,+ challenge+ });+ });+// 1. POST /api/v1/devices/registerserver.post('/api/v1/devices/register', async (req, res) => {const body = await HttpServer.parseBody(req).catch(() => ({}));- const { publicKey, signals } = body;+ const { publicKey, signals, challenge, signature, payload } = body;- if (!publicKey) {+ if (!publicKey || typeof publicKey !== 'string' || !publicKey.trim()) {HttpServer.json(res, 400, { error: 'Device public key is required for registration.' });return;}+ const trimmedPublicKey = publicKey.trim();+ if (trimmedPublicKey.startsWith('adhoc_')) {+ HttpServer.json(res, 400, { error: 'Invalid device public key format.' });+ return;+ }+// Resolve or generate fingerprint hashconst clientSignals = signals || {};- // Extract server-visible headers if client didn't supply themif (!clientSignals.userAgent && req.headers['user-agent']) {clientSignals.userAgent = req.headers['user-agent'];}@@ -34,31 +90,66 @@ export function registerDeviceRoutes(server, ctx) {const fingerprintHash = body.fingerprintHash || generateFingerprintHash(clientSignals);const normalized = normalizeDeviceSignals(clientSignals);- // Optional customer association from body or authorization token- let customerId = body.customerId || null;- if (!customerId) {- const authHeader = req.headers['authorization'] || '';- if (authHeader.startsWith('Bearer ') && ctx.customerSessionRepo) {- const token = authHeader.slice(7).trim();- const authCtx = ctx.customerSessionRepo.findByToken(token);- if (authCtx?.customer) {- customerId = authCtx.customer.id;- }- }- }+ // Optional customer association strictly from verified customer session token (never bare customerId)+ const customerId = resolveAuthenticatedCustomerId(req, body, ctx);// Check if device with this exact public key already exists- const existing = ctx.deviceRepo.findByPublicKey(publicKey);+ const existing = ctx.deviceRepo.findByPublicKey(trimmedPublicKey);if (existing) {+ if (existing.status !== 'ACTIVE') {+ HttpServer.json(res, 403, { error: 'DEVICE_REVOKED', message: 'Device has been revoked or deactivated.' });+ return;+ }++ // Never return or rotate a deviceToken for an existing publicKey unless the caller+ // proves possession of the private key by signing a valid server-issued challenge.+ const hasChallengeProof =+ typeof challenge === 'string' &&+ challenge.trim().length > 0 &&+ typeof signature === 'string' &&+ signature.trim().length > 0 &&+ payload !== undefined &&+ payload !== null;++ if (!hasChallengeProof) {+ const freshChallenge = createDeviceChallenge(existing.id);+ HttpServer.json(res, 409, {+ error: 'DEVICE_ALREADY_REGISTERED',+ code: 'CHALLENGE_REQUIRED',+ message: 'This public key is already registered. Sign the server challenge with your private key to rotate credentials.',+ deviceId: existing.id,+ challenge: freshChallenge,+ isExisting: true+ });+ return;+ }++ const challengeOk = consumeDeviceChallenge(challenge.trim(), existing.id);+ const sigOk = challengeOk && verifyDeviceSignature(+ existing.publicKey,+ payload,+ signature,+ { expectedDeviceId: existing.id, expectedChallenge: challenge.trim() }+ );++ if (!sigOk) {+ HttpServer.json(res, 401, {+ error: 'DEVICE_CHALLENGE_FAILED',+ message: 'Failed to verify private-key ownership for existing device public key.'+ });+ return;+ }+if (customerId && !existing.customerId) {ctx.deviceRepo.associateCustomer(existing.id, customerId);}ctx.deviceRepo.touch(existing.id);+ const rotatedToken = ctx.deviceRepo.rotateToken(existing.id);HttpServer.json(res, 200, {success: true,deviceId: existing.id,- deviceToken: existing.deviceToken,+ deviceToken: rotatedToken,fingerprintHash: existing.fingerprintHash,status: existing.status,isExisting: true@@ -69,7 +160,7 @@ export function registerDeviceRoutes(server, ctx) {// Register new deviceconst device = ctx.deviceRepo.create({customerId,- publicKey,+ publicKey: trimmedPublicKey,fingerprintHash,userAgent: normalized.userAgent,platform: normalized.platform,@@ -109,35 +200,59 @@ export function registerDeviceRoutes(server, ctx) {const body = await HttpServer.parseBody(req).catch(() => ({}));const { deviceId, payload, signature, deviceToken } = body;- if (!deviceId) {- HttpServer.json(res, 400, { error: 'deviceId is required' });+ if (!deviceId || typeof deviceId !== 'string') {+ HttpServer.json(res, 400, { valid: false, error: 'deviceId is required' });return;}const device = ctx.deviceRepo.findById(deviceId);- if (!device || device.status !== 'ACTIVE') {+ if (!device || device.status !== 'ACTIVE' || (typeof device.publicKey === 'string' && device.publicKey.startsWith('adhoc_'))) {HttpServer.json(res, 404, { valid: false, error: 'Device not found or inactive' });return;}- let tokenValid = true;- if (deviceToken && device.deviceToken !== deviceToken) {- tokenValid = false;+ const hasToken = typeof deviceToken === 'string' && deviceToken.trim().length > 0;+ const hasSig = typeof signature === 'string' && signature.trim().length > 0;+ const hasPayload = payload !== undefined && payload !== null && String(payload).trim().length > 0;++ // Require at least one cryptographic credential; never default to valid: true!+ if (!hasToken && !hasSig) {+ HttpServer.json(res, 401, {+ valid: false,+ error: 'DEVICE_CREDENTIALS_REQUIRED',+ message: 'A deviceToken or cryptographic signature with payload is required.',+ deviceId: device.id,+ tokenValid: false,+ signatureValid: false+ });+ return;}- let signatureValid = true;- if (signature && payload) {- signatureValid = verifyDeviceSignature(device.publicKey, payload, signature);+ if ((hasSig && !hasPayload) || (!hasSig && hasPayload)) {+ HttpServer.json(res, 401, {+ valid: false,+ error: 'DEVICE_SIGNATURE_INVALID',+ message: 'Both signature and payload are required for signature verification.',+ deviceId: device.id,+ tokenValid: false,+ signatureValid: false+ });+ return;}+ const tokenValid = hasToken ? ctx.deviceRepo.verifyToken(device.id, deviceToken.trim()) : true;+ const signatureValid = hasSig+ ? verifyDeviceSignature(device.publicKey, payload, signature, { expectedDeviceId: device.id })+ : true;+const isValid = tokenValid && signatureValid;HttpServer.json(res, isValid ? 200 : 401, {valid: isValid,deviceId: device.id,customerId: device.customerId,- tokenValid,- signatureValid+ tokenValid: hasToken ? tokenValid : false,+ signatureValid: hasSig ? signatureValid : false});});diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex 61551e1..aa15895 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -1,6 +1,6 @@import { HttpServer } from '../server.js';import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual } from '@youpi/common';-import { isTerminalStatus, toPublicOutcome } from '@youpi/core';+import { isTerminalStatus, toPublicOutcome, verifyRegisteredDeviceCredentials } from '@youpi/core';import { isPaymentOwner } from '../auth-guard.js';/**@@ -59,16 +59,24 @@ export function registerPaymentRoutes(server, ctx) {}const deviceId = body.deviceId || req.headers['x-device-id'] || null;- if (deviceId && ctx.deviceRepo) {- let dev = ctx.deviceRepo.findById(deviceId);- if (!dev) {- try {- ctx.deviceRepo.create({- id: deviceId,- publicKey: `adhoc_${deviceId}`,- fingerprintHash: `fp_${deviceId}`- });- } catch {}+ const deviceToken = body.deviceToken || req.headers['x-device-token'] || null;+ const deviceSignature = body.deviceSignature || req.headers['x-device-signature'] || null;+ const signaturePayload = body.signaturePayload || req.headers['x-device-payload'] || null;++ if (deviceId) {+ const credCheck = verifyRegisteredDeviceCredentials({+ deviceId,+ deviceToken,+ deviceSignature,+ signaturePayload,+ deviceRepo: ctx.deviceRepo+ });+ if (!credCheck.valid) {+ HttpServer.json(res, 401, {+ error: credCheck.error || 'DEVICE_CREDENTIALS_INVALID',+ message: credCheck.message || 'A registered device and valid device credential are required.'+ });+ return;}}@@ -112,8 +120,8 @@ export function registerPaymentRoutes(server, ctx) {// If existing is non-terminal (ACTIVE, PROCESSING, QUEUED, INITIATED):if ([PaymentStatus.ACTIVE, PaymentStatus.PROCESSING, PaymentStatus.QUEUED, PaymentStatus.INITIATED].includes(existing.status)) {- // CASE 3: Active session + Different device -> DUPLICATE_SESSION_DETECTED- if (deviceId && existing.deviceId && deviceId !== existing.deviceId) {+ // CASE 3: Active session bound to a device + missing or different device -> DUPLICATE_SESSION_DETECTED+ if (existing.deviceId && (!deviceId || deviceId !== existing.deviceId)) {HttpServer.json(res, 409, {error: 'DUPLICATE_SESSION_DETECTED',code: 'DEVICE_SESSION_MISMATCH',@@ -201,7 +209,7 @@ export function registerPaymentRoutes(server, ctx) {if (customerId && ctx.sessionRepo) {const activeForCust = ctx.sessionRepo.findActiveForCustomer ? ctx.sessionRepo.findActiveForCustomer(customerId) : null;if (activeForCust) {- if (deviceId && activeForCust.deviceId && deviceId !== activeForCust.deviceId) {+ if (activeForCust.deviceId && (!deviceId || deviceId !== activeForCust.deviceId)) {HttpServer.json(res, 409, {error: 'DUPLICATE_SESSION_DETECTED',code: 'DEVICE_SESSION_MISMATCH',diff --git a/packages/common/src/secrets.js b/packages/common/src/secrets.jsindex c2e3577..dbe22d9 100644--- a/packages/common/src/secrets.js+++ b/packages/common/src/secrets.js@@ -59,13 +59,117 @@ export const getCoinStoreWebhookSecret = () => resolveSecret('coin_store_webhook*/export const getInternalServiceToken = () => resolveSecret('internal_service_token', 'INTERNAL_SERVICE_TOKEN');-/** True only when the caller proves it is a trusted internal service. */+/** True when a socket remoteAddress is loopback (IPv4 or IPv6). */+function isLoopbackRemoteAddress(remoteAddress) {+ if (!remoteAddress || typeof remoteAddress !== 'string') return true;+ const addr = remoteAddress.trim().toLowerCase();+ return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';+}++/** True only when the caller proves it is a trusted co-located internal service. */export function isInternalServiceRequest(req) {+ if (!isLoopbackRemoteAddress(req?.socket?.remoteAddress)) return false;const match = /^Bearer\s+(.+)$/i.exec(req?.headers?.['authorization'] || '');const presented = (match ? match[1].trim() : '') || (req?.headers?.['x-internal-token'] || '');return Boolean(presented) && safeEqual(presented, getInternalServiceToken());}+/**+ * Mints a server-signed device credential bound to a specific `deviceId`.+ * Format: `devtok_<deviceId>.<nonce>.<issuedAt>.<hmac>`+ * @param {string} deviceId+ * @returns {string}+ */+export function issueDeviceCredential(deviceId) {+ if (!deviceId || typeof deviceId !== 'string') {+ throw new Error('deviceId is required to issue a device credential');+ }+ const nonce = crypto.randomBytes(16).toString('hex');+ const issuedAt = String(Date.now());+ const mac = crypto+ .createHmac('sha256', getInternalServiceToken())+ .update(`devcred:v1:${deviceId}:${nonce}:${issuedAt}`)+ .digest('hex');+ return `devtok_${deviceId}.${nonce}.${issuedAt}.${mac}`;+}++/**+ * Verifies in constant time that a presented `deviceToken` is a genuine server-signed+ * credential issued for `deviceId`.+ * @param {string} deviceId+ * @param {string} token+ * @returns {boolean}+ */+export function verifyDeviceCredential(deviceId, token) {+ if (!deviceId || typeof deviceId !== 'string' || !token || typeof token !== 'string') {+ return false;+ }+ const prefix = `devtok_${deviceId}.`;+ if (!token.startsWith(prefix)) return false;+ const rest = token.slice(prefix.length);+ const parts = rest.split('.');+ if (parts.length !== 3) return false;+ const [nonce, issuedAt, presentedMac] = parts;+ if (!nonce || !issuedAt || !presentedMac) return false;+ const expectedMac = crypto+ .createHmac('sha256', getInternalServiceToken())+ .update(`devcred:v1:${deviceId}:${nonce}:${issuedAt}`)+ .digest('hex');+ return safeEqual(presentedMac, expectedMac);+}++const DEVICE_CHALLENGE_TTL_MS = 5 * 60 * 1000;+const consumedDeviceChallenges = new Map();++function deviceChallengeMac(deviceId, nonce, expiresAt) {+ return crypto+ .createHmac('sha256', getInternalServiceToken())+ .update(`devchal:v1:${deviceId}:${nonce}:${expiresAt}`)+ .digest('hex');+}++/**+ * Mints a short-lived, single-use challenge bound to a registered `deviceId` for+ * challenge-response token re-issuance.+ * @param {string} deviceId+ * @returns {string}+ */+export function createDeviceChallenge(deviceId) {+ if (!deviceId || typeof deviceId !== 'string') {+ throw new Error('deviceId is required to create a device challenge');+ }+ const nonce = crypto.randomBytes(16).toString('hex');+ const expiresAt = String(Date.now() + DEVICE_CHALLENGE_TTL_MS);+ const mac = deviceChallengeMac(deviceId, nonce, expiresAt);+ return `devchal_${deviceId}.${nonce}.${expiresAt}.${mac}`;+}++/**+ * Verifies and consumes a single-use device challenge bound to `deviceId`.+ * @param {string} challenge+ * @param {string} deviceId+ * @returns {boolean}+ */+export function consumeDeviceChallenge(challenge, deviceId) {+ if (typeof challenge !== 'string' || typeof deviceId !== 'string' || !deviceId) return false;+ const prefix = `devchal_${deviceId}.`;+ if (!challenge.startsWith(prefix)) return false;+ const parts = challenge.slice(prefix.length).split('.');+ if (parts.length !== 3) return false;+ const [nonce, expiresAt, mac] = parts;+ if (!nonce || !expiresAt || !mac) return false;+ if (!safeEqual(mac, deviceChallengeMac(deviceId, nonce, expiresAt))) return false;+ const now = Date.now();+ if (!(Number(expiresAt) > now)) return false;+ for (const [k, exp] of consumedDeviceChallenges) {+ if (exp <= now) consumedDeviceChallenges.delete(k);+ }+ const key = `${deviceId}:${nonce}`;+ if (consumedDeviceChallenges.has(key)) return false;+ consumedDeviceChallenges.set(key, Number(expiresAt));+ return true;+}+/** Literal that older builds seeded into databases; must never be trusted. */export const LEGACY_DEFAULT_WEBHOOK_SECRET = 'merchant_webhook_secret_for_wallet_store';diff --git a/packages/core/src/device-security.js b/packages/core/src/device-security.jsindex 724a0e5..6af99bb 100644--- a/packages/core/src/device-security.js+++ b/packages/core/src/device-security.js@@ -1,4 +1,18 @@import crypto from 'node:crypto';+import {+ safeEqual,+ issueDeviceCredential,+ verifyDeviceCredential,+ createDeviceChallenge,+ consumeDeviceChallenge+} from '@youpi/common';++export {+ issueDeviceCredential,+ verifyDeviceCredential,+ createDeviceChallenge,+ consumeDeviceChallenge+};/*** Normalizes privacy-conscious browser/device signals into a canonical dictionary.@@ -86,47 +100,276 @@ export function importDevicePublicKey(publicKeyInput) {});}+const DEFAULT_SIGNATURE_MAX_AGE_MS = 5 * 60 * 1000;+const DEFAULT_SIGNATURE_CLOCK_SKEW_MS = 60 * 1000;+const usedSignatureNonces = new Map();++function pruneSignatureNonces(now = Date.now()) {+ if (usedSignatureNonces.size < 256) return;+ for (const [k, exp] of usedSignatureNonces.entries()) {+ if (exp <= now) usedSignatureNonces.delete(k);+ }+}++/**+ * Extracts and validates the anti-replay `{ nonce, timestamp }` metadata from a signed payload.+ * Payloads must be a JSON string/object `{ nonce, timestamp, ... }` or `<nonce>:<timestamp>[:...]`.+ * @param {string|Buffer|object} dataToVerify+ * @param {{ maxAgeMs?: number, maxClockSkewMs?: number, expectedDeviceId?: string, expectedChallenge?: string }} [options]+ * @returns {{ canonicalBuffer: Buffer, nonce: string, timestamp: number } | null}+ */+export function parseSignedDevicePayload(dataToVerify, options = {}) {+ if (dataToVerify === null || dataToVerify === undefined) return null;++ const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : DEFAULT_SIGNATURE_MAX_AGE_MS;+ const maxClockSkewMs = Number.isFinite(options.maxClockSkewMs) ? options.maxClockSkewMs : DEFAULT_SIGNATURE_CLOCK_SKEW_MS;++ let rawString;+ let parsedObj = null;++ if (Buffer.isBuffer(dataToVerify)) {+ rawString = dataToVerify.toString('utf8');+ } else if (typeof dataToVerify === 'object') {+ parsedObj = dataToVerify;+ rawString = JSON.stringify(dataToVerify);+ } else if (typeof dataToVerify === 'string') {+ rawString = dataToVerify;+ } else {+ return null;+ }++ if (!parsedObj && rawString.trim().startsWith('{') && rawString.trim().endsWith('}')) {+ try {+ parsedObj = JSON.parse(rawString);+ } catch {+ return null;+ }+ }++ let nonce = null;+ let rawTs = null;++ if (parsedObj && typeof parsedObj === 'object') {+ nonce = typeof parsedObj.nonce === 'string' ? parsedObj.nonce.trim() : null;+ rawTs = parsedObj.timestamp ?? parsedObj.ts ?? parsedObj.issuedAt;+ if (options.expectedDeviceId && parsedObj.deviceId && parsedObj.deviceId !== options.expectedDeviceId) {+ return null;+ }+ if (options.expectedChallenge && parsedObj.challenge !== options.expectedChallenge) {+ return null;+ }+ } else {+ // Support colon-separated `<nonce>:<timestamp>[:<challenge>...]`+ const parts = rawString.split(':');+ if (parts.length < 2) return null;+ nonce = parts[0].trim();+ rawTs = parts[1].trim();+ if (options.expectedChallenge && !parts.slice(2).includes(options.expectedChallenge)) {+ return null;+ }+ }++ if (!nonce || nonce.length < 8 || nonce.length > 256) {+ return null;+ }++ let timestampMs = NaN;+ if (typeof rawTs === 'number' && Number.isFinite(rawTs)) {+ timestampMs = rawTs >= 1e9 && rawTs < 1e11 ? rawTs * 1000 : rawTs;+ } else if (typeof rawTs === 'string' && rawTs.trim()) {+ const num = Number(rawTs.trim());+ if (Number.isFinite(num)) {+ timestampMs = num >= 1e9 && num < 1e11 ? num * 1000 : num;+ } else {+ timestampMs = Date.parse(rawTs.trim());+ }+ }++ if (!Number.isFinite(timestampMs) || timestampMs <= 0) {+ return null;+ }++ const now = Date.now();+ if (now - timestampMs > maxAgeMs) {+ return null;+ }+ if (timestampMs - now > maxClockSkewMs) {+ return null;+ }++ const canonicalBuffer = Buffer.isBuffer(dataToVerify)+ ? dataToVerify+ : Buffer.from(rawString, 'utf8');++ return { canonicalBuffer, nonce, timestamp: timestampMs };+}+/*** Verifies an ECDSA P-256 signature generated by browser Web Crypto.+ * Requires a fresh timestamp and single-use nonce in the signed payload.* @param {string|object} publicKey- * @param {string|Buffer} dataToVerify+ * @param {string|Buffer|object} dataToVerify* @param {string} signatureBase64+ * @param {{ maxAgeMs?: number, maxClockSkewMs?: number, expectedDeviceId?: string, expectedChallenge?: string }} [options]* @returns {boolean}*/-export function verifyDeviceSignature(publicKey, dataToVerify, signatureBase64) {+export function verifyDeviceSignature(publicKey, dataToVerify, signatureBase64, options = {}) {try {+ if (!publicKey || !signatureBase64) return false;++ const parsed = parseSignedDevicePayload(dataToVerify, options);+ if (!parsed) return false;+const keyObject = importDevicePublicKey(publicKey);- const dataBuffer = Buffer.isBuffer(dataToVerify) ? dataToVerify : Buffer.from(String(dataToVerify));- const sigBuffer = Buffer.from(String(signatureBase64).trim(), 'base64');+ const dataBuffer = parsed.canonicalBuffer;+ const sigStr = String(signatureBase64).trim();+ if (!sigStr) return false;+ const sigBuffer = Buffer.from(sigStr, 'base64');+ if (sigBuffer.length === 0) return false;++ const keyDer = keyObject.export({ format: 'der', type: 'spki' });+ const keyFp = crypto.createHash('sha256').update(keyDer).digest('hex').slice(0, 32);+ const nonceKey = `${keyFp}:${parsed.nonce}`;+ const now = Date.now();+ pruneSignatureNonces(now);++ const existingExp = usedSignatureNonces.get(nonceKey);+ if (existingExp && existingExp > now) {+ return false;+ }++ let verified = false;// Try ieee-p1363 (standard Web Crypto ECDSA output: r || s, 64 bytes)try {- const valid = crypto.verify(+ verified = crypto.verify('SHA256',dataBuffer,{ key: keyObject, dsaEncoding: 'ieee-p1363' },sigBuffer);- if (valid) return true;} catch {}// Fallback to standard DER encoding- try {- return crypto.verify(- 'SHA256',- dataBuffer,- keyObject,- sigBuffer- );- } catch {}+ if (!verified) {+ try {+ verified = crypto.verify(+ 'SHA256',+ dataBuffer,+ keyObject,+ sigBuffer+ );+ } catch {}+ }- return false;+ if (!verified) return false;++ const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : DEFAULT_SIGNATURE_MAX_AGE_MS;+ usedSignatureNonces.set(nonceKey, now + maxAgeMs);+ return true;} catch (err) {console.warn('[DeviceSecurity] Signature verification error:', err.message);return false;}}+/**+ * Verifies that a device exists, is ACTIVE, is not an adhoc placeholder, and that the+ * caller presented a valid cryptographic credential (token or ECDSA signature).+ * @param {{+ * deviceId: string,+ * deviceToken?: string|null,+ * deviceSignature?: string|null,+ * signaturePayload?: string|object|null,+ * deviceRepo: any+ * }} params+ * @returns {{ valid: boolean, error?: string, message?: string, device?: any }}+ */+export function verifyRegisteredDeviceCredentials({+ deviceId,+ deviceToken,+ deviceSignature,+ signaturePayload,+ deviceRepo+}) {+ if (!deviceId || typeof deviceId !== 'string') {+ return {+ valid: false,+ error: 'DEVICE_ID_REQUIRED',+ message: 'A registered deviceId is required.'+ };+ }+ if (!deviceRepo) {+ return {+ valid: false,+ error: 'DEVICE_REPO_UNAVAILABLE',+ message: 'Device repository is required for device verification.'+ };+ }++ const dev = deviceRepo.findById(deviceId);+ if (!dev || dev.status !== 'ACTIVE' || (typeof dev.publicKey === 'string' && dev.publicKey.startsWith('adhoc_'))) {+ return {+ valid: false,+ error: 'DEVICE_REVOKED',+ message: 'The device is unregistered, revoked, or invalid.'+ };+ }++ const hasToken = typeof deviceToken === 'string' && deviceToken.trim().length > 0;+ const hasSig = typeof deviceSignature === 'string' && deviceSignature.trim().length > 0;+ const hasPayload = signaturePayload !== undefined && signaturePayload !== null && String(signaturePayload).trim().length > 0;++ if (!hasToken && !hasSig) {+ return {+ valid: false,+ error: 'DEVICE_CREDENTIALS_REQUIRED',+ message: 'Device authentication credential (token or cryptographic signature) is required.'+ };+ }++ if ((hasSig && !hasPayload) || (!hasSig && hasPayload)) {+ return {+ valid: false,+ error: 'DEVICE_SIGNATURE_INVALID',+ message: 'Both device signature and signed payload are required for signature verification.'+ };+ }++ if (hasToken) {+ let tokenOk = false;+ if (typeof deviceRepo.verifyToken === 'function') {+ tokenOk = deviceRepo.verifyToken(deviceId, deviceToken.trim());+ } else if (dev.deviceToken) {+ tokenOk = safeEqual(dev.deviceToken, deviceToken.trim()) && verifyDeviceCredential(deviceId, deviceToken.trim());+ } else {+ tokenOk = verifyDeviceCredential(deviceId, deviceToken.trim());+ }+ if (!tokenOk) {+ return {+ valid: false,+ error: 'DEVICE_TOKEN_INVALID',+ message: 'Device token failed verification.'+ };+ }+ }++ if (hasSig) {+ const sigOk = verifyDeviceSignature(dev.publicKey, signaturePayload, deviceSignature, {+ expectedDeviceId: deviceId+ });+ if (!sigOk) {+ return {+ valid: false,+ error: 'DEVICE_SIGNATURE_INVALID',+ message: 'Device cryptographic signature failed verification.'+ };+ }+ }++ return { valid: true, device: dev };+}+/*** Validates whether the requesting device matches the payment session's bound device.* @param {{@@ -139,15 +382,17 @@ export function verifyDeviceSignature(publicKey, dataToVerify, signatureBase64)* }} options* @returns {{* allowed: boolean,+ * shouldBind?: boolean,* error?: string,+ * session_id?: string,* action?: string,* message?: string,- * boundDeviceId?: string,- * requestingDeviceId?: string+ * boundDeviceId?: string|null,+ * requestingDeviceId?: string|null* }}*/export function validateSessionDeviceAccess(options) {- const { session, requestingDeviceId, deviceToken, deviceSignature, signaturePayload, deviceRepo } = options;+ const { session, requestingDeviceId, deviceToken, deviceSignature, signaturePayload, deviceRepo } = options || {};if (!session) {return {@@ -159,8 +404,41 @@ export function validateSessionDeviceAccess(options) {const boundDeviceId = session.deviceId;- // If session is not yet bound to any device, allow current device to bind+ // If session is not yet bound to any device:+ // Only allow binding if the caller presents a registered, cryptographically verified device.if (!boundDeviceId) {+ if (!requestingDeviceId) {+ return {+ allowed: false,+ error: 'DEVICE_ID_REQUIRED',+ session_id: session.id,+ action: 'REGISTER_DEVICE',+ message: 'A registered device identity is required to access or bind this checkout session.',+ boundDeviceId: null,+ requestingDeviceId: null+ };+ }++ const credCheck = verifyRegisteredDeviceCredentials({+ deviceId: requestingDeviceId,+ deviceToken,+ deviceSignature,+ signaturePayload,+ deviceRepo+ });++ if (!credCheck.valid) {+ return {+ allowed: false,+ error: credCheck.error === 'DEVICE_SIGNATURE_INVALID' ? 'DEVICE_SIGNATURE_INVALID' : 'DUPLICATE_SESSION_DETECTED',+ session_id: session.id,+ action: 'END_SESSION_AND_CREATE_NEW',+ message: credCheck.message || 'Valid registered device credentials are required.',+ boundDeviceId: null,+ requestingDeviceId+ };+ }+return {allowed: true,shouldBind: true,@@ -181,10 +459,17 @@ export function validateSessionDeviceAccess(options) {};}- // If cryptographic device token is provided, verify against repository- if (deviceRepo && deviceToken) {- const dev = deviceRepo.findById(boundDeviceId);- if (!dev || dev.status !== 'ACTIVE') {+ // Verify the bound device is registered, active, and that the caller supplied a valid token or signature+ const credCheck = verifyRegisteredDeviceCredentials({+ deviceId: boundDeviceId,+ deviceToken,+ deviceSignature,+ signaturePayload,+ deviceRepo+ });++ if (!credCheck.valid) {+ if (credCheck.error === 'DEVICE_REVOKED') {return {allowed: false,error: 'DEVICE_REVOKED',@@ -193,35 +478,24 @@ export function validateSessionDeviceAccess(options) {message: 'The device registered for this payment session has been revoked or is invalid.'};}-- if (dev.deviceToken && dev.deviceToken !== deviceToken) {+ if (credCheck.error === 'DEVICE_SIGNATURE_INVALID') {return {allowed: false,- error: 'DUPLICATE_SESSION_DETECTED',+ error: 'DEVICE_SIGNATURE_INVALID',session_id: session.id,action: 'END_SESSION_AND_CREATE_NEW',- message: 'This payment session was created on another device. For security reasons, this session cannot be continued from this device.',- boundDeviceId,- requestingDeviceId+ message: 'Device cryptographic signature failed verification.'};}- }-- // If cryptographic signature is provided, verify with registered public key- if (deviceRepo && deviceSignature && signaturePayload) {- const dev = deviceRepo.findById(boundDeviceId);- if (dev && dev.publicKey) {- const isValidSig = verifyDeviceSignature(dev.publicKey, signaturePayload, deviceSignature);- if (!isValidSig) {- return {- allowed: false,- error: 'DEVICE_SIGNATURE_INVALID',- session_id: session.id,- action: 'END_SESSION_AND_CREATE_NEW',- message: 'Device cryptographic signature failed verification.'- };- }- }+ return {+ allowed: false,+ error: 'DUPLICATE_SESSION_DETECTED',+ session_id: session.id,+ action: 'END_SESSION_AND_CREATE_NEW',+ message: 'This payment session was created on another device. For security reasons, this session cannot be continued from this device.',+ boundDeviceId,+ requestingDeviceId+ };}return {diff --git a/packages/core/src/timing-engine.js b/packages/core/src/timing-engine.jsindex 5731330..105d135 100644--- a/packages/core/src/timing-engine.js+++ b/packages/core/src/timing-engine.js@@ -200,15 +200,15 @@ export class TimingEngine {* @param {string} sessionId*/handleCancel(sessionId) {- this.clearTimers(sessionId);-const session = this.sessionRepo.findById(sessionId);if (!session) return null;- if ([PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED].includes(session.status)) {- return session; // already terminal+ if ([PaymentStatus.PROCESSING, PaymentStatus.SUCCESS, PaymentStatus.FAILED, PaymentStatus.EXPIRED, PaymentStatus.CANCELLED, PaymentStatus.SUSPICIOUS].includes(session.status)) {+ return session; // cannot cancel in-flight PROCESSING or already terminal sessions}+ this.clearTimers(sessionId);+const updated = this.sessionRepo.transitionToTerminal(sessionId, PaymentStatus.CANCELLED);if (this.auditRepo) {diff --git a/packages/db/src/repositories/device.repository.js b/packages/db/src/repositories/device.repository.jsindex 2c1f2aa..bde0f2b 100644--- a/packages/db/src/repositories/device.repository.js+++ b/packages/db/src/repositories/device.repository.js@@ -1,5 +1,5 @@import crypto from 'node:crypto';-import { blindIndex } from '@youpi/common';+import { blindIndex, blindIndexMatches, safeEqual, issueDeviceCredential, verifyDeviceCredential } from '@youpi/common';/** Namespace so device-token digests never collide with other blind indexes. */const INDEX_NS = 'devtok';@@ -31,7 +31,7 @@ export class DeviceRepository {*/create(data) {const id = data.id || `dev_${crypto.randomUUID()}`;- const deviceToken = data.deviceToken || `devtok_${crypto.randomBytes(32).toString('hex')}`;+ const deviceToken = data.deviceToken || issueDeviceCredential(id);const now = new Date().toISOString();const status = data.status || 'ACTIVE';@@ -78,6 +78,62 @@ export class DeviceRepository {return row ? this.mapRow(row) : null;}+ /**+ * Verifies a presented device token for a specific device ID in constant time.+ * @param {string} deviceId+ * @param {string} presentedToken+ * @returns {boolean}+ */+ verifyToken(deviceId, presentedToken) {+ if (!deviceId || typeof deviceId !== 'string' || !presentedToken || typeof presentedToken !== 'string') {+ return false;+ }+ const row = this.db.queryOne(+ 'SELECT id, device_token, status FROM devices WHERE id = ?',+ [deviceId]+ );+ if (!row || row.status !== 'ACTIVE' || !row.device_token) {+ return false;+ }++ // If token uses the server-signed envelope (`devtok_<deviceId>...`), verify its HMAC signature too.+ if (presentedToken.startsWith(`devtok_${deviceId}.`) && !verifyDeviceCredential(deviceId, presentedToken)) {+ return false;+ }++ if (blindIndexMatches(presentedToken, row.device_token, INDEX_NS)) {+ return true;+ }++ // Support legacy rows that stored the raw token prior to blind indexing, and upgrade them.+ if (safeEqual(presentedToken, row.device_token)) {+ try {+ this.db.execute('UPDATE devices SET device_token = ? WHERE id = ?', [blindIndex(presentedToken, INDEX_NS), row.id]);+ } catch {}+ return true;+ }++ return false;+ }++ /**+ * Rotates and issues a fresh server-signed device credential for an existing device.+ * @param {string} deviceId+ * @returns {string|null}+ */+ rotateToken(deviceId) {+ if (!deviceId) return null;+ const row = this.db.queryOne('SELECT id, status FROM devices WHERE id = ?', [deviceId]);+ if (!row || row.status !== 'ACTIVE') return null;+ const freshToken = issueDeviceCredential(deviceId);+ const now = new Date().toISOString();+ this.db.execute(+ 'UPDATE devices SET device_token = ?, last_seen_at = ? WHERE id = ?',+ [blindIndex(freshToken, INDEX_NS), now, deviceId]+ );+ return freshToken;+ }+/*** Finds a device by its active device token.* @param {string} token