From cb8d92befbbc0c5868b2a25147904a89091717df Mon Sep 17 00:00:00 2001 From: Jannis R Date: Sun, 7 Feb 2021 22:17:02 +0100 Subject: [PATCH] configure iface address used via LOCAL_ADDRESS env var --- lib/request.js | 28 +++++++++++++++++++++++++--- package.json | 1 + 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lib/request.js b/lib/request.js index f9f02de5..0db3ca4f 100644 --- a/lib/request.js +++ b/lib/request.js @@ -3,18 +3,40 @@ const DEV = process.env.NODE_ENV === 'dev' const DEBUG = /\bhafas-client\b/.test(process.env.DEBUG || '') +const ProxyAgent = require('https-proxy-agent') +const {isIP} = require('net') +const {Agent: HttpsAgent} = require('https') +const roundRobin = require('@derhuerst/round-robin-scheduler') const {randomBytes} = require('crypto') const createHash = require('create-hash') const pick = require('lodash/pick') const captureStackTrace = DEV ? require('capture-stack-trace') : () => {} const {stringify} = require('qs') -const ProxyAgent = require('https-proxy-agent') const Promise = require('pinkie-promise') const {fetch} = require('fetch-ponyfill')({Promise}) const {addErrorInfo} = require('./errors') const proxyAddress = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || null -const proxyAgent = proxyAddress ? new ProxyAgent(proxyAddress) : null +const localAddresses = process.env.LOCAL_ADDRESS || null + +if (proxyAddress && localAddresses) { + console.error('Both env vars HTTPS_PROXY/HTTP_PROXY and LOCAL_ADDRESS are not supported.') + process.exit(1) +} +let getAgent = () => null +if (proxyAddress) { + const agent = new ProxyAgent(proxyAddress) + getAgent = () => agent +} else if (localAddresses) { + const agents = process.env.LOCAL_ADDRESS.split(',') + .map((addr) => { + const family = isIP(addr) + if (family === 0) throw new Error('invalid local address:' + addr) + return new HttpsAgent({addr, family}) + }) + const pool = roundRobin(agents) + getAgent = () => pool.get() +} const id = randomBytes(6).toString('hex') const randomizeUserAgent = (userAgent) => { @@ -42,7 +64,7 @@ const request = (ctx, userAgent, reqData) => { if (DEBUG) console.error(JSON.stringify(body)) const req = profile.transformReq(ctx, { - agent: proxyAgent, + agent: getAgent(), method: 'post', // todo: CORS? referrer policy? body: JSON.stringify(body), diff --git a/package.json b/package.json index 0cce9f2c..4f50a861 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ }, "dependencies": { "@derhuerst/br2nl": "^1.0.0", + "@derhuerst/round-robin-scheduler": "^1.0.4", "capture-stack-trace": "^1.0.0", "create-hash": "^1.2.0", "fetch-ponyfill": "^7.0.0",