|
| 1 | +/* eslint-disable no-console */ |
| 2 | +/** |
| 3 | + * CLI command for GitHub OAuth authentication |
| 4 | + * |
| 5 | + * This file contains the user interaction and CLI-specific logic for GitHub authentication. |
| 6 | + * It uses the core GitHub OAuth utilities from utils/github.mjs. |
| 7 | + */ |
| 8 | + |
| 9 | +import chalk from 'chalk'; |
| 10 | +import * as client from 'openid-client'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Interactive GitHub authentication with user prompts and device flow |
| 14 | + * |
| 15 | + * @param {import('../utils/github.mjs')} gh - GitHub utility module |
| 16 | + * @returns {Promise<void>} |
| 17 | + */ |
| 18 | +async function authenticateWithGitHub(gh) { |
| 19 | + try { |
| 20 | + // Try to get existing valid token first |
| 21 | + const existingToken = await gh.getStoredGitHubToken(); |
| 22 | + if (existingToken) { |
| 23 | + console.log('✅ Using existing GitHub token'); |
| 24 | + return; |
| 25 | + } |
| 26 | + } catch (error) { |
| 27 | + // No existing token or expired, continue with authentication |
| 28 | + } |
| 29 | + |
| 30 | + try { |
| 31 | + // Try token refresh first |
| 32 | + const refreshedToken = await gh.refreshGitHubToken(); |
| 33 | + if (refreshedToken) { |
| 34 | + console.log('✅ GitHub token refreshed successfully'); |
| 35 | + return; |
| 36 | + } |
| 37 | + } catch (error) { |
| 38 | + console.log('Token refresh failed, initiating new authentication...'); |
| 39 | + } |
| 40 | + |
| 41 | + // Start new device flow authentication |
| 42 | + console.log('Starting GitHub authentication...'); |
| 43 | + |
| 44 | + /** @type {{verification_uri: string, user_code: string, config: any, interval: number, device_code: string, expires_in: number}} */ |
| 45 | + const deviceFlow = await gh.initiateGitHubDeviceFlow(); |
| 46 | + |
| 47 | + console.log(`\nPlease visit: ${chalk.cyan(deviceFlow.verification_uri)}`); |
| 48 | + console.log(`Enter code: ${chalk.blueBright(chalk.underline(deviceFlow.user_code))}`); |
| 49 | + console.log('Waiting for authentication...'); |
| 50 | + |
| 51 | + // Poll for completion with user-friendly output |
| 52 | + let accessToken = ''; |
| 53 | + let pollCount = 0; |
| 54 | + const startPoll = async () => { |
| 55 | + if (pollCount > 12) { |
| 56 | + throw new Error('Authentication timed out. Please try again.'); |
| 57 | + } |
| 58 | + pollCount += 1; |
| 59 | + try { |
| 60 | + // The built-in polling method is not reliable since it throws for unexpected response. |
| 61 | + // So we handle the polling loop manually here. |
| 62 | + const tokens = await client.pollDeviceAuthorizationGrant(deviceFlow.config, deviceFlow); |
| 63 | + accessToken = tokens.access_token; |
| 64 | + |
| 65 | + // Store the tokens using core utility |
| 66 | + await gh.storeGitHubTokens(tokens); |
| 67 | + } catch (err) { |
| 68 | + if (err instanceof client.ClientError && err.code === 'OAUTH_INVALID_RESPONSE') { |
| 69 | + // Still waiting for user authorization, continue polling |
| 70 | + await startPoll(); |
| 71 | + return; |
| 72 | + } |
| 73 | + throw err; |
| 74 | + } |
| 75 | + }; |
| 76 | + |
| 77 | + await startPoll(); |
| 78 | + |
| 79 | + if (accessToken) { |
| 80 | + console.log('✅ GitHub authentication successful'); |
| 81 | + return; |
| 82 | + } |
| 83 | + |
| 84 | + throw new Error('Authentication failed'); |
| 85 | +} |
| 86 | + |
| 87 | +/** |
| 88 | + * @typedef {Object} Args |
| 89 | + * @property {boolean} authorize |
| 90 | + * @property {boolean} clear |
| 91 | + */ |
| 92 | + |
| 93 | +export default /** @type {import('yargs').CommandModule<{}, Args>} */ ({ |
| 94 | + command: 'github', |
| 95 | + describe: 'Authenticates the user with GitHub and stores the access token securely.', |
| 96 | + builder: (yargs) => |
| 97 | + yargs |
| 98 | + .option('authorize', { |
| 99 | + type: 'boolean', |
| 100 | + describe: 'Trigger the authentication flow to get a new token.', |
| 101 | + default: false, |
| 102 | + }) |
| 103 | + .option('clear', { |
| 104 | + type: 'boolean', |
| 105 | + describe: 'Clear stored GitHub authentication tokens.', |
| 106 | + default: false, |
| 107 | + }), |
| 108 | + async handler(args) { |
| 109 | + const gh = await import('../utils/github.mjs'); |
| 110 | + if (args.clear) { |
| 111 | + try { |
| 112 | + await gh.clearGitHubAuth(); |
| 113 | + console.log('✅ GitHub authentication cleared'); |
| 114 | + } catch (/** @type {any} */ error) { |
| 115 | + console.error('❌ Failed to clear GitHub authentication:', error.message); |
| 116 | + process.exit(1); |
| 117 | + } |
| 118 | + } else if (args.authorize) { |
| 119 | + try { |
| 120 | + await authenticateWithGitHub(gh); |
| 121 | + } catch (/** @type {any} */ error) { |
| 122 | + console.error('❌ GitHub authentication failed:', error.message); |
| 123 | + process.exit(1); |
| 124 | + } |
| 125 | + } |
| 126 | + }, |
| 127 | +}); |
0 commit comments