gh-setup-git-identity 0.8.0 → 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/.github/workflows/release.yml +31 -0
- package/CHANGELOG.md +12 -0
- package/README.md +22 -8
- package/docs/case-studies/issue-32/README.md +162 -0
- package/docs/case-studies/issue-32/raw-logs/bun-add-command-stream-2.0.0-no-toolchain.txt +47 -0
- package/docs/case-studies/issue-32/raw-logs/bun-add-command-stream-2.4.0-no-toolchain.txt +10 -0
- package/docs/case-studies/issue-32/raw-logs/ci-run-37733836425-release-failed.txt +252 -0
- package/docs/case-studies/issue-32/raw-logs/command-stream-exit-codes.txt +4 -0
- package/docs/case-studies/issue-32/raw-logs/dry-run-fixed-publish-fails.txt +91 -0
- package/docs/case-studies/issue-32/raw-logs/dry-run-main-publish-fails.txt +81 -0
- package/docs/case-studies/issue-32/raw-logs/dry-run-rerun-after-fix.txt +195 -0
- package/docs/case-studies/issue-32/raw-logs/dry-run-rerun-before-fix.txt +198 -0
- package/docs/case-studies/issue-32/raw-logs/npm-registry-facts.txt +28 -0
- package/docs/case-studies/issue-32/raw-logs/setup-npm-fixed-node20.txt +8 -0
- package/docs/case-studies/issue-32/raw-logs/setup-npm-main-node20.txt +12 -0
- package/docs/case-studies/issue-34/README.md +53 -0
- package/docs/case-studies/issue-34/raw-logs/email-endpoint-headers.txt +5 -0
- package/docs/case-studies/issue-34/raw-logs/gh-2.102.0-scope-hint.txt +13 -0
- package/docs/case-studies/issue-34/raw-logs/gh-2.105.0-scope-hint.txt +13 -0
- package/docs/case-studies/issue-34/raw-logs/issue-report.txt +46 -0
- package/docs/case-studies/issue-34/raw-logs/prepared-pr-changeset-check.txt +3 -0
- package/docs/case-studies/issue-34/raw-logs/regression-after.txt +19 -0
- package/docs/case-studies/issue-34/raw-logs/regression-before.txt +22 -0
- package/experiments/issue-32-command-stream-exit-codes.mjs +27 -0
- package/experiments/issue-32-pinned-helpers.mjs +27 -0
- package/experiments/issue-32-release-dry-run.sh +66 -0
- package/experiments/issue-34-gh-scope-hint.mjs +68 -0
- package/package.json +1 -1
- package/scripts/changeset-version.mjs +8 -4
- package/scripts/create-github-release.mjs +8 -5
- package/scripts/create-manual-changeset.mjs +4 -5
- package/scripts/format-github-release.mjs +5 -5
- package/scripts/format-release-notes.mjs +5 -5
- package/scripts/instant-version-bump.mjs +8 -5
- package/scripts/publish-to-npm.mjs +18 -12
- package/scripts/release-deps.mjs +21 -0
- package/scripts/report-release-failure.mjs +143 -0
- package/scripts/setup-npm.mjs +80 -27
- package/scripts/version-and-commit.mjs +22 -5
- package/src/cli.js +43 -61
- package/src/index.js +88 -13
- package/test/cli.test.js +257 -0
- package/test/index.test.js +0 -17
- package/test/release-scripts.test.js +232 -0
package/src/cli.js
CHANGED
|
@@ -6,9 +6,12 @@
|
|
|
6
6
|
* Command-line interface for setting up git identity based on GitHub user
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
9
10
|
import { makeConfig } from 'lino-arguments';
|
|
10
11
|
import { setupGitIdentity, isGhAuthenticated, runGhAuthLogin, runGhAuthSetupGit, verifyGitIdentity, defaultAuthOptions } from './index.js';
|
|
11
12
|
|
|
13
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
14
|
+
|
|
12
15
|
// Parse command-line arguments with environment variable and .lenv support
|
|
13
16
|
const config = makeConfig({
|
|
14
17
|
yargs: ({ yargs, getenv }) =>
|
|
@@ -49,16 +52,16 @@ const config = makeConfig({
|
|
|
49
52
|
description: 'Repair git identity configuration without triggering login (requires existing authentication)',
|
|
50
53
|
default: false
|
|
51
54
|
})
|
|
52
|
-
.option('
|
|
55
|
+
.option('auto-login', {
|
|
53
56
|
type: 'boolean',
|
|
54
|
-
description: '
|
|
55
|
-
default:
|
|
57
|
+
description: 'Allow automatic login and re-login (disable with --no-auto-login)',
|
|
58
|
+
default: true
|
|
56
59
|
})
|
|
57
60
|
// gh auth login options
|
|
58
61
|
.option('hostname', {
|
|
59
62
|
type: 'string',
|
|
60
63
|
description: 'GitHub hostname to authenticate with',
|
|
61
|
-
default: getenv('GH_AUTH_HOSTNAME', defaultAuthOptions.hostname)
|
|
64
|
+
default: getenv('GH_AUTH_HOSTNAME', getenv('GH_HOST', defaultAuthOptions.hostname))
|
|
62
65
|
})
|
|
63
66
|
.option('scopes', {
|
|
64
67
|
alias: 's',
|
|
@@ -76,8 +79,8 @@ const config = makeConfig({
|
|
|
76
79
|
.option('web', {
|
|
77
80
|
alias: 'w',
|
|
78
81
|
type: 'boolean',
|
|
79
|
-
description: 'Open a browser to authenticate',
|
|
80
|
-
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)
|
|
81
84
|
})
|
|
82
85
|
.option('with-token', {
|
|
83
86
|
type: 'boolean',
|
|
@@ -119,10 +122,10 @@ const config = makeConfig({
|
|
|
119
122
|
.example('$0 --git-protocol ssh', 'Use SSH protocol for git operations')
|
|
120
123
|
.example('$0 --with-token < token.txt', 'Authenticate using a token file')
|
|
121
124
|
.example('$0 --repair', 'Repair git identity without triggering login')
|
|
122
|
-
.example('$0 --no-auto-login', '
|
|
125
|
+
.example('$0 --no-auto-login', 'Require an existing login with email access')
|
|
123
126
|
.help('h')
|
|
124
127
|
.alias('h', 'help')
|
|
125
|
-
.version(
|
|
128
|
+
.version(version)
|
|
126
129
|
.strict(),
|
|
127
130
|
});
|
|
128
131
|
|
|
@@ -195,27 +198,32 @@ async function main() {
|
|
|
195
198
|
process.exit(0);
|
|
196
199
|
}
|
|
197
200
|
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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
|
+
};
|
|
205
214
|
|
|
206
215
|
if (!authenticated) {
|
|
207
216
|
if (skipAutoLogin) {
|
|
208
|
-
// In repair mode or with --no-auto-login, don't attempt to login
|
|
209
217
|
console.error('GitHub CLI is not authenticated.');
|
|
218
|
+
console.error('');
|
|
210
219
|
if (config.repair) {
|
|
211
|
-
console.error('');
|
|
212
220
|
console.error('The --repair option requires existing authentication.');
|
|
213
|
-
|
|
221
|
+
} else if (config.dryRun) {
|
|
222
|
+
console.error('The --dry-run option requires existing authentication.');
|
|
214
223
|
} else {
|
|
215
|
-
console.error('');
|
|
216
224
|
console.error('Automatic login is disabled (--no-auto-login).');
|
|
217
|
-
console.error('Please authenticate manually using one of these methods:');
|
|
218
225
|
}
|
|
226
|
+
console.error('Please authenticate manually using one of these methods:');
|
|
219
227
|
console.error('');
|
|
220
228
|
console.error(' # Option 1: Interactive web-based login');
|
|
221
229
|
console.error(` gh auth login -h ${config.hostname} -s ${config.scopes} --git-protocol ${config.gitProtocol} --web`);
|
|
@@ -239,19 +247,6 @@ async function main() {
|
|
|
239
247
|
console.log('');
|
|
240
248
|
}
|
|
241
249
|
|
|
242
|
-
// Prepare auth options from CLI arguments
|
|
243
|
-
const authOptions = {
|
|
244
|
-
hostname: config.hostname,
|
|
245
|
-
scopes: config.scopes,
|
|
246
|
-
gitProtocol: config.gitProtocol,
|
|
247
|
-
web: config.web,
|
|
248
|
-
withToken: config.withToken,
|
|
249
|
-
skipSshKey: config.skipSshKey,
|
|
250
|
-
insecureStorage: config.insecureStorage,
|
|
251
|
-
clipboard: config.clipboard,
|
|
252
|
-
verbose: config.verbose
|
|
253
|
-
};
|
|
254
|
-
|
|
255
250
|
// Automatically run gh auth login with configured options
|
|
256
251
|
const loginSuccess = await runGhAuthLogin(authOptions);
|
|
257
252
|
|
|
@@ -261,37 +256,12 @@ async function main() {
|
|
|
261
256
|
console.log(` printf "y" | gh auth login -h ${config.hostname} -s ${config.scopes} --git-protocol ${config.gitProtocol} --web`);
|
|
262
257
|
process.exit(1);
|
|
263
258
|
}
|
|
264
|
-
|
|
265
|
-
// After successful login, setup git credential helper
|
|
266
|
-
// This is required for HTTPS git operations to work properly
|
|
267
|
-
const setupGitSuccess = await runGhAuthSetupGit({
|
|
268
|
-
hostname: config.hostname,
|
|
269
|
-
verbose: config.verbose
|
|
270
|
-
});
|
|
271
|
-
|
|
272
|
-
if (!setupGitSuccess) {
|
|
273
|
-
console.log('');
|
|
274
|
-
console.log('Warning: Failed to setup git credential helper. You may need to run manually:');
|
|
275
|
-
console.log(` gh auth setup-git -h ${config.hostname}`);
|
|
276
|
-
// Continue anyway, as identity setup might still work
|
|
277
|
-
}
|
|
278
|
-
} else {
|
|
279
|
-
// Even if already authenticated, ensure git credential helper is configured
|
|
280
|
-
// This helps fix cases where gh auth login was run but gh auth setup-git wasn't
|
|
281
|
-
const setupGitSuccess = await runGhAuthSetupGit({
|
|
282
|
-
hostname: config.hostname,
|
|
283
|
-
verbose: config.verbose
|
|
284
|
-
});
|
|
285
|
-
|
|
286
|
-
if (!setupGitSuccess && config.verbose) {
|
|
287
|
-
console.log('Note: Git credential helper may not be configured. Consider running:');
|
|
288
|
-
console.log(` gh auth setup-git -h ${config.hostname}`);
|
|
289
|
-
}
|
|
290
259
|
}
|
|
291
260
|
|
|
292
261
|
// Prepare options
|
|
293
262
|
const options = {
|
|
294
263
|
scope,
|
|
264
|
+
hostname: config.hostname,
|
|
295
265
|
dryRun: config.dryRun,
|
|
296
266
|
verbose: config.verbose
|
|
297
267
|
};
|
|
@@ -305,8 +275,20 @@ async function main() {
|
|
|
305
275
|
console.log('DRY MODE - No actual changes will be made');
|
|
306
276
|
}
|
|
307
277
|
|
|
308
|
-
|
|
309
|
-
|
|
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
|
+
}
|
|
310
292
|
|
|
311
293
|
// Display results
|
|
312
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
|
|
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(() =>
|
|
284
|
+
log.debug(() => `Running: gh ${args.join(' ')}`);
|
|
280
285
|
|
|
281
|
-
|
|
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
|
|
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
|
|
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.
|
|
406
|
+
const [username, email] = await Promise.allSettled([
|
|
359
407
|
getGitHubUsername(options),
|
|
360
408
|
getGitHubEmail(options)
|
|
361
409
|
]);
|
|
362
410
|
|
|
363
|
-
|
|
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
|
-
|
|
448
|
-
|
|
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
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression tests for the CLI
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { test, assert } from 'test-anywhere';
|
|
6
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
7
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
const cliPath = fileURLToPath(new URL('../src/cli.js', import.meta.url));
|
|
13
|
+
const packageDir = fileURLToPath(new URL('../', import.meta.url));
|
|
14
|
+
const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
15
|
+
|
|
16
|
+
function cliVersion(cwd) {
|
|
17
|
+
return execFileSync(process.execPath, [cliPath, '--version'], {
|
|
18
|
+
cwd,
|
|
19
|
+
encoding: 'utf8',
|
|
20
|
+
timeout: 10000,
|
|
21
|
+
stdio: 'pipe'
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test('CLI --version matches the package version', () => {
|
|
26
|
+
assert.equal(cliVersion(packageDir), `${version}\n`);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('CLI --version uses its own package from an unrelated directory', () => {
|
|
30
|
+
const cwd = mkdtempSync(join(tmpdir(), 'gh-setup-git-identity-version-'));
|
|
31
|
+
try {
|
|
32
|
+
writeFileSync(join(cwd, 'package.json'), JSON.stringify({ version: '99.99.99' }));
|
|
33
|
+
assert.equal(cliVersion(cwd), `${version}\n`);
|
|
34
|
+
} finally {
|
|
35
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
36
|
+
}
|
|
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
|
+
});
|
package/test/index.test.js
CHANGED
|
@@ -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
|
-
});
|