-
Notifications
You must be signed in to change notification settings - Fork 16
/
cli.js
executable file
·109 lines (98 loc) · 2.63 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env node
// @ts-check
const yargs = require("yargs")
const pkg = require("./package.json")
const argv = yargs
// @ts-ignore
.usage("Usage: $0 --port 9191 [options]")
.option("port", {
alias: "p",
default: 9191,
describe: `Port to bind on`,
type: "number",
})
.option("auth", {
alias: "a",
describe: `Enable proxy authentication`,
type: "string",
})
.option("dynamic-auth", {
// alias: "a",
describe: `Enable proxy authentication with no validation`,
type: "boolean",
})
.example('$0 --auth "user:pass"', "Require authentication")
.option("echo", {
alias: "e",
describe: `Enable echo mode (mock all http responses)`,
type: "boolean",
})
.example("$0 --echo", "Mock responses for all http requests")
.option("debug", {
alias: "d",
describe: `Enabled debug output`,
type: "boolean",
})
.option("cluster", {
alias: "c",
describe: `Run a cluster of proxies (using number of CPUs)`,
type: "boolean",
})
.option("cluster-count", {
describe: `Specify how many cluster workers to spawn`,
type: "number",
})
.option("quiet", {
alias: "q",
describe: `Suppress request logs`,
type: "boolean",
})
.option("silent", {
alias: "s",
describe: `Don't print anything to stdout`,
type: "boolean",
})
.help("h")
.alias("h", "help")
.epilog(`Report issues at ${pkg.bugs.url}`).argv
if (argv.debug) {
process.env.DEBUG += ",straightforward"
}
const { Straightforward, middleware } = require("./dist/index.js")
async function cli() {
const sf = new Straightforward()
if (!argv.silent) {
sf.on("listen", (port) => {
console.log(`
straightforward forward-proxy running on localhost:${port}
`)
})
sf.on("serverError", (err) => console.error("An error occured.", err))
}
if (argv.auth && !argv.dynamicAuth) {
const [user, pass] = argv.auth.split(":")
sf.onRequest.use(middleware.auth({ user, pass }))
sf.onConnect.use(middleware.auth({ user, pass }))
}
if (argv.dynamicAuth) {
sf.onRequest.use(middleware.auth({ dynamic: true }))
sf.onConnect.use(middleware.auth({ dynamic: true }))
}
if (argv.echo) {
sf.onRequest.use(middleware.echo)
}
if (!argv.quiet && !argv.silent && !argv.debug) {
sf.onRequest.use(async ({ req, res }, next) => {
console.log(`\t ${req.method} \t\t ${req.url}`)
return next()
})
sf.onConnect.use(async ({ req }, next) => {
console.log(`\t ${req.method} \t ${req.url}`)
return next()
})
}
argv.cluster
? await sf.cluster(argv.port, argv.clusterCount)
: await sf.listen(argv.port)
}
cli()