randomayzer/tools/production-transport.cjs

21 lines
1.2 KiB
JavaScript

'use strict';
const { isIP } = require('node:net');
function normalizePeer(ip) { return (ip || '').replace(/^::ffff:/, ''); }
/** Run before handing the raw HTTP request to Next. Never use a header as peer identity. */
function sanitizeProxyHeaders(req, { trustedProxyIp, origin }) {
const peer = normalizePeer(req.socket.remoteAddress);
const trusted = !!trustedProxyIp && peer === trustedProxyIp;
const forwarded = req.headers['x-forwarded-for'];
const proto = req.headers['x-forwarded-proto'];
for (const key of Object.keys(req.headers)) {
if (key.startsWith('x-forwarded-') || ['forwarded', 'x-real-ip', 'cf-connecting-ip'].includes(key)) delete req.headers[key];
}
// Our VPS overwrites this with one client address; chains are deliberately unsupported.
const client = trusted && typeof forwarded === 'string' && isIP(forwarded) ? forwarded : peer;
req.headers['x-forwarded-for'] = isIP(client) ? client : 'unknown-client';
req.headers['x-forwarded-proto'] = trusted && proto === 'https' ? 'https' : 'http';
req.headers['x-forwarded-host'] = origin.host;
req.headers['x-forwarded-port'] = origin.port || (origin.protocol === 'https:' ? '443' : '80');
req.headers.host = origin.host;
}
module.exports = { sanitizeProxyHeaders };