This repository has been archived by the owner on Feb 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zeroframe.js
100 lines (85 loc) · 2.24 KB
/
zeroframe.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
const WebSocketClient = require("websocket").client;
const request = require("request");
const address = process.env.ZERONET_CLIENT || "http://127.0.0.1:43110";
let masterAddress;
class ZeroFrame {
constructor(connection) {
this.connection = connection;
this.nextMessageId = 1;
this.waitingCallbacks = {};
connection.on("message", message => {
if(message.type === "utf8") {
message = JSON.parse(message.utf8Data);
if(message.cmd === "response") {
if(this.waitingCallbacks[message.to]) {
this.waitingCallbacks[message.to](message.result);
}
} else if(message.cmd === "ping") {
this.send({
cmd: "response",
to: message.id,
result: "pong"
});
}
}
});
}
send(message, callback) {
message.id = this.nextMessageId++;
this.connection.sendUTF(JSON.stringify(message));
if(callback) {
this.waitingCallbacks[message.id] = callback;
}
}
cmd(cmd, params={}) {
this.send({cmd, params});
}
async cmdp(cmd, params={}) {
return await new Promise(resolve => {
this.send({cmd, params}, resolve);
});
}
}
module.exports = async siteAddress => {
return await new Promise((resolve, reject) => {
// Get wrapper_key
request({
url: `${address}/${siteAddress}`,
headers: {
Accept: "text/html",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0"
}
}, (e, res, body) => {
if(e) {
reject(e);
return;
}
if(body.indexOf("Adding new sites disabled on this proxy") > -1) {
reject(new Error("Adding new sites disabled on this proxy"));
return;
}
for(const cookie of res.headers["set-cookie"]) {
if(cookie.startsWith("master_address=")) {
masterAddress = cookie.replace("master_address=", "").split(";")[0];
}
}
const wrapperKey = body.split("wrapper_key = \"")[1].split("\"")[0];
// Connect
const client = new WebSocketClient();
client.on("connectFailed", e => {
reject(e);
});
client.on("connect", connection => {
resolve(new ZeroFrame(connection));
});
client.connect(
`${address.replace("http", "ws")}/ZeroNet-Internal/Websocket?wrapper_key=${wrapperKey}`,
[],
null,
{
Cookie: `master_address=${masterAddress}`
}
);
});
});
};