-
Notifications
You must be signed in to change notification settings - Fork 1
/
noise-stream-engine.js
54 lines (45 loc) · 1.76 KB
/
noise-stream-engine.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
/**
* Uses noise-protocol-stream as the encryption engine. The security characteristics
* of these engines are still not fully determined, so we add support for multiple
* engines for evaluation.
*
* See https://github.com/kapetan/noise-protocol-stream. This module uses
* Noise_XX_25519_AESGCM_SHA256 as the Noise protocol.
*/
const noise = require('noise-protocol-stream');
const NoiseEngine = require('./noise-engine'); // Base interface.
module.exports = class NoiseStreamEngine extends NoiseEngine {
/**
* See NoiseEngine for descriptions about parameters.
*/
constructor(socket, serverIdentifier) {
super(socket, serverIdentifier);
}
createInitiatorChannel(readCallback) {
if (!readCallback || typeof readCallback !== "function") {
throw new Error('A callback function is required to create initiator channel.')
}
const self = this;
this.noiseChannel = noise({ initiator: true });
this.noiseChannel.encrypt
.pipe(self.socket)
.pipe(self.noiseChannel.decrypt)
.on('data', (data) => {
// Pass the data to be read callback function with the serverAddress:port
// key, so the callers know the server sending the response.
const response = {
from: self.serverIdentifier,
// Response should be JSON.
data: JSON.parse(data.toString())
}
readCallback(response);
});
}
send(jsonData) {
const stringData = JSON.stringify(jsonData); // TO-DO.Use fast-stringify.
this.noiseChannel.encrypt.write(stringData);
}
close() {
// No explicit close is required for this engine.
}
}