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 the checkout frame-ancestors allowlist
rishabhce4a2a4e42d3
diff --cc .env.exampleindex b5a2fb4,3ad1b83..8b317cc--- a/.env.example+++ b/.env.example@@@ -24,6 -23,9 +24,8 @@@ BASE_CHECKOUT_URL=http://localhost:700BASE_ADMIN_URL=http://localhost:6001BASE_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.-# CHECKOUT_FRAME_ANCESTORS=https://shop.example.com# --- DATABASE CONFIGURATION ---# PostgreSQL connection string:@@@ -66,11 -68,6 +68,14 @@@ ANDROID_HEARTBEAT_TIMEOUT_MS=18000WEBHOOK_MAX_RETRIES=5WEBHOOK_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.++# 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 ---DEFAULT_APP_NAME="YOUPI PG"DEFAULT_PRIMARY_COLOR="#2563eb"diff --cc apps/checkout-portal/src/__tests__/checkout-portal.test.jsindex 3f36089,fe8a431..668160f--- a/apps/checkout-portal/src/__tests__/checkout-portal.test.js+++ b/apps/checkout-portal/src/__tests__/checkout-portal.test.js@@@ -2,7 -2,8 +2,8 @@@ import { test, describe, before, afterimport assert from 'node:assert/strict';import http from 'node:http';import { startCheckoutServer } from '../index.js';+import { generateQrMatrix, generateQrSvg } from '@youpi/core';+ import { frameAncestorOrigins } from '../server.js';-import { generateQrMatrix, generateQrSvg } from '../qr.js';describe('Checkout Portal Integration Tests', () => {let serverInstance;@@@ -85,6 -86,25 +86,33 @@@assert.equal(res.text.includes('available-offers-card'), false);});- test('GET /checkout/:id can be framed only by origins in CHECKOUT_FRAME_ANCESTORS', async () => {++ test('GET /checkout/:id framing is controlled by CHECKOUT_FRAME_ANCESTORS', async () => {++ // No allowlist configured: the checkout page stays framable by any origin, because++ // merchant storefronts embed it cross-origin. Deployments can pin the allowlist.+ const before = await get('/checkout/pay_test_uuid_12345');- assert.equal(before.headers['x-frame-options'], 'SAMEORIGIN');- assert.ok(before.headers['content-security-policy'].includes("frame-ancestors 'self';"));++ assert.equal(before.headers['x-frame-options'], undefined);++ assert.ok(before.headers['content-security-policy'].includes('frame-ancestors *;'));++ process.env.CHECKOUT_FRAME_ANCESTORS = 'https://shop.example.com, javascript:alert(1) https://x.test/path *';+ try {+ const res = await get('/checkout/pay_test_uuid_12345');+ assert.equal(res.headers['x-frame-options'], undefined);+ assert.ok(res.headers['content-security-policy'].includes("frame-ancestors 'self' https://shop.example.com;"));+ // The QR image stays unframeable.+ const qr = await get('/checkout/pay_test_uuid_12345/qr.svg');+ assert.equal(qr.headers['x-frame-options'], 'SAMEORIGIN');+ } finally {+ delete process.env.CHECKOUT_FRAME_ANCESTORS;+ }+ assert.deepEqual(frameAncestorOrigins('https://a.test http://localhost:5000/'), ['https://a.test', 'http://localhost:5000']);++ // Entries that are not a bare http(s) origin are rejected outright, so the value can++ // never widen the CSP or inject another directive.++ assert.deepEqual(frameAncestorOrigins('javascript:alert(1)'), []);++ assert.deepEqual(frameAncestorOrigins('https://x.test/path'), []);++ assert.deepEqual(frameAncestorOrigins('*'), []);++ assert.deepEqual(frameAncestorOrigins('https://user:[email protected]'), []);+ });+test('GET /checkout/:id/qr.svg returns dynamic SVG image', async () => {const res = await get('/checkout/pay_test_uuid_12345/qr.svg');assert.equal(res.status, 200);diff --cc apps/checkout-portal/src/server.jsindex 8677b67,980f52d..bb1f643--- a/apps/checkout-portal/src/server.js+++ b/apps/checkout-portal/src/server.js@@@ -16,91 -16,52 +16,107 @@@ const BASE_SECURITY_HEADERS = Object.fr'Content-Security-Policy': "default-src 'self'; 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'"});+const HTML_ESCAPES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };++ /**+ * Origins allowed to embed the checkout page, from CHECKOUT_FRAME_ANCESTORS+ * (comma or space separated, e.g. "https://shop.example.com"). youpi.js opens the+ * checkout in an iframe on the merchant's own site, which `frame-ancestors 'self'`+ * blocks whenever the store and the portal are on different origins. Anything that+ * is not a plain http(s) origin is ignored, so the CSP cannot be widened by accident.+ */+ export function frameAncestorOrigins(raw = process.env.CHECKOUT_FRAME_ANCESTORS) {+ const origins = [];+ for (const entry of String(raw || '').split(/[\s,]+/)) {+ if (!entry) continue;+ try {+ const url = new URL(entry);+ if ((url.protocol === 'https:' || url.protocol === 'http:') && entry.replace(/\/$/, '') === url.origin) {+ origins.push(url.origin);+ }+ } catch {}+ }+ return origins;+ }+-/** Headers for the embeddable checkout page: BASE_SECURITY_HEADERS plus any allowed embedders. */-function checkoutPageSecurityHeaders() {++/**++ * 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.++ */++function checkoutFrameHeaders() {+ const origins = frameAncestorOrigins();- if (!origins.length) return BASE_SECURITY_HEADERS;- // X-Frame-Options cannot express an allowlist; CSP frame-ancestors takes over.- const { 'X-Frame-Options': _xfo, ...rest } = BASE_SECURITY_HEADERS;+ return {- ...rest,- 'Content-Security-Policy': BASE_SECURITY_HEADERS['Content-Security-Policy']- .replace("frame-ancestors 'self'", `frame-ancestors 'self' ${origins.join(' ')}`)++ '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'`+ };+ }+/*** Escapes a value for interpolation into HTML text or attribute context.* Order ids, merchant names and branding fields are attacker-influenced, so they must* never be injected raw into the checkout template.*/-function escapeHtml(value) {- return String(value ?? '')- .replaceAll('&', '&')- .replaceAll('<', '<')- .replaceAll('>', '>')- .replaceAll('"', '"')- .replaceAll("'", ''');+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.- */- function resolveFrameAncestors() {- const configured = (process.env.CHECKOUT_FRAME_ANCESTORS || '').trim();- return configured || '*';- }-- /**- * Security headers for the embeddable checkout pages. Built per response so the- * frame-ancestors allowlist can be pinned per deployment via CHECKOUT_FRAME_ANCESTORS.- */- function checkoutFrameHeaders() {- 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 ${resolveFrameAncestors()}; base-uri 'none'; form-action 'self'; object-src 'none'`- };- }-+/**+ * 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);+ });}/**diff --cc docs/CONFIGURATION.mdindex 7bad9ec,9f34a4c..db54f41--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@@ -27,44 -27,8 +27,44 @@@| `YOUPI_EXPOSE_DEV_OTP` | unset | Set to `true` for local development to get the OTP in the `send-otp` response. Ignored when `NODE_ENV=production` || `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` |-| `CHECKOUT_FRAME_ANCESTORS` | unset | 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 || `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. |++| `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 |+| `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 |++---++## 1b. Merchant API Authentication (`X-Merchant-Key`)++Endpoints that expose merchant-private or customer-contact data require the caller to+prove which merchant it is. There are three accepted credentials:++| Credential | Header | Grants |+| :--- | :--- | :--- |+| Merchant webhook secret | `X-Merchant-Key: <merchant webhook secret>` | Full merchant-private view of that merchant's own sessions: `metadata`, `internalStatus`, `verificationLevel` / `verificationSources` / `verificationTag`, `returnUrl`, and customer contact details |+| Admin bearer token | `Authorization: Bearer <ADMIN_API_TOKEN>` | Full access to every merchant's data (operator tooling) |+| Observer bearer token | `Authorization: Bearer <OBSERVER_API_TOKEN>` | Full access to every merchant's data (local observer processes) |++Affected routes: `GET /api/v1/payments/:id`, `GET /api/v1/payments/:id/cod`,+`GET /api/v1/orders/:orderId/cod` and `GET /api/v1/checkout/:id/state`.++**Without a credential these routes return a redacted public view** — status, amount,+currency, method and order id only. Customer name, email and phone number are never+disclosed to an anonymous caller that merely holds a payment id.++The official SDK sends `X-Merchant-Key` automatically when the merchant secret is+configured, so existing integrations receive the full view with no code change:++```javascript+const client = new YoupiPaymentClient({+ apiUrl: 'https://pay-api.example.com',+ merchantId: '00000000-0000-0000-0000-000000000001',+ webhookSecret: 'your-merchant-webhook-secret' // enables the merchant-scoped view+});+```++A customer browsing the checkout page sees their own profile because the checkout client+sends the customer session token (`x-customer-token`), not because the payment id is+enough to unlock it.---