diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 734f905..2381957 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,6 +63,9 @@ jobs: cache-dependency-path: web/package-lock.json - name: 构建便携包 run: node build.mjs + - name: 前端请求客户端测试 + working-directory: web + run: npm test - name: 上传便携包 uses: actions/upload-artifact@v4 with: diff --git "a/docs/\345\221\275\344\273\244\351\205\215\347\275\256\344\270\216\346\250\241\346\213\237.md" "b/docs/\345\221\275\344\273\244\351\205\215\347\275\256\344\270\216\346\250\241\346\213\237.md" new file mode 100644 index 0000000..7d75c28 --- /dev/null +++ "b/docs/\345\221\275\344\273\244\351\205\215\347\275\256\344\270\216\346\250\241\346\213\237.md" @@ -0,0 +1,95 @@ +# 文本命令配置与模拟解析 + +本批完成版本 1 文本命令配置校验、单条命令匹配、假设身份授权和预期回复生成。**没有接入真实消息触发或投递**,不执行 Minecraft 命令、PAPI、脚本或主机 shell。Minecraft 桥接继续暂缓,JS 独立进程运行时仍待实现。 + +## 配置 + +命令继续使用 `kind: "commands"` 的 Record;`detail` 是以下 JSON 的字符串。创建、更新和 `POST /api/v1/commands/validate` 使用同一校验逻辑。预检接收 `detail` 字符串,返回 `valid:true`、`persisted:false`、`runtimeAvailable:false`,不写入配置。 + +```json +{ + "schemaVersion": 1, + "prefix": "/", + "match": "regex", + "triggers": ["问候 (.+)", "hello (.+)"], + "permission": "all", + "identity": "", + "action": "text", + "reply": "{sender_name} 向 {arg1} 问好" +} +``` + +- `prefix` 可为空,最多 32 字节,不含空白或 NUL。消息必须从此前缀开始。 +- `match` 为 `exact` 或 `regex`,大小写敏感,不自动去除消息两端空白。精确模式必须完整等于关键词,不接受额外参数。 +- `triggers` 允许 1~16 条,不重复,每条最多 512 字节;精确关键词不含空白。正则使用 Go RE2 语法,对去除前缀后的整条消息匹配,最多 9 个捕获组;不支持反向引用或 lookaround。多个表达式按列表顺序取首个匹配。 +- `permission` 为 `all`、`admin`、`owner`、`bound` 或 `custom`。`custom` 必须设置 1~120 字节的 `identity`,其他权限须留空。 +- `action` 当前只能为 `text`;不接受未实现的执行动作。 +- `reply` 为 1~4000 字节,变量只允许 `{sender_name}`、`{user_id}` 和已有捕获组 `{arg1}` 至 `{arg9}`。如果某条别名表达式捕获组较少,缺少的参数展开为空。展开仅执行一次,用户输入中的花括号或命令样式文本按原文保留。预期回复超过 16000 字节时拒绝生成。 + +现有旧命令在启动时保留原始 JSON、enabled 和时间,不做自动迁移。可读取或删除;更新或模拟前必须显式转为版本 1。命令不建立群组、服务器或身份记录引用,不增加数据库迁移版本;旧配置错误由单条模拟和批量诊断报告。自定义身份在本批仅作模拟标识,尚无身份成员管理服务。 + +## 模拟接口 + +`POST /api/v1/commands/simulate` 使用现有管理会话鉴权。有两种互斥输入方式: + +1. 已保存命令:提供 `id`,后端读取该命令的 detail 和 enabled;不能同时提供草稿覆盖。 +2. 草稿:提供 `detail` 字符串和明确的 `enabled` 布尔值,不保存记录。 + +例如: + +```json +{ + "id": "命令记录 ID", + "message": "/问候 世界", + "context": { + "userId": "test-user", + "senderName": "测试用户", + "verified": false, + "role": "member", + "bound": false, + "identities": [] + } +} +``` + +`context` 是管理员提供的**假设输入**,不代表真实角色、绑定或权限。除全员权限以外,只有 `verified:true` 且 userId 非空才进一步判定:管理权限接受 admin/owner,群主权限只接受 owner,绑定权限检查 bound,自定义权限要求 identities 中存在精确身份标识。未知角色不获得管理权限。未来真实运行时必须从可信平台和绑定服务生成上下文,不能信任消息内声明。 + +响应始终声明 `simulated:true`、`executed:false`、`runtimeAvailable:false`,并返回 `matched`、`allowed`、捕获参数及允许时的 `reply`。`reason` 为: + +| reason | 含义 | +| --- | --- | +| `disabled` | 命令停用,不匹配或授权 | +| `not_matched` | 前缀或内容不匹配 | +| `permission_denied` | 已匹配,假设身份无权限,不返回回复 | +| `reply_too_long` | 展开超限,不返回回复 | +| `preview_ready` | 已生成预期回复,未实际发送 | + +消息最多 8192 字节,userId 最多 128 字节,senderName 最多 512 字节,身份列表最多 32 项。配置/输入无效返回字段错误 400,命令不存在或 ID 类型不匹配返回 404,未登录返回 401。 + +模拟过程不修改配置、冷却或执行状态,不调用适配器/Bridge,不记录测试消息和预期回复正文。HTTP 访问元数据仍遵循现有日志策略。当前只评估一条命令,未检查命令之间的匹配冲突、平台/群/服务器范围、冷却或速率限制。 + +## 管理台和验证边界 + +命令编辑窗口提供前缀、匹配方式、关键词、权限和回复表单,以及草稿模拟区。旧版 JSON 保留原文,只有明确点击替换草稿才切换为版本 1 示例;取消不会写入。模拟结果在修改配置或测试身份后失效,过期请求结果不覆盖新草稿。 + +本地自动化测试覆盖五种权限允许/拒绝、未知或未验证角色拒绝、完整匹配、捕获与单次模板展开、超限拒绝、停用、无效动作、保存失败不改数据、旧配置重启保留、HTTP 鉴权、只读模拟与正文不进日志。浏览器人工交互、真实账号触发/收发均未验收;测试和前端构建不代表命令运行时已完成。 + +## 多命令冲突诊断 + +`POST /api/v1/commands/diagnose` 接收 `message` 和同格式的假设 `context`,诊断所有已保存且启用的命令。单个无效或旧版配置作为该条 `error` 返回,不阻止其他命令;停用命令仅计数跳过。返回每条结果、matched/allowed/invalid/disabled 计数及 conflict。匹配超过一条即 conflict=true,包括被权限拒绝的匹配,避免以测试身份掩盖关键词重叠。排序按记录 ID 固定,不代表执行优先级;不选择赢家,不发送消息。 + +管理台命令页提供诊断区,修改测试消息、身份或命令列表后清除旧结果。最多诊断 500 条记录,超过时返回 400;请求取消时停止后续评估。身份标识单项最多 120 字节。单命令草稿模拟仍保留,诊断不检查尚未实现的平台范围、冷却和真实绑定。自动测试覆盖空列表、鉴权、冲突、权限、旧配置隔离、停用、输入上限及无写入;浏览器人工验收待完成。 + +## Draft PR 人工验收清单 + +用户明确允许先创建 Draft PR;以下人工操作尚未执行,不应据此合并。 + +1. 启动测试实例,登录后在命令页新建默认文本命令;输入 `/help`,应预览问候,未发出平台消息。 +2. 新建第二条同关键词命令,在命令页批量诊断;应显示冲突。将第二条停用再诊断,应无冲突且跳过停用数增加。 +3. 将权限改为管理员,未验证身份时拒绝;勾选已验证并选择管理员时允许,实际执行仍为否。 +4. 正则设置 `echo (.+)`,回复 `{arg1}`,输入 `/echo {user_id}`;预期回复保留 `{user_id}` 原文。 +5. 在测试数据库准备旧版命令,编辑时应保留完整原 JSON;取消不改数据,诊断应仅报告该条配置无效,其余命令照常诊断。 +6. 模拟请求在进行中时更改输入,旧结果不应覆盖新输入。退出登录后再次调用接口应返回 401。 + + +本地验证:Go 全量测试、go vet、前端 7 项客户端测试、TypeScript 检查及 Vite 打包通过。CI 加入前端客户端测试;外部数据库和浏览器人工测试尚未完成。 diff --git "a/docs/\345\274\200\345\217\221\350\257\264\346\230\216.md" "b/docs/\345\274\200\345\217\221\350\257\264\346\230\216.md" index 643753b..c3859da 100644 --- "a/docs/\345\274\200\345\217\221\350\257\264\346\230\216.md" +++ "b/docs/\345\274\200\345\217\221\350\257\264\346\230\216.md" @@ -127,3 +127,7 @@ npm run build 外部数据库测试使用 `EASYBOT_TEST_DATABASE_DSN` 指定专用空测试库,再执行 `go test -count=1 -vet=off ./internal/store`。测试会创建用户和记录,不得指向生产数据库;未设置该变量时,外部数据库测试会跳过。当前 CI 验证目标为 MySQL 8.4.11、MySQL 9.6.0 和 PostgreSQL 18.6,具体版本以对应集成测试通过为准。 贡献要求见 [贡献规范](../CONTRIBUTING.md)。建议使用中文说明 PR 和提交;中文 CI 仅提醒,不阻断合并。AI 辅助贡献须披露工具及用途,并由贡献者人工审阅和验证,相关要求不纳入自动检测。 + +### 文本命令配置与诊断 + +命令页支持版本 1 文本命令表单、单条草稿模拟和多命令冲突诊断。接口为 `/api/v1/commands/validate`、`/simulate`、`/diagnose`,共用现有管理会话。旧命令 JSON 保留,更新前须显式确认版本。当前不接入真实消息触发、绑定授权、冷却或回复投递。字段与人工验收步骤见 [命令配置与模拟](命令配置与模拟.md)。在 `web/` 运行 `npm test` 验证请求客户端。 diff --git a/internal/api/command_diagnostics_test.go b/internal/api/command_diagnostics_test.go new file mode 100644 index 0000000..cb87183 --- /dev/null +++ b/internal/api/command_diagnostics_test.go @@ -0,0 +1,102 @@ +package api + +import ( + "context" + "database/sql" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "easybot/internal/runtime" + "easybot/internal/store" +) + +func TestCommandDiagnostics(t *testing.T) { + path := t.TempDir() + "/diagnose.db" + db, err := store.Open(path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + createTestSession(t, db) + handler := New(db, slog.New(slog.NewTextHandler(io.Discard, nil)), runtime.NewLogs(100, nil)) + invoke := func(body string, auth bool) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/api/v1/commands/diagnose", strings.NewReader(body)) + if auth { + req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "test-session"}) + } + res := httptest.NewRecorder() + handler.ServeHTTP(res, req) + return res + } + if res := invoke(`{}`, false); res.Code != 401 { + t.Fatal("unprotected diagnostic") + } + request := `{"message":"/help","context":{"userId":"u","role":"admin","verified":false}}` + if res := invoke(request, true); res.Code != 200 || !strings.Contains(res.Body.String(), `"items":[]`) { + t.Fatal("empty diagnostic", res.Body.String()) + } + ctx := context.Background() + for _, permission := range []string{"all", "admin", "owner"} { + config := store.DefaultCommandConfig() + config.Permission = permission + raw, _ := json.Marshal(config) + _, err := db.Save(ctx, store.Record{Kind: "commands", Name: permission, Detail: string(raw), Enabled: true}) + if err != nil { + t.Fatal(err) + } + } + config, _ := json.Marshal(store.DefaultCommandConfig()) + for _, name := range []string{"disabled", "legacy"} { + item, err := db.Save(ctx, store.Record{Kind: "commands", Name: name, Detail: string(config), Enabled: name != "disabled"}) + if err != nil { + t.Fatal(err) + } + if name == "legacy" { + // An existing unversioned configuration must be isolated as an error. + item.Detail = "{}" + // Create the legacy fixture via the same pre-contract DB fixture helper below. + fixture, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + _, err = fixture.Exec(`UPDATE records SET detail=? WHERE id=?`, item.Detail, item.ID) + fixture.Close() + if err != nil { + t.Fatal(err) + } + } + } + before, _ := db.List(ctx, "commands") + res := invoke(request, true) + var report struct { + Matched, Allowed, Invalid, Disabled int + Conflict, Executed, Simulated bool + Items []struct{ ID, Error string } + } + if err := json.Unmarshal(res.Body.Bytes(), &report); err != nil || res.Code != 200 || report.Matched != 3 || report.Allowed != 1 || report.Invalid != 1 || report.Disabled != 1 || !report.Conflict || report.Executed || !report.Simulated { + t.Fatal(res.Code, res.Body.String(), err) + } + for i := 1; i < len(report.Items); i++ { + if report.Items[i-1].ID >= report.Items[i].ID { + t.Fatal("unstable ordering") + } + } + after, _ := db.List(ctx, "commands") + a, _ := json.Marshal(before) + b, _ := json.Marshal(after) + if string(a) != string(b) { + t.Fatal("diagnostic changed records") + } + if res := invoke(`{"message":"/unknown"}`, true); res.Code != 200 || !strings.Contains(res.Body.String(), `"conflict":false`) { + t.Fatal("non-match conflict") + } + oversized, _ := json.Marshal(map[string]string{"message": strings.Repeat("x", 8193)}) + if res := invoke(string(oversized), true); res.Code != 400 { + t.Fatal("oversized message accepted") + } +} diff --git a/internal/api/commands.go b/internal/api/commands.go new file mode 100644 index 0000000..ec6da2f --- /dev/null +++ b/internal/api/commands.go @@ -0,0 +1,121 @@ +package api + +import ( + "net/http" + "sort" + + "easybot/internal/command" + "easybot/internal/store" +) + +// diagnoseCommands evaluates saved commands independently. It never chooses a +// winner: conflicting matches need an explicit future runtime policy. +func (s *server) diagnoseCommands(w http.ResponseWriter, r *http.Request) { + var request struct { + Message string `json:"message"` + Context command.Context `json:"context"` + } + if !decode(w, r, &request) { + return + } + if err := command.ValidateInput(request.Message, request.Context); err != nil { + writeStoreError(w, err) + return + } + items, err := s.store.List(r.Context(), "commands") + if err != nil { + writeStoreError(w, err) + return + } + if len(items) > 500 { + writeStoreError(w, &store.ValidationError{Field: "commands", Message: "诊断最多支持 500 条命令,请先精简配置"}) + return + } + sort.Slice(items, func(i, j int) bool { return items[i].ID < items[j].ID }) + type evaluation struct { + ID string `json:"id"` + Name string `json:"name"` + Result *command.Result `json:"result,omitempty"` + Error string `json:"error,omitempty"` + } + results := make([]evaluation, 0, len(items)) + matched, allowed, invalid, disabled := 0, 0, 0, 0 + for _, item := range items { + if err := r.Context().Err(); err != nil { + return + } + if !item.Enabled { + disabled++ + continue + } + result, err := command.Simulate(item.Detail, true, request.Message, request.Context) + entry := evaluation{ID: item.ID, Name: item.Name} + if err != nil { + entry.Error = err.Error() + invalid++ + } else { + entry.Result = &result + if result.Matched { + matched++ + } + if result.Allowed { + allowed++ + } + } + results = append(results, entry) + } + writeJSON(w, http.StatusOK, map[string]any{"simulated": true, "executed": false, "runtimeAvailable": false, "items": results, "matched": matched, "allowed": allowed, "invalid": invalid, "disabled": disabled, "conflict": matched > 1}) +} + +func (s *server) simulateCommand(w http.ResponseWriter, r *http.Request) { + var request struct { + // Use an ID for persisted configuration, or detail+enabled for a draft. + ID string `json:"id"` + Detail *string `json:"detail"` + Enabled *bool `json:"enabled"` + Message string `json:"message"` + Context command.Context `json:"context"` + } + if !decode(w, r, &request) { + return + } + detail, enabled := "", false + if request.ID != "" { + if request.Detail != nil || request.Enabled != nil { + writeStoreError(w, &store.ValidationError{Field: "id", Message: "模拟已保存命令时不能同时覆盖草稿配置"}) + return + } + item, err := s.store.Get(r.Context(), "commands", request.ID) + if err != nil { + writeStoreError(w, err) + return + } + detail, enabled = item.Detail, item.Enabled + } else { + if request.Detail == nil || request.Enabled == nil { + writeStoreError(w, &store.ValidationError{Field: "detail", Message: "模拟草稿必须提供 detail 和 enabled"}) + return + } + detail, enabled = *request.Detail, *request.Enabled + } + result, err := command.Simulate(detail, enabled, request.Message, request.Context) + if err != nil { + writeStoreError(w, err) + return + } + writeJSON(w, http.StatusOK, result) +} + +func (s *server) validateCommand(w http.ResponseWriter, r *http.Request) { + var request struct { + Detail string `json:"detail"` + } + if !decode(w, r, &request) { + return + } + if _, err := store.ValidateCommandConfig(request.Detail); err != nil { + writeStoreError(w, err) + return + } + writeJSON(w, http.StatusOK, map[string]any{"valid": true, "persisted": false, "runtimeAvailable": false}) +} diff --git a/internal/api/commands_test.go b/internal/api/commands_test.go new file mode 100644 index 0000000..fa42213 --- /dev/null +++ b/internal/api/commands_test.go @@ -0,0 +1,103 @@ +package api + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "easybot/internal/command" + "easybot/internal/runtime" + "easybot/internal/store" +) + +func TestCommandSimulationHTTP(t *testing.T) { + db, err := store.Open(t.TempDir() + "/commands.db") + if err != nil { + t.Fatal(err) + } + defer db.Close() + createTestSession(t, db) + logs := runtime.NewLogs(100, nil) + handler := New(db, slog.New(slog.NewTextHandler(io.Discard, nil)), logs) + invoke := func(path string, body any, auth bool) *httptest.ResponseRecorder { + raw, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest("POST", path, strings.NewReader(string(raw))) + if auth { + req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "test-session"}) + } + res := httptest.NewRecorder() + handler.ServeHTTP(res, req) + return res + } + c := store.DefaultCommandConfig() + c.Permission = "admin" + c.Reply = "private preview {sender_name}" + raw, _ := json.Marshal(c) + item := store.Record{Kind: "commands", Name: "test", Detail: string(raw), Enabled: true} + if res := invoke("/api/v1/commands/simulate", map[string]any{}, false); res.Code != 401 { + t.Fatal("unprotected simulation", res.Code) + } + res := invoke("/api/v1/records", item, true) + if res.Code != 201 { + t.Fatal(res.Code, res.Body.String()) + } + if err := json.Unmarshal(res.Body.Bytes(), &item); err != nil { + t.Fatal(err) + } + request := map[string]any{"id": item.ID, "message": "/help", "context": map[string]any{"userId": "u", "senderName": "secret-body", "verified": false, "role": "admin"}} + res = invoke("/api/v1/commands/simulate", request, true) + var result command.Result + if err := json.Unmarshal(res.Body.Bytes(), &result); err != nil || res.Code != 200 || !result.Matched || result.Allowed || result.Executed || result.Reply != "" { + t.Fatal(res.Code, result, err) + } + request["context"] = map[string]any{"userId": "u", "senderName": "secret-body", "verified": true, "role": "owner"} + res = invoke("/api/v1/commands/simulate", request, true) + if err := json.Unmarshal(res.Body.Bytes(), &result); err != nil || res.Code != 200 || !result.Allowed || result.Executed || !result.Simulated || result.RuntimeAvailable || result.Reply != "private preview secret-body" { + t.Fatal(res.Code, result, err) + } + request["detail"] = string(raw) + if res := invoke("/api/v1/commands/simulate", request, true); res.Code != 400 { + t.Fatal("ID and draft override accepted") + } + delete(request, "id") + request["enabled"] = false + res = invoke("/api/v1/commands/simulate", request, true) + if !strings.Contains(res.Body.String(), `"reason":"disabled"`) { + t.Fatal(res.Body.String()) + } + delete(request, "enabled") + if res := invoke("/api/v1/commands/simulate", request, true); res.Code != 400 { + t.Fatal("missing enabled accepted") + } + if res := invoke("/api/v1/commands/simulate", map[string]any{"id": "missing"}, true); res.Code != 404 { + t.Fatal("missing command did not return 404", res.Code) + } + request["enabled"] = true + request["detail"] = `{"schemaVersion":1,"action":"shell"}` + if res := invoke("/api/v1/commands/simulate", request, true); res.Code != 400 { + t.Fatal("unsupported action accepted") + } + if res := invoke("/api/v1/commands/validate", item, true); res.Code != 200 { + t.Fatal("command preflight failed", res.Body.String()) + } + stored, err := db.Get(context.Background(), "commands", item.ID) + if err != nil || stored.Detail != item.Detail || stored.Enabled != item.Enabled || !stored.UpdatedAt.Equal(item.UpdatedAt) { + t.Fatal("simulation mutated persisted configuration", stored, err) + } + items, err := db.List(context.Background(), "commands") + if err != nil || len(items) != 1 { + t.Fatal("draft simulation persisted a record") + } + entries, _ := json.Marshal(logs.Recent(100)) + if strings.Contains(string(entries), "secret-body") || strings.Contains(string(entries), "private preview") { + t.Fatal("simulation leaked message/reply into logs") + } +} diff --git a/internal/api/response.go b/internal/api/response.go index 06b9d70..3cedaa5 100644 --- a/internal/api/response.go +++ b/internal/api/response.go @@ -2,6 +2,7 @@ package api import ( "database/sql" + "easybot/internal/store" "encoding/json" "errors" "net/http" @@ -18,6 +19,11 @@ func decode(w http.ResponseWriter, r *http.Request, target any) bool { } func writeStoreError(w http.ResponseWriter, err error) { + var validation *store.ValidationError + if errors.As(err, &validation) { + writeJSON(w, http.StatusBadRequest, map[string]string{"code": "validation_error", "field": validation.Field, "message": validation.Message}) + return + } if errors.Is(err, sql.ErrNoRows) { writeJSON(w, http.StatusNotFound, map[string]string{"message": "record not found"}) return diff --git a/internal/api/routes.go b/internal/api/routes.go index 5ad7468..017966e 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -6,6 +6,7 @@ func (s *server) registerRoutes(mux *http.ServeMux) { s.registerSystemRoutes(mux) s.registerAuthRoutes(mux) s.registerRecordRoutes(mux) + s.registerCommandRoutes(mux) s.registerAdapterRoutes(mux) s.registerLogRoutes(mux) s.registerBridgeRoutes(mux) @@ -62,3 +63,9 @@ func (s *server) registerBridgeRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/v1/bridge/{id}/send", s.bridgeSend) mux.HandleFunc("POST /api/v1/servers/{id}/token", s.rotateServerToken) } + +func (s *server) registerCommandRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/v1/commands/validate", s.validateCommand) + mux.HandleFunc("POST /api/v1/commands/simulate", s.simulateCommand) + mux.HandleFunc("POST /api/v1/commands/diagnose", s.diagnoseCommands) +} diff --git a/internal/command/simulate.go b/internal/command/simulate.go new file mode 100644 index 0000000..d5c5182 --- /dev/null +++ b/internal/command/simulate.go @@ -0,0 +1,126 @@ +// Package command implements side-effect-free command evaluation. +package command + +import ( + "regexp" + "strconv" + "strings" + + "easybot/internal/store" +) + +// Context is hypothetical in simulation. A future runtime must derive it from +// trusted platform/binding services, never directly from a message payload. +type Context struct { + UserID string `json:"userId"` + SenderName string `json:"senderName"` + Verified bool `json:"verified"` + Role string `json:"role"` + Bound bool `json:"bound"` + Identities []string `json:"identities"` +} +type Result struct { + Simulated bool `json:"simulated"` + Executed bool `json:"executed"` + RuntimeAvailable bool `json:"runtimeAvailable"` + Matched bool `json:"matched"` + Allowed bool `json:"allowed"` + Reason string `json:"reason"` + Trigger string `json:"trigger,omitempty"` + Arguments []string `json:"arguments"` + Reply string `json:"reply,omitempty"` +} + +func ValidateInput(message string, ctx Context) error { + if len(message) > 8192 || len(ctx.UserID) > 128 || len(ctx.SenderName) > 512 || len(ctx.Identities) > 32 { + return &store.ValidationError{Field: "context", Message: "消息或模拟身份超过长度上限"} + } + for _, identity := range ctx.Identities { + if len(identity) > 120 { + return &store.ValidationError{Field: "context.identities", Message: "模拟身份标识最多 120 字节"} + } + } + return nil +} + +// Simulate validates configuration even for disabled commands, then evaluates +// one command only. No database, network, process or cooldown state is changed. +func Simulate(raw string, enabled bool, message string, ctx Context) (Result, error) { + result := Result{Simulated: true, Arguments: []string{}} + config, err := store.ValidateCommandConfig(raw) + if err != nil { + return result, err + } + if err := ValidateInput(message, ctx); err != nil { + return result, err + } + if !enabled { + result.Reason = "disabled" + return result, nil + } + result.Reason = "not_matched" + if !strings.HasPrefix(message, config.Prefix) { + return result, nil + } + body := strings.TrimPrefix(message, config.Prefix) + for _, trigger := range config.Triggers { + if config.Match == "exact" { + if body != trigger { + continue + } + } else { + re := regexp.MustCompile("\\A(?:" + trigger + ")\\z") // validated above; bounded RE2 patterns + parts := re.FindStringSubmatch(body) + if parts == nil { + continue + } + result.Arguments = parts[1:] + } + result.Matched = true + result.Trigger = trigger + break + } + if !result.Matched { + return result, nil + } + result.Allowed = config.Permission == "all" + if !result.Allowed && ctx.Verified && ctx.UserID != "" { + switch config.Permission { + case "admin": + result.Allowed = ctx.Role == "admin" || ctx.Role == "owner" + case "owner": + result.Allowed = ctx.Role == "owner" + case "bound": + result.Allowed = ctx.Bound + case "custom": + for _, identity := range ctx.Identities { + if identity == config.Identity { + result.Allowed = true + break + } + } + } + } + if !result.Allowed { + result.Reason = "permission_denied" + return result, nil + } + values := []string{"{sender_name}", ctx.SenderName, "{user_id}", ctx.UserID} + for i := 1; i <= 9; i++ { + value := "" + if i <= len(result.Arguments) { + value = result.Arguments[i-1] + } + values = append(values, "{arg"+strconv.Itoa(i)+"}", value) + } + // One pass prevents user input containing placeholders from being re-expanded. + result.Reply = strings.NewReplacer(values...).Replace(config.Reply) + if len(result.Reply) > 16000 { + result.Allowed = false + result.Reply = "" + result.Reason = "reply_too_long" + return result, nil + } + result.Reason = "preview_ready" + return result, nil +} diff --git a/internal/command/simulate_test.go b/internal/command/simulate_test.go new file mode 100644 index 0000000..cb68415 --- /dev/null +++ b/internal/command/simulate_test.go @@ -0,0 +1,96 @@ +package command + +import ( + "encoding/json" + "strings" + "testing" + + "easybot/internal/store" +) + +func raw(t *testing.T, c store.CommandConfig) string { + t.Helper() + v, err := json.Marshal(c) + if err != nil { + t.Fatal(err) + } + return string(v) +} + +func TestPermissionMatrix(t *testing.T) { + for _, test := range []struct { + permission string + ctx Context + allowed bool + }{ + {"all", Context{}, true}, + {"admin", Context{Verified: true, UserID: "u", Role: "admin"}, true}, + {"admin", Context{Verified: true, UserID: "u", Role: "owner"}, true}, + {"admin", Context{Verified: true, UserID: "u", Role: "member"}, false}, + {"admin", Context{Verified: false, UserID: "u", Role: "admin"}, false}, + {"admin", Context{Verified: true, UserID: "u", Role: "unknown"}, false}, + {"owner", Context{Verified: true, UserID: "u", Role: "owner"}, true}, + {"owner", Context{Verified: true, UserID: "u", Role: "admin"}, false}, + {"bound", Context{Verified: true, UserID: "u", Bound: true}, true}, + {"bound", Context{Verified: true, UserID: "u"}, false}, + {"bound", Context{Bound: true}, false}, + {"custom", Context{Verified: true, UserID: "u", Identities: []string{"operator"}}, true}, + {"custom", Context{Verified: true, UserID: "u", Identities: []string{"other"}}, false}, + {"custom", Context{Verified: false, UserID: "u", Identities: []string{"operator"}}, false}, + {"admin", Context{Verified: true, Role: "admin"}, false}, + } { + t.Run(test.permission+"/"+test.ctx.Role, func(t *testing.T) { + c := store.DefaultCommandConfig() + c.Permission = test.permission + if c.Permission == "custom" { + c.Identity = "operator" + } + result, err := Simulate(raw(t, c), true, "/help", test.ctx) + if err != nil || !result.Matched || result.Allowed != test.allowed || result.Executed || !result.Simulated || result.RuntimeAvailable { + t.Fatalf("result=%+v err=%v", result, err) + } + if !test.allowed && result.Reply != "" { + t.Fatal("denied evaluation produced reply") + } + }) + } +} + +func TestMatchingArgumentsAndLiteralExpansion(t *testing.T) { + c := store.DefaultCommandConfig() + c.Match = "regex" + c.Triggers = []string{`echo (.+)`, `say (.+)`} + c.Reply = "{sender_name}: {arg1} ({user_id})" + ctx := Context{SenderName: "{arg1}", UserID: "u"} + result, err := Simulate(raw(t, c), true, "/say $(whoami) {user_id}", ctx) + if err != nil || result.Trigger != `say (.+)` || len(result.Arguments) != 1 || result.Reply != "{arg1}: $(whoami) {user_id} (u)" { + t.Fatalf("%+v %v", result, err) + } + for _, message := range []string{"say hi", "/xxsay hi", "/say", "/say hi\nextra"} { + result, err := Simulate(raw(t, c), true, message, ctx) + if err != nil || result.Matched || result.Reply != "" { + t.Fatalf("partial match %q: %+v %v", message, result, err) + } + } + c = store.DefaultCommandConfig() + for _, message := range []string{"help", "/HELP", "/help extra", " /help", "/help\n"} { + result, _ := Simulate(raw(t, c), true, message, ctx) + if result.Matched { + t.Fatalf("unexpected exact match: %q", message) + } + } + result, _ = Simulate(raw(t, c), false, "/help", ctx) + if result.Matched || result.Allowed || result.Reason != "disabled" { + t.Fatal(result) + } + if _, err := Simulate(raw(t, c), true, strings.Repeat("a", 8193), ctx); err == nil { + t.Fatal("oversized input accepted") + } + c.Match = "regex" + c.Triggers = []string{`(.+)`} + c.Reply = strings.Repeat("{arg1}", 10) + result, err = Simulate(raw(t, c), true, "/"+strings.Repeat("a", 2000), ctx) + if err != nil || result.Allowed || result.Reply != "" || result.Reason != "reply_too_long" { + t.Fatal(result, err) + } +} diff --git a/internal/store/command_config.go b/internal/store/command_config.go new file mode 100644 index 0000000..04204b7 --- /dev/null +++ b/internal/store/command_config.go @@ -0,0 +1,128 @@ +package store + +import ( + "bytes" + "encoding/json" + "io" + "regexp" + "strconv" + "strings" + "unicode" +) + +type ValidationError struct { + Field string `json:"field"` + Message string `json:"message"` +} + +func (e *ValidationError) Error() string { return e.Message } +func invalid(field, message string) error { return &ValidationError{Field: field, Message: message} } + +var routeVariable = regexp.MustCompile(`\{([^{}]+)\}`) + +func decodeContract(raw string, target any) error { + if len(raw) > 64<<10 { + return invalid("detail", "配置不能超过 64 KiB") + } + decoder := json.NewDecoder(bytes.NewBufferString(raw)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + return invalid("detail", "配置字段或 JSON 格式无效") + } + if decoder.Decode(new(any)) != io.EOF { + return invalid("detail", "配置必须为单个 JSON 对象") + } + return nil +} + +// CommandConfig describes text-only commands. It does not grant execution rights. +type CommandConfig struct { + SchemaVersion int `json:"schemaVersion"` + Prefix string `json:"prefix"` + Match string `json:"match"` + Triggers []string `json:"triggers"` + Permission string `json:"permission"` + Identity string `json:"identity"` + Action string `json:"action"` + Reply string `json:"reply"` +} + +func DefaultCommandConfig() CommandConfig { + return CommandConfig{SchemaVersion: 1, Prefix: "/", Match: "exact", Triggers: []string{"帮助", "help"}, Permission: "all", Action: "text", Reply: "你好,{sender_name}"} +} + +func ValidateCommandConfig(raw string) (CommandConfig, error) { + var config CommandConfig + if err := decodeContract(raw, &config); err != nil { + return config, err + } + if config.SchemaVersion != 1 { + return config, invalid("schemaVersion", "命令配置须明确使用 schemaVersion 1;旧配置请核对后更新") + } + if len(config.Prefix) > 32 || strings.IndexFunc(config.Prefix, unicode.IsSpace) >= 0 || strings.ContainsRune(config.Prefix, '\x00') { + return config, invalid("prefix", "前缀最多 32 字节且不能包含空白或 NUL") + } + if config.Match != "exact" && config.Match != "regex" { + return config, invalid("match", "匹配方式仅支持 exact 或 regex") + } + if len(config.Triggers) < 1 || len(config.Triggers) > 16 { + return config, invalid("triggers", "命令需要 1 到 16 个关键词或正则表达式") + } + seen := map[string]bool{} + maxCaptures := 0 + for _, trigger := range config.Triggers { + if strings.TrimSpace(trigger) == "" || len(trigger) > 512 || seen[trigger] || strings.ContainsRune(trigger, '\x00') { + return config, invalid("triggers", "关键词或表达式不能为空、重复或超过 512 字节") + } + seen[trigger] = true + if config.Match == "exact" { + if strings.IndexFunc(trigger, unicode.IsSpace) >= 0 { + return config, invalid("triggers", "精确关键词不能包含空白;参数请使用正则捕获组") + } + } else { + // Validate the expression independently so it cannot close our wrapper + // and move an alternative outside the full-message anchors. + if _, err := regexp.Compile(trigger); err != nil { + return config, invalid("triggers", "正则表达式无效;使用 Go RE2 语法") + } + re, err := regexp.Compile("\\A(?:" + trigger + ")\\z") + if err != nil || re.NumSubexp() > 9 { + return config, invalid("triggers", "正则表达式无效或捕获组超过 9 个;使用 Go RE2 语法") + } + if re.NumSubexp() > maxCaptures { + maxCaptures = re.NumSubexp() + } + } + } + switch config.Permission { + case "all", "admin", "owner", "bound": + if config.Identity != "" { + return config, invalid("identity", "非自定义身份权限不能设置 identity") + } + case "custom": + if strings.TrimSpace(config.Identity) != config.Identity || config.Identity == "" || len(config.Identity) > 120 { + return config, invalid("identity", "自定义权限需要 1 到 120 字节的身份标识") + } + default: + return config, invalid("permission", "权限必须为 all、admin、owner、bound 或 custom") + } + if config.Action != "text" { + return config, invalid("action", "当前命令合同只支持 text 回复,服务器命令及 PAPI 尚未开放") + } + if strings.TrimSpace(config.Reply) == "" || len(config.Reply) > 4000 { + return config, invalid("reply", "回复必须为 1 到 4000 字节") + } + for _, match := range routeVariable.FindAllStringSubmatch(config.Reply, -1) { + if match[1] == "sender_name" || match[1] == "user_id" { + continue + } + index, err := strconv.Atoi(strings.TrimPrefix(match[1], "arg")) + if !strings.HasPrefix(match[1], "arg") || err != nil || index < 1 || index > maxCaptures || match[1] != "arg"+strconv.Itoa(index) { + return config, invalid("reply", "回复变量仅允许 sender_name、user_id 和已定义捕获组 arg1 至 arg9") + } + } + if strings.ContainsAny(routeVariable.ReplaceAllString(config.Reply, ""), "{}") { + return config, invalid("reply", "回复变量括号不完整") + } + return config, nil +} diff --git a/internal/store/command_config_test.go b/internal/store/command_config_test.go new file mode 100644 index 0000000..a13d786 --- /dev/null +++ b/internal/store/command_config_test.go @@ -0,0 +1,104 @@ +package store + +import ( + "context" + "encoding/json" + "strings" + "testing" +) + +func contractJSON(t *testing.T, value any) string { + t.Helper() + raw, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return string(raw) +} + +func TestCommandConfigValidation(t *testing.T) { + for _, change := range []func(*CommandConfig){ + func(c *CommandConfig) { c.SchemaVersion = 0 }, + func(c *CommandConfig) { c.Action = "shell" }, + func(c *CommandConfig) { c.Action = "papi" }, + func(c *CommandConfig) { c.Prefix = "bad prefix" }, + func(c *CommandConfig) { c.Triggers = []string{} }, + func(c *CommandConfig) { c.Triggers = []string{"help", "help"} }, + func(c *CommandConfig) { c.Triggers = []string{"help extra"} }, + func(c *CommandConfig) { c.Match = "regex"; c.Triggers = []string{"("} }, + func(c *CommandConfig) { c.Match = "regex"; c.Triggers = []string{`(a)\1`} }, + func(c *CommandConfig) { c.Match = "regex"; c.Triggers = []string{`a)\z|(?:b`} }, + func(c *CommandConfig) { c.Match = "regex"; c.Triggers = []string{strings.Repeat("(a)", 10)} }, + func(c *CommandConfig) { c.Permission = "superuser" }, + func(c *CommandConfig) { c.Permission = "custom" }, + func(c *CommandConfig) { c.Identity = "unexpected" }, + func(c *CommandConfig) { c.Reply = "{arg1}" }, + func(c *CommandConfig) { c.Reply = "{sender_name" }, + func(c *CommandConfig) { c.Reply = "{unknown}" }, + func(c *CommandConfig) { c.Reply = "" }, + } { + c := DefaultCommandConfig() + change(&c) + if _, err := ValidateCommandConfig(contractJSON(t, c)); err == nil { + t.Fatalf("invalid config accepted: %+v", c) + } + } + valid := contractJSON(t, DefaultCommandConfig()) + for _, value := range []string{"null", valid + " {}", strings.TrimSuffix(valid, "}") + `,"unknown":true}`} { + if _, err := ValidateCommandConfig(value); err == nil { + t.Fatal("invalid JSON accepted") + } + } +} + +func TestCommandSaveValidationAndLegacyPreservation(t *testing.T) { + path := t.TempDir() + "/commands.db" + db, err := Open(path) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + item, err := db.Save(ctx, Record{Kind: "commands", Name: "command", Detail: contractJSON(t, DefaultCommandConfig()), Enabled: true}) + if err != nil { + t.Fatal(err) + } + old := item.Detail + item.Detail = `{"schemaVersion":1,"action":"shell"}` + if _, err := db.Save(ctx, item); err == nil { + t.Fatal("invalid config saved") + } + stored, err := db.Get(ctx, "commands", item.ID) + if err != nil || stored.Detail != old { + t.Fatal("failed save changed data") + } + // Emulate an existing pre-contract command without rewriting its source JSON. + legacy := `{"mode":"text","custom":"preserve me"}` + if _, err := db.db.Exec(db.query(`UPDATE records SET detail=? WHERE id=?`), legacy, item.ID); err != nil { + t.Fatal(err) + } + db.Close() + db, err = Open(path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + stored, err = db.Get(ctx, "commands", item.ID) + if err != nil || stored.Detail != legacy || !stored.Enabled { + t.Fatal("startup changed legacy command") + } + if err := validateCommandRecord(stored); err == nil { + t.Fatal("legacy command passed versioned validation") + } + stored.Detail = old + if err := validateCommandRecord(stored); err != nil { + t.Fatal(err) + } + if _, err := db.Save(ctx, stored); err != nil { + t.Fatal(err) + } +} + +func validateCommandRecord(item Record) error { + _, err := ValidateCommandConfig(item.Detail) + return err +} diff --git a/internal/store/records.go b/internal/store/records.go index e88e3f3..8267615 100644 --- a/internal/store/records.go +++ b/internal/store/records.go @@ -58,6 +58,11 @@ func (s *Store) List(ctx context.Context, kind string) ([]Record, error) { } func (s *Store) Save(ctx context.Context, item Record) (Record, error) { + if item.Kind == "commands" { + if _, err := ValidateCommandConfig(item.Detail); err != nil { + return item, err + } + } if !Kinds[item.Kind] { return item, errors.New("unsupported record kind") } diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 49d08b4..85f44b6 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -20,7 +20,7 @@ func TestRecordLifecycle(t *testing.T) { defer db.Close() ctx := context.Background() - created, err := db.Save(ctx, Record{Kind: "commands", Name: "!status", Detail: `{"mode":"text"}`, Enabled: true}) + created, err := db.Save(ctx, Record{Kind: "commands", Name: "!status", Detail: contractJSON(t, DefaultCommandConfig()), Enabled: true}) if err != nil { t.Fatal(err) } diff --git a/web/package.json b/web/package.json index abc89e2..35327b3 100644 --- a/web/package.json +++ b/web/package.json @@ -4,6 +4,7 @@ "version": "0.0.0", "type": "module", "scripts": { + "test": "node --test tests/api.test.mjs", "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" diff --git a/web/src/App.vue b/web/src/App.vue index 680fa31..14cc549 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -1,9 +1,11 @@ + +