mirror of
https://gitcode.com/JianFeeeee/ModelRouter.git
synced 2026-11-07 09:47:23 +00:00
fix: 回退两处内核改动,channels 改为插件自持持久化(照参考实现)
## 回退的内核改动
用户指出「你又tm改内核?」—— 核对后确认两处本可避免:
1. internal/lua/vm.go +32 行 新增 base64_decode 全局函数
2. internal/lua/plugin_http_handler.go +16 行 InvokeHandler 补 markDirty
工作区已还原到 v2.0.2(git diff v2.0.2 = 0 行)。
## 为什么两处都是错的
参考实现(dsh-our-free-model/vendor/channel-pack)对同一问题的做法:
- 解 JWT:用**语言自带**的 `Buffer.from(..., 'base64url')`,从不为此改宿主。
→ 我改成了插件的纯 Lua b64url_decode(约 20 行),实测解出真 JWT 的
nickname/sub/exp 全对。
- 状态持久化:插件**自己 writeFileSync+renameSync** 写
`channel-pack/state.json`,从不依赖宿主 settings。
→ 参考还记下了同构教训(Gitee IKI7WT):DSH 0.1.7 移除 settings.register()
后账号列表退化为纯内存;正解是**插件探测宿主能力、自持文档**,不是要求
宿主改。我的 markDirty 修法方向相反:把插件的数据安全外包给宿主某条
分发路径的实现细节。
## channels 改为插件自持存储
- `.channels-store.json`(tmp + rename 原子替换),只放**索引与配置**
(账号条目含 credentialRef 而非凭据本身、模型黑名单、设置、事件日志)。
凭据仍在 .secrets/(0600),两者分离:即便文档泄露也不含 token。
- 变更点同步落盘(不用「置标志+定时 flush」):本插件无 hooks、45 个端点
各自变更状态,还有大量内部互调;挂在某个边界就必须保证**每条**路径都
经过它,漏一条就是「操作成功但重启丢失」——正是本次要修的缺陷形态。
状态实测 ~1.7KB,写入只发生在运维动作上,不在请求热路径。
- 黑名单写入收口到 setModelDisabled(写点曾有 5+ 处,散着写必漏)。
- 存量迁移:读内核遗留 `.channels.state.json`(v2.0.4 内核写的)→ 写自有
文档 → **写成功才删**遗留(写失败还删=用一次迁移丢数据);自有存储已存在
时也删遗留,否则内核 restore() 会在启动时用它覆盖。
## 顺带修了两个真实缺陷
1. **测试污染生产目录**(严重):插件 storeDir() 读 /etc/llmsproxy/config.yaml
决定落盘位置,而既有测试都没隔离 → 一次全量测试把 26 个测试账号写进了
**生产** .channels-store.json(含 fixture-a/example 等夹具 id)。
prod 文件已删除(真实账号另有来源);kernelTestCore 现在隔离插件目录,
且尊重调用方已设的值(多次「重启」需共用同一目录)。
2. model_set_disabled 改了写入口后仍引用已删除的局部变量(nil 索引崩溃)。
## 判据(变异全部咬人)
- TestChannelsStoreIsPluginOwned:状态写进**插件自己的**文件、不含凭据字段、
新实例读回。变异(markDirty 空操作)→ FAIL。
- TestChannelsMigrationKeepsLegacyOnWriteFailure:**写失败必须保留遗留文件**。
变异(无条件删)→ FAIL。(这条单独测:迁移成功后的删除有两条路径互相掩盖,
只测「最终文件没了」区分不出「写失败也删了」。)
- TestChannelsMigratesLegacyKernelState:遗留账号迁入内存 + 自有存储写出 +
遗留文件删除。
- 内核对照 v2.0.2:diff 为空。
go test ./internal/core/(78s)与 ./internal/lua/(63s)全绿;
全量测试后确认生产插件目录未被写入。
This commit is contained in:
@ -804,13 +804,191 @@ end
|
||||
-- 状态
|
||||
-- ============================================================================
|
||||
|
||||
-- ============================================================================
|
||||
-- 插件自有持久化(账号池 / 模型黑名单 / 设置 / 日志)
|
||||
-- ============================================================================
|
||||
--
|
||||
-- 为什么插件自己落盘,而不是靠宿主框架的 plugin.state:
|
||||
-- 本插件声明 hooks = {},一切状态变更都走自己的 HTTP 路由。宿主的状态自动
|
||||
-- flush 由 hook / Call / handler 三条分发路径触发,插件不应把「我的状态会不会
|
||||
-- 被写下去」押在宿主某条路径的实现细节上 —— 那是把插件的数据安全外包给宿主。
|
||||
-- 参考实现踩过同一课(channel-pack-store.ts):宿主 settings 能力一变,账号
|
||||
-- 列表就退化为纯内存,必须改由插件自持文档。
|
||||
--
|
||||
-- 位置与凭据分离:凭据在 .secrets/(0600,跨插件不可读),这里只放**索引与
|
||||
-- 配置**(账号条目含 credentialRef 而非凭据本身、模型黑名单、设置、事件日志)。
|
||||
-- 即便这个文件泄露,也不含任何 token。
|
||||
--
|
||||
-- 写入:tmp + rename 原子替换。读:缺失/损坏 → 用内置默认值(不阻塞启动)。
|
||||
local STORE_NAME = ".channels-store.json"
|
||||
|
||||
-- storeDir 求插件目录:优先 config.yaml 的 plugin_dir,否则用本文件所在目录。
|
||||
-- 插件与内核同机、有完整 OS 权限,读自己的配置是能力范围内的事。
|
||||
local function storeDir()
|
||||
-- 显式覆盖优先(测试与多实例部署都靠它隔离,避免读到别处的生产配置)
|
||||
local env = os.getenv and os.getenv("LLMSPROXY_PLUGIN_DIR")
|
||||
if type(env) == "string" and env ~= "" then return env end
|
||||
local s = plugin.state.settings and plugin.state.settings.store_dir
|
||||
if type(s) == "string" and s ~= "" then return s end
|
||||
for _, path in ipairs({ "/etc/llmsproxy/config.yaml", "/usr/local/etc/llmsproxy/config.yaml" }) do
|
||||
local f = io.open(path, "r")
|
||||
if f then
|
||||
local txt = f:read("*a")
|
||||
f:close()
|
||||
if txt then
|
||||
local d = txt:match("\nplugin_dir:%s*([^\n]%S*)") or txt:match("^plugin_dir:%s*([^\n]%S*)")
|
||||
if d and d ~= "" then return d end
|
||||
end
|
||||
end
|
||||
end
|
||||
return "/etc/llmsproxy/plugins"
|
||||
end
|
||||
|
||||
-- persistKeys 是要落盘的字段。故意不含 sessions(登录会话是短命态,重启即失效,
|
||||
-- 写下去只会留下过期垃圾)与 browser(进程 pid 跨重启无意义)。
|
||||
local PERSIST_KEYS = {
|
||||
"accounts", "pool", "modelDisabled", "settings",
|
||||
"providerOrder", "log", "injected_platforms",
|
||||
}
|
||||
|
||||
local function persistState()
|
||||
local dir = storeDir()
|
||||
local path = dir .. "/" .. STORE_NAME
|
||||
local snap = {}
|
||||
for _, k in ipairs(PERSIST_KEYS) do
|
||||
if plugin.state[k] ~= nil then snap[k] = plugin.state[k] end
|
||||
end
|
||||
local body = json.encode({ version = 1, state = snap })
|
||||
if not body then return false, "json.encode 失败" end
|
||||
local tmp = path .. ".tmp"
|
||||
local w = io.open(tmp, "w")
|
||||
if not w then return false, "无法写入 " .. tmp end
|
||||
w:write(body)
|
||||
w:close()
|
||||
os.execute(("chmod 0600 %s 2>/dev/null"):format(tmp))
|
||||
local ok = os.rename(tmp, path)
|
||||
if not ok then
|
||||
os.remove(tmp)
|
||||
return false, "rename 失败"
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function applySnapshot(snap)
|
||||
for _, k in ipairs(PERSIST_KEYS) do
|
||||
if snap[k] ~= nil then plugin.state[k] = snap[k] end
|
||||
end
|
||||
end
|
||||
|
||||
-- dropLegacyKernelState 删除内核遗留文件(若存在)。
|
||||
--
|
||||
-- 必须删:内核的 restore() 在插件源码执行**之后**运行,会把这个文件的内容整体
|
||||
-- 覆盖到 plugin.state 上。自有存储已经是权威,留下它等于给"下次启动被旧数据
|
||||
-- 覆盖"留一个后门。删它不需要先读它(迁移路径自己会读)。
|
||||
local function dropLegacyKernelState()
|
||||
local legacy = storeDir() .. "/.channels.state.json"
|
||||
local f = io.open(legacy, "r")
|
||||
if not f then return end
|
||||
f:close()
|
||||
os.remove(legacy)
|
||||
io.stderr:write("[channels] 已删除内核遗留状态文件(自有存储为权威)\n")
|
||||
end
|
||||
|
||||
-- loadState 读插件自有文档;缺失时**从内核遗留文件迁移一次**。
|
||||
--
|
||||
-- 历史背景:v2.0.4 曾让内核的 InvokeHandler 补 markDirty,于是状态被内核写到了
|
||||
-- `.channels.state.json`(内核的 <plugin>.state.json 命名)。现在内核改动已回退,
|
||||
-- 那个文件不会再被内核读写;但生产上已经存在一份(含真实账号池),必须迁移过来,
|
||||
-- 否则升级即丢账号 —— 与本次要修的缺陷同类,不能自己再造一次。
|
||||
-- 迁移后删除遗留文件:留着它只会让「哪个文件权威」变成永久的疑团。
|
||||
local function loadOwnSnapshot()
|
||||
local dir = storeDir()
|
||||
local f = io.open(dir .. "/" .. STORE_NAME, "r")
|
||||
if f then
|
||||
local txt = f:read("*a")
|
||||
f:close()
|
||||
if txt and txt ~= "" then
|
||||
local ok, rec = pcall(json.decode, txt)
|
||||
if ok and type(rec) == "table" and type(rec.state) == "table" then
|
||||
applySnapshot(rec.state)
|
||||
return true
|
||||
end
|
||||
-- 损坏文件不阻塞:用内置默认值(下次写入覆盖它)
|
||||
io.stderr:write("[channels] 自有存储损坏,改用默认值\n")
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- migrateLegacyKernelState 把内核遗留的 .channels.state.json 搬进自有文档。
|
||||
local function migrateLegacyKernelState()
|
||||
local dir = storeDir()
|
||||
local legacy = dir .. "/.channels.state.json"
|
||||
local f = io.open(legacy, "r")
|
||||
if not f then return false end
|
||||
local txt = f:read("*a")
|
||||
f:close()
|
||||
if not txt or txt == "" then return false end
|
||||
local ok, rec = pcall(json.decode, txt)
|
||||
if not ok or type(rec) ~= "table" or type(rec.state) ~= "table" then
|
||||
return false
|
||||
end
|
||||
applySnapshot(rec.state)
|
||||
-- 立即写成自有文档;**只有写成功才删遗留文件** —— 写失败还删它,
|
||||
-- 等于用一次迁移把数据弄丢,与本次要修的缺陷同类。
|
||||
local written, werr = persistState()
|
||||
if written then
|
||||
os.remove(legacy)
|
||||
io.stderr:write("[channels] 已迁移遗留状态到 " .. STORE_NAME .. "\n")
|
||||
else
|
||||
io.stderr:write("[channels] 遗留状态迁移写入失败(保留原文件): "
|
||||
.. tostring(werr) .. "\n")
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function loadState()
|
||||
if loadOwnSnapshot() then
|
||||
-- 自有存储已权威:遗留文件必须删掉,否则内核 restore() 会用它覆盖
|
||||
dropLegacyKernelState()
|
||||
return true
|
||||
end
|
||||
return migrateLegacyKernelState()
|
||||
end
|
||||
|
||||
-- markDirty = 立即同步落盘(tmp + rename 原子替换)。
|
||||
--
|
||||
-- 为什么不用「置标志 + 定时 flush」:本插件没有 hooks,45 个端点各自
|
||||
-- 直接变更状态,还有大量内部调用(syncAccountSource / claim_daily /
|
||||
-- auto_checkin 互调)。把 flush 挂在某个边界上就必须保证**每一条**路径都经过
|
||||
-- 它,漏一条就是「操作成功但重启丢失」——正是本次要修的缺陷形态。同步写在
|
||||
-- 变更点,路径覆盖是结构性的,不依赖我数全 45 个入口。
|
||||
--
|
||||
-- 代价可接受:状态很小(实测 ~1.7KB),channels 没有 chat 钩子,写入只发生在
|
||||
-- 运维动作(登录/领取/开关)与登录轮询(未完成时才有)上,不在请求热路径。
|
||||
-- 参考实现同样是每次变更 writeFileSync + renameSync。
|
||||
--
|
||||
-- 失败处理:写失败**不从状态里回滚**内存变更(内存是对的),只留痕到 stderr
|
||||
-- ——不递归调 logEvent,那会再次触发 markDirty。
|
||||
local function markDirty()
|
||||
local ok, err = persistState()
|
||||
if not ok then
|
||||
io.stderr:write("[channels] 状态落盘失败: " .. tostring(err) .. "\n")
|
||||
end
|
||||
end
|
||||
|
||||
plugin.state = plugin.state or {}
|
||||
plugin.state.accounts = plugin.state.accounts or {}
|
||||
plugin.state.log = plugin.state.log or {}
|
||||
|
||||
-- 启动时从插件自有文档恢复(必须在 plugin.state 建表之后:loadState 往表里填
|
||||
-- 字段,先填再被 or {} 覆盖就白填了)。
|
||||
loadState()
|
||||
|
||||
local function logEvent(msg)
|
||||
table.insert(plugin.state.log, 1, { at = os.time and os.time() or 0, msg = msg })
|
||||
while #plugin.state.log > 50 do table.remove(plugin.state.log) end
|
||||
markDirty()
|
||||
end
|
||||
|
||||
-- accountOf 取某平台的账号记录(凭据本身在保险库,不在 state 里)
|
||||
@ -854,10 +1032,12 @@ end
|
||||
|
||||
local function poolAdd(provider, entry)
|
||||
poolAccounts(provider)[entry.id] = entry
|
||||
markDirty()
|
||||
end
|
||||
|
||||
local function poolRemove(provider, accountId)
|
||||
poolAccounts(provider)[accountId] = nil
|
||||
markDirty()
|
||||
end
|
||||
|
||||
-- 凭据取值:保险库里存的可能是**裸 token**(历史/device-poll/paste 路径),
|
||||
@ -897,12 +1077,41 @@ end
|
||||
-- CodeBuddy 的 login/account 响应**不含昵称**,昵称只在 access_token 的声明里;
|
||||
-- token 端又只返回 expiresIn(相对秒数)而不含 expiresAt。两处都得从 JWT 兜底。
|
||||
-- 解析失败返回 nil(调用方自行处理)。
|
||||
-- b64url_decode 纯 Lua 的 base64url 解码(读 JWT payload 用)。
|
||||
--
|
||||
-- 为什么不用内核的 base64 能力:内核只提供 encode(适配器签名要用),没有 decode。
|
||||
-- 为读一个 JWT 声明而给内核加一个通用解码函数,是把插件的事推给内核 ——
|
||||
-- 插件能做就该自己做。纯 Lua 实现约 20 行,无依赖、无内核改动。
|
||||
-- 接受标准/URL-safe 两种字母表,容忍缺失填充。
|
||||
local B64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
local B64_LOOKUP = {}
|
||||
for i = 1, #B64_ALPHABET do B64_LOOKUP[B64_ALPHABET:sub(i, i)] = i - 1 end
|
||||
local function b64url_decode(input)
|
||||
if type(input) ~= "string" or input == "" then return nil end
|
||||
-- 归一化:URL-safe → 标准,去空白,去掉填充(下面按 4 位一组补零处理)
|
||||
local s = input:gsub("%s", ""):gsub("-", "+"):gsub("_", "/"):gsub("=", "")
|
||||
local out, acc, bits = {}, 0, 0
|
||||
for i = 1, #s do
|
||||
local v = B64_LOOKUP[s:sub(i, i)]
|
||||
if v == nil then return nil end -- 非法字符:如实失败,不猜
|
||||
acc = acc * 64 + v
|
||||
bits = bits + 6
|
||||
if bits >= 8 then
|
||||
bits = bits - 8
|
||||
local byte = math.floor(acc / (2 ^ bits)) % 256
|
||||
out[#out + 1] = string.char(byte)
|
||||
acc = acc % (2 ^ bits)
|
||||
end
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function jwtClaim(token, name)
|
||||
if type(token) ~= "string" or token == "" then return nil end
|
||||
local payload = token:match("^[^%.]+%.([^%.]+)")
|
||||
if not payload then return nil end
|
||||
local bin, derr = base64_decode(payload) -- 内核新增:base64url 兼容
|
||||
if not bin or derr then return nil end
|
||||
local bin = b64url_decode(payload)
|
||||
if not bin then return nil end
|
||||
local ok, rec = pcall(json.decode, bin)
|
||||
if not ok or type(rec) ~= "table" then return nil end
|
||||
return rec[name]
|
||||
@ -1033,6 +1242,15 @@ local function disabledModelsOf(provider)
|
||||
return m
|
||||
end
|
||||
|
||||
-- setModelDisabled 是**唯一**的模型黑名单写入口:写完即落盘。
|
||||
-- 之所以收成一个函数:黑名单的写点曾有 5+ 处(单个开关/批量/清死模型/供应商
|
||||
-- 整体开关),散着写必然漏标脏。收口后只有这里需要保证。
|
||||
local function setModelDisabled(provider, modelId, disabled)
|
||||
local m = disabledModelsOf(provider)
|
||||
if disabled then m[modelId] = true else m[modelId] = nil end
|
||||
markDirty()
|
||||
end
|
||||
|
||||
-- 渠道积分能力表(对齐参考 CHANNEL_CREDITS):声明各渠道有没有领取/余额。
|
||||
local CHANNEL_CREDITS = {
|
||||
codearts = { claim = true },
|
||||
@ -1136,12 +1354,39 @@ end
|
||||
-- plugin.state.browser.pids,插件卸载或会话结束时 kill。
|
||||
-- 绑定地址默认 127.0.0.1(同机操作);远程运维可把 settings.vnc_bind 设成
|
||||
-- "0.0.0.0" 并依赖 x11vnc 随机会话密码(不设密码的裸 VNC 永远不会出现)。
|
||||
--
|
||||
-- 为什么需要它:有些平台的登录**必须**在服务端完成 —— 回环重定向落不到用户
|
||||
-- 机器上、或授权页要求浏览器内交互(扫码后确认、短信验证码)。这时只有服务端
|
||||
-- 浏览器能走完,VNC 是把那个浏览器呈现给运维的唯一途径。
|
||||
--
|
||||
-- 登录后的取凭据不走「截图 + 人眼看」:浏览器以 --remote-debugging-port 起,
|
||||
-- 完成后经 CDP 读 document.cookie / localStorage / 显式取回的 token,
|
||||
-- 落到保险库。人只负责在 VNC 窗口里完成交互,机器负责把结果取出来。
|
||||
|
||||
local function browserStack()
|
||||
if not plugin.state.browser then plugin.state.browser = { pids = {}, seq = 0 } end
|
||||
return plugin.state.browser
|
||||
end
|
||||
|
||||
-- browserDeps 探测浏览器栈的外部依赖。返回 { ok=bool, missing={...}, present={...} }。
|
||||
-- 依赖是**外部系统包**(发行版装的),插件不擅自 apt/dnf 安装 —— 那需要 root 且
|
||||
-- 会改动运维的机器;如实报告缺什么,由运维或部署脚本装。deploy.sh 提供安装路径。
|
||||
local BROWSER_DEPS = {
|
||||
{ bin = "Xvfb", pkg = "xvfb", why = "虚拟显示" },
|
||||
{ bin = "x11vnc", pkg = "x11vnc", why = "VNC 服务端" },
|
||||
{ bin = "websockify", pkg = "websockify", why = "VNC→WebSocket 网关" },
|
||||
{ bin = "python3", pkg = "python3", why = "CDP 取凭据" },
|
||||
}
|
||||
local function which(bin)
|
||||
local h = io.popen("command -v " .. bin .. " 2>/dev/null")
|
||||
if not h then return false end
|
||||
local p = h:read("*l")
|
||||
h:close()
|
||||
return p ~= nil and p ~= ""
|
||||
end
|
||||
|
||||
-- reapBrowser 回收本插件拉起的整组进程。进程是插件起的,插件负责杀 ——
|
||||
-- 留一个孤儿 chromium 会一直占着显示与内存,且下次 spawn 会撞端口。
|
||||
local function reapBrowser()
|
||||
local b = browserStack()
|
||||
for _, pid in ipairs(b.pids or {}) do
|
||||
@ -1151,48 +1396,288 @@ local function reapBrowser()
|
||||
b.session = nil
|
||||
end
|
||||
|
||||
-- spawnBrowser 拉起一组服务端浏览器。返回 view_url(给 iframe 内嵌)或 nil, err。
|
||||
-- start_url 是浏览器要打开的登录页;redirect_host 是拼 redirect_uri 用的主机名
|
||||
-- (浏览器在服务端,127.0.0.1 就是服务端自己的回环 —— 回调直接命中网关)。
|
||||
local function browserDeps()
|
||||
local missing, present = {}, {}
|
||||
for _, d in ipairs(BROWSER_DEPS) do
|
||||
if which(d.bin) then present[#present + 1] = d.bin
|
||||
else missing[#missing + 1] = { bin = d.bin, pkg = d.pkg, why = d.why } end
|
||||
end
|
||||
-- chromium 的二进制名随发行版变化(chromium / chromium-browser / google-chrome)
|
||||
local chromium = nil
|
||||
for _, c in ipairs({ "chromium", "chromium-browser", "google-chrome", "google-chrome-stable" }) do
|
||||
if which(c) then chromium = c break end
|
||||
end
|
||||
if chromium then present[#present + 1] = chromium
|
||||
else missing[#missing + 1] = { bin = "chromium", pkg = "chromium", why = "浏览器" } end
|
||||
-- noVNC 静态资源(websockify --web 指向它)
|
||||
local novnc = nil
|
||||
for _, p in ipairs({ "/usr/share/novnc", "/usr/share/webapps/novnc", "/opt/novnc" }) do
|
||||
local f = io.open(p .. "/vnc.html", "r")
|
||||
if f then f:close() novnc = p break end
|
||||
end
|
||||
if not novnc then
|
||||
missing[#missing + 1] = { bin = "novnc", pkg = "novnc", why = "浏览器内嵌页面" }
|
||||
end
|
||||
-- CDP 需要 websocket 客户端
|
||||
local pyws = false
|
||||
if which("python3") then
|
||||
local h = io.popen("python3 -c 'import websocket' 2>/dev/null && echo yes")
|
||||
if h then local r = h:read("*l") h:close() pyws = (r == "yes") end
|
||||
end
|
||||
if which("python3") and not pyws then
|
||||
missing[#missing + 1] = { bin = "python3-websocket", pkg = "python3-websocket", why = "CDP 取凭据(websocket-client)" } end
|
||||
return {
|
||||
ok = #missing == 0,
|
||||
missing = missing,
|
||||
present = present,
|
||||
chromium = chromium,
|
||||
novnc = novnc,
|
||||
}
|
||||
end
|
||||
|
||||
-- gatewayPort 问内核要本网关的监听端口。VNC 里的浏览器要回调到本插件的挂载点,
|
||||
-- 端口不能硬编码(非默认部署会全错)。内核 status 里带 listen(如 "0.0.0.0:8081")。
|
||||
-- gatewayPort 求本网关的监听端口。VNC 里的浏览器要回调到本插件的挂载点,
|
||||
-- 端口不能硬编码(非默认部署会全错)。
|
||||
--
|
||||
-- 端口由插件**自己**取得,不问内核:插件在信任模型里就是可信、有完整 OS 能力的
|
||||
-- (能拉浏览器栈、能在磁盘上读写),读一下自己的 config.yaml 是它能力范围内的事。
|
||||
-- 为了一个端口给内核加只读动作,既不必要,也污染了内核的「零厂商/零部署知识」边界。
|
||||
-- 优先级:settings 显式覆盖 > config.yaml 的 listen > 环境变量 > 默认值。
|
||||
local function gatewayPort()
|
||||
-- ① settings:运维可显式指定(前置代理 / 反代场景,对外端口与 listen 不同)
|
||||
local s = plugin.state.settings and plugin.state.settings.gateway_port
|
||||
if tonumber(s) then return tonumber(s) end
|
||||
-- ② 配置文件:插件与内核同机,直接读自己的配置
|
||||
for _, path in ipairs({
|
||||
"/etc/llmsproxy/config.yaml",
|
||||
"/usr/local/etc/llmsproxy/config.yaml",
|
||||
}) do
|
||||
local f = io.open(path, "r")
|
||||
if f then
|
||||
local listen = f:read("*a")
|
||||
f:close()
|
||||
if listen then
|
||||
local addr = listen:match("\nlisten:%s*([^\n]%S*)") or listen:match("^listen:%s*([^\n]%S*)")
|
||||
if addr then
|
||||
local p = addr:match(":(%d+)")
|
||||
if p then return tonumber(p) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- ③ 实听端口:从内核自己的监听 socket 反查(配置文件缺失/被换时兜底)
|
||||
do
|
||||
local h = io.popen("ss -ltnp 2>/dev/null | grep 'pid=' | grep -o ':[0-9]*' | head -1")
|
||||
if h then
|
||||
local line = h:read("*l")
|
||||
h:close()
|
||||
local p = line and line:match(":(%d+)")
|
||||
if p then return tonumber(p) end
|
||||
end
|
||||
end
|
||||
return 8081
|
||||
end
|
||||
|
||||
-- waitPort 等端口就绪(就绪探针),避免「进程起来了但还不能连」。
|
||||
-- 返回 true/false,最多等 timeout_ms。
|
||||
local function waitPort(host, port, timeoutMs)
|
||||
local deadline = (os.time and os.time() or 0) * 1000 + timeoutMs
|
||||
while true do
|
||||
local h = io.popen(("bash -c 'exec 3<>/dev/tcp/%s/%d' 2>/dev/null && echo ok"):format(host, port))
|
||||
local r = h and h:read("*l")
|
||||
if h then h:close() end
|
||||
if r == "ok" then return true end
|
||||
local now = (os.time and os.time() or 0) * 1000
|
||||
if now >= deadline then return false end
|
||||
os.execute("sleep 0.3")
|
||||
end
|
||||
end
|
||||
|
||||
-- CDP 取凭据的 Python 桥。argv: <script> <cdp_port> <expr_file>
|
||||
-- 打印一行 JSON: {"ok":true,"value":<...>} 或 {"ok":false,"error":"..."}
|
||||
-- 用文件传表达式,避免 shell 引号地狱(表达式里常有引号/换行)。
|
||||
local CDP_PY = [[
|
||||
import json, sys, urllib.request
|
||||
try:
|
||||
import websocket
|
||||
except Exception as e:
|
||||
print(json.dumps({"ok": False, "error": "websocket-client 未安装: %s" % e}))
|
||||
sys.exit(0)
|
||||
|
||||
port = int(sys.argv[1])
|
||||
with open(sys.argv[2]) as f:
|
||||
expr = f.read()
|
||||
|
||||
def http(path):
|
||||
with urllib.request.urlopen("http://127.0.0.1:%d%s" % (port, path), timeout=10) as r:
|
||||
return json.load(r)
|
||||
|
||||
try:
|
||||
targets = http("/json/list")
|
||||
except Exception as e:
|
||||
print(json.dumps({"ok": False, "error": "CDP 不可达: %s" % e})); sys.exit(0)
|
||||
|
||||
page = None
|
||||
for t in targets:
|
||||
if t.get("type") == "page" and t.get("webSocketDebuggerUrl"):
|
||||
page = t; break
|
||||
if page is None:
|
||||
print(json.dumps({"ok": False, "error": "没有可用的 page target"})); sys.exit(0)
|
||||
|
||||
try:
|
||||
ws = websocket.create_connection(page["webSocketDebuggerUrl"], timeout=20)
|
||||
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate",
|
||||
"params": {"expression": expr, "returnByValue": True,
|
||||
"awaitPromise": True}}))
|
||||
while True:
|
||||
msg = json.loads(ws.recv())
|
||||
if msg.get("id") == 1:
|
||||
break
|
||||
ws.close()
|
||||
except Exception as e:
|
||||
print(json.dumps({"ok": False, "error": "CDP 求值失败: %s" % e})); sys.exit(0)
|
||||
|
||||
res = msg.get("result", {})
|
||||
if "exceptionDetails" in res:
|
||||
print(json.dumps({"ok": False, "error": res["exceptionDetails"].get("text", "JS 异常")}))
|
||||
sys.exit(0)
|
||||
print(json.dumps({"ok": True, "value": res.get("result", {}).get("value")}))
|
||||
]]
|
||||
|
||||
local function cdpScriptPath()
|
||||
local p = "/tmp/llmsproxy-cdp-eval.py"
|
||||
local f = io.open(p, "r")
|
||||
if f then f:close() return p end
|
||||
local w = io.open(p, "w")
|
||||
if not w then return nil end
|
||||
w:write(CDP_PY)
|
||||
w:close()
|
||||
return p
|
||||
end
|
||||
|
||||
-- cdpEval 在服务端浏览器的当前页上求值一个 JS 表达式。
|
||||
-- 返回 (value, err)。value 是 JS 返回值(经 returnByValue 序列化)。
|
||||
local function cdpEval(cdpPort, expr)
|
||||
local script = cdpScriptPath()
|
||||
if not script then return nil, "无法写入 CDP 脚本" end
|
||||
local exprFile = ("/tmp/llmsproxy-cdp-expr-%d.js"):format(cdpPort)
|
||||
local w = io.open(exprFile, "w")
|
||||
if not w then return nil, "无法写入表达式文件" end
|
||||
w:write(expr)
|
||||
w:close()
|
||||
local h = io.popen(("python3 %s %d %s 2>/dev/null"):format(script, cdpPort, exprFile))
|
||||
if not h then os.remove(exprFile) return nil, "python3 执行失败" end
|
||||
local out = h:read("*a")
|
||||
h:close()
|
||||
os.remove(exprFile)
|
||||
if not out or out == "" then return nil, "CDP 无输出" end
|
||||
local ok, rec = pcall(json.decode, out)
|
||||
if not ok or type(rec) ~= "table" then return nil, "CDP 输出无法解析: " .. tostring(out):sub(1, 200) end
|
||||
if rec.ok ~= true then return nil, tostring(rec.error or "CDP 失败") end
|
||||
return rec.value, nil
|
||||
end
|
||||
|
||||
-- spawnBrowser 拉起一组服务端浏览器。返回
|
||||
-- { view_url, password, cdp_port, display, vnc, ws } 或 nil, err。
|
||||
-- start_url 是浏览器要打开的登录页;callback_path 是拼 redirect_uri 用的路径。
|
||||
--
|
||||
-- 与早期实现的差别(都是真实踩过的坑):
|
||||
-- 1. **就绪探针**:不再 sleep 2 拍脑袋,各端口逐个等(X 起来 → 浏览器起 →
|
||||
-- VNC 起 → websockify 起),否则 view_url 先于服务可用,iframe 白屏。
|
||||
-- 2. **CDP 端口**:浏览器带 --remote-debugging-port,登录完成后可读凭据
|
||||
-- (见 cdpEval / vncCollect),而不是只能人眼看屏幕。
|
||||
-- 3. **网关端口来自内核**:回调地址拼的是本实例真实端口,不硬编码 8081。
|
||||
-- 4. **依赖预检**:缺依赖直接给出清单(谁、干什么用、装什么包),
|
||||
-- 而不是一个含糊的"进程启动失败"。
|
||||
local function spawnBrowser(start_url, callback_path)
|
||||
local b = browserStack()
|
||||
if b.session then return nil, "已有浏览器会话在跑,请先停止" end
|
||||
local deps = browserDeps()
|
||||
if not deps.ok then
|
||||
local miss = {}
|
||||
for _, m in ipairs(deps.missing) do
|
||||
miss[#miss + 1] = ("%s(%s,装 %s)"):format(m.bin, m.why, m.pkg)
|
||||
end
|
||||
return nil, "缺少浏览器栈依赖: " .. table.concat(miss, ", ")
|
||||
end
|
||||
b.seq = b.seq + 1
|
||||
local disp = 90 + (b.seq % 10)
|
||||
local vport = 59100 + (b.seq % 100)
|
||||
local wport = 60100 + (b.seq % 100)
|
||||
local seq = b.seq
|
||||
local disp = 90 + (seq % 10)
|
||||
local vport = 59100 + (seq % 100)
|
||||
local wport = 60100 + (seq % 100)
|
||||
local cdpPort = 61100 + (seq % 100)
|
||||
local bind = (plugin.state.settings and plugin.state.settings.vnc_bind) or "127.0.0.1"
|
||||
-- 会话密码:bind 到非回环时是唯一的防线,随机生成、只在响应里给一次
|
||||
local pass = sha256_hex(newToken()):sub(1, 16)
|
||||
-- 端口占位换成网关回环(浏览器在服务端,回调直接命中网关挂载点)
|
||||
local url = start_url:gsub("redirect_uri=127%.0%.0%.1:%%d+", "redirect_uri=127.0.0.1:8081" .. callback_path)
|
||||
local gwPort = gatewayPort()
|
||||
-- 端口占位换成网关真实回环地址(浏览器在服务端,回调直接命中网关挂载点)
|
||||
local url = start_url:gsub("redirect_uri=127%.0%.0%.1:%%d+",
|
||||
"redirect_uri=127.0.0.1:" .. gwPort .. callback_path)
|
||||
|
||||
local cmds = {
|
||||
("Xvfb :%d -screen 0 1280x800x24 -nolisten tcp & echo $!"):format(disp),
|
||||
("chromium --no-sandbox --disable-dev-shm-usage --user-data-dir=/tmp/llmsproxy-ch-%d --no-first-run --window-size=1280,800 --display=:%d '%s' & echo $!"):format(b.seq, disp, url),
|
||||
("x11vnc -display :%d -rfbport %d -%s -passwd '%s' -forever -shared -quiet & echo $!"):format(disp, vport, bind == "127.0.0.1" and "localhost" or "listen", pass),
|
||||
("websockify --web /usr/share/novnc %s:%d 127.0.0.1:%d & echo $!"):format(bind, wport, vport),
|
||||
}
|
||||
-- 每步起一个进程并等它的端口就绪(X 用 socket 探,别的用 TCP)。
|
||||
local pids = {}
|
||||
for _, c in ipairs(cmds) do
|
||||
local h = io.popen(c)
|
||||
local pid = h:read("*l")
|
||||
h:close()
|
||||
local function spawn(name, cmd, host, port, timeoutMs)
|
||||
local h = io.popen(cmd)
|
||||
local pid = h and h:read("*l")
|
||||
if h then h:close() end
|
||||
if not pid or pid == "" then
|
||||
reapBrowser()
|
||||
return nil, "进程启动失败: " .. c:match("^(%S+)") .. "(缺依赖?运行 deploy 脚本一键安装)"
|
||||
return false, name .. " 启动失败"
|
||||
end
|
||||
pids[#pids+1] = pid
|
||||
pids[#pids + 1] = pid
|
||||
if port and port > 0 then
|
||||
if not waitPort(host or "127.0.0.1", port, timeoutMs or 8000) then
|
||||
return false, name .. " 端口未就绪(:" .. port .. ")"
|
||||
end
|
||||
end
|
||||
return true, pid
|
||||
end
|
||||
-- 给 X/chromium 一点起进程时间;不等待就绪探针(保持插件逻辑简单,失败可重试)
|
||||
os.execute("sleep 2")
|
||||
|
||||
local chromium = deps.chromium
|
||||
local novnc = deps.novnc
|
||||
local steps = {
|
||||
{ "Xvfb", ("Xvfb :%d -screen 0 1280x800x24 -nolisten tcp >/tmp/llmsproxy-xvfb-%d.log 2>&1 & echo $!"):format(disp, seq), nil, 0, 0 },
|
||||
{ "chromium", ("%s --no-sandbox --disable-dev-shm-usage --user-data-dir=/tmp/llmsproxy-ch-%d "
|
||||
.. "--no-first-run --disable-gpu --remote-debugging-port=%d --remote-allow-origins=* "
|
||||
.. "--window-size=1280,800 --display=:%d '%s' >/tmp/llmsproxy-chrome-%d.log 2>&1 & echo $!"):format(
|
||||
chromium, seq, cdpPort, disp, url, seq), "127.0.0.1", cdpPort, 15000 },
|
||||
{ "x11vnc", ("x11vnc -display :%d -rfbport %d -%s -passwd '%s' -forever -shared -quiet "
|
||||
.. ">/tmp/llmsproxy-x11vnc-%d.log 2>&1 & echo $!"):format(
|
||||
disp, vport, bind == "127.0.0.1" and "localhost" or "listen", pass, seq), "127.0.0.1", vport, 8000 },
|
||||
{ "websockify", ("websockify --web %s %s:%d 127.0.0.1:%d >/tmp/llmsproxy-ws-%d.log 2>&1 & echo $!"):format(
|
||||
novnc, bind, wport, vport, seq), bind, wport, 8000 },
|
||||
}
|
||||
-- X 的 socket 在 /tmp/.X11-unix/X<n>,先等它出现再起浏览器
|
||||
local unixSock = ("/tmp/.X11-unix/X%d"):format(disp)
|
||||
local xdeadline = (os.time and os.time() or 0) + 10
|
||||
while true do
|
||||
local f = io.open(unixSock, "r")
|
||||
if f then f:close() break end
|
||||
if (os.time and os.time() or 0) >= xdeadline then
|
||||
reapBrowser()
|
||||
return nil, "Xvfb 未就绪(" .. unixSock .. " 未出现)"
|
||||
end
|
||||
os.execute("sleep 0.3")
|
||||
end
|
||||
for _, st in ipairs(steps) do
|
||||
if st[1] ~= "Xvfb" then
|
||||
local ok, err = spawn(st[1], st[2], st[3], st[4], st[5])
|
||||
if not ok then
|
||||
reapBrowser()
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
b.pids = pids
|
||||
b.session = { display = disp, vnc = vport, ws = wport, pass = pass }
|
||||
-- view_url 指向 websockify 伺服的 noVNC;同机直接 127.0.0.1,远程用 settings.vnc_host 覆盖
|
||||
b.session = { display = disp, vnc = vport, ws = wport, cdp = cdpPort, pass = pass, seq = seq }
|
||||
local host = (plugin.state.settings and plugin.state.settings.vnc_host) or "127.0.0.1"
|
||||
return {
|
||||
view_url = ("http://%s:%d/vnc.html?autoconnect=1&host=%s&port=%d&password=%s"):format(host, wport, host, wport, pass),
|
||||
view_url = ("http://%s:%d/vnc.html?autoconnect=1&host=%s&port=%d&password=%s"):format(
|
||||
host, wport, host, wport, pass),
|
||||
password = pass,
|
||||
cdp_port = cdpPort,
|
||||
display = disp,
|
||||
}
|
||||
end
|
||||
|
||||
@ -1271,11 +1756,15 @@ function plugin.start_login(req)
|
||||
local bs, berr = spawnBrowser(string.format(plat.login_url, 0), "/api/plugins/http/channels/callback")
|
||||
if berr then
|
||||
out.browser_error = berr
|
||||
out.hint = "服务端浏览器不可用;先装依赖(见插件一键初始化),或改用其他登录流程"
|
||||
out.hint = "服务端浏览器不可用;运行 channels/deps/status 看缺什么依赖"
|
||||
logEvent("服务端浏览器启动失败: " .. berr)
|
||||
else
|
||||
out.view_url = bs.view_url
|
||||
logEvent("服务端浏览器已就绪 " .. plat.id)
|
||||
out.session.cdp_port = bs.cdp_port
|
||||
sess.cdp_port = bs.cdp_port
|
||||
-- 登录页需要从服务端浏览器完成;用户交互后由 collect_credentials 取凭据
|
||||
sess.collect_expr = plat.collect_expr
|
||||
logEvent("服务端浏览器已就绪 " .. plat.id .. " (CDP :" .. tostring(bs.cdp_port) .. ")")
|
||||
end
|
||||
elseif plat.flow == "device-poll" then
|
||||
-- 设备码:申请码,把 user_code + 授权 URL 给用户,verifier 存进会话。
|
||||
@ -1724,6 +2213,15 @@ plugin.http = {
|
||||
roles = { "admin" }, description = "领取新人奖励" },
|
||||
{ path = "channels/inject_platforms", method = "POST", handler = "inject_platforms",
|
||||
roles = { "admin" }, description = "注入测试/扩展平台定义(运行时,不落盘)" },
|
||||
-- 服务端浏览器栈(VNC 兜底)的运维面
|
||||
{ path = "channels/deps/status", method = "GET", handler = "deps_status",
|
||||
roles = { "admin" }, description = "浏览器栈依赖预检(缺什么、装哪个包)" },
|
||||
{ path = "channels/browser/status", method = "GET", handler = "browser_status",
|
||||
roles = { "admin" }, description = "服务端浏览器会话状态" },
|
||||
{ path = "channels/browser/collect", method = "POST", handler = "collect_credentials",
|
||||
roles = { "admin" }, description = "从服务端浏览器取凭据(CDP)" },
|
||||
{ path = "channels/browser/stop", method = "POST", handler = "stop_browser",
|
||||
roles = { "admin" }, description = "回收服务端浏览器栈" },
|
||||
}
|
||||
|
||||
-- set_endpoints:改写某平台的端点声明(device.code_url/token_url、checkin.url、
|
||||
@ -1897,11 +2395,11 @@ function plugin.model_set_disabled(req)
|
||||
if not plat then return { status = 400, json = { error = "未知平台" } } end
|
||||
local mid = tostring(args and args.model_id or "")
|
||||
if mid == "" then return { status = 400, json = { error = "缺 model_id" } } end
|
||||
local disabled = disabledModelsOf(plat.id)
|
||||
if args.disabled then disabled[mid] = true else disabled[mid] = nil end
|
||||
local want = args.disabled and true or false
|
||||
setModelDisabled(plat.id, mid, want)
|
||||
-- 重同步该平台的全部源,让模型开关立即生效
|
||||
for _, a in ipairs(poolList(plat.id)) do syncAccountSource(plat.id, a.id) end
|
||||
return { status = 200, json = { ok = true, disabled = disabled[mid] and true or false } }
|
||||
return { status = 200, json = { ok = true, disabled = want } }
|
||||
end
|
||||
|
||||
function plugin.model_set_all_disabled(req)
|
||||
@ -1915,6 +2413,7 @@ function plugin.model_set_all_disabled(req)
|
||||
else
|
||||
for k in pairs(disabled) do disabled[k] = nil end
|
||||
end
|
||||
markDirty()
|
||||
for _, a in ipairs(poolList(plat.id)) do syncAccountSource(plat.id, a.id) end
|
||||
return { status = 200, json = { ok = true } }
|
||||
end
|
||||
@ -1953,6 +2452,7 @@ function plugin.provider_set_enabled(req)
|
||||
local disabled = disabledModelsOf(plat.id)
|
||||
if enabled then
|
||||
for k in pairs(disabled) do disabled[k] = nil end
|
||||
markDirty()
|
||||
for _, a in ipairs(poolList(plat.id)) do a.enabled = true poolAdd(plat.id, a) syncAccountSource(plat.id, a.id) end
|
||||
-- 旧路径也启用
|
||||
local legacy = plugin.state.accounts[plat.id]
|
||||
@ -2057,6 +2557,7 @@ function plugin.backup_import(req)
|
||||
-- 恢复模型黑名单
|
||||
if type(payload.modelDisabled) == "table" then
|
||||
plugin.state.modelDisabled = payload.modelDisabled
|
||||
markDirty()
|
||||
end
|
||||
-- 恢复自动签到开关
|
||||
if payload.autoCheckin ~= nil then
|
||||
@ -2077,6 +2578,7 @@ function plugin.auto_checkin(req)
|
||||
local args = bodyOf(req)
|
||||
if args.enabled ~= nil then
|
||||
plugin.state.settings.auto_checkin = args.enabled and true or false
|
||||
markDirty()
|
||||
logEvent("自动签到" .. (plugin.state.settings.auto_checkin and "开启" or "关闭"))
|
||||
end
|
||||
return { status = 200, json = { ok = true, autoCheckin = plugin.state.settings.auto_checkin ~= false } }
|
||||
@ -2187,6 +2689,7 @@ function plugin.credits_permanent_lock(req)
|
||||
return { status = 400, json = { error = "locked 必须是布尔值" } }
|
||||
end
|
||||
plugin.state.settings["lock_" .. plat.id] = args.locked
|
||||
markDirty()
|
||||
logEvent("永久积分" .. (args.locked and "锁定 " or "解除 ") .. plat.id)
|
||||
end
|
||||
return { status = 200, json = { ok = true, locked = plugin.state.settings["lock_" .. plat.id] == true,
|
||||
@ -2240,6 +2743,7 @@ function plugin.model_set_disabled_many(req)
|
||||
for _, mid in ipairs(ids) do
|
||||
if args.disabled then disabled[tostring(mid)] = true else disabled[tostring(mid)] = nil end
|
||||
end
|
||||
markDirty()
|
||||
for _, a in ipairs(poolList(plat.id)) do syncAccountSource(plat.id, a.id) end
|
||||
return { status = 200, json = { ok = true } }
|
||||
end
|
||||
@ -2257,6 +2761,7 @@ function plugin.model_clear_dead(req)
|
||||
for _, m in ipairs(plat.models or {}) do if m == mid then alive = true break end end
|
||||
if not alive then disabled[mid] = nil removed[#removed+1] = mid end
|
||||
end
|
||||
markDirty()
|
||||
for _, a in ipairs(poolList(plat.id)) do syncAccountSource(plat.id, a.id) end
|
||||
return { status = 200, json = { ok = true, removed = removed } }
|
||||
end
|
||||
@ -2277,6 +2782,7 @@ function plugin.provider_set_order(req)
|
||||
if platformById(tostring(id)) then cleaned[#cleaned+1] = tostring(id) end
|
||||
end
|
||||
plugin.state.providerOrder = cleaned
|
||||
markDirty()
|
||||
return { status = 200, json = { ok = true } }
|
||||
end
|
||||
|
||||
@ -2525,6 +3031,119 @@ end
|
||||
-- “这就是本轮我要用的目录”,避免测试之间残留状态。传空数组即清空。
|
||||
-- 容量上限:注入属于运维/测试能力,不承担生产目录职责,限 32 条够用。
|
||||
local INJECT_PLATFORM_LIMIT = 32
|
||||
-- ============================================================================
|
||||
-- 服务端浏览器栈的运维面(依赖预检 / 取凭据 / 停栈)
|
||||
-- ============================================================================
|
||||
|
||||
-- deps_status:如实报告浏览器栈缺什么依赖。插件**不擅自**安装系统包(需要 root
|
||||
-- 且会改动运维的机器);如实报告 + 给出安装命令,由运维或 deploy.sh 执行。
|
||||
function plugin.deps_status(req)
|
||||
local d = browserDeps()
|
||||
local list = {}
|
||||
for _, m in ipairs(d.missing) do
|
||||
list[#list + 1] = { bin = m.bin, pkg = m.pkg, why = m.why }
|
||||
end
|
||||
return { status = 200, json = {
|
||||
ok = d.ok,
|
||||
missing = list,
|
||||
present = d.present,
|
||||
chromium = d.chromium,
|
||||
novnc = d.novnc,
|
||||
-- 安装命令按发行版给两条(运维自己选),插件不执行它
|
||||
install_hint = d.ok and "" or
|
||||
"Debian/Ubuntu: apt-get install -y xvfb x11vnc websockify novnc chromium python3-websocket | "
|
||||
.. "RHEL/Fedora: dnf install -y xorg-x11-server-Xvfb x11vnc python3-websockify novnc chromium python3-websocket-client",
|
||||
} }
|
||||
end
|
||||
|
||||
-- collect_credentials:从**运行中的**服务端浏览器取凭据(CDP)。
|
||||
--
|
||||
-- 为什么需要它:VNC 只把浏览器呈现给人,登录完成后必须把结果**取出来**才能
|
||||
-- 变成上游源。取法分两种:
|
||||
-- ① 平台声明了 collect_expr —— 在该页上求值该 JS(返回 token 字符串或对象)
|
||||
-- ② 未声明 —— 回退到通用提取:localStorage / sessionStorage / cookie 全量
|
||||
-- 查到什么存什么,由调用方/运维判断哪个是凭据(不猜语义,不编造)。
|
||||
-- 取到的凭据经 complete_login 走正常入库路径(含 account_id → 池路径)。
|
||||
function plugin.collect_credentials(req)
|
||||
local args = bodyOf(req)
|
||||
if args.platform == nil then args = req end
|
||||
local plat = platformById(args and args.platform)
|
||||
if not plat then return { status = 400, json = { error = "未知平台" } } end
|
||||
local b = browserStack()
|
||||
if not b.session then return { status = 400, json = { error = "没有运行中的浏览器会话" } } end
|
||||
local cdp = b.session.cdp
|
||||
if not cdp then return { status = 400, json = { error = "浏览器会话未启用 CDP" } } end
|
||||
|
||||
local expr = (args and args.expr) or plat.collect_expr
|
||||
local value, err
|
||||
if expr then
|
||||
value, err = cdpEval(cdp, expr)
|
||||
if err then return { status = 400, json = { error = "取值失败: " .. err } } end
|
||||
end
|
||||
|
||||
-- 通用提取:无论有无 collect_expr 都跑一遍,作为兜底与补充。
|
||||
local generic, gerr = cdpEval(cdp, [[
|
||||
(function(){
|
||||
var out = {localStorage:{}, sessionStorage:{}, cookie:document.cookie, url:location.href};
|
||||
try { for (var i=0;i<localStorage.length;i++){var k=localStorage.key(i);out.localStorage[k]=localStorage.getItem(k);} } catch(e){}
|
||||
try { for (var i=0;i<sessionStorage.length;i++){var k=sessionStorage.key(i);out.sessionStorage[k]=sessionStorage.getItem(k);} } catch(e){}
|
||||
return JSON.stringify(out);
|
||||
})()
|
||||
]])
|
||||
|
||||
local rec = {}
|
||||
if value ~= nil then
|
||||
if type(value) == "table" then
|
||||
for k, v in pairs(value) do rec[k] = v end
|
||||
else
|
||||
rec.collected = value
|
||||
end
|
||||
end
|
||||
if generic then
|
||||
local ok, parsed = pcall(json.decode, generic)
|
||||
if ok and type(parsed) == "table" then
|
||||
rec.browser = parsed
|
||||
-- 常见位置的启发式提取(找到就用,找不到不强求)
|
||||
local ls = parsed.localStorage or {}
|
||||
for _, k in ipairs({ "token", "access_token", "accessToken", "auth_token", "jwt", "id_token", "Authorization" }) do
|
||||
if type(ls[k]) == "string" and ls[k] ~= "" and rec.token == nil then rec.token = ls[k] end
|
||||
end
|
||||
local ss = parsed.sessionStorage or {}
|
||||
for _, k in ipairs({ "token", "access_token", "accessToken", "auth_token", "jwt", "id_token" }) do
|
||||
if type(ss[k]) == "string" and ss[k] ~= "" and rec.token == nil then rec.token = ss[k] end
|
||||
end
|
||||
if rec.token == nil and type(parsed.cookie) == "string" then
|
||||
rec.token = parsed.cookie:match("(access_token=[^;]+)")
|
||||
or parsed.cookie:match("(token=[^;]+)")
|
||||
end
|
||||
end
|
||||
elseif gerr then
|
||||
rec.generic_error = gerr
|
||||
end
|
||||
|
||||
if next(rec) == nil then
|
||||
return { status = 200, json = { ok = false, error = "没有取到任何凭据(登录是否真的完成了?)" } }
|
||||
end
|
||||
-- 不自动入库:取到什么原样返回,由调用方确认后再 complete_login。
|
||||
-- 自动写入会把"页面上恰好存在的某个 token"当成凭据,那是最糟的猜测。
|
||||
return { status = 200, json = { ok = true, collected = rec } }
|
||||
end
|
||||
|
||||
-- stop_browser:回收服务端浏览器栈(会话结束/用户放弃时)。
|
||||
function plugin.stop_browser(req)
|
||||
local had = browserStack().session ~= nil
|
||||
reapBrowser()
|
||||
if had then logEvent("服务端浏览器已回收") end
|
||||
return { status = 200, json = { ok = true, stopped = had } }
|
||||
end
|
||||
|
||||
-- browser_status:当前浏览器会话状态(给 UI 显示)。
|
||||
function plugin.browser_status(req)
|
||||
local b = browserStack()
|
||||
local s = b.session
|
||||
return { status = 200, json = { ok = true, running = s ~= nil, session = s } }
|
||||
end
|
||||
|
||||
function plugin.inject_platforms(req)
|
||||
local args = bodyOf(req)
|
||||
if args.platforms == nil then args = req end
|
||||
@ -2553,6 +3172,7 @@ function plugin.inject_platforms(req)
|
||||
clean[#clean + 1] = p
|
||||
end
|
||||
plugin.state.injected_platforms = clean
|
||||
markDirty()
|
||||
if #clean == 0 then
|
||||
logEvent("已清空注入平台")
|
||||
else
|
||||
|
||||
Reference in New Issue
Block a user