Files
magpie/internal/provider/devin_accounts.go
T
yetone 40df6dbd38 provider: a subscription sign-in canceled while its token is fetched adds no account (#2054)
A sign-in checked canceled/finished only when its callback was claimed.
The token exchange after that went on to addLogin / addGoogleLogin /
addSideLogin and only then called finish, a no-op after CancelSignIn, so
a sign-in the user canceled while its token was in flight still added
the account, or replaced an existing account's tokens. Sibling of #1750
(mcpauth's flow.keep, 1a7aa76b4).

Every built-in sign-in's write of its account now goes through one gate:
keepLogin(ctx, store), which finds the flow s.via put on the sign-in's
context and runs store under the flow's lock only while the flow is
live (signInFlow.keep). The CLI-run sign-ins (Claude, Grok, Cursor),
whose context isn't the flow's, call s.keep directly. Cancel takes the
same lock in finish, so either it comes first and nothing is written
(the flow stays "canceled"), or the account is kept and a cancel after
that is too late (kept): the flow then goes on to "done", matching the
account list.

Routed through it: Codex and Devin callbacks (Devin's own credentials
file and its side home), Gemini/Antigravity, ChatGPT API, Claude Code,
Copilot, Command Code (callback and pasted key), Factory, Kiro, MiMo,
Qoder, WorkBuddy, Zed, ZCode, and runCLISignIn's identity (Grok's second
account). Plugin sign-ins are kept by the plugin host and aren't
covered here.

Run:
- TestCanceledSignInAddsNoAccount (Codex: browser callback and pasted
  address, the token endpoint's reply held until CancelSignIn) and
  TestCanceledDeviceSignInAddsNoAccount (Copilot device code, GitHub's
  answer held, read whole, until after the cancel). On the old code all
  three FAIL: "the canceled sign-in wrote ~/.codex/auth.json", "the
  canceled sign-in added cx@example.com", "the canceled sign-in added
  late-user". With the fix they pass, -race -count=5.
- go test -tags nogui -timeout 45m ./internal/provider/... ok (sandbox
  HOME, private GOCACHE).
- gofmt -l clean; go vet ./internal/provider (darwin), GOOS=linux and
  GOOS=windows go vet -tags nogui ./internal/provider ok.
Rerun after rebasing on origin/main f71155591 (#2052, which touches
provider/models.go): gofmt and the three vets ok; the provider suite
(-timeout 45m) ended once in a bare FAIL with no test named, then passed
3 runs in a row (one -v). Filed as #2061. Rebased again on 8da304767:
gofmt, the three vets and the provider suite ok.
Not tried against a real vendor's sign-in.
2026-10-14 08:39:37 +08:00

179 lines
6.1 KiB
Go

package provider
// PLUGIN-SERVED (see AGENTS.md): Devin ("devin") is a deprecated built-in
// subscription served by its plugin, @magpie-community/opencode-devin-auth,
// once moved onto it (provider.Moved; the default for a new sign-in). A
// moved one's sign-ins, models, requests and usage are all the plugin's,
// never this code's (only the move, in migrate*.go, still reads its
// accounts). A fix here alone doesn't reach those users; fix the plugin
// (github.com/magpie-community/plugins, packages/devin) and raise the
// mover's min in internal/provider/migrate_side.go.
// Several Devin subscriptions. The devin CLI keeps one account, in its
// credentials.toml; magpie signs the CLI in when it has none, and reads it
// after. Each further account gets a home of magpie's own, laid out as the
// CLI's data folder, so the CLI itself answers for it (`devin auth status`
// and `devin models list` run with that home as their data folder) and the
// CLI's own sign-in is never touched. logins.json names those homes; the
// CLI's own account is remembered there too, with no home, so it can stand
// behind another or be turned off.
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
)
// devinAccountsDir holds the homes of the Devin accounts magpie signed in.
func devinAccountsDir() string { return filepath.Join(filepath.Dir(Path()), "devin") }
// devinCredentialsAt is where an account's credentials.toml is: the CLI's
// own for home "", else the one in magpie's home.
func devinCredentialsAt(home string) string {
if home == "" {
return DevinCredentialsPath()
}
return filepath.Join(home, "devin", "credentials.toml")
}
// devinCommand runs the devin CLI for an account: the CLI's own for home
// "", else with magpie's home as its data folder. It goes through the
// proxy ctx names (a sign-in's), else the account's own (devinProxy), as
// the account's requests do, never always the global one (#1663).
func devinCommand(ctx context.Context, home, path string, args ...string) *exec.Cmd {
cmd := proc.CommandContext(ctx, path, args...)
proxy := netproxy.Choice(ctx)
if proxy == "" {
proxy = devinProxy(home)
}
if home == "" {
cmd.Env = netproxy.EnvWith(proxy, nil)
return cmd
}
var env []string
for _, e := range os.Environ() {
k, _, _ := strings.Cut(e, "=")
switch strings.ToUpper(k) {
case "XDG_DATA_HOME", "APPDATA":
continue
}
env = append(env, e)
}
cmd.Env = netproxy.EnvWith(proxy, append(env, "XDG_DATA_HOME="+home, "APPDATA="+home))
return cmd
}
// devinProxy is the proxy of the account signed in in home (the CLI's own
// for ""), as logins.json names it: that account's (ProxyOfLogin), or the
// subscription's for a home no account is kept for yet. It reads
// logins.json without loginsMu, which a caller may hold.
func devinProxy(home string) string {
for _, l := range readLogins() {
if l.Agent == "devin" && l.Home == home && (home != "" || l.own()) {
return ProxyOfLogin("devin", l.User)
}
}
return ProxyOf("devin")
}
// devinLogin is a Devin account and the home it is signed in in, "" for
// the CLI's own.
type devinLogin struct {
Login
Home string
}
// devinLogins lists the Devin accounts that are signed in, the first in
// use first, then the rest as they were added.
func devinLogins() []devinLogin {
own, plan, ok := devinIdentity()
if !ok {
own = ""
}
var out []devinLogin
for _, l := range sideLogins("devin", own, func(l savedLogin) bool {
_, _, err := DevinAuthAt(l.Home)
return l.Home != "" && err == nil
}) {
if l.saved.own() && l.Plan == "" {
l.Plan = plan // the CLI's own, by the tier `devin auth status` says, as the plugin names it
}
out = append(out, devinLogin{l.Login, l.saved.Home})
}
return out
}
func devinSide() []sideLogin {
var out []sideLogin
for _, d := range devinLogins() {
out = append(out, sideLogin{Login: d.Login})
}
return out
}
// devinLoginList is the Devin accounts as Logins lists them.
func devinLoginList() []Login { return loginsOf(devinSide()) }
// switchDevinLogin puts a Devin account first. The CLI's own sign-in stays
// as it is: magpie only changes which account its gateway uses first.
func switchDevinLogin(user string) error { return switchSideLogin("devin", user, devinSide()) }
func setDevinLoginOn(user string, on bool) error {
return setSideLoginOn("devin", user, on, devinSide())
}
// forgetDevinLogin drops an account magpie signed in, with its home. The
// CLI's own is only hidden (forgetSideLogin).
func forgetDevinLogin(user string) error {
return forgetSideLogin("devin", user, devinSide(),
func(l savedLogin) { removeDevinHome(l.Home) })
}
// newDevinHome makes the home a further Devin account is signed in in.
func newDevinHome() (string, error) {
home := filepath.Join(devinAccountsDir(), strings.ToLower(strings.NewReplacer("-", "", "_", "").Replace(randomToken(9))))
return home, os.MkdirAll(filepath.Join(home, "devin"), 0o700)
}
// removeDevinHome deletes a home magpie made, and nothing else.
func removeDevinHome(home string) {
if rel, err := filepath.Rel(devinAccountsDir(), home); err == nil && rel != "." && !strings.HasPrefix(rel, "..") {
_ = os.RemoveAll(home)
}
}
// addDevinLogin keeps the account just signed in in home, in use beside
// the others, once the CLI says whose it is. Signed in again, an account
// keeps the newer home.
func addDevinLogin(ctx context.Context, home string) (user, plan string, err error) {
user, plan, ok := askDevinIdentityAt(ctx, home)
if !ok || user == "" {
return "", "", errors.New("signed in, but `devin auth status` doesn't show the account; run it in a terminal to see why")
}
own, _, ownOK := devinIdentity()
if !ownOK {
own = ""
}
return user, plan, keepLogin(ctx, func() error {
return addSideLogin(savedLogin{Agent: "devin", User: user, Plan: plan, Home: home}, own,
func(l savedLogin) { removeDevinHome(l.Home) })
})
}
// devinAlsoOn is the Devin accounts in use behind the first.
func devinAlsoOn() []Provider {
var out []Provider
for _, d := range devinLogins() {
if !d.Active && d.On {
out = append(out, devinProvider(d))
}
}
return out
}