68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
import type { Command } from 'commander';
|
|
import readline from 'readline';
|
|
import { loadStoredOpenAIApiKey, storeOpenAIApiKey } from '../auth/index.js';
|
|
|
|
async function promptHidden(question: string): Promise<string> {
|
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
const rlAny = rl as unknown as { stdoutMuted?: boolean; _writeToOutput?: (s: string) => void };
|
|
rlAny.stdoutMuted = true;
|
|
|
|
rlAny._writeToOutput = (s: string) => {
|
|
if (!rlAny.stdoutMuted) {
|
|
process.stdout.write(s);
|
|
return;
|
|
}
|
|
if (s.includes('\n')) {
|
|
process.stdout.write('\n');
|
|
} else {
|
|
process.stdout.write('*');
|
|
}
|
|
};
|
|
|
|
const answer = await new Promise<string>((resolve) => rl.question(question, resolve));
|
|
rlAny.stdoutMuted = false;
|
|
rl.close();
|
|
process.stdout.write('\n');
|
|
return answer.trim();
|
|
}
|
|
|
|
async function promptYesNo(question: string): Promise<boolean> {
|
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
const answer = await new Promise<string>((resolve) => rl.question(question, resolve));
|
|
rl.close();
|
|
const normalized = answer.trim().toLowerCase();
|
|
return normalized === 'y' || normalized === 'yes';
|
|
}
|
|
|
|
export function registerOpenaiKeyCommand(program: Command): void {
|
|
program
|
|
.command('openai-key')
|
|
.description('Store an OpenAI API key (auth.json)')
|
|
.action(async () => {
|
|
const existing = loadStoredOpenAIApiKey();
|
|
if (existing) {
|
|
console.log('OpenAI API key already exists.');
|
|
const confirmed = await promptYesNo('Re-authenticate and replace it? (y/N): ');
|
|
if (!confirmed) {
|
|
console.log('Cancelled.');
|
|
process.exit(0);
|
|
}
|
|
}
|
|
|
|
console.log('OpenAI uses API keys for standard API access.');
|
|
console.log('Create a key at: https://platform.openai.com/api-keys');
|
|
console.log('');
|
|
|
|
try {
|
|
const apiKey = await promptHidden('Enter OpenAI API key: ');
|
|
storeOpenAIApiKey(apiKey);
|
|
console.log('');
|
|
console.log('OpenAI API key stored in ~/.config/flynn/auth.json');
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
console.error(`OpenAI API key storage failed: ${message}`);
|
|
process.exit(1);
|
|
}
|
|
});
|
|
}
|