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) {
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.