-
Notifications
You must be signed in to change notification settings - Fork 14
/
config.js
233 lines (194 loc) · 5.26 KB
/
config.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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
const WebSocket = require("ws");
const { User, Server, IPGuard, File } = require("./utils");
const { default: axios } = require("axios");
const { DBAdapter } = require("./db/Adapter");
const { join } = require("path");
const sqlite3 = require("sqlite3").verbose();
const DBSqlite3 = require("./db/DBSqlite3");
class Ws {
/**
* @param {WebSocketConfigType} params
*/
constructor(params) {
let patch = params?.node ? `node/${params.node}` : "core";
this.access_token = params.accessToken;
this.params = params;
const url = `${process.env.SSL === "true" ? "wss" : "ws"}://${
params.url
}/api/${patch}/logs?interval=${process.env.FETCH_INTERVAL_LOGS_WS}&token=${
this.access_token
}`;
const db = new DBAdapter(params.DB);
const ws = new WebSocket(url);
// retry to get token
ws.on("unexpected-response", async (error, response) => {
const token = await params.api.token();
const _ws = new Ws({ ...params, accessToken: token });
_ws.logs();
});
const user = new User();
const ipGuard = new IPGuard(new DBSqlite3());
/**
* someProperty is an example property that is set to `true`
* @type {WebSocketConfigType}
* @public
*/
this.params = params;
this.db = db;
this.user = user;
this.ws = ws;
this.ipGuard = ipGuard;
}
logs() {
// Opened connections
this.ws.on("message", async (msg) => {
const bufferToString = msg.toString();
const data = this.user.GetNewUserIP(bufferToString);
if (data.length === 0) return;
let num = data.length;
while (num--) {
const item = data[num];
await this.ipGuard.use(
item.ip,
() => this.db.read(item.email),
() =>
this.db.addIp(item.email, {
ip: item.ip,
port: item.port,
date: new Date().toISOString().toString(),
}),
() => this.db.deleteLastIp(item.email),
);
}
});
}
}
class Api {
/**
* @description Marzban access_token
*/
accessToken = "";
/**
* @description Default: Bearer
*/
accessTokenType = "Bearer";
accessTokenExpireAt = null;
/**
* @description Creates an instance to communicate with the marzban api
* @returns {void}
*/
create() {
const url = new Server().CleanAddress(
`${process.env.ADDRESS}:${process.env.PORT_ADDRESS}`,
);
this.axios = axios.create({
baseURL: url,
headers: {
accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
});
this.axios.interceptors.response.use(
(value) => value,
async (error) => {
if (
error?.response?.data?.detail === "Could not validate credentials"
) {
await this.token();
}
return error;
},
);
}
/**
* @description It receives access_token from Marzban api
* @returns {Promise}
*/
async token() {
if (this.accessTokenExpireAt && Date.now() < +this.accessTokenExpireAt)
return;
try {
const { data } = await this.axios.post("/admin/token", {
username: process.env.P_USER,
password: process.env.P_PASS,
});
this.accessToken = data.access_token;
this.axios.defaults.headers.common.Authorization = `Bearer ${data.access_token}`;
this.accessTokenType = data.token_type;
this.accessTokenExpireAt = new Date() + 1000 * 60 * 60;
return data.access_token;
} catch (e) {
console.error(e);
}
}
async getNodes() {
let nodes = [];
try {
const { data } = await this.axios.get("/nodes");
if (!data) return nodes;
nodes = data
.filter((item) => item.status === "connected")
.map((item) => item.id);
} catch (e) {
console.error(e);
}
return nodes;
}
}
class Connection {
/**
*
* @deprecated
*/
BanDB() {
const dbPath = join(__dirname, "ban.sqlite");
new File().ForceExistsFile(dbPath);
return new sqlite3.Database(dbPath);
}
}
/**
* @deprecated
*/
class BanDBConfig {
constructor() {
this.db = new Connection().BanDB();
this.db.serialize(() => {
const sql =
"CREATE TABLE IF NOT EXISTS banned (ip TEXT, cid TEXT, date TEXT)";
this.db.run(sql);
});
}
/**
* @param {BanIpConfigAddType} params
*/
add(params) {
this.db.serialize(() => {
const sql = "SELECT * FROM banned WHERE cid = ?";
this.db.get(sql, [params.cid], (err, row) => {
if (err) throw new Error(err);
if (!row) {
const sql = "INSERT INTO banned (ip, cid, date) VALUES (?, ?, ?) ";
this.db.run(
sql,
[{ ...params, date: new Date().toLocaleString("en-US") }],
(err) => {
if (err) throw new Error(err);
console.log("Ip banned:", cid);
},
);
}
console.log("Ip already banned:", params.cid);
});
});
}
remove(cid) {
this.db.serialize(() => {
const sql = "DELETE FROM banned WHERE cid = ?";
this.db.run(sql, [cid], (err) => {
if (err) throw new Error(err);
console.log("Ip unbanned:", cid);
});
});
}
}
module.exports = { Ws, Api, Connection, BanDBConfig };