From b2cea6ed840c704b56d7687b505bb237b941872b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Tue, 17 Nov 2026 16:59:47 +0800 Subject: [PATCH] =?UTF-8?q?feat(settings):=20=E6=96=B0=E5=A2=9E=20DWS=20?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E7=99=BB=E5=BD=95=E4=B8=8E=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 数据源配置可发起钉钉官方设备授权、重新授权和取消,完成后刷新共享账号状态并独立检查目录权限。 授权会话限定发起的管理员登录会话,令牌由现有 CLI 存储,取消等待子进程退出。 验证:完整 make verify 通过;前端 582 项、Go 1545 项通过,487 项声明的可选集成未运行。 授权处理器与 HTTP 边界通过 race 检查;本人钉钉授权仍由管理员在官方页面完成。 --- CHANGELOG.md | 2 + README.md | 2 +- cmd/api/main.go | 1 + docs/DWS_LOGIN.md | 40 +++ internal/dingtalkdiscovery/credentials.go | 8 +- internal/dingtalkdiscovery/device_login.go | 243 +++++++++++++++ .../dingtalkdiscovery/device_login_test.go | 160 ++++++++++ internal/dingtalkdiscovery/exec_runner.go | 18 +- internal/httpapi/auth.go | 3 + internal/httpapi/dws_login.go | 74 +++++ internal/httpapi/dws_login_test.go | 82 +++++ internal/httpapi/server.go | 3 + web/src/DWSAccount.mounted.test.tsx | 167 ++++++++++ web/src/DWSAccount.test.tsx | 12 + web/src/DWSAccount.tsx | 286 ++++++++++++++++++ web/src/SourceManagement.css | 29 +- web/src/SourceManagement.tsx | 37 +-- web/src/SystemSettings.test.tsx | 4 +- web/src/dwsLogin.test.ts | 65 ++++ web/src/dwsLogin.ts | 101 +++++++ 20 files changed, 1291 insertions(+), 46 deletions(-) create mode 100644 docs/DWS_LOGIN.md create mode 100644 internal/dingtalkdiscovery/device_login.go create mode 100644 internal/dingtalkdiscovery/device_login_test.go create mode 100644 internal/httpapi/dws_login.go create mode 100644 internal/httpapi/dws_login_test.go create mode 100644 web/src/DWSAccount.mounted.test.tsx create mode 100644 web/src/DWSAccount.test.tsx create mode 100644 web/src/DWSAccount.tsx create mode 100644 web/src/dwsLogin.test.ts create mode 100644 web/src/dwsLogin.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c2a945e..50a10c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2386,6 +2386,8 @@ ### Added +- 数据源配置新增 DWS 登录与重新授权入口,使用钉钉官方设备授权;成功后刷新账号并独立检查目录访问权限。支持取消、过期和重试,授权仅限发起的管理员会话。[操作说明](docs/DWS_LOGIN.md) + - 新增解析监控统一工作台:顶部运行指标与依赖卡片、下方单一文件处理表;来源文件与目标测试库归并最新版本,动作、阶段、状态分列,后端统一筛选、计数及分页。支持单条/跨页勾选重试和版本、失败、重试详情;测试库移除重试独立核验治理规则,不误走上传流程。取消六分页和手动开始入口,生产授权仍在发布管理;本次不改变后台自动调度策略,自动处理闭环需另行端到端验收。 - 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。 diff --git a/README.md b/README.md index 704247b..5483d13 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Knowledge Adapter / DobotAI 网关 | 来源 | 当前接入方式 | 参考文档 | | --- | --- | --- | -| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) | +| 钉钉 | 知识库目录发现与取件;优先 dws,按错误类型决定是否回落兼容路径 | [登录授权](docs/DWS_LOGIN.md) · [钉钉取件](docs/DINGTALK_DWS_FETCHER.md) | | AList | 来源目录与资料获取,依赖指定连接和凭据 | [用户操作流程](docs/OPERATIONS_RUNBOOK.md) | | PP(资料门户) | 本地清单、历史账本接管与只读扫描 | [历史接管](docs/P2_PP_LEDGER_TAKEOVER_ACCEPTANCE.md)、[来源扫描](docs/P42_SOURCE_SCAN_ACCEPTANCE.md) | diff --git a/cmd/api/main.go b/cmd/api/main.go index 701ef82..fca8eb4 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -223,6 +223,7 @@ func run(ctx context.Context, getenv func(string) string) error { ProductionReleaseAuthorizationToken: releaseAuthorizationToken, // 数据源发现(系统设置 → 数据源配置):用与 worker 同一份 dws 状态做只读列举。 DingtalkSources: dingtalkSourceLister{}, + DWSLogin: dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{}), DingtalkDocuments: dingtalkSourceLister{}, BackupSchedule: postgresstore.NewStore(pool), VersionHistory: versionHistoryStore, diff --git a/docs/DWS_LOGIN.md b/docs/DWS_LOGIN.md new file mode 100644 index 0000000..1b6bd51 --- /dev/null +++ b/docs/DWS_LOGIN.md @@ -0,0 +1,40 @@ +# DWS 登录授权 + +管理员入口:系统设置 → 数据源配置 → 钉钉账号(DWS)。 + +- 未登录时点击“登录授权”,在弹窗中打开钉钉官方授权页,由本人选择账号与组织并确认。 +- 平台等待设备授权完成。成功后自动刷新账号、组织和续期凭证有效期,并检查知识库、钉盘目录访问。 +- “重新授权”采用同一流程;授权中可取消,失败或过期后可重新发起。 +- “检查连接”只列目录与读取登录元数据,不登记来源、不扫描已有来源、不发起入库或生产发布。 +- 登录成功与目录可用分开显示;部分范围无权限时保留其他已成功范围,并展示原因。 + +## 服务端接线 + +API 直接管理 `dws auth login --device --no-browser --format json` 子进程,不复用旧浏览器扫码侧车。 +CLI 负责官方 OAuth 协议、组织 CLI 权限校验及凭据加密持久化。平台只解析官方设备授权链接、用户授权码、有效期与状态;原始输出、access token、refresh token不进入接口或日志。 + +API 与 worker 必须使用相同 UID,以及同一组可写挂载: + +| 配置 | 用途 | +|---|---| +| `DWS_BIN` | 固定版本的 DWS 程序 | +| `DWS_CONFIG_DIR` | 共享的 DWS 状态目录 | +| `DWS_HOME` | 共享 home,包含 `.local/share/dws-cli` 文件型密钥存储 | +| `DWS_DISABLE_KEYCHAIN=1` | 容器使用文件型凭据存储 | + +子进程 HOME 由 DWS_HOME 指定,只透传所需环境。禁止把认证状态复制成多份,避免轮换令牌互相失效。 + +## 接口与生命周期 + +- `POST /api/v1/dws-login`:立即返回 starting,后台生成设备授权;同一浏览器管理员会话重复请求复用在途授权。 +- `GET /api/v1/dws-login/{id}`:读取本人发起的授权。 +- `DELETE /api/v1/dws-login/{id}`:取消并等待旧 CLI 退出,清除授权链接与用户码。 +- 上述接口均为管理员专用;授权绑定管理员及其登录会话,另一会话无法读取或取消。 +- 创建和取消要求同源操作意图;响应禁止缓存。仅允许 `https://login.dingtalk.com/oauth2/device/verify.htm` 官方链接。 +- 每次只运行一个授权,防止覆盖共享状态。服务重启会结束在途授权;页面提示重新发起。 +- CLI 成功退出后必须再次读到有效本地凭据才显示登录成功;真实目录访问另行检查。 + +## 验证边界 + +自动回归覆盖授权生成、成功后状态更新、目录访问失败与部分可用、取消与进程退出、过期、重试、跨管理员/会话隔离、同源限制、官方链接校验及元数据脱敏。 +真实本人授权需要管理员在钉钉官方页面确认;自动测试与生成真实授权链接不替代本人授权,也不证明其公司目录权限。 diff --git a/internal/dingtalkdiscovery/credentials.go b/internal/dingtalkdiscovery/credentials.go index c3ea3c4..dbdfda1 100644 --- a/internal/dingtalkdiscovery/credentials.go +++ b/internal/dingtalkdiscovery/credentials.go @@ -12,6 +12,9 @@ type CredentialStatus struct { RefreshTokenValid bool `json:"refresh_token_valid"` ExpiresAt string `json:"expires_at,omitempty"` RefreshExpiresAt string `json:"refresh_expires_at,omitempty"` + CorpName string `json:"corp_name,omitempty"` + UserName string `json:"user_name,omitempty"` + StatusKnown bool `json:"status_known"` } func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) { @@ -24,9 +27,12 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, RefreshTokenValid bool `json:"refresh_token_valid"` ExpiresAt string `json:"expires_at"` RefreshExpiresAt string `json:"refresh_expires_at"` + CorpName string `json:"corp_name"` + UserName string `json:"user_name"` + Reason string `json:"reason"` } if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil { return CredentialStatus{}, errors.New("invalid DWS credential status") } - return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil + return CredentialStatus{Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil } diff --git a/internal/dingtalkdiscovery/device_login.go b/internal/dingtalkdiscovery/device_login.go new file mode 100644 index 0000000..11a3a05 --- /dev/null +++ b/internal/dingtalkdiscovery/device_login.go @@ -0,0 +1,243 @@ +package dingtalkdiscovery + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" +) + +var ErrLoginBusy = errors.New("another DWS authorization is active") +var ErrLoginNotFound = errors.New("DWS authorization not found") + +// DeviceLoginView contains only the user-facing challenge. Tokens remain in the +// CLI's shared credential store; command output is never logged or returned. +type DeviceLoginView struct { + ID string `json:"id"` + State string `json:"state"` + VerificationURL string `json:"verification_url,omitempty"` + UserCode string `json:"user_code,omitempty"` + ExpiresAt time.Time `json:"expires_at"` + Error string `json:"error,omitempty"` +} + +type deviceLogin struct { + view DeviceLoginView + owner string + cancel context.CancelFunc + done chan struct{} +} + +type DeviceLoginManager struct { + ctx context.Context + runner ExecRunner + mu sync.Mutex + sessions map[string]*deviceLogin +} + +func NewDeviceLoginManager(ctx context.Context, runner ExecRunner) *DeviceLoginManager { + return &DeviceLoginManager{ctx: ctx, runner: runner, sessions: make(map[string]*deviceLogin)} +} + +func loginActive(state string) bool { + return state == "starting" || state == "waiting" || state == "verifying" +} + +func (m *DeviceLoginManager) Start(owner string) (DeviceLoginView, error) { + if owner == "" { + return DeviceLoginView{}, ErrLoginNotFound + } + m.mu.Lock() + defer m.mu.Unlock() + for id, s := range m.sessions { + if s.view.State == "cancelled" || s.view.State == "expired" { + select { + case <-s.done: + default: + return DeviceLoginView{}, ErrLoginBusy + } + } + if loginActive(s.view.State) { + if s.owner == owner { + return s.view, nil + } + return DeviceLoginView{}, ErrLoginBusy + } + if time.Since(s.view.ExpiresAt) > 30*time.Minute || len(m.sessions) >= 16 { + delete(m.sessions, id) + } + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return DeviceLoginView{}, err + } + ctx, cancel := context.WithTimeout(m.ctx, 20*time.Minute) + s := &deviceLogin{view: DeviceLoginView{ID: hex.EncodeToString(b[:]), State: "starting", ExpiresAt: time.Now().UTC().Add(20 * time.Minute)}, owner: owner, cancel: cancel, done: make(chan struct{})} + m.sessions[s.view.ID] = s + go m.run(ctx, s) + return s.view, nil +} + +func (m *DeviceLoginManager) Get(owner, id string) (DeviceLoginView, error) { + m.mu.Lock() + defer m.mu.Unlock() + s := m.sessions[id] + if s == nil || s.owner != owner { + return DeviceLoginView{}, ErrLoginNotFound + } + if loginActive(s.view.State) && !time.Now().Before(s.view.ExpiresAt) { + s.cancel() + finishLogin(s, "expired", "授权已过期,请重新发起。") + } + return s.view, nil +} + +func (m *DeviceLoginManager) Cancel(owner, id string) (DeviceLoginView, error) { + m.mu.Lock() + s := m.sessions[id] + if s == nil || s.owner != owner { + m.mu.Unlock() + return DeviceLoginView{}, ErrLoginNotFound + } + if loginActive(s.view.State) { + s.cancel() + finishLogin(s, "cancelled", "") + } + m.mu.Unlock() + // Do not acknowledge cancellation while the old CLI could still write tokens. + timer := time.NewTimer(7 * time.Second) + defer timer.Stop() + select { + case <-s.done: + case <-timer.C: + return DeviceLoginView{}, ErrLoginBusy + } + m.mu.Lock() + defer m.mu.Unlock() + return s.view, nil +} + +func finishLogin(s *deviceLogin, state, message string) { + s.view.State = state + s.view.Error = message + s.view.VerificationURL = "" + s.view.UserCode = "" +} + +var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`) +var challengeCode = regexp.MustCompile(`(?:授权码|User code|User Code)\s*[::]\s*([A-Za-z0-9-]{4,32})`) +var challengeExpiry = regexp.MustCompile(`(?:将在\s*|expires in\s*)([0-9]+)\s*(?:秒|seconds)`) + +func safeDeviceURL(raw string) bool { + u, err := url.Parse(raw) + return err == nil && u.Scheme == "https" && u.Host == "login.dingtalk.com" && u.User == nil && u.Fragment == "" && u.Path == "/oauth2/device/verify.htm" +} + +func (m *DeviceLoginManager) observe(s *deviceLogin, line string) { + line = strings.TrimSpace(ansiEscape.ReplaceAllString(line, "")) + m.mu.Lock() + defer m.mu.Unlock() + if !loginActive(s.view.State) { + return + } + if match := challengeCode.FindStringSubmatch(line); len(match) == 2 { + s.view.UserCode = match[1] + } + if match := challengeExpiry.FindStringSubmatch(line); len(match) == 2 { + seconds, _ := strconv.Atoi(match[1]) + if seconds > 0 && seconds <= 1800 { + s.view.ExpiresAt = time.Now().UTC().Add(time.Duration(seconds) * time.Second) + } + } + if safeDeviceURL(line) { + u, _ := url.Parse(line) + if s.view.VerificationURL == "" || u.Query().Get("user_code") != "" { + s.view.VerificationURL = line + } + } + if s.view.State == "starting" && s.view.UserCode != "" && s.view.VerificationURL != "" { + s.view.State = "waiting" + } + if strings.Contains(line, "Step 3:") { + s.view.State = "verifying" + } +} + +func (m *DeviceLoginManager) run(ctx context.Context, s *deviceLogin) { + defer close(s.done) + defer s.cancel() + command, err := m.runner.command(ctx, "auth", "login", "--device", "--no-browser", "--format", "json") + if err != nil { + m.failed(s, "DWS 登录程序不可用,请联系管理员检查服务配置。") + return + } + command.Env = append(command.Env, "DWS_LANG=zh", "NO_COLOR=1", "TERM=dumb") + command.Stdout = io.Discard + stderr, err := command.StderrPipe() + if err != nil { + m.failed(s, "无法启动 DWS 授权,请重试。") + return + } + if err = command.Start(); err != nil { + m.failed(s, "无法启动 DWS 授权,请检查凭据目录权限。") + return + } + scanner := bufio.NewScanner(stderr) + scanner.Buffer(make([]byte, 4096), 64*1024) + for scanner.Scan() { + m.observe(s, scanner.Text()) + } + if scanner.Err() != nil { + s.cancel() + } + err = command.Wait() + m.mu.Lock() + active := loginActive(s.view.State) + m.mu.Unlock() + if !active { + return + } + if err != nil || ctx.Err() != nil { + m.mu.Lock() + defer m.mu.Unlock() + if !loginActive(s.view.State) { + return + } + if errors.Is(ctx.Err(), context.DeadlineExceeded) || !time.Now().Before(s.view.ExpiresAt) { + finishLogin(s, "expired", "授权已过期,请重新发起。") + } else { + finishLogin(s, "failed", "DWS 授权未完成,请重试;若组织未开通 CLI 数据权限,请联系钉钉管理员。") + } + return + } + // A process exit alone is not proof that usable credentials were persisted. + checkCtx, cancel := context.WithTimeout(m.ctx, 5*time.Second) + defer cancel() + status, statusErr := ReadCredentialStatus(checkCtx, m.runner) + m.mu.Lock() + defer m.mu.Unlock() + if !loginActive(s.view.State) { + return + } + if statusErr != nil || !status.Authenticated || !status.RefreshTokenValid || !status.StatusKnown { + finishLogin(s, "failed", "授权结束,但未读到有效 DWS 凭据,请重新授权。") + } else { + finishLogin(s, "succeeded", "") + } +} + +func (m *DeviceLoginManager) failed(s *deviceLogin, message string) { + m.mu.Lock() + defer m.mu.Unlock() + if loginActive(s.view.State) { + finishLogin(s, "failed", message) + } +} diff --git a/internal/dingtalkdiscovery/device_login_test.go b/internal/dingtalkdiscovery/device_login_test.go new file mode 100644 index 0000000..eaea06e --- /dev/null +++ b/internal/dingtalkdiscovery/device_login_test.go @@ -0,0 +1,160 @@ +package dingtalkdiscovery + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func deviceFixture(t *testing.T) (*DeviceLoginManager, string) { + t.Helper() + root := t.TempDir() + binary := filepath.Join(root, "dws") + script := `#!/usr/bin/env python3 +import sys,time,pathlib,json,os +root=pathlib.Path(` + strconv.Quote(root) + `) +a=sys.argv[1:] +if a==['auth','login','--device','--no-browser','--format','json']: + (root/'pid').write_text(str(os.getpid())) + print(' 授权码: TEST-CODE',file=sys.stderr,flush=True) + print('授权码将在 900 秒后过期。',file=sys.stderr,flush=True) + print('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',file=sys.stderr,flush=True) + print('https://login.dingtalk.com/oauth2/device/verify.htm',file=sys.stderr,flush=True) + print('never-expose-this-marker',file=sys.stderr,flush=True) + while not (root/'finish').exists(): time.sleep(.01) + if (root/'fail').exists(): sys.exit(1) +elif a==['auth','status','--readonly','--format','json']: + print(json.dumps({'authenticated':not (root/'invalid').exists(),'refresh_token_valid':True,'corp_name':'测试组织','user_name':'测试账号','access_token':'never-expose-this-marker'})) +else: sys.exit(9) +` + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + return NewDeviceLoginManager(ctx, ExecRunner{Binary: binary}), root +} +func awaitDevice(t *testing.T, m *DeviceLoginManager, id, state string) DeviceLoginView { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + v, e := m.Get("owner", id) + if e != nil { + t.Fatal(e) + } + if v.State == state { + return v + } + time.Sleep(10 * time.Millisecond) + } + v, _ := m.Get("owner", id) + t.Fatalf("state=%s want=%s error=%s", v.State, state, v.Error) + return v +} +func TestDeviceLoginUsesOfficialChallengeAndSharedCLI(t *testing.T) { + m, root := deviceFixture(t) + initial, err := m.Start("owner") + if err != nil { + t.Fatal(err) + } + if initial.State != "starting" { + t.Fatal(initial) + } + waiting := awaitDevice(t, m, initial.ID, "waiting") + if waiting.UserCode != "TEST-CODE" || !strings.Contains(waiting.VerificationURL, "user_code=TEST-CODE") { + t.Fatal("missing complete official challenge") + } + if _, err = m.Start("other"); !errors.Is(err, ErrLoginBusy) { + t.Fatal("parallel logins may overwrite shared credentials") + } + duplicate, _ := m.Start("owner") + if duplicate.ID != initial.ID { + t.Fatal("duplicate start was not idempotent") + } + if _, err = m.Get("other", initial.ID); !errors.Is(err, ErrLoginNotFound) { + t.Fatal("challenge leaked to another owner") + } + if _, err = m.Cancel("other", initial.ID); !errors.Is(err, ErrLoginNotFound) { + t.Fatal("foreign cancellation permitted") + } + if err = os.WriteFile(filepath.Join(root, "finish"), nil, 0600); err != nil { + t.Fatal(err) + } + done := awaitDevice(t, m, initial.ID, "succeeded") + raw, _ := json.Marshal(done) + if done.UserCode != "" || done.VerificationURL != "" || strings.Contains(string(raw), "never-expose") { + t.Fatal("completed session retained sensitive output") + } +} +func TestDeviceLoginCancellationClearsChallenge(t *testing.T) { + m, root := deviceFixture(t) + v, _ := m.Start("owner") + awaitDevice(t, m, v.ID, "waiting") + closed, err := m.Cancel("owner", v.ID) + if err != nil || closed.State != "cancelled" || closed.UserCode != "" || closed.VerificationURL != "" { + t.Fatal(closed, err) + } + pidBytes, err := os.ReadFile(filepath.Join(root, "pid")) + if err != nil { + t.Fatal(err) + } + pid, _ := strconv.Atoi(string(pidBytes)) + if syscall.Kill(pid, 0) == nil { + t.Fatal("cancel returned while credential-writing process was still running") + } + again, _ := m.Get("owner", v.ID) + if again.State != "cancelled" { + t.Fatal("late process exit overwrote cancellation") + } +} +func TestDeviceLoginRejectsExitWithoutPersistedCredentials(t *testing.T) { + m, root := deviceFixture(t) + os.WriteFile(filepath.Join(root, "invalid"), nil, 0600) + os.WriteFile(filepath.Join(root, "finish"), nil, 0600) + v, _ := m.Start("owner") + done := awaitDevice(t, m, v.ID, "failed") + if !strings.Contains(done.Error, "未读到有效") { + t.Fatal("successful exit was treated as authenticated") + } +} +func TestDeviceLoginFailureIsRedactedAndRetryable(t *testing.T) { + m, root := deviceFixture(t) + os.WriteFile(filepath.Join(root, "fail"), nil, 0600) + os.WriteFile(filepath.Join(root, "finish"), nil, 0600) + v, _ := m.Start("owner") + done := awaitDevice(t, m, v.ID, "failed") + if strings.Contains(done.Error, "never-expose") || done.Error == "" { + t.Fatal("raw CLI output or missing error") + } + retry, e := m.Start("owner") + if e != nil || retry.ID == v.ID { + t.Fatal("cannot retry failed authorization") + } +} +func TestDeviceChallengeRejectsUntrustedLinksAndExpires(t *testing.T) { + m, root := deviceFixture(t) + _ = root + s := &deviceLogin{view: DeviceLoginView{State: "starting", ExpiresAt: time.Now().Add(time.Minute)}, cancel: func() {}} + m.observe(s, "授权码: TEST-CODE") + for _, link := range []string{"http://login.dingtalk.com/oauth2/device/verify.htm", "https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm", "https://user:pass@login.dingtalk.com/oauth2/device/verify.htm", "javascript:alert(1)", "https://login.dingtalk.com/other"} { + m.observe(s, link) + } + if s.view.State != "starting" || s.view.VerificationURL != "" { + t.Fatal("untrusted link accepted") + } + s.view.ID = "test-expired" + s.owner = "owner" + s.view.ExpiresAt = time.Now().Add(-time.Second) + m.sessions[s.view.ID] = s + got, e := m.Get("owner", s.view.ID) + if e != nil || got.State != "expired" || got.UserCode != "" { + t.Fatal("expired challenge retained") + } +} diff --git a/internal/dingtalkdiscovery/exec_runner.go b/internal/dingtalkdiscovery/exec_runner.go index 7f75f88..7bc7324 100644 --- a/internal/dingtalkdiscovery/exec_runner.go +++ b/internal/dingtalkdiscovery/exec_runner.go @@ -19,8 +19,8 @@ type ExecRunner struct { Timeout time.Duration } -// RunDWS 运行 `dws ` 并返回 stdout。 -func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) { +// command keeps device login and source reads on one credential environment. +func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, error) { binary := r.Binary if binary == "" { binary = os.Getenv("DWS_BIN") @@ -32,14 +32,24 @@ func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) } binary = found } + command := exec.CommandContext(ctx, binary, args...) + command.Env = dwsEnv() + command.WaitDelay = 2 * time.Second + return command, nil +} + +// RunDWS uses the same executable and credential environment as device login. +func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) { timeout := r.Timeout if timeout <= 0 { timeout = 25 * time.Second } runCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() - command := exec.CommandContext(runCtx, binary, args...) - command.Env = dwsEnv() + command, err := r.command(runCtx, args...) + if err != nil { + return nil, err + } var stdout, stderr bytes.Buffer command.Stdout = &stdout command.Stderr = &stderr diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go index 9bea0fd..468f8ba 100644 --- a/internal/httpapi/auth.go +++ b/internal/httpapi/auth.go @@ -107,6 +107,9 @@ func classifyRole(method, path string) string { if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") { return roleAdmin } + if strings.HasPrefix(path, "/api/v1/dws-login") { + return roleAdmin + } if method == http.MethodGet { return roleViewer } diff --git a/internal/httpapi/dws_login.go b/internal/httpapi/dws_login.go new file mode 100644 index 0000000..520ee76 --- /dev/null +++ b/internal/httpapi/dws_login.go @@ -0,0 +1,74 @@ +package httpapi + +import ( + "errors" + "log" + "net/http" + "net/url" + + "knowledge-governance/internal/dingtalkdiscovery" +) + +func registerDWSLoginRoutes(mux *http.ServeMux, config Config) { + mux.HandleFunc("POST /api/v1/dws-login", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "start") }) + mux.HandleFunc("GET /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "get") }) + mux.HandleFunc("DELETE /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "cancel") }) +} + +func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, action string) { + w.Header().Set("Cache-Control", "no-store") + identity, ok := requireSessionIdentity(w, r) + if !ok { + return + } + if identity.Role != roleAdmin { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "需要管理员身份才能管理 DWS 授权"}) + return + } + if action != "get" { + originOK := true + if raw := r.Header.Get("Origin"); raw != "" { + origin, err := url.Parse(raw) + originOK = err == nil && origin.Host == r.Host && (origin.Scheme == "http" || origin.Scheme == "https") + } + if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != "dws-login" { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "请从本平台的数据源配置页发起授权"}) + return + } + } + if config.DWSLogin == nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "DWS 登录服务未接通,请联系管理员"}) + return + } + // Bind the challenge to this authenticated administrator and browser session. + owner := identity.UserID + "/" + identity.SessionID + var view dingtalkdiscovery.DeviceLoginView + var err error + switch action { + case "start": + view, err = config.DWSLogin.Start(owner) + case "get": + view, err = config.DWSLogin.Get(owner, r.PathValue("id")) + case "cancel": + view, err = config.DWSLogin.Cancel(owner, r.PathValue("id")) + } + if err != nil { + switch { + case errors.Is(err, dingtalkdiscovery.ErrLoginNotFound): + writeJSON(w, http.StatusNotFound, map[string]string{"error": "授权会话已结束或服务已重启,请重新发起"}) + case errors.Is(err, dingtalkdiscovery.ErrLoginBusy): + writeJSON(w, http.StatusConflict, map[string]string{"error": "另一位管理员正在授权,请稍后再试"}) + default: + writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法发起 DWS 授权,请重试"}) + } + return + } + if action != "get" { + log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username) + } + status := http.StatusOK + if action == "start" { + status = http.StatusAccepted + } + writeJSON(w, status, map[string]any{"data": view}) +} diff --git a/internal/httpapi/dws_login_test.go b/internal/httpapi/dws_login_test.go new file mode 100644 index 0000000..675544e --- /dev/null +++ b/internal/httpapi/dws_login_test.go @@ -0,0 +1,82 @@ +package httpapi + +import ( + "context" + "encoding/json" + "knowledge-governance/internal/dingtalkdiscovery" + "net/http" + "net/http/httptest" + "testing" +) + +func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"}) + h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager}) + if err != nil { + t.Fatal(err) + } + call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, nil) + if role != "" { + r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session})) + } + r.Header.Set("Origin", origin) + r.Header.Set("X-Governance-Action", intent) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + for _, role := range []string{"", roleViewer, roleEngineer} { + w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login") + if w.Code != 401 && w.Code != 403 { + t.Fatalf("role=%q status=%d", role, w.Code) + } + } + for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} { + w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1]) + if w.Code != 403 { + t.Fatalf("origin/intent not enforced: %d", w.Code) + } + } + w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login") + if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("start=%d body=%s", w.Code, w.Body) + } + var body struct { + Data dingtalkdiscovery.DeviceLoginView `json:"data"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" { + t.Fatal("missing session", err) + } + path := "/api/v1/dws-login/" + body.Data.ID + for _, method := range []string{"GET", "DELETE"} { + w = call(method, path, roleAdmin, "other-session", "", "dws-login") + if w.Code != 404 { + t.Fatalf("foreign session %s=%d", method, w.Code) + } + w = call(method, path, roleEngineer, "s1", "", "dws-login") + if w.Code != 403 { + t.Fatalf("engineer %s=%d", method, w.Code) + } + } + w = call("GET", path, roleAdmin, "s1", "", "") + if w.Code != 200 { + t.Fatalf("get=%d", w.Code) + } + w = call("DELETE", path, roleAdmin, "s1", "", "dws-login") + if w.Code != 200 { + t.Fatalf("cancel=%d", w.Code) + } +} + +func TestDWSLoginRoutesAreAdminOnly(t *testing.T) { + for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} { + for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} { + if got := classifyRole(method, path); got != roleAdmin { + t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got) + } + } + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 862f09c..7d0ab02 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -15,6 +15,7 @@ import ( "time" "knowledge-governance/internal/backuphost" + "knowledge-governance/internal/dingtalkdiscovery" "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" "knowledge-governance/internal/monitoring" @@ -222,6 +223,7 @@ type Config struct { DingtalkSources dingtalkSourcesLister // DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。 DingtalkDocuments dingtalkDocLister + DWSLogin *dingtalkdiscovery.DeviceLoginManager NewID func() (string, error) Auth *AuthConfig } @@ -256,6 +258,7 @@ func NewHandler(config Config) (http.Handler, error) { config.NewID = newID } mux := http.NewServeMux() + registerDWSLoginRoutes(mux, config) registerQAAIRoutes(mux, config) mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) }) mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) }) diff --git a/web/src/DWSAccount.mounted.test.tsx b/web/src/DWSAccount.mounted.test.tsx new file mode 100644 index 0000000..cc66cdd --- /dev/null +++ b/web/src/DWSAccount.mounted.test.tsx @@ -0,0 +1,167 @@ +// @vitest-environment jsdom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { DWSAccount } from './DWSAccount' +const id = 'a'.repeat(32) +const session = { + id, + state: 'waiting', + verification_url: 'https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE', + user_code: 'TEST-CODE', + expires_at: '2099-01-01T01:00:00Z', +} +const json = (data: unknown, status = 200) => new Response(JSON.stringify({ data }), { status }) +let root: Root +let container: HTMLDivElement +let fetcher: ReturnType Promise>> +const flush = async () => { + await act(async () => { + await Promise.resolve() + }) +} +const click = async (label: string) => { + const button = Array.from(container.querySelectorAll('button')).find((x) => x.textContent === label) + expect(button, label).toBeTruthy() + await act(async () => button!.click()) +} +beforeEach(() => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + vi.useFakeTimers() + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + fetcher = vi.fn((path: string, init?: RequestInit) => { + if (path.endsWith('credential-status')) + return Promise.resolve(json({ authenticated: false, refresh_token_valid: false })) + if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202)) + if (path.startsWith('/api/v1/dws-login/')) + return Promise.resolve(json({ ...session, state: init?.method === 'DELETE' ? 'cancelled' : 'waiting' })) + if (path.endsWith('/available')) + return Promise.resolve(json({ knowledge_bases: [], drive_spaces: [], fetched_at: '2026-11-17T09:00:00Z' })) + throw new Error(`unexpected ${path}`) + }) + vi.stubGlobal('fetch', fetcher) +}) +afterEach(async () => { + await act(async () => root.unmount()) + container.remove() + vi.useRealTimers() + vi.unstubAllGlobals() +}) +const mount = async () => { + await act(async () => root.render()) + await flush() +} + +describe('DWS device authorization', () => { + it('opens the official challenge and cancellation removes it', async () => { + await mount() + await click('登录授权') + expect(container.querySelector('[role="dialog"]')).not.toBeNull() + expect(container.querySelector('a')?.href).toBe(session.verification_url) + expect(container.textContent).toContain('TEST-CODE') + await click('取消授权') + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true) + }) + it('refreshes identity after login and independently reports failed directory access', async () => { + let authorized = false + fetcher.mockImplementation((path: string, init?: RequestInit) => { + if (path.endsWith('credential-status')) + return Promise.resolve( + json({ + authenticated: authorized, + refresh_token_valid: authorized, + corp_name: '测试组织', + user_name: '测试账号', + }) + ) + if (path === '/api/v1/dws-login') return Promise.resolve(json(session, 202)) + if (path.endsWith('/available')) + return Promise.resolve(new Response(JSON.stringify({ error: '目录权限不足' }), { status: 503 })) + if (init?.method === 'DELETE') return Promise.resolve(json({ ...session, state: 'cancelled' })) + authorized = true + return Promise.resolve(json({ ...session, state: 'succeeded', verification_url: '', user_code: '' })) + }) + await mount() + await click('登录授权') + await act(async () => vi.advanceTimersByTimeAsync(1500)) + await flush() + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(container.textContent).toContain('DWS 登录成功') + expect(container.textContent).toContain('测试账号 · 测试组织') + expect(container.textContent).toContain('目录连接检查未通过:目录权限不足') + expect(container.textContent).not.toContain('目录连接正常') + }) + it('reports partial directory access without claiming full connection success', async () => { + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path.endsWith('/available') + ? Promise.resolve( + json({ + knowledge_bases: [{}], + drive_spaces: [], + knowledge_notice: '个人知识库权限不足', + fetched_at: '2026-11-17T09:00:00Z', + }) + ) + : fallback(path, init) + ) + await mount() + await click('检查连接') + expect(container.textContent).toContain('目录部分可用') + expect(container.textContent).toContain('个人知识库权限不足') + expect(container.textContent).not.toContain('目录连接正常') + expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false) + }) + it('shows backend startup errors and provides retry', async () => { + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path === '/api/v1/dws-login' + ? Promise.resolve(new Response(JSON.stringify({ error: '另一位管理员正在授权' }), { status: 409 })) + : fallback(path, init) + ) + await mount() + await click('登录授权') + expect(container.textContent).toContain('另一位管理员正在授权') + expect(Array.from(container.querySelectorAll('button')).some((x) => x.textContent === '重试')).toBe(true) + }) + it('cancels a session returned after its dialog was closed during startup', async () => { + let resolve!: (response: Response) => void + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path === '/api/v1/dws-login' + ? new Promise((done) => { + resolve = done + }) + : fallback(path, init) + ) + await mount() + await click('登录授权') + await click('取消授权') + await act(async () => resolve(json(session, 202))) + await flush() + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(fetcher.mock.calls.some(([path, init]) => path.endsWith(id) && init?.method === 'DELETE')).toBe(true) + }) + it('does not reopen a cancelled dialog when a late poll succeeds', async () => { + let resolve!: (response: Response) => void + const fallback = fetcher.getMockImplementation()! + fetcher.mockImplementation((path: string, init?: RequestInit) => + path.endsWith(id) && init?.method === 'GET' + ? new Promise((done) => { + resolve = done + }) + : fallback(path, init) + ) + await mount() + await click('登录授权') + await act(async () => vi.advanceTimersByTimeAsync(1500)) + await click('取消授权') + await act(async () => resolve(json({ ...session, state: 'succeeded' }))) + await flush() + expect(container.querySelector('[role="dialog"]')).toBeNull() + expect(container.textContent).not.toContain('DWS 登录成功') + }) +}) diff --git a/web/src/DWSAccount.test.tsx b/web/src/DWSAccount.test.tsx new file mode 100644 index 0000000..2fd6ffc --- /dev/null +++ b/web/src/DWSAccount.test.tsx @@ -0,0 +1,12 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { DingtalkAccountStatus } from './SourceManagement' + +describe('DWS account entry', () => { + it('offers device login and a separate connection check beside account status', () => { + const html = renderToStaticMarkup() + expect(html).toContain('登录授权') + expect(html).toContain('检查连接') + expect(html).not.toContain('扫码刷新会话') + }) +}) diff --git a/web/src/DWSAccount.tsx b/web/src/DWSAccount.tsx new file mode 100644 index 0000000..5456079 --- /dev/null +++ b/web/src/DWSAccount.tsx @@ -0,0 +1,286 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + cancelDWSLogin, + checkDWSConnection, + dwsLoginActive, + fetchDWSCredentials, + fetchDWSLogin, + startDWSLogin, +} from './dwsLogin' +import type { DWSCredentials, DWSLogin } from './dwsLogin' + +const messageOf = (cause: unknown) => (cause instanceof Error ? cause.message : '请求失败,请重试') +const moment = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false }) + +export function DWSAccount() { + const [credentials, setCredentials] = useState(null) + const [loading, setLoading] = useState(true) + const [error, setError] = useState('') + const [notice, setNotice] = useState('') + const [connection, setConnection] = useState> | null>(null) + const [checking, setChecking] = useState(false) + const [session, setSession] = useState(null) + const [open, setOpen] = useState(false) + const [starting, setStarting] = useState(false) + const [loginError, setLoginError] = useState('') + const id = useRef('') + const generation = useRef(0) + const mounted = useRef(false) + const handled = useRef('') + const action = useRef(null) + const checkAction = useRef(null) + + useEffect(() => { + mounted.current = true + const controller = new AbortController() + void fetchDWSCredentials(controller.signal) + .then(setCredentials) + .catch((cause) => { + if (!controller.signal.aborted) setError(messageOf(cause)) + }) + .finally(() => { + if (!controller.signal.aborted) setLoading(false) + }) + return () => { + mounted.current = false + controller.abort() + action.current?.abort() + checkAction.current?.abort() + generation.current++ + if (id.current) void cancelDWSLogin(id.current).catch(() => undefined) + } + }, []) + + const check = useCallback(async () => { + checkAction.current?.abort() + const controller = new AbortController() + checkAction.current = controller + setChecking(true) + setConnection(null) + setError('') + try { + const result = await checkDWSConnection(controller.signal) + const fresh = await fetchDWSCredentials(controller.signal) + if (!controller.signal.aborted && mounted.current) { + setConnection(result) + setCredentials(fresh) + } + } catch (cause) { + if (!controller.signal.aborted && mounted.current) setError(`目录连接检查未通过:${messageOf(cause)}`) + } finally { + if (!controller.signal.aborted && mounted.current) setChecking(false) + } + }, []) + + const start = async () => { + const current = ++generation.current + action.current?.abort() + checkAction.current?.abort() + setChecking(false) + const controller = new AbortController() + action.current = controller + setOpen(true) + setStarting(true) + setSession(null) + setLoginError('') + setNotice('') + setConnection(null) + setError('') + try { + const next = await startDWSLogin(controller.signal) + if (!mounted.current || current !== generation.current) { + void cancelDWSLogin(next.id).catch(() => undefined) + return + } + id.current = next.id + setSession(next) + } catch (cause) { + if (mounted.current && current === generation.current) setLoginError(messageOf(cause)) + } finally { + if (mounted.current && current === generation.current) setStarting(false) + } + } + + const close = async () => { + const current = generation.current + const sessionID = id.current + setLoginError('') + if (!sessionID && starting) { + // Keep the POST alive so its returned session can be cancelled by ID. + ++generation.current + setOpen(false) + setStarting(false) + return + } + if (sessionID && session && dwsLoginActive(session.state)) { + try { + await cancelDWSLogin(sessionID) + } catch (cause) { + if (mounted.current && generation.current === current) setLoginError(`取消未完成:${messageOf(cause)}`) + return + } + } + if (mounted.current && generation.current === current) { + ++generation.current + id.current = '' + setOpen(false) + setSession(null) + } + } + + useEffect(() => { + if (!session || !dwsLoginActive(session.state) || loginError) return + const controller = new AbortController() + const current = generation.current + const timer = window.setTimeout(() => { + void fetchDWSLogin(session.id, controller.signal) + .then((next) => { + if (!controller.signal.aborted && current === generation.current) setSession(next) + }) + .catch((cause) => { + if (!controller.signal.aborted && current === generation.current) setLoginError(messageOf(cause)) + }) + }, 1500) + return () => { + window.clearTimeout(timer) + controller.abort() + } + }, [session, loginError]) + + useEffect(() => { + if (session?.state !== 'succeeded' || handled.current === session.id) return + handled.current = session.id + const current = generation.current + id.current = '' + setOpen(false) + setNotice('DWS 登录成功,正在检查目录连接…') + void fetchDWSCredentials() + .then((fresh) => { + if (!mounted.current || current !== generation.current) return + setCredentials(fresh) + setNotice('DWS 登录成功') + void check() + }) + .catch((cause) => { + if (mounted.current && current === generation.current) setError(`授权成功,状态刷新失败:${messageOf(cause)}`) + }) + }, [session, check]) + + const status = loading + ? '读取中…' + : error && !credentials + ? '状态读取失败' + : !credentials?.status_known + ? '登录状态待核验' + : !credentials.authenticated + ? '未登录' + : credentials.refresh_token_valid + ? '已登录' + : '凭证需更新' + const busy = starting || Boolean(session && dwsLoginActive(session.state)) + const labels: Record = { + starting: '正在生成授权入口…', + waiting: '请打开钉钉授权页,确认本次登录。完成后此页会自动更新。', + verifying: '已收到授权,正在验证并保存登录状态…', + succeeded: '登录成功', + expired: '授权已过期,请重新发起。', + failed: '授权未完成,请重试。', + cancelled: '授权已取消。', + } + return ( +
+
+
+ 钉钉账号(DWS) · {status} + {credentials?.authenticated ? ( +
+ {[credentials.user_name, credentials.corp_name].filter(Boolean).join(' · ') || '账号信息暂未返回'} +
+ ) : null} + {credentials?.authenticated && credentials.refresh_expires_at ? ( + 授权有效期至 {moment(credentials.refresh_expires_at)} + ) : null} +
+
+ + +
+
+ 所有钉钉来源共用此账号。登录后检查知识库与钉盘的实际访问权限。 + {notice ? ( +

+ {notice} +

+ ) : null} + {error ? ( +

+ {error} +

+ ) : null} + {connection ? ( +
+

+ {connection.notices.length ? '目录部分可用' : '目录连接正常'}:{connection.message} · 检查于{' '} + {moment(connection.checkedAt)} +

+ {connection.notices.map((value) => ( +

+ {value} +

+ ))} +
+ ) : null} + {open ? ( +
+
+

DWS 登录授权

+

{starting ? '正在生成授权入口…' : session ? labels[session.state] : '授权入口生成失败'}

+ {session?.state === 'waiting' && session.verification_url ? ( + <> + + 打开钉钉授权页 + +

+ 若授权页要求输入授权码:{session.user_code} +

+ 本次授权有效期至 {moment(session.expires_at)} + + ) : null} + {session?.error ? ( +

+ {session.error} +

+ ) : null} + {loginError ? ( +

+ {loginError} +

+ ) : null} +
+ {session && !dwsLoginActive(session.state) ? ( + + ) : null} + {loginError && session && dwsLoginActive(session.state) ? ( + + ) : null} + {!starting && !session ? : null} + +
+
+
+ ) : null} +
+ ) +} diff --git a/web/src/SourceManagement.css b/web/src/SourceManagement.css index 6bde915..2dc87fb 100644 --- a/web/src/SourceManagement.css +++ b/web/src/SourceManagement.css @@ -23,9 +23,32 @@ margin: 0 0 14px; font-size: 12px; } -.source-account > button { - padding: 5px 0; - color: var(--ink-mute); +.dws-account-heading { + display: flex; + align-items: flex-start; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; + margin-bottom: 8px; +} +.dws-account-heading strong { + display: block; + margin-bottom: 6px; + font-size: 14px; +} +.dws-login-card { + width: min(480px, calc(100vw - 40px)); +} +.dws-authorize-link { + display: inline-block; + margin: 8px 0; +} +.dws-user-code { + font-size: 18px; + letter-spacing: 2px; +} +.dws-login-card .row-actions { + margin-top: 20px; } .source-account-detail { padding: 12px 16px; diff --git a/web/src/SourceManagement.tsx b/web/src/SourceManagement.tsx index 5b30129..17c9a51 100644 --- a/web/src/SourceManagement.tsx +++ b/web/src/SourceManagement.tsx @@ -21,42 +21,7 @@ const choices = [ ] const errorText = (error: unknown) => (error instanceof Error ? error.message : '操作失败,请重试') -export function DingtalkAccountStatus() { - const [status, setStatus] = useState('读取中…') - const [expires, setExpires] = useState('') - useEffect(() => { - const controller = new AbortController() - void fetch('/api/v1/dingtalk-spaces/credential-status', { - headers: { Accept: 'application/json' }, - signal: controller.signal, - }) - .then(async (response) => { - if (!response.ok) throw new Error('读取失败') - const value = await response.json() - const data = value.data - if (!data || typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean') - throw new Error('状态格式错误') - if (controller.signal.aborted) return - setStatus(!data.authenticated ? '未登录' : data.refresh_token_valid ? '已登录' : '凭证需更新') - setExpires(data.authenticated && typeof data.refresh_expires_at === 'string' ? data.refresh_expires_at : '') - }) - .catch(() => { - if (!controller.signal.aborted) setStatus('状态读取失败') - }) - return () => controller.abort() - }, []) - return ( -
- DWS 凭证 · {status} - {expires ? ( - · 续期凭证有效期至 {new Date(expires).toLocaleString('zh-CN', { hour12: false })} - ) : null} -
- 仅显示本地凭证状态,不检测目录权限或业务接口。 -
-
- ) -} +export { DWSAccount as DingtalkAccountStatus } from './DWSAccount' export function SourceSettingsCard({ connection, diff --git a/web/src/SystemSettings.test.tsx b/web/src/SystemSettings.test.tsx index c0f6b3e..78a4287 100644 --- a/web/src/SystemSettings.test.tsx +++ b/web/src/SystemSettings.test.tsx @@ -574,7 +574,9 @@ describe('SystemSettingsView 数据源配置的默认清单', () => { expect(html).toContain('aria-expanded="false"') expect(html).toContain('仅手动刷新') expect(html).toContain('数据源设置审计') - expect((html.match(/DWS 凭证 ·/g) ?? []).length).toBe(1) + expect((html.match(/aria-label="钉钉账号(DWS)"/g) ?? []).length).toBe(1) + expect(html).toContain('登录授权') + expect(html).toContain('检查连接') for (const removed of ['+ 新增钉钉知识库', '文件格式筛选']) expect(html).not.toContain(removed) // 文档工程师看不到添加向导与「去掉来源」:两者都是管理员动作。 const engineer = view('engineer') diff --git a/web/src/dwsLogin.test.ts b/web/src/dwsLogin.test.ts new file mode 100644 index 0000000..be593ab --- /dev/null +++ b/web/src/dwsLogin.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { checkDWSConnection, fetchDWSCredentials, startDWSLogin, validDWSAuthorizationURL } from './dwsLogin' +afterEach(() => vi.unstubAllGlobals()) +describe('DWS transport boundaries', () => { + it('accepts only the official device verification URL', () => { + expect(validDWSAuthorizationURL('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST')).toBe(true) + for (const value of [ + 'javascript:alert(1)', + 'http://login.dingtalk.com/oauth2/device/verify.htm', + 'https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm', + 'https://login.dingtalk.com/other', + ]) + expect(validDWSAuthorizationURL(value)).toBe(false) + }) + it('keeps backend errors from a real single-use response', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'DWS 登录服务未接通' }), { status: 503 })) + ) + await expect(startDWSLogin()).rejects.toThrow('DWS 登录服务未接通') + }) + it('rejects missing or hostile session data', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + id: 'a'.repeat(32), + state: 'waiting', + expires_at: '2099-01-01T00:00:00Z', + verification_url: 'https://evil.invalid/', + }, + }) + ) + ) + ) + await expect(startDWSLogin()).rejects.toThrow('不是钉钉官方地址') + }) + it('does not treat an invalid directory envelope as a successful empty result', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: {} })))) + await expect(checkDWSConnection()).rejects.toThrow('未取得有效目录检查结果') + }) + it('returns only safe credential metadata', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + data: { + authenticated: true, + refresh_token_valid: true, + corp_name: '测试组织', + user_name: '测试账号', + access_token: 'do-not-return', + }, + }) + ) + ) + ) + const result = await fetchDWSCredentials() + expect(result.corp_name).toBe('测试组织') + expect(JSON.stringify(result)).not.toContain('do-not-return') + }) +}) diff --git a/web/src/dwsLogin.ts b/web/src/dwsLogin.ts new file mode 100644 index 0000000..4aa4c4d --- /dev/null +++ b/web/src/dwsLogin.ts @@ -0,0 +1,101 @@ +export interface DWSCredentials { + authenticated: boolean + refresh_token_valid: boolean + status_known: boolean + corp_name: string + user_name: string + refresh_expires_at: string +} +export type DWSLoginState = 'starting' | 'waiting' | 'verifying' | 'succeeded' | 'failed' | 'expired' | 'cancelled' +export interface DWSLogin { + id: string + state: DWSLoginState + verification_url: string + user_code: string + expires_at: string + error: string +} +const states = new Set(['starting', 'waiting', 'verifying', 'succeeded', 'failed', 'expired', 'cancelled']) +export const dwsLoginActive = (state: DWSLoginState) => ['starting', 'waiting', 'verifying'].includes(state) +const record = (value: unknown): value is Record => typeof value === 'object' && value !== null +const text = (value: unknown) => (typeof value === 'string' ? value : '') +export function validDWSAuthorizationURL(value: string) { + try { + const url = new URL(value) + return ( + url.protocol === 'https:' && + url.host === 'login.dingtalk.com' && + !url.username && + !url.password && + !url.hash && + url.pathname === '/oauth2/device/verify.htm' + ) + } catch { + return false + } +} +async function request(path: string, signal?: AbortSignal, method = 'GET') { + const response = await fetch(path, { + method, + signal, + headers: { Accept: 'application/json', ...(method !== 'GET' ? { 'X-Governance-Action': 'dws-login' } : {}) }, + }) + const payload: unknown = await response.json().catch(() => null) + if (!response.ok) + throw new Error( + record(payload) && typeof payload.error === 'string' ? payload.error : `DWS 请求失败(HTTP ${response.status})` + ) + if (!record(payload) || !record(payload.data)) throw new Error('DWS 返回的数据格式不正确,请重试') + return payload.data +} +export async function fetchDWSCredentials(signal?: AbortSignal): Promise { + const data = await request('/api/v1/dingtalk-spaces/credential-status', signal) + if (typeof data.authenticated !== 'boolean' || typeof data.refresh_token_valid !== 'boolean') + throw new Error('无法判断 DWS 登录状态') + return { + authenticated: data.authenticated, + refresh_token_valid: data.refresh_token_valid, + status_known: data.status_known !== false, + corp_name: text(data.corp_name), + user_name: text(data.user_name), + refresh_expires_at: text(data.refresh_expires_at), + } +} +function parseLogin(data: Record): DWSLogin { + if ( + typeof data.id !== 'string' || + !/^[a-f0-9]{32}$/.test(data.id) || + typeof data.state !== 'string' || + !states.has(data.state) || + !Number.isFinite(Date.parse(text(data.expires_at))) + ) + throw new Error('授权会话格式不正确,请重新发起') + const url = text(data.verification_url) + if (url && !validDWSAuthorizationURL(url)) throw new Error('授权链接不是钉钉官方地址,请重新发起') + return { + id: data.id, + state: data.state as DWSLoginState, + verification_url: url, + user_code: text(data.user_code), + expires_at: text(data.expires_at), + error: text(data.error), + } +} +export async function startDWSLogin(signal?: AbortSignal) { + return parseLogin(await request('/api/v1/dws-login', signal, 'POST')) +} +export async function fetchDWSLogin(id: string, signal?: AbortSignal) { + return parseLogin(await request(`/api/v1/dws-login/${encodeURIComponent(id)}`, signal)) +} +export async function cancelDWSLogin(id: string) { + return parseLogin(await request(`/api/v1/dws-login/${encodeURIComponent(id)}`, undefined, 'DELETE')) +} +export async function checkDWSConnection(signal?: AbortSignal) { + const data = await request('/api/v1/dingtalk-spaces/available', signal) + if (!('knowledge_bases' in data) || !('drive_spaces' in data) || !text(data.fetched_at)) + throw new Error('未取得有效目录检查结果,请重试') + const knowledge = Array.isArray(data.knowledge_bases) ? data.knowledge_bases.length : 0 + const drive = Array.isArray(data.drive_spaces) ? data.drive_spaces.length : 0 + const notices = [text(data.knowledge_notice), text(data.drive_notice)].filter(Boolean) + return { message: `已读取 ${knowledge} 个知识库、${drive} 个钉盘空间`, notices, checkedAt: text(data.fetched_at) } +}