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() {