feat: add admin settings control flow
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>DobotAI 设置</title><style>body{font-family:sans-serif;background:#f5f8ff;color:#17324d;max-width:960px;margin:40px auto;padding:0 20px}.card{background:white;border:1px solid #dbe7f4;border-radius:14px;padding:20px;margin:14px 0}.ok{color:#087f5b}input{padding:10px;width:95%;margin:6px 0}button{padding:10px 18px;background:#1677ff;color:white;border:0;border-radius:8px}</style></head><body><h1>DobotAI 配置中心</h1><div class="card"><b>系统状态:</b>{{.SystemState}}<br><b>Client ID:</b>{{.ClientIDMasked}}<br><b>Client Secret:</b>{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}</div><div class="card"><h2>配置钉钉应用</h2><form method="post" action="/admin/setup/credentials"><label>Client ID / AppKey</label><input name="client_id" required><label>Client Secret / AppSecret</label><input type="password" name="client_secret" required autocomplete="new-password"><button>测试并保存</button></form></div>{{range .Components}}<div class="card"><b>{{.Name}}</b>:{{.State}}<br>{{.Detail}}</div>{{end}}</body></html>`))
|
||||
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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 <auto|zh-CN|en|ja|ko|es>\n🛠 系统管理:support、question、faq", nil
|
||||
}
|
||||
return "⚙️ 我的设置:/setting language <auto|zh-CN|en|ja|ko|es>", 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 != ""
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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) }
|
||||
Reference in New Issue
Block a user