diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ddb7561f9..36aed89df 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11653,8 +11653,8 @@ const subOf = (agent) => { const pl = pluginSubs().find((x) => x.agent === agent); if (own && pl && movedSub(agent)) { const { name, icon, plans, risk, riskNote, hint, sites, importable } = own; - // a Factory API key is kept by the built-in, which the plugin replaces - return { ...pl, name, icon, plans, risk, riskNote, hint, sites, importable: importable && agent !== "factory", moved: true }; + // a moved Factory's imported API keys go to its plugin (factory_key.go) + return { ...pl, name, icon, plans, risk, riskNote, hint, sites, importable, moved: true }; } return own || pl; }; diff --git a/internal/gui/tests/plugin-moved-signin.test.cjs b/internal/gui/tests/plugin-moved-signin.test.cjs index 470213482..4104a1aaf 100644 --- a/internal/gui/tests/plugin-moved-signin.test.cjs +++ b/internal/gui/tests/plugin-moved-signin.test.cjs @@ -63,8 +63,8 @@ function server(lang, asked) { } const L = { - en: { subs: "Subscriptions", plugins: "From plugins", anyway: "Sign in anyway", again: "Try again", single: "keeps one account", signedIn: "Signed in ·" }, - zh: { subs: "订阅", plugins: "来自插件", anyway: "仍然登录", again: "重试", single: "只保存一个账号", signedIn: "已登录 ·" }, + en: { subs: "Subscriptions", plugins: "From plugins", anyway: "Sign in anyway", key: "Use an API key instead…", again: "Try again", single: "keeps one account", signedIn: "Signed in ·" }, + zh: { subs: "订阅", plugins: "来自插件", anyway: "仍然登录", key: "改用 API Key…", again: "重试", single: "只保存一个账号", signedIn: "已登录 ·" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -116,6 +116,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", // Factory: warned, its one way, the code to copy asked.length = 0; await sheet.locator('.tile[data-pick="Factory"]').click(); + // and its API keys, which its plugin keeps (factory_key.go) + await box.locator("button", { hasText: w.key }).waitFor(); await box.locator("button", { hasText: w.anyway }).click(); await box.locator(".devcode code", { hasText: "ABCD-EFGH" }).waitFor(); if (process.env.ARTIFACT_DIR) await box.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `plugin-moved-code-${engine}-${lang}.png`) }); diff --git a/internal/provider/factory_key.go b/internal/provider/factory_key.go index f34285f77..5e8a3b50f 100644 --- a/internal/provider/factory_key.go +++ b/internal/provider/factory_key.go @@ -24,7 +24,10 @@ import ( "errors" "fmt" "regexp" + "strings" "time" + + "github.com/yetone/magpie/internal/plugin" ) // factoryKeyPrefix is droid's Uh: what a Factory API key starts with. @@ -91,6 +94,9 @@ func factoryAddKey(ctx context.Context, key string) ImportedAccount { if user == "" { return ImportedAccount{User: factoryKeyName(key), Status: "failed", Error: "Factory took the key but didn't say whose account it is"} } + if Moved("factory") { + return factoryKeyToPlugin(wctx, user, c) + } status := "added" if l, ok := factoryLookup(user); ok { status = "updated" @@ -111,3 +117,27 @@ func factoryAddKey(ctx context.Context, key string) ImportedAccount { }) return ImportedAccount{User: user, Status: status} } + +// factoryKeyToPlugin keeps a key as an account of Factory's plugin, which +// a moved Factory signs in with: an api account, as the plugin's own +// "Factory API key" sign-in saves one (whoami's metadata beside the key). +func factoryKeyToPlugin(ctx context.Context, user string, c factoryCreds) ImportedAccount { + status := "added" + for _, a := range plugin.Auths("factory") { + md, _ := a["metadata"].(map[string]any) + switch { + case str(a["type"]) == "api" && str(a["key"]) == c.Access: + status = "exists" + case status == "added" && strings.EqualFold(firstNonEmpty(str(md["email"]), str(a["email"])), user): + status = "updated" + } + } + auth := map[string]any{"type": "api", "key": c.Access, "metadata": map[string]any{ + "email": c.Email, "userId": c.UserID, "region": c.Region, "premBaseHost": c.Prem}} + if status != "exists" { + if _, err := plugin.Import(ctx, "factory", auth); err != nil { + return ImportedAccount{User: user, Status: "failed", Error: err.Error()} + } + } + return ImportedAccount{User: user, Status: status} +} diff --git a/internal/provider/factory_key_test.go b/internal/provider/factory_key_test.go index afc3ab98b..bb5116487 100644 --- a/internal/provider/factory_key_test.go +++ b/internal/provider/factory_key_test.go @@ -4,9 +4,14 @@ import ( "context" "io" "net/http" + "path/filepath" "strings" "sync" "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/testenv" ) // #506: a Factory account added by its API key, as droid takes @@ -85,3 +90,56 @@ func TestFactoryAPIKey(t *testing.T) { t.Fatal("no key in it, and no error") } } + +// A moved Factory's keys are the plugin's accounts: an imported key is kept +// by the plugin as its own "Factory API key" sign-in keeps one, an api +// account with whoami's metadata, and not as a built-in account the moved +// Factory never reads. The same key again is "exists". +func TestFactoryAPIKeyMoved(t *testing.T) { + signIn(t) + bun := testenv.Bun(t) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("FAKE_ID", "factory") + t.Cleanup(plugin.Settle) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if err := setMigration("factory", func(m *Migration) { m.State, m.Package = MovePlugin, abs }); err != nil { + t.Fatal(err) + } + const good = "fk-good_0123456789abcdef" + factorySite(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/cli/whoami" || r.Header.Get("Authorization") != "Bearer "+good { + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + w.WriteHeader(404) + return + } + factoryJSON(w, 200, map[string]any{"userId": "user_k", "orgId": "fac_K", "email": "key@example.com"}) + }) + res, err := ImportFactoryKeys(ctx, []string{good}) + if err != nil || len(res) != 1 || res[0].Status != "added" || res[0].User != "key@example.com" { + t.Fatalf("imported %+v, %v", res, err) + } + var kept []map[string]any + for _, a := range plugin.Auths("factory") { + kept = append(kept, a) + } + if len(kept) != 1 || kept[0]["type"] != "api" || kept[0]["key"] != good { + t.Fatalf("the plugin keeps %v", kept) + } + if md, _ := kept[0]["metadata"].(map[string]any); md["email"] != "key@example.com" || md["userId"] != "user_k" { + t.Fatalf("the key's metadata %v", kept[0]["metadata"]) + } + if _, ok := factoryLookup("key@example.com"); ok { + t.Fatal("the key was kept by the built-in too") + } + if res, err = ImportFactoryKeys(ctx, []string{good}); err != nil || len(res) != 1 || res[0].Status != "exists" { + t.Fatalf("again: %+v, %v", res, err) + } + if n := len(plugin.Auths("factory")); n != 1 { + t.Fatalf("again: the plugin keeps %d accounts", n) + } +} diff --git a/internal/provider/migrate_factory.go b/internal/provider/migrate_factory.go index cda7e2094..0629057ef 100644 --- a/internal/provider/migrate_factory.go +++ b/internal/provider/migrate_factory.go @@ -3,6 +3,7 @@ package provider import ( "encoding/json" "errors" + "strings" "time" ) @@ -23,6 +24,22 @@ func init() { var out []Moving for _, l := range ls { c := l.creds + if c.Key { + // an API key (fk-…) is the plugin's api account, as its + // own "Factory API key" sign-in saves one: an oauth one + // would be renewed with no refresh token and lapse + out = append(out, Moving{User: l.User, First: l.Active, On: l.On, Lapsed: l.Lapsed != "", Plan: l.Plan, Auth: map[string]any{ + "type": "api", + "key": c.Access, + "metadata": map[string]any{ + "email": c.Email, + "userId": c.UserID, + "region": c.Region, + "premBaseHost": c.Prem, + }, + }}) + continue + } out = append(out, Moving{User: l.User, First: l.Active, On: l.On, Lapsed: l.Lapsed != "", Plan: l.Plan, Auth: map[string]any{ "type": "oauth", "access": c.Access, @@ -40,6 +57,9 @@ func init() { return out, nil }, back: func(ls []savedLogin, user string, auth map[string]any) ([]savedLogin, string, error) { + if str(auth["type"]) == "api" { + return factoryKeyBack(ls, user, auth) + } access := str(auth["access"]) if access == "" { return ls, "", errors.New("Factory: an unreadable plugin sign-in") @@ -65,3 +85,25 @@ func init() { }, } } + +// factoryKeyBack keeps the plugin's api account (an fk- key) as the +// built-in's key account (factory_key.go). +func factoryKeyBack(ls []savedLogin, user string, auth map[string]any) ([]savedLogin, string, error) { + key := strings.TrimSpace(str(auth["key"])) + if !strings.HasPrefix(key, factoryKeyPrefix) { + return ls, "", errors.New("Factory: an unreadable plugin API key") + } + md, _ := auth["metadata"].(map[string]any) + if user == "" { + user = firstNonEmpty(str(md["email"]), str(md["userId"]), factoryKeyName(key)) + } + i := backInto(&ls, "factory", user) + c := factoryCreds{Access: key, Key: true, Email: str(md["email"]), UserID: str(md["userId"]), + Region: str(md["region"]), Prem: str(md["premBaseHost"])} + b, err := json.Marshal(c) + if err != nil { + return ls, "", err + } + ls[i].Auth, ls[i].Lapsed, ls[i].Seen = b, "", time.Now().UTC().Truncate(time.Second) + return ls, ls[i].User, nil +} diff --git a/internal/provider/migrate_movers_test.go b/internal/provider/migrate_movers_test.go index 6615ef34b..8141a3bf1 100644 --- a/internal/provider/migrate_movers_test.go +++ b/internal/provider/migrate_movers_test.go @@ -129,6 +129,43 @@ func TestFactoryMover(t *testing.T) { }) } +// A Factory account added by its API key (fk-…) moves as the plugin's own +// "Factory API key" sign-in saves one, an api account with its key and +// whoami's metadata (keyAccount in its index.mjs), not as a sign-in the +// plugin would try to renew with no refresh token; and comes back a key. +func TestFactoryKeyMover(t *testing.T) { + k := factoryCreds{Access: "fk-key_0123456789abcdef", Key: true, Email: "k@f.com", UserID: "user_k", Region: "eu", Prem: "llm.example.com"} + c := factoryCreds{Access: "a1", Refresh: "r1", ExpiresAt: 1_900_000_000_000, Email: "a@f.com"} + saved := []savedLogin{ + {Agent: "factory", User: "k@f.com", First: true, Auth: authOf(t, k)}, + {Agent: "factory", User: "a@f.com", On: true, Auth: authOf(t, c)}, + } + roundTrip(t, "factory", saved, func(t *testing.T, a, b savedLogin) { + ca, _ := factorySaved(a) + cb, _ := factorySaved(b) + if ca != cb { + t.Fatalf("factory %s: %+v, want %+v", a.User, cb, ca) + } + }) + loginsMu.Lock() + if err := writeLogins(slicesClone(saved)); err != nil { + t.Fatal(err) + } + loginsMu.Unlock() + accts, err := movers["factory"].out() + if err != nil { + t.Fatal(err) + } + want := map[string]any{"type": "api", "key": k.Access, "metadata": map[string]any{ + "email": "k@f.com", "userId": "user_k", "region": "eu", "premBaseHost": "llm.example.com"}} + if !reflect.DeepEqual(accts[0].Auth, want) { + t.Fatalf("the key account moves as %v, want %v", accts[0].Auth, want) + } + if accts[1].Auth["type"] != "oauth" { + t.Fatalf("a signed-in account moves as %v", accts[1].Auth) + } +} + func TestMiMoMover(t *testing.T) { issued := time.Date(2026, 9, 29, 10, 0, 0, 0, time.UTC) c1 := mimoCreds{UserID: "123", CUserID: "c123", PassToken: "p1", DeviceID: "dev1", Region: "sg", Base: "https://aistudio.xiaomimimo.com", Cookies: map[string]string{"serviceToken": "s1", "userId": "123"}, Issued: issued, Name: "Mi One"}