Files
ModelRouter/internal/lua/plugin_bridges.go
JianFeeeee 9bec158d2e chore(main): 回流 release/v2.0.x(v2.0.12)—— 内容对齐,main 无独有内容
按发布纪律回流。**注意这是内容对齐而非 merge**,理由与依据:

1. 纪律禁止 merge 回主干,因为 merge 会把发布分支的**版本号变更**带进 main。
   本项目版本号**只由 `git describe --tags` 推导**(Makefile VERSION),
   仓库里没有任何文件存放版本号 ⇒ 回流不存在版本污染风险。
2. 逐项核对确认 **main 是 release 的内容严格子集**:
   - `main` 独有的**文件**:0 个;
   - `internal/lua/plugins.go` / `internal/core/kernel_actions.go` 等内核文件
     main 独有行数:0;
   - `deploy.sh` 那 14 行只是 emoji 清理(release 刻意去掉了 emoji);
   - `channels.lua` 那 333 行是**旧版内容**(旧 exports 表、旧模型名单)。
   - main 独有的 9 个提交按 patch-id **全部已在 release 中等效存在**
     (`git cherry` 逐条列出均为 `-`,即已合入)。
3. 故回流 = 把 release 的内容带到 main,等价于"只捡拾修复、不带版本号",
   且不会丢任何 main 独有的修复。

本次带回 v2.0.12 的全部内容(37 个提交):
- 源串行 + 按模型节流(照 model-gate)
- 已失效模型存储 + 远端目录闸门
- 余额分档选号
- 模型能力元数据(models.dev,isFree 权威判定)
- **凭据续期修复**(此前恒报 ok:true 却一个请求都不发)
- 通用件 TTL 缓存 + 串行锁;account_test/account_adopt/account_delete 修正
- 内核级:出站授权持久化重启后不生效、`__llmsproxy_plugin_dir` ground truth

校验:`git diff release/v2.0.x` = 0 行;`go build -tags luajit ./...` 通过。
2026-10-14 16:52:58 +08:00

286 lines
8.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package lua
import (
"fmt"
"sort"
"strings"
golua "github.com/aarzilli/golua/lua"
)
// Package lua — Lua 绑定:凭据保险库 + 内核动作面
//
// 这两个全局把"插件自己主导链接认证"所需的两块补齐:
//
// __llmsproxy_secrets —— 安全存放 OAuth token / session / 设备指纹
// __llmsproxy_kernel —— 触发内核动作(注册源、探测、清冷却、改链路…)
//
// 注册点与 __llmsproxy_http 相同:只在 PLUGIN 的 bootPluginState 里装,
// 因为适配器共用 setupGlobals 而不该拿到这些能力。
//
// 两张表都用 buildJSONTable 的既有写法(NewTable + PushGoClosure + SetField),
// 该写法在 json 表上长期稳定,也是内核自己的用法。
// secretGlobal 是凭据保险库的 Lua 名字。
const secretGlobal = "__llmsproxy_secrets"
// pluginDirGlobal carries the plugin's OWN directory as ground truth.
//
// Why it must come from the kernel (live defect): the channels plugin decides
// where to keep its state by reading /etc/llmsproxy/config.yaml when
// LLMSPROXY_PLUGIN_DIR is unset. Tests load the real plugin but never set that
// variable, so they read AND WROTE the production store — one full
// `go test ./internal/lua` replaced the production account pool with the test's
// empty one (13 accounts → 0; the credentials stayed in the vault, so the
// symptom was "accounts vanished"). The kernel already knows the true directory
// (ps.dir), so handing it over removes the guess entirely: a plugin no longer
// has to infer its own location from a config file it might not own.
const pluginDirGlobal = "__llmsproxy_plugin_dir"
// registerPluginDirBridge installs the plugin's own directory as a plain string
// global. Deliberately a string, not a table: there is nothing to call, and a
// bare value cannot be shadowed by a later SetField on a shared table.
func registerPluginDirBridge(L *golua.State, dir string) {
L.PushString(dir)
L.SetGlobal(pluginDirGlobal)
}
// kernelGlobal 是内核动作面的 Lua 名字。
const kernelGlobal = "__llmsproxy_kernel"
// registerSecretBridge installs the credential vault onto a plugin's state.
//
// The plugin name is bound HERE, at boot, rather than read from the Lua state at
// call time. That is what makes "a plugin can only read its OWN credentials" a
// mechanism instead of a convention: a shard or any other holder of the compiled
// script cannot pass a different name.
func registerSecretBridge(L *golua.State, ps *Plugins, name string) {
L.NewTable()
L.PushGoClosure(luaSecretSet(ps, name))
L.SetField(-2, "set")
L.PushGoClosure(luaSecretGet(ps, name))
L.SetField(-2, "get")
L.PushGoClosure(luaSecretDelete(ps, name))
L.SetField(-2, "delete")
L.PushGoClosure(luaSecretKeys(ps, name))
L.SetField(-2, "keys")
L.SetGlobal(secretGlobal)
}
// luaSecretSet: set(key, value) -> (true, nil) | (nil, err)
func luaSecretSet(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
key := L.ToString(1)
val := L.ToString(2)
if err := ps.SetSecret(name, key, val); err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
L.PushBoolean(true)
L.PushNil()
return 2
}
}
// luaSecretGet: get(key) -> (value, nil) | (nil, err). A missing key yields
// (nil, nil) so a plugin can test `if tok == nil then login() end` — the "no
// credential stored yet" case is the common one for a fresh install, and making
// it an error would force every caller to string-match on a message.
func luaSecretGet(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
key := L.ToString(1)
v, ok, err := ps.GetSecret(name, key)
if err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
if !ok {
L.PushNil()
L.PushNil()
return 2
}
L.PushString(v)
L.PushNil()
return 2
}
}
// luaSecretDelete: delete(key) -> (true, nil) | (nil, err)
func luaSecretDelete(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
key := L.ToString(1)
if err := ps.DeleteSecret(name, key); err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
L.PushBoolean(true)
L.PushNil()
return 2
}
}
// luaSecretKeys: keys() -> (array of key names, nil). Names only — a plugin can
// render "which accounts are configured" without ever echoing token bytes.
func luaSecretKeys(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
keys, err := ps.SecretKeys(name)
if err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
L.NewTable()
for i, k := range keys {
L.PushString(k)
L.RawSeti(-2, i+1)
}
L.PushNil()
return 2
}
}
// registerKernelBridge installs the kernel action surface onto a plugin's state.
func registerKernelBridge(L *golua.State, ps *Plugins, name string) {
L.NewTable()
L.PushGoClosure(luaKernelActions(ps, name))
L.SetField(-2, "actions")
L.PushGoClosure(luaKernelCall(ps, name))
L.SetField(-2, "call")
L.SetGlobal(kernelGlobal)
}
// luaKernelActions: actions() -> (array of {name,title,danger,description,params,
// granted}, nil)
//
// It reports GRANTED alongside each action so a plugin can degrade gracefully
// (skip the part that needs a permission it does not have) instead of
// discovering it by hitting an error mid-operation.
func luaKernelActions(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
perm := ps.PluginKernelPermission(name)
L.NewTable()
for i, a := range KernelActions() {
L.NewTable()
L.PushString(a.Name)
L.SetField(-2, "name")
L.PushString(a.Title)
L.SetField(-2, "title")
L.PushString(a.Danger)
L.SetField(-2, "danger")
L.PushString(a.Description)
L.SetField(-2, "description")
L.PushBoolean(perm.allows(a))
L.SetField(-2, "granted")
L.NewTable()
for j, p := range a.Params {
L.PushString(p)
L.RawSeti(-2, j+1)
}
L.SetField(-2, "params")
L.RawSeti(-2, i+1)
}
L.PushNil()
return 2
}
}
// luaKernelCall: call(name, args) -> (result, nil) | (nil, err)
//
// One entry point rather than a function per action: the action set will change,
// and a table field per action would mean editing bootPluginState — the exact
// place that produced a cgo crash during earlier work.
func luaKernelCall(ps *Plugins, name string) golua.LuaGoFunction {
return func(L *golua.State) int {
action := L.ToString(1)
args := map[string]interface{}{}
if L.Type(2) == golua.LUA_TTABLE {
var raw interface{}
if err := luaToJSON(L, 2, &raw); err == nil {
if m, ok := raw.(map[string]interface{}); ok {
args = m
}
}
}
v, err := ps.callKernel(name, action, args)
if err != nil {
L.PushNil()
L.PushString(err.Error())
return 2
}
if v == nil {
L.PushNil()
} else {
pushGoValue(L, v)
}
L.PushNil()
return 2
}
}
// readPluginKernelDeclared reads `plugin.kernel`, the actions a plugin asks for.
//
// The shape is a list of names:
//
// plugin.kernel = { "status", "reset_health" }
//
// Unknown names are kept rather than dropped so the settings page can show a
// typo as "requested but not a real action" — silently discarding it would make
// a plugin's intent invisible at exactly the moment the operator is deciding
// what to grant.
func readPluginKernelDeclared(L *golua.State) []string {
raw, ok := pluginFieldValue(L, "kernel")
if !ok {
return nil
}
items, isList := raw.([]interface{})
if !isList {
if one, isTable := raw.(map[string]interface{}); isTable {
// A single string field or a set-style table; accept both spellings.
if v, ok := one["actions"].([]interface{}); ok {
items = v
} else {
return nil
}
} else {
return nil
}
}
out := make([]string, 0, len(items))
seen := map[string]bool{}
for _, it := range items {
name, ok := it.(string)
if !ok {
continue
}
name = strings.TrimSpace(name)
if name == "" || seen[name] {
continue
}
seen[name] = true
out = append(out, name)
}
sort.Strings(out)
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).
func luaTableArg(L *golua.State, idx int) (map[string]interface{}, error) {
if L.Type(idx) != golua.LUA_TTABLE {
return nil, fmt.Errorf("expected a table argument, got %s", normalizeString(L, idx))
}
var raw interface{}
if err := luaToJSON(L, idx, &raw); err != nil {
return nil, err
}
m, ok := raw.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("argument must be a keyed table")
}
return m, nil
}