refactor(lua): 内核回归六项职责 —— 登录/浏览器全部移入插件

用户钉死了内核的职责边界,本提交把越界部分全部拆除:

  内核只做:加载适配器 · auto 调度 · 加载插件 · 调度插件 · 维护源与 key · 签发密钥

## 架构纠正(用户指出的根本错误)

我此前把信任模型弄反了。实测:插件 VM 的 os.execute/io.popen/package 全部可达
(true,true,true) —— 插件从来不是 OS 级沙箱。正确的边界是:

  插件   可信(运维安装),非沙箱,有完整 OS 能力 → 平台知识/登录/浏览器归它
  适配器 不可信(可被动态安装),请求级 → 沙箱归它(12 个内置适配器实测均不碰
         os/io/package,后续沙箱化零风险,属独立一步)

## 删除(内核越界部分)

- plugin_browser.go        内核浏览器管理器(Xvfb/chromium/x11vnc/websockify
                           进程栈、回环监听器)—— 388 行全删,浏览器由插件用
                           os.execute 自己拉起(实测 spawn+reap 闭环可用)
- plugin_login.go          登录会话状态机 + LoginFlow 枚举 + VNC 全局门禁
                           —— 457 行全删。"登录"从内核概念中消失
- gateway/browser_proxy.go viewer 反代
- handlePluginLogin API    登录会话列表端点
- vnc_enabled 全局开关     改为 per-plugin 授权(见下)

## 新增(内核职责内的通用机制,无任何登录/浏览器语义)

- plugin_outbound.go       通用额外出站主机授权:插件声明 plugin.hosts(请求)
                           → 运维在设置页逐个批准(授权)。与 kernel actions
                           同一"声明≠授权"模型。内核只知道白名单加减,不知道
                           host 被用来干什么
- on_unload 生命周期钩子   卸载是"调度插件"的一部分:内核在关闭插件状态前调用
                           插件导出的 on_unload,让它自清理外部资源。内核不知道
                           资源是什么(进程/句柄/远端会话都行)。带进程回收回归
                           测试 TestOnUnloadReapsPluginProcesses

## channels.lua 全量接管

- 登录会话自持:plugin.state.sessions(nonce 只在 begin 响应出现一次,
  惰性过期清理)
- 服务端浏览器栈自持:spawnBrowser 用 io.popen 拉起 Xvfb/chromium/x11vnc/
  websockify 并记 pid,reapBrowser 回收;on_unload 兜底
- 优先级阶梯(用户指定):① 本机浏览器(给 URL)→ ② 自动化(轮询/nonce 回调)
  → ③ VNC 无头浏览器兜底(无浏览器系统/自动化无法完成的场景,如回环重定向
  必须落在服务端)
- plugin.auth_hosts → plugin.hosts(语义泛化:出站主机授权与登录无关)

## 验收

- 全仓旧符号零残留(grep 权威确认,代码+注释+lua+测试)
- 内核非测试代码零厂商名
- build + vet 全绿;lua/core/gateway/types/scheduler/provider 全量测试通过
- channels 端到端(登录→凭据→add_source→模型可见)继续通过
This commit is contained in:
JianFeeeee
2026-10-11 16:24:55 +08:00
parent fa50ec8bc7
commit 74ec1e7874
14 changed files with 425 additions and 1778 deletions

View File

@ -245,242 +245,6 @@ func readPluginKernelDeclared(L *golua.State) []string {
return out
}
// loginGlobal is the Lua name of the login-session bridge.
const loginGlobal = "__llmsproxy_login"
// registerLoginBridge installs the login session API.
//
// A plugin drives the whole flow itself (it knows the platform's endpoints) and
// the kernel only owns the session lifecycle: create, poll, resolve, cancel.
// That split is what lets one kernel serve OAuth, device-code, QR and paste
// flows without containing any platform knowledge.
func registerLoginBridge(L *golua.State, ps *Plugins, name string) {
L.NewTable()
L.PushGoClosure(luaLoginBegin(ps, name))
L.SetField(-2, "begin")
L.PushGoClosure(luaLoginGet(ps, name))
L.SetField(-2, "get")
L.PushGoClosure(luaLoginResolve(ps, name))
L.SetField(-2, "resolve")
L.PushGoClosure(luaLoginList(ps, name))
L.SetField(-2, "list")
L.PushGoClosure(luaLoginCancel(ps, name))
L.SetField(-2, "cancel")
// 服务端浏览器(回环类登录的唯一自动化路径)。与登录会话同一张表,
// 因为它就是登录的一种流程,而不是独立能力。
L.PushGoClosure(luaBrowserStart(ps, name))
L.SetField(-2, "start_browser")
L.PushGoClosure(luaBrowserGet(ps, name))
L.SetField(-2, "get_browser")
L.PushGoClosure(luaBrowserStop(ps, name))
L.SetField(-2, "stop_browser")
L.SetGlobal(loginGlobal)
}
// luaBrowserStart: start_browser({platform, start_url, callback_port}) ->
//
// ({view_url, id, callback_port}, nil) | (nil, err)
//
// The plugin gets a VIEW URL, never a browser-control handle. That is the
// deliberate boundary: a plugin that could drive the browser arbitrarily could
// read every tab's cookies, and the browser is logged into the OPERATOR's
// third-party accounts, not the plugin's own.
func luaBrowserStart(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
args, err := luaTableArg(L, 1)
if err != nil {
L.PushNil()
L.PushString("__llmsproxy_login.start_browser: " + err.Error())
return 2
}
port := 0
if n, ok := asFloat(args["callback_port"]); ok {
port = int(n)
}
sess, err := ps.StartBrowserSession(name, asString(args["platform"]),
asString(args["start_url"]), port)
if err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
pushGoValue(L, browserToLua(*sess))
L.PushNil()
return 2
}
}
// luaBrowserGet: get_browser(id) -> (session, nil) | (nil, nil)
func luaBrowserGet(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
id := L.ToString(1)
s, ok := ps.GetBrowserSession(id)
if !ok || s.Plugin != name {
L.PushNil()
L.PushNil()
return 2
}
pushGoValue(L, browserToLua(*s))
L.PushNil()
return 2
}
}
// luaBrowserStop: stop_browser(id) -> (true, nil)
func luaBrowserStop(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
id := L.ToString(1)
if s, ok := ps.GetBrowserSession(id); ok && s.Plugin == name {
ps.StopBrowserSession(id)
}
L.PushBoolean(true)
L.PushNil()
return 2
}
}
// browserToLua renders a browser session for Lua. The CDP/debug ports are NOT
// included: the plugin receives what it needs to display the viewer and read the
// captured code, and nothing that would let it drive the browser.
func browserToLua(s BrowserSession) map[string]interface{} {
return map[string]interface{}{
"id": s.ID,
"platform": s.Platform,
"view_url": s.ViewURL,
"callback_port": s.CallbackPort,
"captured_code": s.CapturedCode,
"state": s.CapturedState,
"error": s.Error,
"started_at": s.StartedAt.Unix(),
"expires_at": s.ExpiresAt.Unix(),
}
}
// luaLoginBegin: begin({platform, flow, url, user_code}) -> (session, nil) | (nil, err)
func luaLoginBegin(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
args, err := luaTableArg(L, 1)
if err != nil {
L.PushNil()
L.PushString("__llmsproxy_login.begin: " + err.Error())
return 2
}
s := LoginSession{
Plugin: name,
Platform: asString(args["platform"]),
Flow: LoginFlow(asString(args["flow"])),
URL: asString(args["url"]),
UserCode: asString(args["user_code"]),
}
out, err := ps.BeginLogin(s)
if err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
pushGoValue(L, sessionToLua(*out, true))
L.PushNil()
return 2
}
}
// luaLoginGet: get(id) -> (session, nil) | (nil, err)
func luaLoginGet(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
id := L.ToString(1)
s, ok := ps.GetLogin(id)
if !ok {
L.PushNil()
L.PushNil() // absent is not an error; the plugin tests for nil
return 2
}
if s.Plugin != name {
// Another plugin's session is indistinguishable from a missing one.
// Reporting "not yours" would confirm the id exists.
L.PushNil()
L.PushNil()
return 2
}
pushGoValue(L, sessionToLua(*s, false))
L.PushNil()
return 2
}
}
// luaLoginResolve: resolve(id, state, account, message) -> (true, nil) | (nil, err)
func luaLoginResolve(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
id := L.ToString(1)
state := LoginSessionState(L.ToString(2))
account := L.ToString(3)
message := L.ToString(4)
s, ok := ps.GetLogin(id)
if !ok || s.Plugin != name {
L.PushNil()
L.PushString("no such login session")
return 2
}
if err := ps.ResolveLogin(id, state, account, message); err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
L.PushBoolean(true)
L.PushNil()
return 2
}
}
// luaLoginList: list() -> (array of sessions, nil)
func luaLoginList(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
sessions := ps.ListLogins(name)
L.NewTable()
for i, s := range sessions {
pushGoValue(L, sessionToLua(s, false))
L.RawSeti(-2, i+1)
}
L.PushNil()
return 2
}
}
// luaLoginCancel: cancel(id) -> (true, nil)
func luaLoginCancel(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
id := L.ToString(1)
s, ok := ps.GetLogin(id)
if ok && s.Plugin == name {
_ = ps.ResolveLogin(id, LoginCancelled, "", "cancelled by the plugin")
}
L.PushBoolean(true)
L.PushNil()
return 2
}
}
// sessionToLua renders a session for Lua. The nonce is included ONLY on begin
// (the plugin needs it to build its redirect_uri); subsequent reads omit it so a
// plugin that logs or forwards a session cannot leak the CSRF token.
func sessionToLua(s LoginSession, includeNonce bool) map[string]interface{} {
out := map[string]interface{}{
"id": s.ID,
"platform": s.Platform,
"flow": string(s.Flow),
"state": string(s.State),
"url": s.URL,
"user_code": s.UserCode,
"message": s.Message,
"account": s.Account,
"created_at": s.CreatedAt.Unix(),
"expires_at": s.ExpiresAt.Unix(),
}
if includeNonce {
out["nonce"] = s.Nonce
}
return out
}
// luaTableArg decodes a Lua table argument into a Go map, reporting a clear error
// when the caller passed something else (a common mistake that would otherwise
// surface as a silent zero value).
@ -498,46 +262,3 @@ func luaTableArg(L *golua.State, idx int) (map[string]interface{}, error) {
}
return m, nil
}
// readPluginAuthHosts reads `plugin.auth_hosts`, the login hosts a plugin needs.
//
// plugin.auth_hosts = { "auth.example.com", "accounts.google.com" }
//
// A list of bare hostnames — not URLs — because the allowlist matches on host,
// and accepting full URLs would invite a plugin to smuggle a path or scheme that
// the operator did not read. Entries are normalised so the granted and declared
// forms always compare equal.
func readPluginAuthHosts(L *golua.State) []string {
raw, ok := pluginFieldValue(L, "auth_hosts")
if !ok {
return nil
}
items, isList := raw.([]interface{})
if !isList {
if one, isTable := raw.(map[string]interface{}); isTable {
if v, ok := one["hosts"].([]interface{}); ok {
items = v
} else {
return nil
}
} else {
return nil
}
}
out := make([]string, 0, len(items))
seen := map[string]bool{}
for _, it := range items {
s, ok := it.(string)
if !ok {
continue
}
h := normalizeHost(s)
if h == "" || seen[h] {
continue
}
seen[h] = true
out = append(out, h)
}
sort.Strings(out)
return out
}