diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.json index d0da210a9f..0f5c99b2b7 100644 --- a/.github/plugin/marketplace.json +++ b/.github/plugin/marketplace.json @@ -2434,7 +2434,7 @@ "name": "pr-artifact-explorer", "source": "plugins/pr-artifact-explorer", "description": "Navigate pull requests and workflow runs (including scheduled and manual runs without a PR) and securely explore GitHub Actions artifacts, including test results, static sites, terminal recordings, and source files.", - "version": "1.0.0" + "version": "1.0.1" }, { "name": "pr-review", diff --git a/extensions/pr-artifact-explorer/README.md b/extensions/pr-artifact-explorer/README.md index cb5b39b8ff..fe420a189a 100644 --- a/extensions/pr-artifact-explorer/README.md +++ b/extensions/pr-artifact-explorer/README.md @@ -47,6 +47,10 @@ Playwright is loaded lazily from the extension's own `playwright-core` dependenc Artifact Explorer inherits eligible GitHub accounts from the Copilot app, GitHub CLI, or process environment. Tokens remain inside the extension process: the canvas receives only sanitized account metadata, while authenticated GitHub API requests are made by the local extension server. +Standalone sidebar canvases may not inherit session account tokens. When `APPDATA` is missing on Windows, the GitHub CLI subprocess tries an existing `USERPROFILE\.config\gh` directory first; if it is missing or none of its saved GitHub.com accounts authenticate (for example, a revoked or expired token), it asks Windows for the current user's Roaming folder, including redirected locations. A home-store credential still counts when it is also supplied by Copilot or the environment; a subsequent repository-check error does not trigger Roaming fallback. It uses that folder only when the Windows profile matches `USERPROFILE`. On macOS and Linux, a missing or empty `HOME` is restored for the subprocess when an absolute home is available, falling back to the OS account lookup if the environment-based lookup fails. Existing `GH_CONFIG_DIR`, `XDG_CONFIG_HOME`, and `APPDATA` settings are preserved and disable that fallback. When `GH_HOST` targets a host other than `github.com`, `GH_TOKEN` and `GITHUB_TOKEN` are not used for GitHub.com. These variables do not identify their host, so without `GH_HOST` they are assumed to be for GitHub.com. If a location cannot be recovered safely or Windows settings conflict, the canvas reports the problem instead of guessing an account store. No sign-in or GitHub CLI account switch is performed. + +Standalone canvases without conversation credentials need a saved GitHub CLI account. If necessary, sign in with `gh auth login --hostname github.com` or open the canvas from a session. Use the GitHub accounts button to see diagnostics and rescan after signing in. The GitHub CLI must be available to the extension, and saved GitHub CLI accounts for other hosts are not used for GitHub.com requests. + Artifact ZIPs and preferences are stored under: ```text @@ -72,6 +76,8 @@ You can also copy the folder to one of the supported extension locations: Reload extensions, then ask Copilot to open the `pr-artifact-explorer` canvas. You can optionally provide a repository (`owner/name`), pull request number, workflow run ID, or a GitHub pull request, run, or Actions URL when opening it. +User-scoped copies and installed plugin copies are independent. Updating the plugin does not update a folder copied into `~/.copilot/extensions/`; update that copy too if it is the provider selected by your standalone canvas. + ## Agent actions - `open_pull_request { repository, pullNumber }` - navigate an open canvas to a pull request. diff --git a/extensions/pr-artifact-explorer/accounts.mjs b/extensions/pr-artifact-explorer/accounts.mjs index 8542f5207e..61fcff0bbf 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -1,6 +1,9 @@ import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; -import { promisify } from "node:util"; +import { stat } from "node:fs/promises"; +import { promisify, stripVTControlCharacters } from "node:util"; +import { homedir, userInfo } from "node:os"; +import { isAbsolute, join, normalize } from "node:path"; import { GITHUB_API, USER_AGENT } from "./constants.mjs"; const execFileAsync = promisify(execFile); @@ -15,11 +18,136 @@ const SOURCE_LABEL = Object.freeze({ const cachedResolutions = new Map(); -function cleanGhEnvironment() { +function windowsEnvironmentValue(env, key) { + return Object.entries(env).find(([name, value]) => name.toUpperCase() === key && value)?.[1]; +} + +function setWindowsEnvironmentValue(env, key, value) { + for (const name of Object.keys(env)) { + if (name.toUpperCase() === key) delete env[name]; + } + env[key] = value; +} + +function normalizeWindowsEnvironmentValue(env, key) { + const names = Object.keys(env).filter((name) => name.toUpperCase() === key); + const values = [...new Set(names.map((name) => env[name]).filter(Boolean))]; + if (values.length > 1) return false; + if (names.length > 1) { + for (const name of names) delete env[name]; + if (values.length) env[key] = values[0]; + } + return true; +} + +function safeHome() { + for (const lookup of [homedir, () => userInfo().homedir]) { + try { + const home = lookup(); + if (home && isAbsolute(home)) return home; + } catch { + // The OS account lookup can still work when the environment-based lookup fails. + } + } + return null; +} + +async function cleanGhEnvironment() { const env = { ...process.env }; - delete env.GH_TOKEN; - delete env.GITHUB_TOKEN; - return env; + const windows = process.platform === "win32"; + for (const name of Object.keys(env)) { + const key = windows ? name.toUpperCase() : name; + if (key === "GH_TOKEN" || key === "GITHUB_TOKEN" || key.startsWith("COPILOT_GH_ACCOUNT_")) { + delete env[name]; + } + } + + if (!windows) { + if (!env.HOME) { + const home = safeHome(); + if (home) env.HOME = home; + else if (!env.GH_CONFIG_DIR && !env.XDG_CONFIG_HOME) { + return { + env: null, + diagnostic: "GitHub CLI was not run because no absolute home directory was available. Set HOME or GH_CONFIG_DIR.", + }; + } + } + return { env, diagnostic: null }; + } + + const configKey = ["GH_CONFIG_DIR", "XDG_CONFIG_HOME", "APPDATA"].find((key) => + windowsEnvironmentValue(env, key)); + if (configKey) { + if (!normalizeWindowsEnvironmentValue(env, configKey)) { + return { + env: null, + diagnostic: `GitHub CLI was not run because conflicting ${configKey} settings were provided.`, + }; + } + return { env, diagnostic: null }; + } + + if (!normalizeWindowsEnvironmentValue(env, "USERPROFILE")) { + return { + env: null, + diagnostic: "GitHub CLI was not run because conflicting USERPROFILE settings were provided.", + }; + } + const configuredHome = windowsEnvironmentValue(env, "USERPROFILE"); + const home = configuredHome || safeHome(); + if (!home || !isAbsolute(home)) { + return { + env: null, + diagnostic: "GitHub CLI was not run because the Windows user profile could not be determined. Set APPDATA or GH_CONFIG_DIR.", + }; + } + if (!configuredHome) setWindowsEnvironmentValue(env, "USERPROFILE", home); + + // Prefer gh's native home configuration; the roaming store is consulted only + // if the home store yields no usable github.com account. + try { + await stat(join(home, ".config", "gh")); + return { env, diagnostic: null, fallback: () => windowsRoamingEnvironment({ ...env }, home) }; + } catch (error) { + if (error?.code !== "ENOENT") return { env, diagnostic: null }; + } + return windowsRoamingEnvironment(env, home); +} + +async function windowsRoamingEnvironment(env, home) { + try { + const systemRoot = windowsEnvironmentValue(env, "SYSTEMROOT"); + const powershell = systemRoot && isAbsolute(systemRoot) + ? join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") + : "powershell.exe"; + const { stdout } = await execFileAsync( + powershell, + [ + "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; " + + "@{appData=[Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData); " + + "profile=[Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)} | ConvertTo-Json -Compress", + ], + { timeout: 5_000, env, windowsHide: true }, + ); + const folders = JSON.parse(String(stdout ?? "").replace(/^\uFEFF/, "").trim()); + const appData = folders?.appData; + const profile = folders?.profile; + if (typeof appData === "string" && isAbsolute(appData) && + typeof profile === "string" && isAbsolute(profile)) { + const pathKey = (path) => normalize(path).replace(/[\\/]+$/, "").toLowerCase(); + if (pathKey(home) !== pathKey(profile)) return { env, diagnostic: null }; + setWindowsEnvironmentValue(env, "APPDATA", appData); + return { env, diagnostic: null }; + } + } catch { + // An unavailable known-folder lookup must not silently select a different account store. + } + return { + env: null, + diagnostic: "The Windows roaming folder could not be determined. Set APPDATA or GH_CONFIG_DIR to the GitHub CLI configuration location.", + }; } function tokenHash(token) { @@ -30,28 +158,40 @@ function decodeCopilotLabel(variableName) { let encoded = variableName.replace(/^COPILOT_GH_ACCOUNT_/, ""); encoded = encoded.replace(/_([0-9A-Fa-f]{2})_/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))); - return encoded.replace(/^github\.com_/, "") || null; + return /^github\.com_(.+)$/i.exec(encoded)?.[1] ?? null; +} + +function ghFailure(error, action) { + if (error?.code === "ENOENT") return "GitHub CLI was not found on PATH."; + if (error?.killed || error?.signal === "SIGTERM") { + return "GitHub CLI timed out while checking saved accounts."; + } + if (action === "token") { + return "GitHub CLI could not retrieve a saved credential. Check gh auth status --hostname github.com and your credential store."; + } + return "GitHub CLI could not find or read saved GitHub.com accounts. Check gh auth status --hostname github.com and its configuration."; } -async function listGhAccounts() { +async function listGhAccounts(env) { let output = ""; + let diagnostic = null; try { - const result = await execFileAsync("gh", ["auth", "status"], { + const result = await execFileAsync("gh", ["auth", "status", "--hostname", "github.com"], { timeout: 8_000, - env: cleanGhEnvironment(), + env, windowsHide: true, }); output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`; } catch (error) { - if (error?.code === "ENOENT") return []; + diagnostic = ghFailure(error, "status"); output = `${error?.stdout ?? ""}\n${error?.stderr ?? ""}`; - if (!output.trim()) return []; } const accounts = []; const seen = new Set(); const pattern = /Logged in to (\S+) account (\S+)/g; let match; + output = stripVTControlCharacters(output); while ((match = pattern.exec(output)) !== null) { const key = `${match[1].toLowerCase()}/${match[2].toLowerCase()}`; if (!seen.has(key)) { @@ -59,24 +199,27 @@ async function listGhAccounts() { accounts.push({ host: match[1], login: match[2] }); } } - return accounts; + return { accounts, diagnostic }; } -async function readGhToken(host, login) { +async function readGhToken(host, login, env) { try { const { stdout } = await execFileAsync( "gh", ["auth", "token", "--hostname", host, "--user", login], { timeout: 8_000, - env: cleanGhEnvironment(), + env, windowsHide: true, }, ); - return stdout.trim() || null; + const token = stdout.trim(); + return { + token: token || null, + diagnostic: token ? null : ghFailure(null, "token"), + }; } catch (error) { - if (error?.code === "ENOENT") return null; - return null; + return { token: null, diagnostic: ghFailure(error, "token") }; } } @@ -93,17 +236,57 @@ async function detectCandidates() { for (const [name, value] of Object.entries(process.env)) { if (name.startsWith("COPILOT_GH_ACCOUNT_") && value) { - add("copilot", value, decodeCopilotLabel(name)); + const login = decodeCopilotLabel(name); + if (login) add("copilot", value, login); } } - add("env", process.env.GH_TOKEN, null); - add("env", process.env.GITHUB_TOKEN, null); - - for (const account of await listGhAccounts()) { - if (account.host.toLowerCase() !== "github.com") continue; - add("gh", await readGhToken(account.host, account.login), account.login); + // gh also applies these tokens to *.ghe.com; an explicit non-github.com GH_HOST + // signals they may belong to another host, so never send them to api.github.com. + const ghHost = String(process.env.GH_HOST ?? "").trim().replace(/\.$/, "").toLowerCase(); + const ambientTokensAllowed = !ghHost || ghHost === "github.com"; + let hostDiagnostic = null; + if (ambientTokensAllowed) { + add("env", process.env.GH_TOKEN, null); + add("env", process.env.GITHUB_TOKEN, null); + } else if (process.env.GH_TOKEN || process.env.GITHUB_TOKEN) { + hostDiagnostic = "GH_TOKEN and GITHUB_TOKEN were not used because GH_HOST targets a host other than github.com."; } - return candidates; + + const withHostDiagnostic = (message) => + [message, hostDiagnostic].filter(Boolean).join(" ") || null; + const primaryStoreTokens = new Set(); + const readStore = async (env, primary = false) => { + const cli = await listGhAccounts(env); + let diagnostic = cli.diagnostic; + for (const account of cli.accounts) { + if (account.host.toLowerCase() !== "github.com") continue; + const result = await readGhToken(account.host, account.login, env); + if (primary && result.token) primaryStoreTokens.add(result.token); + add("gh", result.token, account.login); + if (result.diagnostic) diagnostic = result.diagnostic; + } + return diagnostic; + }; + + const store = await cleanGhEnvironment(); + if (!store.env) return { candidates, diagnostic: withHostDiagnostic(store.diagnostic) }; + const diagnostic = await readStore(store.env, true); + const cliUnavailable = [ghFailure({ code: "ENOENT" }), ghFailure({ killed: true })].includes(diagnostic); + // The caller decides after probing, because a revoked token is still retrievable. + const readFallbackStore = store.fallback && !cliUnavailable + ? async () => { + const roaming = await store.fallback(); + // Only retry when the known folder matched this profile and set a distinct store. + if (!roaming.env || !windowsEnvironmentValue(roaming.env, "APPDATA")) return null; + const before = candidates.length; + const secondaryDiagnostic = await readStore(roaming.env); + return { + candidates: candidates.slice(before), + diagnostic: withHostDiagnostic(secondaryDiagnostic), + }; + } + : null; + return { candidates, diagnostic: withHostDiagnostic(diagnostic), readFallbackStore, primaryStoreTokens }; } async function apiProbe(token, path) { @@ -125,6 +308,7 @@ async function probeCandidate(candidate, repository) { source: candidate.source, hash: candidate.hash, hintedLogin: candidate.hintedLogin, + authenticated: false, }; try { @@ -137,11 +321,14 @@ async function probeCandidate(candidate, repository) { avatarUrl: null, status: "failed", repositoryAccess: false, - reason: viewer.payload?.message ?? `Authentication failed (${viewer.response.status}).`, + reason: typeof viewer.payload?.message === "string" + ? viewer.payload.message.replaceAll(candidate.token, "[redacted]") + : `Authentication failed (${viewer.response.status}).`, scopes: [], }; } + safe.authenticated = true; let repositoryAccess = null; let repositoryReason = null; if (repository) { @@ -151,7 +338,9 @@ async function probeCandidate(candidate, repository) { ); repositoryAccess = access.response.ok; if (!repositoryAccess) { - repositoryReason = access.payload?.message ?? `Repository check failed (${access.response.status}).`; + repositoryReason = typeof access.payload?.message === "string" + ? access.payload.message.replaceAll(candidate.token, "[redacted]") + : `Repository check failed (${access.response.status}).`; } } @@ -182,7 +371,9 @@ async function probeCandidate(candidate, repository) { company: null, status: "failed", repositoryAccess: false, - reason: error instanceof Error ? error.message : String(error), + reason: error?.name === "TimeoutError" || error?.name === "AbortError" + ? "GitHub account validation timed out." + : "GitHub account validation failed. Check your connection.", scopes: [], }; } @@ -210,9 +401,26 @@ export function invalidateAccounts() { } async function resolveAccountsUncached(preferredId, repository) { + const detection = await detectCandidates(); const probes = await Promise.all( - (await detectCandidates()).map((candidate) => probeCandidate(candidate, repository)), + detection.candidates.map((candidate) => probeCandidate(candidate, repository)), ); + let detectionDiagnostic = detection.diagnostic; + // Deduplication can attribute a primary-store token to Copilot or the environment. + const storeAuthenticated = detection.readFallbackStore && probes.some((probe) => + detection.primaryStoreTokens.has(probe.token) && probe.authenticated); + if (detection.readFallbackStore && !storeAuthenticated) { + const fallback = await detection.readFallbackStore(); + if (fallback) { + const fallbackProbes = await Promise.all( + fallback.candidates.map((candidate) => probeCandidate(candidate, repository)), + ); + probes.push(...fallbackProbes); + if (fallbackProbes.some((probe) => probe.status !== "failed")) { + detectionDiagnostic = fallback.diagnostic; + } + } + } const groups = new Map(); for (const probe of probes) { const keyForLogin = String(probe.login).toLowerCase(); @@ -270,6 +478,11 @@ async function resolveAccountsUncached(preferredId, repository) { active: active ? publicAccount(active) : null, activeToken: active?.token ?? null, accounts: accounts.map(publicAccount), + diagnostic: active ? null : [ + "No usable GitHub.com account was detected.", + detectionDiagnostic, + "For standalone use, sign in with gh auth login --hostname github.com or open the canvas from a session.", + ].filter(Boolean).join(" "), }; return value; } diff --git a/extensions/pr-artifact-explorer/accounts.test.mjs b/extensions/pr-artifact-explorer/accounts.test.mjs new file mode 100644 index 0000000000..325b521aea --- /dev/null +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -0,0 +1,719 @@ +import assert from "node:assert/strict"; +import childProcess from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import os, { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, test } from "node:test"; + +const sharedHome = mkdtempSync(join(tmpdir(), "pae-accounts-test-")); +const originalCopilotHome = process.env.COPILOT_HOME; +process.env.COPILOT_HOME = sharedHome; + +let scenario; +const originalExecFile = childProcess.execFile; +childProcess.execFile = (command, args, options, callback) => { + assert.equal(options.windowsHide, true); + if (command === "powershell.exe") { + scenario.folderCalls.push({ args, env: options.env }); + if (scenario.folderError) return callback(scenario.folderError); + return callback(null, { + stdout: JSON.stringify({ appData: scenario.knownFolder, profile: scenario.knownProfile }), + stderr: "", + }); + } + + assert.equal(command, "gh"); + for (const name of Object.keys(options.env)) { + const key = process.platform === "win32" ? name.toUpperCase() : name; + assert.ok(!["GH_TOKEN", "GITHUB_TOKEN"].includes(key)); + assert.ok(!key.startsWith("COPILOT_GH_ACCOUNT_")); + } + scenario.calls.push({ args, env: options.env }); + const storeAppData = Object.entries(options.env).find(([name]) => + name.toUpperCase() === "APPDATA")?.[1]; + const storeToken = scenario.stores?.[storeAppData ?? "home"]; + if (args[1] === "status") { + assert.deepEqual(args, ["auth", "status", "--hostname", "github.com"]); + if (scenario.statusError) return callback(scenario.statusError); + const config = Object.entries(options.env).find(([name]) => + name.toUpperCase() === scenario.configVariable)?.[1]; + if (scenario.stores ? !storeToken : config !== scenario.configPath) { + return callback(Object.assign(new Error("No saved accounts"), { + stderr: "You are not logged into any GitHub hosts.", + })); + } + return callback(null, { stdout: scenario.statusOutput, stderr: "" }); + } + assert.deepEqual(args, ["auth", "token", "--hostname", "github.com", "--user", "octocat"]); + if (scenario.tokenError) return callback(scenario.tokenError); + return callback(null, { stdout: `${storeToken ?? "cli-token"}\n`, stderr: "" }); +}; +syncBuiltinESMExports(); +const { resolveAccounts, invalidateAccounts } = await import("./accounts.mjs"); +childProcess.execFile = originalExecFile; +syncBuiltinESMExports(); +if (originalCopilotHome === undefined) delete process.env.COPILOT_HOME; +else process.env.COPILOT_HOME = originalCopilotHome; +after(() => rmSync(sharedHome, { recursive: true, force: true })); + +function setup(t, { + platform = "win32", + env = {}, + configVariable = "APPDATA", + configPath, + knownFolder, +} = {}) { + const originalEnv = process.env; + const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); + const originalFetch = globalThis.fetch; + const home = mkdtempSync(join(tmpdir(), "pae-account-profile-")); + process.env = { ...(platform === "win32" ? { USERPROFILE: home } : {}), ...env }; + Object.defineProperty(process, "platform", { value: platform }); + scenario = { + calls: [], + folderCalls: [], + fetchCalls: [], + home, + configVariable, + configPath: configPath ?? join(home, "AppData", "Roaming"), + knownFolder: knownFolder ?? join(home, "AppData", "Roaming"), + knownProfile: home, + statusOutput: "Logged in to github.com account octocat (keyring)\n" + + "Logged in to enterprise.example account enterprise-user (keyring)", + }; + globalThis.fetch = async (url, options) => { + const requestUrl = new URL(url); + const token = options.headers.Authorization; + scenario.fetchCalls.push({ url: requestUrl, token }); + assert.equal(requestUrl.origin, "https://api.github.com"); + if (scenario.fetchError) throw scenario.fetchError; + if (requestUrl.pathname === "/user") { + if (token === "Bearer revoked-token") { + return Response.json({ message: "Bad credentials" }, { status: 401 }); + } + const logins = { + "Bearer cli-token": "octocat", + "Bearer session-token": "session-user", + "Bearer ambient-token": "ambient-user", + "Bearer enterprise-token": "enterprise-user", + "Bearer lookalike-token": "lookalike-user", + }; + return Response.json({ login: logins[token] }); + } + assert.equal(requestUrl.pathname, "/repos/example/repository"); + if (scenario.deniedRepositoryTokens?.includes(token)) { + return Response.json({ message: "Repository access denied" }, { status: 403 }); + } + if (scenario.failedRepositoryTokens?.includes(token)) { + throw new Error("Repository request failed"); + } + return Response.json({ full_name: "example/repository" }); + }; + invalidateAccounts(); + t.after(() => { + process.env = originalEnv; + Object.defineProperty(process, "platform", platformDescriptor); + globalThis.fetch = originalFetch; + invalidateAccounts(); + rmSync(home, { recursive: true, force: true }); + }); + return scenario; +} + +function mockHomeLookups(t, homeLookup, userLookup) { + const originalHomedir = os.homedir; + const originalUserInfo = os.userInfo; + os.homedir = homeLookup; + os.userInfo = userLookup; + syncBuiltinESMExports(); + t.after(() => { + os.homedir = originalHomedir; + os.userInfo = originalUserInfo; + syncBuiltinESMExports(); + }); +} + +test("standalone Windows discovery finds saved CLI accounts without inherited tokens or AppData", async (t) => { + const state = setup(t); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(auth.activeToken, "cli-token"); + assert.deepEqual(auth.active.sourceKinds, ["gh"]); + assert.equal(state.calls.length, 2, "enumeration and token reads use the same configuration"); + assert.equal(state.calls[0].env, state.calls[1].env); + assert.equal(process.env.APPDATA, undefined, "the parent environment is not modified"); + assert.equal(auth.accounts.length, 1, "enterprise CLI accounts are not sent to github.com"); + assert.ok(!JSON.stringify({ active: auth.active, accounts: auth.accounts }).includes("cli-token")); +}); + +test("session discovery retains its preferred account and AppData while excluding ambient CLI overrides", async (t) => { + const appData = join(homedir(), "redirected-roaming"); + const state = setup(t, { + env: { + AppData: appData, + COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user: "session-token", + GH_TOKEN: "ambient-token", + GitHub_Token: "ambient-token", + }, + configPath: appData, + }); + const auth = await resolveAccounts({ + preferredId: "acct:session-user", + repository: "example/repository", + }); + assert.equal(auth.active.login, "session-user"); + assert.equal(auth.activeToken, "session-token"); + assert.deepEqual(auth.active.sourceKinds, ["copilot"]); + assert.equal(state.calls.length, 2); + assert.equal(state.calls[0].env.AppData, appData); + assert.equal(state.calls[0].env.APPDATA, undefined); + assert.equal(state.folderCalls.length, 0); +}); + +test("standalone Windows discovery replaces an empty AppData without duplicate keys", async (t) => { + const state = setup(t, { env: { AppData: "" } }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.ok(state.calls.every(({ env }) => + Object.keys(env).filter((name) => name.toUpperCase() === "APPDATA").length === 1)); +}); + +test("Windows discovery preserves a nonempty AppData when mixed-case duplicates exist", async (t) => { + const appData = join(tmpdir(), "explicit-roaming"); + const state = setup(t, { + env: { AppData: "", APPDATA: appData }, + configPath: appData, + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(state.folderCalls.length, 0); + assert.ok(state.calls.every(({ env }) => + Object.keys(env).filter((name) => name.toUpperCase() === "APPDATA").length === 1)); +}); + +test("Windows discovery does not choose between conflicting explicit configuration values", async (t) => { + const state = setup(t, { + env: { APPDATA: join(tmpdir(), "first-roaming"), AppData: join(tmpdir(), "second-roaming") }, + }); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /conflicting.*APPDATA/i); + assert.equal(state.calls.length, 0); + assert.equal(state.folderCalls.length, 0); +}); + +test("Windows discovery honors a higher-priority config override despite conflicting AppData values", async (t) => { + const configPath = join(tmpdir(), "explicit-gh"); + const state = setup(t, { + env: { + GH_CONFIG_DIR: configPath, + APPDATA: join(tmpdir(), "first-roaming"), + AppData: join(tmpdir(), "second-roaming"), + }, + configVariable: "GH_CONFIG_DIR", + configPath, + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.ok(state.calls.every(({ env }) => env.GH_CONFIG_DIR === configPath)); + assert.equal(state.folderCalls.length, 0); +}); + +test("Windows discovery uses the known roaming folder when AppData is redirected", async (t) => { + const redirected = join(tmpdir(), "redirected-roaming"); + const state = setup(t, { knownFolder: redirected, configPath: redirected }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(state.folderCalls.length, 1); + assert.ok(state.calls.every(({ env }) => env.APPDATA === redirected)); +}); + +test("Windows discovery does not switch away from an explicitly different user profile", async (t) => { + const state = setup(t); + state.knownProfile = join(state.home, "different-windows-profile"); + state.configVariable = "USERPROFILE"; + state.configPath = state.home; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.ok(auth.active, auth.diagnostic); + assert.equal(auth.active.login, "octocat"); + assert.ok(state.calls.every(({ env }) => env.USERPROFILE === state.home && env.APPDATA === undefined)); +}); + +test("Windows discovery does not choose between conflicting user profiles", async (t) => { + const state = setup(t, { env: { UserProfile: join(tmpdir(), "another-profile") } }); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /conflicting.*USERPROFILE/i); + assert.equal(state.calls.length, 0); + assert.equal(state.folderCalls.length, 0); +}); + +test("Windows discovery does not guess the roaming path if the known-folder lookup fails", async (t) => { + const state = setup(t); + state.folderError = Object.assign(new Error("PowerShell unavailable"), { code: "ENOENT" }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /APPDATA|GH_CONFIG_DIR/); + assert.equal(state.calls.length, 0); +}); + +test("Windows discovery preserves an existing native home configuration", async (t) => { + const state = setup(t); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + state.configVariable = "USERPROFILE"; + state.configPath = state.home; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(state.folderCalls.length, 0, "a working home store never consults the roaming store"); + assert.ok(state.calls.every(({ env }) => env.APPDATA === undefined)); +}); + +test("Windows discovery falls back to the roaming store when the home store has no accounts", async (t) => { + const state = setup(t); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.ok(auth.active, auth.diagnostic); + assert.equal(auth.active.login, "octocat"); + assert.equal(auth.diagnostic, null, "the empty home store's failure is not reported after recovery"); + assert.equal(state.folderCalls.length, 1); + assert.equal(state.calls[0].env.APPDATA, undefined, "the native home store is tried first"); + assert.ok(state.calls.slice(1).every(({ env }) => env.APPDATA === roaming)); + assert.equal(process.env.APPDATA, undefined); +}); + +test("Windows roaming fallback recovers when the home store token is revoked", async (t) => { + const state = setup(t); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + state.stores = { home: "revoked-token", [roaming]: "cli-token" }; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.ok(auth.active, auth.diagnostic); + assert.equal(auth.active.login, "octocat"); + assert.equal(auth.activeToken, "cli-token"); + assert.equal(auth.diagnostic, null); + assert.equal(state.folderCalls.length, 1); + assert.deepEqual(auth.accounts.map(({ login }) => login), ["octocat"]); +}); + +test("Windows roaming fallback is not used when the home store account authenticates", async (t) => { + const state = setup(t); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + state.stores = { home: "cli-token", [roaming]: "revoked-token" }; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.activeToken, "cli-token"); + assert.equal(state.folderCalls.length, 0); + assert.ok(state.fetchCalls.every(({ token }) => token !== "Bearer revoked-token")); +}); + +for (const [source, env] of [ + ["GH_TOKEN", { GH_TOKEN: "cli-token" }], + ["GITHUB_TOKEN", { GITHUB_TOKEN: "cli-token" }], + ["Copilot", { COPILOT_GH_ACCOUNT_github_2E_com_octocat: "cli-token" }], +]) { + test(`Windows roaming fallback skips an authenticated home-store token shared with ${source}`, async (t) => { + const state = setup(t, { env }); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + state.stores = { home: "cli-token", [roaming]: "ambient-token" }; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active?.login, "octocat"); + assert.equal(auth.activeToken, "cli-token"); + assert.deepEqual(auth.accounts.map(({ login }) => login), ["octocat"]); + assert.equal(state.folderCalls.length, 0); + assert.equal(state.fetchCalls.filter(({ url }) => url.pathname === "/user").length, 1); + assert.ok(!JSON.stringify({ active: auth.active, accounts: auth.accounts }).includes("cli-token")); + }); +} + +test("Windows roaming fallback skips a shared home-store token with limited repository access", async (t) => { + const state = setup(t, { env: { GH_TOKEN: "cli-token" } }); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + state.stores = { home: "cli-token", [roaming]: "ambient-token" }; + state.deniedRepositoryTokens = ["Bearer cli-token"]; + const auth = await resolveAccounts({ + preferredId: "acct:octocat", + repository: "example/repository", + }); + assert.equal(auth.active?.login, "octocat"); + assert.equal(auth.active.status, "limited"); + assert.equal(state.folderCalls.length, 0); +}); + +for (const [source, env] of [ + ["CLI only", {}], + ["environment", { GH_TOKEN: "cli-token" }], +]) { + test(`Windows roaming fallback skips an authenticated ${source} home-store token when the repository request fails`, async (t) => { + const state = setup(t, { env }); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + state.stores = { home: "cli-token", [roaming]: "ambient-token" }; + state.failedRepositoryTokens = ["Bearer cli-token"]; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active, null); + assert.equal(state.folderCalls.length, 0); + assert.ok(state.fetchCalls.every(({ token }) => token !== "Bearer ambient-token")); + assert.match(auth.accounts[0].reason, /validation failed/i); + assert.ok(!JSON.stringify(auth.accounts).includes("cli-token")); + }); +} + +test("Windows roaming fallback still recovers when a shared home-store token is revoked", async (t) => { + const state = setup(t, { env: { GH_TOKEN: "revoked-token" } }); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const roaming = join(state.home, "AppData", "Roaming"); + state.stores = { home: "revoked-token", [roaming]: "cli-token" }; + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active?.login, "octocat"); + assert.equal(auth.activeToken, "cli-token"); + assert.equal(state.folderCalls.length, 1); +}); + +test("Windows roaming fallback never switches to a different user profile", async (t) => { + const state = setup(t); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + state.knownProfile = join(state.home, "different-windows-profile"); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active, null); + assert.equal(state.folderCalls.length, 1); + assert.equal(state.calls.length, 1, "the home store is not re-read and no other store is used"); + assert.ok(auth.diagnostic); +}); + +test("Windows roaming fallback is skipped when the CLI is unavailable", async (t) => { + const state = setup(t); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + state.statusError = Object.assign(new Error("missing"), { code: "ENOENT" }); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /not found/); + assert.equal(state.folderCalls.length, 0); +}); + +test("explicit APPDATA disables the roaming fallback", async (t) => { + const appData = join(tmpdir(), "explicit-empty-roaming"); + const state = setup(t, { env: { APPDATA: appData }, configPath: join(tmpdir(), "elsewhere") }); + mkdirSync(join(state.home, ".config", "gh"), { recursive: true }); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.equal(state.folderCalls.length, 0); + assert.ok(state.calls.every(({ env }) => env.APPDATA === appData)); +}); + +for (const variable of ["GH_CONFIG_DIR", "XDG_CONFIG_HOME"]) { + test(`standalone discovery preserves explicit ${variable}`, async (t) => { + const configPath = join(homedir(), "custom-gh"); + const state = setup(t, { + env: { [variable]: configPath }, + configVariable: variable, + configPath, + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.ok(state.calls.every(({ env }) => env.APPDATA === undefined)); + assert.equal(state.folderCalls.length, 0); + }); +} + +test("native Linux discovery recovers an empty HOME from the OS account", { + skip: process.platform !== "linux", +}, async (t) => { + const home = os.userInfo().homedir; + const nativeEnv = process.env; + const originalHome = nativeEnv.HOME; + nativeEnv.HOME = ""; + t.after(() => { + if (originalHome === undefined) delete nativeEnv.HOME; + else nativeEnv.HOME = originalHome; + }); + const state = setup(t, { + platform: "linux", env: { HOME: "" }, configVariable: "HOME", configPath: home, + }); + assert.equal(os.homedir(), "", "Linux preserves an explicitly empty HOME"); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active?.login, "octocat", auth.diagnostic); + assert.equal(process.env.HOME, ""); + assert.ok(state.calls.every(({ env }) => env.HOME === home)); +}); + +for (const platform of ["linux", "darwin"]) { + for (const unavailableHome of ["empty", "relative", "throwing"]) { + test(`${platform} discovery recovers ${unavailableHome} home lookup from the OS account`, async (t) => { + const state = setup(t, { platform, env: { HOME: "" }, configVariable: "HOME" }); + state.configPath = state.home; + mockHomeLookups(t, () => { + if (unavailableHome === "throwing") throw new Error("home unavailable"); + return unavailableHome === "empty" ? "" : "relative-home"; + }, () => ({ homedir: state.home })); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active?.login, "octocat", auth.diagnostic); + assert.equal(process.env.HOME, "", "the parent environment is not modified"); + assert.equal(state.calls.length, 2); + assert.ok(state.calls.every(({ env }) => env.HOME === state.home && env.APPDATA === undefined)); + }); + } + + test(`${platform} discovery restores missing HOME for the CLI only`, async (t) => { + const home = homedir(); + const state = setup(t, { platform, env: { HOME: "" }, configVariable: "HOME", configPath: home }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(process.env.HOME, ""); + assert.ok(state.calls.every(({ env }) => env.HOME === home && env.APPDATA === undefined)); + }); + + test(`${platform} discovery keeps explicit HOME and configuration overrides`, async (t) => { + const home = join(homedir(), "explicit-home"); + const configPath = join(homedir(), "explicit-gh"); + const state = setup(t, { + platform, + env: { HOME: home, GH_CONFIG_DIR: configPath }, + configVariable: "GH_CONFIG_DIR", + configPath, + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.ok(state.calls.every(({ env }) => env.HOME === home && env.GH_CONFIG_DIR === configPath)); + }); +} + +test("missing Unix HOME never falls back to a relative CLI configuration", async (t) => { + const state = setup(t, { platform: "linux", env: {} }); + mockHomeLookups(t, + () => { throw new Error("home unavailable"); }, + () => { throw new Error("OS account unavailable"); }); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /HOME|GH_CONFIG_DIR/); + assert.equal(state.calls.length, 0); +}); + +for (const home of ["", "relative-home"]) { + test(`Unix discovery rejects a nonabsolute OS account home ${JSON.stringify(home)}`, async (t) => { + const state = setup(t, { platform: "linux", env: { HOME: "" } }); + mockHomeLookups(t, () => "", () => ({ homedir: home })); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /HOME|GH_CONFIG_DIR/); + assert.equal(state.calls.length, 0); + }); +} + +test("explicit Unix CLI configuration works even when HOME cannot be recovered", async (t) => { + const configPath = join(tmpdir(), "explicit-gh"); + const state = setup(t, { + platform: "linux", + env: { GH_CONFIG_DIR: configPath }, + configVariable: "GH_CONFIG_DIR", + configPath, + }); + mockHomeLookups(t, + () => { throw new Error("home unavailable"); }, + () => { throw new Error("OS account unavailable"); }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.ok(state.calls.every(({ env }) => env.GH_CONFIG_DIR === configPath)); +}); + +test("Copilot credentials are never probed against a different host", async (t) => { + const state = setup(t, { + env: { + AppData: join(homedir(), "existing-roaming"), + COPILOT_GH_ACCOUNT_GitHub_2E_COM_session_2D_user: "session-token", + COPILOT_GH_ACCOUNT_msft_2E_ghe_2E_com_enterprise: "enterprise-token", + COPILOT_GH_ACCOUNT_github_2E_com_2E_evil_lookalike: "lookalike-token", + }, + configPath: join(homedir(), "existing-roaming"), + }); + const auth = await resolveAccounts({ + preferredId: "acct:session-user", + repository: "example/repository", + }); + assert.equal(auth.active.login, "session-user"); + assert.equal(auth.activeToken, "session-token"); + assert.deepEqual(auth.accounts.map((account) => account.login).sort(), ["octocat", "session-user"]); + assert.ok(state.fetchCalls.some(({ token }) => token === "Bearer session-token")); + assert.ok(state.fetchCalls.every(({ token }) => + token !== "Bearer enterprise-token" && token !== "Bearer lookalike-token")); + assert.ok(!JSON.stringify({ active: auth.active, accounts: auth.accounts }).includes("session-token")); +}); + +test("ambient tokens are probed only when GH_HOST is unset or github.com", async (t) => { + for (const ghHost of [undefined, "", "github.com", " GitHub.COM ", "github.com."]) { + await t.test(`GH_HOST=${JSON.stringify(ghHost)}`, async (st) => { + const state = setup(st, { + platform: "linux", + env: { HOME: homedir(), GH_TOKEN: "ambient-token", ...(ghHost === undefined ? {} : { GH_HOST: ghHost }) }, + }); + state.statusError = Object.assign(new Error("not found"), { code: "ENOENT" }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "ambient-user"); + assert.deepEqual(auth.active.sourceKinds, ["env"]); + }); + } +}); + +test("ambient tokens for another GH_HOST are never sent to github.com", async (t) => { + for (const ghHost of ["tenant.ghe.com", "ghes.example.com", "github.com.evil.example", "github.com:8443"]) { + await t.test(`GH_HOST=${ghHost}`, async (st) => { + const state = setup(st, { + platform: "linux", + env: { HOME: homedir(), GH_HOST: ghHost, GH_TOKEN: "ambient-token", GITHUB_TOKEN: "enterprise-token" }, + configVariable: "HOME", + configPath: homedir(), + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat", "saved github.com CLI accounts still work"); + assert.deepEqual(auth.accounts.map((account) => account.login), ["octocat"]); + assert.ok(state.fetchCalls.every(({ token }) => + token !== "Bearer ambient-token" && token !== "Bearer enterprise-token")); + }); + } +}); + +test("a skipped GH_HOST token explains why no account was found", async (t) => { + const state = setup(t, { + platform: "linux", + env: { HOME: homedir(), GH_HOST: "tenant.ghe.com", GH_TOKEN: "ambient-token" }, + }); + state.statusError = Object.assign(new Error("No saved accounts"), { + stderr: "You are not logged into any GitHub hosts.", + }); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /GH_HOST/); + assert.ok(!auth.diagnostic.includes("ambient-token")); + assert.equal(state.fetchCalls.length, 0); +}); + +test("colored partial CLI status output still discovers valid accounts", async (t) => { + const state = setup(t, { platform: "linux", env: { HOME: homedir() }, configVariable: "HOME", configPath: homedir() }); + state.statusError = Object.assign(new Error("one account failed"), { + stdout: "\u001b[32mLogged in to \u001b[0mgithub.com account \u001b[1moctocat\u001b[0m (keyring)\n", + stderr: "Another account failed.", + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(state.calls.length, 2); +}); + +test("a missing CLI does not prevent a session-backed account from working", async (t) => { + const state = setup(t, { + platform: "linux", + env: { HOME: homedir(), COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user: "session-token" }, + }); + state.statusError = Object.assign(new Error("not found"), { code: "ENOENT" }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "session-user"); + assert.equal(auth.activeToken, "session-token"); + assert.equal(auth.diagnostic, null); +}); + +test("CLI failures produce sanitized, actionable diagnostics", async (t) => { + const state = setup(t, { platform: "linux", env: { HOME: homedir() }, configVariable: "HOME", configPath: homedir() }); + state.statusError = Object.assign(new Error("sensitive-secret"), { + killed: true, + stderr: "sensitive-secret", + }); + let auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /timed out/i); + assert.ok(!JSON.stringify(auth).includes("sensitive-secret")); + + state.statusError = null; + state.tokenError = Object.assign(new Error("sensitive-secret"), { stderr: "sensitive-secret" }); + auth = await resolveAccounts({ force: true }); + assert.equal(auth.active, null); + assert.match(auth.diagnostic, /credential/i); + assert.ok(!JSON.stringify(auth).includes("sensitive-secret")); +}); + +test("errors validating an account do not disclose the credential", async (t) => { + const state = setup(t, { + platform: "linux", + env: { HOME: homedir(), COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user: "session-token" }, + }); + state.statusError = Object.assign(new Error("not found"), { code: "ENOENT" }); + state.fetchError = new Error("Invalid authorization value: session-token"); + const auth = await resolveAccounts(); + assert.equal(auth.active, null); + assert.equal(auth.accounts[0].status, "failed"); + assert.ok(!JSON.stringify(auth.accounts).includes("session-token")); +}); + +test("GitHub API failure messages redact the credential", async (t) => { + const state = setup(t, { + platform: "linux", + env: { HOME: homedir(), COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user: "session-token" }, + }); + state.statusError = Object.assign(new Error("not found"), { code: "ENOENT" }); + globalThis.fetch = async () => Response.json( + { message: "Invalid credential: session-token" }, + { status: 401 }, + ); + let auth = await resolveAccounts({ repository: "example/repository" }); + assert.match(auth.accounts[0].reason, /\[redacted\]/); + assert.ok(!JSON.stringify(auth.accounts).includes("session-token")); + + globalThis.fetch = async (url) => new URL(url).pathname === "/user" + ? Response.json({ login: "session-user" }) + : Response.json({ message: "Denied credential: session-token" }, { status: 403 }); + auth = await resolveAccounts({ repository: "example/repository", force: true }); + assert.equal(auth.accounts[0].status, "limited"); + assert.match(auth.accounts[0].reason, /\[redacted\]/); + assert.ok(!JSON.stringify(auth.accounts).includes("session-token")); +}); + +test("account rescan is available without credentials and recovers after sign-in", async (t) => { + const nativeFetch = globalThis.fetch; + const state = setup(t, { platform: "linux", env: { HOME: homedir() }, configVariable: "HOME", configPath: homedir() }); + state.statusError = Object.assign(new Error("not found"), { code: "ENOENT" }); + const { startInstance, stopInstance } = await import("./server.mjs"); + const instance = await startInstance("account-rescan", null, () => {}); + t.after(() => stopInstance("account-rescan")); + const call = (path) => nativeFetch(`${instance.origin}${path}`, { + headers: { "x-pr-artifact-explorer-token": instance.token }, + }); + + let response = await nativeFetch(`${instance.origin}/api/accounts?repo=example%2Frepository`); + assert.equal(response.status, 403, "account discovery still requires the canvas capability"); + + response = await call("/api/bootstrap"); + assert.equal(response.status, 200); + let payload = await response.json(); + assert.equal(payload.account, null); + assert.match(payload.diagnostic, /GitHub CLI.*not found/i); + + response = await call("/api/accounts?repo=example%2Frepository"); + assert.equal(response.status, 200); + payload = await response.json(); + assert.equal(payload.account, null); + assert.deepEqual(payload.accounts, []); + assert.match(payload.diagnostic, /GitHub CLI.*not found/i); + + response = await call("/api/pulls?repo=example%2Frepository"); + assert.equal(response.status, 401); + assert.match((await response.json()).error, /GitHub CLI.*not found/i); + + process.env.COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user = "session-token"; + state.fetchError = new Error("Invalid authorization value: session-token"); + response = await call("/api/accounts?repo=example%2Frepository"); + payload = await response.json(); + assert.equal(response.status, 200); + assert.equal(payload.accounts[0].status, "failed"); + assert.ok(!JSON.stringify(payload).includes("session-token")); + + delete process.env.COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user; + state.fetchError = null; + state.statusError = null; + response = await call("/api/accounts?repo=example%2Frepository"); + assert.equal(response.status, 200); + payload = await response.json(); + assert.equal(payload.account.login, "octocat"); + assert.equal(payload.diagnostic, null); + assert.ok(!JSON.stringify(payload).includes("cli-token")); +}); diff --git a/extensions/pr-artifact-explorer/assets/app.js b/extensions/pr-artifact-explorer/assets/app.js index f111230365..f45d253138 100644 --- a/extensions/pr-artifact-explorer/assets/app.js +++ b/extensions/pr-artifact-explorer/assets/app.js @@ -5648,6 +5648,7 @@ async function renderAccountsPage(sequence) {
Account access is checked against ${escapeHtml(repository)}.
+ ${payload.diagnostic ? `
${escapeHtml(payload.diagnostic)}
` : ""}
${ accounts.length @@ -5659,7 +5660,7 @@ async function renderAccountsPage(sequence) { : `
${icon("person")}

No GitHub accounts detected

-

Sign in through the Copilot app or GitHub CLI, then rescan.

+

Use a saved GitHub CLI account or open the canvas from a session, then rescan.

` }
`; diff --git a/extensions/pr-artifact-explorer/extension.mjs b/extensions/pr-artifact-explorer/extension.mjs index 99f71e3c74..cfa19351c3 100644 --- a/extensions/pr-artifact-explorer/extension.mjs +++ b/extensions/pr-artifact-explorer/extension.mjs @@ -55,7 +55,7 @@ async function resolveToken(repository) { const prefs = await loadPrefs(); const auth = await resolveAccounts({ preferredId: prefs.account, repository }); if (!auth.activeToken) { - throw new CanvasError("github_auth_required", "No usable GitHub account was found."); + throw new CanvasError("github_auth_required", auth.diagnostic); } return { token: auth.activeToken, account: auth.active?.id ?? null }; } @@ -533,7 +533,7 @@ const session = await joinSession({ repository: prefs.repository, force: true, }); - return { active: auth.active, accounts: auth.accounts }; + return { active: auth.active, accounts: auth.accounts, diagnostic: auth.diagnostic }; }, }, { diff --git a/extensions/pr-artifact-explorer/package-lock.json b/extensions/pr-artifact-explorer/package-lock.json index 7dc58f1151..bb17a75d79 100644 --- a/extensions/pr-artifact-explorer/package-lock.json +++ b/extensions/pr-artifact-explorer/package-lock.json @@ -1,12 +1,12 @@ { "name": "pr-artifact-explorer", - "version": "1.0.0", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pr-artifact-explorer", - "version": "1.0.0", + "version": "1.0.1", "optionalDependencies": { "playwright-core": "^1.60.0" } diff --git a/extensions/pr-artifact-explorer/package.json b/extensions/pr-artifact-explorer/package.json index 6658bd7913..984176d3ed 100644 --- a/extensions/pr-artifact-explorer/package.json +++ b/extensions/pr-artifact-explorer/package.json @@ -1,6 +1,6 @@ { "name": "pr-artifact-explorer", - "version": "1.0.0", + "version": "1.0.1", "type": "module", "main": "extension.mjs", "optionalDependencies": { diff --git a/extensions/pr-artifact-explorer/server.mjs b/extensions/pr-artifact-explorer/server.mjs index 16f7fb4ad6..264b7b76ec 100644 --- a/extensions/pr-artifact-explorer/server.mjs +++ b/extensions/pr-artifact-explorer/server.mjs @@ -333,7 +333,7 @@ function ensureJobBroadcast() { }); } -async function resolveAuth(repository, force = false) { +async function resolveAuth(repository, { force = false, requireToken = true } = {}) { const prefs = await loadPrefs(); const previousRepository = prefs.repository; const previousRecent = JSON.stringify(prefs.repositories.recent); @@ -351,11 +351,8 @@ async function resolveAuth(repository, force = false) { changed = true; } if (changed) await savePrefs(prefs); - if (!auth.activeToken) { - throw new HttpError( - 401, - "No usable GitHub account was detected. Sign in through the Copilot app or GitHub CLI.", - ); + if (requireToken && !auth.activeToken) { + throw new HttpError(401, auth.diagnostic); } return { prefs, auth }; } @@ -516,6 +513,7 @@ async function handleApi(req, res, entry, url) { prefs, account: auth.active, accounts: auth.accounts, + diagnostic: auth.diagnostic, cache: await getCacheSummary(), initialInput: entry.initialInput ?? null, }); @@ -526,12 +524,13 @@ async function handleApi(req, res, entry, url) { const repository = normalizeRepository( url.searchParams.get("repo") || prefs.repository, ); - const { auth } = await resolveAuth(repository, true); + const { auth } = await resolveAuth(repository, { force: true, requireToken: false }); pullRequestCache.clear(); progressivePullRequestCache.clear(); return sendJson(res, 200, { account: auth.active, accounts: auth.accounts, + diagnostic: auth.diagnostic, prefs: await loadPrefs(), }); } @@ -548,7 +547,7 @@ async function handleApi(req, res, entry, url) { invalidateAccounts(); pullRequestCache.clear(); progressivePullRequestCache.clear(); - const { auth } = await resolveAuth(repository, true); + const { auth } = await resolveAuth(repository, { force: true }); broadcast(entry, "refresh", { reason: "account" }); return sendJson(res, 200, { account: auth.active, @@ -565,7 +564,7 @@ async function handleApi(req, res, entry, url) { repository: prefs.repository, }); if (!auth.activeToken) { - throw new HttpError(401, "No usable GitHub account was found."); + throw new HttpError(401, auth.diagnostic); } return sendJson(res, 200, { repositories: await suggestRepositories(auth.activeToken, query), @@ -581,7 +580,7 @@ async function handleApi(req, res, entry, url) { repository, }); if (!auth.activeToken) { - throw new HttpError(401, "No usable GitHub account was found."); + throw new HttpError(401, auth.diagnostic); } return sendJson(res, 200, { repository: await getRepository(auth.activeToken, repository), diff --git a/plugins/pr-artifact-explorer/README.md b/plugins/pr-artifact-explorer/README.md index 8cd0ce2382..a4f987f4cc 100644 --- a/plugins/pr-artifact-explorer/README.md +++ b/plugins/pr-artifact-explorer/README.md @@ -8,6 +8,12 @@ Navigate pull requests and securely explore GitHub Actions artifacts, including copilot plugin install pr-artifact-explorer@awesome-copilot `` +## What's new in 1.0.1 + +- **Standalone account discovery.** On Windows, recover a missing `APPDATA` from the current user's Windows Roaming folder when safe, including redirected folders. On macOS and Linux, recover a missing or empty `HOME` when an absolute home is available, falling back to the OS account lookup if the environment-based lookup fails. Explicit GitHub CLI configuration and existing home configuration are preserved; if none of the GitHub.com accounts saved in an existing home configuration authenticate, the matching Roaming store is checked as a fallback. A home-store credential counts even when shared with Copilot or the environment, and a later repository-check error does not trigger the fallback. +- **Account isolation and recovery.** Saved GitHub CLI accounts for other hosts are excluded from GitHub.com account probes, and `GH_TOKEN`/`GITHUB_TOKEN` are not sent to GitHub.com when `GH_HOST` targets another host. Those variables carry no host, so without `GH_HOST` they are treated as GitHub.com tokens. The accounts view reports discovery problems and can rescan after sign-in. +- **Scope.** Standalone canvases may not receive conversation credentials. If you are signed in only to the Copilot app and have no saved GitHub CLI account, run `gh auth login --hostname github.com` or open the canvas from a session. User-scoped extension copies must be updated separately from installed plugins. + ## Source This plugin is part of [Awesome Copilot](https://github.com/github/awesome-copilot). diff --git a/plugins/pr-artifact-explorer/plugin.json b/plugins/pr-artifact-explorer/plugin.json index 00e084b9be..2b94956d9f 100644 --- a/plugins/pr-artifact-explorer/plugin.json +++ b/plugins/pr-artifact-explorer/plugin.json @@ -1,7 +1,7 @@ { "name": "pr-artifact-explorer", "description": "Navigate pull requests and workflow runs (including scheduled and manual runs without a PR) and securely explore GitHub Actions artifacts, including test results, static sites, terminal recordings, and source files.", - "version": "1.0.0", + "version": "1.0.1", "author": { "name": "David Pine", "url": "https://github.com/IEvangelist"