From 5c6a8aa893ecedf46f9da1da13ca6cd80224a25d Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:42:56 -0600 Subject: [PATCH 1/6] Fix standalone Artifact Explorer account discovery on Windows Restore the GitHub CLI roaming configuration directory when a standalone canvas omits APPDATA, preserving explicit configuration overrides and existing account selection. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- extensions/pr-artifact-explorer/README.md | 6 + extensions/pr-artifact-explorer/accounts.mjs | 10 ++ .../pr-artifact-explorer/accounts.test.mjs | 126 ++++++++++++++++++ 3 files changed, 142 insertions(+) create mode 100644 extensions/pr-artifact-explorer/accounts.test.mjs diff --git a/extensions/pr-artifact-explorer/README.md b/extensions/pr-artifact-explorer/README.md index cb5b39b8ff..147abd62ee 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. On Windows, when that runtime also omits `APPDATA`, the GitHub CLI subprocess uses the current user's `AppData\Roaming` directory to find its saved accounts. Existing `APPDATA`, `GH_CONFIG_DIR`, and `XDG_CONFIG_HOME` settings are preserved. No sign-in or account switch is performed. + +Because standalone canvases receive no conversation credentials, they use the GitHub CLI accounts saved for the current user (including those used by the GitHub CLI bundled with the Copilot app). If none are saved, sign in with `gh auth login` or open the canvas from a session. + 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..305f5cc29f 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -1,6 +1,8 @@ import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; +import { homedir } from "node:os"; +import { join } from "node:path"; import { GITHUB_API, USER_AGENT } from "./constants.mjs"; const execFileAsync = promisify(execFile); @@ -19,6 +21,14 @@ function cleanGhEnvironment() { const env = { ...process.env }; delete env.GH_TOKEN; delete env.GITHUB_TOKEN; + // Standalone canvases may omit APPDATA, making gh miss its Windows keyring accounts. + if ( + process.platform === "win32" && + !Object.keys(env).some((name) => + /^(APPDATA|GH_CONFIG_DIR|XDG_CONFIG_HOME)$/i.test(name) && env[name]) + ) { + env.APPDATA = join(homedir(), "AppData", "Roaming"); + } return env; } diff --git a/extensions/pr-artifact-explorer/accounts.test.mjs b/extensions/pr-artifact-explorer/accounts.test.mjs new file mode 100644 index 0000000000..8c9a4f0b39 --- /dev/null +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +let scenario; +const originalExecFile = childProcess.execFile; +childProcess.execFile = (command, args, options, callback) => { + assert.equal(command, "gh"); + assert.equal(options.windowsHide, true); + assert.equal(options.env.GH_TOKEN, undefined); + assert.equal(options.env.GITHUB_TOKEN, undefined); + scenario.calls.push({ args, env: options.env }); + if (args[1] === "status") { + const config = Object.entries(options.env).find(([name]) => + name.toUpperCase() === scenario.configVariable)?.[1]; + if (config !== scenario.configPath) { + callback(Object.assign(new Error("No saved accounts"), { + stderr: "You are not logged into any GitHub hosts.", + })); + return; + } + callback(null, { + stdout: "Logged in to github.com account octocat (keyring)\n" + + "Logged in to enterprise.example account enterprise-user (keyring)", + stderr: "", + }); + return; + } + assert.deepEqual(args, ["auth", "token", "--hostname", "github.com", "--user", "octocat"]); + callback(null, { stdout: "cli-token\n", stderr: "" }); +}; +syncBuiltinESMExports(); +const { resolveAccounts, invalidateAccounts } = await import("./accounts.mjs"); +childProcess.execFile = originalExecFile; +syncBuiltinESMExports(); + +function setup(t, { platform = "win32", env = {}, configVariable = "APPDATA", + configPath = join(homedir(), "AppData", "Roaming") } = {}) { + const originalEnv = process.env; + const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); + const originalFetch = globalThis.fetch; + process.env = { ...env }; + Object.defineProperty(process, "platform", { value: platform }); + scenario = { calls: [], configVariable, configPath }; + globalThis.fetch = async (url, options) => { + assert.equal(new URL(url).origin, "https://api.github.com"); + const token = options.headers.Authorization; + assert.ok(["Bearer cli-token", "Bearer session-token"].includes(token)); + if (new URL(url).pathname === "/user") { + return Response.json({ login: token === "Bearer cli-token" ? "octocat" : "session-user" }); + } + assert.equal(new URL(url).pathname, "/repos/example/repository"); + return Response.json({ full_name: "example/repository" }); + }; + invalidateAccounts(); + t.after(() => { + process.env = originalEnv; + Object.defineProperty(process, "platform", platformDescriptor); + globalThis.fetch = originalFetch; + invalidateAccounts(); + }); + return scenario; +} + +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(process.env.APPDATA, undefined, "the parent environment is not modified"); + assert.equal(auth.accounts.length, 1, "enterprise tokens 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); +}); + +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)); + }); +} + +test("non-Windows discovery does not synthesize a Windows configuration directory", async (t) => { + const home = homedir(); + const state = setup(t, { + platform: "linux", env: { HOME: home }, configVariable: "HOME", configPath: home, + }); + const auth = await resolveAccounts({ repository: "example/repository" }); + assert.equal(auth.active.login, "octocat"); + assert.equal(state.calls.length, 2); + assert.ok(state.calls.every(({ env }) => env.APPDATA === undefined)); +}); From 8d807d9408253eb829e54ebdc41b3200aca084e5 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:23:41 -0600 Subject: [PATCH 2/6] Bump Artifact Explorer to 1.0.1 and document standalone account discovery Replace empty AppData keys without duplicate casing, document the redirected Roaming AppData limitation, and regenerate marketplace metadata. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/plugin/marketplace.json | 2 +- extensions/pr-artifact-explorer/README.md | 2 +- extensions/pr-artifact-explorer/accounts.mjs | 3 +++ extensions/pr-artifact-explorer/accounts.test.mjs | 8 ++++++++ extensions/pr-artifact-explorer/package-lock.json | 4 ++-- extensions/pr-artifact-explorer/package.json | 2 +- plugins/pr-artifact-explorer/README.md | 5 +++++ plugins/pr-artifact-explorer/plugin.json | 2 +- 8 files changed, 22 insertions(+), 6 deletions(-) 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 147abd62ee..58dbec745a 100644 --- a/extensions/pr-artifact-explorer/README.md +++ b/extensions/pr-artifact-explorer/README.md @@ -47,7 +47,7 @@ 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. On Windows, when that runtime also omits `APPDATA`, the GitHub CLI subprocess uses the current user's `AppData\Roaming` directory to find its saved accounts. Existing `APPDATA`, `GH_CONFIG_DIR`, and `XDG_CONFIG_HOME` settings are preserved. No sign-in or account switch is performed. +Standalone sidebar canvases may not inherit session account tokens. On Windows, when that runtime also omits `APPDATA`, the GitHub CLI subprocess uses the current user's `AppData\Roaming` directory to find its saved accounts. Existing `APPDATA`, `GH_CONFIG_DIR`, and `XDG_CONFIG_HOME` settings are preserved. No sign-in or account switch is performed. The fallback assumes the default Roaming location; if your Roaming AppData folder is redirected elsewhere, set `GH_CONFIG_DIR` to your GitHub CLI configuration directory. Because standalone canvases receive no conversation credentials, they use the GitHub CLI accounts saved for the current user (including those used by the GitHub CLI bundled with the Copilot app). If none are saved, sign in with `gh auth login` or open the canvas from a session. diff --git a/extensions/pr-artifact-explorer/accounts.mjs b/extensions/pr-artifact-explorer/accounts.mjs index 305f5cc29f..a1b45e6aa8 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -27,6 +27,9 @@ function cleanGhEnvironment() { !Object.keys(env).some((name) => /^(APPDATA|GH_CONFIG_DIR|XDG_CONFIG_HOME)$/i.test(name) && env[name]) ) { + for (const name of Object.keys(env)) { + if (/^APPDATA$/i.test(name)) delete env[name]; + } env.APPDATA = join(homedir(), "AppData", "Roaming"); } return env; diff --git a/extensions/pr-artifact-explorer/accounts.test.mjs b/extensions/pr-artifact-explorer/accounts.test.mjs index 8c9a4f0b39..0673a5d66b 100644 --- a/extensions/pr-artifact-explorer/accounts.test.mjs +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -100,6 +100,14 @@ test("session discovery retains its preferred account and AppData while excludin assert.equal(state.calls[0].env.APPDATA, undefined); }); +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)); +}); + for (const variable of ["GH_CONFIG_DIR", "XDG_CONFIG_HOME"]) { test(`standalone discovery preserves explicit ${variable}`, async (t) => { const configPath = join(homedir(), "custom-gh"); 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/plugins/pr-artifact-explorer/README.md b/plugins/pr-artifact-explorer/README.md index 8cd0ce2382..ef295df30d 100644 --- a/plugins/pr-artifact-explorer/README.md +++ b/plugins/pr-artifact-explorer/README.md @@ -8,6 +8,11 @@ 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.** Opening the canvas from the Copilot app's Canvases sidebar no longer fails with "No usable GitHub account was detected" when GitHub CLI accounts are saved. The standalone runtime can omit `APPDATA`, so the GitHub CLI subprocess now falls back to the current user's `AppData\Roaming`. Existing `APPDATA`, `GH_CONFIG_DIR`, and `XDG_CONFIG_HOME` values are preserved. If Roaming AppData is redirected away from the default location, set `GH_CONFIG_DIR`. +- **Scope.** Standalone canvases receive no conversation credentials. If you are signed in only to the Copilot app and have no saved GitHub CLI account, run `gh auth login` or open the canvas from a session. + ## 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" From f915066b5b9b604d1b67570dab16e04b67c226cd Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:56:21 -0600 Subject: [PATCH 3/6] Harden Artifact Explorer account discovery Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- extensions/pr-artifact-explorer/README.md | 4 +- extensions/pr-artifact-explorer/accounts.mjs | 212 ++++++++-- .../pr-artifact-explorer/accounts.test.mjs | 395 ++++++++++++++++-- extensions/pr-artifact-explorer/assets/app.js | 3 +- extensions/pr-artifact-explorer/extension.mjs | 4 +- extensions/pr-artifact-explorer/server.mjs | 19 +- plugins/pr-artifact-explorer/README.md | 5 +- 7 files changed, 561 insertions(+), 81 deletions(-) diff --git a/extensions/pr-artifact-explorer/README.md b/extensions/pr-artifact-explorer/README.md index 58dbec745a..ad009fdb3e 100644 --- a/extensions/pr-artifact-explorer/README.md +++ b/extensions/pr-artifact-explorer/README.md @@ -47,9 +47,9 @@ 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. On Windows, when that runtime also omits `APPDATA`, the GitHub CLI subprocess uses the current user's `AppData\Roaming` directory to find its saved accounts. Existing `APPDATA`, `GH_CONFIG_DIR`, and `XDG_CONFIG_HOME` settings are preserved. No sign-in or account switch is performed. The fallback assumes the default Roaming location; if your Roaming AppData folder is redirected elsewhere, set `GH_CONFIG_DIR` to your GitHub CLI configuration directory. +Standalone sidebar canvases may not inherit session account tokens. When `APPDATA` is missing on Windows, the GitHub CLI subprocess preserves an existing `USERPROFILE\.config\gh` directory; otherwise it asks Windows for the current user's Roaming folder, including redirected locations. It uses that folder only when the Windows profile matches `USERPROFILE`. On macOS and Linux, a missing `HOME` is restored for the subprocess when an absolute OS home is available. Existing `GH_CONFIG_DIR`, `XDG_CONFIG_HOME`, and `APPDATA` settings are preserved. 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 account switch is performed. -Because standalone canvases receive no conversation credentials, they use the GitHub CLI accounts saved for the current user (including those used by the GitHub CLI bundled with the Copilot app). If none are saved, sign in with `gh auth login` or open the canvas from a session. +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 GitHub Enterprise credentials are not used for GitHub.com requests. Artifact ZIPs and preferences are stored under: diff --git a/extensions/pr-artifact-explorer/accounts.mjs b/extensions/pr-artifact-explorer/accounts.mjs index a1b45e6aa8..93a52586c3 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -1,8 +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 } from "node:os"; -import { join } from "node:path"; +import { isAbsolute, join, normalize } from "node:path"; import { GITHUB_API, USER_AGENT } from "./constants.mjs"; const execFileAsync = promisify(execFile); @@ -17,22 +18,129 @@ 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() { + try { + const home = homedir(); + return home && isAbsolute(home) ? home : null; + } catch { + return null; + } +} + +async function cleanGhEnvironment() { const env = { ...process.env }; - delete env.GH_TOKEN; - delete env.GITHUB_TOKEN; - // Standalone canvases may omit APPDATA, making gh miss its Windows keyring accounts. - if ( - process.platform === "win32" && - !Object.keys(env).some((name) => - /^(APPDATA|GH_CONFIG_DIR|XDG_CONFIG_HOME)$/i.test(name) && env[name]) - ) { - for (const name of Object.keys(env)) { - if (/^APPDATA$/i.test(name)) delete env[name]; + 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.`, + }; } - env.APPDATA = join(homedir(), "AppData", "Roaming"); + return { env, diagnostic: null }; } - return env; + + 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); + + // Preserve gh's native home configuration rather than switching stores. + try { + await stat(join(home, ".config", "gh")); + return { env, diagnostic: null }; + } catch (error) { + if (error?.code !== "ENOENT") return { env, diagnostic: null }; + } + + 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) { @@ -43,28 +151,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; } -async function listGhAccounts() { +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(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)) { @@ -72,24 +192,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") }; } } @@ -106,17 +229,24 @@ 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()) { + const { env, diagnostic: environmentDiagnostic } = await cleanGhEnvironment(); + if (!env) return { candidates, diagnostic: environmentDiagnostic }; + const cli = await listGhAccounts(env); + let diagnostic = cli.diagnostic; + for (const account of cli.accounts) { if (account.host.toLowerCase() !== "github.com") continue; - add("gh", await readGhToken(account.host, account.login), account.login); + const result = await readGhToken(account.host, account.login, env); + add("gh", result.token, account.login); + if (result.diagnostic) diagnostic = result.diagnostic; } - return candidates; + return { candidates, diagnostic }; } async function apiProbe(token, path) { @@ -150,7 +280,9 @@ 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: [], }; } @@ -164,7 +296,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}).`; } } @@ -195,7 +329,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: [], }; } @@ -223,8 +359,9 @@ 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)), ); const groups = new Map(); for (const probe of probes) { @@ -283,6 +420,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.", + detection.diagnostic, + "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 index 0673a5d66b..6ede02db0d 100644 --- a/extensions/pr-artifact-explorer/accounts.test.mjs +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -1,58 +1,101 @@ 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 { homedir } from "node:os"; +import os, { homedir, tmpdir } from "node:os"; import { join } from "node:path"; -import test from "node:test"; +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(command, "gh"); assert.equal(options.windowsHide, true); - assert.equal(options.env.GH_TOKEN, undefined); - assert.equal(options.env.GITHUB_TOKEN, undefined); + 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 }); 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 (config !== scenario.configPath) { - callback(Object.assign(new Error("No saved accounts"), { + return callback(Object.assign(new Error("No saved accounts"), { stderr: "You are not logged into any GitHub hosts.", })); - return; } - callback(null, { - stdout: "Logged in to github.com account octocat (keyring)\n" + - "Logged in to enterprise.example account enterprise-user (keyring)", - stderr: "", - }); - return; + return callback(null, { stdout: scenario.statusOutput, stderr: "" }); } assert.deepEqual(args, ["auth", "token", "--hostname", "github.com", "--user", "octocat"]); - callback(null, { stdout: "cli-token\n", stderr: "" }); + if (scenario.tokenError) return callback(scenario.tokenError); + return callback(null, { stdout: "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 = join(homedir(), "AppData", "Roaming") } = {}) { +function setup(t, { + platform = "win32", + env = {}, + configVariable = "APPDATA", + configPath, + knownFolder, +} = {}) { const originalEnv = process.env; const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); const originalFetch = globalThis.fetch; - process.env = { ...env }; + const home = mkdtempSync(join(tmpdir(), "pae-account-profile-")); + process.env = { ...(platform === "win32" ? { USERPROFILE: home } : {}), ...env }; Object.defineProperty(process, "platform", { value: platform }); - scenario = { calls: [], configVariable, configPath }; + 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) => { - assert.equal(new URL(url).origin, "https://api.github.com"); + const requestUrl = new URL(url); const token = options.headers.Authorization; - assert.ok(["Bearer cli-token", "Bearer session-token"].includes(token)); - if (new URL(url).pathname === "/user") { - return Response.json({ login: token === "Bearer cli-token" ? "octocat" : "session-user" }); + scenario.fetchCalls.push({ url: requestUrl, token }); + assert.equal(requestUrl.origin, "https://api.github.com"); + if (scenario.fetchError) throw scenario.fetchError; + if (requestUrl.pathname === "/user") { + 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(new URL(url).pathname, "/repos/example/repository"); + assert.equal(requestUrl.pathname, "/repos/example/repository"); return Response.json({ full_name: "example/repository" }); }; invalidateAccounts(); @@ -61,6 +104,7 @@ function setup(t, { platform = "win32", env = {}, configVariable = "APPDATA", Object.defineProperty(process, "platform", platformDescriptor); globalThis.fetch = originalFetch; invalidateAccounts(); + rmSync(home, { recursive: true, force: true }); }); return scenario; } @@ -72,8 +116,9 @@ test("standalone Windows discovery finds saved CLI accounts without inherited to 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 tokens are not sent to github.com"); + 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")); }); @@ -84,7 +129,7 @@ test("session discovery retains its preferred account and AppData while excludin AppData: appData, COPILOT_GH_ACCOUNT_github_2E_com_session_2D_user: "session-token", GH_TOKEN: "ambient-token", - GITHUB_TOKEN: "ambient-token", + GitHub_Token: "ambient-token", }, configPath: appData, }); @@ -98,6 +143,7 @@ test("session discovery retains its preferred account and AppData while excludin 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) => { @@ -108,6 +154,96 @@ test("standalone Windows discovery replaces an empty AppData without duplicate k 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); + assert.ok(state.calls.every(({ env }) => env.APPDATA === undefined)); +}); + for (const variable of ["GH_CONFIG_DIR", "XDG_CONFIG_HOME"]) { test(`standalone discovery preserves explicit ${variable}`, async (t) => { const configPath = join(homedir(), "custom-gh"); @@ -119,16 +255,217 @@ for (const variable of ["GH_CONFIG_DIR", "XDG_CONFIG_HOME"]) { 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); + }); +} + +for (const platform of ["linux", "darwin"]) { + 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("non-Windows discovery does not synthesize a Windows configuration directory", async (t) => { - const home = homedir(); +test("missing Unix HOME never falls back to a relative CLI configuration", async (t) => { + const state = setup(t, { platform: "linux", env: {} }); + const originalHomedir = os.homedir; + os.homedir = () => { throw new Error("home unavailable"); }; + syncBuiltinESMExports(); + t.after(() => { + os.homedir = originalHomedir; + syncBuiltinESMExports(); + }); + 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, + }); + const originalHomedir = os.homedir; + os.homedir = () => { throw new Error("home unavailable"); }; + syncBuiltinESMExports(); + t.after(() => { + os.homedir = originalHomedir; + syncBuiltinESMExports(); + }); + 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, { - platform: "linux", env: { HOME: home }, configVariable: "HOME", configPath: home, + 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("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); - assert.ok(state.calls.every(({ env }) => env.APPDATA === undefined)); +}); + +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/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 ef295df30d..2000aedf7b 100644 --- a/plugins/pr-artifact-explorer/README.md +++ b/plugins/pr-artifact-explorer/README.md @@ -10,8 +10,9 @@ copilot plugin install pr-artifact-explorer@awesome-copilot ## What's new in 1.0.1 -- **Standalone account discovery on Windows.** Opening the canvas from the Copilot app's Canvases sidebar no longer fails with "No usable GitHub account was detected" when GitHub CLI accounts are saved. The standalone runtime can omit `APPDATA`, so the GitHub CLI subprocess now falls back to the current user's `AppData\Roaming`. Existing `APPDATA`, `GH_CONFIG_DIR`, and `XDG_CONFIG_HOME` values are preserved. If Roaming AppData is redirected away from the default location, set `GH_CONFIG_DIR`. -- **Scope.** Standalone canvases receive no conversation credentials. If you are signed in only to the Copilot app and have no saved GitHub CLI account, run `gh auth login` or open the canvas from a session. +- **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 `HOME` when an absolute OS home is available. Explicit GitHub CLI configuration and existing home configuration are preserved. +- **Account isolation and recovery.** GitHub Enterprise credentials are excluded from GitHub.com account probes. 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 From 235f982963f36296cca9998eeda2cebf1957fe3b Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:09:40 -0600 Subject: [PATCH 4/6] Harden Artifact Explorer token host isolation and roaming fallback Skip ambient GH_TOKEN/GITHUB_TOKEN when GH_HOST names another host, and retry the matching Windows Roaming gh store when no home-store account authenticates (including revoked tokens). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- extensions/pr-artifact-explorer/README.md | 4 +- extensions/pr-artifact-explorer/accounts.mjs | 82 ++++++++--- .../pr-artifact-explorer/accounts.test.mjs | 130 +++++++++++++++++- plugins/pr-artifact-explorer/README.md | 4 +- 4 files changed, 197 insertions(+), 23 deletions(-) diff --git a/extensions/pr-artifact-explorer/README.md b/extensions/pr-artifact-explorer/README.md index ad009fdb3e..2472ad3f6a 100644 --- a/extensions/pr-artifact-explorer/README.md +++ b/extensions/pr-artifact-explorer/README.md @@ -47,9 +47,9 @@ 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 preserves an existing `USERPROFILE\.config\gh` directory; otherwise it asks Windows for the current user's Roaming folder, including redirected locations. It uses that folder only when the Windows profile matches `USERPROFILE`. On macOS and Linux, a missing `HOME` is restored for the subprocess when an absolute OS home is available. Existing `GH_CONFIG_DIR`, `XDG_CONFIG_HOME`, and `APPDATA` settings are preserved. 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 account switch is performed. +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. It uses that folder only when the Windows profile matches `USERPROFILE`. On macOS and Linux, a missing `HOME` is restored for the subprocess when an absolute OS home is available. 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 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 GitHub Enterprise credentials are not used for GitHub.com requests. +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: diff --git a/extensions/pr-artifact-explorer/accounts.mjs b/extensions/pr-artifact-explorer/accounts.mjs index 93a52586c3..40df212519 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -101,14 +101,18 @@ async function cleanGhEnvironment() { } if (!configuredHome) setWindowsEnvironmentValue(env, "USERPROFILE", home); - // Preserve gh's native home configuration rather than switching stores. + // 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 }; + 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) @@ -233,20 +237,51 @@ async function detectCandidates() { if (login) add("copilot", value, login); } } - add("env", process.env.GH_TOKEN, null); - add("env", process.env.GITHUB_TOKEN, null); - - const { env, diagnostic: environmentDiagnostic } = await cleanGhEnvironment(); - if (!env) return { candidates, diagnostic: environmentDiagnostic }; - 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); - add("gh", result.token, account.login); - if (result.diagnostic) diagnostic = result.diagnostic; + // 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, diagnostic }; + + const withHostDiagnostic = (message) => + [message, hostDiagnostic].filter(Boolean).join(" ") || null; + const readStore = async (env) => { + 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); + 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); + 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 }; } async function apiProbe(token, path) { @@ -363,6 +398,21 @@ async function resolveAccountsUncached(preferredId, repository) { const probes = await Promise.all( detection.candidates.map((candidate) => probeCandidate(candidate, repository)), ); + let detectionDiagnostic = detection.diagnostic; + const storeAuthenticated = probes.some((probe) => + probe.source === "gh" && probe.status !== "failed"); + 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(); @@ -422,7 +472,7 @@ async function resolveAccountsUncached(preferredId, repository) { accounts: accounts.map(publicAccount), diagnostic: active ? null : [ "No usable GitHub.com account was detected.", - detection.diagnostic, + detectionDiagnostic, "For standalone use, sign in with gh auth login --hostname github.com or open the canvas from a session.", ].filter(Boolean).join(" "), }; diff --git a/extensions/pr-artifact-explorer/accounts.test.mjs b/extensions/pr-artifact-explorer/accounts.test.mjs index 6ede02db0d..6c15814d02 100644 --- a/extensions/pr-artifact-explorer/accounts.test.mjs +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -30,12 +30,15 @@ childProcess.execFile = (command, args, options, callback) => { 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 (config !== scenario.configPath) { + 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.", })); @@ -44,7 +47,7 @@ childProcess.execFile = (command, args, options, callback) => { } assert.deepEqual(args, ["auth", "token", "--hostname", "github.com", "--user", "octocat"]); if (scenario.tokenError) return callback(scenario.tokenError); - return callback(null, { stdout: "cli-token\n", stderr: "" }); + return callback(null, { stdout: `${storeToken ?? "cli-token"}\n`, stderr: "" }); }; syncBuiltinESMExports(); const { resolveAccounts, invalidateAccounts } = await import("./accounts.mjs"); @@ -86,6 +89,9 @@ function setup(t, { 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", @@ -240,10 +246,80 @@ test("Windows discovery preserves an existing native home configuration", async state.configPath = state.home; const auth = await resolveAccounts({ repository: "example/repository" }); assert.equal(auth.active.login, "octocat"); - assert.equal(state.folderCalls.length, 0); + 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")); +}); + +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"); @@ -342,6 +418,54 @@ test("Copilot credentials are never probed against a different host", async (t) 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"), { diff --git a/plugins/pr-artifact-explorer/README.md b/plugins/pr-artifact-explorer/README.md index 2000aedf7b..5aae69c06c 100644 --- a/plugins/pr-artifact-explorer/README.md +++ b/plugins/pr-artifact-explorer/README.md @@ -10,8 +10,8 @@ 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 `HOME` when an absolute OS home is available. Explicit GitHub CLI configuration and existing home configuration are preserved. -- **Account isolation and recovery.** GitHub Enterprise credentials are excluded from GitHub.com account probes. The accounts view reports discovery problems and can rescan after sign-in. +- **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 `HOME` when an absolute OS home is available. 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. +- **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 From aed008a50c7ae66b9aa214e22a50e4c4e0a71b28 Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:15:17 -0600 Subject: [PATCH 5/6] Recover Artifact Explorer home from OS account lookup Fall back to the absolute OS-account home when environment-based home discovery is empty, relative, or unavailable. Cover native Linux empty HOME and unavailable lookup cases. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- extensions/pr-artifact-explorer/README.md | 2 +- extensions/pr-artifact-explorer/accounts.mjs | 15 ++-- .../pr-artifact-explorer/accounts.test.mjs | 81 +++++++++++++++---- plugins/pr-artifact-explorer/README.md | 2 +- 4 files changed, 78 insertions(+), 22 deletions(-) diff --git a/extensions/pr-artifact-explorer/README.md b/extensions/pr-artifact-explorer/README.md index 2472ad3f6a..0cb4d3e876 100644 --- a/extensions/pr-artifact-explorer/README.md +++ b/extensions/pr-artifact-explorer/README.md @@ -47,7 +47,7 @@ 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. It uses that folder only when the Windows profile matches `USERPROFILE`. On macOS and Linux, a missing `HOME` is restored for the subprocess when an absolute OS home is available. 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 account switch is performed. +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. 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 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. diff --git a/extensions/pr-artifact-explorer/accounts.mjs b/extensions/pr-artifact-explorer/accounts.mjs index 40df212519..866e59a3ad 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -2,7 +2,7 @@ import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; import { stat } from "node:fs/promises"; import { promisify, stripVTControlCharacters } from "node:util"; -import { homedir } from "node:os"; +import { homedir, userInfo } from "node:os"; import { isAbsolute, join, normalize } from "node:path"; import { GITHUB_API, USER_AGENT } from "./constants.mjs"; @@ -41,12 +41,15 @@ function normalizeWindowsEnvironmentValue(env, key) { } function safeHome() { - try { - const home = homedir(); - return home && isAbsolute(home) ? home : null; - } catch { - return null; + 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() { diff --git a/extensions/pr-artifact-explorer/accounts.test.mjs b/extensions/pr-artifact-explorer/accounts.test.mjs index 6c15814d02..d4543f970c 100644 --- a/extensions/pr-artifact-explorer/accounts.test.mjs +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -115,6 +115,19 @@ function setup(t, { 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" }); @@ -335,7 +348,44 @@ for (const variable of ["GH_CONFIG_DIR", "XDG_CONFIG_HOME"]) { }); } +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 }); @@ -362,19 +412,26 @@ for (const platform of ["linux", "darwin"]) { test("missing Unix HOME never falls back to a relative CLI configuration", async (t) => { const state = setup(t, { platform: "linux", env: {} }); - const originalHomedir = os.homedir; - os.homedir = () => { throw new Error("home unavailable"); }; - syncBuiltinESMExports(); - t.after(() => { - os.homedir = originalHomedir; - syncBuiltinESMExports(); - }); + 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, { @@ -383,13 +440,9 @@ test("explicit Unix CLI configuration works even when HOME cannot be recovered", configVariable: "GH_CONFIG_DIR", configPath, }); - const originalHomedir = os.homedir; - os.homedir = () => { throw new Error("home unavailable"); }; - syncBuiltinESMExports(); - t.after(() => { - os.homedir = originalHomedir; - syncBuiltinESMExports(); - }); + 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)); diff --git a/plugins/pr-artifact-explorer/README.md b/plugins/pr-artifact-explorer/README.md index 5aae69c06c..023dd62036 100644 --- a/plugins/pr-artifact-explorer/README.md +++ b/plugins/pr-artifact-explorer/README.md @@ -10,7 +10,7 @@ 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 `HOME` when an absolute OS home is available. 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. +- **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. - **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. From 1d3fd822879bba1e232c429fbb3c76cd4ad746df Mon Sep 17 00:00:00 2001 From: David Pine <7679720+IEvangelist@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:36:26 -0600 Subject: [PATCH 6/6] Preserve the primary account during roaming fallback Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- extensions/pr-artifact-explorer/README.md | 2 +- extensions/pr-artifact-explorer/accounts.mjs | 15 ++-- .../pr-artifact-explorer/accounts.test.mjs | 71 +++++++++++++++++++ plugins/pr-artifact-explorer/README.md | 2 +- 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/extensions/pr-artifact-explorer/README.md b/extensions/pr-artifact-explorer/README.md index 0cb4d3e876..fe420a189a 100644 --- a/extensions/pr-artifact-explorer/README.md +++ b/extensions/pr-artifact-explorer/README.md @@ -47,7 +47,7 @@ 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. 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 account switch is performed. +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. diff --git a/extensions/pr-artifact-explorer/accounts.mjs b/extensions/pr-artifact-explorer/accounts.mjs index 866e59a3ad..61fcff0bbf 100644 --- a/extensions/pr-artifact-explorer/accounts.mjs +++ b/extensions/pr-artifact-explorer/accounts.mjs @@ -254,12 +254,14 @@ async function detectCandidates() { const withHostDiagnostic = (message) => [message, hostDiagnostic].filter(Boolean).join(" ") || null; - const readStore = async (env) => { + 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; } @@ -268,7 +270,7 @@ async function detectCandidates() { const store = await cleanGhEnvironment(); if (!store.env) return { candidates, diagnostic: withHostDiagnostic(store.diagnostic) }; - const diagnostic = await readStore(store.env); + 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 @@ -284,7 +286,7 @@ async function detectCandidates() { }; } : null; - return { candidates, diagnostic: withHostDiagnostic(diagnostic), readFallbackStore }; + return { candidates, diagnostic: withHostDiagnostic(diagnostic), readFallbackStore, primaryStoreTokens }; } async function apiProbe(token, path) { @@ -306,6 +308,7 @@ async function probeCandidate(candidate, repository) { source: candidate.source, hash: candidate.hash, hintedLogin: candidate.hintedLogin, + authenticated: false, }; try { @@ -325,6 +328,7 @@ async function probeCandidate(candidate, repository) { }; } + safe.authenticated = true; let repositoryAccess = null; let repositoryReason = null; if (repository) { @@ -402,8 +406,9 @@ async function resolveAccountsUncached(preferredId, repository) { detection.candidates.map((candidate) => probeCandidate(candidate, repository)), ); let detectionDiagnostic = detection.diagnostic; - const storeAuthenticated = probes.some((probe) => - probe.source === "gh" && probe.status !== "failed"); + // 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) { diff --git a/extensions/pr-artifact-explorer/accounts.test.mjs b/extensions/pr-artifact-explorer/accounts.test.mjs index d4543f970c..325b521aea 100644 --- a/extensions/pr-artifact-explorer/accounts.test.mjs +++ b/extensions/pr-artifact-explorer/accounts.test.mjs @@ -102,6 +102,12 @@ function setup(t, { 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(); @@ -302,6 +308,71 @@ test("Windows roaming fallback is not used when the home store account authentic 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 }); diff --git a/plugins/pr-artifact-explorer/README.md b/plugins/pr-artifact-explorer/README.md index 023dd62036..a4f987f4cc 100644 --- a/plugins/pr-artifact-explorer/README.md +++ b/plugins/pr-artifact-explorer/README.md @@ -10,7 +10,7 @@ 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. +- **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.