configure iface address used via LOCAL_ADDRESS env var

This commit is contained in:
Jannis R 2021-02-07 22:17:02 +01:00
parent 2afe4154f8
commit cb8d92befb
No known key found for this signature in database
GPG key ID: 0FE83946296A88A5
2 changed files with 26 additions and 3 deletions

View file

@ -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),

View file

@ -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",