auth.ts
1 import { Command } from 'commander'; 2 import { password } from '@inquirer/prompts'; 3 import { config, tokenSource, userConfigHint } from '../config.js'; 4 5 export function authCommand(): Command { 6 const auth = new Command('auth').description('Authentication'); 7 8 auth 9 .command('login') 10 .description('Authenticate with AtomGit (stores token in user config)') 11 .option('-t, --token <token>', 'API token') 12 .action(async (options: { token?: string }) => { 13 const t = options.token?.trim() || (await password({ message: 'Paste your AtomGit token', mask: '*' })).trim(); 14 if (!t) { 15 // eslint-disable-next-line no-console 16 console.error('No token provided.'); 17 process.exitCode = 1; 18 return; 19 } 20 config.set('token', t); 21 // eslint-disable-next-line no-console 22 console.log('Token saved to your user config.'); 23 }); 24 25 auth 26 .command('logout') 27 .description('Remove stored token') 28 .action(() => { 29 config.delete('token'); 30 // eslint-disable-next-line no-console 31 console.log('Token removed.'); 32 }); 33 34 auth 35 .command('status') 36 .description('Show auth status') 37 .action(async () => { 38 const source = tokenSource(); 39 if (source === 'none') { 40 // eslint-disable-next-line no-console 41 console.log(`Not authenticated. ${userConfigHint()}`); 42 process.exitCode = 1; 43 return; 44 } 45 46 // Try to fetch username from API 47 try { 48 const { get } = await import('../http.js'); 49 const user = await get('/user') as { login?: string; username?: string; name?: string }; 50 const username = user.login || user.username || user.name || 'Unknown'; 51 // eslint-disable-next-line no-console 52 console.log(`Logged in to api.atomgit.com as ${username} (${source})`); 53 } catch (error) { 54 // Fallback if API call fails 55 // eslint-disable-next-line no-console 56 console.log(`Authenticated (token from ${source}).`); 57 } 58 }); 59 60 auth 61 .command('token') 62 .description('Print a redacted token hint') 63 .action(() => { 64 const t = config.get('token'); 65 if (!t) { 66 // eslint-disable-next-line no-console 67 console.log('No token stored (try `atomgit auth login`).'); 68 process.exitCode = 1; 69 return; 70 } 71 const redacted = t.length <= 8 ? '********' : `${t.slice(0, 4)}…${t.slice(-4)}`; 72 // eslint-disable-next-line no-console 73 console.log(redacted); 74 }); 75 76 return auth; 77 }