Files
magpie/internal/provider/copilot_cli.go
T
yetone 9f94b2156b copilot: an account on GitHub Enterprise Cloud with data residency (*.ghe.com) signs in, is read from copilot login --host and is served at its enterprise (#723, guitaoliu: magpie skipped a Copilot CLI sign-in whose host wasn't github.com and its own sign-in was fixed to github.com) — a Copilot account now remembers its host (copilotApp.Host, "host" in its logins.json auth; none for github.com) and every URL it uses follows it, as VS Code's Copilot Chat, copilot.lua and avante do (checked against the issue's references and GitHub's docs): the device flow at https://<name>.ghe.com/login/device/code and /login/oauth/access_token with the same Copilot OAuth app, the device page there, whose account at https://api.<name>.ghe.com/user, its plan and usage at api.<name>.ghe.com/copilot_internal/user, its session token at api.<name>.ghe.com/copilot_internal/v2/token, and its requests, model list, Auto and terms at the session's endpoints.api, or https://copilot-api.<name>.ghe.com when it names none (the provider's base too). A github.com account has no host and goes where it always did, the same vars and the same bytes. CopilotHost (copilot_ghe.go) takes only github.com or one <name>.ghe.com label (a scheme and a trailing slash are dropped; a port, path, user, deeper subdomain or any other host is refused), in the sign-in, the CLI and a host read back from logins.json, so a GitHub token is never sent to a host of the user's choosing. The Copilot CLI's sign-in: a github.com account first, as before; then one copilot login --host <name>.ghe.com signed in, its token under "https://<name>.ghe.com:<login>" in copilotTokens or the keychain; a GitHub Enterprise Server host is still left out. An editor's apps.json entry keyed "<name>.ghe.com:…" is read after the editors' github.com one and the CLI's. GUI: a Copilot device code's panel has "Account on GHE.com?" (zh 账号在 GHE.com 上?), which ends that sign-in and asks "Your enterprise on GHE.com" (你的企业在 GHE.com 上的地址) in a field (acme.ghe.com; Sign in stays off until it reads as <name>.ghe.com), then signs in there; that sign-in's panel offers "Sign in on github.com instead" (改为在 github.com 登录), as does a failed one. CLI: magpie accounts add copilot [--host <name>.ghe.com]. TestCopilotHost, TestCopilotGHESignIn (an httptest server standing in for acme.ghe.com, api.acme.ghe.com and copilot-api.acme.ghe.com through copilotGHEOrigin: sign-in, what is kept, models, a signed request, usage, nothing sent to github.com, a bad host refused) and TestCopilotCLIGHELogin are new and fail on the old code; copilot-ghe.test.cjs (webkit and chromium, en and zh: the link, the field refusing evil.com, a.b.ghe.com, ports and the like, the posted site, the way back, cancels, no native select, no left-border accent) fails on the old code. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass; signin-link, signin-close, signin-again and routing-signin pass in webkit, signin-callback fails before and after the change alike. Not tried with a real GHE.com account: the URLs follow the references, and the CLI's token key for a ghe.com host is taken to be the github.com one's form. Accounts are still told apart by login alone; an EMU login carries its enterprise's suffix.
2026-10-04 06:56:04 +08:00

168 lines
4.9 KiB
Go

package provider
// The standalone Copilot CLI keeps its sign-in apart from the editors: who
// is signed in in ~/.copilot/config.json, the token in the system keychain
// (service copilot-cli), or in that file when the user chose plaintext. Its
// token is not traded for a session token the way an editor's is (that
// exchange answers 403): the CLI sends it as is, under its own integration.
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/proc"
)
// copilotCLIHeaders are what the CLI sends with its token.
var copilotCLIHeaders = map[string]string{
"Editor-Version": "copilot/1.0.88",
"Copilot-Integration-Id": "copilot-developer-cli",
"X-GitHub-Api-Version": "2026-07-01",
"User-Agent": "copilot/1.0.88",
}
// CopilotUserURL says where an account's Copilot API is; a var so tests can
// point it elsewhere.
var CopilotUserURL = "https://api.github.com/copilot_internal/user"
type copilotCLIUser struct {
Host string `json:"host"`
Login string `json:"login"`
}
// copilotCLIHome is where the CLI keeps its settings.
func copilotCLIHome() string {
if h := os.Getenv("COPILOT_HOME"); h != "" {
return h
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".copilot")
}
// copilotCLILogin is the account the Copilot CLI is signed in to, with its
// token.
func copilotCLILogin() (copilotApp, bool) {
raw, err := os.ReadFile(filepath.Join(copilotCLIHome(), "config.json"))
if err != nil {
return copilotApp{}, false
}
var cfg struct {
Last *copilotCLIUser `json:"lastLoggedInUser"`
Users []copilotCLIUser `json:"loggedInUsers"`
Tokens map[string]string `json:"copilotTokens"`
}
if json.Unmarshal(jsonc.ToJSON(raw), &cfg) != nil {
return copilotApp{}, false
}
users := cfg.Users
if cfg.Last != nil {
users = append([]copilotCLIUser{*cfg.Last}, users...)
}
// a github.com account first, as before; then one an enterprise's
// `copilot login --host <name>.ghe.com` signed in (#723). A GitHub
// Enterprise Server's own host is left out: its API isn't GHE.com's.
for _, ghe := range []bool{false, true} {
for _, u := range users {
host, ok := copilotHostOf(u.Host)
if u.Login == "" || !ok || (host != "") != ghe {
continue
}
key := "https://github.com:" + u.Login
if ghe {
key = strings.TrimSuffix(u.Host, "/") + ":" + u.Login
}
tok := cfg.Tokens[key]
if tok == "" {
tok = copilotCLISecret(key)
}
if tok != "" {
return copilotApp{User: u.Login, Token: tok, Host: host, cli: true}, true
}
}
}
return copilotApp{}, false
}
var copilotSecrets struct {
sync.Mutex
at map[string]time.Time
tok map[string]string
}
// copilotCLISecret reads the CLI's token from the keychain, once in a
// while: each read may ask the user to allow it.
var copilotCLISecret = func(account string) string {
c := &copilotSecrets
c.Lock()
defer c.Unlock()
if c.at == nil {
c.at, c.tok = map[string]time.Time{}, map[string]string{}
}
ttl := time.Hour
if c.tok[account] == "" {
ttl = 10 * time.Minute // denied or absent; don't ask again at once
}
if at, ok := c.at[account]; ok && time.Since(at) < ttl {
return c.tok[account]
}
var out []byte
switch runtime.GOOS {
case "darwin":
out, _ = proc.Command("security", "find-generic-password", "-s", "copilot-cli", "-a", account, "-w").Output()
case "linux":
if p, err := exec.LookPath("secret-tool"); err == nil {
out, _ = proc.Command(p, "lookup", "service", "copilot-cli", "account", account).Output()
}
}
c.at[account], c.tok[account] = time.Now(), string(bytes.TrimSpace(out))
return c.tok[account]
}
// copilotDirect is the session a CLI token makes: the token itself, at the
// API its account is served from.
func copilotDirect(ctx context.Context, app copilotApp) (copilotSession, error) {
github := app.Token
copilotMu.Lock()
defer copilotMu.Unlock()
if s, ok := copilotSessions[github]; ok && time.Until(time.Unix(s.ExpiresAt, 0)) > 2*time.Minute {
return s, nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, copilotUserURL(app.Host), nil)
if err != nil {
return copilotSession{}, err
}
req.Header.Set("Authorization", "token "+github)
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return copilotSession{}, errors.New("Copilot sign-in: " + err.Error())
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
var u struct {
Endpoints struct {
API string `json:"api"`
} `json:"endpoints"`
}
if res.StatusCode != 200 || json.Unmarshal(b, &u) != nil {
return copilotSession{}, errors.New("the Copilot CLI's sign-in was refused (" + APIError(b, res.Status) + "); run `copilot login` again")
}
s := copilotSession{Token: github, ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), direct: true}
s.Endpoints.API = u.Endpoints.API
copilotSessions[github] = s
return s, nil
}