Skip to content

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): correct the agent skill docs and harden the MCP server

rishabh60dcad8d28c0
diff --git a/.agents/skills/youpi-android-gateway/SKILL.md b/.agents/skills/youpi-android-gateway/SKILL.md
index 5800f2e..f282ffc 100644
--- a/.agents/skills/youpi-android-gateway/SKILL.md
+++ b/.agents/skills/youpi-android-gateway/SKILL.md
@@ -16,7 +16,7 @@ Use this skill when developing, testing, or building the Android Banking SMS/Not
- **Core Components**:
1. `PaymentNotificationListenerService`: Extends `NotificationListenerService` to intercept banking SMS and UPI app push notifications.
2. `ForegroundService`: Persistent low-priority background daemon keeping observer connection alive across aggressive OEM battery managers (MIUI, ColorOS, OneUI).
- 3. `ApiClient`: Posts captured bank alerts to gateway endpoint (`/webhook/sms` or `/api/v1/device/notification`) with HMAC authentication and device token.
+ 3. `ApiClient`: Posts captured bank alerts to the gateway endpoints `/api/v1/observers/sms` (SMS broadcast) or `/api/v1/pollers/android/events` (notification listener), with HMAC authentication and the device token.
## Banking Package Allowlist
@@ -27,7 +27,7 @@ Run the idempotent allowlist synchronization script whenever packages or banking
```bash
node scripts/sync-android-allowlist.js
```
-This updates `apps/android-observer-app/app/src/main/res/values/banking_packages.xml`.
+This updates the `ALLOWED_BANKING_PACKAGES` set in `apps/android-observer-app/app/src/main/java/com/youpi/observer/PaymentNotificationListenerService.java`.
## Certified APK Build Process
diff --git a/.agents/skills/youpi-banking-observer/SKILL.md b/.agents/skills/youpi-banking-observer/SKILL.md
index fb4e8f9..b26f1a1 100644
--- a/.agents/skills/youpi-banking-observer/SKILL.md
+++ b/.agents/skills/youpi-banking-observer/SKILL.md
@@ -24,9 +24,9 @@ Use this skill when developing, testing, or auditing payment observation parsers
### SMS Observer (`apps/sms-observer` on port `6002`):
Send a simulated incoming SMS payload:
```bash
-curl -X POST http://localhost:6002/webhook/sms \
+curl -X POST http://localhost:6002/process-sms \
-H "Content-Type: application/json" \
- -H "X-Observer-Token: $OBSERVER_TOKEN" \
+ -H "Authorization: Bearer $OBSERVER_API_TOKEN" \
-d '{
"sender": "VK-HDFCBK",
"body": "Dear Customer, INR 499.00 credited to account **1234 on 21-OCT-26 by UPI/123456789012/Ref-TSHIRT. Available balance INR 10,450.00.",
@@ -37,9 +37,9 @@ curl -X POST http://localhost:6002/webhook/sms \
### Gmail Observer (`apps/gmail-observer` on port `6003`):
Send a simulated incoming Gmail alert:
```bash
-curl -X POST http://localhost:6003/webhook/gmail \
+curl -X POST http://localhost:6003/process-email \
-H "Content-Type: application/json" \
- -H "X-Observer-Token: $OBSERVER_TOKEN" \
+ -H "Authorization: Bearer $OBSERVER_API_TOKEN" \
-d '{
"subject": "Credit Alert: A/C *1234 credited with INR 499.00",
"snippet": "INR 499.00 received via UPI ref 123456789012",
@@ -49,7 +49,7 @@ curl -X POST http://localhost:6003/webhook/gmail \
## Adding New Bank Regex Patterns
-1. Update parser in `packages/core/src/attribution-engine.js` or `apps/sms-observer/src/parsers/`.
+1. Update the parser in `packages/core/src/bank-sms-parser.js` (shared) or `apps/sms-observer/src/sms-parser.js`.
2. Ensure regex extracts:
- `amountPaise` (integer in paise, e.g. 49900)
- `utr` (`\b\d{12}\b` or bank specific alpha-numeric UTR)
diff --git a/.agents/skills/youpi-security-audit/SKILL.md b/.agents/skills/youpi-security-audit/SKILL.md
index 15134fe..7ef42cc 100644
--- a/.agents/skills/youpi-security-audit/SKILL.md
+++ b/.agents/skills/youpi-security-audit/SKILL.md
@@ -19,17 +19,17 @@ Use this skill when auditing or modifying core payment APIs, checkout lifecycle,
- `X-Gateway-Timestamp: <ms>`
- `X-Gateway-Event: SUCCESS`
- `X-Gateway-Delivery-Id: <uuid>`
-- Signature verification helper: `YoupiPaymentClient.verifyWebhook(rawBody, signature, secret, timestamp)` enforces freshness window (default 300s).
+- Signature verification helper: `YoupiPaymentClient.verifyWebhook(rawPayloadString, signatureHeader, customSecret)` verifies `HMAC-SHA256(secret, rawBody)` in constant time. It takes no timestamp argument; replay protection is implemented by the RECEIVER, for example `apps/coin-wallet-store/src/server.js` (X-Gateway-Timestamp skew window plus X-Gateway-Delivery-Id deduplication).
### 2. Device Binding & Fail-Closed Access Control
- `checkSessionDeviceAccess(session, req, body, ctx)` in `apps/payment-api/src/routes/checkout.routes.js`:
- - When a payment session is bound to an active device (`session.deviceId`), requests omitting `X-Device-Id` **MUST fail closed** with `HTTP 401 DEVICE_ID_REQUIRED`.
+ - When a payment session is bound to an active device (`session.deviceId`), a request from a DIFFERENT device is rejected with `HTTP 409 DUPLICATE_SESSION_DETECTED`. Omitting `X-Device-Id` on a bound session is also rejected, with the same 409; there is no `401 DEVICE_ID_REQUIRED` response.
- Mismatched device identities must return `HTTP 409 DUPLICATE_SESSION_DETECTED`.
- - Admin tokens (`ADMIN_API_TOKEN`) and owning merchant API keys (`X-Merchant-Key`) bypass device lock for administrative support.
+ - Only a co-located internal renderer bypasses the device lock, and it must present the internal service token over loopback (`isInternalServiceRequest()` in `packages/common/src/secrets.js`). Admin tokens and `X-Merchant-Key` do NOT bypass it - do not add such a bypass.
### 3. Payment Creation Guard (`POST /api/v1/payments`)
-- Requests require a valid `X-Merchant-Key` (matching `apiKeyHash` with fallback to `webhookSecret`), or authenticated admin token.
-- `autoActivate: true` is strictly forbidden in production unless authorized by admin credentials or verified test mode, returning `HTTP 403 AUTOACTIVATE_FORBIDDEN`.
+- `X-Merchant-Key` (the merchant's webhook secret) is OPTIONAL on `POST /api/v1/payments`; when present it is validated, and when absent the request proceeds. There is no `apiKeyHash` column. The key grants the merchant-private view of a session on `GET /api/v1/payments/:id` and the COD endpoints, where an anonymous caller receives a redacted view.
+- `autoActivate: true` is currently honoured unconditionally on `POST /api/v1/payments` - there is no `403 AUTOACTIVATE_FORBIDDEN` guard. If you rely on auto-activation being blocked in production, add that guard; do not assume it exists.
### 4. Running Verification Test Suites
Verify all invariants locally before committing:
diff --git a/packages/youpi-mcp/src/tools.js b/packages/youpi-mcp/src/tools.js
index ffd43c4..6eee94f 100644
--- a/packages/youpi-mcp/src/tools.js
+++ b/packages/youpi-mcp/src/tools.js
@@ -1,5 +1,5 @@
-import crypto from 'node:crypto';
import http from 'node:http';
+import { verifyHmac } from '@youpi/common';
export const TOOLS_DEFINITIONS = [
{
@@ -10,6 +10,7 @@ export const TOOLS_DEFINITIONS = [
properties: {
host: {
type: 'string',
+ description: 'Ignored. The probe only ever targets the local gateway.',
description: 'Host to check (defaults to 127.0.0.1)',
default: '127.0.0.1'
}
@@ -49,7 +50,7 @@ export const TOOLS_DEFINITIONS = [
},
{
name: 'youpi_simulate_bank_notification',
- description: 'Simulate an incoming Indian bank SMS credit notification to test automated payment verification.',
+ description: 'Format an incoming Indian bank SMS credit notification as text. This only returns the message body - it does NOT deliver anything to the observers or the gateway, so it can never mark a payment as settled.',
inputSchema: {
type: 'object',
properties: {
@@ -70,11 +71,6 @@ export const TOOLS_DEFINITIONS = [
type: 'string',
description: 'Last 3-4 digits of receiving account',
default: '1234'
- },
- observerPort: {
- type: 'number',
- description: 'SMS Observer port (default 6002)',
- default: 6002
}
},
required: ['bank', 'amount', 'utr']
@@ -82,6 +78,9 @@ export const TOOLS_DEFINITIONS = [
}
];
+/** The only hosts the health probe may target. */
+const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);
+
export function verifyWebhookSignature({ rawPayload, signature, secret, timestamp, maxAgeSeconds = 300 }) {
if (!rawPayload || !signature || !secret) {
return { valid: false, error: 'MISSING_REQUIRED_PARAMS' };
@@ -102,23 +101,15 @@ export function verifyWebhookSignature({ rawPayload, signature, secret, timestam
if (!/^[0-9a-fA-F]+$/.test(sig) || sig.length % 2 !== 0) {
return { valid: false, error: 'INVALID_SIGNATURE_FORMAT' };
}
- const hmac = crypto.createHmac('sha256', secret);
- hmac.update(rawPayload, 'utf8');
- const expected = hmac.digest('hex');
- const bufA = Buffer.from(sig, 'hex');
- const bufB = Buffer.from(expected, 'hex');
-
- if (bufA.length !== bufB.length) {
+ // Use the shared verifier so this tool can never drift from the contract the gateway
+ // and the merchant SDK implement: HMAC-SHA256(secret, rawBody), constant-time compare.
+ // The length is checked first so a truncated signature is reported distinctly.
+ if (sig.length !== 64) {
return { valid: false, error: 'SIGNATURE_LENGTH_MISMATCH' };
}
-
- try {
- const matches = crypto.timingSafeEqual(bufA, bufB);
- return { valid: matches, error: matches ? null : 'INVALID_SIGNATURE' };
- } catch (_) {
- return { valid: false, error: 'INVALID_SIGNATURE' };
- }
+ const matches = verifyHmac(rawPayload, secret, sig);
+ return { valid: matches, error: matches ? null : 'INVALID_SIGNATURE' };
}
export function generateBankSmsText({ bank, amount, utr, accountLastDigits = '1234' }) {
@@ -141,10 +132,16 @@ export function generateBankSmsText({ bank, amount, utr, accountLastDigits = '12
}
}
+/**
+ * Probes a local gateway port. The host is deliberately NOT caller-controlled: the tool
+ * exists to report the health of the gateway running next to it, and letting a caller
+ * choose the host would turn it into an arbitrary GET probe of other hosts.
+ */
export async function checkPortHealth(port, host = '127.0.0.1') {
+ const targetHost = LOOPBACK_HOSTS.has(String(host)) ? String(host) : '127.0.0.1';
return new Promise((resolve) => {
try {
- const req = http.request({ host, port, path: '/health', method: 'GET', timeout: 800 }, (res) => {
+ const req = http.request({ host: targetHost, port, path: '/health', method: 'GET', timeout: 800 }, (res) => {
res.resume();
resolve({ port, online: res.statusCode >= 200 && res.statusCode < 500, statusCode: res.statusCode });
});
diff --git a/scripts/test-all.js b/scripts/test-all.js
index 39dfe61..6f9ea7d 100644
--- a/scripts/test-all.js
+++ b/scripts/test-all.js
@@ -10,6 +10,7 @@ const testFiles = [
'packages/core/src/__tests__/queue-timing.test.js',
'packages/core/src/__tests__/webhook-engine.test.js',
'packages/merchant-sdk/src/__tests__/merchant-sdk.test.js',
+ 'packages/youpi-mcp/src/__tests__/mcp-server.test.js',
'packages/merchant-sdk/src/__tests__/youpi-universal-integration.test.js',
'apps/checkout-portal/src/__tests__/checkout-portal.test.js',
'apps/checkout-portal/src/__tests__/checkout-xss.test.js',