This repository has been archived by the owner on Sep 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
initiator.js
104 lines (91 loc) · 2.34 KB
/
initiator.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
const { connect } = require("net");
const isNil = require("lodash/isNil");
const noise = require("../src");
const keyPair = require("./initiator-keypair.json");
const remotePublicKey = require("./responder-keypair.json").publicKey;
const noiseOpts = { mode: "initiator", keyPair, remotePublicKey };
const port = 14912;
const host = "127.0.0.1";
let interval;
const intervalDelay = 500; // time between messages
let initiator;
/**
* Try to gracefully shutdown
* @method shutdown
* @param {number} code
*/
function shutdown(code = 0) {
// stop the server
if (isNil(initiator) === false) {
try {
initiator.end();
} catch (err) {
console.error("error closing initiator", err);
}
}
// stop timers
if (isNil(interval) === false) {
clearInterval(interval);
}
process.exit(code);
}
//
// 1. Make some Noise!
//
noise.createNoise(noiseOpts, function(err, { handshake }) {
if (isNil(err) === false) {
console.error("error creating noise objec", err);
return shutdown(1);
}
//
// 2. Connect to the responder
//
initiator = connect(
{ port, host },
function() {
console.log("initiator connected");
//
// 3. Initiate the handshake
//
handshake({ socket: initiator }, function(err, res) {
if (isNil(err) === false) {
console.error("error handshaking socket", err);
return shutdown(1);
}
//
// 4. Send and receive encrypted data
//
const { encrypt, decrypt } = res;
console.log("initiator handshake success");
initiator.on("data", function(chunk) {
//
// decrypt incoming data
//
let op = decrypt(chunk);
op = Buffer.from(op);
op = op.toString();
console.log("initiator decrypted:", op);
});
//
// Encrypt outgoing data
//
let counter = 0;
interval = setInterval(function() {
let op = `initiator message ${counter}`;
op = Buffer.from(op);
op = encrypt(op);
initiator.write(op);
counter += 1;
}, intervalDelay);
});
}
);
initiator.on("error", function(err) {
console.error("initiator error", err);
shutdown(1);
});
initiator.on("close", function() {
console.log("initiator close");
shutdown();
});
});