gateway keys: a key may keep some accounts out and use every other, later ones too (LeiWang_2000 on X)

A gateway key could only be held to accounts picked one by one, so an
account signed in after the key was saved was never used. An entry
"<provider>/!<account>" (access.ExcludeMark) now keeps that account out:
the key uses every other account of the provider, one added later too,
and never the one kept out.

- access: AllowsAccount refuses a kept-out account first, and counts only
  the entries naming accounts to use for "the providers it names", so a
  provider with only kept-out entries serves every other account.
  HeldModels and AccountModels ignore kept-out entries (keeping one out
  holds the key to no model). An issued key keeps out what its issuer
  does (foldAccounts). CleanAccounts resolves the ref after the mark and
  refuses an account both used and kept out. ReplaceAccount moves
  kept-out entries too. AccountsShown renders "X; every account but Z"
  for the CLI and the gateway's refusals.
- CLI: `magpie gateway-key accounts <id> relay/!Second` prints "every
  account but relay/Second"; list and models read it.
- GUI: the key row's menu has "Keep accounts out", which opens the app's
  menu (openProtoMenu, no native select); a badge names what is kept out
  and opens the same menu; an account the key was held to and is now kept
  out leaves the held ones. Strings in zh, zh-TW, ja and de.
- docs: reference.md and providers-accounts.md.

Run (mote, at this tree):
- gofmt -l internal/ clean; go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows of access, cli and gateway: clean.
- go test -count=1 ./internal/access ./internal/cli ./internal/gateway: ok.
  New: TestKeptOutAccounts, TestKeptOutFolded, TestKeptOutReplaced;
  TestGatewayKeyKeptOutAccountsKeyedRoutes (chat, messages, responses,
  count_tokens, images, videos, System One and /v1/models over a key
  provider, a remote magpie and a Decide provider: the kept-out key never
  asked, every account kept out asks nothing, a key added after the
  gateway key was saved is used); TestGatewayKeyKeptOutCodexAccounts
  (Codex sign-ins, one signed in later used);
  TestGatewayKeyKeptOutQuotaCards; TestGatewayKeyAccountsCLI extended.
- GUI: gateway-key-kept-out.test.cjs, chromium and webkit, 1100 and 440
  px, en zh zh-TW ja de: 20 of 20. Every gateway-*.test.cjs and
  i18n-*.test.cjs file in both engines: 496 of 516, the 20 red all
  gateway-card's count of the row menu's items (5, now 6), updated here;
  then gateway-card, api-key-theme, gateway-connect-keys, gui-de, gui-ja
  and gui-zh-tw: 39 of 39.
- Again after rebasing onto 4869d0c96 (this commit's tree): gofmt clean,
  vet darwin/linux nogui/windows clean, go test access, cli, gateway and
  gui (TestCoreScriptBudget among them) ok; gateway-key-kept-out,
  gateway-card, gateway-key-accounts, i18n-keys, i18n-en-no-cjk, gui-zh-tw,
  gui-ja, gui-de in both engines: 61 of 61.
- Rebased onto b922e5168 (nanobot, which also adds i18n strings): go test
  gui and access ok; gateway-key-kept-out, i18n-keys, i18n-en-no-cjk,
  gui-zh-tw, gui-ja, gui-de in both engines: 37 of 37.

Broken by hand:
- AllowsAccount without its kept-out refusal: TestKeptOutAccounts,
  TestKeptOutFolded and all three TestGatewayKeyKeptOut* tests red.
- gatewayKeptOutPick keeping a held account it was told to keep out:
  gateway-key-kept-out red (the server key's accounts-key body).

Not tried: a real account kept out on a running magpie (the tests use
fake upstreams and sign-ins); Windows (no OS-specific code).
This commit is contained in:
yetone
2026-11-10 10:50:26 +08:00
parent 7c0a103eb1
commit 0842bc517e
14 changed files with 818 additions and 46 deletions
+5 -1
View File
@@ -666,6 +666,7 @@ magpie gateway-key limit <id> off # no limit
magpie gateway-key models <id> openai/gpt-5 anthropic/* # only these models
magpie gateway-key models <id> all # every model
magpie gateway-key accounts <id> codex/me@example.com # only these accounts
magpie gateway-key accounts <id> codex/!me@example.com # every account but these, later ones too
magpie gateway-key accounts <id> all # every account
magpie gateway-key mcp <id> github fs/read_file # only these MCP servers and tools
magpie gateway-key mcp <id> none # no MCP server (all: every one)
@@ -805,7 +806,10 @@ and keys its requests may use, picked in the same menu right after their
provider's models — an account by who is signed in, a key by its
fingerprint — or with
`magpie gateway-key accounts <id> codex/me@example.com openai/<key id>`
(`all` takes the restriction off). The list holds a key to some accounts
(`all` takes the restriction off). An entry `<provider>/!<account>` keeps
that account out instead: the key may use every other account, those
signed in later too, and is held to no model by it (LeiWang_2000 on X;
the menu's "Keep accounts out…"). The list holds a key to some accounts
**of the providers it names**: a provider it names no account of, the key
uses as its models allow. A key that lists accounts and **no model** may use
only the models of those accounts' providers (`access.HeldModels`, each
+1 -1
View File
@@ -366,7 +366,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.
- A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Models → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. A preset with no regions may name its embedding and rerank models itself (`PresetDef.Embeddings`, `Rerankers`): Voyage AI (`voyage`, heatonz on Discord) has no `/models` and serves only those, so they are its whole list, each marked with what it serves (`catalog.Model.Serves`), kept out of chat lists, and found on `/v1/embeddings` or `/v1/rerank` alone by `PlanRetrieval(kind)` (`TestVoyagePreset`, `TestVoyageModelsStayOnTheirRoutes`). [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanRerankers`, `PlanRetrieval`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests.
- A key's provider can have its model list off (`Provider.ListOff`, `ListsOff()`; axelburks on Discord: Ark's pay-as-you-go list names models that can't be asked for, each is asked by an endpoint id the user made). Nothing asks its vendor for a list: `Fetch`, `Refetch`, `List`, `RefreshLists`, a test, a new key's prefill and a resting key's probe (`ListAsks`) skip it, and `Fetch`/`List` return `ErrListOff`. A list fetched before and models.dev's are not read, so only the ids the user added are served. A signed-in account and a plugin list their models as their sign-in does, so the switch is a key provider's alone (`takesListOff` in `/api/providers`). The editor shows it as Fetch the model list, ticked by default; unticked, Fetch models and Forget go. A save that doesn't name `listOff` keeps it. The CLI takes `list=off|on`. Tests: `TestListOffAsksNoListAndServesTheIDsAdded`, `TestProviderSaveListOff`, `provider-list-off.test.cjs`.
- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as its models allow. A key that lists accounts and no model may use only those accounts' providers' models (`access.HeldModels`, applied where `access.Authenticate` makes the request's `Identity`, so every route's model check holds it; Linka on Discord: ticking only an account let the key list and use every other provider's models; `TestGatewayKeyAccountsOnlyHoldTheModels`). The key's menu says so on each account of such a provider ("Used: no … account is picked" when its models reach the provider, "Not used: no … model or account is picked" when they don't), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served), or, with no model picked, that only the picked accounts' providers' models are the key's. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's.
- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as its models allow. A key that lists accounts and no model may use only those accounts' providers' models (`access.HeldModels`, applied where `access.Authenticate` makes the request's `Identity`, so every route's model check holds it; Linka on Discord: ticking only an account let the key list and use every other provider's models; `TestGatewayKeyAccountsOnlyHoldTheModels`). The key's menu says so on each account of such a provider ("Used: no … account is picked" when its models reach the provider, "Not used: no … model or account is picked" when they don't), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served), or, with no model picked, that only the picked accounts' providers' models are the key's. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's. An entry `<provider>/!<ref>` keeps an account out instead (`access.ExcludeMark`; LeiWang_2000 on X: a key of every account but a few, so one signed in later is used too). `AllowsAccount` refuses it first and counts only the entries naming accounts to use for "the providers it names", so a provider with only kept-out entries is used on every other account; `HeldModels` and `AccountModels` ignore such entries, so a key that only keeps some out may use every model; an issued key keeps out what its issuer does (`foldAccounts`), `CleanAccounts` refuses an account both used and kept out, and a magpie older than the mark reads it as an account no provider has, holding the key to none of that provider's (fails closed). The row menu's "Keep accounts out…" picks them (`gatewayKeptOutPick`, `gateway-key-kept-out.test.cjs`); `TestGatewayKeyKeptOut*` and `TestKeptOut*` hold every route to it.
- A routing group may be held to some accounts the same way (`Group.Accounts`, duanckham on X): a request through it uses only those of a provider it names, and with a gateway key only those both allow. Entries are resolved and checked when the group is saved (`cleanGroupAccounts`, `ResolveAccount`), and dropped from a shared or imported group. See [gateway-routing](gateway-routing.md#a-route-group-held-to-chosen-accounts).
- A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says `used 0` with no `reset_at`, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. `ForgetBalances` (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (`keyID`), with windows of its own.
- A Volcengine Ark provider's access key (`TakesVolcAccessKey`: any of its bases on `ark.<region>.volces.com`) is kept with its keys and never sent to the GUI: `/api/providers` tells the editor its ID and whether a Secret is saved (`accessKey`). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends `""`, #1821), and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync keeps this machine's (`KeepSecrets` in `Restore`, `Mirror`, davsync's `take`) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (`SecretHeader`) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (`accessKeyCard`, `needsAccessKey`), with a button to the provider's settings, not a card left out. A `providers.json` saved with a UTF-8 BOM is read through it, not taken for a broken file whose `.bak` stands in. The plan read is the endpoint's: `/api/coding` asks `GetCodingPlanUsage`, `/api/plan` asks `GetAFPUsage`, pay-as-you-go (`/api/v3`) has no card; the region is the host's. One card is read for each access key and plan. `GetCodingPlanUsage`'s reply (`QuotaUsage[]` with `Level`, `Percent`, `ResetTimestamp` in seconds) is the one three tools built on it read; `GetAFPUsage`'s buckets are read in each form those tools read (`Used` of `Quota` or `Total`, or `Percent`; `ResetTime` or `ResetTimestamp`), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (`ForgetPlanQuotas`).
+95 -9
View File
@@ -1,6 +1,7 @@
package access
import (
"cmp"
"errors"
"slices"
"strings"
@@ -17,8 +18,12 @@ import (
// its provider has now, so a typo can't quietly hold a key to nothing;
// one gone later — a key rotated, an account signed out — is kept as it
// is, matching nothing.
//
// An entry "<provider>/!<account>" keeps that account out instead
// (LeiWang_2000 on X): the key may use every other account, those signed
// in later too. An account is never both kept out and named.
func CleanAccounts(in []string) ([]string, error) {
var out []string
var cleaned []string
for _, a := range in {
a = strings.TrimSpace(a)
if a == "" {
@@ -31,12 +36,26 @@ func CleanAccounts(in []string) ([]string, error) {
if len(a) > 300 {
return nil, errors.New("A key's account is at most 300 characters")
}
ref, excl := strings.CutPrefix(ref, ExcludeMark)
if ref = strings.TrimSpace(ref); ref == "" {
return nil, errors.New("A key's account is <provider>/<account> or <provider>/<key id>, like codex/me@example.com: " + a)
}
kept, err := provider.ResolveAccount(pid, ref)
if err != nil {
return nil, err
}
if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, kept) }) {
out = append(out, kept)
if excl {
p, r, _ := strings.Cut(kept, "/")
kept = p + "/" + ExcludeMark + r
}
if !slices.ContainsFunc(cleaned, func(o string) bool { return strings.EqualFold(o, kept) }) {
cleaned = append(cleaned, kept)
}
}
out := cleaned
for _, a := range out {
if p, r, ok := excludedEntry(a); ok && slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, p+"/"+r) }) {
return nil, errors.New("A key's account is either used or kept out, not both: " + p + "/" + r)
}
}
if len(out) > 500 {
@@ -45,26 +64,65 @@ func CleanAccounts(in []string) ([]string, error) {
return out, nil
}
// ExcludeMark starts an entry's account to keep the key off it:
// "<provider>/!<ref>" (LeiWang_2000 on X). A magpie older than the mark
// reads it as an account no provider has, which holds the key to none of
// that provider's: it fails closed.
const ExcludeMark = "!"
// excludedEntry is the provider and account of an entry that keeps an
// account out, "<provider>/!<ref>".
func excludedEntry(a string) (pid, ref string, ok bool) {
pid, ref, cut := strings.Cut(strings.TrimSpace(a), "/")
if ref, ok = strings.CutPrefix(ref, ExcludeMark); !cut || !ok || ref == "" {
return "", "", false
}
return pid, ref, true
}
// Excluded says the entry keeps an account out, "<provider>/!<ref>".
func Excluded(a string) bool {
_, _, ok := excludedEntry(a)
return ok
}
// picksAccounts says some entry names an account to use, not only ones
// kept out.
func picksAccounts(accounts []string) bool {
return slices.ContainsFunc(accounts, func(a string) bool { return !Excluded(a) })
}
// AllowsAccount says the provider pid's account or key ref is among the
// key's accounts — "<provider>/<ref>", told apart in lower case, as
// accounts are. The list holds a key to some accounts **of the providers
// it names**: a provider it names no account of, the key uses as it
// always did, its every account and key. Any, for a key that lists none.
// An account the list keeps out ("<provider>/!<ref>") is never one, and
// keeps the key off no other: every account its provider signs in later
// is one the key may use.
func (who Identity) AllowsAccount(pid, ref string) bool {
if len(who.Accounts) == 0 {
return true
}
pid = strings.ToLower(strings.TrimSpace(pid))
key := pid + "/" + strings.ToLower(strings.TrimSpace(ref))
named := false
ref = strings.ToLower(strings.TrimSpace(ref))
key := pid + "/" + ref
named, used := false, false
for _, a := range who.Accounts {
if a = strings.ToLower(strings.TrimSpace(a)); a == key {
return true
a = strings.ToLower(strings.TrimSpace(a))
if p, r, ok := excludedEntry(a); ok {
if p == pid && r == ref && ref != "" {
return false
}
continue
}
if a == key {
used = true
} else if p, _, ok := strings.Cut(a, "/"); ok && p == pid {
named = true
}
}
return !named
return used || !named
}
// heldToNone is the account an entry "<provider>/<heldToNone>" names: none
@@ -119,8 +177,31 @@ func (who Identity) HeldToGroup(group string, accounts []string) Identity {
return who
}
// AccountsShown is a key's accounts as words say them: those it may use
// by names[entry] (provider.AccountNames), else the entry itself, and
// those it keeps out as "every account but …" (LeiWang_2000 on X).
func AccountsShown(names map[string]string, accounts []string) string {
var used, out []string
for _, a := range accounts {
if p, r, ok := excludedEntry(a); ok {
out = append(out, cmp.Or(names[p+"/"+r], p+"/"+r))
} else {
used = append(used, cmp.Or(names[a], a))
}
}
var parts []string
if len(used) > 0 {
parts = append(parts, strings.Join(used, ", "))
}
if len(out) > 0 {
parts = append(parts, "every account but "+strings.Join(out, ", "))
}
return strings.Join(parts, "; ")
}
// ShownAccounts is who's accounts as a message lists them: the entries
// HeldToGroup adds to name a provider with none of its accounts left out.
// An account kept out stays "<provider>/!<ref>".
func (who Identity) ShownAccounts() []string {
return slices.DeleteFunc(slices.Clone(who.Accounts), func(a string) bool { return strings.HasSuffix(a, "/"+heldToNone) })
}
@@ -140,12 +221,17 @@ func ReplaceAccount(pid, was, now string) (int, error) {
return 0, err
}
old := strings.ToLower(pid + "/" + was)
oldOut := strings.ToLower(pid + "/" + ExcludeMark + was)
moved := 0
for i := range keys {
for j, a := range keys[i].Accounts {
if strings.ToLower(strings.TrimSpace(a)) == old {
switch strings.ToLower(strings.TrimSpace(a)) {
case old:
keys[i].Accounts[j] = pid + "/" + now
moved++
case oldOut:
keys[i].Accounts[j] = pid + "/" + ExcludeMark + now
moved++
}
}
}
+148
View File
@@ -0,0 +1,148 @@
package access
import (
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A key may keep some accounts out instead of naming the ones it uses
// (LeiWang_2000 on X): "<provider>/!<account>" lets it use every other
// account of the provider, one signed in after the key was saved too,
// and never the one kept out.
func TestKeptOutAccounts(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "sk-1", Name: "First"}, {Key: "sk-2"}}}); err != nil {
t.Fatal(err)
}
k1, k2, k3 := provider.KeyID("sk-1"), provider.KeyID("sk-2"), provider.KeyID("sk-3")
// kept by its id, the mark kept, a name resolving to it too
for _, c := range []struct {
name string
in []string
want []string
bad string
}{
{"kept out by its fingerprint", []string{"relay/!" + k2}, []string{"relay/!" + k2}, ""},
{"kept out by the name it is shown by", []string{"relay/!First"}, []string{"relay/!" + k1}, ""},
{"once, told apart in lower case", []string{"relay/!" + k2, " RELAY/!" + strings.ToUpper(k2) + " "}, []string{"relay/!" + k2}, ""},
{"used and kept out is refused", []string{"relay/" + k1, "relay/!First"}, nil, "either used or kept out"},
{"a mark with no account", []string{"relay/!"}, nil, "<provider>/<account>"},
{"one the provider has not", []string{"relay/!" + k3}, nil, "has no key"},
} {
out, err := CleanAccounts(c.in)
if c.bad != "" {
if err == nil || !strings.Contains(err.Error(), c.bad) {
t.Errorf("%s: said %v, want %q in it", c.name, err, c.bad)
}
continue
}
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if !slices.Equal(out, c.want) {
t.Errorf("%s: kept %v, want %v", c.name, out, c.want)
}
}
who := Identity{Accounts: []string{"relay/!" + strings.ToUpper(k2)}}
if !who.AllowsAccount("relay", k1) || who.AllowsAccount("relay", k2) {
t.Fatal("kept out: the other used, it never")
}
// a key signed in after the key was saved is one it may use
if !who.AllowsAccount("relay", k3) {
t.Fatal("an account added later was held out")
}
if !who.AllowsAccount("other", k2) {
t.Fatal("another provider's was held")
}
// a provider with no account left: the list names none it uses, so
// it serves as it always did
if !who.AllowsAccount("relay", "") {
t.Fatal("no account named to use, yet the provider was held")
}
// used and kept out of different providers
mixed := Identity{Accounts: []string{"relay/" + k1, "codex/!acct-2"}}
if !mixed.AllowsAccount("relay", k1) || mixed.AllowsAccount("relay", k3) {
t.Fatal("relay is held to k1")
}
if !mixed.AllowsAccount("codex", "acct-1") || !mixed.AllowsAccount("codex", "acct-9") || mixed.AllowsAccount("codex", "acct-2") {
t.Fatal("codex: every account but acct-2")
}
// kept out holds the key to no model
if ms := HeldModels(nil, []string{"relay/!" + k2}); ms != nil {
t.Fatalf("kept out only: models %v, want every one", ms)
}
if ms := HeldModels(nil, []string{"relay/" + k1, "codex/!acct-2"}); !slices.Equal(ms, []string{"relay/*"}) {
t.Fatalf("models %v", ms)
}
// shown
names := map[string]string{"relay/" + k1: "relay/First", "relay/" + k2: "relay/sk-…2"}
if got := AccountsShown(names, []string{"relay/!" + k2}); got != "every account but relay/sk-…2" {
t.Fatalf("shown %q", got)
}
if got := AccountsShown(names, []string{"relay/" + k1, "codex/!acct-2"}); got != "relay/First; every account but codex/acct-2" {
t.Fatalf("shown %q", got)
}
}
// An issued key folds in its issuer's kept-out accounts, and may not
// name one of them.
func TestKeptOutFolded(t *testing.T) {
for _, c := range []struct {
child, issuer, want []string
}{
{nil, []string{"codex/!a2"}, nil},
{[]string{"codex/a1"}, []string{"codex/!a2"}, []string{"codex/a1", "codex/!a2"}},
{[]string{"codex/a2", "codex/a1"}, []string{"codex/!a2"}, []string{"codex/a1", "codex/!a2"}},
{[]string{"codex/!a3"}, []string{"codex/!a2"}, []string{"codex/!a3", "codex/!a2"}},
{[]string{"codex/!a3"}, []string{"codex/a1"}, []string{"codex/a1", "codex/!a3"}},
} {
got := foldAccounts(c.child, c.issuer)
if c.want == nil {
c.want = c.issuer
}
if !slices.Equal(got, c.want) {
t.Errorf("foldAccounts(%v, %v) = %v, want %v", c.child, c.issuer, got, c.want)
}
who := Identity{Accounts: got}
if who.AllowsAccount("codex", "a2") {
if slices.Contains(c.issuer, "codex/!a2") {
t.Errorf("%v: the issuer's kept-out account was let in", got)
}
}
}
issuer := Identity{Accounts: []string{"codex/!a2"}}
if issuer.allowsEntry("codex/a2") || !issuer.allowsEntry("codex/a9") || !issuer.allowsEntry("codex/!a3") {
t.Fatal("allowsEntry")
}
}
// A key value replaced in place (#1869) moves the keys keeping it out too.
func TestKeptOutReplaced(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "sk-1"}, {Key: "sk-2"}}}); err != nil {
t.Fatal(err)
}
if _, err := Update("add-key", Change{Name: "Desk"}); err != nil {
t.Fatal(err)
}
keys, _ := List()
id := keys[len(keys)-1].ID
if _, err := Update("accounts-key", Change{Key: id, Accounts: []string{"relay/!" + provider.KeyID("sk-2")}}); err != nil {
t.Fatal(err)
}
n, err := ReplaceAccount("relay", provider.KeyID("sk-2"), provider.KeyID("sk-2b"))
if err != nil || n != 1 {
t.Fatalf("moved %d, %v", n, err)
}
keys, _ = List()
if got := keys[len(keys)-1].Accounts; !slices.Equal(got, []string{"relay/!" + provider.KeyID("sk-2b")}) {
t.Fatalf("accounts %v", got)
}
}
+36 -2
View File
@@ -320,7 +320,7 @@ func ScopeBrowser(id string) error {
// identityOf is who k is, folded into its issuer when it has one.
func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency}
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency}
// the default key as Default tells it: marked LAN, or the id the
// settings name (settings read only for an unmarked key)
who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID)
@@ -333,7 +333,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
}
p := keys[j]
pModels := HeldModels(p.Models, p.Accounts)
who.AccountModels = len(k.Models) == 0 && len(p.Models) == 0 && (len(k.Accounts) > 0 || len(p.Accounts) > 0)
who.AccountModels = len(k.Models) == 0 && len(p.Models) == 0 && (picksAccounts(k.Accounts) || picksAccounts(p.Accounts))
if len(pModels) > 0 {
if who.Models = foldModels(who.Models, pModels); len(who.Models) == 0 {
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q may use none of its models now: the key it was issued under no longer lets it", k.Name)}
@@ -386,7 +386,37 @@ func foldModels(child, issuer []string) []string {
// foldAccounts holds a child to the issuer's accounts too: of each
// provider the issuer names accounts of, the child's own of them that the
// issuer has, else the issuer's; the child's of other providers as given.
// An account either keeps out stays out (LeiWang_2000 on X).
func foldAccounts(child, issuer []string) []string {
if len(issuer) == 0 {
return child
}
split := func(as []string) (use, out []string) {
for _, a := range as {
if Excluded(a) {
out = append(out, a)
} else {
use = append(use, a)
}
}
return
}
cu, co := split(child)
pu, po := split(issuer)
out := foldUsed(cu, pu)
if len(po) > 0 {
out = slices.DeleteFunc(out, func(a string) bool { return !(Identity{Accounts: po}).allowsEntry(a) })
}
for _, a := range append(co, po...) {
if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, a) }) {
out = append(out, a)
}
}
return out
}
// foldUsed is foldAccounts over the accounts each names to use.
func foldUsed(child, issuer []string) []string {
if len(issuer) == 0 {
return child
}
@@ -420,7 +450,11 @@ func foldAccounts(child, issuer []string) []string {
}
// allowsEntry: the account entry "<provider>/<ref>" is one who may use.
// An entry keeping an account out asks for nothing, so who allows it.
func (who Identity) allowsEntry(a string) bool {
if Excluded(a) {
return true
}
p, ref, _ := strings.Cut(a, "/")
return who.AllowsAccount(p, ref)
}
+4 -2
View File
@@ -41,14 +41,16 @@ func CleanModels(in []string) ([]string, error) {
// it every model of every other provider, as it did when the accounts
// held only the providers they name (#905). A key that lists models is
// held to those, its accounts holding the providers they name, as before.
// An account kept out ("<provider>/!<ref>", LeiWang_2000 on X) holds the
// key to no model: a key that only keeps some out may use every model.
func HeldModels(models, accounts []string) []string {
if len(models) > 0 || len(accounts) == 0 {
if len(models) > 0 || !picksAccounts(accounts) {
return models
}
var out []string
for _, a := range accounts {
pid, _, ok := strings.Cut(strings.TrimSpace(a), "/")
if !ok || pid == "" {
if !ok || pid == "" || Excluded(a) {
continue
}
m := pid + "/*"
+13 -15
View File
@@ -1,7 +1,6 @@
package cli
import (
"cmp"
"encoding/json"
"fmt"
"io"
@@ -141,11 +140,8 @@ func gatewayKeysTo(out io.Writer, args []string) error {
}
accounts := "all"
if len(k.Accounts) > 0 {
shown := make([]string, len(k.Accounts))
for i, a := range k.Accounts {
shown[i] = cmp.Or(names[a], a)
}
accounts = strings.Join(shown, ",")
// a column: no space after each comma, as before
accounts = strings.ReplaceAll(access.AccountsShown(names, k.Accounts), ", ", ",")
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", k.ID, strings.Map(func(r rune) rune {
if r < 32 || r == 127 {
@@ -471,8 +467,8 @@ func gatewayKeyModels(out io.Writer, args []string) error {
return fmt.Errorf("Key not found")
}
k := keys[i]
if len(k.Models) == 0 && len(k.Accounts) > 0 {
_, err = fmt.Fprintf(out, "%s: only its accounts' providers' models, %s\n", k.Name, strings.Join(access.HeldModels(nil, k.Accounts), ", "))
if ms := access.HeldModels(nil, k.Accounts); len(k.Models) == 0 && len(ms) > 0 {
_, err = fmt.Fprintf(out, "%s: only its accounts' providers' models, %s\n", k.Name, strings.Join(ms, ", "))
return err
}
if len(k.Models) == 0 {
@@ -557,9 +553,11 @@ func limitWords(k access.Key, now time.Time) string {
// gatewayKeyAccounts shows or sets a key's account whitelist (#905): the
// accounts and keys it may use, "<provider>/<account>" — a signed-in
// account by its name, a key by its KeyID — every one when none are set.
// "<provider>/!<account>" keeps one out instead (LeiWang_2000 on X): the
// key may use every other, those signed in later too.
func gatewayKeyAccounts(out io.Writer, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: magpie gateway-key accounts <id> [all | <provider>/<account>|<provider>/<key id> ...]")
return fmt.Errorf("usage: magpie gateway-key accounts <id> [all | <provider>/<account>|<provider>/<key id>|<provider>/!<account> ...]")
}
id := args[0]
if len(args) > 1 {
@@ -584,13 +582,13 @@ func gatewayKeyAccounts(out io.Writer, args []string) error {
_, err = fmt.Fprintf(out, "%s: every account\n", k.Name)
return err
}
// shown by who is signed in, kept by the account's stable id (#905)
names := provider.AccountNames()
shown := make([]string, len(k.Accounts))
for i, a := range k.Accounts {
shown[i] = cmp.Or(names[a], a)
// shown by who is signed in, kept by the account's stable id (#905);
// one kept out, "<provider>/!<account>", as every account but it
shown := access.AccountsShown(provider.AccountNames(), k.Accounts)
if !strings.HasPrefix(shown, "every account but ") {
shown = "only " + shown
}
_, err = fmt.Fprintf(out, "%s: only %s\n", k.Name, strings.Join(shown, ", "))
_, err = fmt.Fprintf(out, "%s: %s\n", k.Name, shown)
return err
}
+17
View File
@@ -314,6 +314,23 @@ func TestGatewayKeyAccountsCLI(t *testing.T) {
t.Error("accepted", args)
}
}
// every account but one (LeiWang_2000 on X), kept by its fingerprint
if got, err := call("accounts", id, "relay/!Second"); err != nil || got != "Phone: every account but relay/Second\n" {
t.Fatal(got, err)
}
if keys, _ = access.List(); !slices.Equal(keys[0].Accounts, []string{"relay/!" + k2}) {
t.Fatal("kept", keys[0].Accounts)
}
if got, _ := call("list"); !strings.Contains(got, "every account but relay/Second") {
t.Fatal(got)
}
// kept out, it holds the key to no model
if got, err := call("models", id); err != nil || strings.Contains(got, "only its accounts") {
t.Fatal(got, err)
}
if _, err := call("accounts", id, "relay/First", "relay/!First"); err == nil {
t.Error("an account both used and kept out was accepted")
}
if got, err := call("accounts", id, "all"); err != nil || got != "Phone: every account\n" {
t.Fatal(got, err)
}
@@ -0,0 +1,283 @@
package gateway
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// LeiWang_2000 on X: a gateway key may keep some accounts out instead of
// naming the ones it uses ("<provider>/!<account>"), so an account added
// after the key was saved is one it uses, and one kept out is never
// asked, on every route that spends an account: chat, Anthropic's
// messages, responses, count_tokens, /v1/models, images, videos, System
// One, and a ChatGPT account's turn on magpie's endpoint and on Codex's.
// keptOutUp stands in for a keyed provider on every route, noting the key
// each request came with.
type keptOutUp struct {
*httptest.Server
mu sync.Mutex
used []string
}
func (u *keptOutUp) take() []string {
u.mu.Lock()
defer u.mu.Unlock()
out := u.used
u.used = nil
return out
}
func newKeptOutUp(t *testing.T) *keptOutUp {
u := &keptOutUp{}
u.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if key == "" {
key = r.Header.Get("x-api-key")
}
u.mu.Lock()
u.used = append(u.used, key)
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
p := r.URL.Path
switch {
case strings.HasPrefix(p, "/decide"):
io.WriteString(w, `{"answers":{"intent":{"choice":"bug"}},"usage":{"input_tokens":10,"output_tokens":2}}`)
case strings.HasSuffix(p, "/messages/count_tokens"):
io.WriteString(w, `{"input_tokens":5}`)
case strings.HasSuffix(p, "/messages"):
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"from `+key+`"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":1}}`)
case strings.HasSuffix(p, "/images/generations"):
io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}]}`)
case strings.HasSuffix(p, "/videos"):
io.WriteString(w, `{"id":"vid-1"}`)
case strings.Contains(string(b), `"stream":true`):
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"from `+key+`"}}]}`,
`data: {"id":"c1","object":"chat.completion.chunk","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`,
`data: [DONE]`))
default:
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"from `+key+`"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
}
}))
t.Cleanup(u.Close)
return u
}
func TestGatewayKeyKeptOutAccountsKeyedRoutes(t *testing.T) {
fresh(t)
up := newKeptOutUp(t)
relay := provider.Provider{ID: "relay", Name: "Relay", Chat: up.URL + "/v1", Anthropic: up.URL,
Key: "kA", Keys: []provider.KeyAccount{{Key: "kB"}}, Models: []string{"m", "gpt-image-1"}}
if err := provider.Save(relay); err != nil {
t.Fatal(err)
}
office := provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset,
Chat: up.URL + "/v1", Key: "oA", Keys: []provider.KeyAccount{{Key: "oB"}}, Models: []string{"grok-imagine-video"}}
if err := provider.Save(office); err != nil {
t.Fatal(err)
}
jev := provider.Provider{ID: "jev", Name: "Jev", Decide: up.URL + "/decide/v1", Key: "jA", Keys: []provider.KeyAccount{{Key: "jB"}}, Models: []string{"jev-latest"}}
if err := provider.Save(jev); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("relay", up.URL+"/v1", []catalog.Model{{ID: "m"}, {ID: "gpt-image-1"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Most")
// every account but these: all the providers have now
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{
"relay/!" + provider.KeyID("kA"), "relay/!" + provider.KeyID("kB"),
"office/!" + provider.KeyID("oA"), "office/!" + provider.KeyID("oB"),
"jev/!" + provider.KeyID("jA"), "jev/!" + provider.KeyID("jB"),
}}); err != nil {
t.Fatal(err)
}
s := New()
ask := func(method, path, body string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
return w
}
routes := []struct {
name, path, body string
// counted locally when no account may count it
local bool
}{
{"chat", "/v1/chat/completions", `{"model":"relay/m","messages":[{"role":"user","content":"hi"}]}`, false},
{"messages", "/v1/messages", `{"model":"relay/m","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, false},
{"responses", "/v1/responses", `{"model":"relay/m","input":"hi"}`, false},
{"count_tokens", "/v1/messages/count_tokens", `{"model":"relay/m","messages":[{"role":"user","content":"hi"}]}`, true},
{"images", "/v1/images/generations", `{"model":"relay/gpt-image-1","prompt":"a magpie"}`, false},
{"videos", "/v1/videos", `{"model":"office/grok-imagine-video","prompt":"a magpie"}`, false},
{"systemone", "/v1/systemone", `{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`, false},
}
listed := func() bool {
w := ask("GET", "/v1/models", "")
return strings.Contains(w.Body.String(), `"relay/m"`)
}
// every account kept out: nothing is asked, nothing listed
for _, c := range routes {
w := ask("POST", c.path, c.body)
if got := up.take(); len(got) != 0 {
t.Fatalf("%s: a kept-out account was asked: %v (%d %s)", c.name, got, w.Code, w.Body.String())
}
if !c.local && w.Code == 200 {
t.Fatalf("%s: served with every account kept out: %s", c.name, w.Body.String())
}
}
if listed() {
t.Fatal("/v1/models lists a provider whose every account is kept out")
}
// an account added after the key was saved is the key's, on every
// route; the kept-out ones, first in the order, are never asked
relay.Keys = append(relay.Keys, provider.KeyAccount{Key: "kC"})
office.Keys = append(office.Keys, provider.KeyAccount{Key: "oC"})
jev.Keys = append(jev.Keys, provider.KeyAccount{Key: "jC"})
for _, p := range []provider.Provider{relay, office, jev} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
for _, c := range routes {
w := ask("POST", c.path, c.body)
if w.Code != 200 {
t.Fatalf("%s: the account added later didn't serve: %d %s", c.name, w.Code, w.Body.String())
}
want := map[string]string{"videos": "oC", "systemone": "jC"}[c.name]
if want == "" {
want = "kC"
}
if got := up.take(); !slices.Equal(got, []string{want}) {
t.Fatalf("%s: asked with %v, want %s alone", c.name, got, want)
}
}
if !listed() {
t.Fatal("/v1/models leaves out the provider of the account added later")
}
}
// A ChatGPT account kept out is never asked, on magpie's endpoint and on
// Codex's, and one signed in after the key was saved serves.
func TestGatewayKeyKeptOutCodexAccounts(t *testing.T) {
heads := twoAccounts(t)
keys, secrets := newCaller(t, "Most")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"codex/!me@example.com"}}); err != nil {
t.Fatal(err)
}
s := New()
post := func(path, model string) (int, string) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(`{"model":"`+model+`","stream":true,"input":"ping"}`))
req.Header.Set("Authorization", "Bearer "+secrets[0])
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
accounts := func() []string {
var out []string
for _, h := range *heads {
out = append(out, h.Get("chatgpt-account-id"))
}
*heads = nil
return out
}
// me, first in the order, kept out: spare serves, me never asked
for path, model := range pinPaths {
for range 2 {
if code, body := post(path, model); code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("%s: %d %s", path, code, body)
}
if got := accounts(); !slices.Equal(got, []string{"acct-2"}) {
t.Fatalf("%s: asked %v", path, got)
}
}
}
// both kept out: no account asked
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"codex/!me@example.com", "codex/!spare@example.com"}}); err != nil {
t.Fatal(err)
}
for path, model := range pinPaths {
if code, body := post(path, model); code == 200 {
t.Fatalf("%s: served with every account kept out: %s", path, body)
}
if got := accounts(); len(got) != 0 {
t.Fatalf("%s: a kept-out account was asked: %v", path, got)
}
}
// a third account signed in after the key was saved serves
codexSignInLater(t, "third@example.com", "acct-3")
for path, model := range pinPaths {
if code, body := post(path, model); code != 200 || !strings.Contains(body, "from acct-3") {
t.Fatalf("%s: the account signed in later: %d %s", path, code, body)
}
if got := accounts(); !slices.Equal(got, []string{"acct-3"}) {
t.Fatalf("%s: asked %v", path, got)
}
}
}
// codexSignInLater adds a ChatGPT account to magpie's saved sign-ins, as
// signing in from magpie does, after codexSignedIn.
func codexSignInLater(t *testing.T, email, acct string) {
t.Helper()
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
}
path := filepath.Join(filepath.Dir(provider.Path()), "logins.json")
var saved []map[string]any
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(b, &saved); err != nil {
t.Fatal(err)
}
saved = append(saved, map[string]any{"agent": "codex", "user": email, "on": true, "seen": time.Now(),
"auth": map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": claims(map[string]any{"email": email}),
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "who": acct}),
"refresh_token": "r-" + acct, "account_id": acct}}})
if err := os.WriteFile(path, mustJSON(saved), 0o600); err != nil {
t.Fatal(err)
}
provider.ForgetAccounts()
}
// A key's quotas (#2216) are told for every account but the ones it keeps
// out, one signed in later too.
func TestGatewayKeyKeptOutQuotaCards(t *testing.T) {
fresh(t)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Key: "kA", Keys: []provider.KeyAccount{{Key: "kB", Name: "Bee"}, {Key: "kC", Name: "Sea"}}, Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
who := access.Identity{KeyID: "k", Quotas: true, Accounts: []string{"relay/!" + provider.KeyID("kB")}}
s := newQuotaScope(who, []provider.Entry{{Provider: provider.Provider{ID: "relay"}, Model: "m"}})
if !s.provider("relay") {
t.Fatal("the provider's quota is the key's")
}
if s.card("relay", "Bee") || !s.card("relay", "Sea") {
t.Fatal("Bee is kept out, Sea is not")
}
}
+1 -10
View File
@@ -785,20 +785,11 @@ func groupsHeldError(model string, left []Weighed) string {
// named as the accounts list names them, "<provider>/<user>" where a
// provider has the account now, the id alone otherwise.
func keyAccountNames(who access.Identity) string {
names := provider.AccountNames()
accounts := who.ShownAccounts()
if len(accounts) == 0 {
return "none"
}
shown := make([]string, len(accounts))
for i, a := range accounts {
if n, ok := names[a]; ok {
shown[i] = n
} else {
shown[i] = a
}
}
return strings.Join(shown, ", ")
return access.AccountsShown(provider.AccountNames(), accounts)
}
// countHeld answers the 403 a gateway key held to some models (#882) gets
+32
View File
@@ -525,6 +525,14 @@ const I18N = {
"{n} MCP servers": "{n} 个 MCP 服务器",
"Only these MCP servers and tools: {list}": "仅限这些 MCP 服务器和工具:{list}",
"MCP servers this key may use": "这个密钥可用的 MCP 服务器",
"Keep accounts out": "排除账号",
"No account kept out": "不排除账号",
"Accounts this key keeps out": "这个密钥排除的账号",
"Not {name}": "排除 {name}",
"{n} accounts kept out": "排除 {n} 个账号",
"Every account but: {list}": "除这些账号外都可用:{list}",
"{name} may use every account but those kept out": "{name} 可用除排除账号外的所有账号",
"{name} keeps no account out": "{name} 不再排除账号",
"{name} may use every MCP server": "{name} 可使用全部 MCP 服务器",
"{name} may use no MCP server": "{name} 不可使用 MCP 服务器",
"{name} may use only the MCP servers and tools picked": "{name} 只可使用所选的 MCP 服务器和工具",
@@ -5359,6 +5367,14 @@ const I18N = {
"{n} MCP servers": "{n} 個 MCP 伺服器",
"Only these MCP servers and tools: {list}": "僅限這些 MCP 伺服器和工具:{list}",
"MCP servers this key may use": "這個金鑰可用的 MCP 伺服器",
"Keep accounts out": "排除帳號",
"No account kept out": "不排除帳號",
"Accounts this key keeps out": "這個金鑰排除的帳號",
"Not {name}": "排除 {name}",
"{n} accounts kept out": "排除 {n} 個帳號",
"Every account but: {list}": "除這些帳號外都可用:{list}",
"{name} may use every account but those kept out": "{name} 可用除排除帳號外的所有帳號",
"{name} keeps no account out": "{name} 不再排除帳號",
"{name} may use every MCP server": "{name} 可使用全部 MCP 伺服器",
"{name} may use no MCP server": "{name} 不可使用 MCP 伺服器",
"{name} may use only the MCP servers and tools picked": "{name} 只可使用所選的 MCP 伺服器和工具",
@@ -10154,6 +10170,14 @@ const I18N = {
"{n} MCP servers": "{n} 個の MCP サーバー",
"Only these MCP servers and tools: {list}": "この MCP サーバーとツールのみ:{list}",
"MCP servers this key may use": "このキーが使える MCP サーバー",
"Keep accounts out": "アカウントを除外",
"No account kept out": "除外なし",
"Accounts this key keeps out": "このキーが除外するアカウント",
"Not {name}": "{name} を除外",
"{n} accounts kept out": "{n} 件のアカウントを除外",
"Every account but: {list}": "これら以外のすべてのアカウント:{list}",
"{name} may use every account but those kept out": "{name} は除外したもの以外のすべてのアカウントを使えます",
"{name} keeps no account out": "{name} はアカウントを除外しません",
"{name} may use every MCP server": "{name} はすべての MCP サーバーを使えます",
"{name} may use no MCP server": "{name} は MCP サーバーを使えません",
"{name} may use only the MCP servers and tools picked": "{name} は選んだ MCP サーバーとツールだけを使えます",
@@ -14967,6 +14991,14 @@ const I18N = {
"{n} MCP servers": "{n} MCP-Server",
"Only these MCP servers and tools: {list}": "Nur diese MCP-Server und Werkzeuge: {list}",
"MCP servers this key may use": "MCP-Server, die dieser Schlüssel nutzen darf",
"Keep accounts out": "Konten ausschließen",
"No account kept out": "Kein Konto ausgeschlossen",
"Accounts this key keeps out": "Konten, die dieser Schlüssel ausschließt",
"Not {name}": "Ohne {name}",
"{n} accounts kept out": "{n} Konten ausgeschlossen",
"Every account but: {list}": "Alle Konten außer: {list}",
"{name} may use every account but those kept out": "{name} darf alle Konten außer den ausgeschlossenen nutzen",
"{name} keeps no account out": "{name} schließt kein Konto aus",
"{name} may use every MCP server": "{name} darf alle MCP-Server nutzen",
"{name} may use no MCP server": "{name} darf keinen MCP-Server nutzen",
"{name} may use only the MCP servers and tools picked": "{name} darf nur die gewählten MCP-Server und Werkzeuge nutzen",
+67 -3
View File
@@ -227,7 +227,7 @@ function renderGatewayKeys() {
tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id });
// the copy sits by the key it copies (the owner: stranded among the
// badges it read as nobody's); Rotate and Remove wait in the row's menu
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k));
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k));
const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u));
if (under.length) row.classList.add("with-limit"), row.append(...under);
list.append(row);
@@ -309,6 +309,7 @@ function gatewayKeyPage() {
const ROTATE_GLYPH = "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3.25h-3.25";
const REMOVE_GLYPH = "M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5M7 7v4M9 7v4";
const KEEP_OUT_GLYPH = "M8 1.8a6.2 6.2 0 1 0 0 12.4A6.2 6.2 0 0 0 8 1.8zM3.6 3.6l8.8 8.8";
const MCP_GLYPH = "M6 2.5v3M10 2.5v3M4.5 5.5h7V8a3.5 3.5 0 0 1-7 0zM8 11.5v2";
const POWER_GLYPH = "M8 2.5v5M4.8 4.6a4.75 4.75 0 1 0 6.4 0";
function gatewayKeyMore(k) {
@@ -336,6 +337,9 @@ function gatewayKeyMore(k) {
// the MCP servers and tools it may use (wakaka on Discord); the
// Browser key connects the extension alone
...(k.browser ? [] : [{ name: "MCP servers", icon: MCP_GLYPH, run: () => gatewayMCPPick(k, more) }]),
// every account but some, those signed in later too (LeiWang_2000
// on X); the Browser key uses no account
...(k.browser ? [] : [{ name: "Keep accounts out", icon: KEEP_OUT_GLYPH, run: () => gatewayKeptOutPick(k, more) }]),
{ name: "Rotate key", icon: ROTATE_GLYPH, run: () => askGatewayKey(k, true) },
{ name: "Remove", icon: REMOVE_GLYPH, sep: true, run: () => askGatewayKey(k, false) },
]);
@@ -419,7 +423,9 @@ let keyModelsLoading = null;
// it may, always shown. A pick is sent when the menu closes.
function gatewayModelsBadge(k) {
const ms = k.models || [];
const as = k.accounts || [];
// the accounts kept out are gatewayKeptOutPick's, sent back as they are
const keptOut = (k.accounts || []).filter(isKeptOut);
const as = (k.accounts || []).filter((a) => !isKeptOut(a));
const b = el("button", "amodels key-models" + (ms.length || as.length ? " set" : ""));
b.type = "button";
b.textContent = !ms.length && !as.length ? t("All models")
@@ -521,7 +527,9 @@ function gatewayModelsBadge(k) {
: pickedAccounts.length ? "{name} may use only the picked accounts' models" : "{name} may use every model", { name: k.name }), "ok");
}
if (pickedAccounts.length !== as.length || pickedAccounts.some((v) => !as.includes(v))) {
await gatewayKeyAction("accounts-key", { key: k.id, accounts: pickedAccounts });
// an account picked is kept out no longer
const out = keptOut.filter((v) => !pickedAccounts.some((a) => a.toLowerCase() === keptIn(v).toLowerCase()));
await gatewayKeyAction("accounts-key", { key: k.id, accounts: [...pickedAccounts, ...out] });
}
})();
}, "Models this key may use", "sess-menu", "right");
@@ -545,6 +553,62 @@ function gatewayModelsBadge(k) {
return b;
}
// ---- the accounts a gateway key keeps out (LeiWang_2000 on X) ----
// isKeptOut: an account entry "<provider>/!<id>" keeps that account out
// (access.ExcludeMark): the key uses every other, those signed in later too
const isKeptOut = (a) => /^[^/]+\/!./.test(a);
// keptIn is the account a kept-out entry names, "<provider>/<id>"
const keptIn = (a) => a.replace("/!", "/");
// gatewayKeptOutPick picks the accounts a key keeps out, in the app's
// menu, from the row's menu and from the key's badge once it keeps some
// out. An account picked to use (gatewayModelsBadge) and kept out here is
// kept out: it is taken off the picked ones.
async function gatewayKeptOutPick(k, anchor) {
const as = k.accounts || [];
const out = as.filter(isKeptOut);
let accounts = [];
try { ({ accounts } = await api("caller-keys/models")); } catch (err) { status(t(err.message), "err"); return; }
if (!anchor.isConnected) return;
const opts = [{ v: "", name: "No account kept out", note: "" }];
for (const a of accounts || []) {
const slash = a.id.indexOf("/");
opts.push({ v: a.id.slice(0, slash) + "/!" + a.id.slice(slash + 1), name: a.name, note: a.plan ? a.providerName + " · " + a.plan : a.providerName, literalName: true });
}
// one kept out and signed out since stays kept out, as the CLI kept it
for (const v of out) if (!opts.some((o) => o.v === v)) opts.push({ v, name: keptIn(v), note: "Not signed in now", literalName: true });
openProtoMenu(anchor, opts, [...out], (picked) => {
if (picked.length === out.length && picked.every((v) => out.includes(v))) return;
const used = as.filter((a) => !isKeptOut(a) && !picked.some((v) => keptIn(v).toLowerCase() === a.toLowerCase()));
(async () => {
const done = await gatewayKeyAction("accounts-key", { key: k.id, accounts: [...used, ...picked] });
if (done) status(t(picked.length ? "{name} may use every account but those kept out" : "{name} keeps no account out", { name: k.name }), "ok");
})();
}, "Accounts this key keeps out", "sess-menu", "right");
}
// gatewayKeptOutBadge says which accounts a key keeps out; a key that
// keeps none out has none (the row's menu sets it)
function gatewayKeptOutBadge(k) {
const out = (k.accounts || []).filter(isKeptOut);
if (!out.length) return [];
const b = el("button", "amodels key-out set");
b.type = "button";
b.textContent = out.length === 1 ? t("Not {name}", { name: accountShown(keptIn(out[0])) }) : t("{n} accounts kept out", { n: out.length });
b.title = t("Every account but: {list}", { list: out.map((v) => accountShown(keptIn(v))).join(", ") });
b.setAttribute("aria-label", t("Accounts this key keeps out"));
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
b.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
gatewayKeptOutPick(k, b);
};
return [b];
}
// gatewayMCPPick picks the MCP servers and tools a key may use (wakaka
// on Discord), as gatewayModelsBadge picks its models: a server whole, or
// some of its tools, or none. It opens from the row's menu, and from the
+3 -3
View File
@@ -105,9 +105,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const menu = page.locator(".row-menu");
await menu.waitFor();
const items = (await menu.getByRole("menuitem").allTextContents()).map((s) => s.trim());
assert.equal(items.length, 5);
if (w.rotate) assert.deepEqual(items.filter((s) => !/MCP/.test(s)), [w.off, w.readOnly, w.rotate, w.remove]);
assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Make read-only"), t("MCP servers"), t("Rotate key"), t("Remove")]));
assert.equal(items.length, 6);
if (w.rotate) assert.deepEqual(items.filter((s) => !/MCP/.test(s)).filter((s, i) => i !== 2), [w.off, w.readOnly, w.rotate, w.remove]);
assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Make read-only"), t("MCP servers"), t("Keep accounts out"), t("Rotate key"), t("Remove")]));
// off from the menu, then on again: the key stays, only its switch moves
await menu.getByRole("menuitem").first().click();
await menu.waitFor({ state: "detached" });
@@ -0,0 +1,113 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A gateway key may keep some accounts out instead of naming the ones it
// uses (LeiWang_2000 on X), so an account signed in later is used too:
// picked in the app's own menu from the key row's menu, sent as
// "accounts-key" with "<provider>/!<account>" entries when the menu
// closes, shown in a badge that opens the same menu; an account the key
// was held to and is now kept out leaves the held ones, and "No account
// kept out" takes them all off. In every language, Chromium and WebKit,
// wide and narrow.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
const words = {
en: { item: "Keep accounts out", label: "Accounts this key keeps out", none: "No account kept out", one: "Not relay/spare@example.com", two: "2 accounts kept out", title: /Every account but: relay\/me@example\.com, relay\/spare@example\.com/ },
zh: { item: "排除账号", label: "这个密钥排除的账号", none: "不排除账号", one: "排除 relay/spare@example.com", two: "排除 2 个账号", title: /除这些账号外都可用:/ },
"zh-TW": { item: "排除帳號", label: "這個金鑰排除的帳號", none: "不排除帳號", one: "排除 relay/spare@example.com", two: "排除 2 個帳號", title: /除這些帳號外都可用:/ },
ja: { item: "アカウントを除外", label: "このキーが除外するアカウント", none: "除外なし", one: "relay/spare@example.com を除外", two: "2 件のアカウントを除外", title: /これら以外のすべてのアカウント:/ },
de: { item: "Konten ausschließen", label: "Konten, die dieser Schlüssel ausschließt", none: "Kein Konto ausgeschlossen", one: "Ohne relay/spare@example.com", two: "2 Konten ausgeschlossen", title: /Alle Konten außer:/ },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 440]) {
for (const [lang, w] of Object.entries(words)) {
test(`${engine} ${width} ${lang}: a gateway key keeps out the accounts picked, and uses every other`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { accounts: ["relay/me@example.com"] } } }));
await page.goto("http://magpie.test/?view=gateway");
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);
const badge = (id) => row(id).getByRole("button", { name: w.label, exact: true });
const sent = () => events.filter((e) => e.action === "accounts-key").map((e) => e.body);
const until = async (fn) => {
for (let i = 0; i < 150 && !fn(); i++) await new Promise((r) => setTimeout(r, 20));
};
const view = page.locator("#view-gateway");
const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)];
const at = await scrolled();
// a key that keeps none out has no badge; the row's menu picks
await page.mouse.move(0, 0);
assert.equal(await row("work").locator(".key-out").count(), 0);
await row("work").hover();
await row("work").locator(".gw-key-more").click();
await page.locator(".row-menu").getByRole("menuitem", { name: w.item, exact: true }).click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal(await page.locator("select").count(), 0, "no native select");
assert.equal((await menu.locator(".pm-head").textContent()).trim(), w.label);
assert.deepEqual((await menu.locator(".pm-item.on").allTextContents()).map((s) => s.trim()), [w.none]);
const box = await menu.boundingBox();
assert(box.x >= 0 && box.x + box.width <= width + 1, "the menu inside the window");
await menu.locator(".pm-item", { hasText: "spare@example.com" }).click();
assert.equal(sent().length, 0, "a pick was sent before the menu closed");
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await until(() => sent().length);
assert.deepEqual(sent(), [{ key: "work", accounts: ["relay/!spare@example.com"] }]);
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="work"] .key-out'));
assert.equal((await badge("work").textContent()).trim(), w.one);
// kept out is not held to: the models badge still says every model
assert.equal(await row("work").locator(".key-models.set").count(), 0, "keeping one out held the key's models");
// the badge opens the same menu, the one kept out ticked; a second
events.length = 0;
await badge("work").click();
await menu.waitFor();
assert.equal(await menu.locator(".pm-item.on").count(), 1);
await menu.locator(".pm-item", { hasText: "me@example.com" }).first().click();
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await until(() => sent().length);
assert.deepEqual(sent(), [{ key: "work", accounts: ["relay/!me@example.com", "relay/!spare@example.com"] }]);
await page.waitForFunction((two) => document.querySelector('#gatewayKeys .acc[data-key="work"] .key-out')?.textContent.trim() === two, w.two);
assert.match(await badge("work").getAttribute("title"), w.title);
// a key held to an account and now keeping it out uses it no more
events.length = 0;
await row("server").hover();
await row("server").locator(".gw-key-more").click();
await page.locator(".row-menu").getByRole("menuitem", { name: w.item, exact: true }).click();
await menu.waitFor();
await menu.locator(".pm-item", { hasText: "me@example.com" }).first().click();
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await until(() => sent().length);
assert.deepEqual(sent(), [{ key: "server", accounts: ["relay/!me@example.com"] }]);
// "No account kept out" takes them all off
events.length = 0;
await badge("work").click();
await menu.waitFor();
await menu.locator(".pm-item", { hasText: w.none }).click();
await menu.waitFor({ state: "detached" });
await until(() => sent().length);
assert.deepEqual(sent(), [{ key: "work", accounts: [] }]);
await page.waitForFunction(() => !document.querySelector('#gatewayKeys .acc[data-key="work"] .key-out'));
assert.deepEqual(await scrolled(), at, "a click moved the page");
assert(!(await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth)), "the page scrolls sideways");
const lefts = await page.locator("#gatewayKeys .key-out").evaluateAll((els) => els.map((e) => getComputedStyle(e).borderLeftStyle));
assert(lefts.every((s) => s === "none"), "a coloured left border");
assert.deepEqual(errors, []);
});
}
}
}