Skip to content

Commit

Permalink
feat: add x-forwarded header (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
embbnux authored May 28, 2022
1 parent 12e400a commit cfcf10c
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,24 @@ app.get('/tunnel_jwt_generator', (req, res) => {
res.send('Forbidden');
});

function getReqHeaders(req) {
const encrypted = !!(req.isSpdy || req.connection.encrypted || req.connection.pair);
const headers = { ...req.headers };
const url = new URL(`${encrypted ? 'https' : 'http'}://${req.headers.host}`);
const forwardValues = {
for: req.connection.remoteAddress || req.socket.remoteAddress,
port: url.port || (encrypted ? 443 : 80),
proto: encrypted ? 'https' : 'http',
};
['for', 'port', 'proto'].forEach((key) => {
const previousValue = req.headers[`x-forwarded-${key}`] || '';
headers[`x-forwarded-${key}`] =
`${previousValue || ''}${previousValue ? ',' : ''}${forwardValues[key]}`;
});
headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers.host || '';
return headers;
}

app.use('/', (req, res) => {
const tunnelSocket = tunnelSockets[req.headers.host];
if (!tunnelSocket) {
Expand All @@ -88,7 +106,7 @@ app.use('/', (req, res) => {
requestId,
request: {
method: req.method,
headers: { ...req.headers },
headers: getReqHeaders(req),
path: req.url,
},
});
Expand Down Expand Up @@ -164,7 +182,7 @@ httpServer.on('upgrade', (req, socket, head) => {
requestId,
request: {
method: req.method,
headers: { ...req.headers },
headers: getReqHeaders(req),
path: req.url,
},
});
Expand Down

0 comments on commit cfcf10c

Please sign in to comment.