provider, gateway, gui: an account whose sign-in its vendor revoked or refused reads as signed out and is passed over, not asked on every request (#1793 ysicing, echo_ts on Discord)

What changed, one fix for the class:

- ChatGPT and the other built-in subscriptions (#1793): ChatGPT answered
  401 token_revoked on every request, request after request (~18 rows in
  the reporter's log), because a refused sign-in was just "other" and
  rested a while, then asked again. Now a 401 whose words say the sign-in
  is gone (provider.SignInRevoked: token_revoked, token_invalidated,
  invalid_grant, refresh_token_reused/invalidated/expired; never
  token_expired, a 403, a 5xx or a network error) marks the account for
  the credential it was sent with (a 12-byte hash of the header, never the
  credential), in logins.json as Refused "revoked:<mark>" plus Lapsed.
  A saved ChatGPT account is refreshed first, as Codex does on a 401; a
  refresh that goes through marks nothing. The routing loop fails it as
  failAuth (next member at once, no rest); forwardOnce answers its later
  requests with magpie's own 401 without asking the vendor; compaction
  on a magpie account (compactOn) picks a marked one last. Signed in anew
  (upsertLogin with another credential, addSideLogin), refreshed, or a
  request served, the mark is gone. Claude, Copilot and plugins keep
  their own marks; a key's provider answering the same words rests as
  before.
- Copilot (echo_ts): a built-in Copilot account whose GitHub token GitHub
  refused (401/403 on the token exchange, the CLI stand-in or the usage
  read) is marked lapsed on its own account (copilot_lapsed.go), unless a
  working CLI stand-in serves; cleared when a token is served or it signs
  in again. 5xx and network errors never mark it.
- GUI: such an account's row says Sign-in required with Sign in again
  (Copilot's on its GHE.com host) and Remove, the reason on its allowance
  line in the user's language (zh, zh-TW, ja, de added); the card says
  Signed out once every account in use is.
- docs/subsystems: providers-accounts "A revoked sign-in", gateway-routing.

What was run (sandbox HOME, caches pinned, worktree only):
- go test -race on the new tests: provider TestSignInRevokedWords,
  TestRevokedSideLoginMarkedTillSignedInAgain, TestRevokedCodexRefreshedFirst,
  TestRevokedSignInLeavesOthersMarks, TestUpsertLoginKeepsRevokedMarkForTheSameSignIn,
  TestCopilot* (7); gateway TestRevokedSignInPassedOverTillSignedInAgain
  (fake ChatGPT backend, zstd, real routing: turn 1 asks acct-1 then
  acct-2, turns 2-4 and after a restart acct-2 only with no rests, after a
  new auth.json acct-1 again and the mark gone),
  TestRevokedSignInNotCompactedOnAgain, TestRevokedWordsFromAKeyRestAsBefore.
- Broken by hand, each turned a test red: the forwardOnce short-circuit,
  the failureOf clause, noteSignIn in codexUpstreamOn, compactOn's skip,
  ServedSignIn, its in-memory delete, the 401-only check, refresh-first,
  upsertLogin's keep and its sameAuth, sideLogins' Lapsed and
  addSideLogin's clear; and the six Copilot breaks. GUI: the signedOut
  and quotaError lines each turn revoked-signin-account red.
- GUI (Chromium and WebKit, 420 and 1100, en/zh/zh-TW/ja/de):
  revoked-signin-account (new), copilot-signed-out-account (new), and the
  account-*, claude-*, codex-*, plugin-*, quota-*, signin-*, routing-*,
  usage-accounts* suites: 1605 pass, 7 fail. Six are WebKit
  routing-group-fold/routing-sessions/routing-steady cases that fail the
  same on a clean 9964535ad run alone (#1672, #1612, #1307, #1804); one,
  signin-proxy Chromium de 380, timed out under load (load ~60-75) and
  passed 2 of 2 after, filed as #1814.
- gofmt; go vet darwin, linux (nogui) and windows; linux and windows
  builds. go test ./...: every package ok but gateway, where
  TestOTelFastRequestTranscriptDiscovery and
  TestOTelWaterfallIncludesUnbilledFallback failed under load (#1794);
  both pass alone, -count=3.

Not verified: no real revoked ChatGPT or Copilot account was tried; the
words come from the reporter's screenshot and OpenAI's documented codes.
Codex's own relayed sign-in (not one of magpie's accounts) isn't marked:
Codex refreshes and signs itself in. The short-circuit in
codexUpstreamOn (compaction on a marked account, reached only when every
account is marked) has no test of its own; plugins are left to their
plugin.
This commit is contained in:
yetone
2026-10-12 22:16:17 +08:00
parent d7a1fcd41a
commit 86b2f4d053
21 changed files with 1605 additions and 11 deletions
+1
View File
@@ -61,6 +61,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again.
- Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
- A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before.
- A sub2api key out of its own limit answers 429 `api key 7天限额已用完` (or `日限额`, `5小时限额`) as `rate_limit_exceeded`. It is out of quota (`plannedWords`), not rate limited: it rests till the window it filled renews when its windows as last read say so, else `quotaRest`, and its windows are read again (`staleKeyAllowance`). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (`renewed`, told through `provider.OnRenewed`), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (`restingOf`, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 `No available accounts`, or a later version's 429 `All available accounts are currently rate-limited`) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows.
- A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|<unix>`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx.
- A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669) is out of quota in either language (`resetsWhen`), and rests until that time (`resetsWritten`, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or more than `longestWritten` (7 days) off isn't read. One that points to the account's other models (`otherModels`: "切换其他模型", "switch to the other models") rests that model alone (`restID`). On the rate-limit branch, a reset time the refusal names (`resetsAt`, or `resetsHeader` as `keepRetry` noted it) is believed up to `longestQuota`, as out of quota believes it, and the Routing page says it rests until then (`resets`); a `Retry-After` or a rate-limit reset header is still held to `longestWait` (an hour) (`rateRest`). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (`TestPluginWrittenResetRests`). A JSON error body that escapes what isn't ASCII as `\uXXXX` (Python's json.dumps does by default) has its strings decoded before any word list (`creditWords`, `rateWords`, `plannedWords`, `usedUpWords`, `resetsWhen`, …) is matched (`wordsOf`), so an escaped 余额不足 or 用量 reads as an unescaped one does.
+1
View File
@@ -28,6 +28,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
| Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back into `~/.codex/auth.json` for Codex CLI. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) |
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:<mark>"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, or served a request (`ServedSignIn`), it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) |
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go) |
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`), or with the sign-in's while one asks it. | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) |
+19 -1
View File
@@ -538,8 +538,15 @@ func compactOn(r *http.Request, model string) *provider.Provider {
return nil
}
others := p.AlsoOn()
// one whose sign-in its vendor revoked is the last asked (#1793)
revoked := func(o provider.Provider) bool { return provider.SignInMarked(o.Account) }
for i, o := range others {
if !resting(candidate{p: o, model: model, rest: o.ID}) {
if !resting(candidate{p: o, model: model, rest: o.ID}) && !revoked(o) {
return &others[i]
}
}
for i, o := range others {
if !revoked(o) {
return &others[i]
}
}
@@ -721,6 +728,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
end(502, msg, 0, 0)
return
}
// a sign-in its vendor revoked isn't sent again (#1793)
if why, ok := provider.RevokedSignIn(on.Account, req); ok {
writeError(w, provider.Responses, 401, why)
end(401, why, 0, 0)
return
}
req.Header.Del("Accept")
for _, v := range accept {
req.Header.Add("Accept", v)
@@ -740,6 +753,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
end(502, msg, 0, 0)
return
}
if on != nil {
// one of magpie's accounts: a revoked sign-in shows on its
// row, to sign in again (#1793)
noteSignIn(ctx, on.Account, req, res)
}
if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests {
// the account is out of its allowance: one it lets spend its
// resets by itself, its week used up, spends one and is asked
+6
View File
@@ -3239,6 +3239,11 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
if err := p.Sign(ctx, req, to, body); err != nil {
return nil, err
}
// a sign-in its vendor revoked isn't sent again: the next member is
// asked, and the agent told to sign in again (#1793)
if why, ok := provider.RevokedSignIn(p.Account, req); ok {
return revokedReply(req, why), nil
}
if to == provider.Anthropic {
s.fitUserBetas(p, req.Header)
}
@@ -3267,6 +3272,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
}
// what a Codex account's reply says it has used, for its cap (#1295)
heardCodexLimits(p, res)
noteSignIn(ctx, p.Account, req, res)
return res, nil
}
+4
View File
@@ -287,6 +287,10 @@ func failureOf(c candidate, status int, body []byte) string {
if status >= 400 && c.p.Account != nil && c.p.Account.Agent == "claude" && provider.ClaudeSignInRequired(string(body)) {
return failAuth
}
// a subscription's sign-in its vendor revoked (#1793): no wait mends it
if provider.RevokedAccount(c.p.Account) && provider.SignInRevoked(status, body) {
return failAuth
}
return failure(status, body)
}
+54
View File
@@ -0,0 +1,54 @@
package gateway
// A subscription account whose sign-in its vendor revoked (#1793, ysicing:
// a ChatGPT account answering 401 token_revoked, asked again on every
// request). provider/signin_revoked.go keeps which credentials are
// revoked; here the gateway tells it what the vendor said, and answers for
// a revoked one without sending it, so the routing loop passes over it
// (failureOf: failAuth) and asks the next member.
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"strconv"
"github.com/yetone/magpie/internal/provider"
)
// revokedReply is the 401 a request signed with a revoked credential is
// answered with, in the words ChatGPT used, without asking the vendor.
func revokedReply(req *http.Request, why string) *http.Response {
b, _ := json.Marshal(map[string]any{"error": map[string]any{
"message": why, "type": "authentication_error", "code": "token_revoked",
}})
h := http.Header{}
h.Set("Content-Type", "application/json")
h.Set("Content-Length", strconv.Itoa(len(b)))
return &http.Response{
Status: "401 Unauthorized", StatusCode: http.StatusUnauthorized,
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1,
Header: h, Body: io.NopCloser(bytes.NewReader(b)), ContentLength: int64(len(b)), Request: req,
}
}
// noteSignIn tells provider what the vendor said of the sign-in req went
// with: a 401 that says it is revoked marks it, a request served clears a
// mark the account had. The body read is put back for the caller.
func noteSignIn(ctx context.Context, a *provider.Account, req *http.Request, res *http.Response) {
if a == nil || res == nil {
return
}
switch {
case res.StatusCode >= 200 && res.StatusCode < 300:
provider.ServedSignIn(a)
case res.StatusCode == http.StatusUnauthorized && res.Body != nil:
b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
res.Body = readCloser{io.MultiReader(bytes.NewReader(b), res.Body), res.Body}
if err == nil && provider.SignInRevoked(res.StatusCode, b) {
provider.NoteRevokedSignIn(ctx, a, req)
}
}
}
+233
View File
@@ -0,0 +1,233 @@
package gateway
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/klauspost/compress/zstd"
"github.com/yetone/magpie/internal/provider"
)
// revokedUpstream stands in for the ChatGPT backend with the sign-in of
// the access token revoked revoked, as ChatGPT answers one (#1793); tried
// is the accounts asked a turn, and with reset starts the list again.
func revokedUpstream(t *testing.T, revoked string) (tried func(reset bool) []string) {
t.Helper()
var mu sync.Mutex
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
if r.Header.Get("Content-Encoding") == "zstd" {
d, _ := zstd.NewReader(nil)
b, _ = d.DecodeAll(b, nil)
d.Close()
}
var q struct {
Input any `json:"input"`
}
json.Unmarshal(b, &q)
gone := r.Header.Get("Authorization") == "Bearer "+revoked
// a sign-in's warm-up ("hi", codex_warmup.go) isn't a turn
if q.Input != "hi" {
mu.Lock()
asked = append(asked, r.Header.Get("chatgpt-account-id"))
mu.Unlock()
}
if gone {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, `{"error":{"message":"Encountered invalidated oauth token for user, failing request","code":"token_revoked"},"status":401}`)
return
}
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","delta":"pong"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
return func(reset bool) []string {
mu.Lock()
defer mu.Unlock()
out := slices.Clone(asked)
if reset {
asked = nil
}
return out
}
}
// codexAccessToken is the access token in the test's Codex sign-in.
func codexAccessToken(t *testing.T) string {
t.Helper()
var a struct {
Tokens struct {
AccessToken string `json:"access_token"`
} `json:"tokens"`
}
b, err := os.ReadFile(filepath.Join(os.Getenv("HOME"), ".codex", "auth.json"))
if err != nil || json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" {
t.Fatalf("no Codex sign-in: %v %s", err, b)
}
return a.Tokens.AccessToken
}
func codexLapsed(t *testing.T, user string) string {
t.Helper()
for _, l := range provider.Logins("codex") {
if l.User == user {
return l.Lapsed
}
}
t.Fatalf("no codex account %s in %+v", user, provider.Logins("codex"))
return ""
}
// A ChatGPT account whose sign-in OpenAI revoked (#1793, ysicing: 401
// token_revoked, asked again on every request) is passed over for the next
// account at once, without a rest, and isn't asked again while it has that
// sign-in: its row says to sign in again. Signed in anew, it is asked, and
// served, the mark is gone.
func TestRevokedSignInPassedOverTillSignedInAgain(t *testing.T) {
codexSignedIn(t, "spare@example.com")
tried := revokedUpstream(t, codexAccessToken(t))
turn := func(name, input string, want string) {
t.Helper()
tried(true)
s := New()
rec := codexPostTo(s, `{"model":"gpt-5.5","stream":true,"input":"`+input+`"}`)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
t.Fatalf("%s: status %d: %s", name, rec.Code, rec.Body.String())
}
if got := strings.Join(tried(false), ","); got != want {
t.Fatalf("%s: asked %s, not %s: %+v", name, got, want, lastRoute(s).Tries)
}
// passed over for its sign-in, not resting: a rest would end, and
// the account be asked again (the screenshot's rows of 401s)
restingUntil.Lock()
rests := len(restingUntil.m)
restingUntil.Unlock()
if rests != 0 {
t.Fatalf("%s: the revoked account rests, to be asked again after", name)
}
}
turn("first turn", "ping", "acct-1,acct-2")
if got := codexLapsed(t, "me@example.com"); !strings.Contains(got, "sign in again") {
t.Fatalf("the revoked account isn't said signed out: %q", got)
}
for _, in := range []string{"ping", "another", "a third"} {
turn("turn "+in, in, "acct-2")
}
// kept across a restart: read from logins.json again
provider.ForgetAccounts()
turn("after a restart", "ping", "acct-2")
if got := codexLapsed(t, "me@example.com"); got == "" {
t.Fatal("the mark is gone after a restart")
}
// Codex signed in again: a new token, asked and served
claims, _ := json.Marshal(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "who": "acct-1", "n": 2})
auth := map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": "h." + base64.RawURLEncoding.EncodeToString(mustJSON(map[string]any{"email": "me@example.com"})) + ".s",
"access_token": "h." + base64.RawURLEncoding.EncodeToString(claims) + ".s",
"refresh_token": "r-acct-1b", "account_id": "acct-1"}}
if err := os.WriteFile(filepath.Join(os.Getenv("HOME"), ".codex", "auth.json"), mustJSON(auth), 0o600); err != nil {
t.Fatal(err)
}
provider.ForgetAccounts()
turn("signed in again", "a new conversation", "acct-1")
if got := codexLapsed(t, "me@example.com"); got != "" {
t.Fatalf("still said signed out after serving: %q", got)
}
}
// The words of a revoked sign-in from a key's provider (no account to sign
// in again) are failed as before, not passed over as an account's.
func TestRevokedWordsFromAKeyRestAsBefore(t *testing.T) {
fresh(t)
gone := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, `{"error":{"message":"invalidated oauth token","code":"token_revoked"}}`)
})
serveOn(t, "a", "ka", []string{"m"}, gone)
serveOn(t, "b", "kb", []string{"m"}, &keyed{})
if err := provider.SaveGroup(provider.Group{Name: "Two", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
if code, body := postAs(t, s, "", `{"model":"group/two","messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "from kb") {
t.Fatalf("%d %s", code, body)
}
if r := lastRoute(s); len(r.Tries) != 2 || r.Tries[0].Fail == failAuth || r.Tries[0].Rest == nil {
t.Fatalf("not rested as before: %+v", r.Tries)
}
}
// Compaction goes to an account of magpie's alone, with the one Codex is
// signed in to paused (#263): one whose sign-in OpenAI revoked (#1793) is
// marked by its 401 there too, and the next compaction goes to another,
// not to it again.
func TestRevokedSignInNotCompactedOnAgain(t *testing.T) {
codexSignedIn(t, "spare@example.com", "third@example.com")
var mu sync.Mutex
var tried []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
tried = append(tried, r.Header.Get("chatgpt-account-id"))
mu.Unlock()
if r.Header.Get("chatgpt-account-id") == "acct-2" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, `{"error":{"message":"Encountered invalidated oauth token for user, failing request","code":"token_revoked"},"status":401}`)
return
}
io.WriteString(w, `{"output":[{"type":"compaction","encrypted_content":"gAAAAAx"}]}`)
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
if err := provider.SetLoginOn("codex", "me@example.com", false); err != nil {
t.Fatal(err)
}
compact := func() (int, string) {
t.Helper()
mu.Lock()
tried = nil
mu.Unlock()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses/compact", strings.NewReader(`{"model":"gpt-5.5","input":[{"type":"message","role":"user","content":"ping"}]}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
New().Handler().ServeHTTP(rec, req)
mu.Lock()
defer mu.Unlock()
return rec.Code, strings.Join(tried, ",")
}
if code, asked := compact(); code != 401 || asked != "acct-2" {
t.Fatalf("first: %d, asked %s", code, asked)
}
if got := codexLapsed(t, "spare@example.com"); !strings.Contains(got, "sign in again") {
t.Fatalf("not said signed out: %q", got)
}
for range 2 {
if code, asked := compact(); code != 200 || asked != "acct-3" {
t.Fatalf("after: %d, asked %s", code, asked)
}
}
}
+16 -2
View File
@@ -12129,7 +12129,15 @@ function renderAccounts(a, p) {
// a restart): marked lapsed, or its allowance read saying so. Whatever
// else it is (in use, the agent's own), it keeps a way to sign in again
// and its Remove, and the reason never stands in their place.
const signedOut = (l) => !!sub?.plugin && !unusable(l) && (!!l.lapsed || SIGN_IN_GONE.test(quota?.[l.user]?.error || ""));
// A built-in Copilot account whose GitHub token GitHub refused (echo_ts
// on Discord: a revoked token) is the same, marked lapsed by magpie, and
// signed in again in place. So is any other built-in account whose
// sign-in its vendor revoked (#1793: ChatGPT's 401 token_revoked) or
// refused to refresh: the gateway passes over it till then.
const signedOut = (l) => !unusable(l) && (sub?.plugin ? !!l.lapsed || SIGN_IN_GONE.test(quota?.[l.user]?.error || "") : (a.agent === "copilot" && !!l.lapsed) || SIGN_IN_GONE.test(l.lapsed || ""));
// a Copilot account on an enterprise's GHE.com is named login@host, and
// signs in again there
const againSite = (l) => !sub?.plugin && a.agent === "copilot" && String(l.user).includes("@") ? String(l.user).split("@").pop() : undefined;
const several = ls.filter((l) => !unusable(l) && ((l.active && !l.paused) || l.on)).length > 1;
// kept signed in to one of the user's choosing (#524), the first is the
// first in use in the order, which Make first sets without a sign-in
@@ -12203,7 +12211,7 @@ function renderAccounts(a, p) {
row.classList.add("signed-out");
row.append(el("span", "using", t("Sign-in required")));
const again = el("button", "text", t("Sign in again"));
again.onclick = () => startSignIn(a.agent, false, undefined, { user: l.user });
again.onclick = () => startSignIn(a.agent, false, againSite(l), { user: l.user });
const forget = el("button", "text quiet", t("Remove"));
forget.title = l.own ? forgetOwnTitle(a) : t("magpie forgets this account's sign-in; the account itself is untouched");
forget.onclick = () => accountAction("login/forget", { agent: a.agent, user: l.user }, t("{user} removed", { user: l.user }));
@@ -12514,6 +12522,12 @@ const SIGN_IN_GONE = /sign-in has (expired|lapsed)|sign in again/i;
function quotaError(err) {
if (/sign-in has expired/.test(err)) return t("Signed out — add this account again to use it");
// a Copilot account GitHub refused the token of (copilot_lapsed.go), as
// its row says it, in English or already in the user's language
const copilotLapsed = "GitHub refused this Copilot sign-in; sign in again";
if (err === copilotLapsed || err === t(copilotLapsed)) return t(copilotLapsed);
// an account whose sign-in its vendor revoked (signin_revoked.go, #1793)
if (/'s sign-in was revoked; sign in again$/.test(err)) return t("The vendor revoked this sign-in; sign in again");
if (/no longer supported for Gemini Code Assist for individuals/.test(err)) return t("Google no longer serves personal accounts to Gemini CLI — hover for more");
if (/magpie accounts project/.test(err)) return t("Needs a Google Cloud project — hover for how");
if (/^Antigravity (hasn't set|won't serve)/.test(err)) return t("Antigravity hasn't set this account up — hover for why");
+8
View File
@@ -1763,6 +1763,8 @@ const I18N = {
"Sign-in ran out": "登录已失效",
"Sign in again": "重新登录",
"Sign-in required": "需要重新登录",
"GitHub refused this Copilot sign-in; sign in again": "GitHub 拒绝了这个 Copilot 登录,请重新登录",
"The vendor revoked this sign-in; sign in again": "服务商已撤销这个登录,请重新登录",
"sign-in required": "需要重新登录",
"Sign in again to use this account": "重新登录后才能使用此账号",
"Claude Code is no longer signed in; sign in again in magpie": "Claude Code 已退出登录,请在 magpie 中重新登录",
@@ -6141,6 +6143,8 @@ const I18N = {
"Sign-in ran out": "登入已失效",
"Sign in again": "重新登入",
"Sign-in required": "需要重新登入",
"GitHub refused this Copilot sign-in; sign in again": "GitHub 拒絕了這個 Copilot 登入,請重新登入",
"The vendor revoked this sign-in; sign in again": "服務商已撤銷這個登入,請重新登入",
"sign-in required": "需要重新登入",
"Sign in again to use this account": "重新登入後才能使用此帳號",
"Claude Code is no longer signed in; sign in again in magpie": "Claude Code 已退出登入,請在 magpie 中重新登入",
@@ -10495,6 +10499,8 @@ const I18N = {
"Sign-in ran out": "サインインの期限切れ",
"Sign in again": "再度サインイン",
"Sign-in required": "サインインが必要です",
"GitHub refused this Copilot sign-in; sign in again": "GitHub がこの Copilot のサインインを拒否しました。再度サインインしてください",
"The vendor revoked this sign-in; sign in again": "ベンダーがこのサインインを取り消しました。再度サインインしてください",
"sign-in required": "サインインが必要です",
"Sign in again to use this account": "このアカウントを使うには再度サインインしてください",
"Claude Code is no longer signed in; sign in again in magpie": "Claude Code はサインインしていません。magpie で再度サインインしてください",
@@ -14868,6 +14874,8 @@ const I18N = {
"Sign-in ran out": "Anmeldung abgelaufen",
"Sign in again": "Erneut anmelden",
"Sign-in required": "Anmeldung erforderlich",
"GitHub refused this Copilot sign-in; sign in again": "GitHub hat diese Copilot-Anmeldung abgelehnt; bitte erneut anmelden",
"The vendor revoked this sign-in; sign in again": "Der Anbieter hat diese Anmeldung widerrufen; bitte erneut anmelden",
"sign-in required": "Anmeldung erforderlich",
"Sign in again to use this account": "Melden Sie sich erneut an, um dieses Konto zu verwenden",
"Claude Code is no longer signed in; sign in again in magpie": "Claude Code ist nicht mehr angemeldet; melden Sie sich in magpie erneut an",
@@ -0,0 +1,143 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A built-in Copilot account whose GitHub token GitHub refused (echo_ts on
// Discord: a revoked token, every request "Copilot is signed out …; sign in
// to Copilot again", the account to be removed and added anew) reads as
// signed out on its own row — "Sign-in required", the reason on its
// allowance line in the user's language — with Sign in again, which runs
// Copilot's own sign-in for that account (on its enterprise's host for a
// GHE.com one), and Remove. The card's pill says Signed out once every
// account in use is. A Copilot account GitHub still takes has neither.
// Chromium and WebKit, 420 and 1100 wide, in every language.
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 LAPSE = "GitHub refused this Copilot sign-in; sign in again";
const copilot = (logins) => ({
id: "copilot", name: "GitHub Copilot", icon: "githubcopilot", chat: "https://api.githubcopilot.com", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-4.1", name: "GPT-4.1", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: {},
account: { agent: "copilot", agentName: "Copilot", agentIcon: "githubcopilot", builtin: true, user: logins[0].user, plan: "Pro", logins },
});
function serve(lang, logins, posts) {
const providers = () => ({ providers: [copilot(logins)], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [], onPlugins: [] });
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers());
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/login/usage") return json({});
if (route.request().method() === "POST") {
const body = route.request().postDataJSON();
posts.push({ path: url.pathname, body });
if (url.pathname === "/api/signin") return json({ id: "s1", agent: "copilot", state: "waiting", url: "https://github.test/login/device", code: "ABCD-1234" });
return json(providers());
}
if (url.pathname.startsWith("/api/signin/")) return json({ id: "s1", agent: "copilot", state: "waiting", url: "https://github.test/login/device", code: "ABCD-1234" });
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: "" }); }
};
}
const W = {
en: { required: "Sign-in required", again: "Sign in again", remove: "Remove", out: "Signed out", reason: LAPSE },
zh: { required: "需要重新登录", again: "重新登录", remove: "移除", out: "已退出登录", reason: "GitHub 拒绝了这个 Copilot 登录,请重新登录" },
"zh-TW": { required: "需要重新登入", again: "重新登入", remove: "移除", out: "已退出登入", reason: "GitHub 拒絕了這個 Copilot 登入,請重新登入" },
ja: { required: "サインインが必要です", again: "再度サインイン", remove: "削除", out: "サインアウトしました", reason: "GitHub がこの Copilot のサインインを拒否しました。再度サインインしてください" },
de: { required: "Anmeldung erforderlich", again: "Erneut anmelden", remove: "Entfernen", out: "Abgemeldet", reason: "GitHub hat diese Copilot-Anmeldung abgelehnt; bitte erneut anmelden" },
};
const cases = [
{ name: "the only account, on github.com (the report)", user: "octocat", logins: [{ user: "octocat", plan: "Pro", active: true, on: true, lapsed: LAPSE }], body: { agent: "copilot", user: "octocat" }, pill: true },
{ name: "one of two, on an enterprise's GHE.com", user: "octo@acme.ghe.com", logins: [{ user: "hubot", plan: "Pro", active: true, on: true }, { user: "octo@acme.ghe.com", plan: "Business", on: true, lapsed: LAPSE }], body: { agent: "copilot", site: "acme.ghe.com", user: "octo@acme.ghe.com" }, pill: false },
{ name: "the editors' own", user: "octocat", logins: [{ user: "octocat", plan: "Pro", active: true, on: true, own: true, lapsed: LAPSE }], body: { agent: "copilot", user: "octocat" }, pill: true },
];
const overlap = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a Copilot account GitHub refused reads as signed out and signs in again", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(W)) {
const w = W[lang];
for (const width of [420, 1100]) {
const open = async (logins, posts) => {
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, logins, posts));
await page.goto("http://magpie.test/?view=providers");
const card = page.locator(".row.provider", { hasText: "GitHub Copilot" });
await card.waitFor();
return { page, errors, card };
};
for (const c of cases) {
await t.test(`${lang} ${width}: ${c.name}`, async () => {
const posts = [];
const { page, errors, card } = await open(c.logins, posts);
const pill = await card.locator(".key").innerText();
if (c.pill) assert.equal(pill, w.out, "every account in use refused: the card says signed out");
else assert.notEqual(pill, w.out, "another account still in use: the card isn't signed out");
await card.click();
const row = page.locator(".accts .acc", { hasText: c.user }).filter({ has: page.locator(".using", { hasText: w.required }) });
await row.waitFor();
const again = row.getByRole("button", { name: w.again, exact: true });
const rm = row.getByRole("button", { name: w.remove, exact: true });
assert.equal(await again.count(), 1, "Sign in again is on the row");
assert.equal(await rm.count(), 1, "Remove is on the row");
// the reason, in the user's language, below the controls
const aq = row.locator(".aq .aq-none");
await aq.waitFor();
assert.equal(await aq.innerText(), w.reason);
const box = await row.boundingBox(), line = await aq.boundingBox();
for (const b of [again, rm]) {
await b.scrollIntoViewIfNeeded();
assert.ok(await b.isVisible());
const r = await b.boundingBox();
assert.ok(!overlap(r, line), `${await b.innerText()} is under the reason`);
assert.ok(r.x >= box.x - 1 && r.x + r.width <= box.x + box.width + 1, `${await b.innerText()} runs out of the row`);
}
const docW = await page.evaluate(() => document.documentElement.scrollWidth);
assert.ok(docW <= width, `the page scrolls sideways (${docW} > ${width})`);
if (process.env.ARTIFACT_DIR) await row.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `copilot-signed-out-${engine}-${lang}-${width}-${c.user.replace(/[@.]/g, "_")}${c.logins[0].own ? "-own" : ""}.png`) });
// Sign in again is Copilot's own sign-in of this account, on its host
const y = await page.evaluate(() => document.scrollingElement.scrollTop);
await again.click();
for (let i = 0; i < 50 && !posts.some((p) => p.path === "/api/signin"); i++) await page.waitForTimeout(50);
assert.deepEqual(posts.filter((p) => p.path === "/api/signin").map((p) => { const { proxy, ...b } = p.body; return b; }), [c.body]);
await page.locator(".signing").first().waitFor();
assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), y, "the click scrolled the page");
assert.deepEqual(errors, []);
await page.context().close();
});
}
await t.test(`${lang} ${width}: an account GitHub takes has no Sign in again`, async () => {
const posts = [];
const { page, errors, card } = await open([{ user: "octocat", plan: "Pro", active: true, on: true }], posts);
assert.notEqual(await card.locator(".key").innerText(), w.out);
await card.click();
const row = page.locator(".accts .acc", { hasText: "octocat" });
await row.waitFor();
assert.equal(await row.getByRole("button", { name: w.again, exact: true }).count(), 0);
assert.equal(await row.locator(".using", { hasText: w.required }).count(), 0);
assert.deepEqual(errors, []);
await page.context().close();
});
}
}
});
}
@@ -0,0 +1,139 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A ChatGPT account whose sign-in OpenAI revoked (#1793, ysicing: 401
// token_revoked on every request, the account asked again each time) reads
// as signed out on its own row once magpie marks it (signin_revoked.go):
// "Sign-in required", the reason on its allowance line in the user's
// language, with Sign in again, which runs Codex's sign-in for that
// account, and Remove. The card's pill says Signed out once every account
// in use is. An account its vendor still serves has neither.
// Chromium and WebKit, 420 and 1100 wide, in every language.
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 lapse = (user) => `${user}'s sign-in was revoked; sign in again`;
const codex = (logins) => ({
id: "codex", name: "Codex", icon: "openai", chat: "", responses: "https://chatgpt.com/backend-api/codex", anthropic: "", catalog: "",
models: [{ id: "gpt-5.5", name: "GPT-5.5", on: true }], agents: [], fallback: [], headers: {}, keyList: [], key: {},
account: { agent: "codex", agentName: "Codex", agentIcon: "openai", builtin: true, user: logins[0].user, plan: "Plus", logins },
});
function serve(lang, logins, posts) {
const providers = () => ({ providers: [codex(logins)], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [], onPlugins: [] });
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
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:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers());
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
if (url.pathname === "/api/login/usage") return json({});
if (route.request().method() === "POST") {
const body = route.request().postDataJSON();
posts.push({ path: url.pathname, body });
if (url.pathname === "/api/signin") return json({ id: "s1", agent: "codex", state: "waiting", url: "https://auth.openai.test/authorize" });
return json(providers());
}
if (url.pathname.startsWith("/api/signin/")) return json({ id: "s1", agent: "codex", state: "waiting", url: "https://auth.openai.test/authorize" });
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: "" }); }
};
}
const W = {
en: { required: "Sign-in required", again: "Sign in again", remove: "Remove", out: "Signed out", reason: "The vendor revoked this sign-in; sign in again" },
zh: { required: "需要重新登录", again: "重新登录", remove: "移除", out: "已退出登录", reason: "服务商已撤销这个登录,请重新登录" },
"zh-TW": { required: "需要重新登入", again: "重新登入", remove: "移除", out: "已退出登入", reason: "服務商已撤銷這個登入,請重新登入" },
ja: { required: "サインインが必要です", again: "再度サインイン", remove: "削除", out: "サインアウトしました", reason: "ベンダーがこのサインインを取り消しました。再度サインインしてください" },
de: { required: "Anmeldung erforderlich", again: "Erneut anmelden", remove: "Entfernen", out: "Abgemeldet", reason: "Der Anbieter hat diese Anmeldung widerrufen; bitte erneut anmelden" },
};
const cases = [
{ name: "the only account (the report)", user: "me@example.com", logins: [{ user: "me@example.com", plan: "Plus", active: true, on: true, lapsed: lapse("me@example.com") }], pill: true },
{ name: "one of two in use", user: "spare@example.com", logins: [{ user: "me@example.com", plan: "Plus", active: true, on: true }, { user: "spare@example.com", plan: "Pro", on: true, lapsed: lapse("spare@example.com") }], pill: false },
];
const overlap = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": an account whose sign-in its vendor revoked reads as signed out and signs in again", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of Object.keys(W)) {
const w = W[lang];
for (const width of [420, 1100]) {
const open = async (logins, posts) => {
const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, logins, posts));
await page.goto("http://magpie.test/?view=providers");
const card = page.locator(".row.provider", { hasText: "Codex" });
await card.waitFor();
return { page, errors, card };
};
for (const c of cases) {
await t.test(`${lang} ${width}: ${c.name}`, async () => {
const posts = [];
const { page, errors, card } = await open(c.logins, posts);
const pill = await card.locator(".key").innerText();
if (c.pill) assert.equal(pill, w.out, "every account in use revoked: the card says signed out");
else assert.notEqual(pill, w.out, "another account still in use: the card isn't signed out");
await card.click();
const row = page.locator(".accts .acc", { hasText: c.user }).filter({ has: page.locator(".using", { hasText: w.required }) });
await row.waitFor();
const again = row.getByRole("button", { name: w.again, exact: true });
const rm = row.getByRole("button", { name: w.remove, exact: true });
assert.equal(await again.count(), 1, "Sign in again is on the row");
assert.equal(await rm.count(), 1, "Remove is on the row");
const aq = row.locator(".aq .aq-none");
await aq.waitFor();
assert.equal(await aq.innerText(), w.reason);
const box = await row.boundingBox(), line = await aq.boundingBox();
for (const b of [again, rm]) {
await b.scrollIntoViewIfNeeded();
assert.ok(await b.isVisible());
const r = await b.boundingBox();
assert.ok(!overlap(r, line), `${await b.innerText()} is under the reason`);
assert.ok(r.x >= box.x - 1 && r.x + r.width <= box.x + box.width + 1, `${await b.innerText()} runs out of the row`);
}
const docW = await page.evaluate(() => document.documentElement.scrollWidth);
assert.ok(docW <= width, `the page scrolls sideways (${docW} > ${width})`);
if (process.env.ARTIFACT_DIR) await row.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `revoked-signin-${engine}-${lang}-${width}-${c.user.replace(/[@.]/g, "_")}.png`) });
// Sign in again is Codex's sign-in of this account
const y = await page.evaluate(() => document.scrollingElement.scrollTop);
await again.click();
for (let i = 0; i < 50 && !posts.some((p) => p.path === "/api/signin"); i++) await page.waitForTimeout(50);
assert.deepEqual(posts.filter((p) => p.path === "/api/signin").map((p) => { const { proxy, ...b } = p.body; return b; }), [{ agent: "codex", user: c.user }]);
assert.equal(await page.evaluate(() => document.scrollingElement.scrollTop), y, "the click scrolled the page");
assert.deepEqual(errors, []);
await page.context().close();
});
}
await t.test(`${lang} ${width}: an account its vendor serves has no Sign in again`, async () => {
const posts = [];
const { page, errors, card } = await open([{ user: "me@example.com", plan: "Plus", active: true, on: true }], posts);
assert.notEqual(await card.locator(".key").innerText(), w.out);
await card.click();
const row = page.locator(".accts .acc", { hasText: "me@example.com" });
await row.waitFor();
assert.equal(await row.getByRole("button", { name: w.again, exact: true }).count(), 0);
assert.equal(await row.locator(".using", { hasText: w.required }).count(), 0);
assert.deepEqual(errors, []);
await page.context().close();
});
}
}
});
}
+13 -4
View File
@@ -1166,11 +1166,20 @@ func copilotStandIn(a copilotApp) (copilotApp, bool) {
return cli, ok && copilotSameAccount(cli, a)
}
// session is what this sign-in's requests carry. An editor's token GitHub
// refuses is replaced by the Copilot CLI's sign-in of the same account,
// sent as the CLI sends it; with none, the error names the file the
// refused token is in, since it is read before the CLI's (#1238).
// session is what this sign-in's requests carry, and what GitHub said of
// it is kept on its account: refused, it is signed out; served, it isn't
// (copilotSessionDone).
func (a copilotApp) session(ctx context.Context) (copilotSession, error) {
s, err := a.trade(ctx)
copilotSessionDone(a, err)
return s, err
}
// trade gets this sign-in's session. An editor's token GitHub refuses is
// replaced by the Copilot CLI's sign-in of the same account, sent as the
// CLI sends it; with none, the error names the file the refused token is
// in, since it is read before the CLI's (#1238).
func (a copilotApp) trade(ctx context.Context) (copilotSession, error) {
if a.cli {
return copilotDirect(ctx, a)
}
+14 -3
View File
@@ -223,6 +223,11 @@ func copilotLogins(cfg string) []copilotLoginApp {
app, _ = copilotSaved(l.saved)
}
app.User = l.User
// signed out by GitHub with the token it still has (copilot_lapsed.go)
if copilotLapsedOn(l.saved, app.Token) {
l.Login.Lapsed = l.saved.Lapsed
copilotLapsedNote(l.User, true)
}
out = append(out, copilotLoginApp{l.Login, app})
}
return out
@@ -281,15 +286,18 @@ func addCopilotLogin(user, plan, token, host string) error {
// copilotEditorRefused says GitHub refused the editors' sign-in of user on
// host: a stale token in apps.json, which a sign-in from magpie is not let
// go for (#1238).
// go for (#1238). The Copilot CLI's, when it is the account's own sign-in,
// is the same: a revoked one is signed in again in magpie (echo_ts).
func copilotEditorRefused(cfg, user, host string) bool {
who := copilotApp{User: user, Host: host}
gh, ghe := copilotEditorLogins(cfg)
for _, e := range []*copilotApp{gh, ghe} {
if e != nil && copilotSameAccount(*e, copilotApp{User: user, Host: host}) && copilotRefusedToken(e.Token) {
if e != nil && copilotSameAccount(*e, who) && copilotRefusedToken(e.Token) {
return true
}
}
return false
own, ok := copilotLogin(cfg)
return ok && own.cli && copilotSameAccount(own, who) && copilotRefusedToken(own.Token)
}
// copilotProbeEditor asks GitHub whether it still takes the editors' sign-in
@@ -302,6 +310,9 @@ func copilotProbeEditor(ctx context.Context, user, host string) {
_, _ = copilotToken(ctx, *e)
}
}
if own, ok := copilotLogin(copilotConfigDir()); ok && own.cli && copilotSameAccount(own, copilotApp{User: user, Host: host}) && !copilotRefusedToken(own.Token) {
_, _ = copilotDirect(ctx, own)
}
}
// copilotAccount is the Copilot account in use first.
+9
View File
@@ -236,8 +236,17 @@ func copilotDirect(ctx context.Context, app copilotApp) (copilotSession, error)
} `json:"endpoints"`
}
if res.StatusCode != 200 || json.Unmarshal(b, &u) != nil {
// 401 is GitHub refusing the token itself; a 403 here can be an
// account without Copilot, and a 5xx is GitHub's own trouble
if res.StatusCode == http.StatusUnauthorized {
copilotRefuse(github, res.StatusCode)
}
return copilotSession{}, errors.New("the Copilot CLI's sign-in was refused (" + APIError(b, res.Status) + "); run `copilot login` again")
}
copilotRefusals.Lock()
delete(copilotRefusals.at, github)
delete(copilotRefusals.status, github)
copilotRefusals.Unlock()
s := copilotSession{Token: github, ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), direct: true}
s.Endpoints.API = u.Endpoints.API
copilotSessions[github] = s
+143
View File
@@ -0,0 +1,143 @@
package provider
// A Copilot account whose GitHub token GitHub refuses is signed out: GitHub
// revokes a token (signed out on github.com, the OAuth app's access taken
// back, a token unused for a year), and every request then failed with
// "Copilot is signed out …; sign in to Copilot again" while the account
// still read as signed in, to be removed and added anew (echo_ts on
// Discord). Such an account is now marked lapsed on its own row, where it
// is signed in again in place, its settings kept.
//
// Only GitHub's refusal of the token marks it — 401 on the trade for a
// session token or on the CLI's /copilot_internal/user, 403 on the trade
// — never a 5xx or a network error; and an editor's token refused while
// the Copilot CLI's sign-in of the same account stands in for it is no
// lapse (#1238). The mark is kept with a digest of the token refused, so
// a new sign-in (magpie's, the editor's or the CLI's) is never called
// signed out for the old one, and a request served on the account clears it.
import (
"crypto/sha256"
"encoding/hex"
"errors"
"slices"
"strings"
"sync"
)
// copilotLapsedText is what a lapsed Copilot account's row says.
const copilotLapsedText = "GitHub refused this Copilot sign-in; sign in again"
// copilotTokenMark tells a GitHub token from another without keeping it.
func copilotTokenMark(token string) string {
sum := sha256.Sum256([]byte("copilot\x00" + token))
return hex.EncodeToString(sum[:12])
}
// copilotLapsedOn says a saved Copilot account is signed out with token:
// it was marked so while it had this very token.
func copilotLapsedOn(l savedLogin, token string) bool {
return l.Lapsed != "" && token != "" && slices.Contains(strings.Split(l.Refused, ","), copilotTokenMark(token))
}
// copilotLapsedSeen is the Copilot accounts known marked lapsed, by
// accountKey: a request served on one clears its mark without reading
// logins.json at every request.
var (
copilotLapsedMu sync.Mutex
copilotLapsedSeen = map[string]bool{}
)
func copilotLapsedNote(user string, lapsed bool) {
copilotLapsedMu.Lock()
defer copilotLapsedMu.Unlock()
if lapsed {
copilotLapsedSeen[accountKey(user)] = true
} else {
delete(copilotLapsedSeen, accountKey(user))
}
}
var errUnchanged = errors.New("unchanged")
// copilotLapsedBy says GitHub refused app's sign-in, with nothing standing
// in for it: its token refused, and an editor's token's stand-in, the
// Copilot CLI's sign-in of the same account, refused too or not there.
func copilotLapsedBy(app copilotApp) bool {
if !copilotRefusedToken(app.Token) {
return false
}
if app.cli || app.src == "" {
return true
}
if cli, ok := copilotStandIn(app); ok && !copilotRefusedToken(cli.Token) {
return false
}
return true
}
// copilotLapse marks the account of app signed out, with the token GitHub
// refused (and, for an editor's, its stand-in's too, which copilotLogins
// may list it with).
func copilotLapse(app copilotApp) {
if app.User == "" {
return
}
marks := []string{copilotTokenMark(app.Token)}
if app.src != "" && !app.cli {
if cli, ok := copilotStandIn(app); ok {
marks = append(marks, copilotTokenMark(cli.Token))
}
}
err := editSideLogin("copilot", app.User, func(ls []savedLogin, i int) ([]savedLogin, error) {
was := strings.Split(ls[i].Refused, ",")
if ls[i].Lapsed == copilotLapsedText && !slices.ContainsFunc(marks, func(m string) bool { return !slices.Contains(was, m) }) {
return nil, errUnchanged
}
if ls[i].Lapsed != copilotLapsedText {
was = nil
}
for _, m := range marks {
if !slices.Contains(was, m) {
was = append(was, m)
}
}
ls[i].Lapsed, ls[i].Refused = copilotLapsedText, strings.Join(slices.DeleteFunc(was, func(m string) bool { return m == "" }), ",")
return ls, nil
})
if err == nil || errors.Is(err, errUnchanged) {
copilotLapsedNote(app.User, true)
}
}
// copilotUnlapse clears the mark of the account of app: GitHub served it.
func copilotUnlapse(app copilotApp) {
copilotLapsedMu.Lock()
seen := copilotLapsedSeen[accountKey(app.User)]
copilotLapsedMu.Unlock()
if !seen || app.User == "" {
return
}
err := editSideLogin("copilot", app.User, func(ls []savedLogin, i int) ([]savedLogin, error) {
if ls[i].Lapsed == "" && ls[i].Refused == "" {
return nil, errUnchanged
}
ls[i].Lapsed, ls[i].Refused = "", ""
return ls, nil
})
if err == nil || errors.Is(err, errUnchanged) {
copilotLapsedNote(app.User, false)
}
}
// copilotSessionDone notes what GitHub said of app's sign-in at a trade:
// served, its mark goes; refused with nothing in its place, it is marked.
func copilotSessionDone(app copilotApp, err error) {
if err == nil {
copilotUnlapse(app)
return
}
if copilotLapsedBy(app) {
copilotLapse(app)
}
}
+359
View File
@@ -0,0 +1,359 @@
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
// lapsedCopilot is a machine with the editors signed in to octocat (gho_x,
// taken) and magpie to hubot (gho_kept), whose trade for a session token
// answers what status says.
func lapsedCopilot(t *testing.T) *atomic.Int32 {
t.Helper()
signIn(t)
os.RemoveAll(copilotCLIHome()) // no CLI sign-in
var status atomic.Int32
status.Store(200)
exchange := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "token gho_kept" && status.Load() != 200 {
w.WriteHeader(int(status.Load()))
w.Write([]byte(`{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest","status":"401"}`))
return
}
json.NewEncoder(w).Encode(map[string]any{"token": "tid", "expires_at": time.Now().Add(time.Hour).Unix()})
}))
t.Cleanup(exchange.Close)
old := CopilotTokenURL
CopilotTokenURL = exchange.URL
t.Cleanup(func() { CopilotTokenURL = old })
resetCopilotState()
t.Cleanup(resetCopilotState)
copilotLoginList()
if err := addCopilotLogin("hubot", "Pro", "gho_kept", ""); err != nil {
t.Fatal(err)
}
return &status
}
func resetCopilotState() {
copilotMu.Lock()
copilotSessions = map[string]copilotSession{}
copilotMu.Unlock()
copilotRefusals.Lock()
copilotRefusals.at, copilotRefusals.status = map[string]time.Time{}, map[string]int{}
copilotRefusals.Unlock()
copilotLapsedMu.Lock()
copilotLapsedSeen = map[string]bool{}
copilotLapsedMu.Unlock()
}
func copilotLapsedOf(t *testing.T, user string) string {
t.Helper()
for _, l := range Logins("copilot") {
if strings.EqualFold(l.User, user) {
return l.Lapsed
}
}
t.Fatalf("no copilot account %s in %+v", user, Logins("copilot"))
return ""
}
// copilotTrade sends a request on user's account the way the gateway
// does, and says what it got.
func copilotTrade(t *testing.T, user string) error {
t.Helper()
for _, c := range copilotLogins(copilotConfigDir()) {
if strings.EqualFold(c.User, user) {
copilotMu.Lock()
copilotSessions = map[string]copilotSession{}
copilotMu.Unlock()
p := copilotProvider(c.app, c.Plan)
req, _ := http.NewRequest("POST", "https://api.githubcopilot.com/chat/completions", nil)
return p.Sign(context.Background(), req, Chat, []byte(`{"messages":[{"role":"user","content":"hi"}]}`))
}
}
t.Fatalf("no copilot account %s", user)
return nil
}
// echo_ts on Discord: GitHub revoked a Copilot account's token, and the
// account still read as signed in while every request failed. Refused
// with 401 (or 403), it is signed out on its own row; signed in again in
// place it is in use as it was, its mark gone.
func TestCopilotRefusedTokenSignsTheAccountOut(t *testing.T) {
for _, code := range []int{401, 403} {
t.Run(http.StatusText(code), func(t *testing.T) {
status := lapsedCopilot(t)
if err := copilotTrade(t, "hubot"); err != nil {
t.Fatalf("taken: %v", err)
}
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("lapsed while taken: %q", l)
}
status.Store(int32(code))
if err := copilotTrade(t, "hubot"); err == nil || !strings.Contains(err.Error(), "signed out") {
t.Fatalf("refused: %v", err)
}
if l := copilotLapsedOf(t, "hubot"); l != copilotLapsedText {
t.Fatalf("refused %d, the account reads %q", code, l)
}
if l := copilotLapsedOf(t, "octocat"); l != "" {
t.Fatalf("the editors' octocat, still taken, reads %q", l)
}
// marked in logins.json: it reads so after a restart as well
resetCopilotState()
if l := copilotLapsedOf(t, "hubot"); l != copilotLapsedText {
t.Fatalf("after a restart the account reads %q", l)
}
var before Login
for _, l := range Logins("copilot") {
if l.User == "hubot" {
before = l
}
}
// signed in again from its row: the new token, in use as before
if err := addCopilotLogin("hubot", "Pro", "gho_new", ""); err != nil {
t.Fatal(err)
}
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("signed in again, the account reads %q", l)
}
// nothing of the old token's mark is kept in logins.json
for _, l := range readLogins() {
if l.Agent == "copilot" && l.User == "hubot" && (l.Lapsed != "" || l.Refused != "") {
t.Fatalf("signed in again, saved %+v", l)
}
}
n := 0
for _, l := range Logins("copilot") {
if l.User == "hubot" {
n++
if l.On != before.On || l.Active != before.Active || l.Plan != before.Plan {
t.Fatalf("signed in again: %+v, was %+v", l, before)
}
}
}
if n != 1 {
t.Fatalf("hubot listed %d times after signing in again", n)
}
if err := copilotTrade(t, "hubot"); err != nil {
t.Fatalf("the new sign-in: %v", err)
}
})
}
}
// Only GitHub's refusal of the token signs an account out: a 5xx, a 429 or
// a network error leave it as it was.
func TestCopilotTransientErrorsDontSignOut(t *testing.T) {
status := lapsedCopilot(t)
for _, code := range []int32{500, 502, 503, 429} {
status.Store(code)
if err := copilotTrade(t, "hubot"); err == nil {
t.Fatalf("%d: no error", code)
}
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("%d signed the account out: %q", code, l)
}
}
old := CopilotTokenURL
dead := httptest.NewServer(http.NotFoundHandler())
CopilotTokenURL = dead.URL
dead.Close()
if err := copilotTrade(t, "hubot"); err == nil {
t.Fatal("unreachable: no error")
}
CopilotTokenURL = old
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("a network error signed the account out: %q", l)
}
}
// Marked signed out, an account GitHub takes again (a request served on
// the same token) is in use again without a sign-in.
func TestCopilotServedAgainClearsTheMark(t *testing.T) {
status := lapsedCopilot(t)
status.Store(401)
copilotTrade(t, "hubot")
if copilotLapsedOf(t, "hubot") == "" {
t.Fatal("not marked")
}
resetCopilotState()
status.Store(200)
if err := copilotTrade(t, "hubot"); err != nil {
t.Fatal(err)
}
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("served again, the account reads %q", l)
}
}
// The editors' token refused while the Copilot CLI's sign-in of the same
// account stands in for it (#1238): served, so not signed out.
func TestCopilotStandInIsNotSignedOut(t *testing.T) {
staleEditor(t, "octocat")
t.Cleanup(resetCopilotState)
copilotLapsedMu.Lock()
copilotLapsedSeen = map[string]bool{}
copilotLapsedMu.Unlock()
p, ok := find(All(), "copilot")
if !ok {
t.Fatal("no copilot")
}
req, _ := http.NewRequest("POST", p.Chat+"/chat/completions", nil)
if err := p.Sign(context.Background(), req, Chat, []byte(`{}`)); err != nil {
t.Fatal(err)
}
if l := copilotLapsedOf(t, "octocat"); l != "" {
t.Fatalf("served by the CLI's sign-in, the account reads %q", l)
}
}
// The editors' token refused with the CLI signed in to another account:
// nothing stands in, so the editors' own account is signed out, and
// signed in again from magpie it is kept and in use.
func TestCopilotEditorRefusedSignsOut(t *testing.T) {
staleEditor(t, "hubot")
t.Cleanup(resetCopilotState)
copilotLapsedMu.Lock()
copilotLapsedSeen = map[string]bool{}
copilotLapsedMu.Unlock()
p, ok := find(All(), "copilot")
if !ok {
t.Fatal("no copilot")
}
if _, err := p.Fetch(context.Background()); err == nil {
t.Fatal("no error")
}
if l := copilotLapsedOf(t, "octocat"); l != copilotLapsedText {
t.Fatalf("refused, the editors' account reads %q", l)
}
if err := addCopilotLogin("octocat", "Business", "gho_magpie", ""); err != nil {
t.Fatal(err)
}
if l := copilotLapsedOf(t, "octocat"); l != "" {
t.Fatalf("signed in again, the account reads %q", l)
}
p, _ = find(All(), "copilot")
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatalf("with magpie's sign-in: %v", err)
}
}
// The account's allowance read is GitHub's answer too: 401 there, nothing
// in its place, signs it out and says so on its row; a 503 doesn't; read
// again, it is signed in again.
func TestCopilotUsageRefusedSignsOut(t *testing.T) {
lapsedCopilot(t)
var status atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "token gho_kept" && status.Load() != 200 {
w.WriteHeader(int(status.Load()))
return
}
w.Write([]byte(`{"copilot_plan":"individual","quota_snapshots":{"chat":{"unlimited":true},"completions":{"unlimited":true},"premium_interactions":{"has_quota":true,"entitlement":300,"quota_remaining":300}}}`))
}))
defer srv.Close()
old := CopilotUserURL
CopilotUserURL = srv.URL
defer func() { CopilotUserURL = old }()
status.Store(503)
if q := loginQuota(context.Background(), Login{Agent: "copilot", User: "hubot"}); q.Error == "" || q.Error == copilotLapsedText {
t.Fatalf("503: %+v", q)
}
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("503 signed the account out: %q", l)
}
status.Store(401)
if q := loginQuota(context.Background(), Login{Agent: "copilot", User: "hubot"}); q.Error != copilotLapsedText {
t.Fatalf("401: %+v", q)
}
if l := copilotLapsedOf(t, "hubot"); l != copilotLapsedText {
t.Fatalf("401, the account reads %q", l)
}
if l := copilotLapsedOf(t, "octocat"); l != "" {
t.Fatalf("the editors' octocat reads %q", l)
}
status.Store(200)
if q := loginQuota(context.Background(), Login{Agent: "copilot", User: "hubot"}); q.Error != "" {
t.Fatalf("200: %+v", q)
}
if l := copilotLapsedOf(t, "hubot"); l != "" {
t.Fatalf("read again, the account reads %q", l)
}
}
// The Copilot CLI's own sign-in revoked (401 from GitHub): its account is
// signed out, and signed in again from magpie the new token is kept and
// used in its place, the account listed once.
func TestCopilotCLIRefusedSignsOut(t *testing.T) {
home := signIn(t)
os.Remove(filepath.Join(home, ".config", "github-copilot", "apps.json"))
cli := filepath.Join(home, "copilot-home")
t.Setenv("COPILOT_HOME", cli)
os.MkdirAll(cli, 0o700)
os.WriteFile(filepath.Join(cli, "config.json"), []byte(`{"lastLoggedInUser":{"host":"https://github.com","login":"octocat"},"copilotTokens":{"https://github.com:octocat":"gho_cli"}}`), 0o600)
var refused atomic.Bool
user := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "token gho_cli" && refused.Load() {
w.WriteHeader(401)
w.Write([]byte(`{"message":"Bad credentials"}`))
return
}
json.NewEncoder(w).Encode(map[string]any{"endpoints": map[string]string{"api": "https://api.githubcopilot.com"}})
}))
defer user.Close()
exchange := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{"token": "tid", "expires_at": time.Now().Add(time.Hour).Unix()})
}))
defer exchange.Close()
oldUser, oldToken := CopilotUserURL, CopilotTokenURL
CopilotUserURL, CopilotTokenURL = user.URL, exchange.URL
defer func() { CopilotUserURL, CopilotTokenURL = oldUser, oldToken }()
resetCopilotState()
t.Cleanup(resetCopilotState)
if err := copilotTrade(t, "octocat"); err != nil {
t.Fatal(err)
}
refused.Store(true)
if err := copilotTrade(t, "octocat"); err == nil {
t.Fatal("refused: no error")
}
if l := copilotLapsedOf(t, "octocat"); l != copilotLapsedText {
t.Fatalf("refused, the CLI's account reads %q", l)
}
// a restart forgets the refusal; the sign-in asks GitHub again
resetCopilotState()
copilotProbeEditor(context.Background(), "octocat", "")
if err := addCopilotLogin("octocat", "Pro", "gho_magpie", ""); err != nil {
t.Fatal(err)
}
if l := copilotLapsedOf(t, "octocat"); l != "" {
t.Fatalf("signed in again, the account reads %q", l)
}
n := 0
for _, c := range copilotLogins(copilotConfigDir()) {
if strings.EqualFold(c.User, "octocat") {
n++
if c.app.Token != "gho_magpie" {
t.Fatalf("signed in again, the account sends %q", c.app.Token)
}
}
}
if n != 1 {
t.Fatalf("octocat listed %d times", n)
}
if err := copilotTrade(t, "octocat"); err != nil {
t.Fatalf("the new sign-in: %v", err)
}
}
+10
View File
@@ -338,6 +338,7 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
if l.Agent == "copilot" {
for _, c := range copilotLogins(copilotConfigDir()) {
if strings.EqualFold(c.User, l.User) {
orig := c.app
q := copilotSubscriptionUsage(ctx, c.app.Token, c.app.Host)
// an editor's stale token, the CLI signed in to the same
// account: read as the requests are sent (#1238)
@@ -348,7 +349,16 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
q = copilotSubscriptionUsage(ctx, cli.Token, cli.Host)
}
}
// GitHub refused the token, with none in its place: the
// account is signed out (echo_ts on Discord)
if q.Error == http.StatusText(http.StatusUnauthorized) {
copilotRefuse(orig.Token, http.StatusUnauthorized)
copilotRefuse(c.app.Token, http.StatusUnauthorized)
copilotLapse(orig)
q.Error = copilotLapsedText
}
if q.Error == "" {
copilotUnlapse(orig)
refreshCopilotEntitlement(c.app, q.Plan, q.AccessSKU)
}
return q
+11
View File
@@ -316,6 +316,12 @@ func upsertLogin(ls []savedLogin, l savedLogin) []savedLogin {
if l.Agent == "claude" && l.Lapsed == "" && ls[i].Refused != "" && ls[i].Refused == claudeLoginVersion(l) {
l.Lapsed, l.Refused = ls[i].Lapsed, ls[i].Refused
}
// so does a revoked sign-in's mark (signin_revoked.go), while
// the credential is the same: a sign-in anew or a refresh
// clears it, as does a request it serves
if l.Lapsed == "" && strings.HasPrefix(ls[i].Refused, revokedPrefix) && sameAuth(l.Auth, ls[i].Auth) && l.Home == ls[i].Home {
l.Lapsed, l.Refused = ls[i].Lapsed, ls[i].Refused
}
l.On = l.On || ls[i].On
l.Paused = l.Paused || ls[i].Paused
l.Order = ls[i].Order
@@ -869,6 +875,9 @@ func Logins(agent string) []Login {
Paused: (using || first) && pausedOwn(ls, l.Agent, l.User), first: first}
if l.Agent == "claude" {
lg.Lapsed = claudeSignedOut(l)
} else {
// the one in use too, its sign-in revoked (#1793)
lg.Lapsed = revokedLapse(l)
}
if !using {
if l.Agent != "claude" {
@@ -1321,6 +1330,8 @@ func ForgetAccounts() {
clear(newFetches.m)
newFetches.Unlock()
forgetAccountCaches()
// the revoked sign-ins known are read from logins.json again
resetRevoked()
}
// forgetAccountCaches makes the next look at the accounts read them afresh.
+7 -1
View File
@@ -104,7 +104,8 @@ func sideLogins(agent, ownUser string, usable func(savedLogin) bool) []sideLogin
if l.First || (first < 0 && l.own()) {
first = len(out)
}
out = append(out, sideLogin{Login{Agent: agent, User: l.User, Plan: l.Plan, Seen: l.Seen, On: l.On, Own: l.own()}, l})
// a sign-in its vendor revoked shows on the account (signin_revoked.go)
out = append(out, sideLogin{Login{Agent: agent, User: l.User, Plan: l.Plan, Seen: l.Seen, On: l.On, Own: l.own(), Lapsed: revokedLapse(l)}, l})
}
if len(out) == 0 {
return nil
@@ -283,6 +284,11 @@ func addSideLogin(l savedLogin, ownUser string, dup func(savedLogin)) (err error
if l.Agent == "copilot" {
ls[i].AccessSKU = l.AccessSKU
}
// a new sign-in: the token its vendor refused is gone
// (copilot_lapsed.go, signin_revoked.go)
if l.Agent == "copilot" || strings.HasPrefix(ls[i].Refused, revokedPrefix) {
ls[i].Lapsed, ls[i].Refused = "", ""
}
if old.own() {
ls[i].On = true
} else if old.Home != l.Home {
+218
View File
@@ -0,0 +1,218 @@
package provider
// A subscription account whose sign-in its vendor revoked. ChatGPT answers
// a request on a revoked token 401 "token_revoked" (ysicing, #1793), and
// waiting doesn't mend it: the account was signed out elsewhere, its
// password changed, its session ended. magpie used to send every request
// to it all the same, each refused, the account never said to be signed
// out. Now the account is marked lapsed, for the credential refused: the
// gateway passes over it while it still has that credential, without
// asking the vendor, and its row says to sign in again. A credential
// changed since (refreshed, or the account signed in again) is not the
// one refused, and a request it serves clears the mark.
//
// Claude's sign-ins keep their own mark (claude_auth.go), as do Copilot's
// (copilot_lapsed.go); a plugin's account is its plugin's to mark.
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"regexp"
"strings"
"sync"
"time"
)
// revokedPrefix starts a savedLogin's Refused when it holds the mark of a
// credential its vendor revoked.
const revokedPrefix = "revoked:"
// revokedWords: a 401 that says the sign-in itself is gone, not expired
// for a refresh to mend (token_expired) nor the request's fault. ChatGPT's
// token_revoked ("Encountered invalidated oauth token for user") and the
// refresh codes OpenAI's auth answers a dead sign-in with; and magpie's own
// words for one (revokedText), which the gateway may hold in place of the
// reply's body.
var revokedWords = regexp.MustCompile(`(?i)\btoken_revoked\b|\btoken_invalidated\b|\brefresh_token_(reused|invalidated|expired)\b|\binvalid_grant\b|invalidated oauth token|(token|sign-in) (has been|was) revoked`)
// SignInRevoked says a reply is the vendor's word that the sign-in it was
// sent with is revoked.
func SignInRevoked(status int, body []byte) bool {
return status == http.StatusUnauthorized && revokedWords.Match(body)
}
// RevokedAccount says the account's revoked sign-in is marked here: one
// of the built-in subscriptions that keep no mark of their own.
func RevokedAccount(a *Account) bool {
return a != nil && a.plugin == nil && a.User != "" && a.Agent != "claude" && a.Agent != "copilot"
}
// credentialMark tells the credential a request went with from another
// without keeping it.
func credentialMark(h http.Header) string {
for _, k := range []string{"Authorization", "X-Api-Key", "Cookie"} {
if v := h.Get(k); v != "" {
sum := sha256.Sum256([]byte(k + "\x00" + v))
return hex.EncodeToString(sum[:12])
}
}
return ""
}
// revoked is the credentials known revoked, by mark, each with why; and
// the mark of each account marked so, by agent and user, which a served
// request clears. Loaded from logins.json the first time either is asked.
var revoked = struct {
sync.Mutex
loaded bool
marks map[string]string
accounts map[string]string
}{marks: map[string]string{}, accounts: map[string]string{}}
func revokedKey(agent, user string) string { return agent + "\x00" + strings.ToLower(user) }
// revokedLoad reads the marks kept in logins.json; revoked is held.
func revokedLoad() {
if revoked.loaded {
return
}
revoked.loaded = true
loginsMu.Lock()
ls := readLogins()
loginsMu.Unlock()
for _, l := range ls {
if m, ok := strings.CutPrefix(l.Refused, revokedPrefix); ok && l.Lapsed != "" && m != "" {
revoked.marks[m] = l.Lapsed
revoked.accounts[revokedKey(l.Agent, l.User)] = m
}
}
}
// resetRevoked forgets what is known, to be read from logins.json again.
func resetRevoked() {
revoked.Lock()
defer revoked.Unlock()
revoked.loaded = false
revoked.marks, revoked.accounts = map[string]string{}, map[string]string{}
}
// revokedText is what a revoked account's row says.
func revokedText(user string) string {
return user + "'s sign-in was revoked; sign in again"
}
// RevokedSignIn is why the request req, signed for account a, isn't sent:
// its vendor revoked the credential it carries. ok is false otherwise.
func RevokedSignIn(a *Account, req *http.Request) (why string, ok bool) {
if !RevokedAccount(a) {
return "", false
}
m := credentialMark(req.Header)
if m == "" {
return "", false
}
revoked.Lock()
defer revoked.Unlock()
revokedLoad()
why, ok = revoked.marks[m]
return why, ok
}
// SignInMarked says account a is marked revoked: a request is asked of
// another account first where the gateway picks one alone (compaction).
func SignInMarked(a *Account) bool {
if !RevokedAccount(a) {
return false
}
revoked.Lock()
defer revoked.Unlock()
revokedLoad()
_, ok := revoked.accounts[revokedKey(a.Agent, a.User)]
return ok
}
// NoteRevokedSignIn keeps that the vendor revoked the credential req went
// to account a with. A saved ChatGPT account is refreshed first, as Codex
// does on a 401: a refresh that goes through is a new sign-in, and the
// account isn't marked.
func NoteRevokedSignIn(ctx context.Context, a *Account, req *http.Request) {
if !RevokedAccount(a) {
return
}
m := credentialMark(req.Header)
if m == "" {
return
}
if a.Agent == "codex" && a.token != nil {
// refreshed, the next request goes with the new token; refused
// or unanswered, the token sent is revoked all the same
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
_, _, err := renewSavedLogin(rctx, a.Agent, a.User, true)
cancel()
if err == nil {
return
}
}
why := revokedText(a.User)
revoked.Lock()
revokedLoad()
k := revokedKey(a.Agent, a.User)
if was, ok := revoked.accounts[k]; ok && was != m {
delete(revoked.marks, was) // logins.json keeps one mark an account
}
revoked.marks[m] = why
revoked.accounts[k] = m
revoked.Unlock()
_ = editSideLogin(a.Agent, a.User, func(ls []savedLogin, i int) ([]savedLogin, error) {
ls[i].Lapsed, ls[i].Refused = why, revokedPrefix+m
return ls, nil
})
}
// ServedSignIn notes a request account a's vendor served: a mark of a
// revoked sign-in it has is gone, as the account was signed in again or
// its sign-in refreshed.
func ServedSignIn(a *Account) {
if !RevokedAccount(a) {
return
}
k := revokedKey(a.Agent, a.User)
revoked.Lock()
revokedLoad()
m, marked := revoked.accounts[k]
delete(revoked.accounts, k)
delete(revoked.marks, m) // as after a restart, which reads it gone
revoked.Unlock()
if !marked {
return
}
_ = editSideLogin(a.Agent, a.User, func(ls []savedLogin, i int) ([]savedLogin, error) {
if !strings.HasPrefix(ls[i].Refused, revokedPrefix) {
return nil, errUnchanged
}
ls[i].Lapsed, ls[i].Refused = "", ""
return ls, nil
})
}
// sameAuth says two credential blobs are the same sign-in, however each
// was laid out (logins.json indents what auth.json may not).
func sameAuth(a, b json.RawMessage) bool {
var ca, cb bytes.Buffer
if json.Compact(&ca, a) != nil || json.Compact(&cb, b) != nil {
return bytes.Equal(bytes.TrimSpace(a), bytes.TrimSpace(b))
}
return bytes.Equal(ca.Bytes(), cb.Bytes())
}
// revokedLapse is a saved account's lapse when it is a revoked sign-in's.
func revokedLapse(l savedLogin) string {
if strings.HasPrefix(l.Refused, revokedPrefix) {
return l.Lapsed
}
return ""
}
+197
View File
@@ -0,0 +1,197 @@
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Only a 401 whose words say the sign-in is gone marks it (#1793): an
// expired token is a refresh's to mend, and a 403, a 5xx or a rate limit
// says nothing about the sign-in.
func TestSignInRevokedWords(t *testing.T) {
for _, c := range []struct {
status int
body string
want bool
}{
{401, `{"error":{"message":"Encountered invalidated oauth token for user, failing request","code":"token_revoked"},"status":401}`, true},
{401, `{"error":"invalid_grant","error_description":"Refresh token has been revoked"}`, true},
{401, `{"error":{"code":"refresh_token_reused"}}`, true},
{401, `{"error":{"code":"token_expired","message":"Provided authentication token is expired."}}`, false},
{401, `{"error":{"message":"Incorrect API key provided"}}`, false},
{403, `{"error":{"code":"token_revoked"}}`, false},
{500, `{"error":{"code":"token_revoked"}}`, false},
{502, `upstream connect error`, false},
{429, `{"error":{"code":"rate_limit_exceeded"}}`, false},
} {
if got := SignInRevoked(c.status, []byte(c.body)); got != c.want {
t.Errorf("%d %s: %v, want %v", c.status, c.body, got, c.want)
}
}
}
func revokedReq(t *testing.T, token string) *http.Request {
t.Helper()
req, _ := http.NewRequest("POST", "http://x", nil)
req.Header.Set("Authorization", "Bearer "+token)
return req
}
func sideLapsed(t *testing.T, agent, user string) string {
t.Helper()
for _, l := range sideLogins(agent, "", func(savedLogin) bool { return true }) {
if strings.EqualFold(l.User, user) {
return l.Lapsed
}
}
t.Fatalf("no %s account %s", agent, user)
return ""
}
// A side account (ZCode, Grok, ... signed in in magpie) whose sign-in its
// vendor revoked is marked for that credential, kept across a restart,
// shown on its row, and cleared by a request it serves or a sign-in anew.
func TestRevokedSideLoginMarkedTillSignedInAgain(t *testing.T) {
signIn(t)
resetRevoked()
t.Cleanup(resetRevoked)
if err := addSideLogin(savedLogin{Agent: "zcode", User: "u@example.com", Auth: json.RawMessage(`{"token":"a"}`)}, "", func(savedLogin) {}); err != nil {
t.Fatal(err)
}
a := &Account{Agent: "zcode", User: "u@example.com"}
if _, ok := RevokedSignIn(a, revokedReq(t, "a")); ok {
t.Fatal("marked before anything was refused")
}
NoteRevokedSignIn(context.Background(), a, revokedReq(t, "a"))
if why, ok := RevokedSignIn(a, revokedReq(t, "a")); !ok || !strings.Contains(why, "sign in again") {
t.Fatalf("not marked: %q %v", why, ok)
}
if _, ok := RevokedSignIn(a, revokedReq(t, "b")); ok {
t.Fatal("another credential of the account is held too")
}
if got := sideLapsed(t, "zcode", "u@example.com"); !strings.Contains(got, "sign in again") {
t.Fatalf("the row isn't said signed out: %q", got)
}
// a restart reads it from logins.json
resetRevoked()
if _, ok := RevokedSignIn(a, revokedReq(t, "a")); !ok {
t.Fatal("the mark is gone after a restart")
}
// served (its sign-in mended elsewhere): cleared, in logins.json too
ServedSignIn(a)
if _, ok := RevokedSignIn(a, revokedReq(t, "a")); ok {
t.Fatal("still held after a request was served")
}
resetRevoked()
if _, ok := RevokedSignIn(a, revokedReq(t, "a")); ok {
t.Fatal("held again after a restart")
}
if got := sideLapsed(t, "zcode", "u@example.com"); got != "" {
t.Fatalf("still said signed out: %q", got)
}
// marked again, then signed in anew in magpie: the row is clear
NoteRevokedSignIn(context.Background(), a, revokedReq(t, "a"))
if err := addSideLogin(savedLogin{Agent: "zcode", User: "u@example.com", Auth: json.RawMessage(`{"token":"c"}`)}, "", func(savedLogin) {}); err != nil {
t.Fatal(err)
}
if got := sideLapsed(t, "zcode", "u@example.com"); got != "" {
t.Fatalf("signed in again, still said signed out: %q", got)
}
}
// Claude's, Copilot's and a plugin's accounts keep their own marks.
func TestRevokedSignInLeavesOthersMarks(t *testing.T) {
for _, a := range []*Account{nil, {Agent: "claude", User: "x"}, {Agent: "copilot", User: "x"}, {Agent: "codex"}} {
if RevokedAccount(a) {
t.Errorf("%+v marked here", a)
}
}
if !RevokedAccount(&Account{Agent: "codex", User: "x"}) {
t.Error("a ChatGPT account isn't marked")
}
}
// A saved ChatGPT account is refreshed before it is marked, as Codex does
// on a 401: a refresh that goes through is a new sign-in. A refresh refused
// marks it, and the account's row says so.
func TestRevokedCodexRefreshedFirst(t *testing.T) {
home := signIn(t)
resetRevoked()
t.Cleanup(resetRevoked)
codexSignIn(t, home, "old@example.com", "r-old")
rememberLogins(true)
codexSignIn(t, home, "work@example.com", "r-work")
rememberLogins(true)
refuse := false
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if refuse {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"invalid_grant","error_description":"refresh token has been revoked"}`))
return
}
json.NewEncoder(w).Encode(map[string]any{"access_token": "fresh-old", "refresh_token": "r-old-2"})
}))
defer fake.Close()
old := codexTokenURL
codexTokenURL = fake.URL
t.Cleanup(func() { codexTokenURL = old })
if err := SetLoginOn("codex", "old@example.com", true); err != nil {
t.Fatal(err)
}
p, err := Find("codex")
if err != nil {
t.Fatal(err)
}
also := p.AlsoOn()
if len(also) != 1 || also[0].Account.User != "old@example.com" || also[0].Account.token == nil {
t.Fatalf("not the saved account: %+v", also)
}
a := also[0].Account
lapsed := func() string {
for _, l := range Logins("codex") {
if l.User == "old@example.com" {
return l.Lapsed
}
}
t.Fatal("old@ isn't listed")
return ""
}
NoteRevokedSignIn(context.Background(), a, revokedReq(t, "stale"))
if _, ok := RevokedSignIn(a, revokedReq(t, "stale")); ok {
t.Fatal("marked although its refresh went through")
}
if got := lapsed(); got != "" {
t.Fatalf("refreshed, still said signed out: %q", got)
}
refuse = true
NoteRevokedSignIn(context.Background(), a, revokedReq(t, "fresh-old"))
if _, ok := RevokedSignIn(a, revokedReq(t, "fresh-old")); !ok {
t.Fatal("its refresh refused, the account isn't marked")
}
if got := lapsed(); !strings.Contains(got, "sign in again") {
t.Fatalf("not said signed out: %q", got)
}
}
// The account's record written again with the same sign-in (as each time
// Codex's auth.json is read) keeps the mark; a new sign-in drops it.
func TestUpsertLoginKeepsRevokedMarkForTheSameSignIn(t *testing.T) {
ls := []savedLogin{{Agent: "codex", User: "x@example.com", Auth: json.RawMessage("{\n \"a\": 1\n}"), Lapsed: revokedText("x@example.com"), Refused: revokedPrefix + "m"}}
same := upsertLogin(append([]savedLogin(nil), ls...), savedLogin{Agent: "codex", User: "x@example.com", Auth: json.RawMessage(`{"a":1}`)})
if len(same) != 1 || same[0].Refused != revokedPrefix+"m" || same[0].Lapsed == "" {
t.Fatalf("the same sign-in lost its mark: %+v", same)
}
anew := upsertLogin(append([]savedLogin(nil), ls...), savedLogin{Agent: "codex", User: "x@example.com", Auth: json.RawMessage(`{"a":2}`)})
if len(anew) != 1 || anew[0].Refused != "" || anew[0].Lapsed != "" {
t.Fatalf("a new sign-in kept the mark: %+v", anew)
}
}