refactor: add a banner

pull/180/head
xiaojunnuo 2020-11-08 00:44:15 +08:00
parent 2a78765e6b
commit a392b4c54d
19 changed files with 38 additions and 516 deletions

8
packages/core/banner.txt Normal file
View File

@ -0,0 +1,8 @@
____ _____ _ __
/ __ \___ _ __ / ___/(_)___/ /__ _________ ______
/ / / / _ \ | / /_____\__ \/ / __ / _ \/ ___/ __ `/ ___/
/ /_/ / __/ |/ /_____/__/ / / /_/ / __/ /__/ /_/ / /
/_____/\___/|___/ /____/_/\__,_/\___/\___/\__,_/_/
==================== 开发者边车 ====================

View File

@ -67,7 +67,9 @@ module.exports = {
plugins.push(start())
}
}
if (plugins && plugins.length > 0) {
await Promise.all(plugins)
}
},
shutdown: async () => {
try {

View File

@ -8,7 +8,7 @@ process.on('uncaughtException', function (err) {
// console.error(err.errno)
return
}
console.error(err)
console.error('uncaughtException',err)
})
process.on('unhandledRejection', (reason, p) => {

View File

@ -79,7 +79,7 @@ module.exports = (config) => {
}
} catch (err) {
// 拦截失败
console.error(err)
console.error('拦截处理失败',err)
}
}
}

View File

@ -12,7 +12,6 @@ let server
function start () {
const config = JSON.parse(process.argv[2])
const proxyOptions = ProxyOptions(config)
console.log('proxy options:', proxyOptions)
const newServer = mitmproxy.createProxy(proxyOptions, () => {
fireStatus(true)
console.log('代理服务已启动127.0.0.1:' + proxyOptions.port)

View File

@ -65,8 +65,9 @@ async function _winSetProxy (exec, ip, port) {
_winAsyncRegSet(regKey, 'ProxyServer', Registry.REG_SZ, `${ip}:${port}`),
_winAsyncRegSet(regKey, 'ProxyOverride', Registry.REG_SZ, lanIpStr)
])
console.log('---代理设置成功等待refresh------')
console.log('代理设置成功等待refresh')
await exec([refreshInternetPs])
console.log('代理设置refresh完成')
return true
}

View File

@ -1,26 +0,0 @@
const config = require('../../../lib/proxy/common/config')
const Shell = require('../../../shell')
module.exports = {
async setProxy (ip, port) {
const cmds = [
`npm config set proxy=http://${ip}:${port}`,
`npm config set https-proxy=http://${ip}:${port}`,
`npm config set NODE_EXTRA_CA_CERTS ${config.getDefaultCACertPath()}`,
'npm config set strict-ssl false'
]
const ret = await Shell.exec(cmds)
return ret
},
async unsetProxy () {
const cmds = [
'npm config delete proxy',
'npm config delete https-proxy',
'npm config delete NODE_EXTRA_CA_CERTS',
'npm config delete strict-ssl'
]
const ret = await Shell.exec(cmds)
return ret
}
}

View File

@ -1,14 +0,0 @@
const script = `
$signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
'@
$INTERNET_OPTION_SETTINGS_CHANGED = 39
$INTERNET_OPTION_REFRESH = 37
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
$a -and $b
`
module.exports = script

View File

@ -1,61 +0,0 @@
const script = `
Function Set-InternetProxy
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String[]]$Proxy,
[Parameter(Mandatory=$False,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[AllowEmptyString()]
[String[]]$acs
)
Begin
{
$regKey="HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
}
Process
{
Set-ItemProperty -path $regKey ProxyEnable -value 1
Set-ItemProperty -path $regKey ProxyServer -value $proxy
if($acs)
{
Set-ItemProperty -path $regKey AutoConfigURL -Value $acs
}
}
End
{
Write-Output "Proxy is now enabled"
Write-Output "Proxy Server : $proxy"
if ($acs)
{
Write-Output "Automatic Configuration Script : $acs"
}
else
{
Write-Output "Automatic Configuration Script : Not Defined"
}
}
}
`
module.exports = script

View File

@ -1,191 +0,0 @@
const util = require('util')
const os = require('os')
const childProcess = require('child_process')
const _exec = childProcess.exec
const Registry = require('winreg')
// const cmd = require('node-cmd')
const exec = util.promisify(_exec)
const refreshInternetPs = require('./refresh-internet')
const PowerShell = require('node-powershell')
const _lanIP = [
'localhost',
'127.*',
'10.*',
'172.16.*',
'172.17.*',
'172.18.*',
'172.19.*',
'172.20.*',
'172.21.*',
'172.22.*',
'172.23.*',
'172.24.*',
'172.25.*',
'172.26.*',
'172.27.*',
'172.28.*',
'172.29.*',
'172.30.*',
'172.31.*',
'192.168.*',
'<local>'
]
class SystemProxy {
static async setProxy (ip, port) {
throw new Error('You have to implement the method setProxy!')
}
static async unsetProxy () {
throw new Error('You have to implement the method unsetProxy!')
}
}
// TODO: Add path http_proxy and https_proxy
// TODO: Support for non-gnome
class LinuxSystemProxy extends SystemProxy {
static async setProxy (ip, port) {
await exec('gsettings set org.gnome.system.proxy mode manual')
await exec(`gsettings set org.gnome.system.proxy.http host ${ip}`)
await exec(`gsettings set org.gnome.system.proxy.http port ${port}`)
}
static async unsetProxy () {
await exec('gsettings set org.gnome.system.proxy mode none')
}
}
// TODO: Support for lan connections too
// TODO: move scripts to ../scripts/darwin
class DarwinSystemProxy extends SystemProxy {
static async setProxy (ip, port) {
const wifiAdaptor = (await exec('sh -c "networksetup -listnetworkserviceorder | grep `route -n get 0.0.0.0 | grep \'interface\' | cut -d \':\' -f2` -B 1 | head -n 1 | cut -d \' \' -f2"')).stdout.trim()
await exec(`networksetup -setwebproxy '${wifiAdaptor}' ${ip} ${port}`)
await exec(`networksetup -setsecurewebproxy '${wifiAdaptor}' ${ip} ${port}`)
}
static async unsetProxy () {
const wifiAdaptor = (await exec('sh -c "networksetup -listnetworkserviceorder | grep `route -n get 0.0.0.0 | grep \'interface\' | cut -d \':\' -f2` -B 1 | head -n 1 | cut -d \' \' -f2"')).stdout.trim()
await exec(`networksetup -setwebproxystate '${wifiAdaptor}' off`)
await exec(`networksetup -setsecurewebproxystate '${wifiAdaptor}' off`)
}
}
class WindowsSystemProxy extends SystemProxy {
static async setProxy (ip, port) {
const regKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'
})
let lanIpStr = ''
for (const string of _lanIP) {
lanIpStr += string + ';'
}
// console.log('lanIps:', lanIpStr, ip, port)
await Promise.all([
WindowsSystemProxy._asyncRegSet(regKey, 'MigrateProxy', Registry.REG_DWORD, 1),
WindowsSystemProxy._asyncRegSet(regKey, 'ProxyEnable', Registry.REG_DWORD, 1),
WindowsSystemProxy._asyncRegSet(regKey, 'ProxyHttp1.1', Registry.REG_DWORD, 0),
WindowsSystemProxy._asyncRegSet(regKey, 'ProxyServer', Registry.REG_SZ, `${ip}:${port}`),
WindowsSystemProxy._asyncRegSet(regKey, 'ProxyOverride', Registry.REG_SZ, lanIpStr)
])
await WindowsSystemProxy._resetWininetProxySettings('echo refreshing') // 要执行以下这个才能生效
await WindowsSystemProxy._resetWininetProxySettings(refreshInternetPs)
}
static async unsetProxy () {
const regKey = new Registry({
hive: Registry.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'
})
await Promise.all([
WindowsSystemProxy._asyncRegSet(regKey, 'ProxyEnable', Registry.REG_DWORD, 0),
WindowsSystemProxy._asyncRegSet(regKey, 'ProxyServer', Registry.REG_SZ, '')
])
await WindowsSystemProxy._resetWininetProxySettings(refreshInternetPs)
}
static _asyncRegSet (regKey, name, type, value) {
return new Promise((resolve, reject) => {
regKey.set(name, type, value, e => {
if (e) {
reject(e)
} else {
resolve()
}
})
})
}
static _resetWininetProxySettings (script) {
return new Promise((resolve, reject) => {
const ps = new PowerShell({
executionPolicy: 'Bypass',
noProfile: true
})
// ps.addCommand(setproxyPs)
// ps.addCommand(`Set-InternetProxy -Proxy "${ip}:${port}"`)
ps.addCommand(script)
ps.invoke()
.then(output => {
// console.log(output)
resolve()
})
.catch(err => {
console.log(err)
reject(err)
})
// const scriptPath = path.join(__dirname, '..', 'scripts', 'windows', 'wininet-reset-settings.ps1')
// const child = spawn('powershell.exe', [scriptPath])
// child.stdout.setEncoding('utf8')
// child.stdout.on('data', (data) => {
// console.log('data', data)
// if (data.includes('True')) {
// resolve()
// } else {
// reject(data)
// }
// })
//
// child.stderr.on('data', (err) => {
// console.log('data', err)
// reject(err)
// })
//
// child.stdin.end()
})
}
}
function getSystemProxy () {
switch (os.platform()) {
case 'darwin':
return DarwinSystemProxy
case 'linux':
return LinuxSystemProxy
case 'win32':
case 'win64':
return WindowsSystemProxy
case 'unknown os':
default:
throw new Error(`UNKNOWN OS TYPE ${os.platform()}`)
}
}
module.exports = {
async setProxy (ip, port) {
const systemProxy = getSystemProxy()
await systemProxy.setProxy(ip, port)
},
async unsetProxy () {
const systemProxy = getSystemProxy()
await systemProxy.unsetProxy()
}
}

View File

@ -1,89 +0,0 @@
const cmd = require('node-cmd')
const util = require('util')
const winExec = util.promisify(cmd.get, { multiArgs: true, context: cmd })
const os = require('os')
// eslint-disable-next-line no-unused-vars
const config = require('../../../lib/proxy/common/config')
class SystemProxy {
static async setProxy (ip, port) {
throw new Error('You have to implement the method setProxy!')
}
static async unsetProxy () {
throw new Error('You have to implement the method unsetProxy!')
}
}
class DarwinSystemProxy extends SystemProxy {
}
class LinuxSystemProxy extends SystemProxy {
}
class WindowsSystemProxy extends SystemProxy {
static async setProxy (ip, port) {
let ret = await winExec(`yarn config set proxy=http://${ip}:${port}`)
console.log('yarn http proxy set success', ret)
ret = await winExec(`yarn config set https-proxy=http://${ip}:${port}`)
console.log('yarn https proxy set success', ret)
ret = await winExec(`yarn config set cafile ${config.getDefaultCACertPath()}`)
console.log('yarn cafile set success', ret)
// ret = await winExec('yarn config set strict-ssl false')
// console.log('yarn strict-ssl false success', ret)
}
static async unsetProxy () {
await winExec('yarn config delete proxy')
console.log('yarn https proxy unset success')
await winExec('yarn config delete https-proxy')
console.log('yarn https proxy unset success')
await winExec('yarn config delete cafile')
console.log('yarn ca unset success')
// await winExec(' yarn config delete strict-ssl')
// console.log('yarn strict-ssl true success')
}
static _asyncRegSet (regKey, name, type, value) {
return new Promise((resolve, reject) => {
regKey.set(name, type, value, e => {
if (e) {
reject(e)
} else {
resolve()
}
})
})
}
}
function getSystemProxy () {
switch (os.platform()) {
case 'darwin':
return DarwinSystemProxy
case 'linux':
return LinuxSystemProxy
case 'win32':
case 'win64':
return WindowsSystemProxy
case 'unknown os':
default:
throw new Error(`UNKNOWN OS TYPE ${os.platform()}`)
}
}
module.exports = {
async setProxy (ip, port) {
const systemProxy = getSystemProxy()
await systemProxy.setProxy(ip, port)
},
async unsetProxy () {
const systemProxy = getSystemProxy()
await systemProxy.unsetProxy()
}
}

View File

@ -1,34 +0,0 @@
const systemProxy = require('./impl/system-proxy')
const npmProxy = require('./impl/npm-proxy')
const yarnProxy = require('./impl/yarn-proxy')
const event = require('../../event')
const config = require('../../config')
function createProxyApi (type, impl) {
return {
async open (conf = { ip: '127.0.0.1', port: config.get().server.port }) {
try {
const { ip, port } = conf
await impl.setProxy(ip, port)
event.fire('status', { key: 'proxy.' + type, value: true })
console.info(`开启【${type}】代理成功`)
} catch (e) {
console.error(`开启【${type}】代理失败`, e)
}
},
async close () {
try {
await impl.unsetProxy()
event.fire('status', { key: 'proxy.' + type, value: false })
console.info(`关闭【${type}】代理成功`)
} catch (e) {
console.error(`关闭【${type}】代理失败`, e)
}
}
}
}
module.exports = {
system: createProxyApi('system', systemProxy),
npm: createProxyApi('npm', npmProxy),
yarn: createProxyApi('yarn', yarnProxy)
}

View File

@ -1,74 +0,0 @@
<#
.Synopsis
This function will set the proxy settings provided as input to the cmdlet.
.Description
This function will set the proxy server and (optinal) Automatic configuration script.
.Parameter ProxyServer
This parameter is set as the proxy for the system.
Data from. This parameter is Mandatory
.Example
Setting proxy information
Set-InternetProxy -proxy "proxy:7890"
.Example
Setting proxy information and (optinal) Automatic Configuration Script
Set-InternetProxy -proxy "proxy:7890" -acs "http://proxy:7892"
#>
Function Set-InternetProxy
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String[]]$Proxy,
[Parameter(Mandatory=$False,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[AllowEmptyString()]
[String[]]$acs
)
Begin
{
$regKey="HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
}
Process
{
Set-ItemProperty -path $regKey ProxyEnable -value 1
Set-ItemProperty -path $regKey ProxyServer -value $proxy
if($acs)
{
Set-ItemProperty -path $regKey AutoConfigURL -Value $acs
}
}
End
{
Write-Output "Proxy is now enabled"
Write-Output "Proxy Server : $proxy"
if ($acs)
{
Write-Output "Automatic Configuration Script : $acs"
}
else
{
Write-Output "Automatic Configuration Script : Not Defined"
}
}
}

View File

@ -1,14 +0,0 @@
$signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int
dwOption, IntPtr lpBuffer, int dwBufferLength);
'@
$interopHelper = Add-Type -MemberDefinition $signature -Name MyInteropHelper -PassThru
$INTERNET_OPTION_SETTINGS_CHANGED = 39
$INTERNET_OPTION_REFRESH = 37
$result1 = $interopHelper::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$result2 = $interopHelper::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
$result1 -and $result2

View File

@ -1,9 +1,16 @@
const DevSidercar = require('.')
const fs = require('fs')
// require('json5/lib/register')
// const config = require('../../config/index.json5')
// 启动服务
const mitmproxyPath = './mitmproxy'
DevSidercar.api.startup({ mitmproxyPath })
async function startup () {
const banner = fs.readFileSync('./banner.txt')
console.log(banner.toString())
await DevSidercar.api.startup({ mitmproxyPath })
console.log('dev-sidecar 已启动')
}
async function onClose () {
console.log('on sigint ')
await DevSidercar.api.shutdown()
@ -11,3 +18,5 @@ async function onClose () {
process.exit(0)
}
process.on('SIGINT', onClose)
startup()

View File

@ -42,7 +42,6 @@ function registerProcessListener () {
const api = {
async start (config) {
const proxyOptions = ProxyOptions(config)
console.log('proxy options:', proxyOptions)
if (proxyOptions.setting && proxyOptions.setting.NODE_TLS_REJECT_UNAUTHORIZED === false) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
} else {

View File

@ -34,7 +34,7 @@ util.getOptionsFormRequest = (req, ssl, externalProxy = null) => {
try {
externalProxyUrl = externalProxy(req, ssl)
} catch (e) {
console.error(e)
console.error('externalProxy',e)
}
}
}

View File

@ -14,7 +14,7 @@ module.exports = function createConnectHandler (sslConnectInterceptor, fakeServe
fakeServerCenter.getServerPromise(hostname, srvUrl.port).then((serverObj) => {
connect(req, cltSocket, head, localIP, serverObj.port)
}, (e) => {
console.error(e)
console.error('getServerPromise', e)
})
} else {
if (dnsConfig) {
@ -35,7 +35,7 @@ function connect (req, cltSocket, head, hostname, port) {
// console.log('connect:', hostname, port)
const start = new Date().getTime()
try {
const proxySocket = net.connect(port, hostname, () => {
const proxySocket = net.connect({ port, host: hostname, connectTimeout: 5000 }, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: dev-sidecar\r\n' +
'\r\n')
@ -45,14 +45,21 @@ function connect (req, cltSocket, head, hostname, port) {
cltSocket.pipe(proxySocket)
})
proxySocket.on('timeout', () => {
const end = new Date().getTime()
console.log('代理socket timeout', hostname, port, (end - start) + 'ms')
proxySocket.destroy()
cltSocket.destroy()
})
proxySocket.on('error', (e) => {
// 连接失败可能被GFW拦截或者服务端拥挤
const end = new Date().getTime()
console.error('代理连接失败:', e.errno, hostname, port, (end - start) / 1000 + 'ms')
console.error('代理连接失败:', e.message, hostname, port, (end - start) + 'ms')
cltSocket.destroy()
})
return proxySocket
} catch (error) {
console.log('err', error)
console.log('connect err', error)
}
}

View File

@ -172,7 +172,7 @@ module.exports = function createRequestHandler (requestInterceptor, responseInte
res.write(`Dev-Sidecar Warning:\n\n ${e.toString()}`)
res.end()
}
console.error(e)
console.error('request error', e.message)
}
)
}