gh-setup-git-identity 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # gh-setup-git-identity
2
2
 
3
+ ## 0.8.2
4
+
5
+ ### Patch Changes
6
+
7
+ - e740d67: Retry GitHub login once when the active account cannot read its primary email, then configure Git from the account selected during login. Honor `--repair`, `--no-auto-login`, and `--dry-run` during authentication recovery.
8
+
3
9
  ## 0.8.1
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -33,7 +33,7 @@ gh-setup-git-identity
33
33
 
34
34
  - **Automatic identity setup**: Fetches username and email from GitHub
35
35
  - **Global and local configuration**: Configure git globally or per-repository
36
- - **Authentication check**: Prompts you to login if not authenticated
36
+ - **Authentication recovery**: Starts login when signed out or when the active credential lacks email access
37
37
  - **Git credential helper setup**: Automatically runs `gh auth setup-git` to configure git to use GitHub CLI for HTTPS authentication
38
38
  - **Dry-run mode**: Preview changes without making them
39
39
  - **Cross-platform**: Works on macOS, Linux, and Windows
@@ -94,14 +94,14 @@ Git Identity Options:
94
94
  --dry-run, --dry Dry run - show what would be done without making changes
95
95
  --verify Verify current git identity configuration
96
96
  --repair Repair git identity without triggering login (requires existing auth)
97
- --no-auto-login Disable automatic login if not authenticated
97
+ --no-auto-login Disable automatic login and re-login
98
98
  --verbose, -v Enable verbose output
99
99
 
100
100
  GitHub Authentication Options:
101
101
  --hostname GitHub hostname to authenticate with (default: github.com)
102
102
  --scopes, -s Authentication scopes, comma-separated (default: repo,workflow,user,read:org,gist)
103
103
  --git-protocol, -p Protocol for git operations: ssh or https (default: https)
104
- --web, -w Open a browser to authenticate (default: true)
104
+ --web, -w Open a browser to authenticate (default unless using --with-token)
105
105
  --with-token Read token from standard input
106
106
  --skip-ssh-key Skip generate/upload SSH key prompt
107
107
  --insecure-storage Save credentials in plain text instead of credential store
@@ -159,6 +159,14 @@ printf "y" | gh auth login -h github.com -s repo,workflow,user,read:org,gist --g
159
159
  gh auth setup-git -h github.com
160
160
  ```
161
161
 
162
+ ### When the Active Account Lacks Email Access
163
+
164
+ GitHub CLI can be signed in with a credential that cannot read the account's primary email. If `gh api user/emails` reports missing email access, the CLI starts `gh auth login` once and retries both identity lookups for the account you authorize. Recovery uses the configured hostname and login options. For OAuth login, it adds the reported email scope when your requested scopes omit both `user` and `user:email`.
165
+
166
+ If an environment token is active, replace it with a classic token that has `user:email` or `user`, or with a fine-grained user token that has **Email addresses: Read**. To use stored credentials or sign in with the browser, clear the environment token for the target host before rerunning the tool. [GitHub's email API permissions](https://docs.github.com/en/rest/users/emails#list-email-addresses-for-the-authenticated-user)
167
+
168
+ Use `--verbose` to see the authentication decision, login command and retry. The incident transcript, root cause and tests are in the [issue #34 case study](./docs/case-studies/issue-34/).
169
+
162
170
  ### Successful Run
163
171
 
164
172
  ```
@@ -226,18 +234,18 @@ This is useful when:
226
234
  - The `user.name` or `user.email` was accidentally cleared or corrupted
227
235
  - You want to reconfigure git identity without going through the login flow again
228
236
 
229
- The `--repair` option requires that you're already authenticated with GitHub CLI. If not authenticated, it will show helpful instructions for manual authentication.
237
+ The `--repair` option requires an existing GitHub CLI login with access to the primary email. It reports authentication or permission errors without starting login.
230
238
 
231
239
  ### Disabling Auto-Login
232
240
 
233
- By default, if you're not authenticated, the tool will automatically start the GitHub CLI login process. You can disable this behavior:
241
+ By default, the tool starts GitHub CLI login when signed out or when the active account lacks email access. You can disable automatic login:
234
242
 
235
243
  ```bash
236
- # Fail immediately if not authenticated (don't auto-login)
244
+ # Require a usable existing login
237
245
  gh-setup-git-identity --no-auto-login
238
246
  ```
239
247
 
240
- This is useful in scripts or automated environments where you want to fail fast rather than wait for an interactive login prompt.
248
+ Use `--dry-run` to preview identity changes with an existing login. It skips login and Git configuration writes.
241
249
 
242
250
  ## Library Usage
243
251
 
@@ -271,6 +279,8 @@ const result2 = await setupGitIdentity({
271
279
 
272
280
  Check if GitHub CLI is authenticated.
273
281
 
282
+ Pass `options.hostname` to check the active account on that host.
283
+
274
284
  **Returns:** `Promise<boolean>`
275
285
 
276
286
  #### `runGhAuthLogin(options?)`
@@ -326,6 +336,8 @@ Default authentication options object that can be imported and used as a referen
326
336
 
327
337
  Get GitHub user information (username and primary email).
328
338
 
339
+ Pass `options.hostname` to query a specific host.
340
+
329
341
  **Returns:** `Promise<{username: string, email: string}>`
330
342
 
331
343
  #### `setupGitIdentity(options?)`
@@ -334,6 +346,8 @@ Setup git identity based on GitHub user.
334
346
 
335
347
  **Parameters:**
336
348
  - `options.scope` - `'global'` or `'local'` (default: `'global'`)
349
+ - `options.hostname` - GitHub host for both identity lookups
350
+ - `options.authOptions` - Opt in to one re-login on an email permission error. Accepts `runGhAuthLogin` options and defaults the host to `github.com` when neither hostname option is set.
337
351
  - `options.dryRun` - Preview only, don't make changes (default: `false`)
338
352
  - `options.verbose` - Enable verbose logging (default: `false`)
339
353
  - `options.logger` - Custom logger (default: `console`)
@@ -403,7 +417,7 @@ For a detailed case study of this issue, see [docs/case-studies/issue-26/](./doc
403
417
 
404
418
  #### GitHub Authentication Options
405
419
 
406
- - `GH_AUTH_HOSTNAME` - GitHub hostname (default: `github.com`)
420
+ - `GH_AUTH_HOSTNAME` - GitHub hostname (defaults to `GH_HOST`, then `github.com`)
407
421
  - `GH_AUTH_SCOPES` - Authentication scopes (default: `repo,workflow,user,read:org,gist`)
408
422
  - `GH_AUTH_GIT_PROTOCOL` - Git protocol: `ssh` or `https` (default: `https`)
409
423
  - `GH_AUTH_WEB` - Open browser for authentication (default: `true`)
@@ -0,0 +1,53 @@
1
+ # Issue #34 case study — a signed-in GitHub CLI account lacked email access
2
+
3
+ The application treated a successful `gh auth status` as proof that it could fetch the authenticated user's primary email. The reported credential passed that check, then GitHub rejected `GET /user/emails` and `gh` identified a missing OAuth scope. Signing in again with `user` restored the lookup. The fix starts the existing login flow once on the permission error and fetches the username and email again before writing Git identity. [Issue #34](https://github.com/link-foundation/gh-setup-git-identity/issues/34) · [Reported terminal transcript](raw-logs/issue-report.txt)
4
+
5
+ ## Timeline
6
+
7
+ | Order | Observed event | Significance |
8
+ | --- | --- | --- |
9
+ | 1 | The tool configured the GitHub CLI credential helper, then printed `Fetching GitHub user information...`. | The installed CLI followed its already-authenticated branch. Git credential helper setup configures Git transport and grants no API permissions. |
10
+ | 2 | Email lookup failed with HTTP 404 and the `"user" scope` hint. | The endpoint needed privileges that the credential did not provide. The program stopped before the two identity writes. |
11
+ | 3 | The reporter piped `y` to `gh auth login -h github.com -s repo,workflow,user,read:org,gist --git-protocol https --web` and approved the device flow. | The command requested the missing scope and activated the account authorized in the browser. The clipboard and keyring messages were incidental because login completed. |
12
+ | 4 | On the next invocation, the tool fetched the username and primary email and set both Git identity fields globally. | The resulting credential could read the identity. |
13
+ | 5 | Issue #34 was filed on 2026-11-22 at 16:05:51 UTC and edited at 16:07:08 UTC. | The issue contains the only incident transcript. The terminal commands have no individual timestamps. |
14
+ | 6 | A mock-subprocess regression reproduced the application failure. A separate replay with `gh` 2.102.0 and 2.105.0 reproduced an unusable refresh hint for environment tokens. | The two experiments established the application control flow and a separate upstream diagnostic problem. |
15
+
16
+ The report does not record the first credential's source, the previous account login, or the version of `gh`. The successful manual login establishes that a new authorization recovered the application. Whether the browser was signed into a different account, and whether `gh auth refresh` would have worked for the original credential, are unknown. The [archived transcript](raw-logs/issue-report.txt) removes the one-time code, email, account and container identifiers. The issue had no comments or linked sub-issues when investigated.
17
+
18
+ ## Root causes and affected entry points
19
+
20
+ 1. **The preflight checks authentication, while the failed operation checks email permission.** The CLI only initiated login on a nonzero `gh auth status`. The library treated any `gh api user/emails` failure as an ordinary setup error, so the CLI exited even when `gh` described a recoverable scope issue. GitHub documents `user:email` for classic token email reads. The parent `user` scope includes it. Fine-grained user tokens need the read permission for email addresses. The live API advertises `user, user:email` in its accepted OAuth scopes header. [REST email endpoint](https://docs.github.com/en/rest/users/emails#list-email-addresses-for-the-authenticated-user) · [OAuth scopes](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps) · [Captured response headers](raw-logs/email-endpoint-headers.txt)
21
+ 2. **A host or account can change across authentication.** The old CLI supplied `--hostname` for login and credential helper setup, while status and identity requests let `gh` choose their host. Restarting only the failed email call could also pair the old username with a newly authorized email. The CLI now passes its selected host through every setup operation and looks up both fields again after login. The recovery path waits for the original lookups to finish before replacing the active credential.
22
+ 3. **The upstream scope hint lacks credential-source context.** `gh api` derives the scope hint from the error status and OAuth response headers. The hint recommends refreshing stored credentials even when an environment variable supplies the active token. `gh auth refresh` explicitly rejects that source. The loopback test reproduces this secondary problem independently of the reporter's unknown credential source. The application now names the applicable variable and explains how to provide a usable token. [Scope suggestion code](https://github.com/cli/cli/blob/v2.105.0/api/client.go#L342-L411) · [Refresh command](https://github.com/cli/cli/blob/v2.105.0/pkg/cmd/auth/refresh/refresh.go#L191-L195) · [Upstream issue](https://github.com/cli/cli/issues/15129)
23
+ 4. **The opt-out flag was declared in the wrong form for the argument parser.** Yargs parses `--no-auto-login` as `auto-login=false`. Strict mode rejected the flag when the positive form was undefined, and the old test only scanned source text. The CLI now declares `auto-login` and tests the user-facing negated flag against both signed-out and insufficient-scope credentials.
24
+
25
+ The CLI recognizes the `user` and `user:email` hints and explicit token-access denials from the email endpoint. A bare HTTP 404, a missing primary email, and failures from the username lookup still surface as setup errors. Low-level lookup functions perform only reads. Library consumers of `setupGitIdentity` can enable the same one-attempt recovery by passing `authOptions`.
26
+
27
+ ## Options considered
28
+
29
+ | Approach | Fit for this incident |
30
+ | --- | --- |
31
+ | Reuse `gh auth login`, then rerun the identity lookup | Matches the successful workaround, delegates device authorization and secure storage to `gh`, and allows the user to choose or reauthorize an account. The implementation preserves login flags and adds a necessary OAuth scope for custom lists that omit email access. |
32
+ | Run `gh auth refresh -s user:email` | A manual option for the active stored account when preserving that account is desired. It cannot select a different account or update an environment-provided token. [GitHub CLI refresh manual](https://cli.github.com/manual/gh_auth_refresh) |
33
+ | Switch an already-authorized account with `gh auth switch` | Useful when the user already knows which stored account has the needed permission. The application cannot infer a preferred account from the permission error. [GitHub CLI switch manual](https://cli.github.com/manual/gh_auth_switch) |
34
+ | Use a user token supplied by the caller | Fits automation and the existing `--with-token` interface. Environment token precedence is controlled by `gh`. Recovery tells the caller how to remove or replace an environment credential that lacks email access. [GitHub CLI environment manual](https://cli.github.com/manual/gh_help_environment) |
35
+ | Replace `gh` API calls with Octokit and implement device authorization in JavaScript | Octokit can perform the REST request and device authorization. The application would also need to manage GitHub CLI's active account and credential store so later `gh` and Git commands use the same identity. [Octokit device authorization](https://github.com/octokit/auth-oauth-device.js) |
36
+ | Use the public profile email or synthesize a noreply address | An identity fallback could be useful for other tooling. This tool promises the account's primary email, which may be private and different from either value. Native Git identity setup has been proposed separately. [cli/cli#6096](https://github.com/cli/cli/issues/6096) |
37
+
38
+ ## Requirements and verification
39
+
40
+ | Requirement | Implementation and evidence |
41
+ | --- | --- |
42
+ | Automatically sign in again when an existing credential lacks the required scope | The CLI uses its existing `gh auth login` flow once, then refetches both identity fields and configures Git. [Regression before](raw-logs/regression-before.txt) · [Regression after](raw-logs/regression-after.txt) |
43
+ | Apply the behavior to affected setup paths | Subprocess tests cover the CLI's default and Enterprise hosts, global and local Git scope, custom settings, a replacement token from stdin, and opt-in library recovery. A first-time login, canceled login, and persistent errors all respect the one-login bound. [CLI tests](../../../test/cli.test.js) |
44
+ | Preserve callers' control of authentication | Tests exercise `--repair`, `--no-auto-login`, and `--dry-run`, an older `gh` without `--active`, healthy credentials, and non-permission errors. Environment token replacement guidance is also covered. [CLI tests](../../../test/cli.test.js) |
45
+ | Collect incident evidence, reconstruct events, establish root causes, and research existing solutions | The [incident transcript](raw-logs/issue-report.txt), [regression logs](raw-logs/) and primary references above preserve the available evidence. The existing `--verbose` mode now shows the scope error, invoked login, and retry host. |
46
+ | Report related upstream findings with reproduction, workaround and code proposal | The environment-token hint mismatch was reproduced against two real `gh` releases with a synthetic API response. The upstream report includes both a classic-token reproduction procedure and the loopback fixture, a credential-source-aware fix proposal, and the token replacement workaround. [cli/cli#15129](https://github.com/cli/cli/issues/15129) |
47
+ | Prepare the fix for release in one PR | The prepared PR's initial changeset check failed because the placeholder commit lacked a release entry. The PR adds a patch changeset and uses the existing check, lint, and Linux/macOS test jobs. [Initial CI failure excerpt](raw-logs/prepared-pr-changeset-check.txt) · [PR #35](https://github.com/link-foundation/gh-setup-git-identity/pull/35) |
48
+
49
+ Run the mocked regression suite with `bun test test/cli.test.js`. To reproduce the original failure locally, use those tests against the original implementation and select the test named `CLI signs in again when an authenticated account lacks the user scope`. The test supplies the same scope diagnostic as the incident and models an account switch so that success requires reading both fields again.
50
+
51
+ The [loopback experiment](../../../experiments/issue-34-gh-scope-hint.mjs) runs with `node experiments/issue-34-gh-scope-hint.mjs [path-to-gh]`. It uses an isolated configuration, a disposable TLS certificate, a synthetic token, and a local listener on port 443. [GitHub CLI 2.102.0 log](raw-logs/gh-2.102.0-scope-hint.txt) · [GitHub CLI 2.105.0 log](raw-logs/gh-2.105.0-scope-hint.txt)
52
+
53
+ Automated checks simulate login completion and cancellation. Browser approval in the original incident is documented in the reporter's transcript.
@@ -0,0 +1,5 @@
1
+ gh version 2.102.0 (2026-09-30)
2
+ https://github.com/cli/cli/releases/tag/v2.102.0
3
+ HTTP/2.0 200 OK
4
+ X-Accepted-Oauth-Scopes: user, user:email
5
+ X-Oauth-Scopes: gist, read:org, repo, user, workflow
@@ -0,0 +1,13 @@
1
+ $ gh --version
2
+ gh version 2.102.0 (2026-09-30)
3
+ https://github.com/cli/cli/releases/tag/v2.102.0
4
+ Exit status 0
5
+ $ gh api --hostname 127.0.0.1 user/emails
6
+ {"message":"Not Found"}
7
+ gh: Not Found (HTTP 404)
8
+ gh: This API operation needs the "user" scope. To request it, run: gh auth refresh -h 127.0.0.1 -s user
9
+ Exit status 1
10
+ $ gh auth refresh -h 127.0.0.1 -s user
11
+ The value of the GH_ENTERPRISE_TOKEN environment variable is being used for authentication.
12
+ To refresh credentials stored in GitHub CLI, first clear the value from the environment.
13
+ Exit status 1
@@ -0,0 +1,13 @@
1
+ $ gh --version
2
+ gh version 2.105.0 (2026-11-17)
3
+ https://github.com/cli/cli/releases/tag/v2.105.0
4
+ Exit status 0
5
+ $ gh api --hostname 127.0.0.1 user/emails
6
+ {"message":"Not Found"}
7
+ gh: Not Found (HTTP 404)
8
+ gh: This API operation needs the "user" scope. To request it, run: gh auth refresh -h 127.0.0.1 -s user
9
+ Exit status 1
10
+ $ gh auth refresh -h 127.0.0.1 -s user
11
+ The value of the GH_ENTERPRISE_TOKEN environment variable is being used for authentication.
12
+ To refresh credentials stored in GitHub CLI, first clear the value from the environment.
13
+ Exit status 1
@@ -0,0 +1,46 @@
1
+ Source: https://github.com/link-foundation/gh-setup-git-identity/issues/34
2
+ Title: `gh: This API operation needs the "user" scope` must trigger relogin sequence instead of failure
3
+ Created: 2026-11-22T16:05:51Z
4
+ Updated: 2026-11-22T16:07:08Z
5
+
6
+ Terminal transcript (device code, user, email and container redacted):
7
+ user@container:~$ gh-setup-git-identity
8
+ Git credential helper configured for GitHub CLI
9
+
10
+ Fetching GitHub user information...
11
+
12
+ Error: Failed to get GitHub email: gh: Not Found (HTTP 404)
13
+ gh: This API operation needs the "user" scope. To request it, run: gh auth refresh -h github.com -s user
14
+ user@container:~$ printf "y" | gh auth login -h github.com -s repo,workflow,user,read:org,gist --git-protocol https --web
15
+
16
+ ! Failed to copy one-time code to clipboard
17
+ No clipboard utilities available. Please install xsel, xclip, wl-clipboard or Termux:API add-on for termux-clipboard-get/set.
18
+ ! First copy your one-time code: [REDACTED]
19
+ Open this URL to continue in your web browser: https://github.com/login/device
20
+ ✓ Authentication complete.
21
+ - gh config set -h github.com git_protocol https
22
+ ✓ Configured git protocol
23
+ ! Authentication credentials saved in plain text
24
+ ✓ Logged in as example-user
25
+ user@container:~$ gh-setup-git-identity
26
+ Git credential helper configured for GitHub CLI
27
+
28
+ Fetching GitHub user information...
29
+ GitHub user: example-user
30
+ GitHub email: user@example.test
31
+
32
+ Configuring git (global)...
33
+ Git identity configured successfully!
34
+
35
+ Git configured:
36
+ user.name: example-user
37
+ user.email: user@example.test
38
+ Scope: global (--global)
39
+
40
+ Git identity setup complete!
41
+
42
+ You can verify your configuration with:
43
+ gh auth status
44
+ git config --global user.name
45
+ git config --global user.email
46
+ user@container:~$
@@ -0,0 +1,3 @@
1
+ Check for Changesets Check for changesets 2026-11-22T16:52:12.0919378Z ##[error]No changeset found. Please add a changeset by running 'npm run changeset' and commit the result.
2
+ Check for Changesets Check for changesets 2026-11-22T16:52:12.0931353Z Found 0 changeset file(s)
3
+ Check for Changesets Check for changesets 2026-11-22T16:52:12.0933550Z ##[error]Process completed with exit code 1.
@@ -0,0 +1,19 @@
1
+ bun test v1.4.4 (38afee6c8)
2
+
3
+ test/cli.test.js:
4
+ (pass) CLI --version matches the package version [87.68ms]
5
+ (pass) CLI --version uses its own package from an unrelated directory [88.49ms]
6
+ (pass) CLI signs in again when an authenticated account lacks the user scope [179.14ms]
7
+ (pass) CLI recovery uses the selected host, flags, scopes and local Git configuration [185.70ms]
8
+ (pass) CLI keeps the original authentication failure when recovery is disabled [438.08ms]
9
+ (pass) CLI attempts recovery once when login is canceled or permissions remain missing [506.62ms]
10
+ (pass) CLI leaves unrelated failures and a usable account on the existing path [462.53ms]
11
+ (pass) CLI keeps dry-run read-only and retains first-time login [575.40ms]
12
+ (pass) CLI still recovers with gh versions without the active-account status flag [157.95ms]
13
+ (pass) CLI explains how to replace an environment token lacking email permission [110.99ms]
14
+ (pass) CLI can read a replacement token from stdin during recovery [160.92ms]
15
+ (pass) Library callers opt in to interactive recovery through setupGitIdentity [202.02ms]
16
+
17
+ 12 pass
18
+ 0 fail
19
+ Ran 12 tests across 1 file. [3.19s]
@@ -0,0 +1,22 @@
1
+ bun test v1.4.4 (38afee6c8)
2
+
3
+ test/cli.test.js:
4
+ 731 | * Assert that two values are equal (using strict equality ===)
5
+ 732 | */
6
+ 733 | equal(actual, expected, message) {
7
+ 734 | if (actual !== expected) {
8
+ 735 | const defaultMessage = `Expected ${JSON.stringify(actual)} to equal ${JSON.stringify(expected)}`;
9
+ 736 | throw new Error(message || defaultMessage);
10
+ ^
11
+ error:
12
+ Error: Failed to get GitHub email: gh: Not Found (HTTP 404)
13
+ gh: This API operation needs the "user" scope. To request it, run: gh auth refresh -h github.com -s user
14
+
15
+ at equal (./node_modules/test-anywhere/src/index.js:736:48)
16
+ at <anonymous> (./test/cli.test.js:116:10)
17
+ (fail) CLI signs in again when an authenticated account lacks the user scope [227.20ms]
18
+
19
+ 0 pass
20
+ 8 filtered out
21
+ 1 fail
22
+ Ran 1 test across 1 file. [258.00ms]
@@ -0,0 +1,68 @@
1
+ // Replays the upstream scope hint with a real gh binary, an isolated config, and a loopback API.
2
+ // Run with Node.js and OpenSSL. The unprivileged process must be able to bind 127.0.0.1:443.
3
+ import { execFile, execFileSync } from 'node:child_process';
4
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
5
+ import { createServer } from 'node:https';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+
9
+ const gh = process.argv[2] || 'gh';
10
+ const host = '127.0.0.1';
11
+ const token = 'fixture-token';
12
+ const configDir = mkdtempSync(join(tmpdir(), 'gh-scope-hint-'));
13
+ const key = join(configDir, 'key.pem');
14
+ const cert = join(configDir, 'cert.pem');
15
+ let server;
16
+
17
+ try {
18
+ execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1',
19
+ '-subj', `/CN=${host}`, '-addext', `subjectAltName=IP:${host}`, '-keyout', key, '-out', cert], { stdio: 'pipe' });
20
+
21
+ server = createServer({ key: readFileSync(key), cert: readFileSync(cert) }, (request, response) => {
22
+ if (request.url !== '/api/v3/user/emails' || request.headers.authorization !== `token ${token}`) {
23
+ response.writeHead(500).end();
24
+ return;
25
+ }
26
+ response.writeHead(404, {
27
+ 'Content-Type': 'application/json',
28
+ 'X-Accepted-OAuth-Scopes': 'user, user:email',
29
+ 'X-OAuth-Scopes': 'repo',
30
+ }).end(JSON.stringify({ message: 'Not Found' }));
31
+ });
32
+ await new Promise((resolve, reject) => {
33
+ server.once('error', reject);
34
+ server.listen(443, host, resolve);
35
+ });
36
+
37
+ const env = {
38
+ PATH: process.env.PATH,
39
+ GH_CONFIG_DIR: configDir,
40
+ GH_ENTERPRISE_TOKEN: token,
41
+ GH_HOST: host,
42
+ NO_PROXY: host,
43
+ SSL_CERT_FILE: cert,
44
+ };
45
+ const run = (args) => new Promise((resolve, reject) => {
46
+ execFile(gh, args, { env, timeout: 10000 }, (error, stdout, stderr) => {
47
+ if (error && typeof error.code !== 'number') {
48
+ reject(error);
49
+ return;
50
+ }
51
+ const status = error?.code ?? 0;
52
+ const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
53
+ console.log(`$ gh ${args.join(' ')}\n${output}\nExit status ${status}`);
54
+ resolve({ status, stderr });
55
+ });
56
+ });
57
+
58
+ await run(['--version']);
59
+ const api = await run(['api', '--hostname', host, 'user/emails']);
60
+ const refresh = await run(['auth', 'refresh', '-h', host, '-s', 'user']);
61
+ if (api.status !== 1 || !api.stderr.includes(`gh auth refresh -h ${host} -s user`) ||
62
+ refresh.status !== 1 || !refresh.stderr.includes('GH_ENTERPRISE_TOKEN environment variable')) {
63
+ throw new Error('The scope hint or refresh result differed from the reported behavior.');
64
+ }
65
+ } finally {
66
+ if (server?.listening) await new Promise((resolve) => server.close(resolve));
67
+ rmSync(configDir, { recursive: true, force: true });
68
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gh-setup-git-identity",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "A tool to setup git identity based on current gh user",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/cli.js CHANGED
@@ -52,16 +52,16 @@ const config = makeConfig({
52
52
  description: 'Repair git identity configuration without triggering login (requires existing authentication)',
53
53
  default: false
54
54
  })
55
- .option('no-auto-login', {
55
+ .option('auto-login', {
56
56
  type: 'boolean',
57
- description: 'Disable automatic login if not authenticated (exit with error instead)',
58
- default: false
57
+ description: 'Allow automatic login and re-login (disable with --no-auto-login)',
58
+ default: true
59
59
  })
60
60
  // gh auth login options
61
61
  .option('hostname', {
62
62
  type: 'string',
63
63
  description: 'GitHub hostname to authenticate with',
64
- default: getenv('GH_AUTH_HOSTNAME', defaultAuthOptions.hostname)
64
+ default: getenv('GH_AUTH_HOSTNAME', getenv('GH_HOST', defaultAuthOptions.hostname))
65
65
  })
66
66
  .option('scopes', {
67
67
  alias: 's',
@@ -79,8 +79,8 @@ const config = makeConfig({
79
79
  .option('web', {
80
80
  alias: 'w',
81
81
  type: 'boolean',
82
- description: 'Open a browser to authenticate',
83
- default: getenv('GH_AUTH_WEB', defaultAuthOptions.web)
82
+ description: 'Open a browser to authenticate (default unless --with-token is used)',
83
+ default: getenv('GH_AUTH_WEB') === '' ? undefined : getenv('GH_AUTH_WEB', defaultAuthOptions.web)
84
84
  })
85
85
  .option('with-token', {
86
86
  type: 'boolean',
@@ -122,7 +122,7 @@ const config = makeConfig({
122
122
  .example('$0 --git-protocol ssh', 'Use SSH protocol for git operations')
123
123
  .example('$0 --with-token < token.txt', 'Authenticate using a token file')
124
124
  .example('$0 --repair', 'Repair git identity without triggering login')
125
- .example('$0 --no-auto-login', 'Fail if not authenticated instead of auto-login')
125
+ .example('$0 --no-auto-login', 'Require an existing login with email access')
126
126
  .help('h')
127
127
  .alias('h', 'help')
128
128
  .version(version)
@@ -198,27 +198,32 @@ async function main() {
198
198
  process.exit(0);
199
199
  }
200
200
 
201
- // Check if gh is authenticated
202
- const authenticated = await isGhAuthenticated({ verbose: config.verbose });
203
-
204
- // Determine if auto-login should be disabled
205
- // --repair implies no auto-login (it's meant to fix config without triggering login)
206
- // --no-auto-login explicitly disables auto-login
207
- const skipAutoLogin = config.repair || config.noAutoLogin;
201
+ const authenticated = await isGhAuthenticated({ hostname: config.hostname, verbose: config.verbose });
202
+ const skipAutoLogin = config.repair || !config.autoLogin || config.dryRun;
203
+ const authOptions = {
204
+ hostname: config.hostname,
205
+ scopes: config.scopes,
206
+ gitProtocol: config.gitProtocol,
207
+ web: config.web ?? (defaultAuthOptions.web && !config.withToken),
208
+ withToken: config.withToken,
209
+ skipSshKey: config.skipSshKey,
210
+ insecureStorage: config.insecureStorage,
211
+ clipboard: config.clipboard,
212
+ verbose: config.verbose
213
+ };
208
214
 
209
215
  if (!authenticated) {
210
216
  if (skipAutoLogin) {
211
- // In repair mode or with --no-auto-login, don't attempt to login
212
217
  console.error('GitHub CLI is not authenticated.');
218
+ console.error('');
213
219
  if (config.repair) {
214
- console.error('');
215
220
  console.error('The --repair option requires existing authentication.');
216
- console.error('Please authenticate first using one of these methods:');
221
+ } else if (config.dryRun) {
222
+ console.error('The --dry-run option requires existing authentication.');
217
223
  } else {
218
- console.error('');
219
224
  console.error('Automatic login is disabled (--no-auto-login).');
220
- console.error('Please authenticate manually using one of these methods:');
221
225
  }
226
+ console.error('Please authenticate manually using one of these methods:');
222
227
  console.error('');
223
228
  console.error(' # Option 1: Interactive web-based login');
224
229
  console.error(` gh auth login -h ${config.hostname} -s ${config.scopes} --git-protocol ${config.gitProtocol} --web`);
@@ -242,19 +247,6 @@ async function main() {
242
247
  console.log('');
243
248
  }
244
249
 
245
- // Prepare auth options from CLI arguments
246
- const authOptions = {
247
- hostname: config.hostname,
248
- scopes: config.scopes,
249
- gitProtocol: config.gitProtocol,
250
- web: config.web,
251
- withToken: config.withToken,
252
- skipSshKey: config.skipSshKey,
253
- insecureStorage: config.insecureStorage,
254
- clipboard: config.clipboard,
255
- verbose: config.verbose
256
- };
257
-
258
250
  // Automatically run gh auth login with configured options
259
251
  const loginSuccess = await runGhAuthLogin(authOptions);
260
252
 
@@ -264,37 +256,12 @@ async function main() {
264
256
  console.log(` printf "y" | gh auth login -h ${config.hostname} -s ${config.scopes} --git-protocol ${config.gitProtocol} --web`);
265
257
  process.exit(1);
266
258
  }
267
-
268
- // After successful login, setup git credential helper
269
- // This is required for HTTPS git operations to work properly
270
- const setupGitSuccess = await runGhAuthSetupGit({
271
- hostname: config.hostname,
272
- verbose: config.verbose
273
- });
274
-
275
- if (!setupGitSuccess) {
276
- console.log('');
277
- console.log('Warning: Failed to setup git credential helper. You may need to run manually:');
278
- console.log(` gh auth setup-git -h ${config.hostname}`);
279
- // Continue anyway, as identity setup might still work
280
- }
281
- } else {
282
- // Even if already authenticated, ensure git credential helper is configured
283
- // This helps fix cases where gh auth login was run but gh auth setup-git wasn't
284
- const setupGitSuccess = await runGhAuthSetupGit({
285
- hostname: config.hostname,
286
- verbose: config.verbose
287
- });
288
-
289
- if (!setupGitSuccess && config.verbose) {
290
- console.log('Note: Git credential helper may not be configured. Consider running:');
291
- console.log(` gh auth setup-git -h ${config.hostname}`);
292
- }
293
259
  }
294
260
 
295
261
  // Prepare options
296
262
  const options = {
297
263
  scope,
264
+ hostname: config.hostname,
298
265
  dryRun: config.dryRun,
299
266
  verbose: config.verbose
300
267
  };
@@ -308,8 +275,20 @@ async function main() {
308
275
  console.log('DRY MODE - No actual changes will be made');
309
276
  }
310
277
 
311
- // Setup git identity
312
- const result = await setupGitIdentity(options);
278
+ const result = await setupGitIdentity({
279
+ ...options,
280
+ // A first-time login already used this invocation's one login attempt.
281
+ authOptions: authenticated && !skipAutoLogin ? authOptions : undefined
282
+ });
283
+
284
+ if (!options.dryRun) {
285
+ const setupGitSuccess = await runGhAuthSetupGit(options);
286
+ if (!setupGitSuccess) {
287
+ console.log('');
288
+ console.log('Warning: Failed to setup git credential helper. You may need to run manually:');
289
+ console.log(` gh auth setup-git -h ${config.hostname}`);
290
+ }
291
+ }
313
292
 
314
293
  // Display results
315
294
  console.log('');
package/src/index.js CHANGED
@@ -101,7 +101,7 @@ function execInteractiveCommand(command, args = [], options = {}) {
101
101
 
102
102
  child.on('close', (exitCode) => {
103
103
  resolve({
104
- exitCode: exitCode || 0
104
+ exitCode: exitCode ?? 1
105
105
  });
106
106
  });
107
107
 
@@ -169,7 +169,7 @@ export async function runGhAuthLogin(options = {}) {
169
169
  }
170
170
 
171
171
  // Add scopes
172
- if (scopes) {
172
+ if (scopes && !withToken) {
173
173
  args.push('-s', scopes);
174
174
  }
175
175
 
@@ -268,17 +268,28 @@ export async function runGhAuthSetupGit(options = {}) {
268
268
  * Check if GitHub CLI is authenticated
269
269
  *
270
270
  * @param {Object} options - Options
271
+ * @param {string} options.hostname - Check the active account for this host
271
272
  * @param {boolean} options.verbose - Enable verbose logging
272
273
  * @param {Object} options.logger - Custom logger
273
274
  * @returns {Promise<boolean>} True if authenticated
274
275
  */
275
276
  export async function isGhAuthenticated(options = {}) {
276
- const { verbose = false, logger = console } = options;
277
+ const { hostname, verbose = false, logger = console } = options;
277
278
  const log = createDefaultLogger({ verbose, logger });
279
+ const args = ['auth', 'status'];
280
+ if (hostname) {
281
+ args.push('--hostname', hostname, '--active');
282
+ }
278
283
 
279
- log.debug(() => 'Checking GitHub CLI authentication status...');
284
+ log.debug(() => `Running: gh ${args.join(' ')}`);
280
285
 
281
- const result = await execCommand('gh', ['auth', 'status']);
286
+ let result = await execCommand('gh', args);
287
+ if (hostname && result.exitCode !== 0 && /^unknown flag: --active\r?$/m.test(result.stderr)) {
288
+ // Older GitHub CLI releases can scope status to a host but cannot filter by active account.
289
+ args.pop();
290
+ log.debug(() => `Running: gh ${args.join(' ')}`);
291
+ result = await execCommand('gh', args);
292
+ }
282
293
 
283
294
  if (result.exitCode !== 0) {
284
295
  log.debug(() => `GitHub CLI is not authenticated: ${result.stderr}`);
@@ -293,17 +304,18 @@ export async function isGhAuthenticated(options = {}) {
293
304
  * Get GitHub username from authenticated user
294
305
  *
295
306
  * @param {Object} options - Options
307
+ * @param {string} options.hostname - GitHub hostname (defaults to gh's API host)
296
308
  * @param {boolean} options.verbose - Enable verbose logging
297
309
  * @param {Object} options.logger - Custom logger
298
310
  * @returns {Promise<string>} GitHub username
299
311
  */
300
312
  export async function getGitHubUsername(options = {}) {
301
- const { verbose = false, logger = console } = options;
313
+ const { hostname, verbose = false, logger = console } = options;
302
314
  const log = createDefaultLogger({ verbose, logger });
303
315
 
304
316
  log.debug(() => 'Getting GitHub username...');
305
317
 
306
- const result = await execCommand('gh', ['api', 'user', '--jq', '.login']);
318
+ const result = await queryGitHub('user', '.login', hostname);
307
319
 
308
320
  if (result.exitCode !== 0) {
309
321
  throw new Error(`Failed to get GitHub username: ${result.stderr}`);
@@ -315,23 +327,58 @@ export async function getGitHubUsername(options = {}) {
315
327
  return username;
316
328
  }
317
329
 
330
+ function queryGitHub(endpoint, filter, hostname) {
331
+ const args = ['api', endpoint, '--jq', filter];
332
+ if (hostname) {
333
+ args.push('--hostname', hostname);
334
+ }
335
+ return execCommand('gh', args);
336
+ }
337
+
338
+ function environmentTokenVariable(hostname) {
339
+ const host = (hostname || process.env.GH_HOST || defaultAuthOptions.hostname).toLowerCase();
340
+ const useCloudToken = /(?:^|\.)(?:github\.com|github\.localhost)$|\.ghe\.com$/.test(host);
341
+ const names = useCloudToken
342
+ ? ['GH_TOKEN', 'GITHUB_TOKEN']
343
+ : ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'];
344
+ return names.find((name) => process.env[name]);
345
+ }
346
+
347
+ class GitHubEmailPermissionError extends Error {
348
+ constructor(stderr, requiredScope, tokenVariable) {
349
+ const guidance = tokenVariable
350
+ ? `\nRemove or replace ${tokenVariable}. Use a classic token with user:email (or user), or a fine-grained token with Email addresses: Read.`
351
+ : '';
352
+ super(`Failed to get GitHub email: ${stderr}${guidance}`);
353
+ this.requiredScope = requiredScope;
354
+ this.tokenVariable = tokenVariable;
355
+ }
356
+ }
357
+
318
358
  /**
319
359
  * Get primary email from GitHub user
320
360
  *
321
361
  * @param {Object} options - Options
362
+ * @param {string} options.hostname - GitHub hostname (defaults to gh's API host)
322
363
  * @param {boolean} options.verbose - Enable verbose logging
323
364
  * @param {Object} options.logger - Custom logger
324
365
  * @returns {Promise<string>} Primary email address
325
366
  */
326
367
  export async function getGitHubEmail(options = {}) {
327
- const { verbose = false, logger = console } = options;
368
+ const { hostname, verbose = false, logger = console } = options;
328
369
  const log = createDefaultLogger({ verbose, logger });
329
370
 
330
371
  log.debug(() => 'Getting GitHub primary email...');
331
372
 
332
- const result = await execCommand('gh', ['api', 'user/emails', '--jq', '.[] | select(.primary==true) | .email']);
373
+ const result = await queryGitHub('user/emails', '.[] | select(.primary==true) | .email', hostname);
333
374
 
334
375
  if (result.exitCode !== 0) {
376
+ const scope = result.stderr.match(/^gh: This API operation needs the "(user(?::email)?)" scope\./m)?.[1];
377
+ const tokenDenied = /^gh: Resource not accessible by (?:personal access token|integration) \(HTTP 403\)$/m.test(result.stderr);
378
+ if (scope || tokenDenied) {
379
+ const tokenVariable = environmentTokenVariable(hostname);
380
+ throw new GitHubEmailPermissionError(result.stderr, scope || 'user:email', tokenVariable);
381
+ }
335
382
  throw new Error(`Failed to get GitHub email: ${result.stderr}`);
336
383
  }
337
384
 
@@ -350,17 +397,20 @@ export async function getGitHubEmail(options = {}) {
350
397
  * Get GitHub user information (username and primary email)
351
398
  *
352
399
  * @param {Object} options - Options
400
+ * @param {string} options.hostname - GitHub hostname (defaults to gh's API host)
353
401
  * @param {boolean} options.verbose - Enable verbose logging
354
402
  * @param {Object} options.logger - Custom logger
355
403
  * @returns {Promise<{username: string, email: string}>} User information
356
404
  */
357
405
  export async function getGitHubUserInfo(options = {}) {
358
- const [username, email] = await Promise.all([
406
+ const [username, email] = await Promise.allSettled([
359
407
  getGitHubUsername(options),
360
408
  getGitHubEmail(options)
361
409
  ]);
362
410
 
363
- return { username, email };
411
+ if (username.status === 'rejected') throw username.reason;
412
+ if (email.status === 'rejected') throw email.reason;
413
+ return { username: username.value, email: email.value };
364
414
  }
365
415
 
366
416
  /**
@@ -426,6 +476,8 @@ export async function getGitConfig(key, options = {}) {
426
476
  * Setup git identity based on GitHub user
427
477
  *
428
478
  * @param {Object} options - Options
479
+ * @param {string} options.hostname - GitHub hostname (defaults to gh's API host without authOptions)
480
+ * @param {Object} options.authOptions - Opt in to one login on an email permission error, with runGhAuthLogin options
429
481
  * @param {string} options.scope - 'global' or 'local' (default: 'global')
430
482
  * @param {boolean} options.dryRun - Dry run mode (default: false)
431
483
  * @param {boolean} options.verbose - Enable verbose logging (default: false)
@@ -436,16 +488,39 @@ export async function setupGitIdentity(options = {}) {
436
488
  const {
437
489
  scope = 'global',
438
490
  dryRun = false,
491
+ authOptions,
439
492
  verbose = false,
440
493
  logger = console
441
494
  } = options;
442
495
 
496
+ const hostname = options.hostname ?? authOptions?.hostname ?? (authOptions ? defaultAuthOptions.hostname : undefined);
443
497
  const log = createDefaultLogger({ verbose, logger });
498
+ const userInfoOptions = { hostname, verbose, logger };
444
499
 
445
500
  log(() => '\nFetching GitHub user information...');
446
501
 
447
- // Get GitHub user info
448
- const { username, email } = await getGitHubUserInfo({ verbose, logger });
502
+ let identity;
503
+ try {
504
+ identity = await getGitHubUserInfo(userInfoOptions);
505
+ } catch (error) {
506
+ if (!(error instanceof GitHubEmailPermissionError) || !authOptions || dryRun || error.tokenVariable) {
507
+ throw error;
508
+ }
509
+
510
+ log.debug(() => `GitHub email lookup failed on ${hostname}: ${error.message}`);
511
+ log(() => 'The current GitHub credential cannot read your email addresses. Starting authentication...');
512
+ const scopes = (authOptions.scopes ?? defaultAuthOptions.scopes).split(',').map((value) => value.trim()).filter(Boolean);
513
+ if (!scopes.includes('user') && !scopes.includes('user:email')) {
514
+ scopes.push(error.requiredScope);
515
+ }
516
+ const loginSuccess = await runGhAuthLogin({ ...authOptions, hostname, scopes: scopes.join(','), verbose, logger });
517
+ if (!loginSuccess) throw error;
518
+
519
+ log.debug(() => `Retrying GitHub username and primary email lookup on ${hostname}`);
520
+ // Login can change the active account, so refetch both identity fields.
521
+ identity = await getGitHubUserInfo(userInfoOptions);
522
+ }
523
+ const { username, email } = identity;
449
524
 
450
525
  log(() => ` GitHub user: ${username}`);
451
526
  log(() => ` GitHub email: ${email}`);
package/test/cli.test.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Regression tests for the CLI version output
2
+ * Regression tests for the CLI
3
3
  */
4
4
 
5
5
  import { test, assert } from 'test-anywhere';
6
- import { execFileSync } from 'node:child_process';
6
+ import { execFileSync, spawnSync } from 'node:child_process';
7
7
  import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { join } from 'node:path';
@@ -35,3 +35,223 @@ test('CLI --version uses its own package from an unrelated directory', () => {
35
35
  rmSync(cwd, { recursive: true, force: true });
36
36
  }
37
37
  });
38
+
39
+ const mockCommands = `#!/bin/sh
40
+ name=$(basename "$0")
41
+ printf '%s %s\\n' "$name" "$*" >> "$MOCK_CALLS"
42
+ case "$name:$1:$2" in
43
+ git:config:*) exit 0 ;;
44
+ gh:auth:status)
45
+ if [ "$MOCK_SCENARIO" = legacy-gh ] && [ "$5" = --active ]; then
46
+ echo 'unknown flag: --active' >&2
47
+ exit 1
48
+ fi
49
+ case "$MOCK_SCENARIO" in signed-out|fresh-login) exit 1 ;; esac ;;
50
+ gh:auth:login)
51
+ test "$MOCK_SCENARIO" != cancel || exit 1
52
+ case " $* " in
53
+ *' --with-token '*)
54
+ case " $* " in *' -s '*|*' --web '*) exit 2 ;; esac
55
+ read -r token
56
+ test "$token" = fixture-token || exit 2 ;;
57
+ esac
58
+ touch "$MOCK_LOGIN"
59
+ ;;
60
+ gh:auth:setup-git) exit 0 ;;
61
+ gh:api:user)
62
+ if [ -e "$MOCK_LOGIN" ]; then echo new-account; else echo old-account; fi ;;
63
+ gh:api:user/emails)
64
+ if [ "$MOCK_SCENARIO" = healthy ]; then
65
+ echo old@example.test
66
+ elif [ -e "$MOCK_LOGIN" ] && [ "$MOCK_SCENARIO" != persistent ] && [ "$MOCK_SCENARIO" != signed-out ]; then
67
+ echo new@example.test
68
+ elif [ "$MOCK_SCENARIO" = no-primary ]; then
69
+ exit 0
70
+ elif [ "$MOCK_SCENARIO" = bare-404 ]; then
71
+ echo 'gh: Not Found (HTTP 404)' >&2
72
+ exit 1
73
+ elif [ "$MOCK_SCENARIO" = pat-denied ]; then
74
+ echo 'gh: Resource not accessible by personal access token (HTTP 403)' >&2
75
+ exit 1
76
+ else
77
+ echo 'gh: Not Found (HTTP 404)' >&2
78
+ printf 'gh: This API operation needs the "%s" scope. To request it, run: gh auth refresh -h github.com -s %s\\n' "$MOCK_SCOPE" "$MOCK_SCOPE" >&2
79
+ exit 1
80
+ fi ;;
81
+ *) echo "Unexpected command: $name $*" >&2; exit 2 ;;
82
+ esac
83
+ `;
84
+
85
+ function runCliWithMockAuth(scenario, args = [], { scope = 'user', env = {}, input, entrypoint = [cliPath] } = {}) {
86
+ const cwd = mkdtempSync(join(tmpdir(), 'gh-setup-git-identity-auth-'));
87
+ const callsFile = join(cwd, 'calls');
88
+ try {
89
+ writeFileSync(join(cwd, 'gh'), mockCommands, { mode: 0o755 });
90
+ writeFileSync(join(cwd, 'git'), mockCommands, { mode: 0o755 });
91
+ writeFileSync(callsFile, '');
92
+ const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
93
+ !/^(GH_|GITHUB_(?:ENTERPRISE_)?TOKEN$)/.test(key)
94
+ ));
95
+ const result = spawnSync(process.execPath, [...entrypoint, ...args], {
96
+ cwd,
97
+ encoding: 'utf8',
98
+ timeout: 10000,
99
+ input,
100
+ env: {
101
+ ...cleanEnv,
102
+ PATH: `${cwd}:${cleanEnv.PATH}`,
103
+ MOCK_CALLS: callsFile,
104
+ MOCK_LOGIN: join(cwd, 'login'),
105
+ MOCK_SCENARIO: scenario,
106
+ MOCK_SCOPE: scope,
107
+ ...env
108
+ }
109
+ });
110
+ if (result.error) throw result.error;
111
+ return { ...result, calls: readFileSync(callsFile, 'utf8').trim().split('\n').filter(Boolean) };
112
+ } finally {
113
+ rmSync(cwd, { recursive: true, force: true });
114
+ }
115
+ }
116
+
117
+ const loginCalls = (calls) => calls.filter((call) => call.startsWith('gh auth login '));
118
+ const configCalls = (calls) => calls.filter((call) => call.startsWith('git config '));
119
+
120
+ test('CLI signs in again when an authenticated account lacks the user scope', () => {
121
+ const { status, stdout, stderr, calls } = runCliWithMockAuth('missing-scope');
122
+ assert.equal(status, 0, stderr);
123
+ assert.deepEqual(loginCalls(calls), [
124
+ 'gh auth login -h github.com -s repo,workflow,user,read:org,gist --git-protocol https --web'
125
+ ]);
126
+ assert.equal(calls.filter((call) => call.startsWith('gh api user --')).length, 2);
127
+ assert.equal(calls.filter((call) => call.startsWith('gh api user/emails ')).length, 2);
128
+ assert.deepEqual(configCalls(calls), [
129
+ 'git config --global user.name new-account',
130
+ 'git config --global user.email new@example.test'
131
+ ]);
132
+ assert.equal(calls.filter((call) => call === 'gh auth setup-git -h github.com').length, 1);
133
+ assert.ok(calls.indexOf('gh auth setup-git -h github.com') > calls.indexOf(loginCalls(calls)[0]));
134
+ assert.ok(stdout.includes('Git identity setup complete!'));
135
+ });
136
+
137
+ test('CLI recovery uses the selected host, flags, scopes and local Git configuration', () => {
138
+ const { status, stderr, calls } = runCliWithMockAuth('missing-scope', [
139
+ '--hostname', 'enterprise.example.test', '--scopes', 'repo, workflow',
140
+ '--git-protocol', 'ssh', '--skip-ssh-key', '--insecure-storage', '--clipboard', '--local'
141
+ ], { scope: 'user:email' });
142
+ assert.equal(status, 0, stderr);
143
+ assert.deepEqual(loginCalls(calls), [
144
+ 'gh auth login -h enterprise.example.test -s repo,workflow,user:email --git-protocol ssh --web --skip-ssh-key --insecure-storage --clipboard'
145
+ ]);
146
+ assert.ok(calls.includes('gh auth status --hostname enterprise.example.test --active'));
147
+ const apiCalls = calls.filter((call) => call.startsWith('gh api '));
148
+ assert.equal(apiCalls.length, 4);
149
+ assert.ok(apiCalls.every((call) => call.includes('--hostname enterprise.example.test')));
150
+ assert.ok(calls.includes('gh auth setup-git -h enterprise.example.test'));
151
+ assert.deepEqual(configCalls(calls), [
152
+ 'git config --local user.name new-account',
153
+ 'git config --local user.email new@example.test'
154
+ ]);
155
+ });
156
+
157
+ test('CLI keeps the original authentication failure when recovery is disabled', () => {
158
+ for (const option of ['--repair', '--no-auto-login', '--dry-run']) {
159
+ const { status, stderr, calls } = runCliWithMockAuth('missing-scope', [option]);
160
+ assert.equal(status, 1, option);
161
+ assert.ok(stderr.includes('This API operation needs the "user" scope.'));
162
+ assert.deepEqual(loginCalls(calls), []);
163
+ assert.deepEqual(configCalls(calls), []);
164
+ }
165
+ });
166
+
167
+ test('CLI attempts recovery once when login is canceled or permissions remain missing', () => {
168
+ for (const scenario of ['cancel', 'persistent', 'signed-out']) {
169
+ const { status, stderr, calls } = runCliWithMockAuth(scenario);
170
+ assert.equal(status, 1, scenario);
171
+ assert.ok(stderr.includes('This API operation needs the "user" scope.'));
172
+ assert.equal(loginCalls(calls).length, 1);
173
+ assert.deepEqual(configCalls(calls), []);
174
+ }
175
+ });
176
+
177
+ test('CLI leaves unrelated failures and a usable account on the existing path', () => {
178
+ for (const scenario of ['bare-404', 'no-primary', 'healthy']) {
179
+ const { status, calls } = runCliWithMockAuth(scenario);
180
+ assert.equal(status, scenario === 'healthy' ? 0 : 1, scenario);
181
+ assert.deepEqual(loginCalls(calls), []);
182
+ assert.equal(configCalls(calls).length, scenario === 'healthy' ? 2 : 0);
183
+ }
184
+ });
185
+
186
+ test('CLI keeps dry-run read-only and retains first-time login', () => {
187
+ const preview = runCliWithMockAuth('healthy', ['--dry-run']);
188
+ assert.equal(preview.status, 0, preview.stderr);
189
+ assert.ok(preview.stdout.includes('[DRY MODE] Would configure'));
190
+ assert.deepEqual(loginCalls(preview.calls), []);
191
+ assert.deepEqual(configCalls(preview.calls), []);
192
+ assert.ok(!preview.calls.some((call) => call.startsWith('gh auth setup-git ')));
193
+
194
+ for (const option of ['--repair', '--no-auto-login', '--dry-run']) {
195
+ const signedOut = runCliWithMockAuth('fresh-login', [option]);
196
+ assert.equal(signedOut.status, 1, option);
197
+ assert.ok(signedOut.stderr.includes('GitHub CLI is not authenticated.'));
198
+ assert.deepEqual(loginCalls(signedOut.calls), []);
199
+ }
200
+
201
+ const firstRun = runCliWithMockAuth('fresh-login');
202
+ assert.equal(firstRun.status, 0, firstRun.stderr);
203
+ assert.equal(loginCalls(firstRun.calls).length, 1);
204
+ assert.equal(configCalls(firstRun.calls).length, 2);
205
+ });
206
+
207
+ test('CLI still recovers with gh versions without the active-account status flag', () => {
208
+ const { status, stderr, calls } = runCliWithMockAuth('legacy-gh');
209
+ assert.equal(status, 0, stderr);
210
+ assert.deepEqual(calls.slice(0, 2), [
211
+ 'gh auth status --hostname github.com --active',
212
+ 'gh auth status --hostname github.com'
213
+ ]);
214
+ assert.equal(loginCalls(calls).length, 1);
215
+ });
216
+
217
+ test('CLI explains how to replace an environment token lacking email permission', () => {
218
+ const { status, stderr, calls } = runCliWithMockAuth('pat-denied', [], {
219
+ env: { GH_TOKEN: 'fixture-environment-token' }
220
+ });
221
+ assert.equal(status, 1);
222
+ assert.ok(stderr.includes('Remove or replace GH_TOKEN'));
223
+ assert.ok(stderr.includes('Email addresses: Read'));
224
+ assert.ok(!stderr.includes('fixture-environment-token'));
225
+ assert.deepEqual(loginCalls(calls), []);
226
+ assert.deepEqual(configCalls(calls), []);
227
+ });
228
+
229
+ test('CLI can read a replacement token from stdin during recovery', () => {
230
+ const { status, stderr, calls } = runCliWithMockAuth('missing-scope', ['--with-token'], {
231
+ input: 'fixture-token\n'
232
+ });
233
+ assert.equal(status, 0, stderr);
234
+ assert.deepEqual(loginCalls(calls), [
235
+ 'gh auth login -h github.com --git-protocol https --with-token'
236
+ ]);
237
+ });
238
+
239
+ test('Library callers opt in to interactive recovery through setupGitIdentity', () => {
240
+ const moduleUrl = new URL('../src/index.js', import.meta.url).href;
241
+ const runLibrary = (options) => runCliWithMockAuth('missing-scope', [], {
242
+ entrypoint: ['--eval', `import { setupGitIdentity } from ${JSON.stringify(moduleUrl)};
243
+ await setupGitIdentity(${JSON.stringify(options)});`]
244
+ });
245
+
246
+ const noninteractive = runLibrary({});
247
+ assert.equal(noninteractive.status, 1);
248
+ assert.ok(noninteractive.stderr.includes('This API operation needs the "user" scope.'));
249
+ assert.deepEqual(loginCalls(noninteractive.calls), []);
250
+ assert.deepEqual(configCalls(noninteractive.calls), []);
251
+
252
+ const interactive = runLibrary({ authOptions: { hostname: 'enterprise.example.test' } });
253
+ assert.equal(interactive.status, 0, interactive.stderr);
254
+ assert.equal(loginCalls(interactive.calls).length, 1);
255
+ assert.ok(loginCalls(interactive.calls)[0].startsWith('gh auth login -h enterprise.example.test '));
256
+ assert.equal(configCalls(interactive.calls).length, 2);
257
+ });
@@ -176,20 +176,3 @@ test('default export contains all functions', async () => {
176
176
  assert.ok(typeof defaultExport.setupGitIdentity === 'function');
177
177
  assert.ok(typeof defaultExport.verifyGitIdentity === 'function');
178
178
  });
179
-
180
- // Test: CLI --repair and --no-auto-login options are present
181
- // Note: Full CLI integration tests would require mocking the subprocess
182
- test('CLI module has --repair and --no-auto-login options', async () => {
183
- // This test verifies the CLI module syntax is correct and options exist
184
- const fs = await import('node:fs');
185
- const cliContent = fs.readFileSync(new URL('../src/cli.js', import.meta.url), 'utf-8');
186
-
187
- // Verify the new options are defined in the CLI
188
- assert.ok(cliContent.includes("'repair'"), 'CLI should have --repair option');
189
- assert.ok(cliContent.includes("'no-auto-login'"), 'CLI should have --no-auto-login option');
190
-
191
- // Verify the repair/no-auto-login logic is implemented
192
- assert.ok(cliContent.includes('skipAutoLogin'), 'CLI should have skipAutoLogin logic');
193
- assert.ok(cliContent.includes('config.repair'), 'CLI should check config.repair');
194
- assert.ok(cliContent.includes('config.noAutoLogin'), 'CLI should check config.noAutoLogin');
195
- });