-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.mjs
executable file
·202 lines (163 loc) · 4.75 KB
/
cli.mjs
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env node
import chalk from "chalk";
import eventToPromise from "event-to-promise";
import execPromise from "exec-promise";
import getStream from "get-stream";
import minimist from "minimist";
import { create as createHttpServer } from "http-server-plus";
import { genSelfSignedCert } from "@xen-orchestra/self-signed";
import { inspect } from "util";
import { load as loadConfig } from "app-conf";
import { parse } from "json-rpc-protocol";
import { readFileSync } from "node:fs";
import {
createReadableCopies,
proxyHttpsRequest,
splitHost,
} from "./utils.mjs";
import { isXmlRpcRequest, parseRequest } from "./xml-rpc.mjs";
// ===================================================================
const paintArg = chalk.yellow;
function pick(obj, keys) {
const result = {};
for (const key of keys) {
result[key] = obj[key];
}
return result;
}
const requiredArg = (name) => {
const message = `Missing argument: <${paintArg(name)}>`;
throw message;
};
const invalidArg = (name, value) => {
const message = `Invalid value ${chalk.bold(value)} for argument: <${paintArg(
name
)}>`;
throw message;
};
// ===================================================================
const COMMANDS = {
async proxy(args) {
let {
bind = "0",
_: [remote = requiredArg("remote address")],
} = minimist(args, {
string: "bind",
});
bind = {
...(await genSelfSignedCert()),
...splitHost(bind),
};
remote = {
protocol: "https:",
...splitHost(remote),
};
// ---------------------------------
const logRpcCall = (url, method, params) =>
console.log(
"[%s] %s(%s)",
chalk.blue(url),
chalk.bold.red(method),
inspect(params, {
colors: true,
depth: null,
})
);
const handleJsonRpcRequest = async (req, res) => {
const [req1, req2] = createReadableCopies(2, req);
const res1 = await proxyHttpsRequest(
{
...pick(req, ["headers", "method", "url"]),
...remote,
},
req1
);
res.writeHead(res1.statusCode, res1.statusMessage, res1.headers);
res1.pipe(res);
const { method, params } = parse(await getStream(req2));
logRpcCall(req.url, method, params);
};
const handleRequest = async (req, res) => {
console.log("[%s] - Not XML-RPC", chalk.blue(req.url));
(await proxyHttpsRequest(remote, req)).pipe(res);
};
const handleXmlRpcRequest = async (req, res) => {
const [req1, req2] = createReadableCopies(2, req);
const res1 = await proxyHttpsRequest(
{
...pick(req, ["headers", "method", "url"]),
...remote,
},
req1
);
res.writeHead(res1.statusCode, res1.statusMessage, res1.headers);
res1.pipe(res);
const { method, params } = await parseRequest(req2);
logRpcCall(req.url, method, params);
};
// ---------------------------------
const server = createHttpServer(async (req, res) => {
try {
if (req.url.startsWith("/jsonrpc")) {
await handleJsonRpcRequest(req, res);
} else if (isXmlRpcRequest(req, res)) {
await handleXmlRpcRequest(req, res);
} else {
await handleRequest(req, res);
}
} catch (error) {
console.error(error.stack || error);
throw error;
}
});
console.log(await server.listen(bind));
await eventToPromise(server, "close");
},
};
// ===================================================================
const { name: pkgName, version: pkgVersion } = JSON.parse(
readFileSync(new URL("package.json", import.meta.url))
);
const usage = `Usage: ${pkgName} proxy [--bind <local address>] <remote address>
Create a XML-RPC proxy which forward requests from <local address>
to <remote address>.
<local address>: [<hostname>]:<port>
<remote address>: <hostname>[:<port = 443>]
${pkgName} v${pkgVersion}
`.replace(/<([^>]+)>/g, (_, arg) => `<${paintArg(arg)}>`);
execPromise(async (args) => {
const {
help = false,
_: restArgs,
"--": restRestArgs,
} = minimist(args, {
boolean: "help",
alias: {
help: "h",
},
stopEarly: true,
"--": true,
});
if (help) {
return usage;
}
// Work around https://github.com/substack/minimist/issues/71
restArgs.push("--");
[].push.apply(restArgs, restRestArgs);
const [commandName, ...commandArgs] = restArgs;
if (commandName === "--") {
throw usage;
}
const command = COMMANDS[commandName];
if (!command) {
invalidArg("command", commandName);
}
return command.call(
{
config: await loadConfig("xapi-inspector", {
appDir: new URL(".", import.meta.url).pathname,
}),
},
commandArgs
);
});