feature: 支持加载多个拦截器。
parent
3ade87d07b
commit
faf029827b
|
@ -13,6 +13,8 @@ function readConfig (config, defaultConfig) {
|
|||
}
|
||||
|
||||
module.exports = {
|
||||
name: 'options',
|
||||
priority: 1,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
|
||||
|
@ -27,7 +29,7 @@ module.exports = {
|
|||
|
||||
const headers = {
|
||||
// 允许跨域
|
||||
'Dev-Sidecar-Interceptor': 'options',
|
||||
'DS-Interceptor': 'options',
|
||||
'Access-Control-Allow-Origin': rOptions.headers.origin,
|
||||
'Access-Control-Allow-Headers': allowHeaders,
|
||||
'Access-Control-Allow-Methods': allowMethods,
|
||||
|
|
|
@ -1,11 +1,23 @@
|
|||
module.exports = {
|
||||
requestIntercept (context, interceptOpts, req, res, ssl, next) {
|
||||
name: 'abort',
|
||||
priority: 103,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
log.info('abort:', rOptions.hostname, req.url)
|
||||
res.writeHead(403)
|
||||
res.write('DevSidecar 403: \n\n request abort, this request is matched by abort intercept.\n\n 因配置abort拦截器,本请求将取消')
|
||||
|
||||
res.writeHead(403, {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'DS-Interceptor': 'abort'
|
||||
})
|
||||
res.write(
|
||||
'DevSidecar 403: Request abort.\r\n\r\n' +
|
||||
' This request is matched by abort intercept.\r\n' +
|
||||
' 因配置abort拦截器,本请求直接返回403禁止访问。'
|
||||
)
|
||||
res.end()
|
||||
return true// 是否结束
|
||||
|
||||
const url = `${rOptions.method} ➜ ${rOptions.protocol}//${rOptions.hostname}:${rOptions.port}${req.url}`
|
||||
log.info('abort intercept:', url)
|
||||
return true // true代表请求结束
|
||||
},
|
||||
is (interceptOpt) {
|
||||
return !!interceptOpt.abort
|
||||
|
|
|
@ -55,6 +55,8 @@ function getLastModifiedTimeFromIfModifiedSince (rOptions, log) {
|
|||
}
|
||||
|
||||
module.exports = {
|
||||
name: 'cacheReq',
|
||||
priority: 111,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
|
||||
|
@ -65,12 +67,12 @@ module.exports = {
|
|||
// 获取 Cache-Control 用于判断是否禁用缓存
|
||||
const cacheControl = rOptions.headers['cache-control']
|
||||
if (cacheControl && (cacheControl.indexOf('no-cache') >= 0 || cacheControl.indexOf('no-store') >= 0)) {
|
||||
return // 禁用缓存,跳过当前拦截器
|
||||
return // 当前请求指定要禁用缓存,跳过当前拦截器
|
||||
}
|
||||
// 获取 Pragma 用于判断是否禁用缓存
|
||||
const pragma = rOptions.headers.pragma
|
||||
if (pragma && (pragma.indexOf('no-cache') >= 0 || pragma.indexOf('no-store') >= 0)) {
|
||||
return // 禁用缓存,跳过当前拦截
|
||||
return // 当前请求指定要禁用缓存,跳过当前拦截器
|
||||
}
|
||||
|
||||
// 最近编辑时间
|
||||
|
@ -89,10 +91,12 @@ module.exports = {
|
|||
|
||||
// 缓存未过期,直接拦截请求并响应304
|
||||
res.writeHead(304, {
|
||||
'Dev-Sidecar-Interceptor': 'cacheReq'
|
||||
'DS-Interceptor': 'cache: ' + maxAge
|
||||
})
|
||||
res.end()
|
||||
|
||||
const url = `${rOptions.method} ➜ ${rOptions.protocol}//${rOptions.hostname}:${rOptions.port}${req.url}`
|
||||
log.info('cache intercept:', url)
|
||||
return true
|
||||
},
|
||||
is (interceptOpt) {
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
const url = require('url')
|
||||
const lodash = require('lodash')
|
||||
module.exports = {
|
||||
name: 'proxy',
|
||||
priority: 121,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log, RequestCounter } = context
|
||||
|
||||
|
@ -8,17 +11,17 @@ module.exports = {
|
|||
let proxyConf = interceptOpt.proxy
|
||||
if (RequestCounter && interceptOpt.backup && interceptOpt.backup.length > 0) {
|
||||
// 优选逻辑
|
||||
const backup = [proxyConf]
|
||||
const backupList = [proxyConf]
|
||||
for (const bk of interceptOpt.backup) {
|
||||
backup.push(bk)
|
||||
backupList.push(bk)
|
||||
}
|
||||
const key = rOptions.hostname + '/' + interceptOpt.key
|
||||
const count = RequestCounter.getOrCreate(key, backup)
|
||||
const count = RequestCounter.getOrCreate(key, backupList)
|
||||
if (count.value == null) {
|
||||
count.doRank()
|
||||
}
|
||||
if (count.value == null) {
|
||||
log.error('count value is null', count)
|
||||
log.error('`count.value` is null, the count:', count)
|
||||
} else {
|
||||
count.doCount(count.value)
|
||||
proxyConf = count.value
|
||||
|
@ -30,27 +33,32 @@ module.exports = {
|
|||
}
|
||||
}
|
||||
|
||||
let uri = req.url
|
||||
if (uri.indexOf('http') === 0) {
|
||||
// eslint-disable-next-line node/no-deprecated-api
|
||||
const URL = url.parse(uri)
|
||||
uri = URL.path
|
||||
}
|
||||
let proxyTarget = proxyConf + uri
|
||||
// 获取代理目标地址
|
||||
let proxyTarget
|
||||
if (interceptOpt.replace) {
|
||||
const regexp = new RegExp(interceptOpt.replace)
|
||||
proxyTarget = req.url.replace(regexp, proxyConf)
|
||||
} else if (proxyConf.indexOf('http:') === 0 || proxyConf.indexOf('https:') === 0) {
|
||||
proxyTarget = proxyConf
|
||||
} else {
|
||||
let uri = req.url
|
||||
if (uri.indexOf('http') === 0) {
|
||||
// eslint-disable-next-line node/no-deprecated-api
|
||||
const URL = url.parse(uri)
|
||||
uri = URL.path
|
||||
}
|
||||
proxyTarget = proxyConf + uri
|
||||
}
|
||||
// eslint-disable-next-line
|
||||
// no-template-curly-in-string
|
||||
|
||||
// eslint-disable-next-line no-template-curly-in-string
|
||||
proxyTarget = proxyTarget.replace('${host}', rOptions.hostname)
|
||||
|
||||
log.info('拦截【proxy】: original:', rOptions.hostname, ',target:', proxyTarget)
|
||||
// const backup = interceptOpt.backup
|
||||
const proxy = proxyTarget.indexOf('http') === 0 ? proxyTarget : rOptions.protocol + '//' + proxyTarget
|
||||
// eslint-disable-next-line node/no-deprecated-api
|
||||
const URL = url.parse(proxy)
|
||||
rOptions.origional = lodash.cloneDeep(rOptions) // 备份原始请求参数
|
||||
delete rOptions.origional.agent
|
||||
delete rOptions.origional.headers
|
||||
rOptions.protocol = URL.protocol
|
||||
rOptions.hostname = URL.host
|
||||
rOptions.host = URL.host
|
||||
|
@ -69,8 +77,10 @@ module.exports = {
|
|||
if (rOptions.agent && rOptions.agent.options) {
|
||||
rOptions.agent.options.rejectUnauthorized = false
|
||||
}
|
||||
res.setHeader('DS-Interceptor', `proxy: ${proxyTarget}, sni: ${interceptOpt.sni}`)
|
||||
log.info('proxy intercept: hostname:', originHostname, ', target:', proxyTarget, ', sni replace servername:', rOptions.servername)
|
||||
} else {
|
||||
res.setHeader('DS-Interceptor', `proxy: ${proxyTarget}`)
|
||||
log.info('proxy intercept: hostname:', originHostname, ', target:', proxyTarget)
|
||||
}
|
||||
|
||||
|
|
|
@ -1,17 +1,32 @@
|
|||
module.exports = {
|
||||
name: 'redirect',
|
||||
priority: 102,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
const url = req.url
|
||||
|
||||
let redirect
|
||||
if (typeof interceptOpt.redirect === 'string') {
|
||||
redirect = rOptions.protocol + '//' + interceptOpt.redirect + url
|
||||
if (interceptOpt.redirect.indexOf('http:') === 0 || interceptOpt.redirect.indexOf('https:') === 0) {
|
||||
redirect = interceptOpt.redirect
|
||||
} else {
|
||||
redirect = rOptions.protocol + '//' + interceptOpt.redirect + req.url
|
||||
}
|
||||
} else {
|
||||
redirect = interceptOpt.redirect(url)
|
||||
redirect = interceptOpt.redirect(req.url)
|
||||
}
|
||||
log.info('请求重定向:', rOptions.hostname, url, redirect)
|
||||
res.writeHead(302, { Location: redirect })
|
||||
|
||||
// eslint-disable-next-line no-template-curly-in-string
|
||||
redirect = redirect.replace('${host}', rOptions.hostname)
|
||||
|
||||
res.writeHead(302, {
|
||||
Location: redirect,
|
||||
'DS-Interceptor': 'redirect'
|
||||
})
|
||||
res.end()
|
||||
return true// 是否结束
|
||||
|
||||
const url = `${rOptions.method} ➜ ${rOptions.protocol}//${rOptions.hostname}:${rOptions.port}${req.url}`
|
||||
log.info(`redirect intercept: ${url} ➜ ${redirect}`)
|
||||
return true // true代表请求结束
|
||||
},
|
||||
is (interceptOpt) {
|
||||
return interceptOpt.redirect // 如果配置中有redirect,那么这个配置是需要redirect拦截的
|
||||
|
|
|
@ -1,13 +1,17 @@
|
|||
module.exports = {
|
||||
requestIntercept (context, interceptOpt) {
|
||||
name: 'sni',
|
||||
priority: 122,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
if (interceptOpt.sni != null) {
|
||||
rOptions.servername = interceptOpt.sni
|
||||
if (rOptions.agent && rOptions.agent.options) {
|
||||
rOptions.agent.options.rejectUnauthorized = false
|
||||
}
|
||||
log.info('sni intercept: sni replace servername:', rOptions.hostname, '➜', rOptions.servername)
|
||||
|
||||
rOptions.servername = interceptOpt.sni
|
||||
if (rOptions.agent && rOptions.agent.options) {
|
||||
rOptions.agent.options.rejectUnauthorized = false
|
||||
}
|
||||
|
||||
res.setHeader('DS-Interceptor', 'sni: ' + interceptOpt.sni)
|
||||
|
||||
log.info('sni intercept: sni replace servername:', rOptions.hostname, '➜', rOptions.servername)
|
||||
return true
|
||||
},
|
||||
is (interceptOpt) {
|
||||
|
|
|
@ -1,11 +1,23 @@
|
|||
module.exports = {
|
||||
requestIntercept (context, interceptOpts, req, res, ssl, next) {
|
||||
name: 'success',
|
||||
priority: 101,
|
||||
requestIntercept (context, interceptOpt, req, res, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
log.info('success:', rOptions.hostname, req.url)
|
||||
res.writeHead(200)
|
||||
res.write('DevSidecar 200: \n\n request success, this request is matched by success intercept.\n\n 因配置success拦截器,本请求将直接返回成功')
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
'DS-Interceptor': 'success'
|
||||
})
|
||||
res.write(
|
||||
'DevSidecar 200: Request success.\n\n' +
|
||||
' This request is matched by success intercept.\n\n' +
|
||||
' 因配置success拦截器,本请求直接返回200成功。'
|
||||
)
|
||||
res.end()
|
||||
return true// 是否结束
|
||||
|
||||
const url = `${rOptions.method} ➜ ${rOptions.protocol}//${rOptions.hostname}:${rOptions.port}${req.url}`
|
||||
log.info('success intercept:', url)
|
||||
return true // true代表请求结束
|
||||
},
|
||||
is (interceptOpt) {
|
||||
return !!interceptOpt.success
|
||||
|
|
|
@ -1,11 +1,14 @@
|
|||
const cacheReq = require('../req/cacheReq')
|
||||
|
||||
module.exports = {
|
||||
name: 'cacheRes',
|
||||
priority: 201,
|
||||
responseIntercept (context, interceptOpt, req, res, proxyReq, proxyRes, ssl, next) {
|
||||
const { rOptions, log } = context
|
||||
|
||||
// 只有GET请求,且响应码为2xx时才进行缓存
|
||||
if (rOptions.method !== 'GET' || proxyRes.statusCode < 200 || proxyRes.statusCode >= 300) {
|
||||
// res.setHeader('DS-Cache-Interceptor', `skip: 'method' or 'status' not match`)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -48,6 +51,9 @@ module.exports = {
|
|||
if (interceptOpt.cacheImmutable !== false && originalHeaders.cacheControl.value.indexOf('immutable') < 0) {
|
||||
maxAge = maxAgeMatch[1]
|
||||
} else {
|
||||
const url = `${rOptions.method} ➜ ${rOptions.protocol}//${rOptions.hostname}:${rOptions.port}${req.url}`
|
||||
res.setHeader('DS-Cache-Interceptor', `skip: ${maxAgeMatch[1]} > ${maxAge}`)
|
||||
log.info(`cache response intercept: skip: ${maxAgeMatch[1]} > ${maxAge}, url: ${url}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
@ -80,7 +86,7 @@ module.exports = {
|
|||
res.setHeader('Expires', replaceHeaders.expires)
|
||||
}
|
||||
|
||||
res.setHeader('Dev-Sidecar-Cache-Response-Interceptor', 'cacheRes:maxAge=' + maxAge)
|
||||
res.setHeader('DS-Cache-Response-Interceptor', maxAge)
|
||||
},
|
||||
is (interceptOpt) {
|
||||
const maxAge = cacheReq.getMaxAge(interceptOpt)
|
||||
|
|
|
@ -13,6 +13,8 @@ function getScript (key, script) {
|
|||
}
|
||||
|
||||
module.exports = {
|
||||
name: 'script',
|
||||
priority: 202,
|
||||
responseIntercept (context, interceptOpt, req, res, proxyReq, proxyRes, ssl, next) {
|
||||
const { rOptions, log, setting } = context
|
||||
let keys = interceptOpt.script
|
||||
|
@ -20,20 +22,23 @@ module.exports = {
|
|||
keys = [keys]
|
||||
}
|
||||
try {
|
||||
let tags = getScript('global', monkey.get(setting.script.dirAbsolutePath).global.script)
|
||||
const scripts = monkey.get(setting.script.dirAbsolutePath)
|
||||
let tags = getScript('global', scripts.global.script)
|
||||
for (const key of keys) {
|
||||
const script = monkey.get(setting.script.dirAbsolutePath)[key]
|
||||
const script = scripts[key]
|
||||
if (script == null) {
|
||||
continue
|
||||
}
|
||||
const scriptTag = getScript(key, script.script)
|
||||
tags += '\r\n' + scriptTag
|
||||
}
|
||||
log.info('responseIntercept: insert script', rOptions.hostname, rOptions.path)
|
||||
res.setHeader('DS-Script-Interceptor', 'true')
|
||||
log.info('script response intercept: insert script', rOptions.hostname, rOptions.path, ', head:', tags)
|
||||
return {
|
||||
head: tags
|
||||
}
|
||||
} catch (err) {
|
||||
res.setHeader('DS-Script-Interceptor', 'error')
|
||||
log.error('load monkey script error', err)
|
||||
}
|
||||
},
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
const interceptors = require('./lib/interceptor')
|
||||
const interceptorImpls = require('./lib/interceptor')
|
||||
const dnsUtil = require('./lib/dns')
|
||||
const log = require('./utils/util.log')
|
||||
const matchUtil = require('./utils/util.match')
|
||||
|
@ -49,7 +49,7 @@ module.exports = (config) => {
|
|||
const hostname = req.url.split(':')[0]
|
||||
const inWhiteList = matchUtil.matchHostname(whiteList, hostname, 'in whiteList') != null
|
||||
if (inWhiteList) {
|
||||
log.info('白名单域名,不拦截', hostname)
|
||||
log.info('为白名单域名,不拦截:', hostname)
|
||||
return false // 所有都不拦截
|
||||
}
|
||||
// 配置了拦截的域名,将会被代理
|
||||
|
@ -57,29 +57,42 @@ module.exports = (config) => {
|
|||
if (matched === true) {
|
||||
return matched // 拦截
|
||||
}
|
||||
return null // 由下一个拦截器判断
|
||||
return null // 未匹配到任何拦截配置,由下一个拦截器判断
|
||||
},
|
||||
createIntercepts: (context) => {
|
||||
const rOptions = context.rOptions
|
||||
const hostname = rOptions.hostname
|
||||
const interceptOpts = matchUtil.matchHostname(intercepts, hostname, 'get interceptOpts')
|
||||
const interceptOpts = matchUtil.matchHostnameAll(intercepts, rOptions.hostname, 'get interceptOpts')
|
||||
if (!interceptOpts) { // 该域名没有配置拦截器,直接过
|
||||
return
|
||||
}
|
||||
|
||||
const matchIntercepts = []
|
||||
const matchInterceptsOpts = {}
|
||||
for (const regexp in interceptOpts) { // 遍历拦截配置
|
||||
const interceptOpt = interceptOpts[regexp]
|
||||
interceptOpt.key = regexp
|
||||
if (regexp !== true) {
|
||||
if (regexp !== true && regexp !== 'true') {
|
||||
if (!matchUtil.isMatched(rOptions.path, regexp)) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
for (const impl of interceptors) {
|
||||
log.info(`interceptor matched, regexp: '${regexp}' =>`, JSON.stringify(interceptOpt), ', path:', rOptions.path)
|
||||
for (const impl of interceptorImpls) {
|
||||
// 根据拦截配置挑选合适的拦截器来处理
|
||||
if (impl.is && impl.is(interceptOpt)) {
|
||||
const interceptor = {}
|
||||
let action = 'add'
|
||||
|
||||
// 如果存在同名拦截器,则order值越大,优先级越高
|
||||
const matchedInterceptOpt = matchInterceptsOpts[impl.name]
|
||||
if (matchedInterceptOpt) {
|
||||
if (matchedInterceptOpt.order >= interceptOpt.order) {
|
||||
log.warn(`duplicate interceptor: ${impl.name}, hostname: ${rOptions.hostname}`)
|
||||
continue
|
||||
}
|
||||
action = 'replace'
|
||||
}
|
||||
|
||||
const interceptor = { name: impl.name, priority: impl.priority }
|
||||
if (impl.requestIntercept) {
|
||||
// req拦截器
|
||||
interceptor.requestIntercept = (context, req, res, ssl, next) => {
|
||||
|
@ -91,10 +104,26 @@ module.exports = (config) => {
|
|||
return impl.responseIntercept(context, interceptOpt, req, res, proxyReq, proxyRes, ssl, next)
|
||||
}
|
||||
}
|
||||
matchIntercepts.push(interceptor)
|
||||
|
||||
// log.info(`${action} interceptor: ${impl.name}, hostname: ${rOptions.hostname}, regexp: ${regexp}`)
|
||||
if (action === 'add') {
|
||||
matchIntercepts.push(interceptor)
|
||||
} else {
|
||||
matchIntercepts[matchedInterceptOpt.index] = interceptor
|
||||
}
|
||||
matchInterceptsOpts[impl.name] = {
|
||||
order: interceptOpt.order || 0,
|
||||
index: matchIntercepts.length - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
matchIntercepts.sort((a, b) => { return a.priority - b.priority })
|
||||
// for (const interceptor of matchIntercepts) {
|
||||
// log.info('interceptor:', interceptor.name, 'priority:', interceptor.priority)
|
||||
// }
|
||||
|
||||
return matchIntercepts
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue