feat: wire settings admin into DobotAI runtime
This commit is contained in:
+15
-3
@@ -11,6 +11,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/agentbinding"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/audit"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk"
|
||||
@@ -49,6 +50,10 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
settingsRuntime, err := buildSettingsRuntime(storeCtx, store, os.Getenv("DOBOTAI_TENANT_KEY"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
client, err := weknora.NewClient(os.Getenv("WEKNORA_BASE_URL"), os.Getenv("WEKNORA_API_KEY"), 120*time.Second)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -95,8 +100,8 @@ func main() {
|
||||
}
|
||||
|
||||
dingCfg := dingtalk.StreamConfig{
|
||||
ClientID: os.Getenv("DINGTALK_CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("DINGTALK_CLIENT_SECRET"),
|
||||
ClientID: settingsRuntime.clientID,
|
||||
ClientSecret: settingsRuntime.secret,
|
||||
TenantKey: os.Getenv("DOBOTAI_TENANT_KEY"),
|
||||
}
|
||||
if err := dingCfg.Validate(); err != nil {
|
||||
@@ -236,6 +241,8 @@ func main() {
|
||||
CardSender: cardSender,
|
||||
Directory: directoryResolver,
|
||||
OutboundRewriter: outboundRewriter,
|
||||
SettingsRouter: &dingTalkSettingsRouter{controller: settingsRuntime.controller},
|
||||
LanguageResolver: settingsRuntime.repository,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
@@ -251,7 +258,12 @@ func main() {
|
||||
defer streamClient.Close()
|
||||
log.Printf("DingTalk Stream ingress started for tenant %s", dingCfg.TenantKey)
|
||||
}
|
||||
server := &http.Server{Addr: address, Handler: api.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 130 * time.Second, IdleTimeout: 60 * time.Second}
|
||||
rootHandler := http.NewServeMux()
|
||||
rootHandler.Handle("/", api.Handler())
|
||||
if strings.TrimSpace(os.Getenv("DOBOTAI_ADMIN_TOKEN")) != "" {
|
||||
rootHandler.Handle("/admin/", adminweb.New(settingsRuntime.admin, os.Getenv("DOBOTAI_ADMIN_TOKEN")))
|
||||
}
|
||||
server := &http.Server{Addr: address, Handler: rootHandler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 130 * time.Second, IdleTimeout: 60 * time.Second}
|
||||
go func() {
|
||||
log.Printf("DobotAI ingress listening on %s", address)
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
|
||||
@@ -2,10 +2,17 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/adminweb"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres"
|
||||
)
|
||||
|
||||
type dingTalkSettingsRouter struct{ controller *settings.Controller }
|
||||
@@ -20,3 +27,61 @@ func (r *dingTalkSettingsRouter) Handle(ctx context.Context, m dingtalk.Settings
|
||||
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
|
||||
}
|
||||
|
||||
type settingsRuntime struct {
|
||||
repository *postgres.SettingsRepository
|
||||
controller *settings.Controller
|
||||
admin *adminweb.ControlService
|
||||
clientID string
|
||||
secret string
|
||||
}
|
||||
|
||||
func buildSettingsRuntime(ctx context.Context, store *postgres.Store, tenantKey string) (*settingsRuntime, error) {
|
||||
tenantKey = strings.TrimSpace(tenantKey)
|
||||
if tenantKey == "" {
|
||||
return nil, errors.New("DOBOTAI_TENANT_KEY is required")
|
||||
}
|
||||
repo, err := postgres.NewSettingsRepository(store)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root := strings.TrimSpace(os.Getenv("DOBOTAI_SECRET_DIR"))
|
||||
if root == "" {
|
||||
home, homeErr := os.UserHomeDir()
|
||||
if homeErr != nil {
|
||||
return nil, homeErr
|
||||
}
|
||||
root = filepath.Join(home, ".config", "dobotai", "secrets")
|
||||
}
|
||||
secrets, err := secretstore.New(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clientID, secretRef, _, err := repo.ActiveDingTalkConfig(ctx, tenantKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var secret string
|
||||
if secretRef != "" {
|
||||
secret, err = secrets.Get(secretRef)
|
||||
if err != nil {
|
||||
return nil, errors.New("active DingTalk secret is unavailable")
|
||||
}
|
||||
}
|
||||
if clientID == "" && strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_ID")) != "" && strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_SECRET")) != "" {
|
||||
clientID, secret = strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_ID")), strings.TrimSpace(os.Getenv("DINGTALK_CLIENT_SECRET"))
|
||||
secretRef, err = secrets.Put("dingtalk", secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = repo.SaveDingTalkConfig(ctx, tenantKey, clientID, secretRef, true); err != nil {
|
||||
_ = secrets.Delete(secretRef)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
control, err := adminweb.NewControlService(tenantKey, repo, secrets, dingtalkconfig.NewVerifier("https://oapi.dingtalk.com/gettoken", nil))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &settingsRuntime{repository: repo, controller: settings.NewController(repo), admin: control, clientID: clientID, secret: secret}, nil
|
||||
}
|
||||
|
||||
@@ -26,6 +26,10 @@ type Service interface {
|
||||
SaveCredentials(context.Context, string, string) error
|
||||
VerifyCredentials(context.Context, string, string) Verification
|
||||
}
|
||||
type BootstrapService interface {
|
||||
CreateBootstrap(context.Context, string) error
|
||||
ConfirmBootstrap(context.Context) error
|
||||
}
|
||||
type server struct {
|
||||
service Service
|
||||
token string
|
||||
@@ -33,25 +37,35 @@ type server struct {
|
||||
page *template.Template
|
||||
}
|
||||
|
||||
const settingsPage = `<!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}input{padding:10px;width:95%;margin:6px 0}button{padding:10px 18px;background:#1677ff;color:white;border:0;border-radius:8px;margin:5px}</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><p>新凭据会先在线验证,成功后保存;服务重启后加载新应用。</p><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><div class="card"><h2>首位管理员</h2><form method="post" action="/admin/setup/bootstrap"><input name="code" pattern="[0-9]{6}" placeholder="输入任意6位一次性绑定码" required><button>生成绑定码</button></form><form method="post" action="/admin/setup/bootstrap/confirm"><button>确认检测到的管理员</button></form></div>{{range .Components}}<div class="card"><b>{{.Name}}</b>:{{.State}}<br>{{.Detail}}</div>{{end}}</body></html>`
|
||||
|
||||
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 := &server{service: service, token: strings.TrimSpace(token), mux: http.NewServeMux(), page: template.Must(template.New("settings").Parse(settingsPage))}
|
||||
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)
|
||||
s.mux.HandleFunc("POST /admin/setup/bootstrap", s.createBootstrap)
|
||||
s.mux.HandleFunc("POST /admin/setup/bootstrap/confirm", s.confirmBootstrap)
|
||||
return s
|
||||
}
|
||||
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if !s.authorized(r) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="DobotAI Admin"`)
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
s.mux.ServeHTTP(w, r)
|
||||
}
|
||||
func (s *server) authorized(r *http.Request) bool {
|
||||
if s.token == "" {
|
||||
return false
|
||||
}
|
||||
if _, password, ok := r.BasicAuth(); ok && len(password) == len(s.token) && subtle.ConstantTimeCompare([]byte(password), []byte(s.token)) == 1 {
|
||||
return true
|
||||
}
|
||||
v := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
return s.token != "" && len(v) == len(s.token) && subtle.ConstantTimeCompare([]byte(v), []byte(s.token)) == 1
|
||||
return 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())
|
||||
@@ -80,3 +94,49 @@ func (s *server) saveCredentials(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
http.Redirect(w, r, "/admin/settings", http.StatusSeeOther)
|
||||
}
|
||||
func (s *server) createBootstrap(w http.ResponseWriter, r *http.Request) {
|
||||
service, ok := s.service.(BootstrapService)
|
||||
if !ok {
|
||||
http.Error(w, "bootstrap unavailable", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "invalid form", 400)
|
||||
return
|
||||
}
|
||||
code := strings.TrimSpace(r.FormValue("code"))
|
||||
if !sixDigits(code) {
|
||||
http.Error(w, "binding code must be 6 digits", 400)
|
||||
return
|
||||
}
|
||||
if err := service.CreateBootstrap(r.Context(), code); err != nil {
|
||||
http.Error(w, "create binding code failed", 500)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
fmt.Fprintf(w, "请在10分钟内私聊机器人发送:/setting %s\n", code)
|
||||
}
|
||||
func (s *server) confirmBootstrap(w http.ResponseWriter, r *http.Request) {
|
||||
service, ok := s.service.(BootstrapService)
|
||||
if !ok {
|
||||
http.Error(w, "bootstrap unavailable", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
if err := service.ConfirmBootstrap(r.Context()); err != nil {
|
||||
http.Error(w, "尚未检测到可确认的管理员", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/admin/settings", http.StatusSeeOther)
|
||||
}
|
||||
func sixDigits(value string) bool {
|
||||
if len(value) != 6 {
|
||||
return false
|
||||
}
|
||||
for _, ch := range value {
|
||||
if ch < '0' || ch > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user