|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const config = require('../config'); |
| 4 | + |
| 5 | +/** |
| 6 | + * Embed (iframe) restrictions. |
| 7 | + * |
| 8 | + * Controls which origins may embed MiroTalk P2P in an <iframe> via CSP |
| 9 | + * `frame-ancestors` (and `X-Frame-Options` for legacy browsers). |
| 10 | + * Configured via ALLOWED_EMBED_ORIGINS env var. See config.server.embed. |
| 11 | + */ |
| 12 | +const embedAllowedOrigins = Array.isArray(config?.server?.embed?.allowedOrigins) |
| 13 | + ? config.server.embed.allowedOrigins |
| 14 | + : []; |
| 15 | + |
| 16 | +function buildEmbedCsp(origins) { |
| 17 | + if (!origins || origins.length === 0) { |
| 18 | + // Allow embedding from anywhere (default, no header set) |
| 19 | + return null; |
| 20 | + } |
| 21 | + // Single-token shortcuts |
| 22 | + if (origins.length === 1) { |
| 23 | + const single = origins[0].toLowerCase(); |
| 24 | + if (single === 'none' || single === "'none'") { |
| 25 | + return { csp: "frame-ancestors 'none'", xfo: 'DENY' }; |
| 26 | + } |
| 27 | + if (single === 'self' || single === "'self'") { |
| 28 | + return { csp: "frame-ancestors 'self'", xfo: 'SAMEORIGIN' }; |
| 29 | + } |
| 30 | + } |
| 31 | + // Build allow-list; always include 'self' implicitly so the app's own |
| 32 | + // pages can still iframe themselves (share popups, etc.) |
| 33 | + const sources = ["'self'"]; |
| 34 | + for (const o of origins) { |
| 35 | + const v = o.trim(); |
| 36 | + if (!v) continue; |
| 37 | + if (v.toLowerCase() === 'self' || v === "'self'") continue; |
| 38 | + if (v.toLowerCase() === 'none' || v === "'none'") continue; |
| 39 | + sources.push(v); |
| 40 | + } |
| 41 | + // X-Frame-Options cannot express multiple origins; omit it to avoid |
| 42 | + // contradicting the CSP (modern browsers prefer CSP anyway). |
| 43 | + return { csp: `frame-ancestors ${sources.join(' ')}`, xfo: null }; |
| 44 | +} |
| 45 | + |
| 46 | +const embedCsp = buildEmbedCsp(embedAllowedOrigins); |
| 47 | + |
| 48 | +const applyEmbedHeaders = (req, res, next) => { |
| 49 | + if (embedCsp) { |
| 50 | + // Merge with any existing CSP header set earlier in the chain |
| 51 | + const existing = res.getHeader('Content-Security-Policy'); |
| 52 | + const merged = existing ? `${existing}; ${embedCsp.csp}` : embedCsp.csp; |
| 53 | + res.setHeader('Content-Security-Policy', merged); |
| 54 | + if (embedCsp.xfo) { |
| 55 | + res.setHeader('X-Frame-Options', embedCsp.xfo); |
| 56 | + } |
| 57 | + } |
| 58 | + next(); |
| 59 | +}; |
| 60 | + |
| 61 | +module.exports = { |
| 62 | + applyEmbedHeaders, |
| 63 | + buildEmbedCsp, |
| 64 | + embedAllowedOrigins, |
| 65 | + embedCsp, |
| 66 | +}; |
0 commit comments