· 5 years ago · Jan 11, 2020, 12:06 PM
1const circular_json_1 = require("circular-json");
2const events_1 = require("events");
3const http_1 = require("http");
4const WebSocket = require("ws");
5
6const options = {
7 protocol: "https:wss:http",
8 localhost: "localhost:10888", // брать из CLI отдельно: port и host
9 authorization: "token:test", // брать из конфига SECRET_KEY заместо "test" ("token:" НЕ ТРОГАТЬ!)
10 remotehost: "proxy.vk.rapps.cloud" // брать из конфига subdomain заместо "vk"
11};
12
13const url = `${options.protocol.split(":")[1]}://${options.authorization}@${options.remotehost}`;
14const connection = new WebSocket(url, {
15 perMessageDeflate: true
16});
17
18connection.on("open", () => {
19 const emitter = new events_1.EventEmitter();
20 connection.on("message", (rawMessage) => {
21 const message = circular_json_1.parse(rawMessage);
22 if (message.type === "header") {
23 const requestOptions = {
24 headers: message.payload.headers,
25 host: options.localhost.split(":")[0],
26 method: message.payload.method,
27 path: message.payload.url,
28 port: options.localhost.split(":")[1],
29 protocol: `${options.protocol.split(":")[2]}:`
30 };
31 const clientRequest = http_1.request(requestOptions, (response) => {
32 connection.send(circular_json_1.stringify({
33 identifier: message.identifier,
34 payload: response,
35 type: "header"
36 }));
37 response.on("data", (data) => {
38 const dataMessage = {
39 identifier: message.identifier,
40 payload: Buffer.from(data).toString("base64"),
41 type: "data"
42 };
43 connection.send(circular_json_1.stringify(dataMessage));
44 });
45 response.on("end", () => {
46 const endMessage = {
47 identifier: message.identifier,
48 type: "end"
49 };
50 connection.send(circular_json_1.stringify(endMessage));
51 });
52 });
53 emitter.on(`data:${message.identifier}`, (dataMessage) => {
54 clientRequest.write(Buffer.from(dataMessage.payload, "base64"));
55 });
56 emitter.on(`end:${message.identifier}`, (endMessage) => {
57 clientRequest.end();
58 emitter.removeAllListeners(`data:${message.identifier}`);
59 emitter.removeAllListeners(`end:${message.identifier}`);
60 });
61 }
62 if (message.type === "data" || message.type === "end") {
63 emitter.emit(`${message.type}:${message.identifier}`, message);
64 }
65 });
66
67 connection.on("close", () => {
68 process.exit();
69 });
70
71 process.stdout.write(`${options.protocol.split(":")[0]}://${options.remotehost}`);
72 process.stdout.write(" <-- ");
73 process.stdout.write(`${options.protocol.split(":")[1]}://${options.remotehost}`);
74 process.stdout.write(" --> ");
75 process.stdout.write(`${options.protocol.split(":")[2]}://${options.localhost}\n`);
76});