Skip to content

Commit

Permalink
代码格式调整:packages/mitmproxy/**/*.js
Browse files Browse the repository at this point in the history
  • Loading branch information
wangliang181230 committed Nov 15, 2024
1 parent 48132c3 commit 3e586bf
Show file tree
Hide file tree
Showing 56 changed files with 428 additions and 366 deletions.
15 changes: 8 additions & 7 deletions packages/mitmproxy/src/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
const mitmproxy = require('./lib/proxy')
const ProxyOptions = require('./options')
const proxyConfig = require('./lib/proxy/common/config')
const speedTest = require('./lib/speed/index.js')
const ProxyOptions = require('./options')
const log = require('./utils/util.log')
const { fireError, fireStatus } = require('./utils/util.process')
const speedTest = require('./lib/speed/index.js')

let servers = []

function registerProcessListener () {
process.on('message', function (msg) {
process.on('message', (msg) => {
log.info('child get msg:', JSON.stringify(msg))
if (msg.type === 'action') {
api[msg.event.key](msg.event.params)
Expand All @@ -22,7 +23,7 @@ function registerProcessListener () {
})

// 避免异常崩溃
process.on('uncaughtException', function (err) {
process.on('uncaughtException', (err) => {
if (err.code === 'ECONNABORTED') {
// log.error(err.errno)
return
Expand All @@ -37,7 +38,7 @@ function registerProcessListener () {
process.on('uncaughtExceptionMonitor', (err, origin) => {
log.info('Process uncaughtExceptionMonitor:', err, origin)
})
process.on('exit', function (code, signal) {
process.on('exit', (code, signal) => {
log.info('代理服务进程被关闭:', code, signal)
})
process.on('beforeExit', (code, signal) => {
Expand Down Expand Up @@ -115,12 +116,12 @@ const api = {
resolve()
}
})
}
},
}

module.exports = {
...api,
config: proxyConfig,
log,
speedTest
speedTest,
}
2 changes: 1 addition & 1 deletion packages/mitmproxy/src/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ module.exports = {
return obj
}
}
}
},
}
6 changes: 4 additions & 2 deletions packages/mitmproxy/src/lib/choice/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const LRU = require('lru-cache')
const cacheSize = 1024
const log = require('../../utils/util.log')

const cacheSize = 1024

class ChoiceCache {
constructor () {
this.cache = new LRU(cacheSize)
Expand Down Expand Up @@ -126,5 +128,5 @@ class DynamicChoice {

module.exports = {
DynamicChoice,
ChoiceCache
ChoiceCache,
}
6 changes: 1 addition & 5 deletions packages/mitmproxy/src/lib/dns/base.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
const LRU = require('lru-cache')
// const { isIP } = require('validator')
const log = require('../../utils/util.log')
const { DynamicChoice } = require('../choice/index')

const cacheSize = 1024
// eslint-disable-next-line no-unused-vars
// function _isIP (v) {
// return v && isIP(v)
// }

class IpCache extends DynamicChoice {
constructor (hostname) {
Expand Down
9 changes: 6 additions & 3 deletions packages/mitmproxy/src/lib/dns/https.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
const { promisify } = require('util')
const doh = require('dns-over-http')
const BaseDNS = require('./base')
const log = require('../../utils/util.log')
const dohQueryAsync = promisify(doh.query)
const matchUtil = require('../../utils/util.match')
const BaseDNS = require('./base')

const dohQueryAsync = promisify(doh.query)

function mapToList (ipMap) {
const ipList = []
for (const key in ipMap) {
if (!ipMap[key]) continue
if (!ipMap[key]) {
continue
}
ipList.push(ipMap[key])
}
return ipList
Expand Down
6 changes: 3 additions & 3 deletions packages/mitmproxy/src/lib/dns/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const DNSOverTLS = require('./tls.js')
const matchUtil = require('../../utils/util.match')
const DNSOverHTTPS = require('./https.js')
const DNSOverIpAddress = require('./ipaddress.js')
const DNSOverPreSetIpList = require('./preset.js')
const matchUtil = require('../../utils/util.match')
const DNSOverTLS = require('./tls.js')

module.exports = {
initDNS (dnsProviders, preSetIpList) {
Expand Down Expand Up @@ -50,5 +50,5 @@ module.exports = {
if (providerName) {
return dnsConfig.dnsMap[providerName]
}
}
},
}
3 changes: 2 additions & 1 deletion packages/mitmproxy/src/lib/dns/ipaddress.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const BaseDNS = require('./base')
const axios = require('axios')
const log = require('../../utils/util.log')
const BaseDNS = require('./base')

module.exports = class DNSOverIpAddress extends BaseDNS {
async _lookup (hostname) {
const url = `https://${hostname}.ipaddress.com`
Expand Down
3 changes: 1 addition & 2 deletions packages/mitmproxy/src/lib/dns/lookup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
module.exports = {
lookup () {

}
},
}
6 changes: 4 additions & 2 deletions packages/mitmproxy/src/lib/dns/preset.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const BaseDNS = require('./base')
const matchUtil = require('../../utils/util.match')
const BaseDNS = require('./base')

function mapToList (ipMap) {
const ipList = []
for (const key in ipMap) {
if (!ipMap[key]) continue
if (!ipMap[key]) {
continue
}
ipList.push(ipMap[key])
}
return ipList
Expand Down
3 changes: 2 additions & 1 deletion packages/mitmproxy/src/lib/dns/tls.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const dnstls = require('dns-over-tls')
const BaseDNS = require('./base')
const log = require('../../utils/util.log')
const BaseDNS = require('./base')

module.exports = class DNSOverTLS extends BaseDNS {
async _lookup (hostname) {
const { answers } = await dnstls.query(hostname)
Expand Down
4 changes: 2 additions & 2 deletions packages/mitmproxy/src/lib/interceptor/impl/req/OPTIONS.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module.exports = {
'Access-Control-Allow-Headers': allowHeaders,
'Access-Control-Allow-Methods': allowMethods,
'Access-Control-Max-Age': interceptOpt.optionsMaxAge > 0 ? interceptOpt.optionsMaxAge : 2592000, // 默认有效一个月
Date: new Date().toUTCString()
'Date': new Date().toUTCString(),
}

// 判断是否允许
Expand All @@ -50,5 +50,5 @@ module.exports = {
},
is (interceptOpt) {
return !!interceptOpt.options
}
},
}
10 changes: 5 additions & 5 deletions packages/mitmproxy/src/lib/interceptor/impl/req/abort.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ module.exports = {

res.writeHead(403, {
'Content-Type': 'text/plain; charset=utf-8',
'DS-Interceptor': 'abort'
'DS-Interceptor': 'abort',
})
res.write(
'DevSidecar 403: Request abort.\r\n\r\n' +
' This request is matched by abort intercept.\r\n' +
' 因配置abort拦截器,本请求直接返回403禁止访问。'
'DevSidecar 403: Request abort.\n\n'
+ ' This request is matched by abort intercept.\n'
+ ' 因配置abort拦截器,本请求直接返回403禁止访问。',
)
res.end()

Expand All @@ -21,5 +21,5 @@ module.exports = {
},
is (interceptOpt) {
return !!interceptOpt.abort
}
},
}
28 changes: 16 additions & 12 deletions packages/mitmproxy/src/lib/interceptor/impl/req/baiduOcr.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ function getTomorrow () {
// }

const AipOcrClient = require('baidu-aip-sdk').ocr

const AipOcrClientMap = {}
const apis = [
'accurateBasic', // 调用通用文字识别(高精度版)
'accurate', // 调用通用文字识别(含位置高精度版)
'handwriting' // 手写文字识别
'handwriting', // 手写文字识别
]

const limitMap = {}

function createBaiduOcrClient (config) {
Expand Down Expand Up @@ -57,7 +57,9 @@ function getConfig (interceptOpt, tryCount, log) {
}

// 避免count值过大,造成问题
if (count >= 100000) count = 0
if (count >= 100000) {
count = 0
}
} else {
config = interceptOpt.baiduOcr
tryCount = null // 将tryCount设置为null代表只有一个配置
Expand Down Expand Up @@ -95,13 +97,13 @@ function getConfig (interceptOpt, tryCount, log) {
}

function limitConfig (id, api) {
const key = id + '_' + api
const key = `${id}_${api}`
limitMap[key] = getTomorrow()
// limitMap[key] = Date.now() + 5000 // 测试用,5秒后解禁
}

function checkIsLimitConfig (id, api) {
const key = id + '_' + api
const key = `${id}_${api}`
const limitTime = limitMap[key]
return limitTime && limitTime > Date.now()
}
Expand All @@ -114,7 +116,7 @@ module.exports = {

const headers = {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*'
'Access-Control-Allow-Origin': '*',
}

// 获取配置
Expand Down Expand Up @@ -151,10 +153,10 @@ module.exports = {
detect_direction: 'false',
paragraph: 'false',
probability: 'false',
...(config.options || {})
...(config.options || {}),
}
log.info('发起百度ocr请求', req.hostname)
client[config.api || apis[0]](imageBase64, options).then(function (result) {
client[config.api || apis[0]](imageBase64, options).then((result) => {
if (result.error_code != null) {
log.error('baiduOcr error:', result)
if (result.error_code === 17) {
Expand All @@ -170,12 +172,14 @@ module.exports = {
res.write(JSON.stringify(result)) // 格式如:{"words_result":[{"words":"6525"}],"words_result_num":1,"log_id":1818877093747960000}
res.end()
if (next) next() // 异步执行完继续next
}).catch(function (err) {
}).catch((err) => {
log.info('baiduOcr error:', err)
res.writeHead(200, headers)
res.write('{"error_code": 999500, "error_msg": "' + err + '"}') // 格式如:{"words_result":[{"words":"6525"}],"words_result_num":1,"log_id":1818877093747960000}
res.write(`{"error_code": 999500, "error_msg": "${err}"}`) // 格式如:{"words_result":[{"words":"6525"}],"words_result_num":1,"log_id":1818877093747960000}
res.end()
if (next) next() // 异步执行完继续next
if (next) {
next() // 异步执行完继续next
}
})

log.info('proxy baiduOcr: hostname:', req.hostname)
Expand All @@ -184,5 +188,5 @@ module.exports = {
},
is (interceptOpt) {
return !!interceptOpt.baiduOcr
}
},
}
10 changes: 5 additions & 5 deletions packages/mitmproxy/src/lib/interceptor/impl/req/cacheReq.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function getLastModifiedTimeFromIfModifiedSince (rOptions, log) {
return new Date(lastModified).getTime()
} catch (e) {
// 为数字时,直接返回
if (/\\d+/g.test(lastModified)) {
if (/\\d+/.test(lastModified)) {
return lastModified - 0
}

Expand All @@ -66,12 +66,12 @@ module.exports = {

// 获取 Cache-Control 用于判断是否禁用缓存
const cacheControl = rOptions.headers['cache-control']
if (cacheControl && (cacheControl.indexOf('no-cache') >= 0 || cacheControl.indexOf('no-store') >= 0)) {
if (cacheControl && (cacheControl.includes('no-cache') || cacheControl.includes('no-store'))) {
return // 当前请求指定要禁用缓存,跳过当前拦截器
}
// 获取 Pragma 用于判断是否禁用缓存
const pragma = rOptions.headers.pragma
if (pragma && (pragma.indexOf('no-cache') >= 0 || pragma.indexOf('no-store') >= 0)) {
if (pragma && (pragma.includes('no-cache') || pragma.includes('no-store'))) {
return // 当前请求指定要禁用缓存,跳过当前拦截器
}

Expand All @@ -91,7 +91,7 @@ module.exports = {

// 缓存未过期,直接拦截请求并响应304
res.writeHead(304, {
'DS-Interceptor': 'cache: ' + maxAge
'DS-Interceptor': `cache: ${maxAge}`,
})
res.end()

Expand All @@ -103,5 +103,5 @@ module.exports = {
const maxAge = getMaxAge(interceptOpt)
return maxAge != null && maxAge > 0
},
getMaxAge
getMaxAge,
}
19 changes: 9 additions & 10 deletions packages/mitmproxy/src/lib/interceptor/impl/req/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,20 @@ const lodash = require('lodash')

// 替换占位符
function replacePlaceholder (url, rOptions, matched) {
if (url.indexOf('${') >= 0) {
// eslint-disable-next-line
if (url.includes('${')) {
// no-template-curly-in-string
// eslint-disable-next-line no-template-curly-in-string
url = url.replace('${host}', rOptions.hostname)

if (matched && url.indexOf('${') >= 0) {
if (matched && url.includes('${')) {
for (let i = 0; i < matched.length; i++) {
url = url.replace('${m[' + i + ']}', matched[i] == null ? '' : matched[i])
url = url.replace(`\${m[${i}]}`, matched[i] == null ? '' : matched[i])
}
}

// 移除多余的占位符
if (url.indexOf('${') >= 0) {
url = url.replace(/\$\{[^}]+}/g, '')
if (url.includes('${')) {
url = url.replace(/\$\{[^}]+\}/g, '')
}
}

Expand Down Expand Up @@ -45,7 +44,7 @@ function buildTargetUrl (rOptions, urlConf, interceptOpt, matched) {
targetUrl = replacePlaceholder(targetUrl, rOptions, matched)

// 拼接协议
targetUrl = targetUrl.indexOf('http:') === 0 || targetUrl.indexOf('https:') === 0 ? targetUrl : rOptions.protocol + '//' + targetUrl
targetUrl = targetUrl.indexOf('http:') === 0 || targetUrl.indexOf('https:') === 0 ? targetUrl : `${rOptions.protocol}//${targetUrl}`

return targetUrl
}
Expand Down Expand Up @@ -90,7 +89,7 @@ module.exports = {
for (const bk of interceptOpt.backup) {
backupList.push(bk)
}
const key = rOptions.hostname + '/' + interceptOpt.key
const key = `${rOptions.hostname}/${interceptOpt.key}`
const count = RequestCounter.getOrCreate(key, backupList)
if (count.value == null) {
count.doRank()
Expand All @@ -103,7 +102,7 @@ module.exports = {
context.requestCount = {
key,
value: count.value,
count
count,
}
}
}
Expand Down Expand Up @@ -135,5 +134,5 @@ module.exports = {
},
is (interceptOpt) {
return !!interceptOpt.proxy
}
},
}
Loading

0 comments on commit 3e586bf

Please sign in to comment.