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.
This commit is contained in:
+24
-1
@@ -24,7 +24,7 @@ import (
|
||||
// — the subscriptions magpie remembers, how much of each one's allowance is
|
||||
// used, and switching the agent between them.
|
||||
func accountsCmd(args []string) error {
|
||||
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts project <gemini|antigravity> <email> <gcp-project-id>"
|
||||
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts project <gemini|antigravity> <email> <gcp-project-id>"
|
||||
agentID := func(s string) (string, error) {
|
||||
switch strings.ToLower(s) {
|
||||
case "claude", "cc":
|
||||
@@ -73,6 +73,27 @@ func accountsCmd(args []string) error {
|
||||
return checkinWorkBuddy(len(args) > 2 && args[2] == "--json")
|
||||
}
|
||||
if len(args) > 1 && args[1] == "add" {
|
||||
// a Copilot account by GitHub's device code, on github.com or an
|
||||
// enterprise's <name>.ghe.com (#723)
|
||||
if len(args) >= 3 && strings.EqualFold(args[2], "copilot") {
|
||||
var host string
|
||||
switch {
|
||||
case len(args) == 5 && args[3] == "--host":
|
||||
host = args[4]
|
||||
case len(args) == 4 && strings.HasPrefix(args[3], "--host="):
|
||||
host = strings.TrimPrefix(args[3], "--host=")
|
||||
case len(args) != 3:
|
||||
return fmt.Errorf("usage: magpie accounts add copilot [--host <name>.ghe.com]")
|
||||
}
|
||||
h, err := provider.CopilotHost(host)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h != "" {
|
||||
return addAccount("copilot:" + h)
|
||||
}
|
||||
return addAccount("copilot")
|
||||
}
|
||||
if len(args) != 3 {
|
||||
return fmt.Errorf("%s", usage)
|
||||
}
|
||||
@@ -357,6 +378,8 @@ func addAccount(agentID string) error {
|
||||
fmt.Println(green.Render("✓"), st.User, "is already listed — its sign-in was renewed")
|
||||
} else if st.Using {
|
||||
fmt.Println(green.Render("✓"), agentID, "is signed in as", st.User)
|
||||
} else if strings.HasPrefix(agentID, "copilot") {
|
||||
fmt.Println(green.Render("✓"), "added", st.User, muted.Render("· with the other Copilot accounts in magpie's window"))
|
||||
} else {
|
||||
fmt.Println(green.Render("✓"), "added", st.User, muted.Render("· use it: magpie accounts switch "+agentID+" "+st.User))
|
||||
}
|
||||
|
||||
@@ -8198,6 +8198,66 @@ function cancelSignIn() {
|
||||
renderProviders();
|
||||
}
|
||||
|
||||
// A Copilot account on GitHub Enterprise Cloud with data residency signs in
|
||||
// at its enterprise's <name>.ghe.com, not github.com (#723): the device
|
||||
// code's panel offers that, and the host is asked in place of the code.
|
||||
const GHE_HOST = /^(https?:\/\/)?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.ghe\.com\/?$/i;
|
||||
|
||||
// copilotHostSwitch: the link from a Copilot sign-in to the other place it
|
||||
// can be — an enterprise's GHE.com, or back to github.com.
|
||||
function copilotHostSwitch(sub) {
|
||||
if (sub.agent !== "copilot" || sub.plugin) return null;
|
||||
const site = signing.site;
|
||||
const b = el("button", "link", site ? t("Sign in on github.com instead") : t("Account on GHE.com?"));
|
||||
b.dataset.ghe = site ? "github" : "ghe";
|
||||
b.title = site ? t("Signing in on {host}", { host: site }) : t("An account of an enterprise on GitHub Enterprise Cloud with data residency signs in at its <name>.ghe.com");
|
||||
b.onclick = () => {
|
||||
if (site) return startSignIn("copilot", true); // which ends this one
|
||||
if (signing?.id) api("signin/" + signing.id + "/cancel", {}).catch(() => {});
|
||||
signing = { agent: "copilot", state: "ghe" };
|
||||
renderProviders();
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
// renderCopilotGHE: the enterprise's host asked before its sign-in starts.
|
||||
function renderCopilotGHE(sub) {
|
||||
const box = el("div", "signing copilot-ghe");
|
||||
const tt = el("span", "tt");
|
||||
box.append(tt);
|
||||
const flow = signing;
|
||||
const label = t("Your enterprise on GHE.com");
|
||||
tt.append(el("span", "n", label),
|
||||
el("span", "s", t("The address you sign in to GitHub at, like acme.ghe.com. An account on github.com doesn't need it.")));
|
||||
const form = el("form", "callback-form");
|
||||
const inp = input(flow.host || "", "acme.ghe.com");
|
||||
inp.setAttribute("aria-label", label);
|
||||
const go = el("button", "text primary", t("Sign in"));
|
||||
go.type = "submit";
|
||||
go.disabled = !GHE_HOST.test(inp.value.trim());
|
||||
const why = el("span", "s why", "");
|
||||
inp.oninput = () => { flow.host = inp.value; go.disabled = !GHE_HOST.test(inp.value.trim()); why.textContent = ""; };
|
||||
const submit = (e) => {
|
||||
e.preventDefault();
|
||||
if (signing !== flow) return;
|
||||
const host = inp.value.trim().replace(/^https?:\/\//i, "").replace(/\/$/, "").toLowerCase();
|
||||
if (!GHE_HOST.test(host)) { why.textContent = t("Type your enterprise's <name>.ghe.com"); return; }
|
||||
startSignIn("copilot", true, host);
|
||||
};
|
||||
form.onsubmit = submit;
|
||||
go.onclick = submit;
|
||||
form.append(inp, go);
|
||||
tt.append(form, why);
|
||||
const close = el("button", "text", t("Cancel"));
|
||||
close.onclick = cancelSignIn;
|
||||
const back = el("button", "text", "github.com");
|
||||
back.title = t("Sign in on github.com instead");
|
||||
back.onclick = () => startSignIn("copilot", true);
|
||||
box.append(close, back);
|
||||
setTimeout(() => { if (inp.isConnected) inp.focus({ preventScroll: true }); });
|
||||
return box;
|
||||
}
|
||||
|
||||
// dropSigningIn: the editor of provider id closing (Cancel, Save, Remove)
|
||||
// leaves no sign-in of its account waiting behind it, to come back with the
|
||||
// editor (#526: 无论我点击底部的移除、取消、保存都没办法); an import being
|
||||
@@ -8249,6 +8309,7 @@ function renderSigning(sub) {
|
||||
}
|
||||
return box;
|
||||
}
|
||||
if (signing.state === "ghe") return renderCopilotGHE(sub);
|
||||
if (signing.state === "import" || signing.state === "importing" || signing.state === "imported") return renderLoginImport(sub);
|
||||
if (signing.state === "method" || signing.state === "prompt" || signing.state === "key") return renderPluginAsk(sub);
|
||||
if (signing.state === "failed") {
|
||||
@@ -8259,6 +8320,8 @@ function renderSigning(sub) {
|
||||
again.onclick = () => sub.plugin ? startPluginSignIn(sub, signing.method) : startSignIn(sub.agent, true, signing.site);
|
||||
const close = el("button", "text", t("Cancel"));
|
||||
close.onclick = cancelSignIn;
|
||||
const ghe = copilotHostSwitch(sub);
|
||||
if (ghe) tt.append(el("span", "acts", ghe));
|
||||
box.append(close, again);
|
||||
return box;
|
||||
}
|
||||
@@ -8298,6 +8361,8 @@ function renderSigning(sub) {
|
||||
const open = el("button", "link", t("Open again"));
|
||||
open.onclick = () => api("open", { url: signing.url }).catch(() => {});
|
||||
acts.append(open);
|
||||
const ghe = copilotHostSwitch(sub);
|
||||
if (ghe) acts.append(ghe);
|
||||
tt.append(acts);
|
||||
}
|
||||
if (signing.pasteCallback || signing.pasteCode || signing.pasteKey) {
|
||||
|
||||
@@ -804,6 +804,13 @@ const I18N = {
|
||||
"1 provider to bring over": "有 1 个供应商可导入",
|
||||
"{n} providers to bring over": "有 {n} 个供应商可导入",
|
||||
"magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.": "magpie 已打开 GitHub 的设备登录页,请在那里输入下面的验证码;完成后账号会立即出现在这里。",
|
||||
"Account on GHE.com?": "账号在 GHE.com 上?",
|
||||
"Sign in on github.com instead": "改为在 github.com 登录",
|
||||
"Signing in on {host}": "正在 {host} 登录",
|
||||
"An account of an enterprise on GitHub Enterprise Cloud with data residency signs in at its <name>.ghe.com": "使用数据驻留的 GitHub Enterprise Cloud 企业账号,要在企业自己的 <name>.ghe.com 登录",
|
||||
"Your enterprise on GHE.com": "你的企业在 GHE.com 上的地址",
|
||||
"The address you sign in to GitHub at, like acme.ghe.com. An account on github.com doesn't need it.": "即你登录 GitHub 时用的地址,例如 acme.ghe.com。github.com 上的账号不用填。",
|
||||
"Type your enterprise's <name>.ghe.com": "请输入企业的 <name>.ghe.com 地址",
|
||||
"magpie opened Factory's sign-in page. Check it shows this code and confirm it; the account shows up here as soon as you're done.": "magpie 已打开 Factory 的登录页,请确认页面上显示的是下面的验证码并确认;完成后账号会立即出现在这里。",
|
||||
"Droid Core · 5 hours": "Droid Core · 5 小时",
|
||||
"Droid Core · 7 days": "Droid Core · 7 天",
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A Copilot account on GitHub Enterprise Cloud with data residency (#723):
|
||||
// the device code's panel offers "Account on GHE.com?", which asks the
|
||||
// enterprise's <name>.ghe.com and posts it as the sign-in's site; a host
|
||||
// that isn't one can't be submitted, and github.com is one click back.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const playwright = require("playwright");
|
||||
|
||||
const engines = (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]);
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
for (const engine of engines) for (const lang of ["en", "zh"]) {
|
||||
test(`copilot GHE.com sign-in (${engine}, ${lang})`, async (t) => {
|
||||
const browser = await playwright[engine].launch();
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage({ viewport: { width: 420, height: 640 } });
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posted = [];
|
||||
const canceled = [];
|
||||
let n = 0;
|
||||
await page.route("**/*", 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:"dark",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "dark" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: {} });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/signin") {
|
||||
const body = route.request().postDataJSON();
|
||||
posted.push(body);
|
||||
const host = body.site || "github.com";
|
||||
return json({ id: "c" + ++n, agent: "copilot", state: "waiting", code: "ABCD-1234", url: `https://${host}/login/device` });
|
||||
}
|
||||
if (/^\/api\/signin\/c\d+\/cancel$/.test(url.pathname)) { canceled.push(url.pathname.split("/")[3]); return json({}); }
|
||||
if (/^\/api\/signin\/c\d+$/.test(url.pathname)) return new Promise(() => {}); // stays waiting
|
||||
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)];
|
||||
return route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
});
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.waitForFunction((l) => state.settings.lang === l, lang);
|
||||
await page.evaluate(() => {
|
||||
providers = providers || { providers: [], presets: [], plugins: [] };
|
||||
window.renderProviders = () => {
|
||||
const host = document.getElementById("csign") || Object.assign(document.createElement("div"), { id: "csign" });
|
||||
host.style.cssText = "position:fixed;inset:0 auto auto 0;width:100%;z-index:1000;";
|
||||
host.replaceChildren(signing ? renderSigning(subOf("copilot")) : "");
|
||||
document.body.append(host);
|
||||
};
|
||||
startSignIn("copilot", true);
|
||||
});
|
||||
const box = page.locator("#csign");
|
||||
const noAccents = async () => {
|
||||
const bad = await box.evaluate((root) => [...root.querySelectorAll("*")].filter((e) => {
|
||||
const s = getComputedStyle(e);
|
||||
return parseFloat(s.borderLeftWidth) > 0 && s.borderLeftWidth !== s.borderRightWidth;
|
||||
}).map((e) => e.outerHTML.slice(0, 80)));
|
||||
assert.deepEqual(bad, []);
|
||||
assert.equal(await box.locator("select").count(), 0);
|
||||
};
|
||||
|
||||
// github.com's sign-in, as before, with the way to an enterprise's
|
||||
await page.waitForFunction(() => signing?.state === "waiting");
|
||||
assert.deepEqual(posted, [{ agent: "copilot" }]);
|
||||
const toGHE = box.locator('button[data-ghe="ghe"]');
|
||||
assert.equal(await toGHE.textContent(), lang === "zh" ? "账号在 GHE.com 上?" : "Account on GHE.com?");
|
||||
assert.ok((await toGHE.getAttribute("title")).length > 0);
|
||||
await noAccents();
|
||||
|
||||
// it asks the host, ending the github.com sign-in
|
||||
await toGHE.click();
|
||||
await page.waitForFunction(() => signing?.state === "ghe");
|
||||
await page.waitForFunction(() => document.querySelector("#csign .copilot-ghe input"));
|
||||
assert.deepEqual(canceled, ["c1"]);
|
||||
const text = await box.innerText();
|
||||
assert.match(text, lang === "zh" ? /你的企业在 GHE\.com 上的地址/ : /Your enterprise on GHE\.com/);
|
||||
assert.match(text, lang === "zh" ? /github\.com 上的账号不用填/ : /An account on github\.com doesn't need it/);
|
||||
const field = box.locator(".copilot-ghe input");
|
||||
const go = box.locator('.copilot-ghe button[type="submit"]');
|
||||
assert.equal(await field.getAttribute("placeholder"), "acme.ghe.com");
|
||||
assert.equal(await go.textContent(), lang === "zh" ? "登录" : "Sign in");
|
||||
assert.equal(await go.isDisabled(), true);
|
||||
for (const bad of ["evil.com", "acme.ghe.com.evil.com", "a.b.ghe.com", "acme.ghe.com:8443", "github.example.com"]) {
|
||||
await field.fill(bad);
|
||||
assert.equal(await go.isDisabled(), true, bad);
|
||||
}
|
||||
await noAccents();
|
||||
await field.fill("https://Acme.ghe.com/");
|
||||
assert.equal(await go.isDisabled(), false);
|
||||
await field.press("Enter");
|
||||
await page.waitForFunction(() => signing?.state === "waiting" && signing.site);
|
||||
assert.deepEqual(posted[1], { agent: "copilot", site: "acme.ghe.com" });
|
||||
assert.equal(await page.evaluate(() => signing.site), "acme.ghe.com");
|
||||
assert.match(await box.innerText(), /https:\/\/acme\.ghe\.com\/login\/device/);
|
||||
|
||||
// and back to github.com
|
||||
const back = box.locator('button[data-ghe="github"]');
|
||||
assert.equal(await back.textContent(), lang === "zh" ? "改为在 github.com 登录" : "Sign in on github.com instead");
|
||||
assert.equal(await back.getAttribute("title"), lang === "zh" ? "正在 acme.ghe.com 登录" : "Signing in on acme.ghe.com");
|
||||
await back.click();
|
||||
await page.waitForFunction(() => signing?.state === "waiting" && !signing.site && signing.id === "c3");
|
||||
assert.deepEqual(posted[2], { agent: "copilot" });
|
||||
assert.deepEqual(canceled, ["c1", "c2"]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
@@ -954,11 +954,15 @@ var (
|
||||
type copilotApp struct {
|
||||
User string `json:"user"`
|
||||
Token string `json:"oauth_token"`
|
||||
cli bool // the standalone Copilot CLI's sign-in
|
||||
// Host is an enterprise's <name>.ghe.com the account is on, "" for
|
||||
// github.com (copilot_ghe.go)
|
||||
Host string `json:"host,omitempty"`
|
||||
cli bool // the standalone Copilot CLI's sign-in
|
||||
}
|
||||
|
||||
// copilotLogin finds the GitHub token Copilot's editors and CLI keep.
|
||||
func copilotLogin(cfg string) (copilotApp, bool) {
|
||||
var ghe *copilotApp // an editor's sign-in on an enterprise's <name>.ghe.com
|
||||
for _, name := range []string{"apps.json", "hosts.json"} {
|
||||
var apps map[string]copilotApp
|
||||
if !readJSON(filepath.Join(cfg, "github-copilot", name), &apps) {
|
||||
@@ -971,19 +975,31 @@ func copilotLogin(cfg string) (copilotApp, bool) {
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if strings.HasPrefix(k, "github.com") && apps[k].Token != "" {
|
||||
return apps[k], true
|
||||
app := apps[k]
|
||||
app.Host = ""
|
||||
return app, true
|
||||
}
|
||||
// "acme.ghe.com:Iv1…", as copilot.lua keeps one (#723)
|
||||
host, _, _ := strings.Cut(k, ":")
|
||||
if h, err := CopilotHost(host); ghe == nil && err == nil && h != "" && apps[k].Token != "" {
|
||||
app := apps[k]
|
||||
app.Host = h
|
||||
ghe = &app
|
||||
}
|
||||
}
|
||||
}
|
||||
return copilotCLILogin()
|
||||
if app, ok := copilotCLILogin(); ok || ghe == nil {
|
||||
return app, ok
|
||||
}
|
||||
return *ghe, true
|
||||
}
|
||||
|
||||
// session is what this sign-in's requests carry.
|
||||
func (a copilotApp) session(ctx context.Context) (copilotSession, error) {
|
||||
if a.cli {
|
||||
return copilotDirect(ctx, a.Token)
|
||||
return copilotDirect(ctx, a)
|
||||
}
|
||||
return copilotToken(ctx, a.Token)
|
||||
return copilotToken(ctx, a)
|
||||
}
|
||||
|
||||
// copilotProvider is Copilot as one GitHub account serves it.
|
||||
@@ -997,8 +1013,8 @@ func copilotProvider(app copilotApp, plan string) Provider {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Endpoints.API != "" {
|
||||
if u, err := url.Parse(s.Endpoints.API + req.URL.Path); err == nil {
|
||||
if s.Endpoints.API != "" || app.Host != "" {
|
||||
if u, err := url.Parse(s.apiBase(app.Host) + req.URL.Path); err == nil {
|
||||
req.URL, req.Host = u, u.Host
|
||||
}
|
||||
}
|
||||
@@ -1046,7 +1062,8 @@ func copilotProvider(app copilotApp, plan string) Provider {
|
||||
// each model is served on some of these: the newest GPT models on
|
||||
// /responses alone, Claude's on /v1/messages and /chat/completions (its
|
||||
// model list says; see Provider.APIs)
|
||||
return Provider{ID: "copilot", Name: "Copilot", Icon: "githubcopilot", Chat: copilotBase, Responses: copilotBase, Anthropic: copilotBase, Website: "https://github.com/features/copilot", Account: acct}
|
||||
base := copilotBaseOf(app.Host)
|
||||
return Provider{ID: "copilot", Name: "Copilot", Icon: "githubcopilot", Chat: base, Responses: base, Anthropic: base, Website: "https://github.com/features/copilot", Account: acct}
|
||||
}
|
||||
|
||||
// bodyModel is the model a request asks for.
|
||||
@@ -1103,13 +1120,14 @@ func lastRole(body []byte) string {
|
||||
return items[len(items)-1].Role
|
||||
}
|
||||
|
||||
func copilotToken(ctx context.Context, github string) (copilotSession, error) {
|
||||
func copilotToken(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, CopilotTokenURL, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, copilotTokenURL(app.Host), nil)
|
||||
if err != nil {
|
||||
return copilotSession{}, err
|
||||
}
|
||||
@@ -1169,10 +1187,7 @@ func copilotAccept(ctx context.Context, app copilotApp, s copilotSession, model
|
||||
if !waiting[model] {
|
||||
return
|
||||
}
|
||||
base := s.Endpoints.API
|
||||
if base == "" {
|
||||
base = copilotBase
|
||||
}
|
||||
base := s.apiBase(app.Host)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/"+url.PathEscape(model)+"/policy", strings.NewReader(`{"state":"enabled"}`))
|
||||
if err != nil {
|
||||
return
|
||||
@@ -1200,10 +1215,7 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := s.Endpoints.API
|
||||
if base == "" {
|
||||
base = copilotBase
|
||||
}
|
||||
base := s.apiBase(app.Host)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -32,6 +32,10 @@ func copilotSaved(l savedLogin) (copilotApp, bool) {
|
||||
if l.own() || json.Unmarshal(l.Auth, &app) != nil || app.Token == "" {
|
||||
return copilotApp{}, false
|
||||
}
|
||||
// only github.com or an enterprise's <name>.ghe.com gets the token
|
||||
if h, err := CopilotHost(app.Host); err != nil || h != app.Host {
|
||||
return copilotApp{}, false
|
||||
}
|
||||
app.User = l.User
|
||||
return app, true
|
||||
}
|
||||
@@ -92,9 +96,14 @@ func forgetCopilotLogin(user string) error {
|
||||
return forgetSideLogin("copilot", user, copilotSide(), nil)
|
||||
}
|
||||
|
||||
// addCopilotLogin keeps an account magpie just signed in.
|
||||
func addCopilotLogin(user, plan, token string) error {
|
||||
auth, _ := json.Marshal(map[string]string{"oauth_token": token})
|
||||
// addCopilotLogin keeps an account magpie just signed in, on host ("" for
|
||||
// github.com).
|
||||
func addCopilotLogin(user, plan, token, host string) error {
|
||||
a := map[string]string{"oauth_token": token}
|
||||
if host != "" {
|
||||
a["host"] = host
|
||||
}
|
||||
auth, _ := json.Marshal(a)
|
||||
return addSideLogin(savedLogin{Agent: "copilot", User: user, Plan: plan, Auth: auth}, copilotOwnUser(copilotConfigDir()), func(savedLogin) {})
|
||||
}
|
||||
|
||||
@@ -126,7 +135,7 @@ var copilotPlans = map[string]string{
|
||||
|
||||
// copilotUser is who a GitHub token belongs to and which Copilot plan it
|
||||
// has; no plan, no Copilot.
|
||||
func copilotUser(ctx context.Context, token string) (user, plan string, err error) {
|
||||
func copilotUser(ctx context.Context, token, host string) (user, plan string, err error) {
|
||||
get := func(u string, v any) (int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
@@ -148,11 +157,11 @@ func copilotUser(ctx context.Context, token string) (user, plan string, err erro
|
||||
var gh struct {
|
||||
Login string `json:"login"`
|
||||
}
|
||||
if _, err := get(GitHubUserURL, &gh); err != nil || gh.Login == "" {
|
||||
if _, err := get(gitHubUserURL(host), &gh); err != nil || gh.Login == "" {
|
||||
return "", "", errors.New("GitHub didn't say whose account this is")
|
||||
}
|
||||
var cp copilotEntitlement
|
||||
if code, err := get(CopilotUserURL, &cp); err != nil {
|
||||
if code, err := get(copilotUserURL(host), &cp); err != nil {
|
||||
if code == 401 || code == 403 || code == 404 {
|
||||
return gh.Login, "", errors.New(gh.Login + " has no Copilot subscription")
|
||||
}
|
||||
|
||||
@@ -68,10 +68,7 @@ func copilotAutoResolve(ctx context.Context, app copilotApp, fresh bool) (copilo
|
||||
if err != nil {
|
||||
return copilotAutoSession{}, err
|
||||
}
|
||||
base := s.Endpoints.API
|
||||
if base == "" {
|
||||
base = copilotBase
|
||||
}
|
||||
base := s.apiBase(app.Host)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/session", strings.NewReader(`{"auto_mode":{"model_hints":["auto"]}}`))
|
||||
if err != nil {
|
||||
return copilotAutoSession{}, err
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -70,17 +71,26 @@ func copilotCLILogin() (copilotApp, bool) {
|
||||
if cfg.Last != nil {
|
||||
users = append([]copilotCLIUser{*cfg.Last}, users...)
|
||||
}
|
||||
for _, u := range users {
|
||||
if u.Login == "" || (u.Host != "" && u.Host != "https://github.com") {
|
||||
continue // GitHub Enterprise has an API of its own
|
||||
}
|
||||
key := "https://github.com:" + u.Login
|
||||
tok := cfg.Tokens[key]
|
||||
if tok == "" {
|
||||
tok = copilotCLISecret(key)
|
||||
}
|
||||
if tok != "" {
|
||||
return copilotApp{User: u.Login, Token: tok, cli: true}, true
|
||||
// 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
|
||||
@@ -123,13 +133,14 @@ var copilotCLISecret = func(account string) string {
|
||||
|
||||
// copilotDirect is the session a CLI token makes: the token itself, at the
|
||||
// API its account is served from.
|
||||
func copilotDirect(ctx context.Context, github string) (copilotSession, error) {
|
||||
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, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, copilotUserURL(app.Host), nil)
|
||||
if err != nil {
|
||||
return copilotSession{}, err
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestCopilotEntitlementLabels(t *testing.T) {
|
||||
|
||||
func TestCopilotEntitlementRefresh(t *testing.T) {
|
||||
signIn(t)
|
||||
if err := addCopilotLogin("hubot", "Pro", "gho_hubot"); err != nil {
|
||||
if err := addCopilotLogin("hubot", "Pro", "gho_hubot", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
copilotLoginList() // remember the editor's own account
|
||||
@@ -56,11 +56,11 @@ func TestCopilotEntitlementRefresh(t *testing.T) {
|
||||
|
||||
func TestCopilotReplacementClearsSKU(t *testing.T) {
|
||||
signIn(t)
|
||||
if err := addCopilotLogin("hubot", "Education", "old"); err != nil {
|
||||
if err := addCopilotLogin("hubot", "Education", "old", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refreshCopilotEntitlement(copilotApp{User: "hubot", Token: "old"}, "Education", "free_educational_quota")
|
||||
if err := addCopilotLogin("hubot", "Pro", "new"); err != nil {
|
||||
if err := addCopilotLogin("hubot", "Pro", "new", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, l := range readLogins() {
|
||||
@@ -84,7 +84,7 @@ func TestCopilotOwnEntitlementSwitch(t *testing.T) {
|
||||
|
||||
func TestCopilotEducationQuotaRefresh(t *testing.T) {
|
||||
signIn(t)
|
||||
if err := addCopilotLogin("hubot", "Pro", "gho_hubot"); err != nil {
|
||||
if err := addCopilotLogin("hubot", "Pro", "gho_hubot", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fail := false
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package provider
|
||||
|
||||
// Copilot on GitHub Enterprise Cloud with data residency (#723): an
|
||||
// enterprise's accounts live at <name>.ghe.com, not github.com. They sign in
|
||||
// with the same device flow and OAuth app at https://<name>.ghe.com, trade
|
||||
// their token at https://api.<name>.ghe.com/copilot_internal/v2/token, are
|
||||
// looked up at api.<name>.ghe.com, and are served at the API their session
|
||||
// names (endpoints.api: https://copilot-api.<name>.ghe.com), as VS Code's
|
||||
// Copilot Chat, copilot.lua and `copilot login --host` do. An account
|
||||
// remembers its host; one on github.com has none, and every URL it uses is
|
||||
// the one it always was.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// gheName is an enterprise's subdomain of ghe.com: one DNS label.
|
||||
var gheName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`)
|
||||
|
||||
// CopilotHost is where a Copilot account signs in, from what a user typed
|
||||
// ("acme.ghe.com", "https://acme.ghe.com/", "github.com"): "" for
|
||||
// github.com, "<name>.ghe.com" for an enterprise on GHE.com. Nothing else
|
||||
// is taken, so a GitHub token is never sent to a host of the user's choosing.
|
||||
func CopilotHost(s string) (string, error) {
|
||||
h := strings.ToLower(strings.TrimSpace(s))
|
||||
if strings.Contains(h, "://") {
|
||||
u, err := url.Parse(h)
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil || u.Port() != "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", errors.New("not a GitHub host: " + strings.TrimSpace(s))
|
||||
}
|
||||
h = u.Hostname()
|
||||
}
|
||||
h = strings.TrimSuffix(h, "/")
|
||||
if h == "" || h == "github.com" || h == "www.github.com" {
|
||||
return "", nil
|
||||
}
|
||||
if name, ok := strings.CutSuffix(h, ".ghe.com"); ok && gheName.MatchString(name) {
|
||||
return h, nil
|
||||
}
|
||||
return "", errors.New("Copilot signs in on github.com or an enterprise's <name>.ghe.com, not " + strings.TrimSpace(s))
|
||||
}
|
||||
|
||||
// copilotGHEOrigin is https://[sub.]host; a var so tests can point an
|
||||
// enterprise's hosts elsewhere.
|
||||
var copilotGHEOrigin = func(host, sub string) string {
|
||||
if sub == "" {
|
||||
return "https://" + host
|
||||
}
|
||||
return "https://" + sub + "." + host
|
||||
}
|
||||
|
||||
// copilotHostOf is an account's host from the Copilot CLI's
|
||||
// ("https://acme.ghe.com"); ok is false for one magpie can't serve.
|
||||
func copilotHostOf(cli string) (string, bool) {
|
||||
if cli == "" {
|
||||
return "", true
|
||||
}
|
||||
h, err := CopilotHost(cli)
|
||||
return h, err == nil
|
||||
}
|
||||
|
||||
// The URLs an account uses: github.com's own (vars tests point elsewhere)
|
||||
// with no host, its enterprise's otherwise.
|
||||
|
||||
func copilotDeviceURL(host string) string {
|
||||
if host == "" {
|
||||
return gitHubDeviceURL
|
||||
}
|
||||
return copilotGHEOrigin(host, "") + "/login/device/code"
|
||||
}
|
||||
|
||||
func copilotOAuthURL(host string) string {
|
||||
if host == "" {
|
||||
return gitHubTokenURL
|
||||
}
|
||||
return copilotGHEOrigin(host, "") + "/login/oauth/access_token"
|
||||
}
|
||||
|
||||
func copilotDevicePage(host string) string {
|
||||
if host == "" {
|
||||
return "https://github.com/login/device"
|
||||
}
|
||||
return copilotGHEOrigin(host, "") + "/login/device"
|
||||
}
|
||||
|
||||
func copilotTokenURL(host string) string {
|
||||
if host == "" {
|
||||
return CopilotTokenURL
|
||||
}
|
||||
return copilotGHEOrigin(host, "api") + "/copilot_internal/v2/token"
|
||||
}
|
||||
|
||||
func copilotUserURL(host string) string {
|
||||
if host == "" {
|
||||
return CopilotUserURL
|
||||
}
|
||||
return copilotGHEOrigin(host, "api") + "/copilot_internal/user"
|
||||
}
|
||||
|
||||
func gitHubUserURL(host string) string {
|
||||
if host == "" {
|
||||
return GitHubUserURL
|
||||
}
|
||||
return copilotGHEOrigin(host, "api") + "/user"
|
||||
}
|
||||
|
||||
// copilotBaseOf is the Copilot API an account is served at when its
|
||||
// session names none.
|
||||
func copilotBaseOf(host string) string {
|
||||
if host == "" {
|
||||
return copilotBase
|
||||
}
|
||||
return copilotGHEOrigin(host, "copilot-api")
|
||||
}
|
||||
|
||||
// apiBase is where this session's requests go.
|
||||
func (s copilotSession) apiBase(host string) string {
|
||||
if s.Endpoints.API != "" {
|
||||
return s.Endpoints.API
|
||||
}
|
||||
return copilotBaseOf(host)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCopilotHost(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"": "", "github.com": "", "https://github.com": "", "https://github.com/": "", "GitHub.com": "",
|
||||
"acme.ghe.com": "acme.ghe.com", "https://acme.ghe.com": "acme.ghe.com", "https://Acme.GHE.com/": "acme.ghe.com",
|
||||
" octo-corp.ghe.com ": "octo-corp.ghe.com",
|
||||
} {
|
||||
if got, err := CopilotHost(in); err != nil || got != want {
|
||||
t.Errorf("CopilotHost(%q) = %q, %v; want %q", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{
|
||||
"evil.com", "ghe.com", ".ghe.com", "a.b.ghe.com", "acme.ghe.com.evil.com", "acme.ghe.com:8443",
|
||||
"https://acme.ghe.com:8443", "https://user@acme.ghe.com", "https://acme.ghe.com/x", "acme.ghe.com/x",
|
||||
"-acme.ghe.com", "acme-.ghe.com", "api.github.com", "github.example.com", "ftp://acme.ghe.com", "acme_x.ghe.com",
|
||||
} {
|
||||
if got, err := CopilotHost(in); err == nil {
|
||||
t.Errorf("CopilotHost(%q) = %q, want an error", in, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gheServer stands in for an enterprise's hosts: a request to
|
||||
// https://<sub>.acme.ghe.com/<path> arrives as /<sub>.acme.ghe.com/<path>.
|
||||
// github.com's own URLs point at a path it refuses.
|
||||
func gheServer(t *testing.T, token string) (*httptest.Server, *[]string) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.Method+" "+r.URL.Path)
|
||||
mu.Unlock()
|
||||
auth := r.Header.Get("Authorization")
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "POST /acme.ghe.com/login/device/code":
|
||||
r.ParseForm()
|
||||
if r.Form.Get("client_id") != copilotClientID {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"device_code": "dc", "user_code": "ABCD-1234", "verification_uri": "https://acme.ghe.com/login/device", "interval": 1})
|
||||
case "POST /acme.ghe.com/login/oauth/access_token":
|
||||
r.ParseForm()
|
||||
if r.Form.Get("device_code") != "dc" || r.Form.Get("client_id") != copilotClientID {
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"access_token": token})
|
||||
case "GET /api.acme.ghe.com/user":
|
||||
if auth != "token "+token {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"login": "mona_acme"})
|
||||
case "GET /api.acme.ghe.com/copilot_internal/user":
|
||||
if auth != "token "+token {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"copilot_plan": "enterprise", "endpoints": map[string]string{"api": srv.URL + "/copilot-api.acme.ghe.com"},
|
||||
"quota_snapshots": map[string]any{"premium_interactions": map[string]any{"has_quota": true, "entitlement": 1000, "quota_remaining": 750}}})
|
||||
case "GET /api.acme.ghe.com/copilot_internal/v2/token":
|
||||
if auth != "token "+token {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"token": "tid=ent", "expires_at": time.Now().Add(time.Hour).Unix(),
|
||||
"endpoints": map[string]string{"api": srv.URL + "/copilot-api.acme.ghe.com"}})
|
||||
case "GET /copilot-api.acme.ghe.com/models":
|
||||
if auth != "Bearer tid=ent" && auth != "Bearer "+token {
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"data":[{"id":"gpt-5.5","name":"GPT-5.5","model_picker_enabled":true,"capabilities":{"type":"chat"},"supported_endpoints":["/responses"]}]}`))
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
oldOrigin := copilotGHEOrigin
|
||||
copilotGHEOrigin = func(host, sub string) string {
|
||||
if sub != "" {
|
||||
host = sub + "." + host
|
||||
}
|
||||
return srv.URL + "/" + host
|
||||
}
|
||||
never := srv.URL + "/github.com"
|
||||
oldDev, oldTok, oldCT, oldCU, oldGU := gitHubDeviceURL, gitHubTokenURL, CopilotTokenURL, CopilotUserURL, GitHubUserURL
|
||||
gitHubDeviceURL, gitHubTokenURL, CopilotTokenURL, CopilotUserURL, GitHubUserURL = never, never, never, never, never
|
||||
t.Cleanup(func() {
|
||||
copilotGHEOrigin = oldOrigin
|
||||
gitHubDeviceURL, gitHubTokenURL, CopilotTokenURL, CopilotUserURL, GitHubUserURL = oldDev, oldTok, oldCT, oldCU, oldGU
|
||||
})
|
||||
copilotMu.Lock()
|
||||
copilotSessions = map[string]copilotSession{}
|
||||
copilotMu.Unlock()
|
||||
return srv, &seen
|
||||
}
|
||||
|
||||
// An account on an enterprise's <name>.ghe.com signs in there, remembers
|
||||
// it, and is looked up, listed, served and metered there (#723).
|
||||
func TestCopilotGHESignIn(t *testing.T) {
|
||||
signIn(t)
|
||||
srv, seen := gheServer(t, "ghu_ent")
|
||||
|
||||
if _, err := StartSignInAt("copilot", "evil.example.com"); err == nil {
|
||||
t.Fatal("a sign-in at a host that isn't github.com or <name>.ghe.com started")
|
||||
}
|
||||
st, err := StartSignInAt("copilot", "https://acme.ghe.com/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Code != "ABCD-1234" || st.URL != "https://acme.ghe.com/login/device" {
|
||||
t.Fatalf("sign-in: %+v", st)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
st, err = WaitSignIn(ctx, st.ID)
|
||||
if err != nil || st.State != "done" || st.User != "mona_acme" || st.Plan != "Enterprise" || st.Using {
|
||||
t.Fatalf("signed in: %+v %v", st, err)
|
||||
}
|
||||
var saved *savedLogin
|
||||
for _, l := range readLogins() {
|
||||
if l.Agent == "copilot" && l.User == "mona_acme" {
|
||||
saved = &l
|
||||
}
|
||||
}
|
||||
var auth map[string]string
|
||||
if saved == nil || json.Unmarshal(saved.Auth, &auth) != nil || len(auth) != 2 || auth["host"] != "acme.ghe.com" || auth["oauth_token"] != "ghu_ent" {
|
||||
t.Fatalf("kept: %+v", saved)
|
||||
}
|
||||
|
||||
var app copilotApp
|
||||
for _, c := range copilotLogins(copilotConfigDir()) {
|
||||
if c.User == "mona_acme" {
|
||||
app = c.app
|
||||
}
|
||||
}
|
||||
if app.Host != "acme.ghe.com" || app.Token != "ghu_ent" {
|
||||
t.Fatalf("listed: %+v", app)
|
||||
}
|
||||
p := copilotProvider(app, "Enterprise")
|
||||
ms, err := p.Fetch(context.Background())
|
||||
if err != nil || len(ms) != 2 || ms[0].ID != "gpt-5.5" {
|
||||
t.Fatalf("models: %+v %v", ms, err)
|
||||
}
|
||||
if p.Responses != srv.URL+"/copilot-api.acme.ghe.com" {
|
||||
t.Fatalf("base: %s", p.Responses)
|
||||
}
|
||||
// the gateway asks the provider's base; the test's base has a path of its own
|
||||
req, _ := http.NewRequest("POST", "https://copilot-api.acme.ghe.com/responses", nil)
|
||||
if err := p.Sign(context.Background(), req, Responses, []byte(`{"model":"gpt-5.5","input":"hi"}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.URL.String() != srv.URL+"/copilot-api.acme.ghe.com/responses" || req.Header.Get("Authorization") != "Bearer tid=ent" {
|
||||
t.Fatalf("signed: %s %v", req.URL, req.Header)
|
||||
}
|
||||
q := copilotSubscriptionUsage(context.Background(), app.Token, app.Host)
|
||||
if q.Error != "" || q.Plan != "Enterprise" || len(q.Windows) != 1 || q.Windows[0].Used != 25 {
|
||||
t.Fatalf("usage: %+v", q)
|
||||
}
|
||||
for _, s := range *seen {
|
||||
if strings.Contains(s, "/github.com") {
|
||||
t.Errorf("an enterprise account asked github.com: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
// a host edited into logins.json isn't sent the token
|
||||
if _, ok := copilotSaved(savedLogin{Agent: "copilot", User: "x", Auth: []byte(`{"oauth_token":"t","host":"evil.example.com"}`)}); ok {
|
||||
t.Fatal("an account at evil.example.com was taken")
|
||||
}
|
||||
}
|
||||
|
||||
// `copilot login --host acme.ghe.com` is read, and served at its
|
||||
// enterprise; a github.com sign-in beside it still comes first, and a
|
||||
// GitHub Enterprise Server's is left out.
|
||||
func TestCopilotCLIGHELogin(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)
|
||||
srv, _ := gheServer(t, "gho_ent")
|
||||
oldSecret := copilotCLISecret
|
||||
copilotCLISecret = func(string) string { return "" }
|
||||
defer func() { copilotCLISecret = oldSecret }()
|
||||
|
||||
write := func(s string) { os.WriteFile(filepath.Join(cli, "config.json"), []byte(s), 0o600) }
|
||||
write(`{"lastLoggedInUser":{"host":"https://acme.ghe.com","login":"mona_acme"},
|
||||
"loggedInUsers":[{"host":"https://acme.ghe.com","login":"mona_acme"}],
|
||||
"copilotTokens":{"https://acme.ghe.com:mona_acme":"gho_ent"}}`)
|
||||
p, ok := find(All(), "copilot")
|
||||
if !ok || p.Account.User != "mona_acme" {
|
||||
t.Fatalf("copilot: %+v", p)
|
||||
}
|
||||
ms, err := p.Fetch(context.Background())
|
||||
if err != nil || len(ms) != 2 || ms[0].ID != "gpt-5.5" {
|
||||
t.Fatalf("models: %+v %v", ms, err)
|
||||
}
|
||||
req, _ := http.NewRequest("POST", "https://copilot-api.acme.ghe.com/chat/completions", nil)
|
||||
if err := p.Sign(context.Background(), req, Chat, []byte(`{"messages":[{"role":"user","content":"hi"}]}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.URL.String() != srv.URL+"/copilot-api.acme.ghe.com/chat/completions" || req.Header.Get("Authorization") != "Bearer gho_ent" {
|
||||
t.Fatalf("signed: %s %v", req.URL, req.Header)
|
||||
}
|
||||
|
||||
write(`{"lastLoggedInUser":{"host":"https://acme.ghe.com","login":"mona_acme"},
|
||||
"loggedInUsers":[{"host":"https://acme.ghe.com","login":"mona_acme"},{"host":"https://github.com","login":"octocat"}],
|
||||
"copilotTokens":{"https://acme.ghe.com:mona_acme":"gho_ent","https://github.com:octocat":"gho_dot"}}`)
|
||||
if app, ok := copilotCLILogin(); !ok || app.User != "octocat" || app.Host != "" || app.Token != "gho_dot" {
|
||||
t.Fatalf("github.com first: %+v", app)
|
||||
}
|
||||
write(`{"lastLoggedInUser":{"host":"https://github.example.com","login":"ghes"},"copilotTokens":{"https://github.example.com:ghes":"gho_ghes"}}`)
|
||||
if app, ok := copilotCLILogin(); ok {
|
||||
t.Fatalf("a GitHub Enterprise Server sign-in was taken: %+v", app)
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,13 @@ func gitHubForm(ctx context.Context, u string, form url.Values, v any) error {
|
||||
return json.Unmarshal(b, v)
|
||||
}
|
||||
|
||||
// startCopilotSignIn signs in on github.com, or on the enterprise's
|
||||
// <name>.ghe.com the sign-in names (#723).
|
||||
func startCopilotSignIn(s *signInFlow) error {
|
||||
host, err := CopilotHost(s.site)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
var dc struct {
|
||||
DeviceCode string `json:"device_code"`
|
||||
@@ -53,7 +59,7 @@ func startCopilotSignIn(s *signInFlow) error {
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
Interval int `json:"interval"`
|
||||
}
|
||||
if err := gitHubForm(ctx, gitHubDeviceURL, url.Values{"client_id": {copilotClientID}, "scope": {"read:user"}}, &dc); err != nil {
|
||||
if err := gitHubForm(ctx, copilotDeviceURL(host), url.Values{"client_id": {copilotClientID}, "scope": {"read:user"}}, &dc); err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
@@ -63,7 +69,7 @@ func startCopilotSignIn(s *signInFlow) error {
|
||||
}
|
||||
s.st.URL, s.st.Code = dc.URI, dc.UserCode
|
||||
if s.st.URL == "" {
|
||||
s.st.URL = "https://github.com/login/device"
|
||||
s.st.URL = copilotDevicePage(host)
|
||||
}
|
||||
s.stop = cancel
|
||||
interval := time.Duration(max(dc.Interval, 1)) * time.Second
|
||||
@@ -80,7 +86,7 @@ func startCopilotSignIn(s *signInFlow) error {
|
||||
Error string `json:"error"`
|
||||
Desc string `json:"error_description"`
|
||||
}
|
||||
err := gitHubForm(ctx, gitHubTokenURL, url.Values{"client_id": {copilotClientID}, "device_code": {dc.DeviceCode},
|
||||
err := gitHubForm(ctx, copilotOAuthURL(host), url.Values{"client_id": {copilotClientID}, "device_code": {dc.DeviceCode},
|
||||
"grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}}, &tok)
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
@@ -102,18 +108,18 @@ func startCopilotSignIn(s *signInFlow) error {
|
||||
fail("GitHub: " + strings.TrimSpace(tok.Error+" "+tok.Desc))
|
||||
return
|
||||
}
|
||||
user, plan, err := copilotUser(ctx, tok.Token)
|
||||
user, plan, err := copilotUser(ctx, tok.Token, host)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
if err := addCopilotLogin(user, plan, tok.Token); err != nil {
|
||||
if err := addCopilotLogin(user, plan, tok.Token, host); err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
// the one Copilot's editors are signed in to, if it is this
|
||||
using := false
|
||||
if own, ok := copilotLogin(copilotConfigDir()); ok && strings.EqualFold(own.User, user) {
|
||||
if own, ok := copilotLogin(copilotConfigDir()); ok && strings.EqualFold(own.User, user) && own.Host == host {
|
||||
using = true
|
||||
}
|
||||
s.finish(SignInState{State: "done", User: user, Plan: plan, Using: using})
|
||||
|
||||
@@ -189,7 +189,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) {
|
||||
q := copilotSubscriptionUsage(ctx, c.app.Token)
|
||||
q := copilotSubscriptionUsage(ctx, c.app.Token, c.app.Host)
|
||||
if q.Error == "" {
|
||||
refreshCopilotEntitlement(c.app, q.Plan, q.AccessSKU)
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ func TestCopilotUsageResets(t *testing.T) {
|
||||
old := CopilotUserURL
|
||||
CopilotUserURL = srv.URL
|
||||
defer func() { CopilotUserURL = old }()
|
||||
q := copilotSubscriptionUsage(t.Context(), "tok")
|
||||
q := copilotSubscriptionUsage(t.Context(), "tok", "")
|
||||
if q.Error != "" || len(q.Windows) != 2 || q.Windows[1].ResetsAt == nil || q.Windows[1].ResetsAt.Month() != time.October {
|
||||
t.Fatalf("%+v", q)
|
||||
}
|
||||
|
||||
@@ -776,7 +776,7 @@ func (w codexWindow) window() QuotaWindow {
|
||||
return out
|
||||
}
|
||||
|
||||
func copilotSubscriptionUsage(ctx context.Context, githubToken string) SubscriptionQuota {
|
||||
func copilotSubscriptionUsage(ctx context.Context, githubToken, host string) SubscriptionQuota {
|
||||
q := SubscriptionQuota{Provider: "copilot", Name: "Copilot", Icon: "githubcopilot", Windows: []QuotaWindow{}}
|
||||
var data struct {
|
||||
copilotEntitlement
|
||||
@@ -784,7 +784,7 @@ func copilotSubscriptionUsage(ctx context.Context, githubToken string) Subscript
|
||||
Reset string `json:"quota_reset_date_utc"`
|
||||
ResetDay string `json:"quota_reset_date"`
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, CopilotUserURL, nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, copilotUserURL(host), nil)
|
||||
if err == nil {
|
||||
req.Header.Set("Authorization", "token "+githubToken)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
@@ -139,7 +139,7 @@ func TestCopilotQuotaWithoutEditorsSignIn(t *testing.T) {
|
||||
if _, ok := copilotLogin(filepath.Join(home, ".config")); ok {
|
||||
t.Fatal("the editors' own sign-in is still readable")
|
||||
}
|
||||
if err := addCopilotLogin("hubot", "Pro+", "ghu_hubot"); err != nil {
|
||||
if err := addCopilotLogin("hubot", "Pro+", "ghu_hubot", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ls := copilotLoginList(); len(ls) != 1 || ls[0].User != "hubot" {
|
||||
|
||||
@@ -75,6 +75,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie group <id> | set <id> k=v… | rm <id> show, change or remove one (magpie group help for more)
|
||||
magpie accounts [agent] [--json] every subscription magpie knows, with each one's allowance used and when it resets
|
||||
magpie accounts add <agent> sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription
|
||||
magpie accounts add copilot [--host <name>.ghe.com] one more Copilot account, on github.com or an enterprise's GHE.com
|
||||
magpie accounts switch <agent> <email> sign the agent in to another of them
|
||||
magpie accounts refresh renew the saved ChatGPT sign-ins now (the gateway does it daily)
|
||||
magpie accounts checkin WorkBuddy's daily check-in (签到) for each WorkBuddy account, now (Settings can do it daily)
|
||||
|
||||
Reference in New Issue
Block a user