main
ts 40 lines 1.63 KB
Raw
1 import { configReady, defineConfig } from './config'
2 import { httpStream, httpString, parseHttpUrl } from './util-http'
3 import { reg } from './util-os'
4 import { IS_WINDOWS } from './const'
5 import { CFG, prefix } from './cross'
6
7 const outboundProxy = defineConfig(CFG.outbound_proxy, '', v => {
8 httpStream.defaultProxy = undefined
9 if (!v) return
10 try {
11 parseHttpUrl(v) // just validate
12 httpStream.defaultProxy = v
13 if (!v || process.env.HFS_SKIP_PROXY_TEST) return
14 const test = 'https://google.com'
15 console.debug("Testing proxy using", test)
16 httpString(test, { noRedirect: true }).catch(e =>
17 console.error(`Proxy test failed on ${test} : ${e?.errors?.[0] || e}`)) // `.errors` in case of AggregateError
18 }
19 catch {
20 console.warn("Invalid URL", v)
21 return ''
22 }
23 })
24
25 configReady.then(async (startedWithoutConfig) => {
26 if (!IS_WINDOWS || !startedWithoutConfig) return
27 // try to read Windows system setting for proxy
28 const out = await reg('query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
29 .catch(() => '')
30 if (!Number(/ProxyEnable\s+\w+\s+(.+)/.exec(out)?.[1])) return
31 const read = /ProxyServer\s+\w+\s+(.+)/.exec(out)?.[1]
32 if (!read) return
33 // it can be like "IP:PORT" or "http=IP:PORT;https=IP:PORT;ftp=IP:PORT"
34 const url = prefix('https://', /https=([\d:.]+)/.exec(out)?.[1]) // prefer https
35 || prefix('http://', /http=([\d:.]+)/.exec(out)?.[1])
36 || !read.includes('=') && 'http://' + read // simpler form
37 if (!url) return
38 outboundProxy.set(url)
39 console.log("Detected proxy", read)
40 })