provider: a keyless public plugin stays listed with subscription accounts off, and its name isn't blurred (lileo0668)
lileo0668 on Discord (#help): OpenCode Zen Free (plugin 0.1.18, the public credential) said 已登录 on the Plugins page, the Add sheet had one blurred row for it, a red line said "<name> 已登录,但 magpie 无法列出它", and Zen's free models were nowhere. Cause, reproduced on a sandbox magpie (HOME and XDG dirs under a scratch folder, :3561, `magpie web` on :3562) built from origin/main8701eb35ewith the real plugin from npm: with Settings -> Privacy -> Subscription accounts off (#1535, or MAGPIE_NO_ACCOUNTS), pluginLogins and All() drop every plugin provider, but PluginAPIKey, the keyless/key route, was not gated. The sign-in went through, plugin-auth.json held it, the Plugins page said signed in, and /api/providers listed nothing, so the GUI showed "signed in, but magpie can't list it". With accounts on it signs in and lists fine. v0.1.1847 (the reporter's) has the same code. The blur: /api/plugin-signin answered user = the plugin's name, Hide accounts takes every answer's user for an account, and spares only listed providers' names, so "OpenCode Zen Free" was blurred on the card, the sheet row and the red line. Fix: - publicPlugin: a plugin whose every way in is keyless holds no account of the user's. With accounts off it is still listed (pluginLogins, All, Accounts), served (Sign) and signed in (PluginAPIKey). - Any other plugin's key is refused with errAccountDiscoveryOff before anything is saved, as its browser sign-in already was. - /api/plugin-signin's key answer no longer names the plugin as a user; the GUI names it from subOf. Hide accounts spares every plugin's id and name from providers.plugins. - providers-accounts.md and discovery.go say so. Run at the rebased head (792f0f286, thenfd80ed99c): - internal/provider TestPublicPluginListedWithAccountsOff, TestAccountDiscoveryOffReadsNoSignIn, TestAccountDiscoverySetting, TestPluginKeylessSingleIdentity, TestPluginEmptyKeyOnlyKeyless: ok. - wsl-run go test -tags nogui ./... -timeout 45m: every package ok but internal/agent: TestGrokInstalled (#3548) and TestOmpDetectedWithPiDir (#4033), the Linux box's known reds; internal/agent isn't touched here. - go vet nogui ./internal/provider ./internal/gui for linux and windows, darwin for provider; gofmt clean. - GUI (wsl-run, chromium + webkit, en zh zh-TW ja de, 900 and 360 wide): plugin-name-unmasked (new), plugin-keyless-signin, account-eye-provider, account-eye, account-mask, privacy-hides-accounts, plugin-moved-signin, plugin-other-ways, plugin-signin-no-url, plugin-key-hint, i18n*: 106 of 106 (on792f0f286); plugin-name-unmasked and plugin-keyless-signin 20 of 20 there too. - Rebased again ontofd80ed99c(mover mins, Picked only, Kimi, usage): the provider tests above ok there. - A first GUI batch on mote timed out on browser launch at load ~90 from other sessions' runners; not a code red, rerun on WSL. Broken by hand: - the four provider files back to origin/main: the new test fails "Zen Free not listed with accounts off: map[]". - Sign's exemption alone: "Zen Free not served with accounts off". - All's exemption alone: "not listed ... map[]". - PluginAPIKey's gate off: Acme's key is not refused (it goes on to the plugin host). - app.js's plugin-name exemption off: plugin-name-unmasked red 5 of 5 (chromium). Not tried: the reporter's own computer; that their Subscription accounts switch is off is inferred, the one route that reproduces it. A real request through the gateway with the fixed build and accounts off wasn't sent; the provider test signs Zen's request. The plugin itself is unchanged (0.1.18 on npm).
This commit is contained in:
@@ -137,7 +137,7 @@ successful model discovery for its decision result, and reports none when
|
||||
no decision model was discovered (`Test` in
|
||||
[`test.go`](../../internal/provider/test.go)).
|
||||
|
||||
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json` or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
|
||||
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json` or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. So does a public plugin, one whose every way in is keyless (`publicPlugin` in [`plugin_accounts.go`](../../internal/provider/plugin_accounts.go), OpenCode Zen Free): it holds no account of the user's, so it stays listed and served, and its sign-in goes through (lileo0668: it signed in, then was listed nowhere). Any other plugin's key is refused in `PluginAPIKey`, as its browser sign-in is, rather than saved and listed nowhere. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
|
||||
|
||||
A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it.
|
||||
|
||||
|
||||
@@ -24123,6 +24123,9 @@ window.noteAccounts = noteAccounts;
|
||||
// the names the user gave accounts (#1515), as the accounts are
|
||||
for (const n of Object.values(p.accountNames || {})) all.add(String(n).trim());
|
||||
}
|
||||
// a plugin's provider, signed in or not, is a provider too: its name
|
||||
// on the Plugins page and the add sheet is no account (lileo0668)
|
||||
for (const p of providers?.plugins || []) for (const n of [p.id, p.pid, p.name]) if (n) not.add(String(n).toLowerCase());
|
||||
for (const q of quotas || []) {
|
||||
for (const n of [q.provider, q.name, q.plan]) if (n) not.add(String(n).toLowerCase());
|
||||
all.add((q.user || "").trim());
|
||||
|
||||
@@ -786,7 +786,11 @@ func pluginRoutes(mux *http.ServeMux, w Windows) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, provider.SignInState{Agent: id, State: "done", User: pp.Name})
|
||||
// no account named: the provider's name as its user was taken
|
||||
// for an account's by Hide accounts, and blurred wherever it
|
||||
// showed (lileo0668 on Discord); the page names the sign-in
|
||||
// by its subscription
|
||||
writeJSON(rw, provider.SignInState{Agent: id, State: "done"})
|
||||
return
|
||||
}
|
||||
st, err := provider.StartPluginSignInWith(in.Provider, in.Method, in.Inputs, provider.SignInOptions{Proxy: in.Proxy, User: in.User})
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// lileo0668 on Discord: with Hide accounts on, OpenCode Zen Free's name was
|
||||
// blurred on the add sheet, on the Plugins page and in the line after its
|
||||
// sign-in. The sign-in's answer named the plugin as its user, Hide accounts
|
||||
// took every answer's user for an account, and only listed providers'
|
||||
// names were spared, so a plugin not listed (yet) had its own name hidden
|
||||
// as if it were someone's account. A plugin's name, signed in or not, is a
|
||||
// provider's: it is never blurred. An account's name still is.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const ZEN = "OpenCode Zen Free", ACCOUNT = "lileo.sample";
|
||||
|
||||
function serve(lang, signed) {
|
||||
const settings = { theme: "light", lang };
|
||||
const plugins = () => [{ id: "opencode-zen-free", pid: "opencode-zen-free", name: ZEN, icon: "generic", spec: "@magpie-community/opencode-zen-free-auth", methods: [{ type: "api", label: "Zen free access", keyless: true }], single: true, signedIn: signed.on, models: 1 }];
|
||||
// an account of another provider's, to show the blur is still on
|
||||
const providers = () => ({
|
||||
providers: [{ id: "codex", name: "Codex", icon: "openai", models: [], agents: [], key: {}, account: { agent: "codex", agentName: "Codex", agentIcon: "openai", user: ACCOUNT, logins: [{ user: ACCOUNT, active: true, on: true }] } }],
|
||||
presets: [], excluded: [], gateway: { running: true, window: true }, plugins: plugins(),
|
||||
});
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
if (url.pathname === "/api/providers") return json(providers());
|
||||
if (url.pathname === "/api/plugin-signin/prompt") return json({ prompt: null, inputs: {} });
|
||||
// what magpie answered before lileo0668: the plugin's name as its user
|
||||
if (url.pathname === "/api/plugin-signin") { signed.on = true; return json({ agent: "opencode-zen-free", state: "done", user: ZEN }); }
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: plugins() });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
test(`${engine} ${lang}: with Hide accounts on, a plugin's own name is not blurred as an account`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const width of [900, 360]) {
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
await context.addInitScript(() => { try { localStorage.setItem("magpie.maskEmails", "1"); } catch {} });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, { on: false }));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
|
||||
// the blur is on: an account's name is hidden
|
||||
await page.waitForFunction((a) => document.querySelector(".pii") && !document.body.innerText.includes(a), ACCOUNT);
|
||||
|
||||
await page.locator("#addProvider").click();
|
||||
await page.locator(`#addSheet .tile[data-pick="${ZEN}"]`).click();
|
||||
const choice = page.getByRole("button", { name: "Zen free access", exact: true });
|
||||
if (await choice.count()) await choice.click();
|
||||
// the line after the sign-in names the plugin, unblurred
|
||||
await page.waitForFunction((z) => document.querySelector("#status").textContent.includes(z), ZEN);
|
||||
// what is drawn is blurred a frame later, if at all
|
||||
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
|
||||
assert.equal(await page.locator("#status .pii").count(), 0, "the status line's plugin name is not blurred");
|
||||
assert.ok((await page.locator("#status").textContent()).includes(ZEN));
|
||||
|
||||
// and the add sheet's tile, opened again, names it in the clear
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator("#modal").waitFor({ state: "hidden" });
|
||||
await page.locator("#addProvider").click();
|
||||
const tile = page.locator(`#addSheet .tile[data-pick="${ZEN}"]`);
|
||||
await tile.waitFor();
|
||||
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
|
||||
assert.equal(await tile.locator(".pii").count(), 0, "the add sheet's tile is not blurred");
|
||||
assert.ok((await tile.innerText()).includes(ZEN), "the tile names the plugin");
|
||||
assert.equal(await page.evaluate((a) => document.body.innerText.includes(a), ACCOUNT), false, "an account stays hidden");
|
||||
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "no sideways scroll");
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -201,7 +201,7 @@ func (p Provider) ListedAPIs(model string) []Protocol {
|
||||
// Sign authenticates a request to the provider, refreshing what needs it.
|
||||
// Plain providers get their key; accounts get the agent's tokens.
|
||||
func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, body []byte) error {
|
||||
if p.Account != nil && settings.AccountDiscoveryOff() {
|
||||
if p.Account != nil && settings.AccountDiscoveryOff() && !p.publicAccount() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
ctx = p.Via(ctx) // a sign-in refreshed on the way goes through its proxy
|
||||
@@ -866,7 +866,7 @@ func refreshFailed(status int, agent, msg string) error {
|
||||
// Accounts lists the signed-in agents as providers.
|
||||
func Accounts() []Provider {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
return pluginAccounts() // the public plugins' alone (publicPlugin)
|
||||
}
|
||||
rememberLogins(false)
|
||||
home, _ := os.UserHomeDir()
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
// kept of its own (logins.json, plugin-auth.json) is left as it is, unread
|
||||
// and unwritten, and comes back when discovery is turned on again.
|
||||
// Middleware plugins and Pi extensions in the plugin host are not
|
||||
// subscriptions and run as before.
|
||||
// subscriptions and run as before, and neither is a public plugin, one
|
||||
// whose every way in is keyless (publicPlugin): it holds no account of
|
||||
// the user's, so it is listed, signed in and served (lileo0668).
|
||||
|
||||
package provider
|
||||
|
||||
|
||||
@@ -22,6 +22,48 @@ import (
|
||||
// pluginAgent is what logins.json lists a plugin provider's accounts as.
|
||||
func pluginAgent(pp plugin.Provider) string { return "plugin:" + pp.ID }
|
||||
|
||||
// publicPlugin is whether every way to sign in to the plugin's provider is
|
||||
// keyless, its credential one the plugin gives whatever is typed: OpenCode
|
||||
// Zen Free's shared "public". Such an account is nobody's, so with
|
||||
// subscription accounts off (#1535, discovery.go) it is still listed and
|
||||
// served. Before, Zen Free signed in all the same with them off, the
|
||||
// Plugins page said so, and magpie listed it nowhere (lileo0668 on
|
||||
// Discord: "signed in, but magpie can't list it").
|
||||
func publicPlugin(pp plugin.Provider) bool {
|
||||
if len(pp.Methods) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, m := range pp.Methods {
|
||||
if m.Type != "api" || !m.Keyless {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// publicLogins are a public plugin's accounts while subscription accounts
|
||||
// are off, read from the plugin alone: logins.json and plugin-auth.json
|
||||
// are left unread then (discovery.go), so the first is in use and every
|
||||
// one is on.
|
||||
func publicLogins(pp plugin.Provider) []pluginLogin {
|
||||
agent, labels := pluginAgent(pp), pluginLabels(pp, nil)
|
||||
var out []pluginLogin
|
||||
for _, a := range pp.Accounts {
|
||||
saved := savedLogin{Agent: agent, User: labels[a.Key], Home: a.Key, On: true}
|
||||
out = append(out, pluginLogin{sideLogin{Login{Agent: agent, User: saved.User, On: true}, saved}, a})
|
||||
}
|
||||
if len(out) > 0 {
|
||||
out[0].Active = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// publicAccount is whether p is a public plugin's provider (publicPlugin),
|
||||
// served while subscription accounts are off.
|
||||
func (p Provider) publicAccount() bool {
|
||||
return p.IsPlugin() && publicPlugin(*p.Account.plugin)
|
||||
}
|
||||
|
||||
// pluginLabels names each account: by named (the agent's own, as the
|
||||
// agent is signed in now), else its id, else the end of its key, else what
|
||||
// it signed in with; a name two share gets the account's slot. The slot
|
||||
@@ -166,6 +208,9 @@ var pluginOwnUser = func(id string) string {
|
||||
// it is only hidden, and shows again once the agent signs in anew.
|
||||
func pluginLogins(pp plugin.Provider) []pluginLogin {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
if publicPlugin(pp) {
|
||||
return publicLogins(pp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
agent := pluginAgent(pp)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// lileo0668 on Discord: with Settings → Privacy's subscription accounts
|
||||
// off (#1535), OpenCode Zen Free's keyless sign-in went through, the
|
||||
// Plugins page said it was signed in, and the providers listed it nowhere
|
||||
// ("signed in, but magpie can't list it"). A plugin whose every way in is
|
||||
// keyless holds no account of the user's: it is listed and served with
|
||||
// them off. Any other plugin's key is refused then, as its browser
|
||||
// sign-in is, rather than saved and listed nowhere.
|
||||
func TestPublicPluginListedWithAccountsOff(t *testing.T) {
|
||||
claudeHome(t)
|
||||
t.Setenv("MAGPIE_BUN", "") // nothing here runs a plugin
|
||||
write := func(name string, v any) {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(v)
|
||||
os.MkdirAll(settings.Dir(), 0o700)
|
||||
if err := os.WriteFile(filepath.Join(settings.Dir(), name), b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
zen, acme := "@magpie-community/opencode-zen-free-auth", "@example/opencode-acme-auth"
|
||||
write("plugins.json", map[string]any{"plugins": []map[string]any{{"spec": zen}, {"spec": acme}}})
|
||||
write("plugin-auth.json", map[string]map[string]any{
|
||||
"opencode-zen-free": {"type": "api", "key": "public"},
|
||||
"acme": {"type": "api", "key": "sk-acme-1234"},
|
||||
})
|
||||
models := []plugin.Model{{ID: "big-pickle", Name: "Big Pickle", Free: true}}
|
||||
plugin.UseCached([]plugin.Provider{
|
||||
{ID: "opencode-zen-free", Spec: zen, Name: "OpenCode Zen Free", Single: true,
|
||||
Methods: []plugin.Method{{Type: "api", Label: "Zen 免费访问", Keyless: true}},
|
||||
Accounts: []plugin.Account{{Key: "opencode-zen-free", Type: "api"}},
|
||||
Models: models},
|
||||
// keyless one way, a browser the other: an account of the user's
|
||||
{ID: "acme", Spec: acme, Name: "Acme",
|
||||
Methods: []plugin.Method{{Type: "api", Label: "API key", Keyless: true}, {Type: "oauth", Label: "Browser"}},
|
||||
Accounts: []plugin.Account{{Key: "acme", Type: "api"}},
|
||||
Models: models},
|
||||
})
|
||||
t.Cleanup(func() { plugin.UseCached(nil) })
|
||||
|
||||
listed := func() map[string]Provider {
|
||||
out := map[string]Provider{}
|
||||
for _, p := range All() {
|
||||
out[p.ID] = p
|
||||
}
|
||||
return out
|
||||
}
|
||||
// on, both are listed, as ever
|
||||
if got := listed(); !got["opencode-zen-free"].IsPlugin() || !got["acme"].IsPlugin() {
|
||||
t.Fatalf("with accounts on: %v", got)
|
||||
}
|
||||
|
||||
before, _ := os.ReadFile(loginsPath())
|
||||
if err := settings.Save(settings.Settings{NoAccountDiscovery: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := listed()
|
||||
zp, ok := got["opencode-zen-free"]
|
||||
if !ok || !zp.IsPlugin() {
|
||||
t.Fatalf("Zen Free not listed with accounts off: %v", got)
|
||||
}
|
||||
if _, ok := got["acme"]; ok {
|
||||
t.Errorf("Acme, an account of the user's, listed with accounts off")
|
||||
}
|
||||
if zp.Name != "OpenCode Zen Free" || !zp.Account.Lists("big-pickle") {
|
||||
t.Errorf("Zen Free as listed: %q, lists big-pickle %v", zp.Name, zp.Account.Lists("big-pickle"))
|
||||
}
|
||||
if p, err := Find("opencode-zen-free"); err != nil || !p.IsPlugin() {
|
||||
t.Errorf("Find(opencode-zen-free) = %+v, %v", p, err)
|
||||
}
|
||||
req, _ := http.NewRequest("POST", "http://127.0.0.1/v1/chat/completions", nil)
|
||||
if err := zp.Sign(context.Background(), req, Chat, nil); err != nil {
|
||||
t.Errorf("Zen Free not served with accounts off: %v", err)
|
||||
}
|
||||
|
||||
// a key to Acme is refused before anything is saved; Zen Free's goes
|
||||
// on to the plugin (no Bun here, so it fails there, not on the gate)
|
||||
if _, err := PluginAPIKey(context.Background(), "acme", 0, nil, "sk-acme-5678"); !errors.Is(err, errAccountDiscoveryOff) {
|
||||
t.Errorf("Acme's key with accounts off: %v, want %v", err, errAccountDiscoveryOff)
|
||||
}
|
||||
if _, err := PluginAPIKey(context.Background(), "opencode-zen-free", 0, nil, ""); errors.Is(err, errAccountDiscoveryOff) {
|
||||
t.Errorf("Zen Free's keyless sign-in refused with accounts off")
|
||||
}
|
||||
if after, _ := os.ReadFile(loginsPath()); string(after) != string(before) {
|
||||
t.Errorf("logins.json written with accounts off:\n%s\nwas\n%s", after, before)
|
||||
}
|
||||
}
|
||||
@@ -214,6 +214,14 @@ func (s *signInFlow) pluginDone(saved plugin.Saved, err error) {
|
||||
// method does, beside the accounts signed in already; it gives the
|
||||
// provider's magpie id.
|
||||
func PluginAPIKey(ctx context.Context, id string, method int, inputs map[string]string, key string) (string, error) {
|
||||
// with subscription accounts off, a key is refused as a browser
|
||||
// sign-in is (StartPluginSignInWith), but for a public plugin's: one
|
||||
// saved would be signed in and listed nowhere
|
||||
if settings.AccountDiscoveryOff() {
|
||||
if pp, ok := PluginOf(PluginID(id)); !ok || !publicPlugin(pp) {
|
||||
return "", errAccountDiscoveryOff
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(key) == "" {
|
||||
pp, ok := PluginOf(PluginID(id))
|
||||
if !ok || method < 0 || method >= len(pp.Methods) || pp.Methods[method].Type != "api" || !pp.Methods[method].Keyless {
|
||||
|
||||
@@ -654,7 +654,7 @@ func All() []Provider {
|
||||
// round every 30s), most of an idle magpie's CPU (xsw on Discord)
|
||||
off := sync.OnceValue(func() bool { return settings.AccountDiscoveryOffIn(heldSettings()) })
|
||||
for _, p := range held {
|
||||
if p.Account != nil && off() {
|
||||
if p.Account != nil && off() && !p.publicAccount() {
|
||||
continue
|
||||
}
|
||||
out = append(out, p.clone()) // callers change theirs, Keys[i] and Headers included
|
||||
|
||||
Reference in New Issue
Block a user