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) } }