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): harden returnUrl, branding sinks and cross-origin messaging

AniketWathoreba2d5ba00daa
diff --git a/.env.example b/.env.example
index 8b317cc..f3edcc3 100644
--- a/.env.example
+++ b/.env.example
@@ -69,11 +69,11 @@ 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.
+# frame-ancestors CSP for the checkout page. Unset defaults to * in development
+# and 'self' in production (NODE_ENV=production or YOUPI_MODE=production); pin
+# it to your storefront origins to prevent clickjacking.
# Origins allowed to frame the checkout page (comma or space separated).
# Only bare http(s) origins are accepted; anything else is ignored.
-# Unset = any site may frame the checkout page.
# CHECKOUT_FRAME_ANCESTORS=https://shop.example.com
# --- WHITE-LABEL BRANDING ---
diff --git a/apps/checkout-portal/src/__tests__/checkout-xss.test.js b/apps/checkout-portal/src/__tests__/checkout-xss.test.js
index 515dcbd..f34f3f5 100644
--- a/apps/checkout-portal/src/__tests__/checkout-xss.test.js
+++ b/apps/checkout-portal/src/__tests__/checkout-xss.test.js
@@ -239,12 +239,20 @@ describe('Checkout Portal XSS / Redirect Hardening', () => {
});
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() || \'*\''));
+ // Payment data must never be broadcast: when the merchant origin cannot be
+ // resolved the message is dropped instead of posted to '*'.
+ assert.ok(view.includes('if (!target) return;'));
+ assert.ok(view.includes('window.parent.postMessage(message, target);'));
+ });
+
+ test('the SDK declares its own origin for referrer-less embeds', () => {
+ const sdk = fs.readFileSync(
+ path.join(__dirname, '../../../../packages/merchant-sdk/src/youpi.js'),
+ 'utf8'
+ );
+ assert.ok(sdk.includes('youpiParentOrigin='));
});
test('the parent message listener validates the sender origin', () => {
@@ -361,14 +369,26 @@ describe('Checkout Portal XSS / Redirect Hardening', () => {
test('no unescaped interpolation is left in an inline event handler', () => {
const handlers = view.match(/onclick="[^"]*\$\{[^"]*"/g) || [];
+ assert.ok(handlers.length > 0, 'expected to find inline handlers to check');
for (const handler of handlers) {
+ // jsArg builds a single string literal that survives HTML entity decoding.
+ // escapeHtml inside a handler argument is NOT safe: the browser decodes
+ // entities before the handler runs, so a quote still breaks out.
assert.ok(
- /\$\{(jsArg|escapeHtml|escapeHtmlValue|escapeAttribute)\(/.test(handler),
- `unescaped interpolation in: ${handler}`
+ /\$\{jsArg\(/.test(handler),
+ `handler argument is not built with jsArg: ${handler}`
);
}
});
+ test('every previously reported escapeHtml-in-handler sink now uses jsArg', () => {
+ assert.ok(view.includes('promptUnbanCustomer(${jsArg(u.id)}, ${jsArg(u.name || \'\')}, ${jsArg(u.phone || u.mobileNumber || \'\')})'));
+ assert.ok(view.includes("copyText(${jsArg(r.hostname || '')}, 'Hostname copied to clipboard!')"));
+ assert.ok(view.includes("copyText(${jsArg(r.serviceUrl)}, 'Service URL copied to clipboard!')"));
+ assert.equal(view.includes("onclick=\"promptUnbanCustomer('${u.id}'"), false);
+ assert.equal(view.includes("copyText('${escapeHtml("), false);
+ });
+
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/__tests__/issue-64-hardening.test.js b/apps/checkout-portal/src/__tests__/issue-64-hardening.test.js
new file mode 100644
index 0000000..50a346e
--- /dev/null
+++ b/apps/checkout-portal/src/__tests__/issue-64-hardening.test.js
@@ -0,0 +1,286 @@
+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 { startHelpServer } from '../../../payment-help/src/index.js';
+import { startServer as startPaymentApi } from '../../../payment-api/src/index.js';
+import { Database, MerchantRepository, PaymentSessionRepository } from '@youpi/db';
+import { authHeadersFor } from '../../../../scripts/test-support.js';
+import { checkoutFrameHeaders, isProductionLike } from '../server.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const checkoutView = fs.readFileSync(
+ path.join(__dirname, '..', 'views', 'checkout.html'),
+ 'utf8'
+);
+
+/**
+ * Lifts functions out of the inline checkout script and evaluates them against
+ * a sandboxed window/document, so the REAL shipping code is what gets tested.
+ */
+function liftCheckoutFunctions(...names) {
+ const sources = names.map(name => {
+ const match = checkoutView.match(new RegExp(`function ${name}\\([^)]*\\) \\{[\\s\\S]*?\\n \\}`));
+ assert.ok(match, `function ${name} not found in checkout.html`);
+ return match[0];
+ });
+ return (window, document) => new Function('window', 'document', `
+ ${sources.join('\n')}
+ return { ${names.join(', ')} };
+ `)(window, document);
+}
+
+function sandboxWindow({ referrer = '', search = '' } = {}) {
+ const posted = [];
+ const window = {
+ location: { origin: 'https://portal.test', search },
+ parent: {
+ postMessage: (msg, origin) => posted.push([msg, origin])
+ }
+ };
+ const document = { referrer };
+ return { window, document, posted };
+}
+
+describe('Issue #64 hardening: returnUrl, branding sinks, postMessage, framing', () => {
+ describe('sanitizeRedirectUrl (live code from checkout.html)', () => {
+ const lifted = liftCheckoutFunctions('sanitizeRedirectUrl')(
+ { location: { origin: 'https://portal.test' } },
+ { referrer: '' }
+ );
+
+ test('rejects scheme confusion regardless of casing or padding', () => {
+ assert.equal(lifted.sanitizeRedirectUrl('javascript:alert(1)'), null);
+ assert.equal(lifted.sanitizeRedirectUrl(' JaVaScRiPt:alert(1) '), null);
+ assert.equal(lifted.sanitizeRedirectUrl('data:text/html,<b>'), null);
+ assert.equal(lifted.sanitizeRedirectUrl('vbscript:msgbox'), null);
+ });
+
+ test('accepts absolute http(s) and trims whitespace', () => {
+ assert.equal(lifted.sanitizeRedirectUrl(' https://store.test/checkout '), 'https://store.test/checkout');
+ assert.equal(lifted.sanitizeRedirectUrl('http://store.test/checkout'), 'http://store.test/checkout');
+ });
+ });
+
+ describe('postToMerchant / resolveMerchantOrigin (live code from checkout.html)', () => {
+ const lifted = liftCheckoutFunctions('resolveMerchantOrigin', 'postToMerchant');
+
+ test('targets the referrer origin', () => {
+ const { window, document, posted } = sandboxWindow({ referrer: 'https://store.test/cart' });
+ lifted(window, document).postToMerchant({ event: 'youpi.payment_success' });
+ assert.equal(posted[0][1], 'https://store.test');
+ });
+
+ test('falls back to the origin declared by youpi.js when the referrer is stripped', () => {
+ const { window, document, posted } = sandboxWindow({
+ search: '?youpiParentOrigin=https%3A%2F%2Fshop.test&embedded=1'
+ });
+ lifted(window, document).postToMerchant({ event: 'youpi.payment_success' });
+ assert.equal(posted[0][1], 'https://shop.test');
+ });
+
+ test('drops the message instead of broadcasting when no origin is known', () => {
+ const { window, document, posted } = sandboxWindow({});
+ lifted(window, document).postToMerchant({ event: 'youpi.payment_success', data: { orderId: 'X' } });
+ assert.equal(posted.length, 0);
+ });
+
+ test('never resolves a non-http(s) declared origin', () => {
+ const { window, document, posted } = sandboxWindow({
+ search: '?youpiParentOrigin=javascript%3Aalert(1)'
+ });
+ lifted(window, document).postToMerchant({ event: 'youpi.payment_success' });
+ assert.equal(posted.length, 0);
+ });
+ });
+
+ 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.equal(checkoutView.includes('btnReturn.href = data.returnUrl;'), false);
+ assert.equal(checkoutView.includes('window.location.href = data.returnUrl;'), false);
+ });
+
+ test('the failed-payment base origin also goes through the sanitiser', () => {
+ assert.ok(checkoutView.includes('const safeReturn = sanitizeRedirectUrl(state && state.returnUrl);'));
+ assert.equal(
+ /baseOrigin = new URL\(state\.returnUrl\)\.origin/.test(checkoutView),
+ false,
+ 'raw state.returnUrl must not be parsed for the failed redirect'
+ );
+ });
+ });
+
+ describe('branding innerHTML sinks', () => {
+ test('support contacts are escaped before innerHTML', () => {
+ assert.ok(checkoutView.includes("emailBox.innerHTML = `<strong>Email:</strong> ${escapeHtml(info.supportEmails.join(', '))}`;"));
+ assert.ok(checkoutView.includes("phoneBox.innerHTML = `<strong>Phone:</strong> ${escapeHtml(info.supportMobiles.join(', '))}`;"));
+ });
+
+ test('appName no longer reaches innerHTML unescaped', () => {
+ assert.ok(checkoutView.includes('Secured by ${escapeHtml(appName)}'));
+ assert.equal(checkoutView.includes('Secured by ${appName}'), false);
+ });
+
+ test('legal links accept https only and escape the href', () => {
+ assert.ok(checkoutView.includes("if (parsed.protocol !== 'https:') return null;"));
+ assert.ok(checkoutView.includes('escapeHtml(privacyUrl)'));
+ assert.ok(checkoutView.includes('escapeHtml(termsHref)'));
+ assert.equal(checkoutView.includes('href="${branding.privacyPolicyUrl}"'), false);
+ assert.equal(checkoutView.includes('href="${branding.termsUrl}"'), false);
+ });
+
+ test('safeLegalUrl behaviour', () => {
+ const { safeLegalUrl } = liftCheckoutFunctions('safeLegalUrl')({}, { referrer: '' });
+ assert.equal(safeLegalUrl('javascript:alert(1)'), null);
+ assert.equal(safeLegalUrl('http://store.test/privacy'), null);
+ assert.equal(safeLegalUrl('HTTPS://store.test/privacy'), 'https://store.test/privacy');
+ assert.equal(safeLegalUrl(''), null);
+ });
+ });
+
+ describe('checkout frame-ancestors defaults', () => {
+ test('production defaults to self-fencing when nothing is configured', () => {
+ assert.ok(checkoutFrameHeaders({ NODE_ENV: 'production' })['Content-Security-Policy'].includes("frame-ancestors 'self'"));
+ assert.ok(checkoutFrameHeaders({ YOUPI_MODE: 'production', NODE_ENV: 'development' })['Content-Security-Policy'].includes("frame-ancestors 'self'"));
+ assert.equal(isProductionLike({ YOUPI_MODE: 'production' }), true);
+ assert.equal(isProductionLike({ NODE_ENV: 'test' }), false);
+ });
+
+ test('development stays framable so the demo storefront keeps embedding', () => {
+ assert.ok(checkoutFrameHeaders({ NODE_ENV: 'development' })['Content-Security-Policy'].includes('frame-ancestors *'));
+ });
+
+ test('an explicit allowlist always wins over the environment default', () => {
+ const configured = checkoutFrameHeaders({
+ NODE_ENV: 'development',
+ CHECKOUT_FRAME_ANCESTORS: 'https://shop.example.com'
+ });
+ assert.ok(configured['Content-Security-Policy'].includes("frame-ancestors 'self' https://shop.example.com"));
+ });
+ });
+
+ describe('payment-help security headers', () => {
+ let helpInstance;
+ let helpBaseUrl;
+
+ before(async () => {
+ helpInstance = await startHelpServer(7196);
+ helpBaseUrl = `http://localhost:${helpInstance.port}`;
+ });
+
+ after(async () => {
+ await helpInstance.close();
+ });
+
+ function get(pathname) {
+ return new Promise((resolve, reject) => {
+ http.get(`${helpBaseUrl}${pathname}`, res => {
+ let data = '';
+ res.on('data', chunk => { data += chunk; });
+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers }));
+ }).on('error', reject);
+ });
+ }
+
+ test('the help page sends nosniff, referrer policy and a self-fencing CSP', async () => {
+ const res = await get('/');
+ assert.equal(res.status, 200);
+ assert.equal(res.headers['x-content-type-options'], 'nosniff');
+ assert.equal(res.headers['referrer-policy'], 'strict-origin-when-cross-origin');
+ assert.ok(res.headers['content-security-policy'].includes("frame-ancestors 'self'"));
+ });
+
+ test('unknown routes carry the headers too', async () => {
+ const res = await get('/nope');
+ assert.equal(res.status, 404);
+ assert.ok(res.headers['content-security-policy']);
+ });
+ });
+
+ describe('payment-api returnUrl validation on write', () => {
+ let apiInstance;
+ let apiBaseUrl;
+ let testDb;
+ let merchantId;
+
+ before(async () => {
+ testDb = new Database({ inMemory: true });
+ apiInstance = await startPaymentApi(6194, testDb);
+ apiBaseUrl = `http://localhost:${apiInstance.port}`;
+ merchantId = new MerchantRepository(testDb).findAll()[0].id;
+ });
+
+ after(async () => {
+ await apiInstance.close();
+ testDb.close();
+ });
+
+ function post(body) {
+ return new Promise((resolve, reject) => {
+ const url = new URL('/api/v1/payments', apiBaseUrl);
+ const req = http.request(url, {
+ method: 'POST',
+ headers: authHeadersFor('/api/v1/payments', { 'Content-Type': 'application/json' })
+ }, res => {
+ let data = '';
+ res.on('data', chunk => { data += chunk; });
+ res.on('end', () => {
+ let parsed;
+ try { parsed = JSON.parse(data); } catch { parsed = data; }
+ resolve({ status: res.statusCode, body: parsed });
+ });
+ });
+ req.on('error', reject);
+ req.setHeader('Content-Type', 'application/json');
+ req.end(JSON.stringify(body));
+ });
+ }
+
+ test('rejects a javascript: returnUrl', async () => {
+ const res = await post({
+ orderId: `ISSUE64-${Date.now()}`,
+ amount: '100.00',
+ returnUrl: 'javascript:alert(1)'
+ });
+ assert.equal(res.status, 400);
+ assert.match(String(res.body.error), /http/);
+ });
+
+ test('rejects relative and encoded-scheme returnUrl values', async () => {
+ for (const bad of ['/order-done', ' JaVaScRiPt:alert(1) ', 'data:text/html,<b>']) {
+ const res = await post({
+ orderId: `ISSUE64-${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ amount: '100.00',
+ returnUrl: bad
+ });
+ assert.equal(res.status, 400, `expected 400 for ${bad}`);
+ }
+ });
+
+ test('accepts https and normalises the stored value', async () => {
+ const orderId = `ISSUE64-OK-${Date.now()}`;
+ const res = await post({
+ orderId,
+ amount: '100.00',
+ returnUrl: ' https://store.test/success '
+ });
+ assert.equal(res.status, 201);
+ const stored = new PaymentSessionRepository(testDb).findByOrderId(merchantId, orderId);
+ assert.ok(stored, 'session should exist');
+ assert.equal(stored.returnUrl, 'https://store.test/success');
+ });
+
+ test('a missing returnUrl is still allowed', async () => {
+ const res = await post({
+ orderId: `ISSUE64-NONE-${Date.now()}`,
+ amount: '100.00'
+ });
+ assert.equal(res.status, 201);
+ });
+ });
+});
diff --git a/apps/checkout-portal/src/server.js b/apps/checkout-portal/src/server.js
index bb1f643..dbcaec8 100644
--- a/apps/checkout-portal/src/server.js
+++ b/apps/checkout-portal/src/server.js
@@ -39,21 +39,33 @@ export function frameAncestorOrigins(raw = process.env.CHECKOUT_FRAME_ANCESTORS)
return origins;
}
+/**
+ * True for production launches. scripts/start.js sets YOUPI_MODE/NODE_ENV to
+ * 'production'; the dev script and the test runner leave them on development/test.
+ */
+export function isProductionLike(env = process.env) {
+ return env.YOUPI_MODE === 'production' || env.NODE_ENV === 'production';
+}
+
/**
* Headers for the embeddable checkout page.
*
- * The checkout page is embedded cross-origin by merchant storefronts, so the default is
- * permissive (`frame-ancestors *`). Deployments can pin the allowlist with
- * CHECKOUT_FRAME_ANCESTORS; when set, only those origins (plus the portal itself) may
- * frame the page. X-Frame-Options is dropped in that case because it cannot express a
- * list and would otherwise block the allowlisted storefronts.
+ * The checkout page is embedded cross-origin by merchant storefronts. An explicit
+ * CHECKOUT_FRAME_ANCESTORS always wins. Without one, production defaults to
+ * frame-ancestors 'self' so unknown sites cannot frame the page, while development
+ * stays permissive because the demo storefront (port 5000) embeds the portal
+ * (port 7000) across origins. X-Frame-Options is dropped when an allowlist is in
+ * effect because it cannot express a list and would block the allowlisted storefronts.
*/
-function checkoutFrameHeaders() {
- const origins = frameAncestorOrigins();
+export function checkoutFrameHeaders(env = process.env) {
+ const configured = frameAncestorOrigins(env.CHECKOUT_FRAME_ANCESTORS);
+ const frameAncestors = configured.length
+ ? `'self' ${configured.join(' ')}`
+ : (isProductionLike(env) ? "'self'" : '*');
return {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
- 'Content-Security-Policy': `default-src 'self' data: blob:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors ${origins.length ? `'self' ${origins.join(' ')}` : '*'}; base-uri 'none'; form-action 'self'; object-src 'none'`
+ 'Content-Security-Policy': `default-src 'self' data: blob:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors ${frameAncestors}; base-uri 'none'; form-action 'self'; object-src 'none'`
};
}
diff --git a/apps/checkout-portal/src/views/checkout.html b/apps/checkout-portal/src/views/checkout.html
index 905dcdf..c182ac0 100644
--- a/apps/checkout-portal/src/views/checkout.html
+++ b/apps/checkout-portal/src/views/checkout.html
@@ -168,10 +168,9 @@
const paymentId = typeof PAYMENT_ID !== 'undefined' ? PAYMENT_ID : (state?.id || '');
let baseOrigin = '';
- if (state && state.returnUrl) {
- try {
- baseOrigin = new URL(state.returnUrl).origin;
- } catch (e) { }
+ const safeReturn = sanitizeRedirectUrl(state && state.returnUrl);
+ if (safeReturn) {
+ baseOrigin = new URL(safeReturn).origin;
}
if (!baseOrigin && document.referrer) {
try {
@@ -202,6 +201,8 @@
// The storefront that embeds this iframe. Used both as the postMessage
// target origin and to validate messages coming back from the parent.
+ // The referrer is the most trustworthy signal; when the browser strips it,
+ // youpi.js declares the parent origin in the URL (`youpiParentOrigin`).
function resolveMerchantOrigin() {
try {
if (document.referrer) {
@@ -211,19 +212,24 @@
} 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);
+ for (const key of ['youpiParentOrigin', 'origin', 'merchantOrigin']) {
+ const declared = params.get(key);
+ if (!declared) continue;
+ const parsed = new URL(declared, 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.
+ // Posts to the embedding storefront. The message carries payment data, so it
+ // is only ever sent to a known merchant origin: when the origin cannot be
+ // resolved the message is dropped rather than broadcast to every origin.
function postToMerchant(message) {
+ const target = resolveMerchantOrigin();
+ if (!target) return;
try {
- window.parent.postMessage(message, resolveMerchantOrigin() || '*');
+ window.parent.postMessage(message, target);
} catch (e) { }
}
@@ -1523,15 +1529,33 @@
}
}
+ // Policy links are merchant branding and land in an href, so only https is
+ // accepted and the value is escaped for attribute context.
+ function safeLegalUrl(candidate) {
+ if (typeof candidate !== 'string') return null;
+ const trimmed = candidate.trim();
+ if (!trimmed) return null;
+ let parsed;
+ try {
+ parsed = new URL(trimmed);
+ } catch (e) {
+ return null;
+ }
+ if (parsed.protocol !== 'https:') return null;
+ return parsed.href;
+ }
+
function renderHelpLegalLinks(branding) {
const container = document.getElementById('helpModalLegalLinks');
if (!container) return;
let html = '';
- if (branding.privacyPolicyUrl) {
- html += `<a href="${branding.privacyPolicyUrl}" target="_blank" rel="noopener noreferrer" style="color:var(--ypg-blue); text-decoration:underline; font-weight:600;">Privacy Policy &nearr;</a>`;
+ const privacyUrl = safeLegalUrl(branding.privacyPolicyUrl);
+ if (privacyUrl) {
+ html += `<a href="${escapeHtml(privacyUrl)}" target="_blank" rel="noopener noreferrer" style="color:var(--ypg-blue); text-decoration:underline; font-weight:600;">Privacy Policy &nearr;</a>`;
}
- if (branding.termsUrl) {
- html += `<a href="${branding.termsUrl}" target="_blank" rel="noopener noreferrer" style="color:var(--ypg-blue); text-decoration:underline; font-weight:600;">Terms of Service &nearr;</a>`;
+ const termsHref = safeLegalUrl(branding.termsUrl);
+ if (termsHref) {
+ html += `<a href="${escapeHtml(termsHref)}" target="_blank" rel="noopener noreferrer" style="color:var(--ypg-blue); text-decoration:underline; font-weight:600;">Terms of Service &nearr;</a>`;
}
container.innerHTML = html;
container.style.display = html ? 'flex' : 'none';
@@ -1792,7 +1816,7 @@
if (b.hidePoweredBy) {
legalDisclaimerEl.innerHTML = `Secured by 256-Bit Bank Encryption &bull; <span style="text-decoration:underline; cursor:pointer;" onclick="openHelpModal()">Privacy &amp; Terms</span>`;
} else {
- legalDisclaimerEl.innerHTML = `Secured by ${appName} &amp; 256-Bit Bank Encryption &bull; <span style="text-decoration:underline; cursor:pointer;" onclick="openHelpModal()">Privacy Notice</span>`;
+ legalDisclaimerEl.innerHTML = `Secured by ${escapeHtml(appName)} &amp; 256-Bit Bank Encryption &bull; <span style="text-decoration:underline; cursor:pointer;" onclick="openHelpModal()">Privacy Notice</span>`;
}
}
@@ -1948,11 +1972,12 @@
} catch (e) { }
const btnReturn = document.getElementById('btnReturnStore') || document.getElementById('btnReturnToStore');
- if (btnReturn && data.returnUrl) {
+ const safeReturnUrl = sanitizeRedirectUrl(data.returnUrl);
+ if (btnReturn && safeReturnUrl) {
btnReturn.hidden = false;
- btnReturn.href = data.returnUrl;
+ btnReturn.href = safeReturnUrl;
if (window.parent === window) {
- setTimeout(() => { window.location.href = data.returnUrl; }, 2000);
+ setTimeout(() => { window.location.href = safeReturnUrl; }, 2000);
}
} else if (btnReturn) {
btnReturn.hidden = true;
@@ -2699,11 +2724,13 @@
const phoneBox = document.getElementById('helpModalMobilesContainer');
const caseBox = document.getElementById('helpModalCaseInfoText');
+ // Support contacts are merchant branding, i.e. attacker-influenced input,
+ // so they are escaped before going into innerHTML.
if (emailBox && info.supportEmails) {
- emailBox.innerHTML = `<strong>Email:</strong> ${info.supportEmails.join(', ')}`;
+ emailBox.innerHTML = `<strong>Email:</strong> ${escapeHtml(info.supportEmails.join(', '))}`;
}
if (phoneBox && info.supportMobiles) {
- phoneBox.innerHTML = `<strong>Phone:</strong> ${info.supportMobiles.join(', ')}`;
+ phoneBox.innerHTML = `<strong>Phone:</strong> ${escapeHtml(info.supportMobiles.join(', '))}`;
}
if (caseBox) {
caseBox.textContent = `PAYMENT_ID: ${PAYMENT_ID}\nORDER_ID: ${state?.orderId || 'N/A'}\nAMOUNT: ₹${state?.amount || 'N/A'}\nSTATUS: ${state?.status || 'N/A'}`;
diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.html
index 401e8f6..8210e40 100644
--- a/apps/merchant-admin/src/views/admin.html
+++ b/apps/merchant-admin/src/views/admin.html
@@ -4821,8 +4821,8 @@
</div>
</div>
<div style="display:flex; gap:0.5rem;">
- <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyText('${escapeHtml(r.hostname || '')}', 'Hostname copied to clipboard!')" ${!r.hostname ? 'disabled' : ''}>📋 Copy Hostname</button>
- <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyText('${escapeHtml(r.serviceUrl)}', 'Service URL copied to clipboard!')">📋 Copy Service URL</button>
+ <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyText(${jsArg(r.hostname || '')}, 'Hostname copied to clipboard!')" ${!r.hostname ? 'disabled' : ''}>📋 Copy Hostname</button>
+ <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyText(${jsArg(r.serviceUrl)}, 'Service URL copied to clipboard!')">📋 Copy Service URL</button>
</div>
</div>
`).join('');
@@ -6767,7 +6767,7 @@
<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(${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>
+ <button class="btn btn-success" style="padding:0.3rem 0.6rem; font-size:0.75rem; background:#059669; border-color:#059669;" onclick="promptUnbanCustomer(${jsArg(u.id)}, ${jsArg(u.name || '')}, ${jsArg(u.phone || u.mobileNumber || '')})">🔓 Unban</button>
</div>
</td>
</tr>
diff --git a/apps/payment-api/src/routes/payments.routes.js b/apps/payment-api/src/routes/payments.routes.js
index 61551e1..30bb597 100644
--- a/apps/payment-api/src/routes/payments.routes.js
+++ b/apps/payment-api/src/routes/payments.routes.js
@@ -58,6 +58,28 @@ export function registerPaymentRoutes(server, ctx) {
return;
}
+ // returnUrl is echoed back to the customer's browser as a redirect target after
+ // payment, so only absolute http(s) URLs are ever stored. This is the write-side
+ // complement to the checkout page's sanitizeRedirectUrl.
+ if (body.returnUrl !== undefined && body.returnUrl !== null && body.returnUrl !== '') {
+ if (typeof body.returnUrl !== 'string') {
+ HttpServer.json(res, 400, { error: 'returnUrl must be a string.' });
+ return;
+ }
+ let parsedReturnUrl;
+ try {
+ parsedReturnUrl = new URL(body.returnUrl.trim());
+ } catch {
+ HttpServer.json(res, 400, { error: 'returnUrl must be an absolute http(s) URL.' });
+ return;
+ }
+ if (parsedReturnUrl.protocol !== 'http:' && parsedReturnUrl.protocol !== 'https:') {
+ HttpServer.json(res, 400, { error: 'returnUrl must use the http or https scheme.' });
+ return;
+ }
+ body.returnUrl = parsedReturnUrl.href;
+ }
+
const deviceId = body.deviceId || req.headers['x-device-id'] || null;
if (deviceId && ctx.deviceRepo) {
let dev = ctx.deviceRepo.findById(deviceId);
diff --git a/apps/payment-help/src/server.js b/apps/payment-help/src/server.js
index 513854f..5322765 100644
--- a/apps/payment-help/src/server.js
+++ b/apps/payment-help/src/server.js
@@ -7,6 +7,15 @@ import { getDatabase, SupportTicketRepository } from '@youpi/db';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
+// The help portal is a standalone page, never framed, so it locks framing down
+// to 'self'. script-src keeps 'unsafe-inline' because help.html ships inline
+// JavaScript; hardening that needs nonces and is tracked separately.
+const HELP_SECURITY_HEADERS = Object.freeze({
+ 'X-Content-Type-Options': 'nosniff',
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
+ 'Content-Security-Policy': "default-src 'self' data: blob:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
+});
+
// 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 {
@@ -73,13 +82,14 @@ export class HelpServer {
const html = this.renderHtml();
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
- 'Cache-Control': 'no-cache'
+ 'Cache-Control': 'no-cache',
+ ...HELP_SECURITY_HEADERS
});
res.end(html);
return;
}
- res.writeHead(404, { 'Content-Type': 'text/plain' });
+ res.writeHead(404, { 'Content-Type': 'text/plain', ...HELP_SECURITY_HEADERS });
res.end('Help Portal Route Not Found');
});
}
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index db54f41..237c84f 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -28,7 +28,7 @@
| `YOUPI_ALLOW_DEV_TOOLS` | unset | Developer test-mode / simulator endpoints (`/admin/dev/*`, `simulate-observation`) are refused when `NODE_ENV=production` unless this is `true` |
| `GMAIL_REDIRECT_URI` | derived | Gmail OAuth redirect URI. Defaults to `<gmail host from your configured domain>/oauth/callback` |
| `ANDROID_HEARTBEAT_TIMEOUT_MS` | `180000` | Inactivity window before Android device is marked DISCONNECTED |
-| `CHECKOUT_FRAME_ANCESTORS` | unset (any origin) | Merchant origins (comma or space separated, e.g. `https://shop.example.com`) allowed to embed `/checkout/:id`. The `youpi.js` modal is an iframe, so a store on a different origin than the checkout portal must be listed here or the browser blocks the modal. When unset, any site may frame the checkout page. Only bare `http(s)` origins are accepted — a path, query, embedded credential or wildcard is ignored, so the value cannot widen the CSP or inject another directive |
+| `CHECKOUT_FRAME_ANCESTORS` | unset (any origin in development, `'self'` in production) | Merchant origins (comma or space separated, e.g. `https://shop.example.com`) allowed to embed `/checkout/:id`. The `youpi.js` modal is an iframe, so a store on a different origin than the checkout portal must be listed here or the browser blocks the modal. When unset, any site may frame the checkout page in development, while a production deployment (either `NODE_ENV=production` or `YOUPI_MODE=production`) fences the page to its own origin. Only bare `http(s)` origins are accepted — a path, query, embedded credential or wildcard is ignored, so the value cannot widen the CSP or inject another directive |
| `YOUPI_ALLOW_PRIVATE_WEBHOOKS` | unset | Set to `true` to permit merchant webhook URLs on loopback/private networks. Required for self-hosted LAN targets; blocked by default as an SSRF guard |
---
diff --git a/packages/merchant-sdk/src/youpi-checkout.js b/packages/merchant-sdk/src/youpi-checkout.js
index bf5abd9..c8fa2b4 100644
--- a/packages/merchant-sdk/src/youpi-checkout.js
+++ b/packages/merchant-sdk/src/youpi-checkout.js
@@ -257,6 +257,16 @@
const sep = targetUrl.includes('?') ? '&' : '?';
targetUrl = `${targetUrl}${sep}embedded=1`;
+ // Declare this page's origin so the checkout can target its postMessages
+ // even when the browser strips the referrer. Opaque origins (file:) and
+ // non-http(s) schemes must not be announced.
+ try {
+ const parsed = new URL(window.location.href);
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
+ targetUrl += `&youpiParentOrigin=${encodeURIComponent(parsed.origin)}`;
+ }
+ } catch {}
+
if (this.options.amount) {
targetUrl += `&customAmount=${encodeURIComponent(this.options.amount)}`;
}
diff --git a/packages/merchant-sdk/src/youpi.js b/packages/merchant-sdk/src/youpi.js
index 51918bc..5f36c8d 100644
--- a/packages/merchant-sdk/src/youpi.js
+++ b/packages/merchant-sdk/src/youpi.js
@@ -267,6 +267,16 @@
const sep = targetUrl.includes('?') ? '&' : '?';
targetUrl = `${targetUrl}${sep}embedded=1`;
+ // Declare this page's origin so the checkout can target its postMessages
+ // even when the browser strips the referrer. Opaque origins (file:) and
+ // non-http(s) schemes must not be announced.
+ try {
+ const parsed = new URL(window.location.href);
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
+ targetUrl += `&youpiParentOrigin=${encodeURIComponent(parsed.origin)}`;
+ }
+ } catch {}
+
if (this.options.amount) {
targetUrl += `&customAmount=${encodeURIComponent(this.options.amount)}`;
}
diff --git a/scripts/test-all.js b/scripts/test-all.js
index db48680..5abed92 100644
--- a/scripts/test-all.js
+++ b/scripts/test-all.js
@@ -13,6 +13,7 @@ const testFiles = [
'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/checkout-portal/src/__tests__/issue-64-hardening.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',