Files
magpie/internal/provider/keepalive.go
T
yetone 8c5b9f928d provider, agent, gui: subscription accounts can be turned off, and then no agent's sign-in is read (#1535, MaxHaiCom)
What changed: Settings → Privacy → Subscription accounts (On/Off),
`magpie accounts discovery [on|off]` and MAGPIE_NO_ACCOUNTS=1 turn off
account discovery. It stays on by default. While it is off, magpie reads
none of the agents' sign-ins: ~/.claude/.credentials.json, .claude.json's
account, ~/.codex/auth.json, Copilot's, Cursor's, Devin's, Kiro's,
Gemini's, ZCode's, Command Code's and OpenCode's files. It runs no
`security` / `secret-tool` for the Keychain or Secret Service, and asks no
agent CLI who is signed in. It serves no subscription. API-key providers,
middleware plugins and Pi extensions work as before.

Why: the reporter runs magpie on machines where reading other tools'
credentials isn't wanted. The owner delegated the call.

How: settings.NoAccountDiscovery (kept per computer by KeepOwn) and
settings.AccountDiscoveryOff(). The variable only ever turns discovery
off. The gates sit at every reader (readAccountFile, discoveryOff) and at
every route that reads or writes a sign-in, so a route that skips
Accounts still reads nothing:
- Accounts, All, Logins, usage, renewal, warm-up, session identities,
  check-ins;
- switching, forgetting, SetLoginOn, StartSignIn, the imports;
- moves onto plugins.
The ones that write refuse with an error that names how to turn it back
on. On the agent side, Agent.Source and OpenCode's auth.json are gated,
and Codex wiring goes by magpie's stash instead of auth.json, so a
toggle never rewires Codex. logins.json and plugin-auth.json are left
untouched and serve again when discovery is turned back on. A change
applies at once (ForgetAccounts).

Docs: providers-accounts.md, README (en, zh-CN), and the site's CLI table
(en, zh, ja).

Run:
- TestAccountDiscoveryOffReadsNoSignIn (provider) and
  TestAccountDiscoveryOffAgentsReadNoSignIn (agent). Every credential
  path is a FIFO that records each open, and security, secret-tool,
  claude, codex, cursor-agent, devin, kiro-cli, copilot and grok are fakes
  on PATH. Both fail with the gate removed: they show the opens and
  `security find-generic-password -s Claude Code-credentials`, among
  others. Both pass with the gate in place.
- TestAccountDiscoverySetting and TestAccountsDiscoveryCmd.
- account-discovery.test.cjs: chromium and webkit, 900 and 360 wide,
  en/zh/zh-TW/ja/de, 32/32. The neighbouring privacy, redact,
  settings-sections and i18n-keys GUI tests: 49/49.
- The full `go test -tags nogui ./...`, gofmt -l, and go vet for darwin,
  linux and windows on the touched packages.

Not tried: a real machine under fs_usage, and Linux and Windows at
runtime. The FIFO tests are !windows.
2026-10-11 06:38:40 +08:00

117 lines
3.5 KiB
Go

package provider
// Keeping saved accounts signed in. A ChatGPT account saved in magpie but
// not the one Codex is signed in to is refreshed only when it is used or
// its allowance looked at — and one waiting its turn (smart
// routing leaves the accounts whose week resets later for days) could sit
// unused past its refresh token's life, and be found signed out just when
// it's needed. So whichever magpie runs the gateway renews each such
// sign-in about once a day. The account the agent is signed in to is the
// agent's own to refresh, and is left to it. A Claude account is never
// refreshed by magpie: Claude Code refreshes it, whenever it runs on it
// (claude_dirs.go).
import (
"context"
"encoding/json"
"errors"
"log"
"strings"
"time"
"github.com/yetone/magpie/internal/settings"
)
// keepAliveEvery is how long a saved sign-in goes before it is renewed.
const keepAliveEvery = 24 * time.Hour
// Renewal is what came of renewing one saved account.
type Renewal struct {
Agent string `json:"agent"`
User string `json:"user"`
// Renewed is false when it wasn't due; Err is why it failed, and Lapsed
// whether the sign-in is gone (the vendor refused it) or may yet renew.
Renewed bool `json:"renewed"`
Err string `json:"error,omitempty"`
Lapsed bool `json:"lapsed,omitempty"`
}
// RenewLogins renews the saved ChatGPT sign-ins not in the
// agent's hands that have gone every or longer without it; every 0 renews
// all of them.
func RenewLogins(ctx context.Context, every time.Duration) []Renewal {
if settings.AccountDiscoveryOff() {
return nil
}
rememberLogins(false)
loginsMu.Lock()
active := map[string]string{}
for _, a := range loginAgents {
if l, ok := liveLogin(a); ok {
active[a] = l.User
}
}
ls := readLogins()
loginsMu.Unlock()
out := []Renewal{}
for _, l := range ls {
if l.Agent != "codex" || strings.EqualFold(active[l.Agent], l.User) || accountRemoved(l.Agent) {
continue
}
r := Renewal{Agent: l.Agent, User: l.User}
if every > 0 && !renewalDue(l, every, time.Now()) {
out = append(out, r)
continue
}
if _, _, err := renewSavedLogin(ctx, l.Agent, l.User, true); err != nil {
r.Err = err.Error()
var refused refreshRefused
r.Lapsed = errors.As(err, &refused)
} else {
r.Renewed = true
}
out = append(out, r)
}
return out
}
// renewalDue says whether a saved sign-in has gone every without being
// renewed — since magpie last renewed it, or since it was last seen in the
// agent's hands, which kept it fresh — or its refresh token is near its end.
func renewalDue(l savedLogin, every time.Duration, now time.Time) bool {
last := l.Renewed
if l.Seen.After(last) {
last = l.Seen
}
var a struct {
LastRefresh time.Time `json:"last_refresh"`
}
if json.Unmarshal(l.Auth, &a) == nil && a.LastRefresh.After(last) {
last = a.LastRefresh
}
return now.Sub(last) >= every
}
// KeepLoginsAlive renews the saved sign-ins that are due, a minute after it
// starts and every hour after that — a computer that slept through a day
// catches up within the hour of waking — until ctx ends.
func KeepLoginsAlive(ctx context.Context) {
t := time.NewTimer(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
c, cancel := context.WithTimeout(ctx, 2*time.Minute)
for _, r := range RenewLogins(c, keepAliveEvery) {
if r.Err != "" {
log.Printf("keeping %s account %s signed in: %s", r.Agent, r.User, r.Err)
}
}
cancel()
t.Reset(time.Hour)
}
}