A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
feat(payments): add secure manual UPI review flow
surenuxui466c8801e877
diff --git a/.env.example b/.env.exampleindex 4299208..35d251f 100644--- a/.env.example+++ b/.env.example@@ -37,6 +37,10 @@ BASE_HELP_URL=http://localhost:3000BASE_DEMO_STORE_URL=http://localhost:5000# Merchant sites allowed to show the checkout in the youpi.js modal (iframe), comma separated.# Unset = only the portal's own origin may frame it.+# Origins allowed to call browser-facing gateway APIs. Set only trusted storefront origins.+YOUPI_ALLOWED_ORIGINS=https://shop.example.com+# Return URL origins accepted when a server creates a payment session.+YOUPI_ALLOWED_RETURN_ORIGINS=https://shop.example.com# --- DATABASE CONFIGURATION ---# PostgreSQL connection string:diff --git a/.gitignore b/.gitignoreindex 54e92f4..ea22168 100644--- a/.gitignore+++ b/.gitignore@@ -27,6 +27,8 @@ local.properties# Environment and Secrets.env+.env.*+!.env.example.env.local.env.development.local.env.test.localdiff --git a/DEPLOYMENT_CHECKLIST.md b/DEPLOYMENT_CHECKLIST.mdnew file mode 100644index 0000000..b99f903--- /dev/null+++ b/DEPLOYMENT_CHECKLIST.md@@ -0,0 +1,27 @@+# Deployment checklist — Fins & Wings manual UPI++Deployment is intentionally not performed as part of this change.++## Before any real payment++- [ ] Keep this gateway out of production until the unresolved items in `SECURITY_REMEDIATION_REPORT.md` are reviewed and signed off.+- [ ] Use a persistent, backed-up database. `render.yaml` currently selects a free service with SQLite and declares no persistent disk; local SQLite data is not a production persistence strategy.+- [ ] Configure a stable `ENCRYPTION_MASTER_KEY`, `JWT_SECRET`, admin credentials/token, merchant API key, webhook secret, Supabase service-role key, and all other secrets in the hosting secret manager. Rotate any key ever committed, shared, or stored in an untracked backup.+- [ ] Set exact HTTPS `YOUPI_ALLOWED_ORIGINS`, `YOUPI_ALLOWED_RETURN_ORIGINS`, checkout frame ancestors, and customer return URL origins.+- [ ] Use a separately rotated merchant API key and webhook HMAC secret. Keep both server-side. Do not put either in Vite/browser configuration.+- [ ] Configure the Fins & Wings webhook URL and matching `YOUPI_WEBHOOK_SECRET`. Confirm raw-body signature verification, delivery-ID matching, and duplicate handling.+- [ ] Review migrations `008_youpi_pg.sql` and `009_youpi_manual_review.sql` against the live schema, take a restorable backup, then apply them through the normal controlled database migration process.+- [ ] Verify RLS and grants in Supabase: gateway attempts/events and the event RPC remain inaccessible to `anon` and ordinary `authenticated` users; only `service_role` invokes the webhook RPC; only authorized admins invoke the review RPC.+- [ ] Apply edge rate limits, request-size limits, WAF rules, egress restrictions, alerting, log retention controls, and an incident/secret-rotation procedure. The gateway's in-process rate limiter is per-process and is not a multi-instance control.+- [ ] Disable unused SMS/Gmail observers and remove their OAuth credentials/permissions if they are not part of the deployment. `MANUAL_UPI` itself bypasses observer-health gating and cannot be auto-attributed.+- [ ] Test UTR reuse, duplicate webhooks, retries, network interruption, timeout, amount mismatch, wrong merchant, admin rejection, admin approval, and rejected order retry using synthetic data.+- [ ] Confirm fulfilment is impossible before authenticated admin verification and stock confirmation. Reconcile the credited bank account manually before approving a UTR.+- [ ] Run gateway `npm test`, customer `npm test`, admin `npm run build`, gateway typecheck/build where supported, and dependency audit. Retain test output with the release review.+- [ ] Establish database backups and perform a restore drill; monitor webhook delivery backlog and failed attempts.++## Release controls++- [ ] Review all diffs and ensure `.env`, `.env.save`, `.env.before-*`, and `data/.secrets/*` remain untracked.+- [ ] Apply migrations only after approval by the database owner. This code change does not connect to or mutate live Supabase.+- [ ] Push the reviewed feature branch only after explicit release approval.+- [ ] Deploy only after the production approval and checklist sign-off.diff --git a/PAYMENT_INTEGRATION_GUIDE.md b/PAYMENT_INTEGRATION_GUIDE.mdnew file mode 100644index 0000000..277b39b--- /dev/null+++ b/PAYMENT_INTEGRATION_GUIDE.md@@ -0,0 +1,47 @@+# Fins & Wings manual UPI integration++This integration uses the YOUPI checkout to display a UPI QR. The customer submits a UTR as a claim. The Fins & Wings admin must compare it with the receiving bank account and make the final decision. A UTR, QR scan, browser callback, observer alert, or signed gateway webhook is not proof of settlement.++## Request and authority flow++1. The Fins & Wings server creates the order in Supabase. It gets the amount from the database order result, then creates a YOUPI session using `method: MANUAL_UPI`, a stable idempotency key, merchant ID, and the server-only merchant API key.+2. YOUPI returns a checkout URL. The browser opens that URL; the merchant key is never sent to the browser.+3. The customer pays in their UPI app and submits their transaction reference in the gateway checkout.+4. YOUPI records `MANUAL_REVIEW` and sends a signed webhook containing the UTR. The Supabase webhook RPC links the event to the exact payment attempt and amount, records the UTR, and leaves the order `pending_verification`.+5. An authenticated Fins & Wings administrator checks the actual receiving account and enters evidence in the admin app. `fw_set_payment_status` atomically records `verified`, `rejected`, or `under_investigation`; a rejection requires a reason.+6. Order fulfilment remains blocked until the admin RPC records `verified` and stock is confirmed.++The `customer_order_hash` capability must remain private to the customer device. The webhook secret and YOUPI merchant API key are different secrets and are server-side only. Rotate the API key through the gateway admin after initial setup and configure the rotated value as `YOUPI_MERCHANT_API_KEY`.++## Server environment++Set these in the customer server environment (Vercel functions or the local server), not in `VITE_*` variables:++- `SUPABASE_URL`+- `SUPABASE_SERVICE_ROLE_KEY`+- `YOUPI_API_URL`+- `YOUPI_MERCHANT_ID`+- `YOUPI_MERCHANT_API_KEY`+- `YOUPI_WEBHOOK_SECRET`+- `CUSTOMER_RETURN_URL`++On YOUPI, set `YOUPI_ALLOWED_RETURN_ORIGINS` and `YOUPI_ALLOWED_ORIGINS` to the exact HTTPS storefront origin(s), comma separated. The return origin must exactly match `CUSTOMER_RETURN_URL`'s origin. No wildcard is supported. The checkout iframe must also be allowed by the checkout portal frame-ancestor configuration.++Apply Supabase migrations in order, including `008_youpi_pg.sql` and `009_youpi_manual_review.sql`, only after reviewing them against the actual project schema. This repository change does not apply migrations to a live Supabase project.++## Status contract++| Gateway | Supabase order | Meaning |+| --- | --- | --- |+| `INITIATED`, `ACTIVE` | `pending_verification` | Checkout opened / awaiting customer payment |+| `MANUAL_REVIEW` | `pending_verification` | Customer submitted a UTR; admin must inspect bank records |+| `FAILED`, `EXPIRED`, `CANCELLED` | unchanged pending status | Attempt ended; this is not a final bank decision |+| Any gateway `SUCCESS`, `OBSERVED_SUCCESS`, or `RECONCILED` | unchanged pending status | Gateway event cannot approve this manual flow |+| Admin `under_investigation` | `under_investigation` | Admin is collecting evidence |+| Admin `verified` / `rejected` | final order decision | Admin decision after bank review |++Retrying a final rejected, verified, or refunded order is blocked. A pending attempt may be retried after it expires or fails.++## Local checks++Use synthetic orders and a test bank/UPI account only. Never treat checkout redirect parameters or client-side events as payment status. Confirm the admin sees the customer UTR and gateway payment ID and that the order remains pending until the RPC succeeds.diff --git a/README.md b/README.mdindex 29efb53..ebebe37 100644--- a/README.md+++ b/README.md@@ -653,6 +653,9 @@ Deep-dive engineering manuals and operational runbooks are available in the [`/d| [`docs/MERCHANT_INTEGRATION.md`](docs/MERCHANT_INTEGRATION.md) | Full developer integration guide, SDK methods & webhooks || [`docs/WHITE_LABEL.md`](docs/WHITE_LABEL.md) | White-label branding customizer, domains & Cloudflare || [`docs/OPERATIONS_TROUBLESHOOTING.md`](docs/OPERATIONS_TROUBLESHOOTING.md) | Production operations, logs, diagnostics & troubleshooting |+| [`PAYMENT_INTEGRATION_GUIDE.md`](PAYMENT_INTEGRATION_GUIDE.md) | Fins & Wings manual UPI checkout, webhook, and admin verification flow |+| [`SECURITY_REMEDIATION_REPORT.md`](SECURITY_REMEDIATION_REPORT.md) | Manual UPI security posture, findings, and remaining blockers |+| [`DEPLOYMENT_CHECKLIST.md`](DEPLOYMENT_CHECKLIST.md) | Production readiness checks; deployment is not included in this work || [`openapi.yaml`](openapi.yaml) | Official OpenAPI 3.0 REST API specification |<br/>diff --git a/SECURITY_REMEDIATION_REPORT.md b/SECURITY_REMEDIATION_REPORT.mdnew file mode 100644index 0000000..20c7ed5--- /dev/null+++ b/SECURITY_REMEDIATION_REPORT.md@@ -0,0 +1,66 @@+# Security remediation report — YOUPI PG manual UPI integration++## Scope and limits++This is a source/configuration review of the checked-out gateway, Fins & Wings customer app, and admin app for the manual UPI integration. It included focused searches for dynamic evaluation, subprocess use, third-party destinations, payment state transitions, browser checkout calls, environment/configuration, migrations, and deploy manifests. It is not a penetration test, a clean-room malware analysis of installed dependencies, or a bank/UPI settlement certification. No live Supabase project, real account, payment, credential file, or deployment was accessed. The gateway's pre-existing local `.env` and secret backups were intentionally not read.++## Security posture++**Do not use the current gateway as a source of payment settlement truth.** This change establishes a manual review flow for Fins & Wings: the customer UTR is a claim, gateway events only update the attempt/UTR, and an authenticated admin decision is the only path to `verified`. Keep the gateway experimental until the production blockers below are addressed.++## Integration changes in this branch++- Fins & Wings server order creation and retry requests now explicitly request `MANUAL_UPI`; amount stays sourced from the Supabase order result.+- Browser checkout SDK no longer creates payment sessions or sends a merchant key. It requires a server-created checkout URL/payment ID.+- Gateway payment creation requires explicit merchant identity and server-side credentials, validates the payment method, binds idempotency to the method, and restricts return URLs to configured origins.+- Checkout allows a UTR submission for manual sessions, stores it in a pending-review state, rejects repeated UTR reuse for the same receiving account, and prevents the legacy “Payment Done” auto-observer flow.+- Automatic observer attribution excludes manual sessions. The manual claim webhook includes customer UTR but cannot mark an order paid in the Supabase RPC.+- Supabase migration 009 makes gateway events non-authoritative and makes admin review atomic, pending-only, evidence-noted, and admin-role gated. Admin rejection requires a reason.+- Browser CORS allow headers include device/customer authentication headers. Basic per-process request throttles are applied to payment creation and UTR submission.++## Findings and remaining risks++### High — Gateway is not independently proven to settle funds++Notification observers, UTR strings, browser events, and signed webhooks cannot prove that funds cleared into the intended receiving account. Manual UTR review reduces automation risk but depends on an admin actually checking bank records and recognizing amount, account, date, reversal, and duplicate-payment issues. Never fulfill from a customer UTR or gateway event alone.++### High — Production persistence is not configured++`render.yaml` selects a free plan, enables SQLite fallback, and defines no durable disk. A restart/ephemeral filesystem may lose payment sessions, outbox items, webhook history, and credentials. Use a production-grade persistent database, backups, restore drills, and durable queue/outbox monitoring before production.++### High — Merchant key and webhook secret backward compatibility++`packages/db/src/repositories/merchant.repository.js` still accepts `webhookSecret` in `verifyApiKey` for legacy merchant compatibility, and initial merchant creation derives the API-key hash from the webhook secret when no API key is supplied. Rotate to an independently generated merchant API key and ensure the database hash is for that key before deployment. Do not share either credential with a browser.++### Medium — Rate limits are process-local++The payment and UTR throttles in `apps/payment-api/src/server.js` are in-memory and reset on restart. They do not coordinate across replicas, and do not replace edge-level limits, abuse monitoring, and durable idempotency controls.++### Medium — CORS and return allowlists must be configured++An empty `YOUPI_ALLOWED_ORIGINS` set denies browser origins and an empty `YOUPI_ALLOWED_RETURN_ORIGINS` rejects supplied return URLs. Configure exact HTTPS origins in each environment and verify iframe frame-ancestor policy separately. Avoid broad wildcard origins.++### Medium — Existing legacy observer functionality remains in the repository++The repository contains Gmail/SMS observer integrations, OAuth handling, device tooling, and subprocess use for local process/tunnel/build operations. The targeted source search found no unexpected `eval`/`new Function` in application runtime source and no unexpected package install lifecycle hooks; dynamic evaluation hits were test harnesses. The subprocesses found were named operational/test tools. This was not a complete behavioral analysis of every observer or installed dependency. If observers are unused, disable their services, revoke their OAuth/app permissions, and remove stored credentials during a separately reviewed cleanup.++### Medium — Browser SDK does not establish payment identity++The old pattern treating browser `data-youpi-key` as session-creation authority is removed from the current SDK path. Merchants must create checkout sessions on their server and pass only the checkout URL/payment ID to the browser. Treat payment IDs as bearer references; continue enforcing device/session binding and minimal public state.++### Medium — Customer webhook replay and database authority++The customer webhook verifies raw-body HMAC, event name, and matching delivery ID. Database idempotency is enforced by delivery ID. Protect the webhook secret and service-role key, and ensure `fw_apply_youpi_event` remains service-role-only. Migration 009 must be reviewed and tested against the live schema before application.++## Malware and hidden behavior review++No obvious credential exfiltration, cryptocurrency miner, obfuscated runtime, or unexpected remote-code execution was identified by the focused source search. Observed outbound destinations are the configured Supabase/YOUPI services, declared Google Maps Routes API, routing fallback, merchant webhook endpoints, and the observer/OAuth services described by the project. Endpoint allowlists, DNS rebinding, and runtime network traffic were not exhaustively validated. `npm audit --omit=dev --audit-level=high` completed with zero reported vulnerabilities. The package lock has a pre-existing worktree diff and was not changed by this implementation; inspect that diff before release.++## Required follow-up before production++1. Independently review this branch and all user-preserved gateway edits; inspect package-lock delta and run a clean dependency advisory audit.+2. Rotate and separate merchant API key, webhook secret, admin token, JWT secret, and encryption key; confirm all secrets in Git history and deployment logs are handled.+3. Choose persistent production database/hosting and implement backups, restore drills, multi-instance throttling, egress restrictions, monitoring, and incident response.+4. Review/apply Supabase migrations through the normal DBA workflow; verify grants, RLS, audit actor identity, pending/final state transitions, and order fulfilment guard.+5. Test the full checkout and bank-verification lifecycle on a sandbox account, including duplicate UTR, webhook replay, refunds/reversals, failure/expiry, and admin decision races.+6. Obtain payment provider/bank/legal compliance approval and independent payment-security review before accepting live funds.diff --git a/apps/checkout-portal/src/__tests__/issue-64-hardening.test.js b/apps/checkout-portal/src/__tests__/issue-64-hardening.test.jsindex 50a346e..b326242 100644--- a/apps/checkout-portal/src/__tests__/issue-64-hardening.test.js+++ b/apps/checkout-portal/src/__tests__/issue-64-hardening.test.js@@ -98,9 +98,9 @@ describe('Issue #64 hardening: returnUrl, branding sinks, postMessage, framing',describe('checkout.html returnUrl success path', () => {test('href and navigation use the sanitized url, never the raw one', () => {- assert.ok(checkoutView.includes('const safeReturnUrl = sanitizeRedirectUrl(data.returnUrl);'));- assert.ok(checkoutView.includes('btnReturn.href = safeReturnUrl;'));- assert.ok(checkoutView.includes('window.location.href = safeReturnUrl;'));+ assert.ok(checkoutView.includes('const safeReturn = sanitizeRedirectUrl(effectiveReturnUrl);'));+ assert.ok(checkoutView.includes('btnReturn.href = safeReturn;'));+ assert.ok(checkoutView.includes('window.location.href = safeReturn;'));assert.equal(checkoutView.includes('btnReturn.href = data.returnUrl;'), false);assert.equal(checkoutView.includes('window.location.href = data.returnUrl;'), false);});@@ -209,6 +209,8 @@ describe('Issue #64 hardening: returnUrl, branding sinks, postMessage, framing',let merchantId;before(async () => {+ process.env.NODE_ENV = 'test';+ process.env.YOUPI_ALLOWED_RETURN_ORIGINS = 'https://store.test';testDb = new Database({ inMemory: true });apiInstance = await startPaymentApi(6194, testDb);apiBaseUrl = `http://localhost:${apiInstance.port}`;@@ -225,7 +227,7 @@ describe('Issue #64 hardening: returnUrl, branding sinks, postMessage, framing',const url = new URL('/api/v1/payments', apiBaseUrl);const req = http.request(url, {method: 'POST',- headers: authHeadersFor('/api/v1/payments', { 'Content-Type': 'application/json' })+ headers: authHeadersFor('/api/v1/payments', { 'Content-Type': 'application/json', 'X-Merchant-Id': merchantId })}, res => {let data = '';res.on('data', chunk => { data += chunk; });@@ -275,6 +277,13 @@ describe('Issue #64 hardening: returnUrl, branding sinks, postMessage, framing',assert.equal(stored.returnUrl, 'https://store.test/success');});+ test('rejects unallowlisted and userinfo-bearing return URLs', async () => {+ for (const returnUrl of ['https://elsewhere.test/return', 'https://[email protected]/return']) {+ const res = await post({ orderId: `ISSUE64-BLOCK-${Date.now()}-${Math.random()}`, amount: '100.00', returnUrl });+ assert.equal(res.status, 400);+ }+ });+test('a missing returnUrl is still allowed', async () => {const res = await post({orderId: `ISSUE64-NONE-${Date.now()}`,diff --git a/apps/checkout-portal/src/sdk/youpi-checkout.js b/apps/checkout-portal/src/sdk/youpi-checkout.jsindex 7961427..4f804cf 100644--- a/apps/checkout-portal/src/sdk/youpi-checkout.js+++ b/apps/checkout-portal/src/sdk/youpi-checkout.js@@ -8,7 +8,8 @@** IMPORTANT SECURITY NOTE:* Browser events and client-side callbacks are strictly for UI and user experience.- * Authoritative proof of payment MUST ALWAYS come from server-to-server HMAC-SHA256 signed webhooks.+ * Browser callbacks are not proof of settlement. For manual UPI, only the merchant's+ * independent bank-account review may approve payment.*/(function (globalScope) {@@ -51,7 +52,8 @@const origin = scriptUrl ? scriptUrl.origin : (window.location.protocol + '//' + window.location.hostname + ':7000');return {- key: script.getAttribute('data-youpi-key') || script.getAttribute('data-key') || script.getAttribute('data-merchant-id') || '',+ // Merchant identifiers are public. Secret API credentials belong only on merchant servers.+ merchantId: script.getAttribute('data-merchant-id') || '',apiUrl: script.getAttribute('data-api-url') || origin,portalUrl: script.getAttribute('data-portal-url') || script.getAttribute('data-checkout-url') || origin,currency: script.getAttribute('data-currency') || 'INR',@@ -67,32 +69,12 @@const scriptConfig = getScriptConfig();- /**- * The gateway stores only an absolute http(s) returnUrl, so a relative successUrl is- * resolved against this storefront's own origin before it is sent. Without this a- * merchant using `data-success-url="/success"` would get a 400 from the API.- * @param {string} [raw]- * @returns {string|undefined} absolute http(s) URL, or undefined when unusable- */- function resolveReturnUrl(raw) {- if (!raw) return undefined;- try {- const base = (typeof window !== 'undefined' && window.location) ? window.location.href : undefined;- const parsed = new URL(raw, base);- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;- return parsed.href;- } catch (e) {- return undefined;- }- }-/*** YoupiCheckout class*/class YoupiCheckout {/*** @param {{- * key?: string,* order_id?: string,* orderId?: string,* amount?: number | string,@@ -131,7 +113,6 @@: 'http://localhost:6100';this.options = Object.assign({- key: scriptConfig.key || '',order_id: '',orderId: '',amount: 0,@@ -195,60 +176,7 @@return instance;}- // Otherwise, call YOUPI PG to create the payment session- try {- const orderId = instance.options.orderId || `ORDER-${Date.now()}`;- instance.options.orderId = orderId;- instance.options.order_id = orderId;-- const customer = instance.options.customer || {};- const custPayload = {- fullName: customer.name || customer.fullName || '',- email: customer.email || '',- phoneNumber: customer.phone || customer.phoneNumber || customer.mobileNumber || ''- };-- const createRes = await fetch(`${instance.options.apiUrl}/api/v1/payments`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- ...(instance.options.key ? { 'X-Merchant-Id': instance.options.key } : {})- },- body: JSON.stringify({- orderId: orderId,- amount: instance.options.amount,- currency: instance.options.currency || 'INR',- customer: (custPayload.email || custPayload.phoneNumber || custPayload.fullName) ? custPayload : undefined,- description: instance.options.description,- metadata: instance.options.metadata,- returnUrl: resolveReturnUrl(instance.options.successUrl)- })- });-- const data = await createRes.json();- if (!createRes.ok || !data.checkoutUrl) {- const errMsg = data.error || data.message || `Failed to create payment session (HTTP ${createRes.status})`;- const failResult = {- status: 'FAILED',- order_id: orderId,- reason: errMsg,- error: errMsg- };- YoupiCheckout._emitEvent('youpi:payment:failed', failResult);- YoupiCheckout._emitEvent('youpi:payment:result', failResult);- if (typeof instance.options.onFailed === 'function') instance.options.onFailed(failResult);- if (typeof instance.options.onPaymentFailed === 'function') instance.options.onPaymentFailed(failResult);- throw new Error(errMsg);- }-- instance.options.paymentId = data.paymentId;- instance.options.checkoutUrl = data.checkoutUrl;- instance.open();- return instance;- } catch (err) {- console.error('[YouPI JS] Payment initialization error:', err.message);- throw err;- }+ throw new Error('Create the payment on your server using trusted order data, then pass checkoutUrl or paymentId to Youpi.pay(). Never put a merchant API secret in browser code.');}/**diff --git a/apps/checkout-portal/src/sdk/youpi.js b/apps/checkout-portal/src/sdk/youpi.jsindex 4f8ac8e..7839f2f 100644--- a/apps/checkout-portal/src/sdk/youpi.js+++ b/apps/checkout-portal/src/sdk/youpi.js@@ -8,7 +8,8 @@** IMPORTANT SECURITY NOTE:* Browser events and client-side callbacks are strictly for UI and user experience.- * Authoritative proof of payment MUST ALWAYS come from server-to-server HMAC-SHA256 signed webhooks.+ * Browser callbacks are not proof of settlement. For manual UPI, only the merchant's+ * independent bank-account review may approve payment.*/(function (globalScope) {@@ -51,7 +52,8 @@const origin = scriptUrl ? scriptUrl.origin : (window.location.protocol + '//' + window.location.hostname + ':7000');return {- key: script.getAttribute('data-youpi-key') || script.getAttribute('data-key') || script.getAttribute('data-merchant-id') || '',+ // Merchant identifiers are public. Secret API credentials belong only on merchant servers.+ merchantId: script.getAttribute('data-merchant-id') || '',apiUrl: script.getAttribute('data-api-url') || origin,portalUrl: script.getAttribute('data-portal-url') || script.getAttribute('data-checkout-url') || origin,currency: script.getAttribute('data-currency') || 'INR',@@ -67,32 +69,12 @@const scriptConfig = getScriptConfig();- /**- * The gateway stores only an absolute http(s) returnUrl, so a relative successUrl is- * resolved against this storefront's own origin before it is sent. Without this a- * merchant using `data-success-url="/success"` would get a 400 from the API.- * @param {string} [raw]- * @returns {string|undefined} absolute http(s) URL, or undefined when unusable- */- function resolveReturnUrl(raw) {- if (!raw) return undefined;- try {- const base = (typeof window !== 'undefined' && window.location) ? window.location.href : undefined;- const parsed = new URL(raw, base);- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;- return parsed.href;- } catch (e) {- return undefined;- }- }-/*** YoupiCheckout class*/class YoupiCheckout {/*** @param {{- * key?: string,* order_id?: string,* orderId?: string,* amount?: number | string,@@ -131,7 +113,6 @@: 'http://localhost:6100';this.options = Object.assign({- key: scriptConfig.key || '',order_id: '',orderId: '',amount: 0,@@ -195,60 +176,7 @@return instance;}- // Otherwise, call YOUPI PG to create the payment session- try {- const orderId = instance.options.orderId || `ORDER-${Date.now()}`;- instance.options.orderId = orderId;- instance.options.order_id = orderId;-- const customer = instance.options.customer || {};- const custPayload = {- fullName: customer.name || customer.fullName || '',- email: customer.email || '',- phoneNumber: customer.phone || customer.phoneNumber || customer.mobileNumber || ''- };-- const createRes = await fetch(`${instance.options.apiUrl}/api/v1/payments`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- ...(instance.options.key ? { 'X-Merchant-Id': instance.options.key } : {})- },- body: JSON.stringify({- orderId: orderId,- amount: instance.options.amount,- currency: instance.options.currency || 'INR',- customer: (custPayload.email || custPayload.phoneNumber || custPayload.fullName) ? custPayload : undefined,- description: instance.options.description,- metadata: instance.options.metadata,- returnUrl: resolveReturnUrl(instance.options.successUrl)- })- });-- const data = await createRes.json();- if (!createRes.ok || !data.checkoutUrl) {- const errMsg = data.error || data.message || `Failed to create payment session (HTTP ${createRes.status})`;- const failResult = {- status: 'FAILED',- order_id: orderId,- reason: errMsg,- error: errMsg- };- YoupiCheckout._emitEvent('youpi:payment:failed', failResult);- YoupiCheckout._emitEvent('youpi:payment:result', failResult);- if (typeof instance.options.onFailed === 'function') instance.options.onFailed(failResult);- if (typeof instance.options.onPaymentFailed === 'function') instance.options.onPaymentFailed(failResult);- throw new Error(errMsg);- }-- instance.options.paymentId = data.paymentId;- instance.options.checkoutUrl = data.checkoutUrl;- instance.open();- return instance;- } catch (err) {- console.error('[YouPI JS] Payment initialization error:', err.message);- throw err;- }+ throw new Error('Create the payment on your server using trusted order data, then pass checkoutUrl or paymentId to Youpi.pay(). Never put a merchant API secret in browser code.');}/**diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.htmlindex 0cb0fb2..2786390 100644--- a/apps/checkout-portal/src/views/checkout.html+++ b/apps/checkout-portal/src/views/checkout.html@@ -1650,6 +1650,14 @@function renderState(data) {state = data;+ const manualUtrPanel = document.getElementById('manualUtrPanel');+ const manualUtrPending = document.getElementById('manualUtrPending');+ const manualUtrButton = document.getElementById('btnContinuePayment');+ const methodSelector = document.getElementById('paymentMethodSelectorBar');+ if (manualUtrPanel) manualUtrPanel.style.display = data.method === 'MANUAL_UPI' && data.status === 'ACTIVE' ? 'block' : 'none';+ if (manualUtrPending) manualUtrPending.style.display = data.method === 'MANUAL_UPI' && data.status === 'MANUAL_REVIEW' ? 'block' : 'none';+ if (manualUtrButton && data.method === 'MANUAL_UPI') manualUtrButton.style.display = 'none';+ if (methodSelector && data.method === 'MANUAL_UPI') methodSelector.style.display = 'none';const b = data.branding || {};const appName = b.appName || 'YouPI PG';const merchantName = data.merchantName || 'Merchant Checkout';@@ -2016,6 +2024,22 @@return;}+ if (data.status === 'MANUAL_REVIEW' && data.method === 'MANUAL_UPI') {+ closeProcessingModal();+ const bar = document.getElementById('paymentMethodSelectorBar');+ if (bar) bar.style.display = 'none';+ hideAllContent();+ const upiView = document.getElementById('viewUpiContent');+ if (upiView) upiView.hidden = false;+ const footer = document.getElementById('ypgStickyFooter');+ if (footer) footer.style.display = 'flex';+ if (manualUtrPanel) manualUtrPanel.style.display = 'none';+ if (manualUtrPending) manualUtrPending.style.display = 'block';+ if (manualUtrButton) manualUtrButton.style.display = 'none';+ const msg = document.getElementById('manualUtrMessage');+ if (msg) msg.textContent = '';+ return;+ }if (data.status === 'MANUAL_REVIEW') {closeProcessingModal();closeCancelPaymentModal();@@ -2257,7 +2281,7 @@if (vCard) vCard.hidden = false;document.getElementById('ypgStickyFooter').style.display = 'none';} else {- // Default: UPI QR (CRITICAL INVARIANT: ALWAYS SHOWS QR AND RUNS 5:00 TIMER REGARDLESS OF GREEN/YELLOW/RED)+ // Default: UPI QR. Manual mode adds a customer UTR claim and never auto-confirms.document.getElementById('viewUpiContent').hidden = false;document.getElementById('ypgStickyFooter').style.display = 'flex';loadQrSvg();@@ -2275,7 +2299,9 @@}// Initialize button hidden until 4:00 has elapsed- if (btnContinue && remainingSec > 240) {+ if (data.method === 'MANUAL_UPI' && btnContinue) {+ btnContinue.style.display = 'none';+ } else if (btnContinue && remainingSec > 240) {btnContinue.style.display = 'none';} else if (btnContinue) {btnContinue.style.display = 'block';@@ -2628,6 +2654,31 @@} catch (e) { }}+ async function submitManualUtr() {+ const input = document.getElementById('manualUtrInput');+ const button = document.getElementById('manualUtrSubmit');+ const message = document.getElementById('manualUtrMessage');+ const utr = String(input?.value || '').trim();+ if (!/^[A-Za-z0-9-]{6,35}$/.test(utr)) {+ if (message) message.textContent = 'Enter a valid UTR/reference (6–35 letters, digits or hyphens).';+ return;+ }+ if (button) { button.disabled = true; button.textContent = 'Submitting…'; }+ if (message) message.textContent = '';+ try {+ const response = await fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/manual-utr`, {+ method: 'POST', headers: { ...getApiHeaders(), 'Content-Type': 'application/json' }, body: JSON.stringify({ utr })+ });+ const result = await response.json().catch(() => ({}));+ if (!response.ok) throw new Error(result.error || 'Could not submit reference.');+ if (message) message.textContent = 'Submitted. Your order remains unpaid until the merchant verifies the bank transaction.';+ await loadState();+ } catch (error) {+ if (message) message.textContent = error?.message || 'Could not submit reference. Try again.';+ if (button) { button.disabled = false; button.textContent = 'Submit'; }+ }+ }+// --- SINGLE ACTIVE PAYMENT SESSION CONFLICT RESOLUTION ---let activeConflictSessionId = null;diff --git a/apps/checkout-portal/src/views/partials/footer.html b/apps/checkout-portal/src/views/partials/footer.htmlindex 159616c..6189e7e 100644--- a/apps/checkout-portal/src/views/partials/footer.html+++ b/apps/checkout-portal/src/views/partials/footer.html@@ -23,6 +23,15 @@Payment Done — Check My Payment</button></div>+ <div id="manualUtrPanel" style="display:none; width:100%; padding:12px 4px 4px;">+ <label for="manualUtrInput" style="display:block; font-weight:600; margin-bottom:6px;">UPI transaction reference (UTR)</label>+ <div style="display:flex; gap:8px;">+ <input id="manualUtrInput" inputmode="text" autocomplete="off" maxlength="35" aria-describedby="manualUtrMessage" placeholder="Enter 6–35 letters or digits" style="flex:1; min-width:0; padding:10px; border:1px solid #cbd5e1; border-radius:8px;">+ <button id="manualUtrSubmit" type="button" onclick="submitManualUtr()" style="padding:10px 14px; border:0; border-radius:8px; background:#0957cb; color:white; font-weight:600;">Submit</button>+ </div>+ <div id="manualUtrMessage" role="status" aria-live="polite" style="margin-top:8px; font-size:13px;"></div>+ </div>+ <div id="manualUtrPending" role="status" style="display:none; width:100%; padding:10px 4px; font-weight:600;">Reference submitted. Waiting for the merchant to verify the payment in their bank account.</div><!-- ORDER BREAKDOWN POPUP DRAWER --><div class="ypg-details-drawer" id="orderDetailsDrawer">diff --git a/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js b/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.jsindex 418075f..47f44d5 100644--- a/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js+++ b/apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import crypto from 'node:crypto';import http from 'node:http';import { Database } from '@youpi/db';+import { hashApiKey } from '../../../../packages/db/src/repositories/merchant.repository.js';import { startServer as startPaymentApi } from '../../../payment-api/src/index.js';import { startCoinWalletStore } from '../index.js';import { generateHmac } from '@youpi/common';@@ -15,20 +16,24 @@ describe('Coin Top-Up Wallet Demo Store Integration Tests', () => {const storeSecret = 'wallet_store_secret_9988';before(async () => {+ process.env.NODE_ENV = 'test';+ process.env.YOUPI_ALLOWED_RETURN_ORIGINS = 'http://localhost:5099';testDb = new Database({ inMemory: true });apiInstance = await startPaymentApi(6193, testDb);// Update demo merchant with our store webhook secret- testDb.execute('UPDATE merchants SET webhook_secret = ?, webhook_url = ? WHERE id = ?', [+ testDb.execute('UPDATE merchants SET webhook_secret = ?, webhook_url = ?, api_key_hash = ? WHERE id = ?', [storeSecret,'http://localhost:5099/api/webhook',+ hashApiKey(storeSecret),'00000000-0000-0000-0000-000000000001']);storeInstance = await startCoinWalletStore(5099, {gatewayApiUrl: `http://localhost:${apiInstance.port}`,merchantId: '00000000-0000-0000-0000-000000000001',- webhookSecret: storeSecret+ webhookSecret: storeSecret,+ publicBaseUrl: 'http://localhost:5099'});storeBaseUrl = `http://localhost:${storeInstance.port}`;diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.htmlindex 632ecec..bbf2b45 100644--- a/apps/merchant-admin/src/views/admin.html+++ b/apps/merchant-admin/src/views/admin.html@@ -7787,7 +7787,7 @@const currentM = merchantsList.find(m => m.id === currentMerchantId);const host = window.location.origin;- const snippet = `<script src="${host}/youpi.js" data-youpi-key="${currentMerchantId}"></script>`;+ const snippet = `<script src="${host}/youpi.js" data-youpi-key="${currentMerchantId}"><\/script>`;if (snippetEl) snippetEl.value = snippet;if (keyEl) {diff --git a/apps/payment-api/src/__tests__/auth-guard.test.js b/apps/payment-api/src/__tests__/auth-guard.test.jsindex f061428..6bea638 100644--- a/apps/payment-api/src/__tests__/auth-guard.test.js+++ b/apps/payment-api/src/__tests__/auth-guard.test.js@@ -16,12 +16,14 @@ describe('Auth guard: admin, observer and force-success endpoints', () => {method,headers: {'Content-Type': 'application/json',+ ...(path.startsWith('/api/v1/payments') ? { 'X-Merchant-Id': '00000000-0000-0000-0000-000000000001' } : {}),...(token ? { Authorization: `Bearer ${token}` } : {})},body: body ? JSON.stringify(body) : undefined});before(async () => {+ process.env.NODE_ENV = 'test';db = new Database({ inMemory: true });api = await startPaymentApi(6197, db);baseUrl = `http://localhost:${api.port}`;diff --git a/apps/payment-api/src/__tests__/counter-payments.test.js b/apps/payment-api/src/__tests__/counter-payments.test.jsindex e78344f..a01fc1f 100644--- a/apps/payment-api/src/__tests__/counter-payments.test.js+++ b/apps/payment-api/src/__tests__/counter-payments.test.js@@ -12,6 +12,7 @@ describe('Phase 15: Counter Payments (Cash & Card at Counter)', () => {let testDb;before(async () => {+ process.env.NODE_ENV = 'test';testDb = new Database({ inMemory: true });apiInstance = await startPaymentApi(6194, testDb);baseUrl = `http://localhost:${apiInstance.port}`;@@ -27,7 +28,9 @@ describe('Phase 15: Counter Payments (Cash & Card at Counter)', () => {const url = new URL(path, baseUrl);const req = http.request(url, {method: options.method || 'GET',- headers: { 'Content-Type': 'application/json', ...authHeadersFor(path), ...(options.headers || {}) }+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(path),+ ...(path.startsWith('/api/v1/payments') ? { 'X-Merchant-Id': '00000000-0000-0000-0000-000000000001' } : {}),+ ...(options.headers || {}) }}, res => {let data = '';res.on('data', chunk => { data += chunk; });diff --git a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.jsindex 85af595..80e74bd 100644--- a/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js+++ b/apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js@@ -23,6 +23,7 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2let testDb;before(async () => {+ process.env.NODE_ENV = 'test';testDb = new Database({ inMemory: true });apiInstance = await startPaymentApi(6291, testDb);baseUrl = `http://localhost:${apiInstance.port}`;@@ -661,9 +662,7 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2const dedicatedApiKey = 'mk_live_dedicated_merchant_api_key_6369';merchantRepo.update(merchantId, { apiKey: dedicatedApiKey });- // 1. Completely unauthenticated request naming the DEFAULT merchant -> allowed.- // The public one-script integration (the browser SDK) cannot carry a merchant- // secret, so this path has to stay open for the gateway's own merchant.+ // 1. Even the default merchant requires server-side authentication.const url = new URL('/api/v1/payments', baseUrl);const unauthRes = await new Promise((resolve, reject) => {const req = http.request(url, {@@ -678,7 +677,8 @@ describe('Gateway Hardening & Invariant Protection Test Suite (#23, #25, #26, #2req.write(JSON.stringify({ orderId: `UNAUTH-${Date.now()}`, amount: '100.00' }));req.end();});- assert.equal(unauthRes.status, 201);+ assert.equal(unauthRes.status, 401);+ assert.equal(unauthRes.body.code, 'MISSING_MERCHANT_KEY');// 1b. An unauthenticated request naming a DIFFERENT merchant -> 401, so an anonymous// caller still cannot inject sessions into another tenant.diff --git a/apps/payment-api/src/__tests__/payment-api.test.js b/apps/payment-api/src/__tests__/payment-api.test.jsindex 86a2c26..4bfe2bc 100644--- a/apps/payment-api/src/__tests__/payment-api.test.js+++ b/apps/payment-api/src/__tests__/payment-api.test.js@@ -26,8 +26,11 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {let testDb;let merchantSecret;let merchantWebhookUrl;+ let merchantId;before(async () => {+ process.env.NODE_ENV = 'test';+ process.env.YOUPI_ALLOWED_RETURN_ORIGINS = 'https://merchant.example';testDb = new Database({ inMemory: true });// Use an ephemeral random port (e.g. 0 or high port 6199) to prevent collisionsserverInstance = await startServer(6199, testDb);@@ -36,6 +39,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {// merchant, so read the seeded secret through the repository (the raw column is// encrypted at rest).const seededMerchant = new MerchantRepository(testDb).findAll()[0];+ merchantId = seededMerchant.id;merchantSecret = seededMerchant.webhookSecret;merchantWebhookUrl = seededMerchant.webhookUrl;});@@ -51,7 +55,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {const url = new URL(path, options.baseUrl || baseUrl);const reqOpts = {method: options.method || 'GET',- headers: authHeadersFor(path, options.headers || {})+ headers: authHeadersFor(path, { ...(path.startsWith('/api/v1/payments') ? { 'X-Merchant-Id': merchantId } : {}), ...(options.headers || {}) })};const req = http.request(url, reqOpts, res => {@@ -1149,7 +1153,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {assert.ok(codAfterCancel.body.error.includes('Cannot place COD order for terminal session'));});- test('Merchant API Key rotation, inspection, and flexible data-youpi-key / X-Merchant-Id resolution (Issue #89)', async () => {+ test('Merchant API key rotation requires X-Merchant-Key and rejects public-key/placeholder authentication', async () => {// 1. Inspect merchant settings via admin APIconst settingsBefore = await request('/api/v1/admin/merchant-settings');assert.equal(settingsBefore.status, 200);@@ -1185,7 +1189,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {});assert.equal(payWithKeyHeader.status, 201);- // 5. Create payment when developer passes mk_live_... directly in data-youpi-key (sent as X-Merchant-Id by youpi.js)+ // A secret in X-Merchant-Id is not a credential flow; the SDK never sends it.const payWithKeyAsId = await request('/api/v1/payments', {method: 'POST',headers: {@@ -1196,7 +1200,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {amount: '135.00'}});- assert.equal(payWithKeyAsId.status, 201);+ assert.equal(payWithKeyAsId.status, 400);// 6. Create payment when developer leaves documentation placeholder YOUR_MERCHANT_KEY in data-youpi-keyconst payWithPlaceholder = await request('/api/v1/payments', {@@ -1209,7 +1213,7 @@ describe('Payment API End-to-End HTTP Integration Tests', () => {amount: '145.00'}});- assert.equal(payWithPlaceholder.status, 201);+ assert.equal(payWithPlaceholder.status, 400);});});});diff --git a/apps/payment-api/src/__tests__/phase1-observed-success.test.js b/apps/payment-api/src/__tests__/phase1-observed-success.test.jsindex 665b8ea..2ec7680 100644--- a/apps/payment-api/src/__tests__/phase1-observed-success.test.js+++ b/apps/payment-api/src/__tests__/phase1-observed-success.test.js@@ -149,7 +149,9 @@ describe('Phase 1 observed success and matching safety', () => {const url = new URL(pathname, baseUrl);const req = http.request(url, {method: options.method || 'GET',- headers: { 'Content-Type': 'application/json', ...authHeadersFor(pathname), ...(options.headers || {}) }+ headers: { 'Content-Type': 'application/json', ...authHeadersFor(pathname),+ ...(pathname.startsWith('/api/v1/payments') ? { 'X-Merchant-Id': '00000000-0000-0000-0000-000000000001' } : {}),+ ...(options.headers || {}) }}, res => {let data = '';res.on('data', chunk => { data += chunk; });diff --git a/apps/payment-api/src/routes/checkout.routes.js b/apps/payment-api/src/routes/checkout.routes.jsindex 760acc6..3fd6e78 100644--- a/apps/payment-api/src/routes/checkout.routes.js+++ b/apps/payment-api/src/routes/checkout.routes.js@@ -506,7 +506,7 @@ export function registerCheckoutRoutes(server, ctx) {if (!receivingAccount && snapshot?.id) {receivingAccount = ctx.accountRepo.findById(snapshot.id);}- if (!receivingAccount && session.method === 'UPI') {+ if (!receivingAccount && [PaymentMethod.UPI, PaymentMethod.MANUAL_UPI].includes(session.method)) {receivingAccount = ctx.accountRepo.findActiveForMerchant(session.merchantId);}@@ -1036,6 +1036,65 @@ export function registerCheckoutRoutes(server, ctx) {});});+ // Manual UTR is a customer claim for independent review, never a payment confirmation.+ server.post('/api/v1/checkout/:id/manual-utr', async (req, res, params) => {+ const body = await HttpServer.parseBody(req).catch(() => ({}));+ const session = ctx.sessionRepo.findById(params.id);+ if (!session) {+ HttpServer.json(res, 404, { error: 'Payment session not found.' });+ return;+ }+ if (session.method !== PaymentMethod.MANUAL_UPI) {+ HttpServer.json(res, 409, { error: 'This checkout does not use manual UPI verification.' });+ return;+ }+ if (session.status !== PaymentStatus.ACTIVE && session.status !== PaymentStatus.MANUAL_REVIEW) {+ HttpServer.json(res, 409, { error: 'This checkout is no longer accepting a transaction reference.' });+ return;+ }+ const deviceAccess = checkSessionDeviceAccess(session, req, body, ctx);+ if (!deviceAccess.allowed) {+ HttpServer.json(res, deviceAccess.statusCode || 409, deviceAccess.body);+ return;+ }+ const utr = String(body.utr || body.reference || '').trim();+ if (!/^[A-Za-z0-9-]{6,35}$/.test(utr)) {+ HttpServer.json(res, 400, { error: 'Enter a valid UPI reference (6–35 letters or digits).' });+ return;+ }+ try {+ const updated = ctx.sessionRepo.submitManualUtr(session.id, utr);+ if (updated.status === PaymentStatus.MANUAL_REVIEW && session.status !== PaymentStatus.MANUAL_REVIEW) {+ ctx.eventEmitter?.emit('PAYMENT.MANUAL_REVIEW', {+ paymentId: updated.id,+ orderId: updated.orderId,+ merchantId: updated.merchantId,+ amountPaise: updated.amountPaise,+ reason: 'CUSTOMER_UTR_SUBMITTED'+ });+ server.broadcastSse(updated.id, 'status_change', {+ status: PaymentStatus.MANUAL_REVIEW,+ settlementState: 'PENDING_VERIFICATION'+ });+ }+ HttpServer.json(res, 200, {+ paymentId: updated.id,+ orderId: updated.orderId,+ status: 'PENDING_VERIFICATION',+ settlementState: 'PENDING_VERIFICATION',+ customerUtr: updated.customerUtr,+ utrSubmittedAt: updated.utrSubmittedAt?.toISOString() || null,+ message: 'Payment submitted. The merchant must verify it in the bank account.'+ });+ } catch (err) {+ const duplicate = String(err?.message || '').includes('idx_manual_upi_utr_per_receiving_account')+ || String(err?.message || '').includes('UNIQUE constraint failed');+ HttpServer.json(res, duplicate ? 409 : 400, {+ error: duplicate ? 'This UPI reference has already been submitted.' : (err.message || 'Could not submit the UPI reference.')+ });+ }+ });+// POST /api/v1/checkout/:id/payment-doneserver.post('/api/v1/checkout/:id/payment-done', async (req, res, params) => {const session = ctx.sessionRepo.findById(params.id);@@ -1044,6 +1103,11 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ if (session.method === PaymentMethod.MANUAL_UPI) {+ HttpServer.json(res, 409, { error: 'Manual UPI checkouts require a transaction reference; automatic observer verification is disabled.' });+ return;+ }+const deviceAccess = checkSessionDeviceAccess(session, req, null, ctx);if (!deviceAccess.allowed) {HttpServer.json(res, deviceAccess.statusCode || 409, deviceAccess.body);@@ -1172,6 +1236,10 @@ export function registerCheckoutRoutes(server, ctx) {return;}+ if (session.method === PaymentMethod.MANUAL_UPI && method !== PaymentMethod.MANUAL_UPI) {+ HttpServer.json(res, 409, { error: 'Manual UPI sessions cannot switch into an automatic payment flow.' });+ return;+ }const validMethods = [PaymentMethod.UPI, PaymentMethod.COD, PaymentMethod.CASH_COUNTER, PaymentMethod.CARD_COUNTER];if (!validMethods.includes(method)) {HttpServer.json(res, 400, { error: `Invalid payment method '${method}'. Allowed: ${validMethods.join(', ')}` });diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.jsindex 1c8b588..19875ea 100644--- a/apps/payment-api/src/routes/payments.routes.js+++ b/apps/payment-api/src/routes/payments.routes.js@@ -1,5 +1,5 @@import { HttpServer } from '../server.js';-import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, safeEqual, verifyHmac } from '@youpi/common';+import { toPaise, toRupeesString, resolveRuntimeUrls, PaymentStatus, PaymentMethod } from '@youpi/common';import { isTerminalStatus, toPublicOutcome, settlementStateFor, verifyRegisteredDeviceCredentials } from '@youpi/core';import { isAdminRequest, isPaymentOwner } from '../auth-guard.js';import { checkUpiServerHealth, observerHealthEnforced, upiObserversAcceptingPayments } from './checkout.routes.js';@@ -54,24 +54,14 @@ export function registerPaymentRoutes(server, ctx) {'YOUR_MERCHANT_ID']);let merchant = null;- let matchedViaApiKeyInMerchantId = false;-if (rawMerchantId && !docPlaceholders.has(rawMerchantId.toUpperCase())) {merchant = ctx.merchantRepo.findById(rawMerchantId);if (!merchant && typeof ctx.merchantRepo.findBySlug === 'function') {merchant = ctx.merchantRepo.findBySlug(rawMerchantId);}- if (!merchant && typeof ctx.merchantRepo.verifyApiKey === 'function') {- // Support developers who put their secret Merchant API Key (`mk_live_...` / webhookSecret) into `data-youpi-key` / `X-Merchant-Id`- const allMerchants = ctx.merchantRepo.findAll();- const byKey = allMerchants.find(m => ctx.merchantRepo.verifyApiKey(m, rawMerchantId));- if (byKey) {- merchant = byKey;- matchedViaApiKeyInMerchantId = true;- }- }} else {- merchant = ctx.merchantRepo.getDefault ? ctx.merchantRepo.getDefault() : (ctx.merchantRepo.findById('00000000-0000-0000-0000-000000000001') || ctx.merchantRepo.findAll()[0]);+ HttpServer.json(res, 400, { error: 'X-Merchant-Id is required.' });+ return;}if (!merchant) {@@ -81,47 +71,20 @@ export function registerPaymentRoutes(server, ctx) {const presentedMerchantKey = req.headers['x-merchant-key'] !== undefined? req.headers['x-merchant-key']- : (body.merchantKey !== undefined ? body.merchantKey : (matchedViaApiKeyInMerchantId ? rawMerchantId : undefined));- const presentedOrderToken = req.headers['x-order-token'] || body.orderToken;-+ : undefined;if (presentedMerchantKey !== undefined && presentedMerchantKey !== null) {const keyValid = typeof ctx.merchantRepo.verifyApiKey === 'function'- ? ctx.merchantRepo.verifyApiKey(merchant, String(presentedMerchantKey))- : (Boolean(merchant.webhookSecret) && safeEqual(String(presentedMerchantKey).trim(), merchant.webhookSecret));+ && ctx.merchantRepo.verifyApiKey(merchant, String(presentedMerchantKey));if (!keyValid) {HttpServer.json(res, 401, { error: 'Invalid merchant key', code: 'INVALID_MERCHANT_KEY' });return;}- } else if (presentedOrderToken) {- let tokenAmountPaise;- try {- tokenAmountPaise = toPaise(body.amount);- } catch {- tokenAmountPaise = -1n;- }- const tokenCurrency = (body.currency || 'INR').toUpperCase();- const canonicalOrderPayload = `${merchant.id}:${body.orderId || ''}:${tokenAmountPaise.toString()}:${tokenCurrency}`;- const rawTokenSig = String(presentedOrderToken).replace(/^sha256=/, '').trim();- if (!merchant.webhookSecret || !verifyHmac(canonicalOrderPayload, merchant.webhookSecret, rawTokenSig)) {- HttpServer.json(res, 401, { error: 'Invalid order token', code: 'INVALID_ORDER_TOKEN' });- return;- }} else if (!isAdminRequest(req)) {- // No credential was presented. The public one-script integration (the browser SDK)- // cannot carry a merchant secret, so this path stays open - but only for the- // gateway's own default merchant. Naming a different merchant requires that- // merchant's key (or an order token), so an anonymous caller still cannot inject- // sessions into another tenant's queue.- const defaultMerchant = ctx.merchantRepo.getDefault- ? ctx.merchantRepo.getDefault()- : (ctx.merchantRepo.findById('00000000-0000-0000-0000-000000000001') || ctx.merchantRepo.findAll()[0]);- if (!defaultMerchant || merchant.id !== defaultMerchant.id) {- HttpServer.json(res, 401, {- error: 'Merchant API key is required (X-Merchant-Key) for this merchant.',- code: 'MISSING_MERCHANT_KEY'- });- return;- }+ HttpServer.json(res, 401, {+ error: 'A server-side merchant API key is required.',+ code: 'MISSING_MERCHANT_KEY'+ });+ return;}if (!body.orderId || !body.amount) {@@ -168,10 +131,17 @@ export function registerPaymentRoutes(server, ctx) {HttpServer.json(res, 400, { error: 'returnUrl must be an absolute http(s) URL.' });return;}- if (parsedReturnUrl.protocol !== 'http:' && parsedReturnUrl.protocol !== 'https:') {+ if ((parsedReturnUrl.protocol !== 'http:' && parsedReturnUrl.protocol !== 'https:')+ || parsedReturnUrl.username || parsedReturnUrl.password) {HttpServer.json(res, 400, { error: 'returnUrl must use the http or https scheme.' });return;}+ const allowedReturnOrigins = String(process.env.YOUPI_ALLOWED_RETURN_ORIGINS || '')+ .split(/[\s,]+/).map(value => value.trim()).filter(Boolean);+ if (!allowedReturnOrigins.includes(parsedReturnUrl.origin)) {+ HttpServer.json(res, 400, { error: 'returnUrl origin is not allowlisted for this gateway.' });+ return;+ }body.returnUrl = parsedReturnUrl.href;}@@ -198,8 +168,17 @@ export function registerPaymentRoutes(server, ctx) {}// Check idempotency & active session state+ const requestedMethod = body.method || PaymentMethod.UPI;+ if (![PaymentMethod.UPI, PaymentMethod.MANUAL_UPI, PaymentMethod.COD, PaymentMethod.CASH_COUNTER, PaymentMethod.CARD_COUNTER].includes(requestedMethod)) {+ HttpServer.json(res, 400, { error: 'Unsupported payment method.' });+ return;+ }const existing = ctx.sessionRepo.findByOrderId(merchant.id, body.orderId);if (existing) {+ if (existing.method !== requestedMethod) {+ HttpServer.json(res, 409, { error: 'ORDER_PAYMENT_METHOD_MISMATCH', code: 'ORDER_PAYMENT_METHOD_MISMATCH' });+ return;+ }const existingCurrency = (existing.currency || 'INR').toUpperCase();if (existing.amountPaise !== amountPaise || existingCurrency !== requestedCurrency) {HttpServer.json(res, 409, {@@ -286,9 +265,10 @@ export function registerPaymentRoutes(server, ctx) {body.orderId = body.orderId.replace(/-R\d+$/, '');}- const isCounterPayment = body.method === 'CASH_COUNTER' || body.method === 'CARD_COUNTER';- const isCod = body.method === 'COD';- if (!isCounterPayment && !isCod && observerHealthEnforced()) {+ const isCounterPayment = requestedMethod === PaymentMethod.CASH_COUNTER || requestedMethod === PaymentMethod.CARD_COUNTER;+ const isCod = requestedMethod === PaymentMethod.COD;+ const isManualUpi = requestedMethod === PaymentMethod.MANUAL_UPI;+ if (!isCounterPayment && !isCod && !isManualUpi && observerHealthEnforced()) {const health = await checkUpiServerHealth(ctx, [], 'ONLINE', merchant.id);if (!upiObserversAcceptingPayments(health)) {HttpServer.json(res, 503, {@@ -389,7 +369,7 @@ export function registerPaymentRoutes(server, ctx) {orderId: body.orderId,amountPaise,currency: body.currency || 'INR',- method: body.method || 'UPI',+ method: requestedMethod,status: initialStatus,returnUrl: body.returnUrl || null,idempotencyKey: idempotencyKey || null,diff --git a/apps/payment-api/src/server.js b/apps/payment-api/src/server.jsindex 45fd4d5..9acb8bb 100644--- a/apps/payment-api/src/server.js+++ b/apps/payment-api/src/server.js@@ -8,6 +8,33 @@ const BASE_SECURITY_HEADERS = Object.freeze({'X-Frame-Options': 'SAMEORIGIN'});+function configuredOrigins() {+ return new Set(String(process.env.YOUPI_ALLOWED_ORIGINS || '').split(/[\s,]+/).map(value => {+ try { return new URL(value).origin; } catch { return ''; }+ }).filter(Boolean));+}++const requestWindows = new Map();+function isRateLimited(req, pathname) {+ if (req.method !== 'POST') return false;+ const now = Date.now();+ const ip = req.socket?.remoteAddress || 'unknown';+ const windowMs = 60_000;+ const limit = pathname === '/api/v1/payments' ? 20+ : (/\/manual-utr$/.test(pathname) ? 8 : 120);+ const key = `${ip}:${pathname}`;+ let bucket = requestWindows.get(key);+ if (!bucket || now - bucket.startedAt >= windowMs) {+ bucket = { startedAt: now, count: 0 };+ requestWindows.set(key, bucket);+ }+ bucket.count++;+ if (requestWindows.size > 10_000) {+ for (const [entry, value] of requestWindows) if (now - value.startedAt >= windowMs) requestWindows.delete(entry);+ }+ return bucket.count > limit;+}+/*** Lightweight, high-performance HTTP router and server with native SSE and CORS.*/@@ -89,11 +116,12 @@ export class HttpServer {* @param {http.ServerResponse} res*/initSse(topic, res) {+ const corsOrigin = res.corsOrigin;res.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache','Connection': 'keep-alive',- 'Access-Control-Allow-Origin': '*',+ ...(corsOrigin ? { 'Access-Control-Allow-Origin': corsOrigin, 'Vary': 'Origin' } : {}),...BASE_SECURITY_HEADERS});@@ -132,9 +160,9 @@ export class HttpServer {);res.writeHead(statusCode, {'Content-Type': 'application/json',- 'Access-Control-Allow-Origin': '*',+ ...(res.corsOrigin ? { 'Access-Control-Allow-Origin': res.corsOrigin, 'Vary': 'Origin' } : {}),'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Timestamp, X-Signature',+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Device-Token, X-Device-Signature, X-Device-Payload, X-Customer-Token, X-Timestamp, X-Signature',...BASE_SECURITY_HEADERS});res.end(jsonStr);@@ -177,12 +205,24 @@ export class HttpServer {*/createServer() {return http.createServer(async (req, res) => {+ const origin = req.headers.origin;+ const origins = configuredOrigins();+ if (origin && !origins.has(origin)) {+ HttpServer.json(res, 403, { error: 'Origin is not allowed.' });+ return;+ }+ if (origin) res.corsOrigin = origin;// Handle CORS preflightif (req.method === 'OPTIONS') {+ if (!origin || !res.corsOrigin) {+ HttpServer.json(res, 403, { error: 'Origin is not allowed.' });+ return;+ }res.writeHead(204, {- 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Origin': res.corsOrigin,+ 'Vary': 'Origin','Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Timestamp, X-Signature',+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Idempotency-Key, X-Device-Id, X-Device-Token, X-Device-Signature, X-Device-Payload, X-Customer-Token, X-Timestamp, X-Signature',...BASE_SECURITY_HEADERS});res.end();@@ -200,6 +240,12 @@ export class HttpServer {const pathname = parsedUrl.pathname;const method = req.method.toUpperCase();+ if (isRateLimited(req, pathname)) {+ res.setHeader('Retry-After', '60');+ HttpServer.json(res, 429, { error: 'Too many requests. Please retry shortly.' });+ return;+ }+try {for (const guard of this.guards) {if (await guard(req, res, pathname, parsedUrl)) return;@@ -225,7 +271,10 @@ export class HttpServer {await route.handler(req, res, params);} catch (err) {// Log the detail server-side; never echo stack/SQL text to an anonymous caller.- console.error(`Route Error [${method} ${pathname}]:`, err);+ console.error(`Route Error [${method} ${pathname}]:`, {+ name: err?.name || 'Error',+ code: typeof err?.code === 'string' ? err.code : 'unclassified'+ });HttpServer.json(res, 500, { error: 'Internal Server Error' });}return;diff --git a/packages/common/src/enums.js b/packages/common/src/enums.jsindex 26e23ae..b3aef9e 100644--- a/packages/common/src/enums.js+++ b/packages/common/src/enums.js@@ -37,6 +37,7 @@ export const PublicPaymentOutcome = Object.freeze({*/export const PaymentMethod = Object.freeze({UPI: 'UPI',+ MANUAL_UPI: 'MANUAL_UPI',COD: 'COD',CASH_COUNTER: 'CASH_COUNTER',CARD_COUNTER: 'CARD_COUNTER'diff --git a/packages/common/src/enums.ts b/packages/common/src/enums.tsindex 328e8f4..a585fa4 100644--- a/packages/common/src/enums.ts+++ b/packages/common/src/enums.ts@@ -27,6 +27,7 @@ export enum PublicPaymentOutcome {*/export enum PaymentMethod {UPI = 'UPI',+ MANUAL_UPI = 'MANUAL_UPI',COD = 'COD',CASH_COUNTER = 'CASH_COUNTER',CARD_COUNTER = 'CARD_COUNTER'diff --git a/packages/core/src/__tests__/fail-closed-attribution.test.js b/packages/core/src/__tests__/fail-closed-attribution.test.jsindex 3b30543..330ce71 100644--- a/packages/core/src/__tests__/fail-closed-attribution.test.js+++ b/packages/core/src/__tests__/fail-closed-attribution.test.js@@ -213,6 +213,17 @@ describe('Phase 9A Fail-Closed Payment Attribution Hardening Suite', () => {assert.equal(sessionRepo.findById(sessionA.id).status, PaymentStatus.OBSERVED_SUCCESS);});+ test('3b. Manual UPI sessions are never verified from SMS or Gmail attribution', () => {+ const manual = sessionRepo.create({ merchantId: merchantA.id, receivingAccountId: accountA.id,+ orderId: 'ORD-MANUAL-UPI', amountPaise: 25000n, method: 'MANUAL_UPI' });+ sessionRepo.acquireSlotAtomic(manual.id, accountA.id, 300000);+ const result = pipeline.process({ source: 'GMAIL', rawText: 'Received Rs 250.00 via UPI. UTR 250000011224',+ sender: '[email protected]', receivingAccountId: accountA.id, rawPayload: { targetSessionId: manual.id } });+ assert.notEqual(result.status, 'VERIFIED');+ assert.equal(sessionRepo.findById(manual.id).status, PaymentStatus.ACTIVE);+ assert.equal(emittedEvents.some(event => event.payload?.paymentId === manual.id), false);+ });+test('4. Missing or invalid observer registration: rejected or quarantined without guessing', () => {const sessionA = sessionRepo.create({merchantId: merchantA.id,diff --git a/packages/core/src/attribution-engine.js b/packages/core/src/attribution-engine.jsindex 2068078..e83f785 100644--- a/packages/core/src/attribution-engine.js+++ b/packages/core/src/attribution-engine.js@@ -299,13 +299,37 @@ export class AttributionEngine {if (normalizedObs.rawPayload?.targetSessionId) {currentSession = this.sessionRepo.findById(normalizedObs.rawPayload.targetSessionId);}+ if (currentSession?.method === 'MANUAL_UPI') {+ if (this.auditRepo) this.auditRepo.log({+ merchantId: currentSession.merchantId,+ entityType: 'PAYMENT_SESSION',+ entityId: currentSession.id,+ action: 'AUTOMATIC_OBSERVATION_IGNORED_FOR_MANUAL_UPI',+ actorType: 'OBSERVER',+ details: { observationId: savedObs.id, source: normalizedObs.source }+ });+ return {+ attributed: false,+ duplicate: false,+ lateMatch: false,+ observationId: savedObs.id,+ outcomeStatus: ObservationAttributionStatus.UNATTRIBUTED,+ reason: 'MANUAL_UPI_REQUIRES_ADMIN_BANK_VERIFICATION'+ };+ }if (!currentSession || (currentSession.amountPaise !== normalizedObs.amountPaise)) {currentSession = this.sessionRepo.findCurrentActiveOrProcessing(normalizedObs.receivingAccountId);}+ if (currentSession?.method === 'MANUAL_UPI') {+ if (this.auditRepo) this.auditRepo.log({ merchantId: currentSession.merchantId, entityType: 'PAYMENT_SESSION', entityId: currentSession.id,+ action: 'AUTOMATIC_OBSERVATION_IGNORED_FOR_MANUAL_UPI', actorType: 'OBSERVER', details: { observationId: savedObs.id, source: normalizedObs.source } });+ return { attributed: false, duplicate: false, lateMatch: false, observationId: savedObs.id,+ outcomeStatus: ObservationAttributionStatus.UNATTRIBUTED, reason: 'MANUAL_UPI_REQUIRES_ADMIN_BANK_VERIFICATION' };+ }if (currentSession && currentSession.amountPaise !== normalizedObs.amountPaise) {const matchRows = this.sessionRepo.db.query(`SELECT * FROM payment_sessions- WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING') AND amount_paise = ?+ WHERE receiving_account_id = ? AND status IN ('ACTIVE', 'PROCESSING') AND method <> 'MANUAL_UPI' AND amount_paise = ?`, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);if (matchRows.length > 1) {return this.holdAmbiguous(@@ -326,6 +350,7 @@ export class AttributionEngine {SELECT * FROM payment_sessionsWHERE receiving_account_id = ?AND status IN ('ACTIVE', 'PROCESSING')+ AND method <> 'MANUAL_UPI'AND amount_paise = ?`, [normalizedObs.receivingAccountId, Number(normalizedObs.amountPaise)]);if (candidates.length > 1) {diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex 980aef5..720226a 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -30,7 +30,7 @@ export class WebhookEngine {// The bank reference (UTR/RRN) lives on the attributed observation, not on the// session row. Merchants need it to reconcile a webhook against their bank// statement, and it is part of the documented webhook contract.- let utr = session.utr || session.bankReferenceNumber || session.bank_reference_number || '';+ let utr = session.customerUtr || session.customer_utr || session.utr || session.bankReferenceNumber || session.bank_reference_number || '';const attributedObsId = session.attributedObservationId || session.attributed_observation_id;if (!utr && attributedObsId) {try {diff --git a/packages/db/src/__tests__/auth-matrix.test.js b/packages/db/src/__tests__/auth-matrix.test.jsindex 48b8c2c..c88f933 100644--- a/packages/db/src/__tests__/auth-matrix.test.js+++ b/packages/db/src/__tests__/auth-matrix.test.js@@ -33,6 +33,8 @@ import { YoupiPaymentClient } from '@youpi/merchant-sdk';import { authHeadersFor } from '../../../../scripts/test-support.js';test('Full 53-Point Customer Identity, Authentication & Payment Invariant Matrix', async () => {+ process.env.NODE_ENV = 'test';+ process.env.YOUPI_ALLOWED_RETURN_ORIGINS = 'https://novacommerce.com http://localhost:5984';const testDb = new Database({ inMemory: true });runMigrations(testDb);@@ -77,7 +79,8 @@ test('Full 53-Point Customer Identity, Authentication & Payment Invariant Matrixconst demoStore = new CoinWalletStoreServer({gatewayApiUrl: apiBase,merchantId: merchant.id,- webhookSecret: merchant.webhookSecret+ webhookSecret: merchant.webhookSecret,+ publicBaseUrl: 'http://localhost:5984'});const demoServer = demoStore.createServer();await new Promise(resolve => demoServer.listen(5984, resolve));@@ -439,10 +442,13 @@ test('Full 53-Point Customer Identity, Authentication & Payment Invariant Matrix// --- MERCHANT INTEGRATION (41 - 43) ---// 41, 42, 43. Generic merchant integration creates payment without customer auth- const genericPay = await paymentClient.createPayment({+ await assert.rejects(paymentClient.createPayment({orderId: 'EXT-MERCHANT-ORD-101',amount: '50.00',returnUrl: 'https://thirdparty.com/return'+ }), /returnUrl origin is not allowlisted/);+ const genericPay = await paymentClient.createPayment({+ orderId: 'EXT-MERCHANT-ORD-101', amount: '50.00'});assert.ok(genericPay.paymentId);assert.ok(genericPay.checkoutUrl);diff --git a/packages/db/src/__tests__/db.test.js b/packages/db/src/__tests__/db.test.jsindex 9758044..689b56b 100644--- a/packages/db/src/__tests__/db.test.js+++ b/packages/db/src/__tests__/db.test.js@@ -14,7 +14,7 @@ import {SupportTicketRepository,AuditLogRepository} from '../index.js';-import { PaymentStatus, ObserverSource, SenderType, TicketStatus } from '@youpi/common';+import { PaymentStatus, PaymentMethod, ObserverSource, SenderType, TicketStatus } from '@youpi/common';describe('@youpi/db Unit & Integration Tests', () => {let db;@@ -57,6 +57,23 @@ describe('@youpi/db Unit & Integration Tests', () => {assert.equal(testAccount.isSlotBusy, false);});+ test('manual UPI UTR is idempotent, unique per receiving account, and only moves to review', () => {+ const first = sessionRepo.create({ merchantId: testMerchant.id, receivingAccountId: testAccount.id,+ orderId: 'MANUAL-UTR-1', amountPaise: 12300, method: PaymentMethod.MANUAL_UPI });+ sessionRepo.acquireSlotAtomic(first.id, testAccount.id, 300000);+ const submitted = sessionRepo.submitManualUtr(first.id, ' ab1234567890 ');+ assert.equal(submitted.status, PaymentStatus.MANUAL_REVIEW);+ assert.equal(submitted.customerUtr, 'AB1234567890');+ assert.equal(sessionRepo.submitManualUtr(first.id, 'AB1234567890').id, first.id);+ assert.throws(() => sessionRepo.submitManualUtr(first.id, 'bad'), /valid UPI reference/);++ const second = sessionRepo.create({ merchantId: testMerchant.id, receivingAccountId: testAccount.id,+ orderId: 'MANUAL-UTR-2', amountPaise: 12300, method: PaymentMethod.MANUAL_UPI });+ sessionRepo.acquireSlotAtomic(second.id, testAccount.id, 300000);+ assert.throws(() => sessionRepo.submitManualUtr(second.id, 'AB1234567890'), /UNIQUE constraint failed/);+ assert.equal(sessionRepo.findById(second.id).status, PaymentStatus.ACTIVE);+ });+test('customer registration and password verification', () => {const customer = customerRepo.create({merchantId: testMerchant.id,diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.jsindex ef23d5e..19f4fa0 100644--- a/packages/db/src/migrate.js+++ b/packages/db/src/migrate.js@@ -63,6 +63,11 @@ export function runMigrations(targetDb) {try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_level INTEGER DEFAULT 0;"); } catch {}try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_sources TEXT DEFAULT '[]';"); } catch {}try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_tag TEXT DEFAULT 'UNVERIFIED';"); } catch {}+ try { db.exec('ALTER TABLE payment_sessions ADD COLUMN customer_utr TEXT;'); } catch {}+ try { db.exec('ALTER TABLE payment_sessions ADD COLUMN utr_submitted_at TEXT;'); } catch {}+ try { db.exec('ALTER TABLE payment_sessions ADD COLUMN manual_reviewed_by TEXT;'); } catch {}+ try { db.exec('ALTER TABLE payment_sessions ADD COLUMN manual_reviewed_at TEXT;'); } catch {}+ try { db.exec('ALTER TABLE payment_sessions ADD COLUMN manual_review_reason TEXT;'); } catch {}// Phase 9C/9D: Preflight conflict check for existing databases prior to applying DDL / indexestry {@@ -111,6 +116,9 @@ export function runMigrations(targetDb) {// Execute schema DDLdb.exec(schemaSql);+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_manual_upi_utr_per_receiving_account+ ON payment_sessions (receiving_account_id, upper(customer_utr))+ WHERE method = 'MANUAL_UPI' AND customer_utr IS NOT NULL;`);// Alter table columns if migrating existing databasestry { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_level INTEGER DEFAULT 0;"); } catch {}diff --git a/packages/db/src/repositories/payment-session.repository.js b/packages/db/src/repositories/payment-session.repository.jsindex 0967ca6..b1c581c 100644--- a/packages/db/src/repositories/payment-session.repository.js+++ b/packages/db/src/repositories/payment-session.repository.js@@ -306,6 +306,42 @@ export class PaymentSessionRepository {});}+ /** Record a customer supplied UTR without treating it as payment evidence. */+ submitManualUtr(sessionId, rawUtr) {+ const utr = String(rawUtr || '').trim().toUpperCase();+ if (!/^[A-Z0-9-]{6,35}$/.test(utr)) {+ throw new Error('Enter a valid UPI reference (6–35 letters or digits).');+ }+ return this.db.transaction(() => {+ const session = this.findById(sessionId);+ if (!session) throw new Error('Session not found');+ if (session.method !== PaymentMethod.MANUAL_UPI) throw new Error('Manual UTR submission is not enabled for this payment.');+ if (session.status === PaymentStatus.MANUAL_REVIEW && session.customerUtr === utr) return session;+ if (session.status !== PaymentStatus.ACTIVE) throw new Error('This payment is no longer accepting a UTR.');+ if (!isValidTransition(session.status, PaymentStatus.MANUAL_REVIEW)) {+ throw new Error(`Illegal payment state transition: cannot move from '${session.status}' to '${PaymentStatus.MANUAL_REVIEW}'.`);+ }+ const now = new Date().toISOString();+ this.db.execute(`+ UPDATE payment_sessions+ SET customer_utr = ?, utr_submitted_at = ?, status = ?, completed_at = ?, updated_at = ?+ WHERE id = ? AND status = ?+ `, [utr, now, PaymentStatus.MANUAL_REVIEW, now, now, sessionId, PaymentStatus.ACTIVE]);+ const updated = this.findById(sessionId);+ if (updated.status !== PaymentStatus.MANUAL_REVIEW || updated.customerUtr !== utr) {+ throw new Error('Payment state changed; refresh and try again.');+ }+ if (session.receivingAccountId) {+ this.db.execute(`+ UPDATE payment_receiving_accounts+ SET is_slot_busy = 0, current_active_session_id = NULL, updated_at = ?+ WHERE id = ? AND current_active_session_id = ?+ `, [now, session.receivingAccountId, sessionId]);+ }+ return updated;+ });+ }+findCurrentActiveOrProcessing(receivingAccountId) {const row = this.db.queryOne(`SELECT * FROM payment_sessions@@ -637,6 +673,11 @@ export class PaymentSessionRepository {verificationLevel: row.verification_level !== undefined && row.verification_level !== null ? Number(row.verification_level) : 0,verificationSources: JSON.parse(row.verification_sources || '[]'),verificationTag: row.verification_tag || 'UNVERIFIED',+ customerUtr: row.customer_utr || null,+ utrSubmittedAt: row.utr_submitted_at ? new Date(row.utr_submitted_at) : null,+ manualReviewedBy: row.manual_reviewed_by || null,+ manualReviewedAt: row.manual_reviewed_at ? new Date(row.manual_reviewed_at) : null,+ manualReviewReason: row.manual_review_reason || null,metadata: JSON.parse(row.metadata || '{}'),createdAt: new Date(row.created_at),updatedAt: new Date(row.updated_at)diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sqlindex 67878a8..34c4ab1 100644--- a/packages/db/src/schema.sql+++ b/packages/db/src/schema.sql@@ -121,6 +121,11 @@ CREATE TABLE IF NOT EXISTS payment_sessions (verification_level INT DEFAULT 0,verification_sources TEXT DEFAULT '[]',verification_tag VARCHAR(100) DEFAULT 'UNVERIFIED',+ customer_utr TEXT,+ utr_submitted_at TIMESTAMPTZ,+ manual_reviewed_by TEXT,+ manual_reviewed_at TIMESTAMPTZ,+ manual_review_reason TEXT,metadata TEXT NOT NULL DEFAULT '{}',created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()@@ -138,6 +143,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_one_slot_per_receiving_accountCREATE UNIQUE INDEX IF NOT EXISTS idx_payment_sessions_attributed_obsON payment_sessions (attributed_observation_id)WHERE attributed_observation_id IS NOT NULL;+CREATE UNIQUE INDEX IF NOT EXISTS idx_manual_upi_utr_per_receiving_account+ ON payment_sessions (receiving_account_id, upper(customer_utr))+ WHERE method = 'MANUAL_UPI' AND customer_utr IS NOT NULL;-- 5. Payment Observations TableCREATE TABLE IF NOT EXISTS payment_observations (diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sqlindex 46484dd..b8eccd9 100644--- a/packages/db/src/sqlite-schema.sql+++ b/packages/db/src/sqlite-schema.sql@@ -119,6 +119,11 @@ CREATE TABLE IF NOT EXISTS payment_sessions (verification_level INTEGER DEFAULT 0,verification_sources TEXT DEFAULT '[]',verification_tag TEXT DEFAULT 'UNVERIFIED',+ customer_utr TEXT,+ utr_submitted_at TEXT,+ manual_reviewed_by TEXT,+ manual_reviewed_at TEXT,+ manual_review_reason TEXT,metadata TEXT NOT NULL DEFAULT '{}',created_at TEXT NOT NULL DEFAULT (datetime('now')),updated_at TEXT NOT NULL DEFAULT (datetime('now'))diff --git a/packages/merchant-sdk/src/__tests__/merchant-sdk.test.js b/packages/merchant-sdk/src/__tests__/merchant-sdk.test.jsindex c5c6aaa..18c6809 100644--- a/packages/merchant-sdk/src/__tests__/merchant-sdk.test.js+++ b/packages/merchant-sdk/src/__tests__/merchant-sdk.test.js@@ -12,6 +12,7 @@ describe('Merchant SDK Integration Tests', () => {const merchantSecret = 'sdk_test_webhook_secret_9988';before(async () => {+ process.env.YOUPI_ALLOWED_RETURN_ORIGINS = 'https://store.example';testDb = new Database({ inMemory: true });apiInstance = await startPaymentApi(6195, testDb);diff --git a/packages/merchant-sdk/src/youpi-checkout.js b/packages/merchant-sdk/src/youpi-checkout.jsindex 0c3f10a..b61edfa 100644--- a/packages/merchant-sdk/src/youpi-checkout.js+++ b/packages/merchant-sdk/src/youpi-checkout.js@@ -8,7 +8,8 @@** IMPORTANT SECURITY NOTE:* Browser events and client-side callbacks are strictly for UI and user experience.- * Authoritative proof of payment MUST ALWAYS come from server-to-server HMAC-SHA256 signed webhooks.+ * Browser callbacks are not proof of settlement. For manual UPI, only the merchant's+ * independent bank-account review may approve payment.*/(function (globalScope) {@@ -51,7 +52,8 @@const origin = scriptUrl ? scriptUrl.origin : (window.location.protocol + '//' + window.location.hostname + ':7000');return {- key: script.getAttribute('data-youpi-key') || script.getAttribute('data-key') || script.getAttribute('data-merchant-id') || '',+ // Merchant identifiers are public. Secret API credentials belong only on merchant servers.+ merchantId: script.getAttribute('data-merchant-id') || '',apiUrl: script.getAttribute('data-api-url') || origin,portalUrl: script.getAttribute('data-portal-url') || script.getAttribute('data-checkout-url') || origin,currency: script.getAttribute('data-currency') || 'INR',@@ -70,29 +72,9 @@/*** YoupiCheckout class*/- /**- * The gateway stores only an absolute http(s) returnUrl, so a relative successUrl is- * resolved against this storefront's own origin before it is sent. Without this a- * merchant using `data-success-url="/success"` would get a 400 from the API.- * @param {string} [raw]- * @returns {string|undefined} absolute http(s) URL, or undefined when unusable- */- function resolveReturnUrl(raw) {- if (!raw) return undefined;- try {- const base = (typeof window !== 'undefined' && window.location) ? window.location.href : undefined;- const parsed = new URL(raw, base);- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;- return parsed.href;- } catch (e) {- return undefined;- }- }-class YoupiCheckout {/*** @param {{- * key?: string,* order_id?: string,* orderId?: string,* amount?: number | string,@@ -131,7 +113,6 @@: 'http://localhost:6100';this.options = Object.assign({- key: scriptConfig.key || '',order_id: '',orderId: '',amount: 0,@@ -195,60 +176,7 @@return instance;}- // Otherwise, call YOUPI PG to create the payment session- try {- const orderId = instance.options.orderId || `ORDER-${Date.now()}`;- instance.options.orderId = orderId;- instance.options.order_id = orderId;-- const customer = instance.options.customer || {};- const custPayload = {- fullName: customer.name || customer.fullName || '',- email: customer.email || '',- phoneNumber: customer.phone || customer.phoneNumber || customer.mobileNumber || ''- };-- const createRes = await fetch(`${instance.options.apiUrl}/api/v1/payments`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- ...(instance.options.key ? { 'X-Merchant-Id': instance.options.key } : {})- },- body: JSON.stringify({- orderId: orderId,- amount: instance.options.amount,- currency: instance.options.currency || 'INR',- customer: (custPayload.email || custPayload.phoneNumber || custPayload.fullName) ? custPayload : undefined,- description: instance.options.description,- metadata: instance.options.metadata,- returnUrl: resolveReturnUrl(instance.options.successUrl)- })- });-- const data = await createRes.json();- if (!createRes.ok || !data.checkoutUrl) {- const errMsg = data.error || data.message || `Failed to create payment session (HTTP ${createRes.status})`;- const failResult = {- status: 'FAILED',- order_id: orderId,- reason: errMsg,- error: errMsg- };- YoupiCheckout._emitEvent('youpi:payment:failed', failResult);- YoupiCheckout._emitEvent('youpi:payment:result', failResult);- if (typeof instance.options.onFailed === 'function') instance.options.onFailed(failResult);- if (typeof instance.options.onPaymentFailed === 'function') instance.options.onPaymentFailed(failResult);- throw new Error(errMsg);- }-- instance.options.paymentId = data.paymentId;- instance.options.checkoutUrl = data.checkoutUrl;- instance.open();- return instance;- } catch (err) {- console.error('[YouPI JS] Payment initialization error:', err.message);- throw err;- }+ throw new Error('Create the payment on your server using trusted order data, then pass checkoutUrl or paymentId to Youpi.pay(). Never put a merchant API secret in browser code.');}/**diff --git a/packages/merchant-sdk/src/youpi.js b/packages/merchant-sdk/src/youpi.jsindex 4011a2c..8832ca1 100644--- a/packages/merchant-sdk/src/youpi.js+++ b/packages/merchant-sdk/src/youpi.js@@ -8,7 +8,8 @@** IMPORTANT SECURITY NOTE:* Browser events and client-side callbacks are strictly for UI and user experience.- * Authoritative proof of payment MUST ALWAYS come from server-to-server HMAC-SHA256 signed webhooks.+ * Browser callbacks are not proof of settlement. For manual UPI, only the merchant's+ * independent bank-account review may approve payment.*/(function (globalScope) {@@ -51,7 +52,8 @@const origin = scriptUrl ? scriptUrl.origin : (window.location.protocol + '//' + window.location.hostname + ':7000');return {- key: script.getAttribute('data-youpi-key') || script.getAttribute('data-key') || script.getAttribute('data-merchant-id') || '',+ // Merchant identifiers are public. Secret API credentials belong only on merchant servers.+ merchantId: script.getAttribute('data-merchant-id') || '',apiUrl: script.getAttribute('data-api-url') || origin,portalUrl: script.getAttribute('data-portal-url') || script.getAttribute('data-checkout-url') || origin,currency: script.getAttribute('data-currency') || 'INR',@@ -70,29 +72,9 @@/*** YoupiCheckout class*/- /**- * The gateway stores only an absolute http(s) returnUrl, so a relative successUrl is- * resolved against this storefront's own origin before it is sent. Without this a- * merchant using `data-success-url="/success"` would get a 400 from the API.- * @param {string} [raw]- * @returns {string|undefined} absolute http(s) URL, or undefined when unusable- */- function resolveReturnUrl(raw) {- if (!raw) return undefined;- try {- const base = (typeof window !== 'undefined' && window.location) ? window.location.href : undefined;- const parsed = new URL(raw, base);- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;- return parsed.href;- } catch (e) {- return undefined;- }- }-class YoupiCheckout {/*** @param {{- * key?: string,* order_id?: string,* orderId?: string,* amount?: number | string,@@ -131,7 +113,6 @@: 'http://localhost:6100';this.options = Object.assign({- key: scriptConfig.key || '',order_id: '',orderId: '',amount: 0,@@ -195,60 +176,7 @@return instance;}- // Otherwise, call YOUPI PG to create the payment session- try {- const orderId = instance.options.orderId || `ORDER-${Date.now()}`;- instance.options.orderId = orderId;- instance.options.order_id = orderId;-- const customer = instance.options.customer || {};- const custPayload = {- fullName: customer.name || customer.fullName || '',- email: customer.email || '',- phoneNumber: customer.phone || customer.phoneNumber || customer.mobileNumber || ''- };-- const createRes = await fetch(`${instance.options.apiUrl}/api/v1/payments`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- ...(instance.options.key ? { 'X-Merchant-Id': instance.options.key } : {})- },- body: JSON.stringify({- orderId: orderId,- amount: instance.options.amount,- currency: instance.options.currency || 'INR',- customer: (custPayload.email || custPayload.phoneNumber || custPayload.fullName) ? custPayload : undefined,- description: instance.options.description,- metadata: instance.options.metadata,- returnUrl: resolveReturnUrl(instance.options.successUrl)- })- });-- const data = await createRes.json();- if (!createRes.ok || !data.checkoutUrl) {- const errMsg = data.error || data.message || `Failed to create payment session (HTTP ${createRes.status})`;- const failResult = {- status: 'FAILED',- order_id: orderId,- reason: errMsg,- error: errMsg- };- YoupiCheckout._emitEvent('youpi:payment:failed', failResult);- YoupiCheckout._emitEvent('youpi:payment:result', failResult);- if (typeof instance.options.onFailed === 'function') instance.options.onFailed(failResult);- if (typeof instance.options.onPaymentFailed === 'function') instance.options.onPaymentFailed(failResult);- throw new Error(errMsg);- }-- instance.options.paymentId = data.paymentId;- instance.options.checkoutUrl = data.checkoutUrl;- instance.open();- return instance;- } catch (err) {- console.error('[YouPI JS] Payment initialization error:', err.message);- throw err;- }+ throw new Error('Create the payment on your server using trusted order data, then pass checkoutUrl or paymentId to Youpi.pay(). Never put a merchant API secret in browser code.');}/**diff --git a/scripts/test-support.js b/scripts/test-support.jsindex 5721e94..1e127ba 100644--- a/scripts/test-support.js+++ b/scripts/test-support.js@@ -26,7 +26,11 @@ const GUARDED = /\/api\/v1\/admin\/|\/api\/v1\/pollers\/events|\/api\/v1\/poller/** Admin bearer header only for routes the gateway guards; other routes (customer auth etc.) get none. */export function authHeadersFor(path, extra = {}) {- return GUARDED.test(String(path)) ? authHeaders(extra) : { ...extra };+ if (!GUARDED.test(String(path))) return { ...extra };+ const merchantForPaymentCreation = /\/api\/v1\/payments(?:\?|$)/.test(String(path))+ ? { 'X-Merchant-Id': '00000000-0000-0000-0000-000000000001' }+ : {};+ return authHeaders({ ...merchantForPaymentCreation, ...extra });}/**