From 99fc8055572d57b4803f53130f3a26c5f0a46f7c Mon Sep 17 00:00:00 2001 From: Marcus Date: Sat, 20 Mar 2021 12:40:43 -0400 Subject: [PATCH] better readyStates --- lib/STP/index.js | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/lib/STP/index.js b/lib/STP/index.js index 01eba90..e6362ca 100644 --- a/lib/STP/index.js +++ b/lib/STP/index.js @@ -55,11 +55,15 @@ class Server extends EventEmitter { class STPSocket extends EventEmitter { tcpSocket; - readyState = 0; buffer = ''; externalKey; identity; + CONNECTING = Symbol('connecting'); + EXCHANGE = Symbol('exchange'); + SECURED = Symbol('secured'); + readyState = this.CONNECTING; + get loopback() { return this.identity.publicKey === this.externalKey.exportKey('pkcs8-public-pem'); @@ -112,24 +116,21 @@ class STPSocket extends EventEmitter { } processMessage(obj) { - switch(obj.cmd) { - case 'KEY': { - if(this.readyState === 0) { - this.externalKey = new NodeRSA(); - this.externalKey.importKey(obj.data.key, 'pkcs8-public-pem'); - this.tcpSocket.write(new AckPacket().toBuffer()); - this.readyState = 1; - } - break; - } - case 'ACK': { - if(this.readyState === 1) { - this.readyState = 2; - this.emit('ready'); - } - break; - } + + if(this.readyState === this.CONNECTING && obj.cmd === 'KEY') { + this.externalKey = new NodeRSA(); + this.externalKey.importKey(obj.data.key, 'pkcs8-public-pem'); + this.tcpSocket.write(new AckPacket().toBuffer()); + this.readyState = this.EXCHANGE; + return; } + + if(this.readyState === this.EXCHANGE && obj.cmd === 'ACK') { + this.readyState = this.SECURED; + this.emit('ready'); + return; + } + } handshake() {