fix(github-copilot): support GUI/RPC wizard auth flow (#73290)

Merged via squash.

Prepared head SHA: aea7d6650c
Co-authored-by: indierawk2k2 <18598712+indierawk2k2@users.noreply.github.com>
Co-authored-by: shanselman <2892+shanselman@users.noreply.github.com>
Reviewed-by: @shanselman
This commit is contained in:
Mike Harsh
2026-04-29 16:45:31 -07:00
committed by GitHub
parent d30b8dccfd
commit 36bb723dfb
6 changed files with 331 additions and 45 deletions

View File

@@ -4,7 +4,6 @@ import path from "node:path";
import {
clearRuntimeAuthProfileStoreSnapshots,
ensureAuthProfileStore,
upsertAuthProfile,
} from "openclaw/plugin-sdk/agent-runtime";
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -216,17 +215,36 @@ describe("github-copilot plugin", () => {
},
}),
);
mocks.githubCopilotLoginCommand.mockImplementationOnce(async (opts: { agentDir?: string }) => {
upsertAuthProfile({
profileId: "github-copilot:github",
credential: {
type: "token",
provider: "github-copilot",
token: "refreshed-token",
},
agentDir: opts.agentDir,
});
const fetchMock = vi.fn(async (input: unknown) => {
const target =
typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input instanceof Request
? input.url
: String(input);
if (target === "https://github.com/login/device/code") {
return new Response(
JSON.stringify({
device_code: "device-code-stub",
user_code: "ABCD-1234",
verification_uri: "https://github.com/login/device",
expires_in: 900,
interval: 0,
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
if (target === "https://github.com/login/oauth/access_token") {
return new Response(
JSON.stringify({ access_token: "refreshed-token", token_type: "bearer" }),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
}
throw new Error(`unexpected fetch in github-copilot refresh test: ${target}`);
});
vi.stubGlobal("fetch", fetchMock);
const prompter = {
confirm: vi.fn(async () => true),
note: vi.fn(),
@@ -253,16 +271,18 @@ describe("github-copilot plugin", () => {
oauth: { createVpsAwareHandlers: vi.fn() },
} as never);
expect(mocks.githubCopilotLoginCommand).toHaveBeenCalledWith(
{ yes: true, profileId: "github-copilot:github", agentDir },
expect.any(Object),
);
expect(prompter.confirm).toHaveBeenCalledWith({
message: "GitHub Copilot auth already exists. Re-run login?",
initialValue: false,
});
expect(mocks.githubCopilotLoginCommand).not.toHaveBeenCalled();
expect(result.profiles[0]?.credential).toEqual({
type: "token",
provider: "github-copilot",
token: "refreshed-token",
});
} finally {
vi.unstubAllGlobals();
if (isTtyDescriptor) {
Object.defineProperty(process.stdin, "isTTY", isTtyDescriptor);
} else {

View File

@@ -256,15 +256,14 @@ export default definePluginEntry({
}
async function runGitHubCopilotAuth(ctx: ProviderAuthContext) {
const { githubCopilotLoginCommand } = await loadGithubCopilotRuntime();
let authResult = resolveExistingCopilotAuthResult(ctx.agentDir);
if (authResult) {
const existing = resolveExistingCopilotAuthResult(ctx.agentDir);
if (existing) {
const runLogin = await ctx.prompter.confirm({
message: "GitHub Copilot auth already exists. Re-run login?",
initialValue: false,
});
if (!runLogin) {
return authResult;
return existing;
}
}
@@ -276,26 +275,54 @@ export default definePluginEntry({
"GitHub Copilot",
);
if (!process.stdin.isTTY) {
const { runGitHubCopilotDeviceFlow } = await import("./login.js");
const result = await runGitHubCopilotDeviceFlow({
showCode: async ({ verificationUrl, userCode, expiresInMs }) => {
const expiresInMinutes = Math.max(1, Math.round(expiresInMs / 60_000));
await ctx.prompter.note(
[
"Open this URL in your browser and enter the code below.",
`URL: ${verificationUrl}`,
`Code: ${userCode}`,
`Code expires in ${expiresInMinutes} minutes. Never share it.`,
"",
"If a browser does not open automatically after you continue, copy the URL manually.",
].join("\n"),
"Authorize GitHub Copilot",
);
},
openUrl: async (url) => {
await ctx.openUrl(url);
},
});
if (result.status === "access_denied") {
await ctx.prompter.note("GitHub Copilot login was cancelled.", "GitHub Copilot");
return { profiles: [] };
}
if (result.status === "expired") {
await ctx.prompter.note(
"GitHub Copilot login requires an interactive TTY.",
"The GitHub device code expired. Retry login to get a new code.",
"GitHub Copilot",
);
return { profiles: [] };
}
try {
await githubCopilotLoginCommand(
{ yes: true, profileId: "github-copilot:github", agentDir: ctx.agentDir },
ctx.runtime,
);
} catch (err) {
await ctx.prompter.note(`GitHub Copilot login failed: ${String(err)}`, "GitHub Copilot");
return { profiles: [] };
}
authResult = resolveExistingCopilotAuthResult(ctx.agentDir);
return authResult ?? { profiles: [] };
return {
profiles: [
{
profileId: DEFAULT_COPILOT_PROFILE_ID,
credential: {
type: "token" as const,
provider: PROVIDER_ID,
token: result.accessToken,
},
},
],
defaultModel: DEFAULT_COPILOT_MODEL,
};
}
api.registerMemoryEmbeddingProvider(githubCopilotMemoryEmbeddingProviderAdapter);

View File

@@ -11,6 +11,7 @@ import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
const CLIENT_ID = "Iv1.b507a08c87ecfe98";
const DEVICE_CODE_URL = "https://github.com/login/device/code";
const ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
const GITHUB_DEVICE_VERIFICATION_URL = "https://github.com/login/device";
type DeviceCodeResponse = {
device_code: string;
@@ -32,6 +33,26 @@ type DeviceTokenResponse =
error_uri?: string;
};
const GITHUB_DEVICE_ACCESS_DENIED = Symbol("github-device-access-denied");
const GITHUB_DEVICE_EXPIRED = Symbol("github-device-expired");
class GitHubDeviceFlowError extends Error {
readonly kind: symbol;
constructor(kind: symbol, message: string) {
super(message);
this.kind = kind;
this.name = "GitHubDeviceFlowError";
}
}
function isGitHubDeviceAccessDeniedError(err: unknown): boolean {
return err instanceof GitHubDeviceFlowError && err.kind === GITHUB_DEVICE_ACCESS_DENIED;
}
function isGitHubDeviceExpiredError(err: unknown): boolean {
return err instanceof GitHubDeviceFlowError && err.kind === GITHUB_DEVICE_EXPIRED;
}
function parseJsonResponse(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object") {
throw new Error("Unexpected response from GitHub");
@@ -105,15 +126,100 @@ async function pollForAccessToken(params: {
continue;
}
if (err === "expired_token") {
throw new Error("GitHub device code expired; run login again");
throw new GitHubDeviceFlowError(
GITHUB_DEVICE_EXPIRED,
"GitHub device code expired; run login again",
);
}
if (err === "access_denied") {
throw new Error("GitHub login cancelled");
throw new GitHubDeviceFlowError(GITHUB_DEVICE_ACCESS_DENIED, "GitHub login cancelled");
}
throw new Error(`GitHub device flow error: ${err}`);
}
throw new Error("GitHub device code expired; run login again");
throw new GitHubDeviceFlowError(
GITHUB_DEVICE_EXPIRED,
"GitHub device code expired; run login again",
);
}
function normalizeGitHubDeviceVerificationUrl(raw: string): string {
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new Error("GitHub device flow returned an invalid verification URL");
}
if (
parsed.protocol !== "https:" ||
parsed.hostname !== "github.com" ||
parsed.pathname !== "/login/device" ||
parsed.username ||
parsed.password
) {
throw new Error("GitHub device flow returned an unexpected verification URL");
}
return GITHUB_DEVICE_VERIFICATION_URL;
}
function normalizeGitHubDeviceUserCode(raw: string): string {
const userCode = raw.trim();
if (!userCode || userCode.length > 64) {
throw new Error("GitHub device flow returned an invalid user code");
}
return userCode;
}
export type GitHubCopilotDeviceFlowResult =
| { status: "authorized"; accessToken: string }
| { status: "access_denied" }
| { status: "expired" };
export type GitHubCopilotDeviceFlowIO = {
showCode(args: { verificationUrl: string; userCode: string; expiresInMs: number }): Promise<void>;
openUrl?: (url: string) => Promise<void>;
};
export async function runGitHubCopilotDeviceFlow(
io: GitHubCopilotDeviceFlowIO,
): Promise<GitHubCopilotDeviceFlowResult> {
const device = await requestDeviceCode({ scope: "read:user" });
const verificationUrl = normalizeGitHubDeviceVerificationUrl(device.verification_uri);
const userCode = normalizeGitHubDeviceUserCode(device.user_code);
const expiresInMs = device.expires_in * 1000;
// Anchor expiry to when GitHub issued the code, not when the UI finishes prompting.
const expiresAt = Date.now() + expiresInMs;
await io.showCode({
verificationUrl,
userCode,
expiresInMs,
});
try {
await io.openUrl?.(verificationUrl);
} catch {
// The code and URL have already been shown. Browser launch is best-effort.
}
try {
const accessToken = await pollForAccessToken({
deviceCode: device.device_code,
intervalMs: Math.max(1000, device.interval * 1000),
expiresAt,
});
return { status: "authorized", accessToken };
} catch (err) {
if (isGitHubDeviceAccessDeniedError(err)) {
return { status: "access_denied" };
}
if (isGitHubDeviceExpiredError(err)) {
return { status: "expired" };
}
throw err;
}
}
export async function githubCopilotLoginCommand(
@@ -166,8 +272,6 @@ export async function githubCopilotLoginCommand(
type: "token",
provider: "github-copilot",
token: accessToken,
// GitHub device flow token doesn't reliably include expiry here.
// Leave expires unset; we'll exchange into Copilot token plus expiry later.
},
agentDir: opts.agentDir,
});