|
1 | | -import { Command, flags } from '@oclif/command' |
2 | | -import { runHTK } from './run-htk'; |
| 1 | +import * as util from 'util'; |
| 2 | +import * as path from 'path'; |
| 3 | +import * as fs from 'fs'; |
| 4 | +import * as envPaths from 'env-paths'; |
| 5 | +import { getStandalone, generateCACertificate } from 'mockttp'; |
3 | 6 |
|
4 | | -class HttpToolkitServer extends Command { |
5 | | - static description = 'run the HTTP Toolkit server' |
| 7 | +import { HttpToolkitServer } from './htk-server'; |
6 | 8 |
|
7 | | - static flags = { |
8 | | - version: flags.version({char: 'v'}), |
9 | | - help: flags.help({char: 'h'}), |
| 9 | +const canAccess = util.promisify(fs.access); |
| 10 | +const mkDir = util.promisify(fs.mkdir); |
| 11 | +const writeFile = util.promisify(fs.writeFile); |
10 | 12 |
|
11 | | - config: flags.string({char: 'c', description: 'path in which to store config files'}), |
12 | | - } |
| 13 | +const ensureDirectoryExists = (path: string) => |
| 14 | + canAccess(path).catch(() => mkDir(path, { recursive: true })); |
13 | 15 |
|
14 | | - async run() { |
15 | | - const { flags } = this.parse(HttpToolkitServer); |
| 16 | +async function generateHTTPSConfig(configPath: string) { |
| 17 | + const keyPath = path.join(configPath, 'ca.key'); |
| 18 | + const certPath = path.join(configPath, 'ca.pem'); |
16 | 19 |
|
17 | | - await runHTK({ configPath: flags.config }); |
18 | | - } |
| 20 | + await Promise.all([ |
| 21 | + canAccess(keyPath, fs.constants.R_OK), |
| 22 | + canAccess(certPath, fs.constants.R_OK) |
| 23 | + ]).catch(() => { |
| 24 | + const newCertPair = generateCACertificate({ |
| 25 | + commonName: 'HTTP Toolkit CA - DO NOT TRUST' |
| 26 | + }); |
| 27 | + |
| 28 | + return Promise.all([ |
| 29 | + writeFile(keyPath, newCertPair.key), |
| 30 | + writeFile(certPath, newCertPair.cert) |
| 31 | + ]); |
| 32 | + }); |
| 33 | + |
| 34 | + return { |
| 35 | + keyPath, |
| 36 | + certPath, |
| 37 | + keyLength: 2048 // Reasonably secure keys please |
| 38 | + }; |
19 | 39 | } |
20 | 40 |
|
21 | | -export = HttpToolkitServer; |
| 41 | +export async function runHTK(options: { |
| 42 | + configPath?: string |
| 43 | +}) { |
| 44 | + const configPath = options.configPath || envPaths('httptoolkit', { suffix: '' }).config; |
| 45 | + |
| 46 | + await ensureDirectoryExists(configPath); |
| 47 | + |
| 48 | + const httpsConfig = await generateHTTPSConfig(configPath); |
| 49 | + |
| 50 | + // Start a standalone server |
| 51 | + const standalone = getStandalone({ |
| 52 | + serverDefaults: { |
| 53 | + cors: false, |
| 54 | + https: httpsConfig |
| 55 | + } |
| 56 | + }); |
| 57 | + standalone.start(); |
| 58 | + |
| 59 | + // Start a HTK server |
| 60 | + const htkServer = new HttpToolkitServer({ |
| 61 | + configPath |
| 62 | + }); |
| 63 | + await htkServer.start(); |
| 64 | + |
| 65 | + console.log('Server started'); |
| 66 | +} |
0 commit comments