使用OpenResty删除上游JS中的location对象
要通过OpenResty处理上游响应并删除JavaScript中的location对象,你可以使用以下方法。这种方法需要结合Lua脚本和可能的正则表达式处理。
基本方案
1. 安装必要的Lua库
首先确保你的OpenResty安装了lua-resty-string
和lua-resty-http
等常用库:
opm get ledgetech/lua-resty-http
2. OpenResty配置示例
http {
lua_package_path "/path/to/your/lua/scripts/?.lua;;";
init_by_lua_block {
-- 加载必要的模块
require "resty.http"
}
server {
listen 80;
location / {
proxy_pass http://upstream_server;
header_filter_by_lua_block {
-- 确保只处理JavaScript文件
if ngx.header.content_type and string.find(ngx.header.content_type, "javascript") then
ngx.header.content_length = nil
end
}
body_filter_by_lua_file /path/to/your/filter_script.lua;
}
}
}
3. Lua过滤脚本 (filter_script.lua
)
local chunk, eof = ngx.arg[1], ngx.arg[2]
local buffered = ngx.ctx.buffered or {}
if not eof then
if chunk then
buffered[#buffered + 1] = chunk
ngx.arg[1] = nil
end
return
end
if #buffered > 0 then
local combined = table.concat(buffered)
-- 匹配并移除location对象引用(基础版本)
-- 注意:这只是一个简单示例,实际JS可能更复杂
-- 匹配类似 location.href, location.replace等调用方式
combined = combined:gsub("location%.%a+%s*%(", "")
-- 匹配直接赋值或访问 location属性 (如 location.href = "...")
combined = combined:gsub("location%.%a+%s*=[^;]-;", "")
-- 匹配window.location的各种形式 (包括混淆后的代码)
combined = combined:gsub("[%w_$]+%.location%.%a+", "")
-- TODO: 添加更多模式来覆盖各种情况
ngx.arg[1] = combined .. (chunk or "")
else
ngx.arg[1] = chunk or ""
end
ngx.ctx.buffered = nil -- 清除缓冲区
Babel插件替代方案
如果你确实需要使用Babel风格的AST转换来处理JS,可以考虑以下方法:
Node.js预处理:
- 在Nginx前设置一个Node.js服务,使用Babel解析和修改JS代码
Lua的JS解析器:
ljs
(Lua JavaScript) - https://github.com/mkottman/ljs/jsdec
- https://github.com/utapyngo/jsdec
WebAssembly方案:
- 将Babel编译为WASM然后在OpenResty中运行
JS混淆处理的注意事项
对于混淆过的代码,你需要考虑:
- 变量名变化:
location
可能被重命名为其他名称如_0x123abc
- 间接引用:
window['lo'+'cation']
- 字符串拼接:
['loc', 'ation'].join('')
更健壮的解决方案可能需要完整的AST解析器或专门的混淆逆向工具。
性能考虑
对于生产环境,建议:
- 缓存处理后的结果
- 仅对必要文件进行处理
- 考虑在CDN边缘节点实现此功能而非应用服务器
内容由零声教学AI助手提供,问题来源于学员提问