import chalk from 'chalk'; import type { CommandModule } from 'yargs'; import type { DatabaseProxyOptions } from './database-proxy-options.js'; import { DEFAULT_LOCAL_PROXY_PORT, proxyDatabase, validateDatabaseProxyArgs, } from './database-proxy.js'; const { red, yellow } = chalk; export const databaseProxy: CommandModule = { builder: (yargs) => { return yargs .option('serviceId', { describe: 'Service ID to open a database access session for', alias: 'i', string: true, }) .option('ttlMinutes', { describe: 'How long the session should last. A request, not a guarantee: a shorter lifetime is granted when the service allows less. Defaults to whatever the service allows.', number: true, }) .option('localProxyPort', { describe: 'Local loopback port the database client connects to. Not 5432, which a local PostgreSQL usually holds. Deliberately not named `port`: a solution sets PORT for its own service, and that would override this.', number: true, default: DEFAULT_LOCAL_PROXY_PORT, }) .option('json', { describe: 'Emit the connection details as one JSON object on stdout, status messages on stderr. Contains the password, so it is as sensitive as the normal output.', boolean: true, }) .option('mosaicHostingClientId', { describe: "The service account client id.\nRequired permissions:\nHOSTING SERVICE -> 'Database Access: Write', 'Database Access Sessions: View', 'Service Definitions: View'", alias: 'c', string: true, }) .option('mosaicHostingClientSecret', { describe: 'Service Account Client Secret to authenticate', alias: 's', string: true, }) .option('idServiceAuthBaseURL', { describe: 'ID Service Authentication Endpoint Base URL', alias: 'a', string: true, }) .option('hostingServiceBaseURL', { describe: 'Hosting Service Base URL', alias: 'h', string: true, }) .example( '$0 hosting database proxy -i channel-service', 'Open a session and listen on 127.0.0.1:5433', ) .example( '$0 hosting database proxy -i channel-service --ttl-minutes 30', 'Open a session for half an hour', ); }, handler: async (args) => { const [validatedArgs, errorMessages] = validateDatabaseProxyArgs(args); if (errorMessages.length > 0) { process.stderr.write(red('Some required arguments are missing.\n')); process.stderr.write(yellow(errorMessages.join('\n') + '\n')); process.exit(1); } else { await proxyDatabase( validatedArgs as DatabaseProxyOptions & { serviceId: string }, ); } }, };