Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

2.8 KB
Raw Blame
import password from '@inquirer/password';
import { Octokit } from '@octokit/rest';
import { Command } from 'commander';
import { describeAuthFailure } from '../../auth/describe-auth-error.ts';
import type { TokenStore } from '../../auth/token-store.ts';
import { readTokenFromStdin } from './read-token-stdin.ts';
import { resolveAuthHost } from './validate-host.ts';

interface PatOptions {
  host: string;
  json: boolean;
}

async function runPat(
  opts: PatOptions,
  tokenStore: TokenStore,
  readToken?: () => Promise<string>,
): Promise<void> {
  const { host, json } = opts;

  const getToken = readToken ?? (() => password({ message: `Enter PAT for ${host}:` }));

  const token = await getToken();
  if (!token) {
    process.stderr.write('No token provided\n');
    process.exit(1);
  }

  const baseUrl = host === 'github.com' ? undefined : `https://${host}/api/v3`;
  const octokit = new Octokit({ auth: token, ...(baseUrl ? { baseUrl } : {}) });

  let login = 'unknown';
  let name: string | undefined;
  let email: string | undefined;
  try {
    const { data } = await octokit.users.getAuthenticated();
    login = data.login;
    name = data.name ?? undefined;
    email = data.email ?? undefined;
  } catch (err) {
    const message = describeAuthFailure(err, host).message;
    if (json) {
      process.stdout.write(`${JSON.stringify({ type: 'error', message })}\n`);
    } else {
      process.stderr.write(`${message}\n`);
    }
    process.exit(1);
  }

  try {
    await tokenStore.set(host, login, token, { gitProtocol: 'https', name, email });
  } catch (err) {
    const reason = err instanceof Error ? err.message : String(err);
    const message = `Could not save the token to the credential store: ${reason}`;
    if (json) {
      process.stdout.write(`${JSON.stringify({ type: 'error', message })}\n`);
    } else {
      process.stderr.write(`${message}\n`);
    }
    process.exit(1);
  }

  if (json) {
    process.stdout.write(`${JSON.stringify({ type: 'complete', host, login })}\n`);
  } else {
    process.stderr.write(`✓ PAT stored for ${login} on ${host}\n`);
  }
}

export function patCommand(getTokenStore: () => Promise<TokenStore>): Command {
  return new Command('pat')
    .description('Store a Personal Access Token')
    .option(
      '--host <host>',
      'GitHub or GitHub Enterprise hostname (default: the GitHub origin host, or github.com with no origin; required otherwise)',
    )
    .option('--json', 'Output JSON', false)
    .option('--token-stdin', 'Read the token from stdin instead of prompting', false)
    .action(async (opts: Omit<PatOptions, 'host'> & { host?: string; tokenStdin?: boolean }) => {
      const host = resolveAuthHost(opts.host);
      const readToken = opts.tokenStdin ? readTokenFromStdin : undefined;
      await runPat({ host, json: opts.json }, await getTokenStore(), readToken);
    });
}