-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage.js
376 lines (282 loc) · 7.09 KB
/
storage.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import net from "node:net";
import { generateKeyPairSync, publicEncrypt, privateDecrypt, randomBytes, createCipheriv, createDecipheriv } from "node:crypto";
import configData from "./config.js";
class EncryptionKey {
#public;
#private;
constructor(pub, priv) {
this.#public = pub;
this.#private = priv;
}
static create() {
const { publicKey, privateKey } = generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "pkcs1",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
return new EncryptionKey(publicKey, privateKey);
}
publicKey() {
return this.#public;
}
encrypt(data) {
return publicEncrypt(this.#public, asBuffer(data));
}
decrypt(encrypted) {
if (!this.#private) {
throw new Error("Private key not set");
}
return privateDecrypt(
{
key: this.#private,
oaepHash: "sha256",
},
encrypted
);
}
}
class SecureConnection {
#socket;
#key;
constructor(socket, key, onDeath) {
this.#socket = socket;
this.#key = key;
this.#socket.on("close", () => {
this.#socket.emit("error", new Error("Connection closed"));
this.#socket.destroy();
this.#socket = null;
onDeath();
});
}
static async connect(host, port, onDeath) {
const socket = await establishTCPConnection(host, port),
local = EncryptionKey.create();
// Perform the key exchange
const key = await SecureConnection.performKeyExchange(socket, local);
return new SecureConnection(socket, key, onDeath);
}
static async performKeyExchange(socket, local) {
// Send our public key
const packet = createPacket(local.publicKey());
socket.write(packet);
// Read the shared session key
const encrypted = await readFromSocket(socket);
// Decrypt the shared session key
return local.decrypt(encrypted);
}
#encrypt(data) {
const nonce = randomBytes(12),
cipher = createCipheriv("aes-256-gcm", this.#key, nonce);
return Buffer.concat([nonce, cipher.update(data, "utf8"), cipher.final(), cipher.getAuthTag()]);
}
#decrypt(data) {
const nonce = data.slice(0, 12),
decipher = createDecipheriv("aes-256-gcm", this.#key, nonce);
decipher.setAuthTag(data.slice(-16));
return Buffer.concat([decipher.update(data.slice(12, -16)), decipher.final()]);
}
close() {
if (!this.#socket) {
return;
}
this.#socket.destroy();
}
async send(data) {
if (!this.#socket) {
throw new Error("Connection closed");
}
// Encrypt the data
const encrypted = this.#encrypt(data);
// Create the packet
const packet = createPacket(encrypted);
this.#socket.write(packet);
}
async read() {
if (!this.#socket) {
throw new Error("Connection closed");
}
// Read the packet
const encrypted = await readFromSocket(this.#socket);
// Decrypt the packet
const data = this.#decrypt(encrypted);
if (data.toString("utf8") === "ERR") {
throw new Error("Something went wrong");
}
return data;
}
}
export class HistoryStorage {
#disabled = false;
#connection;
static #instance = null;
static async getInstance() {
if (!HistoryStorage.#instance) {
HistoryStorage.#instance = new HistoryStorage();
}
await HistoryStorage.#instance.#connect();
return HistoryStorage.#instance;
}
async #connect() {
if (this.#connection || this.#disabled) {
return;
}
const storage = configData.storage || "",
match = storage?.match(/^([^:]+):(\d+)$/);
if (!storage || !match || match.length < 3) {
this.#disabled = true;
}
const host = match[1],
port = parseInt(match[2]) || 4994;
this.#connection = await SecureConnection.connect(host, port, () => {
console.warn("Storage connection closed");
this.#connection = null;
});
console.info("Storage connection established");
}
#request(type, server, timestamp1, timestamp2, license, data = null) {
const header = Buffer.alloc(1 + 1 + 4 + 4 + 40);
// Type (uint8)
header.writeUInt8(type, 0);
// Server (uint8) "c3" -> 3
header.writeUInt8(parseInt(server.substr(1)), 1);
// Timestamp 1 (uint32)
header.writeUInt32LE(timestamp1, 2);
// Timestamp 2 (uint32)
header.writeUInt32LE(timestamp2, 6);
// License (40 bytes)
if (license) {
header.write(Buffer.from(license, "utf8"), 10);
}
if (!data) return header;
return Buffer.concat([header, data]);
}
available() {
return !this.#disabled;
}
close() {
if (!this.#connection) {
return;
}
this.#connection.close();
}
async store(server, timestamp, license, data) {
if (this.#disabled) {
return;
}
await this.#connect();
// Send the request
await this.#connection.send(
this.#request(
1, // Store = 1
server,
timestamp,
timestamp,
license,
asBuffer(data)
)
);
// Wait for the acknowledgement
const ack = await this.#connection.read();
if (ack.toString("utf8") !== "ACK") {
throw new Error("Invalid or missing ACK");
}
}
async readOne(server, start, end, license) {
if (this.#disabled) {
throw new Error("Storage disabled");
}
await this.#connect();
// Send the request
await this.#connection.send(
this.#request(
2, // ReadOne = 2
server,
start,
end,
license,
null
)
);
// Wait for the data
return await this.#connection.read();
}
async readAll(server, timestamp) {
if (this.#disabled) {
throw new Error("Storage disabled");
}
await this.#connect();
// Send the request
await this.#connection.send(
this.#request(
3, // ReadAll = 3
server,
timestamp,
timestamp,
null,
null
)
);
// Wait for the data
return await this.#connection.read();
}
}
function asBuffer(data) {
if (Buffer.isBuffer(data)) {
return data;
}
return Buffer.from(data, "utf8");
}
function readFromSocket(socket) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error("Timeout"));
}, 5000);
const onData = data => {
completed();
// Read the length
const length = data.readUInt32LE(0);
// Validate packet length
if (length !== data.length - 4) {
reject(new Error(`Expected ${length} bytes, got ${data.length - 4}`));
return;
}
// Read the message
resolve(data.slice(4, 4 + length));
};
const onError = err => {
completed();
reject(err);
};
const completed = () => {
clearTimeout(timeout);
socket.off("data", onData);
socket.off("error", onError);
};
socket.once("data", onData);
socket.once("error", onError);
});
}
function createPacket(data) {
data = asBuffer(data);
const packet = Buffer.alloc(4 + data.length);
// Write the length
packet.writeUInt32LE(data.length, 0);
// Write the data
data.copy(packet, 4);
return packet;
}
function establishTCPConnection(host, port) {
return new Promise((resolve, reject) => {
const socket = net.createConnection({ host, port }, () => {
socket.off("error", reject);
resolve(socket);
});
socket.once("error", reject);
});
}