'use strict'; // Public base URL of this server, as seen by clients. Used for OAuth // metadata, the `iss` parameter, and links in the OpenAPI spec. // // config.json: // "publicUrl": "https://files.example.com" (optional, wins when set) // "trustProxy": "loopback" (Express "trust proxy"; default // trusts only a proxy on the same // machine; false disables) const { loadConfig } = require('./config'); const DEFAULT_TRUST_PROXY = 'loopback'; function normalizePublicUrl (raw) { if (typeof raw !== 'string' || !raw.trim()) return null; let u; try { u = new URL(raw.trim()); } catch { return null; } if (u.protocol !== 'https:' && u.protocol !== 'http:') return null; if (u.username || u.password || u.search || u.hash) return null; return `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/, '')}`; } /** * Value for app.set('trust proxy', ...). Accepts what Express accepts: * boolean, hop count, or (comma separated / array of) addresses, subnets * and the names loopback, linklocal, uniquelocal. */ function trustProxySetting (config) { const v = config ? config.trustProxy : undefined; if (v === undefined || v === null || v === '') return DEFAULT_TRUST_PROXY; if (typeof v === 'boolean') return v; if (typeof v === 'number' && Number.isInteger(v) && v >= 0) return v; if (typeof v === 'string') return v.trim(); if (Array.isArray(v) && v.every((x) => typeof x === 'string')) return v; return DEFAULT_TRUST_PROXY; } function publicBaseUrl (req) { const configured = normalizePublicUrl(loadConfig().publicUrl); if (configured) return configured; return `${req.protocol}://${requestHost(req)}`; } /** Host header, or X-Forwarded-Host when the direct peer is a trusted proxy. */ function requestHost (req) { const fwd = req.get('x-forwarded-host'); const trust = req.app && req.app.get('trust proxy fn'); const peer = req.socket && req.socket.remoteAddress; if (fwd && typeof trust === 'function' && trust(peer, 0)) { const first = fwd.split(',')[0].trim(); if (/^[A-Za-z0-9.\-:[\]]+$/.test(first)) return first; } return req.get('host'); } /** Path prefix of the public URL ('' when served at the root). */ function publicPathPrefix (req) { try { return new URL(publicBaseUrl(req)).pathname.replace(/\/+$/, ''); } catch { return ''; } } module.exports = { normalizePublicUrl, trustProxySetting, publicBaseUrl, publicPathPrefix, DEFAULT_TRUST_PROXY };