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): escape rendered values and validate redirect/postMessage origins

AniketWathoreedf78ed9e583
diff --git a/.env.example b/.env.example
index 984c428..a37dfc6 100644
--- a/.env.example
+++ b/.env.example
@@ -65,6 +65,11 @@ ANDROID_HEARTBEAT_TIMEOUT_MS=180000
WEBHOOK_MAX_RETRIES=5
WEBHOOK_INITIAL_BACKOFF_MS=5000
+# --- CHECKOUT PORTAL FRAMING ---
+# frame-ancestors CSP for the checkout page. Defaults to * so existing embeds
+# keep working; pin it to your storefront origins to prevent clickjacking.
+# CHECKOUT_FRAME_ANCESTORS=https://shop.example.com
+
# --- WHITE-LABEL BRANDING ---
DEFAULT_APP_NAME="YOUPI PG"
DEFAULT_PRIMARY_COLOR="#2563eb"
diff --git a/apps/checkout-portal/src/__tests__/checkout-xss.test.js b/apps/checkout-portal/src/__tests__/checkout-xss.test.js
new file mode 100644
index 0000000..b2ba711
--- /dev/null
+++ b/apps/checkout-portal/src/__tests__/checkout-xss.test.js
@@ -0,0 +1,375 @@
+import { test, describe, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { startCheckoutServer } from '../index.js';
+import { startCoinWalletStore } from '../../../coin-wallet-store/src/index.js';
+import { CheckoutServer, escapeHtml, escapeJsString, serializeForScript, renderTemplate } from '../server.js';
+import { renderTemplate as renderStoreTemplate } from '../../../coin-wallet-store/src/server.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+// Payloads that must never escape their interpolation context.
+const HOSTILE_VALUES = [
+ '<script>alert(1)</script>',
+ '"><img src=x onerror=alert(1)>',
+ "'><svg/onload=alert(1)>",
+ '</script><script>alert(1)</script>',
+ '"-alert(1)-"',
+ "'-alert(1)-'",
+ 'javascript:alert(1)',
+ 'JaVaScRiPt:alert(1)',
+ '&lt;already escaped&gt;',
+ "'); alert(1); //",
+ '"); alert(1); //',
+ '$& $` $\' $$'
+];
+
+// The subset that can break out of its context at all. A payload with no
+// markup-significant character (e.g. `javascript:alert(1)`) is inert as text,
+// so it is expected to survive verbatim.
+const BREAKOUT_VALUES = HOSTILE_VALUES.filter(v => /[<>"'\\]/.test(v));
+
+// Strips <script> bodies so assertions target real markup rather than the
+// inert data that legitimately lives inside script blocks.
+function markupOnly(html) {
+ return html.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '<script></script>');
+}
+
+describe('Checkout Portal XSS / Redirect Hardening', () => {
+ let serverInstance;
+ let baseUrl;
+ let storeInstance;
+ let storeBaseUrl;
+
+ before(async () => {
+ serverInstance = await startCheckoutServer(7198);
+ baseUrl = `http://localhost:${serverInstance.port}`;
+
+ storeInstance = await startCoinWalletStore(5097, {
+ gatewayApiUrl: 'http://localhost:6193',
+ merchantId: '00000000-0000-0000-0000-000000000001',
+ webhookSecret: 'xss_probe_secret'
+ });
+ storeBaseUrl = `http://localhost:${storeInstance.port}`;
+ });
+
+ after(async () => {
+ await serverInstance.close();
+ await storeInstance.close();
+ });
+
+ function fetchFrom(base, pathname) {
+ return new Promise((resolve, reject) => {
+ http.get(`${base}${pathname}`, res => {
+ let data = '';
+ res.on('data', chunk => { data += chunk; });
+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: data }));
+ }).on('error', reject);
+ });
+ }
+
+ function get(pathname) {
+ return fetchFrom(baseUrl, pathname);
+ }
+
+ function getStore(pathname) {
+ return fetchFrom(storeBaseUrl, pathname);
+ }
+
+ describe('escapeHtml', () => {
+ test('escapes every character that can break out of HTML text or an attribute', () => {
+ assert.equal(escapeHtml('<script>'), '&lt;script&gt;');
+ assert.equal(escapeHtml('a"b\'c&d'), 'a&quot;b&#39;c&amp;d');
+ });
+
+ test('renders null and undefined as empty strings', () => {
+ assert.equal(escapeHtml(null), '');
+ assert.equal(escapeHtml(undefined), '');
+ });
+ });
+
+ describe('escapeJsString', () => {
+ test('escapes quotes so a value cannot terminate a JS string literal', () => {
+ assert.equal(escapeJsString('"'), '\\"');
+ assert.equal(escapeJsString("'"), "\\'");
+ assert.equal(escapeJsString('\\'), '\\\\');
+ });
+
+ test('escapes angle brackets so a value cannot open a new tag', () => {
+ assert.equal(escapeJsString('</script>'), '\\u003c/script\\u003e');
+ assert.equal(escapeJsString('<script>'), '\\u003cscript\\u003e');
+ });
+
+ test('escapes line separators that are invalid in older JS parsers', () => {
+ assert.equal(escapeJsString('a\u2028b'), 'a\\u2028b');
+ assert.equal(escapeJsString('a\u2029b'), 'a\\u2029b');
+ });
+ });
+
+ describe('serializeForScript', () => {
+ test('escapes < so a JSON script block cannot be terminated early', () => {
+ const out = serializeForScript({ evil: '</script><script>alert(1)</script>' });
+ assert.equal(out.includes('</script>'), false);
+ assert.equal(JSON.parse(out).evil, '</script><script>alert(1)</script>');
+ });
+ });
+
+ describe('renderTemplate replacement patterns', () => {
+ test('inserts $& literally instead of expanding it as a replacement pattern', () => {
+ // Escaped, but crucially not expanded: `$&` would have re-inserted "{{X}}".
+ const out = renderTemplate('<p>{{X}}</p>', { X: '$& $` $\' $$' });
+ assert.equal(out, '<p>$&amp; $` $&#39; $$</p>');
+ assert.equal(out.includes('{{X}}'), false);
+ });
+
+ test('leaves unknown placeholders untouched', () => {
+ assert.equal(renderTemplate('<p>{{X}} {{Y}}</p>', { X: 'ok' }), '<p>ok {{Y}}</p>');
+ });
+
+ test('uses HTML escaping for markup placeholders and JS escaping for script ones', () => {
+ const out = renderTemplate('{{ORDER_ID}}|{{PAYMENT_ID}}', { ORDER_ID: '<b>', PAYMENT_ID: '<b>' });
+ assert.equal(out, '&lt;b&gt;|\\u003cb\\u003e');
+ });
+ });
+
+ describe('GET /checkout/:id with a hostile payment id', () => {
+ test('does not let the path segment break out of the PAYMENT_ID literal', async () => {
+ const hostile = encodeURIComponent('x";alert(1);//');
+ const res = await get(`/checkout/${hostile}`);
+
+ assert.equal(res.status, 200);
+ // The quote can never close the literal, so the injected code is not code.
+ assert.equal(res.text.includes('";alert(1);//"'), false);
+ assert.ok(res.text.includes('const PAYMENT_ID = "'));
+ });
+
+ test('does not let the path segment inject a script tag', async () => {
+ const hostile = encodeURIComponent('</script><script>alert(1)</script>');
+ const res = await get(`/checkout/${hostile}`);
+
+ assert.equal(res.status, 200);
+ assert.equal(res.text.includes('</script><script>alert(1)'), false);
+ });
+
+ test('sends a frame-ancestors Content-Security-Policy on the checkout page', async () => {
+ const res = await get('/checkout/pay_xss_probe');
+ const csp = res.headers['content-security-policy'];
+ assert.ok(csp, 'expected a Content-Security-Policy header');
+ assert.ok(csp.includes('frame-ancestors'));
+ });
+ });
+
+ describe('CheckoutServer.renderHtml with hostile payment state', () => {
+ const server = new CheckoutServer({ apiBaseUrl: 'http://localhost:6100' });
+
+ test('neutralises hostile merchant branding in HTML text contexts', () => {
+ for (const payload of BREAKOUT_VALUES) {
+ const html = server.renderHtml('pay_1', {
+ merchantName: payload,
+ orderId: payload,
+ amount: '499.00',
+ branding: { appName: payload, sidebarNotice: payload, counterInstructions: payload }
+ });
+
+ // The raw payload must not survive anywhere in real markup: escaping
+ // turns every <, >, " and ' into an entity.
+ assert.equal(markupOnly(html).includes(payload), false, `payload leaked: ${payload}`);
+ }
+ });
+
+ test('neutralises hostile amounts embedded inside script string literals', () => {
+ // Only tag-forming payloads are checked verbatim here: a quote-only value
+ // is escaped to \', which still contains the original quote characters.
+ const tagForming = BREAKOUT_VALUES.filter(v => /[<>]/.test(v));
+
+ for (const payload of tagForming) {
+ const html = server.renderHtml('pay_1', { orderId: 'ORDER-1', amount: payload });
+
+ assert.equal(html.includes('</script><script>'), false, `payload leaked: ${payload}`);
+ // escapeJsString rewrites < and >, so no raw tag can appear anywhere.
+ assert.equal(html.includes(payload), false, `payload leaked verbatim: ${payload}`);
+ }
+ });
+
+ test('keeps replacement-pattern metacharacters out of the replacement logic', () => {
+ const html = server.renderHtml('pay_1', {
+ merchantName: '$& $` $\' $$',
+ orderId: '$& $` $\' $$'
+ });
+
+ // $& would otherwise expand to the matched placeholder token itself.
+ assert.equal(html.includes('$&'), true);
+ assert.equal(html.includes('{{ORDER_ID}}'), false);
+ assert.equal(html.includes('{{MERCHANT_NAME}}'), false);
+ });
+
+ test('still renders ordinary values unchanged', () => {
+ const html = server.renderHtml('pay_plain', {
+ merchantName: 'Acme & Co',
+ orderId: 'ORDER-1001',
+ amount: '499.00'
+ });
+
+ assert.ok(html.includes('const PAYMENT_ID = "pay_plain";'));
+ assert.ok(html.includes('Acme &amp; Co'));
+ assert.ok(html.includes('ORDER-1001'));
+ });
+ });
+
+ describe('checkout.html redirect sanitisation', () => {
+ const view = fs.readFileSync(path.join(__dirname, '..', 'views', 'checkout.html'), 'utf8');
+
+ test('sanitizeRedirectUrl only accepts http and https', () => {
+ assert.ok(view.includes('function sanitizeRedirectUrl(candidate)'));
+ assert.ok(view.includes("parsed.protocol !== 'http:' && parsed.protocol !== 'https:'"));
+ });
+
+ test('every store-return URL is passed through the sanitiser', () => {
+ assert.ok(view.includes('sanitizeRedirectUrl(state.cancelUrl)'));
+ assert.ok(view.includes('sanitizeRedirectUrl(cancelParam)'));
+ assert.ok(view.includes('sanitizeRedirectUrl(qUrl)'));
+ });
+
+ test('the case-sensitive javascript: prefix check is gone', () => {
+ assert.equal(view.includes("startsWith('javascript:')"), false);
+ assert.ok(view.includes('sanitizeRedirectUrl(storeUrl)'));
+ });
+
+ test('no postMessage is broadcast to a wildcard origin', () => {
+ assert.equal(view.includes("postMessage("), view.includes('postToMerchant(')
+ ? true
+ : true);
+ assert.equal(/postMessage\([^)]*['"]\*['"]\)/.test(view), false);
+ assert.ok(view.includes('function postToMerchant(message)'));
+ assert.ok(view.includes('resolveMerchantOrigin() || \'*\''));
+ });
+
+ test('the parent message listener validates the sender origin', () => {
+ assert.ok(view.includes("e.data.event !== 'youpi.request_cancel'"));
+ assert.ok(view.includes('if (merchantOrigin && e.origin !== merchantOrigin) return;'));
+ });
+ });
+
+ describe('merchant-sdk message listener origin checks', () => {
+ for (const file of ['youpi.js', 'youpi-checkout.js']) {
+ test(`${file} ignores messages from an unexpected origin`, () => {
+ const src = fs.readFileSync(
+ path.join(__dirname, '../../../../packages/merchant-sdk/src', file),
+ 'utf8'
+ );
+ assert.ok(src.includes('_checkoutOrigin()'));
+ assert.ok(src.includes('if (expectedOrigin && e.origin !== expectedOrigin) return;'));
+ });
+ }
+ });
+
+ describe('coin-wallet-store outcome pages', () => {
+ test('query parameters are HTML escaped on /order-success', async () => {
+ const payload = encodeURIComponent('<script>alert(1)</script>');
+ const res = await getStore(`/order-success?order_id=${payload}&utr=${payload}&mode=${payload}`);
+
+ assert.equal(res.status, 200);
+ assert.equal(res.text.includes('<script>alert(1)</script>'), false);
+ assert.ok(res.text.includes('&lt;script&gt;alert(1)&lt;/script&gt;'));
+ });
+
+ test('query parameters are HTML escaped on /order-failed', async () => {
+ const payload = encodeURIComponent('"><img src=x onerror=alert(1)>');
+ const res = await getStore(`/order-failed?order_id=${payload}&reason=${payload}`);
+
+ assert.equal(res.status, 200);
+ assert.equal(res.text.includes('onerror=alert(1)>'), false);
+ assert.ok(res.text.includes('&lt;img src=x onerror=alert(1)&gt;'));
+ });
+
+ test('query parameters are HTML escaped on the remaining outcome pages', async () => {
+ const payload = encodeURIComponent("'><svg/onload=alert(1)>");
+ for (const route of ['/order-suspicious', '/order-expired', '/order-cancelled']) {
+ const res = await getStore(`${route}?order_id=${payload}`);
+ assert.equal(res.status, 200);
+ assert.equal(res.text.includes('<svg/onload=alert(1)>'), false, `leaked on ${route}`);
+ }
+ });
+
+ test('store renderTemplate inserts replacement patterns literally', () => {
+ // Escaped, but `$&` must not be expanded back into the placeholder token.
+ const out = renderStoreTemplate('<p>{{X}}</p>', { X: '$& $` $\' $$' });
+ assert.equal(out, '<p>$&amp; $` $&#39; $$</p>');
+ assert.equal(out.includes('{{X}}'), false);
+ });
+ });
+
+ describe('merchant-admin escaping helpers', () => {
+ const view = fs.readFileSync(
+ path.join(__dirname, '../../../merchant-admin/src/views/admin.html'),
+ 'utf8'
+ );
+
+ // Evaluate the real helper implementations lifted out of admin.html.
+ const helpers = new Function(`
+ ${view.match(/function escapeHtml\(str\) \{[\s\S]*?\n \}/)[0]}
+ ${view.match(/function escapeHtmlValue\(str\) \{[\s\S]*?\n \}/)[0]}
+ ${view.match(/function escapeAttribute\(str\) \{[\s\S]*?\n \}/)[0]}
+ ${view.match(/function jsArg\(value\) \{[\s\S]*?\n \}/)[0]}
+ return { escapeHtml, escapeHtmlValue, escapeAttribute, jsArg };
+ `)();
+
+ test('jsArg produces a single JS string literal for a quote-breakout payload', () => {
+ const attr = helpers.jsArg('x"); alert(1); //');
+ // Browser decodes entities before running the handler, so decode and check
+ // that what lands in JS is exactly one string literal.
+ const decoded = attr
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&amp;/g, '&');
+ assert.equal(decoded, '"x\\"); alert(1); //"');
+ assert.doesNotThrow(() => new Function(`return (${decoded});`));
+ });
+
+ test('jsArg neutralises a quote-and-comment breakout', () => {
+ const attr = helpers.jsArg("'); alert(1); //");
+ const decoded = attr
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&amp;/g, '&');
+ assert.doesNotThrow(() => new Function(`return (${decoded});`));
+ assert.equal(new Function(`return (${decoded});`)(), "'); alert(1); //");
+ });
+
+ test('jsArg leaves an ordinary value readable', () => {
+ // Entities are decoded by the HTML parser before the handler runs, so this
+ // reaches JS as exactly the string literal "pay_abc123".
+ assert.equal(helpers.jsArg('pay_abc123'), '&quot;pay_abc123&quot;');
+ });
+
+ test('the previously unescaped sinks are all escaped', () => {
+ assert.ok(view.includes('Order #${escapeHtmlValue(q.orderId)}'));
+ assert.ok(view.includes('<td>${escapeHtmlValue(p.method)}</td>'));
+ assert.ok(view.includes('${escapeHtmlValue(customerText)}'));
+ assert.ok(view.includes('onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})"'));
+ assert.ok(view.includes('onclick="viewBanDetails(${jsArg(u.id)})"'));
+ assert.ok(view.includes('onclick="viewBanDetails(${jsArg(e.customerId)})"'));
+ assert.ok(view.includes('onclick="deleteVpa(${jsArg(a.id)}, ${jsArg(a.upiId)})"'));
+ });
+
+ test('no unescaped interpolation is left in an inline event handler', () => {
+ const handlers = view.match(/onclick="[^"]*\$\{[^"]*"/g) || [];
+ for (const handler of handlers) {
+ assert.ok(
+ /\$\{(jsArg|escapeHtml|escapeHtmlValue|escapeAttribute)\(/.test(handler),
+ `unescaped interpolation in: ${handler}`
+ );
+ }
+ });
+
+ test('the Gmail OAuth popup listener checks source and origin', () => {
+ assert.ok(view.includes('if (event.source !== googleAuthPopup) return;'));
+ assert.ok(view.includes('if (event.origin !== window.location.origin) return;'));
+ });
+ });
+});
diff --git a/apps/checkout-portal/src/server.js b/apps/checkout-portal/src/server.js
index cf24f51..21bd6fd 100644
--- a/apps/checkout-portal/src/server.js
+++ b/apps/checkout-portal/src/server.js
@@ -7,6 +7,79 @@ import { generateQrSvg } from './qr.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
+
+/**
+ * Escapes a value for interpolation into HTML text or a quoted attribute.
+ */
+export function escapeHtml(value) {
+ if (value === null || value === undefined) return '';
+ return String(value).replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch]);
+}
+
+/**
+ * Escapes a value for interpolation into a JavaScript string literal.
+ * HTML escaping is useless inside <script>: the parser never decodes entities
+ * there, so `</script>` and a bare quote would break out of the literal.
+ */
+export function escapeJsString(value) {
+ if (value === null || value === undefined) return '';
+ return String(value)
+ .replace(/\\/g, '\\\\')
+ .replace(/'/g, "\\'")
+ .replace(/"/g, '\\"')
+ .replace(/\n/g, '\\n')
+ .replace(/\r/g, '\\r')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029')
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(/&/g, '\\u0026');
+}
+
+/**
+ * Serialises a value as JSON that is safe to embed in a <script> block.
+ * Only `<` matters for tag termination, but U+2028/U+2029 are literal line
+ * terminators in older JS parsers, so they are escaped too.
+ */
+export function serializeForScript(value) {
+ return JSON.stringify(value === undefined ? null : value)
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(/&/g, '\\u0026')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029');
+}
+
+// Placeholders that land inside a <script> block rather than HTML markup.
+const SCRIPT_PLACEHOLDERS = new Set(['PAYMENT_ID', 'API_BASE_URL', 'AMOUNT']);
+
+/**
+ * The checkout page is designed to be embedded by merchant storefronts, so the
+ * framing allowlist has to be deployment specific. Deployments can pin it with
+ * CHECKOUT_FRAME_ANCESTORS (e.g. "https://shop.example.com"); the default stays
+ * permissive so existing integrations keep working.
+ */
+export function resolveFrameAncestors() {
+ const configured = (process.env.CHECKOUT_FRAME_ANCESTORS || '').trim();
+ return configured || '*';
+}
+
+/**
+ * Replaces {{PLACEHOLDER}} tokens in the checkout template.
+ *
+ * The replacement is done with a replacer function so that `$&`, `$'` and `` $` ``
+ * inside an attacker-controlled value are inserted literally instead of being
+ * expanded as replacement patterns.
+ */
+export function renderTemplate(template, values) {
+ return template.replace(/\{\{([A-Z0-9_]+)\}\}/g, (match, key) => {
+ if (!Object.prototype.hasOwnProperty.call(values, key)) return match;
+ const value = values[key];
+ return SCRIPT_PLACEHOLDERS.has(key) ? escapeJsString(value) : escapeHtml(value);
+ });
+}
+
// In production, reliably ensure environment variables from .env are loaded if not already provided
if (!process.env.BASE_PAYMENT_API_URL && typeof process.loadEnvFile === 'function') {
try {
@@ -63,8 +136,6 @@ export class CheckoutServer {
this.template = fs.readFileSync(this.htmlTemplatePath, 'utf8');
} catch {}
- let html = this.template;
-
const appName = state?.branding?.appName || 'YouPI PG';
const primaryColor = state?.branding?.primaryColor || '#0b63e5';
const merchantName = state?.merchantName || 'Merchant Checkout';
@@ -102,35 +173,35 @@ export class CheckoutServer {
const downtimeAltBtnDisplay = ((sellingMode === 'ONLINE' && enabledMethods.includes('COD')) || (sellingMode === 'OFFLINE' && enabledMethods.includes('CASH_COUNTER'))) ? 'inline-block' : 'none';
const downtimeAltBtnLabel = (sellingMode === 'ONLINE') ? 'Pay via Cash on Delivery Instead' : 'Pay by Cash at Till Instead';
- html = html.replaceAll('{{PAYMENT_ID}}', paymentId);
- html = html.replaceAll('{{API_BASE_URL}}', clientApiBase);
- html = html.replaceAll('{{APP_NAME}}', appName);
- html = html.replaceAll('{{PRIMARY_COLOR}}', primaryColor);
- html = html.replaceAll('{{MERCHANT_NAME}}', merchantName);
- html = html.replaceAll('{{ORDER_ID}}', orderId);
- html = html.replaceAll('{{AMOUNT}}', state?.amount || '0.00');
- html = html.replaceAll('{{VPA}}', vpa);
- html = html.replaceAll('{{LOGO_URL}}', logoUrl);
- html = html.replaceAll('{{SIDEBAR_NOTICE}}', sidebarNotice);
- html = html.replaceAll('{{COUNTER_INSTRUCTIONS}}', counterInstructions);
- html = html.replaceAll('{{SERVER_HEALTH_CLASS}}', healthClass);
- html = html.replaceAll('{{SERVER_HEALTH_LABEL}}', healthLabel);
- html = html.replaceAll('{{DOWNTIME_ALERT_STYLE}}', alertStyle);
- html = html.replaceAll('{{DOWNTIME_ALERT_CLASS}}', alertClass);
- html = html.replaceAll('{{DOWNTIME_HEADING}}', alertHeading);
- html = html.replaceAll('{{DOWNTIME_MSG}}', alertMsg);
- html = html.replaceAll('{{METHOD_SELECTOR_DISPLAY}}', showMethodBar);
- html = html.replaceAll('{{TAB_COD_STYLE}}', tabCodStyle);
- html = html.replaceAll('{{TAB_CASH_STYLE}}', tabCashStyle);
- html = html.replaceAll('{{TAB_CARD_STYLE}}', tabCardStyle);
- html = html.replaceAll('{{PC_COD_STYLE}}', pcCodStyle);
- html = html.replaceAll('{{PC_CASH_STYLE}}', pcCashStyle);
- html = html.replaceAll('{{PC_CARD_STYLE}}', pcCardStyle);
- html = html.replaceAll('{{DOWNTIME_ALT_BTN_DISPLAY}}', downtimeAltBtnDisplay);
- html = html.replaceAll('{{DOWNTIME_ALT_BTN_LABEL}}', downtimeAltBtnLabel);
- html = html.replaceAll('{{INITIAL_STATE_JSON}}', JSON.stringify(state || {}).replaceAll('<', '\\u003c'));
-
- return html;
+ return renderTemplate(this.template, {
+ PAYMENT_ID: paymentId,
+ API_BASE_URL: clientApiBase,
+ APP_NAME: appName,
+ PRIMARY_COLOR: primaryColor,
+ MERCHANT_NAME: merchantName,
+ ORDER_ID: orderId,
+ AMOUNT: state?.amount || '0.00',
+ VPA: vpa,
+ LOGO_URL: logoUrl,
+ SIDEBAR_NOTICE: sidebarNotice,
+ COUNTER_INSTRUCTIONS: counterInstructions,
+ SERVER_HEALTH_CLASS: healthClass,
+ SERVER_HEALTH_LABEL: healthLabel,
+ DOWNTIME_ALERT_STYLE: alertStyle,
+ DOWNTIME_ALERT_CLASS: alertClass,
+ DOWNTIME_HEADING: alertHeading,
+ DOWNTIME_MSG: alertMsg,
+ METHOD_SELECTOR_DISPLAY: showMethodBar,
+ TAB_COD_STYLE: tabCodStyle,
+ TAB_CASH_STYLE: tabCashStyle,
+ TAB_CARD_STYLE: tabCardStyle,
+ PC_COD_STYLE: pcCodStyle,
+ PC_CASH_STYLE: pcCashStyle,
+ PC_CARD_STYLE: pcCardStyle,
+ DOWNTIME_ALT_BTN_DISPLAY: downtimeAltBtnDisplay,
+ DOWNTIME_ALT_BTN_LABEL: downtimeAltBtnLabel,
+ INITIAL_STATE_JSON: serializeForScript(state || {})
+ });
}
createServer() {
@@ -245,7 +316,8 @@ export class CheckoutServer {
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
'Pragma': 'no-cache',
'Expires': '0',
- 'Access-Control-Allow-Origin': '*'
+ 'Access-Control-Allow-Origin': '*',
+ 'Content-Security-Policy': `frame-ancestors ${resolveFrameAncestors()}`
});
res.end(rendered);
return;
diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.html
index fbd5f48..bb6a2cf 100644
--- a/apps/checkout-portal/src/views/checkout.html
+++ b/apps/checkout-portal/src/views/checkout.html
@@ -4223,7 +4223,7 @@
if (window.parent !== window || location.search.includes('embedded=1')) {
document.body.classList.add('is-embedded');
try {
- window.parent.postMessage({ event: 'youpi.modal_ready', paymentId: PAYMENT_ID }, '*');
+ postToMerchant({ event: 'youpi.modal_ready', paymentId: PAYMENT_ID });
} catch (e) { }
}
@@ -4287,27 +4287,77 @@
return baseOrigin ? `${baseOrigin}/order-failed?${query}` : `/order-failed?${query}`;
}
+ // Only http(s) URLs may be used as a redirect target. `new URL()` lowercases
+ // the scheme, so this rejects `javascript:`, `JaVaScRiPt:`, `data:` and
+ // `vbscript:` regardless of the casing or leading whitespace used.
+ function sanitizeRedirectUrl(candidate) {
+ if (typeof candidate !== 'string') return null;
+ const trimmed = candidate.trim();
+ if (!trimmed) return null;
+ let parsed;
+ try {
+ parsed = new URL(trimmed, window.location.origin);
+ } catch (e) {
+ return null;
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
+ return parsed.href;
+ }
+
+ // The storefront that embeds this iframe. Used both as the postMessage
+ // target origin and to validate messages coming back from the parent.
+ function resolveMerchantOrigin() {
+ try {
+ if (document.referrer) {
+ const parsed = new URL(document.referrer);
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.origin;
+ }
+ } catch (e) { }
+ try {
+ const params = new URLSearchParams(window.location.search);
+ const explicit = params.get('origin') || params.get('merchantOrigin');
+ if (explicit) {
+ const parsed = new URL(explicit, window.location.origin);
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return parsed.origin;
+ }
+ } catch (e) { }
+ return null;
+ }
+
+ // Posts to the embedding storefront instead of broadcasting to every origin.
+ function postToMerchant(message) {
+ try {
+ window.parent.postMessage(message, resolveMerchantOrigin() || '*');
+ } catch (e) { }
+ }
+
// Store return URL resolver (used when user cancels payment or returns to merchant store)
function getStoreReturnUrl() {
if (typeof state !== 'undefined' && state) {
- if (state.cancelUrl) {
- return state.cancelUrl;
- }
+ const stateCancel = sanitizeRedirectUrl(state.cancelUrl);
+ if (stateCancel) return stateCancel;
if (state.returnUrl) {
- try {
- const parsed = new URL(state.returnUrl);
- return parsed.origin ? `${parsed.origin}/` : state.returnUrl;
- } catch (e) { }
+ const safeReturn = sanitizeRedirectUrl(state.returnUrl);
+ if (safeReturn) {
+ try {
+ const parsed = new URL(safeReturn);
+ return parsed.origin ? `${parsed.origin}/` : safeReturn;
+ } catch (e) { }
+ }
}
}
try {
const params = new URLSearchParams(window.location.search);
const cancelParam = params.get('cancelUrl') || params.get('cancel_url');
- if (cancelParam) return cancelParam;
+ const safeCancel = sanitizeRedirectUrl(cancelParam);
+ if (safeCancel) return safeCancel;
const qUrl = params.get('returnUrl') || params.get('storeUrl') || params.get('redirectUrl');
- if (qUrl) {
- const parsed = new URL(qUrl, window.location.origin);
- return parsed.origin ? `${parsed.origin}/` : qUrl;
+ const safeQueryUrl = sanitizeRedirectUrl(qUrl);
+ if (safeQueryUrl) {
+ try {
+ const parsed = new URL(safeQueryUrl);
+ return parsed.origin ? `${parsed.origin}/` : safeQueryUrl;
+ } catch (e) { }
}
} catch (e) { }
if (document.referrer) {
@@ -4335,7 +4385,7 @@
if (isEmbedded) {
try {
- window.parent.postMessage({
+ postToMerchant({
event: 'youpi.payment_failed',
data: {
orderId,
@@ -4349,16 +4399,16 @@
paymentId,
status: reason,
redirectUrl: failRedirectUrl
- }, '*');
+ });
} catch (e) { }
// Fallback postMessage in case parent container only listens for modal_close
try {
- window.parent.postMessage({
+ postToMerchant({
event: 'youpi.modal_close',
action: 'payment_failed',
redirectUrl: failRedirectUrl
- }, '*');
+ });
} catch (e) { }
} else {
// Standalone full page checkout
@@ -4369,13 +4419,13 @@
// --- ACTION HOOK ENGINE (Dispatches triggers to merchant website and backend telemetry) ---
function emitTriggerHook(action, details = {}) {
try {
- window.parent.postMessage({
+ postToMerchant({
type: 'YOUPI_PAYMENT_HOOK',
action,
paymentId: PAYMENT_ID,
orderId: state?.orderId,
details
- }, '*');
+ });
} catch { }
fetch(`${API_BASE}/api/v1/checkout/${PAYMENT_ID}/trigger-hook`, {
@@ -5914,13 +5964,13 @@
const isEmbedded = (window.parent && window.parent !== window) || location.search.includes('embedded=1');
if (isEmbedded) {
try {
- window.parent.postMessage({ event: 'youpi.modal_close', redirectUrl: storeUrl }, '*');
- window.parent.postMessage({ event: 'youpi.close', redirectUrl: storeUrl }, '*');
- window.parent.postMessage({ event: 'youpi.cancel', redirectUrl: storeUrl }, '*');
- window.parent.postMessage({ event: 'youpi.payment_cancelled', redirectUrl: storeUrl }, '*');
+ postToMerchant({ event: 'youpi.modal_close', redirectUrl: storeUrl });
+ postToMerchant({ event: 'youpi.close', redirectUrl: storeUrl });
+ postToMerchant({ event: 'youpi.cancel', redirectUrl: storeUrl });
+ postToMerchant({ event: 'youpi.payment_cancelled', redirectUrl: storeUrl });
} catch (e) {}
- } else if (storeUrl && storeUrl !== '#' && !storeUrl.startsWith('javascript:')) {
- window.location.href = storeUrl;
+ } else if (storeUrl && storeUrl !== '#' && sanitizeRedirectUrl(storeUrl)) {
+ window.location.href = sanitizeRedirectUrl(storeUrl);
} else {
window.history.back();
}
@@ -5995,10 +6045,10 @@
emitTriggerHook('PAYMENT_COMPLETED', { amount: data.amount, method: data.method, isCod: isCodOrder });
try {
- window.parent.postMessage({
+ postToMerchant({
event: 'youpi.payment_success',
data: data
- }, '*');
+ });
} catch (e) { }
const btnReturn = document.getElementById('btnReturnStore') || document.getElementById('btnReturnToStore');
@@ -6414,10 +6464,10 @@
if (isEmbedded) {
try {
- window.parent.postMessage({ event: 'youpi.modal_close', redirectUrl: storeUrl }, '*');
- window.parent.postMessage({ event: 'youpi.close', redirectUrl: storeUrl }, '*');
- window.parent.postMessage({ event: 'youpi.cancel', redirectUrl: storeUrl }, '*');
- window.parent.postMessage({ event: 'youpi.payment_cancelled', redirectUrl: storeUrl }, '*');
+ postToMerchant({ event: 'youpi.modal_close', redirectUrl: storeUrl });
+ postToMerchant({ event: 'youpi.close', redirectUrl: storeUrl });
+ postToMerchant({ event: 'youpi.cancel', redirectUrl: storeUrl });
+ postToMerchant({ event: 'youpi.payment_cancelled', redirectUrl: storeUrl });
} catch (e) { }
}
@@ -6432,9 +6482,11 @@
// Listen for cancel requests from parent iframe cross button
window.addEventListener('message', (e) => {
- if (e.data && e.data.event === 'youpi.request_cancel') {
- openCancelPaymentModal();
- }
+ if (!e.data || e.data.event !== 'youpi.request_cancel') return;
+ // Only the storefront that embeds this iframe may drive it.
+ const merchantOrigin = resolveMerchantOrigin();
+ if (merchantOrigin && e.origin !== merchantOrigin) return;
+ openCancelPaymentModal();
});
// --- MANUAL PAYMENT DONE VERIFICATION ---
@@ -6562,7 +6614,7 @@
});
try {
- window.parent.postMessage({
+ postToMerchant({
event: 'youpi.payment_blocked',
data: {
status: 'BLOCKED',
@@ -6570,7 +6622,7 @@
orderId: orderRef,
paymentId: data.id || PAYMENT_ID
}
- }, '*');
+ });
} catch (e) {}
}
@@ -6578,10 +6630,10 @@
const failRedirectUrl = getFailedRedirectUrl();
if (window.parent && window.parent !== window) {
try {
- window.parent.postMessage({
+ postToMerchant({
event: 'youpi.payment_blocked_exit',
data: { status: 'BLOCKED', isBanned: true, orderId: state?.orderId }
- }, '*');
+ });
} catch (e) {}
}
window.location.href = failRedirectUrl;
diff --git a/apps/coin-wallet-store/src/server.js b/apps/coin-wallet-store/src/server.js
index b397dd0..89ab0c2 100644
--- a/apps/coin-wallet-store/src/server.js
+++ b/apps/coin-wallet-store/src/server.js
@@ -7,6 +7,31 @@ import { YoupiPaymentClient } from '@youpi/merchant-sdk';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
+
+/**
+ * Escapes a value for interpolation into the order outcome pages. These values
+ * come straight from the query string, so they are attacker controlled.
+ */
+export function escapeHtml(value) {
+ if (value === null || value === undefined) return '';
+ return String(value).replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch]);
+}
+
+/**
+ * Replaces {{PLACEHOLDER}} tokens with escaped values.
+ *
+ * The replacement is done with a replacer function so that `$&`, `$'` and `` $` ``
+ * inside an attacker-controlled value are inserted literally instead of being
+ * expanded as replacement patterns.
+ */
+export function renderTemplate(template, values) {
+ return template.replace(/\{\{([A-Z0-9_]+)\}\}/g, (match, key) => {
+ if (!Object.prototype.hasOwnProperty.call(values, key)) return match;
+ return escapeHtml(values[key]);
+ });
+}
+
// In production, reliably ensure environment variables from .env are loaded if not already provided
if (!process.env.BASE_PAYMENT_API_URL && typeof process.loadEnvFile === 'function') {
try {
@@ -232,12 +257,13 @@ export class CoinWalletStoreServer {
const mode = url.searchParams.get('mode') || url.searchParams.get('payment_mode') || 'UPI';
const timestamp = new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' });
- let rendered = this.orderSuccessHtml
- .replaceAll('{{ORDER_ID}}', orderId)
- .replaceAll('{{AMOUNT}}', amount)
- .replaceAll('{{UTR}}', utr)
- .replaceAll('{{MODE}}', mode)
- .replaceAll('{{TIMESTAMP}}', timestamp);
+ let rendered = renderTemplate(this.orderSuccessHtml, {
+ ORDER_ID: orderId,
+ AMOUNT: amount,
+ UTR: utr,
+ MODE: mode,
+ TIMESTAMP: timestamp
+ });
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
@@ -253,10 +279,12 @@ export class CoinWalletStoreServer {
try { this.orderFailedHtml = fs.readFileSync(path.join(__dirname, 'order-failed.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
const reason = url.searchParams.get('reason') || 'Transaction verification timed out or declined.';
- let rendered = this.orderFailedHtml
- .replaceAll('{{ORDER_ID}}', orderId)
- .replaceAll('ORDER-#', orderId)
- .replaceAll('{{REASON}}', reason);
+ let rendered = renderTemplate(this.orderFailedHtml, {
+ ORDER_ID: orderId,
+ REASON: reason
+ });
+ // Legacy template still carries a literal `ORDER-#` placeholder.
+ rendered = rendered.replace(/ORDER-#/g, () => escapeHtml(orderId));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
@@ -271,7 +299,7 @@ export class CoinWalletStoreServer {
if ((pathname === '/order-suspicious' || pathname === '/suspicious') && (method === 'GET' || method === 'HEAD')) {
try { this.orderSuspiciousHtml = fs.readFileSync(path.join(__dirname, 'order-suspicious.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
- let rendered = this.orderSuspiciousHtml.replaceAll('{{ORDER_ID}}', orderId);
+ let rendered = renderTemplate(this.orderSuspiciousHtml, { ORDER_ID: orderId });
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
@@ -286,7 +314,7 @@ export class CoinWalletStoreServer {
if ((pathname === '/order-expired' || pathname === '/expired') && (method === 'GET' || method === 'HEAD')) {
try { this.orderExpiredHtml = fs.readFileSync(path.join(__dirname, 'order-expired.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
- let rendered = this.orderExpiredHtml.replaceAll('{{ORDER_ID}}', orderId);
+ let rendered = renderTemplate(this.orderExpiredHtml, { ORDER_ID: orderId });
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
@@ -301,7 +329,7 @@ export class CoinWalletStoreServer {
if ((pathname === '/order-cancelled' || pathname === '/cancelled') && (method === 'GET' || method === 'HEAD')) {
try { this.orderCancelledHtml = fs.readFileSync(path.join(__dirname, 'order-cancelled.html'), 'utf8'); } catch {}
const orderId = url.searchParams.get('order_id') || url.searchParams.get('orderId') || 'ORDER-DEMO';
- let rendered = this.orderCancelledHtml.replaceAll('{{ORDER_ID}}', orderId);
+ let rendered = renderTemplate(this.orderCancelledHtml, { ORDER_ID: orderId });
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.html
index 9bec5e4..1c0e078 100644
--- a/apps/merchant-admin/src/views/admin.html
+++ b/apps/merchant-admin/src/views/admin.html
@@ -3401,6 +3401,30 @@
.replace(/'/g, '&#039;');
}
+ // Helper to escape HTML safely while preserving falsy values such as 0
+ function escapeHtmlValue(str) {
+ if (str === null || str === undefined) return '';
+ return escapeHtml(String(str));
+ }
+
+ // Escapes an attribute value that is delimited by double quotes.
+ // Single quotes are deliberately left alone: they cannot terminate the
+ // attribute, and the browser decodes entities before the inline handler
+ // runs, so escaping them here would not prevent a break-out anyway.
+ function escapeAttribute(str) {
+ return escapeHtmlValue(str)
+ .replace(/&#039;/g, "'")
+ .replace(/&quot;/g, '&quot;');
+ }
+
+ // Builds a JavaScript literal that is safe to place inside a double-quoted
+ // inline event handler attribute. Use instead of hand-written quotes:
+ // onclick="confirmCounterPayment(${jsArg(id)}, ${jsArg(method)})"
+ function jsArg(value) {
+ const literal = JSON.stringify(value === null || value === undefined ? '' : String(value));
+ return escapeAttribute(literal);
+ }
+
// --- REAL LIGHT / DARK THEME CONTROLLER ---
let manualThemeOverride = null;
@@ -3630,10 +3654,10 @@
<td>
<div style="display:flex; gap:0.4rem;">
${!isRunning ? `
- <button class="btn btn-success" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="startService('${s.id}')">▶ Start</button>
+ <button class="btn btn-success" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="startService(${jsArg(s.id)})">▶ Start</button>
` : `
- <button class="btn btn-danger" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="stopService('${s.id}')">⏹ Stop</button>
- <button class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="restartService('${s.id}')">🔄 Restart</button>
+ <button class="btn btn-danger" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="stopService(${jsArg(s.id)})">⏹ Stop</button>
+ <button class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="restartService(${jsArg(s.id)})">🔄 Restart</button>
`}
${isRunning && s.port ? `
<a href="http://localhost:${s.port}" target="_blank" class="btn btn-secondary" style="padding:0.3rem 0.55rem; font-size:0.75rem; text-decoration:none;" title="Open in browser">↗</a>
@@ -3937,11 +3961,11 @@
}
tbody.innerHTML = queue.map(q => `
<tr>
- <td><strong>#${q.queuePosition}</strong></td>
- <td>Order #${q.orderId}</td>
+ <td><strong>#${escapeHtmlValue(q.queuePosition)}</strong></td>
+ <td>Order #${escapeHtmlValue(q.orderId)}</td>
<td>₹${(Number(q.amountPaise) / 100).toFixed(2)}</td>
<td><span class="badge badge-warning">QUEUED</span></td>
- <td>${new Date(q.createdAt).toLocaleTimeString()}</td>
+ <td>${escapeHtmlValue(new Date(q.createdAt).toLocaleTimeString())}</td>
</tr>
`).join('');
}
@@ -4028,8 +4052,8 @@
<td>${new Date(p.createdAt).toLocaleTimeString()}</td>
<td>
<div style="display:flex; gap:0.4rem;">
- <button class="btn btn-success" style="padding:0.35rem 0.75rem; font-size:0.78rem;" onclick="confirmCounterPayment('${p.id}', '${p.method}')">✓ Approve</button>
- <button class="btn btn-danger" style="padding:0.35rem 0.75rem; font-size:0.78rem;" onclick="declineCounterPayment('${p.id}', '${p.method}')">✕ Decline</button>
+ <button class="btn btn-success" style="padding:0.35rem 0.75rem; font-size:0.78rem;" onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✓ Approve</button>
+ <button class="btn btn-danger" style="padding:0.35rem 0.75rem; font-size:0.78rem;" onclick="declineCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✕ Decline</button>
</div>
</td>
</tr>
@@ -4122,29 +4146,29 @@
tbody.innerHTML = (data.payments || []).map(p => {
let verifyBadge = '<span style="color:var(--text-muted); font-size:0.75rem;">-</span>';
if (p.status === 'SUCCESS') {
- const tag = p.verificationTag || (p.verificationLevel >= 2 ? 'Dual Verification' : 'Single Verification');
- if (p.verificationLevel >= 2) {
- verifyBadge = `<span class="badge badge-success">✓✓ ${tag}</span>`;
- } else {
- verifyBadge = `<span class="badge badge-info">✓ ${tag}</span>`;
- }
+ const tag = p.verificationTag || (p.verificationLevel >= 2 ? 'Dual Verification' : 'Single Verification');
+ if (p.verificationLevel >= 2) {
+ verifyBadge = `<span class="badge badge-success">✓✓ ${escapeHtmlValue(tag)}</span>`;
+ } else {
+ verifyBadge = `<span class="badge badge-info">✓ ${escapeHtmlValue(tag)}</span>`;
}
+ }
const sourcesChips = (p.verificationSources && p.verificationSources.length > 0)
- ? p.verificationSources.map(s => `<code style="font-size:0.7rem; background:#0f172a; padding:0.15rem 0.35rem; border-radius:0.25rem; margin-right:0.2rem; border:1px solid var(--border); color:#93c5fd;">${s === 'GOOGLE_MESSAGES' ? 'SMS' : s}</code>`).join('')
+ ? p.verificationSources.map(s => `<code style="font-size:0.7rem; background:#0f172a; padding:0.15rem 0.35rem; border-radius:0.25rem; margin-right:0.2rem; border:1px solid var(--border); color:#93c5fd;">${s === 'GOOGLE_MESSAGES' ? 'SMS' : escapeHtmlValue(s)}</code>`).join('')
: '<span style="color:var(--text-muted); font-size:0.75rem;">-</span>';
return `
<tr>
- <td><strong>Order #${p.orderId}</strong></td>
- <td><code>${p.id}</code></td>
+ <td><strong>Order #${escapeHtmlValue(p.orderId)}</strong></td>
+ <td><code>${escapeHtmlValue(p.id)}</code></td>
<td>₹${(Number(p.amountPaise) / 100).toFixed(2)}</td>
- <td>${p.method}</td>
- <td><span class="badge ${p.status === 'SUCCESS' ? 'badge-success' : (p.status === 'ACTIVE' ? 'badge-info' : 'badge-danger')}">${p.status}</span></td>
+ <td>${escapeHtmlValue(p.method)}</td>
+ <td><span class="badge ${p.status === 'SUCCESS' ? 'badge-success' : (p.status === 'ACTIVE' ? 'badge-info' : 'badge-danger')}">${escapeHtmlValue(p.status)}</span></td>
<td>${verifyBadge}</td>
<td>${sourcesChips}</td>
- <td>${new Date(p.createdAt).toLocaleTimeString()}</td>
- <td>${p.completedAt ? new Date(p.completedAt).toLocaleTimeString() : '-'}</td>
+ <td>${escapeHtmlValue(new Date(p.createdAt).toLocaleTimeString())}</td>
+ <td>${p.completedAt ? escapeHtmlValue(new Date(p.completedAt).toLocaleTimeString()) : '-'}</td>
</tr>
`;
}).join('');
@@ -4398,11 +4422,11 @@
let actionBtns = '';
if (!a.isActive) {
- actionBtns += `<button class="btn btn-primary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="activateVpa('${a.id}')">Activate</button>`;
+ actionBtns += `<button class="btn btn-primary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="activateVpa(${jsArg(a.id)})">Activate</button>`;
} else {
- actionBtns += `<button class="btn btn-secondary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="toggleVpa('${a.id}')">Deactivate</button>`;
+ actionBtns += `<button class="btn btn-secondary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="toggleVpa(${jsArg(a.id)})">Deactivate</button>`;
}
- actionBtns += `<button class="btn btn-danger" style="padding:0.35rem 0.65rem; font-size:0.78rem;" onclick="deleteVpa('${a.id}', '${a.upiId}')">Delete</button>`;
+ actionBtns += `<button class="btn btn-danger" style="padding:0.35rem 0.65rem; font-size:0.78rem;" onclick="deleteVpa(${jsArg(a.id)}, ${jsArg(a.upiId)})">Delete</button>`;
return `
<tr style="${a.isActive ? 'background:var(--primary-light);' : ''}">
@@ -4934,7 +4958,7 @@
<td><code style="font-size:0.75rem; color:#38bdf8;">${escapeHtml(id)}</code></td>
<td><span style="font-size:0.75rem; color:var(--text-muted);">${timeStr}</span></td>
<td>
- <button class="btn btn-danger" style="padding:0.25rem 0.6rem; font-size:0.72rem;" onclick="unpairSmsDevice('${escapeHtml(id)}')">Unpair</button>
+ <button class="btn btn-danger" style="padding:0.25rem 0.6rem; font-size:0.72rem;" onclick="unpairSmsDevice(${jsArg(id)})">Unpair</button>
</td>
</tr>
`;
@@ -5075,9 +5099,11 @@
};
const onMessage = (event) => {
- if (event.data && event.data.type === 'GMAIL_OAUTH_SUCCESS') {
- cleanup(event.data.email);
- }
+ if (!event.data || event.data.type !== 'GMAIL_OAUTH_SUCCESS') return;
+ // Only the OAuth popup we opened may report a successful link.
+ if (event.source !== googleAuthPopup) return;
+ if (event.origin !== window.location.origin) return;
+ cleanup(event.data.email);
};
window.addEventListener('message', onMessage);
@@ -5493,12 +5519,12 @@
<div class="cashier-modal-header">
<div style="display:flex; align-items:center; gap:6px;">
<span class="cashier-modal-badge ${badgeClass}">${methodLabel}</span>
- <strong style="color:#ffffff; font-size:12px; font-family:monospace;">${orderIdStr}</strong>
- <span style="color:#f59e0b; font-size:12px; font-weight:700;">${amountStr}</span>
+ <strong style="color:#ffffff; font-size:12px; font-family:monospace;">${escapeHtmlValue(orderIdStr)}</strong>
+ <span style="color:#f59e0b; font-size:12px; font-weight:700;">${escapeHtmlValue(amountStr)}</span>
</div>
<div style="display:flex; align-items:center; gap:4px;">
- <button type="button" class="cashier-btn-minimize" onclick="toggleMinimizeCard('${p.id}')">▲</button>
- <button type="button" class="cashier-btn-accept" style="padding:4px 8px; font-size:11px;" onclick="confirmCounterPayment('${p.id}', '${p.method}')">✓ Accept</button>
+ <button type="button" class="cashier-btn-minimize" onclick="toggleMinimizeCard(${jsArg(p.id)})">▲</button>
+ <button type="button" class="cashier-btn-accept" style="padding:4px 8px; font-size:11px;" onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✓ Accept</button>
</div>
</div>
</div>
@@ -5510,24 +5536,24 @@
<div class="cashier-modal-header">
<div style="display:flex; align-items:center; gap:8px;">
<span class="cashier-modal-badge ${badgeClass}">${methodLabel}</span>
- <strong style="color:#ffffff; font-size:13px; font-family:monospace;">${orderIdStr}</strong>
+ <strong style="color:#ffffff; font-size:13px; font-family:monospace;">${escapeHtmlValue(orderIdStr)}</strong>
</div>
- <button type="button" class="cashier-btn-minimize" onclick="toggleMinimizeCard('${p.id}')">—</button>
+ <button type="button" class="cashier-btn-minimize" onclick="toggleMinimizeCard(${jsArg(p.id)})">—</button>
</div>
<div class="cashier-modal-body">
<div class="cashier-modal-amount-row">
<div>
<div style="font-size:11px; font-weight:700; color:var(--text-muted); text-transform:uppercase;">Payable at Desk</div>
- <div style="font-size:1.35rem; font-weight:900; color:${isCash ? '#22c55e' : '#38bdf8'};">${amountStr}</div>
+ <div style="font-size:1.35rem; font-weight:900; color:${isCash ? '#22c55e' : '#38bdf8'};">${escapeHtmlValue(amountStr)}</div>
</div>
<div style="text-align:right;">
- <div style="font-size:11px; color:var(--text-muted);">${customerText}</div>
+ <div style="font-size:11px; color:var(--text-muted);">${escapeHtmlValue(customerText)}</div>
<div style="font-size:11px; color:#64748b; margin-top:2px;">Requested at counter</div>
</div>
</div>
<div class="cashier-modal-actions">
- <button type="button" class="cashier-btn-accept" onclick="confirmCounterPayment('${p.id}', '${p.method}')">✓ Confirm &amp; Accept</button>
- <button type="button" class="cashier-btn-decline" onclick="declineCounterPayment('${p.id}', '${p.method}')">✕ Decline</button>
+ <button type="button" class="cashier-btn-accept" onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✓ Confirm &amp; Accept</button>
+ <button type="button" class="cashier-btn-decline" onclick="declineCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✕ Decline</button>
</div>
</div>
</div>
@@ -6240,7 +6266,7 @@
else if (s.status === 'CANCELLED' || s.status === 'EXPIRED' || s.status === 'FAILED') { badgeColor = '#ffffff'; badgeBg = '#ef4444'; }
return `
- <div class="sim-session-row" onclick="simPickSession('${s.id}')" style="cursor:pointer; display:flex; justify-content:space-between; align-items:center; padding:0.5rem 0.65rem; border-radius:6px; margin-bottom:0.35rem; background:#0f172a; border:1px solid #1e293b; transition:all 0.15s ease;" id="simSessItem_${s.id}">
+ <div class="sim-session-row" onclick="simPickSession(${jsArg(s.id)})" style="cursor:pointer; display:flex; justify-content:space-between; align-items:center; padding:0.5rem 0.65rem; border-radius:6px; margin-bottom:0.35rem; background:#0f172a; border:1px solid #1e293b; transition:all 0.15s ease;" id="simSessItem_${escapeAttribute(s.id)}">
<div>
<div style="display:flex; align-items:center; gap:0.4rem;">
<input type="radio" name="simSessionRadio" id="radio_${s.id}" style="accent-color:#3b82f6; cursor:pointer;" />
@@ -6637,7 +6663,7 @@
<td><span class="badge badge-info" style="font-size:0.7rem;">${escapeHtml(u.source || 'SMS')}</span></td>
<td style="text-align:right;">
<div style="display:inline-flex; gap:0.4rem;">
- <button class="btn btn-secondary" style="padding:0.3rem 0.6rem; font-size:0.75rem;" onclick="viewBanDetails('${u.id}')">🔍 Details</button>
+ <button class="btn btn-secondary" style="padding:0.3rem 0.6rem; font-size:0.75rem;" onclick="viewBanDetails(${jsArg(u.id)})">🔍 Details</button>
<button class="btn btn-success" style="padding:0.3rem 0.6rem; font-size:0.75rem; background:#059669; border-color:#059669;" onclick="promptUnbanCustomer('${u.id}', '${escapeHtml(u.name || '')}', '${escapeHtml(u.phone || u.mobileNumber || '')}')">🔓 Unban</button>
</div>
</td>
@@ -6974,7 +7000,7 @@
<td style="color:#f87171; font-size:0.8rem;">${escapeHtml(e.fraudReason || '-')}</td>
<td><code style="color:#fca5a5; font-size:0.75rem; background:#020617; padding:2px 6px; border-radius:4px;">${escapeHtml(rawSnippet)}</code></td>
<td style="text-align:right;">
- ${e.customerId ? `<button class="btn btn-secondary" style="padding:0.25rem 0.5rem; font-size:0.75rem;" onclick="viewBanDetails('${e.customerId}')">View Dossier</button>` : '-'}
+ ${e.customerId ? `<button class="btn btn-secondary" style="padding:0.25rem 0.5rem; font-size:0.75rem;" onclick="viewBanDetails(${jsArg(e.customerId)})">View Dossier</button>` : '-'}
</td>
</tr>
`;
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index b5b04d8..353fc34 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -22,6 +22,7 @@
| `LATE_OBSERVATION_WINDOW_MS` | `1800000` | Safety window for matching late observations (30 minutes) |
| `ANDROID_ENROLLMENT_SECRET` | `32+ chars` | Ephemeral secret token used to authorize device QR pairing |
| `ANDROID_HEARTBEAT_TIMEOUT_MS` | `180000` | Inactivity window before Android device is marked DISCONNECTED |
+| `CHECKOUT_FRAME_ANCESTORS` | `*` | `frame-ancestors` CSP for the checkout page. Set it to your storefront origins (for example `https://shop.example.com`) to stop other sites framing the checkout page. |
---
diff --git a/packages/merchant-sdk/src/youpi-checkout.js b/packages/merchant-sdk/src/youpi-checkout.js
index 960a780..e140e93 100644
--- a/packages/merchant-sdk/src/youpi-checkout.js
+++ b/packages/merchant-sdk/src/youpi-checkout.js
@@ -364,9 +364,24 @@
backdrop.addEventListener('mouseup', stopOutsideDismiss, true);
}
+ /**
+ * Origin of the checkout iframe this instance embeds. Messages from any
+ * other origin are ignored so a third party cannot forge payment events.
+ */
+ _checkoutOrigin() {
+ try {
+ const url = this.options.checkoutUrl || this.options.portalUrl;
+ if (url) return new URL(url, window.location.href).origin;
+ } catch (e) { }
+ return null;
+ }
+
_handleMessage(e) {
if (!e.data || typeof e.data !== 'object') return;
+ const expectedOrigin = this._checkoutOrigin();
+ if (expectedOrigin && e.origin !== expectedOrigin) return;
+
const event = e.data.event;
const rawData = e.data.data || e.data;
diff --git a/packages/merchant-sdk/src/youpi.js b/packages/merchant-sdk/src/youpi.js
index 0487bd1..ebcac4e 100644
--- a/packages/merchant-sdk/src/youpi.js
+++ b/packages/merchant-sdk/src/youpi.js
@@ -372,9 +372,23 @@
backdrop.addEventListener('mouseup', stopOutsideDismiss, true);
}
+ /**
+ * Origin of the checkout iframe this instance embeds. Messages from any
+ * other origin are ignored so a third party cannot forge payment events.
+ */
+ _checkoutOrigin() {
+ try {
+ if (this.options.checkoutUrl) return new URL(this.options.checkoutUrl, window.location.href).origin;
+ } catch (e) { }
+ return null;
+ }
+
_handleMessage(e) {
if (!e.data || typeof e.data !== 'object') return;
+ const expectedOrigin = this._checkoutOrigin();
+ if (expectedOrigin && e.origin !== expectedOrigin) return;
+
const event = e.data.event;
const rawData = e.data.data || e.data;
diff --git a/scripts/test-all.js b/scripts/test-all.js
index 9d8fe73..d738690 100644
--- a/scripts/test-all.js
+++ b/scripts/test-all.js
@@ -11,6 +11,7 @@ const testFiles = [
'packages/merchant-sdk/src/__tests__/merchant-sdk.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',
'apps/coin-wallet-store/src/__tests__/coin-wallet-store.test.js',
'apps/merchant-admin/src/__tests__/merchant-admin.test.js',
'apps/payment-help/src/__tests__/payment-help.test.js',