From 462ee1f3ff0afb2b34e4070436ae8781842963c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Thu, 13 Aug 2026 12:45:08 +0800 Subject: [PATCH] feat: add admin settings control flow --- cmd/dobotai/settings_wiring.go | 22 ++ internal/adminweb/control.go | 111 ++++++++++ internal/adminweb/server.go | 82 +++++++ internal/adminweb/server_test.go | 56 +++++ internal/channels/dingtalk/handler.go | 45 ++++ .../channels/dingtalk/settings_route_test.go | 55 +++++ internal/settings/controller.go | 127 +++++++++++ internal/settings/controller_test.go | 91 ++++++++ internal/store/postgres/settings.go | 203 ++++++++++++++++++ 9 files changed, 792 insertions(+) create mode 100644 cmd/dobotai/settings_wiring.go create mode 100644 internal/adminweb/control.go create mode 100644 internal/adminweb/server.go create mode 100644 internal/adminweb/server_test.go create mode 100644 internal/channels/dingtalk/settings_route_test.go create mode 100644 internal/settings/controller.go create mode 100644 internal/settings/controller_test.go create mode 100644 internal/store/postgres/settings.go diff --git a/cmd/dobotai/settings_wiring.go b/cmd/dobotai/settings_wiring.go new file mode 100644 index 0000000..2f87020 --- /dev/null +++ b/cmd/dobotai/settings_wiring.go @@ -0,0 +1,22 @@ +package main + +import ( + "context" + "strings" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type dingTalkSettingsRouter struct{ controller *settings.Controller } + +func (r *dingTalkSettingsRouter) Handle(ctx context.Context, m dingtalk.SettingsMessage) (bool, string, error) { + if r == nil || r.controller == nil { + return false, "", nil + } + if _, ok := settings.ParseCommand(m.Text); !ok { + return false, "", nil + } + out, err := r.controller.Handle(ctx, settings.SettingInput{TenantKey: m.TenantKey, Channel: m.Channel, StaffID: m.StaffID, UnionID: m.UnionID, DisplayName: m.DisplayName, Department: m.Department, Text: m.Text, ConversationType: m.ConversationType, ConversationID: m.ConversationID, ConversationTitle: m.ConversationTitle}) + return true, strings.TrimSpace(out), err +} diff --git a/internal/adminweb/control.go b/internal/adminweb/control.go new file mode 100644 index 0000000..5fc2e66 --- /dev/null +++ b/internal/adminweb/control.go @@ -0,0 +1,111 @@ +package adminweb + +import ( + "context" + "errors" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +type ConfigRepository interface { + ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) + SaveDingTalkConfig(context.Context, string, string, string, bool) error + AdministratorCount(context.Context, string) (int, error) + ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) + CreateBootstrapChallenge(context.Context, string, string, time.Time) error + ConfirmBootstrap(context.Context, string) error +} +type CredentialVerifier interface { + Verify(context.Context, string, string) dingtalkconfig.Result +} +type ControlService struct { + tenant string + repo ConfigRepository + secrets *secretstore.Store + verifier CredentialVerifier +} + +func NewControlService(tenant string, repo ConfigRepository, secrets *secretstore.Store, verifier CredentialVerifier) (*ControlService, error) { + if strings.TrimSpace(tenant) == "" || repo == nil || secrets == nil || verifier == nil { + return nil, errors.New("admin control dependencies are required") + } + return &ControlService{tenant: strings.TrimSpace(tenant), repo: repo, secrets: secrets, verifier: verifier}, nil +} +func (s *ControlService) Snapshot(ctx context.Context) (Snapshot, error) { + id, ref, verified, err := s.repo.ActiveDingTalkConfig(ctx, s.tenant) + if err != nil { + return Snapshot{}, err + } + admins, err := s.repo.AdministratorCount(ctx, s.tenant) + if err != nil { + return Snapshot{}, err + } + bindings, err := s.repo.ActiveBindings(ctx, s.tenant) + if err != nil { + return Snapshot{}, err + } + state := settings.DetermineState(settings.Snapshot{ClientID: id, SecretConfigured: s.secrets.Configured(ref), CredentialsVerified: verified, AdministratorCount: admins}) + components := []Component{{Name: "PostgreSQL", State: "ok", Detail: "配置仓库可用"}, {Name: "钉钉OAuth", State: status(verified), Detail: "凭据验证状态"}, {Name: "管理员", State: countStatus(admins), Detail: itoa(admins) + " 位有效管理员"}, {Name: "技术支持群", State: bindingStatus(bindings, "support_group")}, {Name: "问题AI表格", State: bindingStatus(bindings, "question_table")}, {Name: "FAQ表格", State: bindingStatus(bindings, "faq_table")}} + return Snapshot{SystemState: string(state), ClientIDMasked: maskID(id), SecretConfigured: s.secrets.Configured(ref), Components: components}, nil +} +func (s *ControlService) VerifyCredentials(ctx context.Context, id, secret string) Verification { + r := s.verifier.Verify(ctx, id, secret) + return Verification{OK: r.OK, Code: r.Code, CheckedAt: r.CheckedAt} +} +func (s *ControlService) SaveCredentials(ctx context.Context, id, secret string) error { + ref, err := s.secrets.Put("dingtalk", secret) + if err != nil { + return err + } + if err = s.repo.SaveDingTalkConfig(ctx, s.tenant, strings.TrimSpace(id), ref, true); err != nil { + _ = s.secrets.Delete(ref) + return err + } + return nil +} +func (s *ControlService) CreateBootstrap(ctx context.Context, code string) error { + return s.repo.CreateBootstrapChallenge(ctx, s.tenant, code, time.Now().Add(10*time.Minute)) +} +func (s *ControlService) ConfirmBootstrap(ctx context.Context) error { + return s.repo.ConfirmBootstrap(ctx, s.tenant) +} +func maskID(v string) string { + v = strings.TrimSpace(v) + if len(v) <= 6 { + return v + } + return v[:3] + "***" + v[len(v)-3:] +} +func status(ok bool) string { + if ok { + return "ok" + } + return "unconfigured" +} +func countStatus(n int) string { + if n > 0 { + return "ok" + } + return "unconfigured" +} +func bindingStatus(m map[string]settings.ResourceBinding, k string) string { + if _, ok := m[k]; ok { + return "configured" + } + return "unconfigured" +} +func itoa(n int) string { + if n == 0 { + return "0" + } + b := make([]byte, 0, 8) + for n > 0 { + b = append([]byte{byte('0' + n%10)}, b...) + n /= 10 + } + return string(b) +} diff --git a/internal/adminweb/server.go b/internal/adminweb/server.go new file mode 100644 index 0000000..0cd329a --- /dev/null +++ b/internal/adminweb/server.go @@ -0,0 +1,82 @@ +package adminweb + +import ( + "context" + "crypto/subtle" + "fmt" + "html/template" + "net/http" + "strings" + "time" +) + +type Snapshot struct { + SystemState, ClientIDMasked string + SecretConfigured bool + Components []Component +} +type Component struct{ Name, State, Detail string } +type Verification struct { + OK bool + Code string + CheckedAt time.Time +} +type Service interface { + Snapshot(context.Context) (Snapshot, error) + SaveCredentials(context.Context, string, string) error + VerifyCredentials(context.Context, string, string) Verification +} +type server struct { + service Service + token string + mux *http.ServeMux + page *template.Template +} + +func New(service Service, token string) http.Handler { + page := template.Must(template.New("settings").Parse(`DobotAI 设置

DobotAI 配置中心

系统状态:{{.SystemState}}
Client ID:{{.ClientIDMasked}}
Client Secret:{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}

配置钉钉应用

{{range .Components}}
{{.Name}}:{{.State}}
{{.Detail}}
{{end}}`)) + s := &server{service: service, token: strings.TrimSpace(token), mux: http.NewServeMux(), page: page} + s.mux.HandleFunc("GET /admin/settings", s.settings) + s.mux.HandleFunc("GET /admin/setup", s.settings) + s.mux.HandleFunc("POST /admin/setup/credentials", s.saveCredentials) + return s +} +func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if !s.authorized(r) { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + s.mux.ServeHTTP(w, r) +} +func (s *server) authorized(r *http.Request) bool { + v := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + return s.token != "" && len(v) == len(s.token) && subtle.ConstantTimeCompare([]byte(v), []byte(s.token)) == 1 +} +func (s *server) settings(w http.ResponseWriter, r *http.Request) { + snap, err := s.service.Snapshot(r.Context()) + if err != nil { + http.Error(w, "settings unavailable", 500) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _ = s.page.Execute(w, snap) +} +func (s *server) saveCredentials(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 16<<10) + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", 400) + return + } + id, secret := strings.TrimSpace(r.FormValue("client_id")), strings.TrimSpace(r.FormValue("client_secret")) + result := s.service.VerifyCredentials(r.Context(), id, secret) + if !result.OK { + http.Error(w, fmt.Sprintf("credential verification failed: %s", result.Code), 422) + return + } + if err := s.service.SaveCredentials(r.Context(), id, secret); err != nil { + http.Error(w, "credential save failed", 500) + return + } + http.Redirect(w, r, "/admin/settings", http.StatusSeeOther) +} diff --git a/internal/adminweb/server_test.go b/internal/adminweb/server_test.go new file mode 100644 index 0000000..4fb322b --- /dev/null +++ b/internal/adminweb/server_test.go @@ -0,0 +1,56 @@ +package adminweb + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +type fakeService struct { + snapshot Snapshot + verified bool + saved bool +} + +func (f *fakeService) Snapshot(context.Context) (Snapshot, error) { return f.snapshot, nil } +func (f *fakeService) SaveCredentials(context.Context, string, string) error { + f.saved = true + return nil +} +func (f *fakeService) VerifyCredentials(context.Context, string, string) Verification { + f.verified = true + return Verification{OK: true, Code: "ok", CheckedAt: time.Unix(1, 0)} +} +func TestDashboardNeverRendersSecrets(t *testing.T) { + svc := &fakeService{snapshot: Snapshot{SystemState: "active", ClientIDMasked: "ding***", SecretConfigured: true}} + h := New(svc, "admin-token") + req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != 200 { + t.Fatalf("status=%d", w.Code) + } + body := w.Body.String() + if strings.Contains(body, "admin-token") || strings.Contains(strings.ToLower(body), "client secret value") { + t.Fatal("secret leaked") + } + if !strings.Contains(body, "ding***") { + t.Fatal("masked client id missing") + } +} +func TestSaveCredentialsRequiresVerification(t *testing.T) { + svc := &fakeService{} + h := New(svc, "admin-token") + req := httptest.NewRequest(http.MethodPost, "/admin/setup/credentials", strings.NewReader("client_id=id&client_secret=secret")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Authorization", "Bearer admin-token") + w := httptest.NewRecorder() + h.ServeHTTP(w, req) + if w.Code != http.StatusSeeOther || !svc.verified || !svc.saved { + t.Fatalf("status=%d verified=%v saved=%v", w.Code, svc.verified, svc.saved) + } +} diff --git a/internal/channels/dingtalk/handler.go b/internal/channels/dingtalk/handler.go index db8eb30..533b81f 100644 --- a/internal/channels/dingtalk/handler.go +++ b/internal/channels/dingtalk/handler.go @@ -83,6 +83,23 @@ type OutboundContentRewriter interface { Rewrite(ctx context.Context, content string) string } +type SettingsMessage struct { + TenantKey string + Channel string + StaffID string + UnionID string + DisplayName string + Department string + Text string + ConversationType string + ConversationID string + ConversationTitle string +} + +type SettingsRouter interface { + Handle(context.Context, SettingsMessage) (handled bool, reply string, err error) +} + // FinalCardSender sends an AI card as the final reply. Implementations must // not log err, outTrackID, or content at any level. type FinalCardSender interface { @@ -101,6 +118,7 @@ type HandlerOptions struct { CardSender FinalCardSender Directory UserDirectory OutboundRewriter OutboundContentRewriter + SettingsRouter SettingsRouter } type Handler struct { @@ -111,6 +129,7 @@ type Handler struct { card FinalCardSender directory UserDirectory outboundRewriter OutboundContentRewriter + settingsRouter SettingsRouter now func() time.Time cardUpdateInterval time.Duration finalDeliveryTimeout time.Duration @@ -153,6 +172,7 @@ func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, o card: opts.CardSender, directory: opts.Directory, outboundRewriter: opts.OutboundRewriter, + settingsRouter: opts.SettingsRouter, now: time.Now, cardUpdateInterval: 500 * time.Millisecond, finalDeliveryTimeout: defaultHTTPTimeout, @@ -186,6 +206,24 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return errors.New("dingtalk handler: sender staffId/senderId is required") } + if h.settingsRouter != nil && strings.EqualFold(strings.TrimSpace(cb.Msgtype), msgTypeText) { + handled, settingsReply, err := h.settingsRouter.Handle(ctx, SettingsMessage{ + TenantKey: h.cfg.TenantKey, Channel: h.cfg.Channel, StaffID: externalUserID, + DisplayName: strings.TrimSpace(cb.SenderNick), Text: strings.TrimSpace(cb.Text), + ConversationType: mapDingTalkConversationType(cb.ConversationType), + ConversationID: strings.TrimSpace(cb.ConversationID), ConversationTitle: strings.TrimSpace(cb.ConversationTitle), + }) + if err != nil { + return fmt.Errorf("dingtalk settings: %w", err) + } + if handled { + if strings.TrimSpace(settingsReply) == "" { + return nil + } + return h.sendReply(ctx, webhookURL, settingsReply) + } + } + triggerPerson := strings.TrimSpace(cb.SenderNick) senderName := triggerPerson department := "" @@ -270,6 +308,13 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return h.handleNonStreaming(ctx, webhookURL, req) } +func mapDingTalkConversationType(value string) string { + if value == conversationTypeGroup { + return "group" + } + return "direct" +} + func (h *Handler) eventStreamingCapable() (StreamingCardSender, EventQAAsker) { sc, ok := h.card.(StreamingCardSender) if !ok { diff --git a/internal/channels/dingtalk/settings_route_test.go b/internal/channels/dingtalk/settings_route_test.go new file mode 100644 index 0000000..49d6310 --- /dev/null +++ b/internal/channels/dingtalk/settings_route_test.go @@ -0,0 +1,55 @@ +package dingtalk + +import ( + "context" + "testing" +) + +type fakeSettingsRouter struct { + called bool + handled bool + reply string +} + +func (f *fakeSettingsRouter) Handle(_ context.Context, in SettingsMessage) (bool, string, error) { + f.called = true + if in.StaffID != "staff-123" { + panic("wrong identity") + } + return f.handled, f.reply, nil +} +func TestSettingsCommandBypassesQA(t *testing.T) { + qa := &fakeQA{} + reply := &fakeReply{} + router := &fakeSettingsRouter{handled: true, reply: "settings menu"} + h, err := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{SettingsRouter: router}) + if err != nil { + t.Fatal(err) + } + cb := directTextCallback() + cb.Text = "/setting" + if err = h.Handle(context.Background(), cb); err != nil { + t.Fatal(err) + } + if !router.called { + t.Fatal("router not called") + } + if qa.called { + t.Fatal("settings must bypass QA") + } + if !reply.called || reply.lastText != "settings menu" { + t.Fatalf("reply=%+v", reply) + } +} +func TestOrdinaryQuestionStillCallsQA(t *testing.T) { + qa := &fakeQA{} + reply := &fakeReply{} + router := &fakeSettingsRouter{} + h, _ := NewHandlerWithOptions(TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, qa, reply, HandlerOptions{SettingsRouter: router}) + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatal(err) + } + if !qa.called { + t.Fatal("ordinary question must call QA") + } +} diff --git a/internal/settings/controller.go b/internal/settings/controller.go new file mode 100644 index 0000000..a0d6d12 --- /dev/null +++ b/internal/settings/controller.go @@ -0,0 +1,127 @@ +package settings + +import ( + "context" + "errors" + "fmt" + "strings" + "time" +) + +type ResourceBinding struct { + Kind, TenantKey, ConversationID, ConversationTitle string + BaseID, SheetID, ViewID, OperatorID string + CreatedByStaffID string +} +type BootstrapCandidate struct { + TenantKey, Code, StaffID, UnionID, DisplayName, Department string + DetectedAt time.Time +} +type SettingInput struct{ TenantKey, Channel, StaffID, UnionID, DisplayName, Department, Text, ConversationType, ConversationID, ConversationTitle string } +type ControllerRepository interface { + IsAdministrator(context.Context, string, string) (bool, error) + SetPreference(context.Context, string, string, string, string) error + SaveBinding(context.Context, ResourceBinding) error + DetectBootstrapCandidate(context.Context, BootstrapCandidate) error +} +type Controller struct { + repo ControllerRepository + now func() time.Time +} + +func NewController(repo ControllerRepository) *Controller { + return &Controller{repo: repo, now: time.Now} +} +func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error) { + if c == nil || c.repo == nil { + return "", errors.New("settings repository is required") + } + cmd, ok := ParseCommand(in.Text) + if !ok { + return "", nil + } + if len(cmd.Args) == 1 && len(cmd.Args[0]) == 6 && allDigits(cmd.Args[0]) { + if strings.TrimSpace(in.ConversationType) != "direct" { + return "管理员绑定码只能私聊机器人使用。", nil + } + err := c.repo.DetectBootstrapCandidate(ctx, BootstrapCandidate{TenantKey: in.TenantKey, Code: cmd.Args[0], StaffID: in.StaffID, UnionID: in.UnionID, DisplayName: in.DisplayName, Department: in.Department, DetectedAt: c.now()}) + if err != nil { + return "", err + } + return "身份已验证,请回到后台确认首位管理员。", nil + } + if len(cmd.Args) == 0 { + admin, err := c.repo.IsAdministrator(ctx, in.TenantKey, in.StaffID) + if err != nil { + return "", err + } + if admin { + return "⚙️ 我的设置:/setting language \n🛠 系统管理:support、question、faq", nil + } + return "⚙️ 我的设置:/setting language ", nil + } + action := strings.ToLower(cmd.Args[0]) + if action == "language" { + if len(cmd.Args) != 2 || !validLocale(cmd.Args[1]) { + return "可选语言:auto、zh-CN、en、ja、ko、es。", nil + } + if err := c.repo.SetPreference(ctx, in.TenantKey, defaultChannel(in.Channel), in.StaffID, cmd.Args[1]); err != nil { + return "", err + } + return "✅ 回答语言已设置为 " + cmd.Args[1] + "。", nil + } + admin, err := c.repo.IsAdministrator(ctx, in.TenantKey, in.StaffID) + if err != nil { + return "", err + } + if !admin { + return "你没有系统管理权限。", nil + } + switch action { + case "support": + if in.ConversationType != "group" || strings.TrimSpace(in.ConversationID) == "" { + return "请在目标技术支持群中@机器人发送 /setting support。", nil + } + err = c.repo.SaveBinding(ctx, ResourceBinding{Kind: "support_group", TenantKey: in.TenantKey, ConversationID: in.ConversationID, ConversationTitle: in.ConversationTitle, CreatedByStaffID: in.StaffID}) + if err == nil { + return "✅ 当前群已保存为技术支持群(待后台验证)。", nil + } + case "question", "faq": + if len(cmd.Args) != 2 { + return "请在命令后发送钉钉AI表格链接。", nil + } + link, e := ParseNotableLink(cmd.Args[1]) + if e != nil { + return "AI表格链接无法识别。", nil + } + kind := action + "_table" + err = c.repo.SaveBinding(ctx, ResourceBinding{Kind: kind, TenantKey: in.TenantKey, BaseID: link.BaseID, SheetID: link.SheetID, ViewID: link.ViewID, OperatorID: in.UnionID, CreatedByStaffID: in.StaffID}) + if err == nil { + return fmt.Sprintf("✅ %s已解析并保存为待验证配置。", map[string]string{"question": "问题AI表格", "faq": "FAQ表格"}[action]), nil + } + default: + return "未知设置项。发送 /setting 查看菜单。", nil + } + return "", err +} +func validLocale(s string) bool { + switch s { + case "auto", "zh-CN", "en", "ja", "ko", "es": + return true + } + return false +} +func defaultChannel(s string) string { + if strings.TrimSpace(s) == "" { + return "dingtalk" + } + return strings.TrimSpace(s) +} +func allDigits(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return s != "" +} diff --git a/internal/settings/controller_test.go b/internal/settings/controller_test.go new file mode 100644 index 0000000..5175613 --- /dev/null +++ b/internal/settings/controller_test.go @@ -0,0 +1,91 @@ +package settings + +import ( + "context" + "testing" + "time" +) + +type memoryRepo struct { + admins map[string]bool + prefs map[string]string + bindings map[string]ResourceBinding + candidate BootstrapCandidate +} + +func newMemoryRepo() *memoryRepo { + return &memoryRepo{admins: map[string]bool{}, prefs: map[string]string{}, bindings: map[string]ResourceBinding{}} +} +func (r *memoryRepo) IsAdministrator(_ context.Context, tenant, staff string) (bool, error) { + return r.admins[tenant+"/"+staff], nil +} +func (r *memoryRepo) SetPreference(_ context.Context, tenant, channel, staff, locale string) error { + r.prefs[tenant+"/"+staff] = locale + return nil +} +func (r *memoryRepo) SaveBinding(_ context.Context, b ResourceBinding) error { + r.bindings[b.Kind] = b + return nil +} +func (r *memoryRepo) DetectBootstrapCandidate(_ context.Context, c BootstrapCandidate) error { + r.candidate = c + return nil +} +func TestControllerLanguageForOrdinaryUser(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", Channel: "dingtalk", StaffID: "u", Text: "/setting language ja", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.prefs["t/u"] != "ja" || out == "" { + t.Fatalf("prefs=%v out=%q", r.prefs, out) + } +} +func TestControllerRejectsOrdinaryUserSystemBinding(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "u", Text: "/setting support", ConversationType: "group", ConversationID: "g"}) + if err != nil { + t.Fatal(err) + } + if len(r.bindings) != 0 || out != "你没有系统管理权限。" { + t.Fatalf("bindings=%v out=%q", r.bindings, out) + } +} +func TestControllerBindsAdminSupportGroup(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting support", ConversationType: "group", ConversationID: "g", ConversationTitle: "技术支持"}) + if err != nil { + t.Fatal(err) + } + if r.bindings["support_group"].ConversationID != "g" { + t.Fatalf("binding=%+v", r.bindings) + } +} +func TestControllerParsesAdminQuestionTable(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting question https://alidocs.dingtalk.com/i/nodes/base?sheetId=sheet&viewId=view", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.bindings["question_table"].BaseID != "base" { + t.Fatalf("binding=%+v", r.bindings) + } +} +func TestControllerDetectsBootstrapCandidate(t *testing.T) { + r := newMemoryRepo() + c := NewController(r) + c.now = func() time.Time { return time.Unix(100, 0) } + _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", UnionID: "union", DisplayName: "Alice", Text: "/setting 123456", ConversationType: "direct"}) + if err != nil { + t.Fatal(err) + } + if r.candidate.Code != "123456" || r.candidate.StaffID != "a" { + t.Fatalf("candidate=%+v", r.candidate) + } +} diff --git a/internal/store/postgres/settings.go b/internal/store/postgres/settings.go new file mode 100644 index 0000000..d8543e4 --- /dev/null +++ b/internal/store/postgres/settings.go @@ -0,0 +1,203 @@ +package postgres + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" + "github.com/jackc/pgx/v5" +) + +type SettingsRepository struct{ store *Store } + +func NewSettingsRepository(s *Store) (*SettingsRepository, error) { + if s == nil || s.pool == nil { + return nil, errors.New("settings repository: store is required") + } + return &SettingsRepository{store: s}, nil +} +func (r *SettingsRepository) IsAdministrator(ctx context.Context, tenant, staff string) (bool, error) { + var ok bool + err := r.store.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM administrators WHERE tenant_key=$1 AND staff_id=$2 AND status='active')`, strings.TrimSpace(tenant), strings.TrimSpace(staff)).Scan(&ok) + return ok, err +} +func (r *SettingsRepository) SetPreference(ctx context.Context, tenant, channel, staff, locale string) error { + mode := "fixed" + if locale == "auto" { + mode = "auto" + } + _, err := r.store.pool.Exec(ctx, `INSERT INTO user_preferences(tenant_key,channel,external_actor_id,language_mode,locale) VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_key,channel,external_actor_id) DO UPDATE SET language_mode=EXCLUDED.language_mode,locale=EXCLUDED.locale,updated_at=NOW()`, tenant, channel, staff, mode, locale) + return err +} +func (r *SettingsRepository) GetPreference(ctx context.Context, tenant, channel, staff string) (string, error) { + var locale string + err := r.store.pool.QueryRow(ctx, `SELECT locale FROM user_preferences WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, tenant, channel, staff).Scan(&locale) + if errors.Is(err, pgx.ErrNoRows) { + return "auto", nil + } + return locale, err +} +func (r *SettingsRepository) SaveBinding(ctx context.Context, b settings.ResourceBinding) error { + payload, err := json.Marshal(map[string]string{"conversation_id": b.ConversationID, "conversation_title": b.ConversationTitle, "base_id": b.BaseID, "sheet_id": b.SheetID, "view_id": b.ViewID, "operator_id": b.OperatorID}) + if err != nil { + return err + } + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var rev int + if err = tx.QueryRow(ctx, `SELECT COALESCE(MAX(revision),0)+1 FROM system_resource_bindings WHERE tenant_key=$1 AND kind=$2`, b.TenantKey, b.Kind).Scan(&rev); err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE system_resource_bindings SET state='retired' WHERE tenant_key=$1 AND kind=$2 AND state='active'`, b.TenantKey, b.Kind); err != nil { + return err + } + _, err = tx.Exec(ctx, `INSERT INTO system_resource_bindings(id,tenant_key,kind,revision,state,public_config,validation_code,validated_at,activated_at,created_by_staff_id) VALUES($1,$2,$3,$4,'active',$5,'pending_external_probe',NOW(),NOW(),$6)`, newSettingsID(), b.TenantKey, b.Kind, rev, payload, b.CreatedByStaffID) + if err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) DetectBootstrapCandidate(ctx context.Context, c settings.BootstrapCandidate) error { + hash := sha256.Sum256([]byte(strings.TrimSpace(c.Code))) + var id, stored string + var attempts, max int + err := r.store.pool.QueryRow(ctx, `SELECT id,code_hash,attempts,max_attempts FROM admin_bootstrap_challenges WHERE tenant_key=$1 AND status='pending' AND expires_at>NOW() ORDER BY created_at DESC LIMIT 1`, c.TenantKey).Scan(&id, &stored, &attempts, &max) + if err != nil { + return err + } + if attempts >= max { + return errors.New("bootstrap challenge locked") + } + provided := hex.EncodeToString(hash[:]) + if len(provided) != len(stored) || subtle.ConstantTimeCompare([]byte(provided), []byte(stored)) != 1 { + _, _ = r.store.pool.Exec(ctx, `UPDATE admin_bootstrap_challenges SET attempts=attempts+1,status=CASE WHEN attempts+1>=max_attempts THEN 'locked' ELSE status END,updated_at=NOW() WHERE id=$1`, id) + return errors.New("invalid bootstrap code") + } + _, err = r.store.pool.Exec(ctx, `UPDATE admin_bootstrap_challenges SET candidate_staff_id=$2,candidate_union_id=$3,candidate_display_name=$4,candidate_department=$5,status='candidate_detected',updated_at=NOW() WHERE id=$1`, id, c.StaffID, c.UnionID, c.DisplayName, c.Department) + return err +} +func (r *SettingsRepository) CreateBootstrapChallenge(ctx context.Context, tenant, code string, expires time.Time) error { + sum := sha256.Sum256([]byte(code)) + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, `UPDATE admin_bootstrap_challenges SET status='expired',updated_at=NOW() WHERE tenant_key=$1 AND status IN ('pending','candidate_detected')`, tenant); err != nil { + return err + } + _, err = tx.Exec(ctx, `INSERT INTO admin_bootstrap_challenges(id,tenant_key,code_hash,expires_at,status) VALUES($1,$2,$3,$4,'pending')`, newSettingsID(), tenant, hex.EncodeToString(sum[:]), expires) + if err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) ConfirmBootstrap(ctx context.Context, tenant string) error { + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var challengeID, staff, union, name, dept string + err = tx.QueryRow(ctx, `SELECT id,candidate_staff_id,candidate_union_id,candidate_display_name,candidate_department FROM admin_bootstrap_challenges WHERE tenant_key=$1 AND status='candidate_detected' AND expires_at>NOW() FOR UPDATE`, tenant).Scan(&challengeID, &staff, &union, &name, &dept) + if err != nil { + return err + } + if strings.TrimSpace(staff) == "" { + return errors.New("bootstrap candidate missing") + } + _, err = tx.Exec(ctx, `INSERT INTO administrators(id,tenant_key,staff_id,union_id,display_name,department,role,status) VALUES($1,$2,$3,$4,$5,$6,'super_admin','active') ON CONFLICT(tenant_key,staff_id) DO UPDATE SET status='active',role='super_admin',updated_at=NOW()`, newSettingsID(), tenant, staff, union, name, dept) + if err != nil { + return err + } + if _, err = tx.Exec(ctx, `UPDATE admin_bootstrap_challenges SET status='confirmed',updated_at=NOW() WHERE id=$1`, challengeID); err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) AdministratorCount(ctx context.Context, tenant string) (int, error) { + var n int + err := r.store.pool.QueryRow(ctx, `SELECT COUNT(*) FROM administrators WHERE tenant_key=$1 AND status='active'`, tenant).Scan(&n) + return n, err +} +func (r *SettingsRepository) SaveDingTalkConfig(ctx context.Context, tenant, clientID, secretRef string, verified bool) error { + payload, _ := json.Marshal(map[string]string{"client_id": clientID}) + state := "draft" + validation := "pending" + if verified { + state = "active" + validation = "ok" + } + tx, err := r.store.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var rev int + if err = tx.QueryRow(ctx, `SELECT COALESCE(MAX(revision),0)+1 FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app'`, tenant).Scan(&rev); err != nil { + return err + } + if state == "active" { + if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='retired' WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active'`, tenant); err != nil { + return err + } + } + _, err = tx.Exec(ctx, `INSERT INTO system_config_revisions(id,tenant_key,kind,revision,state,public_config,secret_ref,validation_status,validation_code,validated_at,activated_at) VALUES($1,$2,'dingtalk_app',$3,$4,$5,$6,$7,$7,CASE WHEN $7='ok' THEN NOW() END,CASE WHEN $7='ok' THEN NOW() END)`, newSettingsID(), tenant, rev, state, payload, secretRef, validation) + if err != nil { + return err + } + return tx.Commit(ctx) +} +func (r *SettingsRepository) ActiveDingTalkConfig(ctx context.Context, tenant string) (clientID, secretRef string, verified bool, err error) { + var payload []byte + var status string + err = r.store.pool.QueryRow(ctx, `SELECT public_config,secret_ref,validation_status FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' ORDER BY revision DESC LIMIT 1`, tenant).Scan(&payload, &secretRef, &status) + if errors.Is(err, pgx.ErrNoRows) { + err = nil + return + } + if err != nil { + return + } + var v map[string]string + if json.Unmarshal(payload, &v) != nil { + err = fmt.Errorf("decode dingtalk config") + return + } + clientID = v["client_id"] + verified = status == "ok" + return +} +func (r *SettingsRepository) ActiveBindings(ctx context.Context, tenant string) (map[string]settings.ResourceBinding, error) { + rows, err := r.store.pool.Query(ctx, `SELECT kind,public_config FROM system_resource_bindings WHERE tenant_key=$1 AND state='active'`, tenant) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]settings.ResourceBinding{} + for rows.Next() { + var kind string + var raw []byte + if err = rows.Scan(&kind, &raw); err != nil { + return nil, err + } + var v map[string]string + if json.Unmarshal(raw, &v) != nil { + continue + } + out[kind] = settings.ResourceBinding{Kind: kind, TenantKey: tenant, ConversationID: v["conversation_id"], ConversationTitle: v["conversation_title"], BaseID: v["base_id"], SheetID: v["sheet_id"], ViewID: v["view_id"], OperatorID: v["operator_id"]} + } + return out, rows.Err() +} +func newSettingsID() string { b := make([]byte, 16); _, _ = rand.Read(b); return hex.EncodeToString(b) }