From f60ed187a2269b68ae831ebb7a331ab57ba2e8bc Mon Sep 17 00:00:00 2001 From: Minecraft0122 <168195378+Minecraft0122@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:08:32 +0800 Subject: [PATCH] =?UTF-8?q?feat(commands):=20=E5=A2=9E=E5=8A=A0=E6=96=87?= =?UTF-8?q?=E6=9C=AC=E5=91=BD=E4=BB=A4=E6=A8=A1=E6=8B=9F=E4=B8=8E=E5=A4=9A?= =?UTF-8?q?=E5=91=BD=E4=BB=A4=E5=86=B2=E7=AA=81=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 3 + dev/README.md | 4 + dev/internal/command/simulate.go | 126 +++++++++++++++++ dev/internal/command/simulate_test.go | 96 +++++++++++++ dev/internal/store/command_config.go | 128 ++++++++++++++++++ dev/internal/store/command_config_test.go | 104 ++++++++++++++ dev/internal/store/store.go | 5 + dev/internal/store/store_test.go | 2 +- dev/internal/web/command_diagnostics_test.go | 102 ++++++++++++++ dev/internal/web/commands.go | 121 +++++++++++++++++ dev/internal/web/commands_test.go | 103 ++++++++++++++ dev/internal/web/web.go | 8 ++ dev/web/package.json | 1 + dev/web/src/App.vue | 17 ++- dev/web/src/api.ts | 52 +++++++ dev/web/src/components/CommandDiagnostics.vue | 41 ++++++ dev/web/src/components/CommandEditor.vue | 67 +++++++++ dev/web/tests/api.test.mjs | 49 +++++++ ...56\344\270\216\346\250\241\346\213\237.md" | 95 +++++++++++++ 19 files changed, 1116 insertions(+), 8 deletions(-) create mode 100644 dev/internal/command/simulate.go create mode 100644 dev/internal/command/simulate_test.go create mode 100644 dev/internal/store/command_config.go create mode 100644 dev/internal/store/command_config_test.go create mode 100644 dev/internal/web/command_diagnostics_test.go create mode 100644 dev/internal/web/commands.go create mode 100644 dev/internal/web/commands_test.go create mode 100644 dev/web/src/api.ts create mode 100644 dev/web/src/components/CommandDiagnostics.vue create mode 100644 dev/web/src/components/CommandEditor.vue create mode 100644 dev/web/tests/api.test.mjs create mode 100644 "docs/\345\221\275\344\273\244\351\205\215\347\275\256\344\270\216\346\250\241\346\213\237.md" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 66444d8..b6e7053 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,6 +65,9 @@ jobs: cache-dependency-path: dev/web/package-lock.json - name: 构建便携包 run: node build.mjs + - name: 前端请求客户端测试 + working-directory: dev/web + run: npm test - name: 上传便携包 uses: actions/upload-artifact@v4 with: diff --git a/dev/README.md b/dev/README.md index 58470fd..ee4f676 100644 --- a/dev/README.md +++ b/dev/README.md @@ -142,3 +142,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) 和 [协作约定](../AGENTS.md)。建议使用中文说明 PR 和提交;中文 CI 仅提醒,不阻断合并。AI 辅助贡献须披露工具及用途,并由贡献者人工审阅和验证,相关要求不纳入自动检测。 + +### 文本命令配置与诊断 + +命令页支持版本 1 文本命令表单、单条草稿模拟和多命令冲突诊断。管理接口为 `POST /api/commands/validate`、`/api/commands/simulate`、`/api/commands/diagnose`,共用现有会话认证。旧命令 JSON 保留,更新前须显式确认版本。当前不接入真实消息触发、绑定授权、冷却或回复投递。接口字段、错误与人工验收步骤见 [命令配置与模拟](../docs/命令配置与模拟.md)。前端统一客户端可用 `npm test` 测试;人工验收待完成。 diff --git a/dev/internal/command/simulate.go b/dev/internal/command/simulate.go new file mode 100644 index 0000000..d5c5182 --- /dev/null +++ b/dev/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/dev/internal/command/simulate_test.go b/dev/internal/command/simulate_test.go new file mode 100644 index 0000000..cb68415 --- /dev/null +++ b/dev/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/dev/internal/store/command_config.go b/dev/internal/store/command_config.go new file mode 100644 index 0000000..04204b7 --- /dev/null +++ b/dev/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/dev/internal/store/command_config_test.go b/dev/internal/store/command_config_test.go new file mode 100644 index 0000000..a13d786 --- /dev/null +++ b/dev/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/dev/internal/store/store.go b/dev/internal/store/store.go index 8707d21..56f2b0b 100644 --- a/dev/internal/store/store.go +++ b/dev/internal/store/store.go @@ -541,6 +541,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/dev/internal/store/store_test.go b/dev/internal/store/store_test.go index 49d08b4..85f44b6 100644 --- a/dev/internal/store/store_test.go +++ b/dev/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/dev/internal/web/command_diagnostics_test.go b/dev/internal/web/command_diagnostics_test.go new file mode 100644 index 0000000..edb05c7 --- /dev/null +++ b/dev/internal/web/command_diagnostics_test.go @@ -0,0 +1,102 @@ +package web + +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.NewLogBuffer(100)) + invoke := func(body string, auth bool) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/api/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/dev/internal/web/commands.go b/dev/internal/web/commands.go new file mode 100644 index 0000000..7a6cf27 --- /dev/null +++ b/dev/internal/web/commands.go @@ -0,0 +1,121 @@ +package web + +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/dev/internal/web/commands_test.go b/dev/internal/web/commands_test.go new file mode 100644 index 0000000..b66db34 --- /dev/null +++ b/dev/internal/web/commands_test.go @@ -0,0 +1,103 @@ +package web + +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.NewLogBuffer(100) + 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/commands/simulate", map[string]any{}, false); res.Code != 401 { + t.Fatal("unprotected simulation", res.Code) + } + res := invoke("/api/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/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/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/commands/simulate", request, true); res.Code != 400 { + t.Fatal("ID and draft override accepted") + } + delete(request, "id") + request["enabled"] = false + res = invoke("/api/commands/simulate", request, true) + if !strings.Contains(res.Body.String(), `"reason":"disabled"`) { + t.Fatal(res.Body.String()) + } + delete(request, "enabled") + if res := invoke("/api/commands/simulate", request, true); res.Code != 400 { + t.Fatal("missing enabled accepted") + } + if res := invoke("/api/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/commands/simulate", request, true); res.Code != 400 { + t.Fatal("unsupported action accepted") + } + if res := invoke("/api/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/dev/internal/web/web.go b/dev/internal/web/web.go index 78afa3c..70d0e39 100644 --- a/dev/internal/web/web.go +++ b/dev/internal/web/web.go @@ -79,6 +79,9 @@ func NewForListenerWithRuntimes(db *store.Store, logger *slog.Logger, logs *runt mux.HandleFunc("POST /api/auth/login", s.login) mux.HandleFunc("POST /api/auth/logout", s.logout) mux.HandleFunc("GET /api/dashboard/data", s.dashboard) + mux.HandleFunc("POST /api/commands/simulate", s.simulateCommand) + mux.HandleFunc("POST /api/commands/diagnose", s.diagnoseCommands) + mux.HandleFunc("POST /api/commands/validate", s.validateCommand) mux.HandleFunc("GET /api/records", s.listRecords) mux.HandleFunc("POST /api/records", s.createRecord) mux.HandleFunc("PUT /api/records/{kind}/{id}", s.updateRecord) @@ -1110,6 +1113,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/dev/web/package.json b/dev/web/package.json index abc89e2..35327b3 100644 --- a/dev/web/package.json +++ b/dev/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/dev/web/src/App.vue b/dev/web/src/App.vue index 1d2eeff..83b2a32 100644 --- a/dev/web/src/App.vue +++ b/dev/web/src/App.vue @@ -1,6 +1,9 @@ + +