Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
95 changes: 95 additions & 0 deletions docs/命令配置与模拟.md
Original file line number Diff line number Diff line change
@@ -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 加入前端客户端测试;外部数据库和浏览器人工测试尚未完成。
4 changes: 4 additions & 0 deletions docs/开发说明.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 验证请求客户端。
102 changes: 102 additions & 0 deletions internal/api/command_diagnostics_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
121 changes: 121 additions & 0 deletions internal/api/commands.go
Original file line number Diff line number Diff line change
@@ -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})
}
Loading
Loading