@automata-network/pom-socket
Advanced tools
Comparing version 0.0.2 to 0.0.3
@@ -1,2 +0,2 @@ | ||
"use strict";var e,t=require("diffie-hellman-ts"),s=require("socket.io-client"),n=require("./encryption.js");exports.SocketStatus=void 0,(e=exports.SocketStatus||(exports.SocketStatus={}))[e.Disconnected=1]="Disconnected",e[e.Connecting=2]="Connecting",e[e.Connected=3]="Connected";const c=new Error("shared secret is not exist"),o=new Error("socket is not connected"),i=new Error("socket connect to server failed"),r=new Error("session is expired"),a=new Error("message salt is missing"),h=new Error("message type is unknown");var d;!function(e){e.KeyExchange="key-exchange",e.EncryptedMessage="encrypted-message"}(d||(d={}));class u{aesKey;manualReconnectionCount=0;connectedEventReceived=!1;connectedEventListener;keyExchangeEventListener;listeners={};dhClient;sharedPublicNumber;socket;constructor(e,n){this.dhClient=new t.Client,this.sharedPublicNumber=this.dhClient.generatePublicNumber(),this.socket=s.io(e,{...n||{},autoConnect:!1})}get status(){return this.socket.connected&&this.aesKey&&this.connectedEventReceived?exports.SocketStatus.Connected:this.socket.disconnected?exports.SocketStatus.Disconnected:exports.SocketStatus.Connecting}connect(){let e,t;const s="object"==typeof this.socket.auth&&!!this.socket.auth.sessionID,c=n.createRandomString(32),o=e=>{try{const t=y({message:e});t.type===d.KeyExchange&&(this.generateAESKey(t.data,c),this.socket.off("data",o),this.keyExchangeEventListener&&this.keyExchangeEventListener.resolve())}catch(e){this.keyExchangeEventListener&&this.keyExchangeEventListener.reject(e),this.socket.off("data",o)}};return new Promise(((n,i)=>{this.socket.once("connect",(()=>{s?n({dhSharedPublicNumber:this.sharedPublicNumber,sessionId:this.socket.auth.sessionID,hkdfSalt:c}):e?n({dhSharedPublicNumber:this.sharedPublicNumber,sessionId:e,hkdfSalt:c}):t=!0})),s||this.socket.once("setupSession",(s=>{t?n({dhSharedPublicNumber:this.sharedPublicNumber,sessionId:s,hkdfSalt:c}):e=s})),this.socket.once("disconnect",(e=>{this.manualReconnectionCount<3?(this.manualReconnectionCount+=1,this.connect().then((e=>{n(e)})).catch((e=>{i(e)}))):(this.manualReconnectionCount=0,i(new Error(e)))})),this.socket.once("connect_error",(e=>{i(e)})),this.socket.once("connected",(()=>{this.connectedEventReceived=!0,this.connectedEventListener&&(this.connectedEventListener.resolve(),this.connectedEventListener=void 0)})),this.socket.on("data",o),this.socket.connect()}))}generateAESKey(e,t){const s=this.dhClient.generateSharedSecret(e);this.aesKey=n.generateAESKey(s,t)}async waitForConnectedEvent(){return this.connectedEventReceived?Promise.resolve():new Promise(((e,t)=>{this.connectedEventListener={resolve:e,reject:t}}))}async waitForKeyExchangeEvent(){return this.aesKey?Promise.resolve():new Promise(((e,t)=>{this.keyExchangeEventListener={resolve:e,reject:t}}))}emitSharedPublicKey(){const e=k({type:d.KeyExchange,data:this.sharedPublicNumber});this.socket.emit("data",e)}disconnect(){this.socket.disconnect(),this.connectedEventReceived=!1,this.aesKey=void 0,this.sharedPublicNumber=this.dhClient.generatePublicNumber()}on(e){const t=t=>{E({message:t,key:this.aesKey,cb:e})};this.listeners.data=this.listeners.data||[],this.listeners.data.push({handler:t,cb:e}),this.socket.on("data",t)}off(e){const t=this.listeners.data;if(!t||0===t.length)return;const s=t.findIndex((t=>t.cb===e));-1!==s&&(this.socket.off("data",t[s].handler),t.splice(s,1))}once(e){this.socket.once("data",(t=>{E({message:t,key:this.aesKey,cb:e})}))}send(e){if(!this.aesKey)throw c;if(this.status!==exports.SocketStatus.Connected)throw o;this.socket.emit("data",k({type:d.EncryptedMessage,data:e,key:this.aesKey}))}}function E(e){const{message:t,key:s,cb:n}=e;try{const e=y({message:t,key:s});n.success(e.data)}catch(e){n.error(e)}}function y(e){const{message:t,key:s}=e,o=JSON.parse(t),i=o.t;switch(i){case d.KeyExchange:return{type:i,data:o.d};case d.EncryptedMessage:if(!o.s)throw a;if(!s)throw c;return{type:i,data:n.decryptMessage(o.d,s,o.s).decryptedMessage};default:throw h}}function k(e){const{type:t,data:s,key:o}=e,i={t:t,d:s};switch(t){case d.KeyExchange:break;case d.EncryptedMessage:if(!o)throw c;const e=n.encryptMessage(s,o);i.d=e.encryptedMessage,i.s=e.iv;break;default:throw h}return JSON.stringify(i)}exports.createRandomString=n.createRandomString,exports.ERR_MESSAGE_SALT_IS_MISSING=a,exports.ERR_MESSAGE_TYPE_IS_UNKNOWN=h,exports.ERR_SESSION_IS_EXPIRED=r,exports.ERR_SHARED_SECRET_NOT_EXIST=c,exports.ERR_SOCKET_CONNECT_TO_SERVER_FAILED=i,exports.ERR_SOCKET_IS_NOT_CONNECTED=o,exports.POMSocket=u,exports.getSocket=function(e,t){return new u(e,t)}; | ||
"use strict";var e,t=require("diffie-hellman-ts"),s=require("socket.io-client"),n=require("./encryption.js");exports.SocketStatus=void 0,(e=exports.SocketStatus||(exports.SocketStatus={}))[e.Disconnected=1]="Disconnected",e[e.Connecting=2]="Connecting",e[e.Connected=3]="Connected";const c=new Error("shared secret is not exist"),o=new Error("socket is not connected"),i=new Error("socket connect to server failed"),r=new Error("session is expired"),a=new Error("message salt is missing"),h=new Error("message type is unknown");var d;!function(e){e.KeyExchange="key-exchange",e.EncryptedMessage="encrypted-message"}(d||(d={}));class u{aesKey;manualReconnectionCount=0;connectedEventReceived=!1;connectedEventListener;keyExchangeEventListener;listeners={};dhClient;sharedPublicNumber;socket;constructor(e,n){this.dhClient=new t.Client,this.sharedPublicNumber=this.dhClient.generatePublicNumber(),this.socket=s.io(e,{...n||{},autoConnect:!1})}get status(){return this.socket.connected&&this.aesKey&&this.connectedEventReceived?exports.SocketStatus.Connected:this.socket.disconnected?exports.SocketStatus.Disconnected:exports.SocketStatus.Connecting}connect(){let e,t;const s="object"==typeof this.socket.auth&&!!this.socket.auth.sessionID,c=n.createRandomString(32),o=e=>{try{const t=k({message:e});t.type===d.KeyExchange&&(this.generateAESKey(t.data,c),this.socket.off("data",o),this.keyExchangeEventListener&&this.keyExchangeEventListener.resolve())}catch(e){this.keyExchangeEventListener&&this.keyExchangeEventListener.reject(e),this.socket.off("data",o)}},i=()=>{this.connectedEventReceived=!0,this.connectedEventListener&&(this.connectedEventListener.resolve(),this.connectedEventListener=void 0),this.socket.off("connected",i)};return new Promise(((n,a)=>{const h=()=>{s?f({dhSharedPublicNumber:this.sharedPublicNumber,sessionId:this.socket.auth.sessionID,hkdfSalt:c}):e?f({dhSharedPublicNumber:this.sharedPublicNumber,sessionId:e,hkdfSalt:c}):t=!0,this.socket.off("connect",h)},d=s=>{t?f({dhSharedPublicNumber:this.sharedPublicNumber,sessionId:s,hkdfSalt:c}):e=s,this.socket.off("setupSession",d)},u=e=>{"io server disconnect"===e?k(r):this.manualReconnectionCount<3?(this.manualReconnectionCount+=1,this.connect().then((e=>{f(e)})).catch((e=>{k(e)}))):(this.manualReconnectionCount=0,k(new Error(e))),this.socket.off("disconnect",d)},E=e=>{console.log("handleConnectErrorEvent",e),"invalid session or expired!"===e.message?k(r):k(e),this.socket.off("connect_error",E)},k=e=>{this.socket.off("connect",h),this.socket.off("setupSession",d),this.socket.off("disconnect",u),this.socket.off("connect_error",E),a(e)},f=e=>{this.socket.off("connect",h),this.socket.off("setupSession",d),this.socket.off("disconnect",u),this.socket.off("connect_error",E),n(e)};this.socket.on("connect",h),this.socket.on("disconnect",u),this.socket.on("connect_error",E),s||this.socket.on("setupSession",d),this.socket.on("connected",i),this.socket.on("data",o),this.socket.connect()}))}generateAESKey(e,t){const s=this.dhClient.generateSharedSecret(e);this.aesKey=n.generateAESKey(s,t)}async waitForConnectedEvent(){return this.connectedEventReceived?Promise.resolve():new Promise(((e,t)=>{this.connectedEventListener={resolve:e,reject:t}}))}async waitForKeyExchangeEvent(){return this.aesKey?Promise.resolve():new Promise(((e,t)=>{this.keyExchangeEventListener={resolve:e,reject:t}}))}emitSharedPublicKey(){const e=f({type:d.KeyExchange,data:this.sharedPublicNumber});this.socket.emit("data",e)}disconnect(){this.socket.disconnect(),this.connectedEventReceived=!1,this.aesKey=void 0,this.sharedPublicNumber=this.dhClient.generatePublicNumber()}on(e){const t=t=>{E({message:t,key:this.aesKey,cb:e})};this.listeners.data=this.listeners.data||[],this.listeners.data.push({handler:t,cb:e}),this.socket.on("data",t)}off(e){const t=this.listeners.data;if(!t||0===t.length)return;const s=t.findIndex((t=>t.cb===e));-1!==s&&(this.socket.off("data",t[s].handler),t.splice(s,1))}once(e){const t=t=>{E({message:t,key:this.aesKey,cb:e}),this.off(e)};this.listeners.data=this.listeners.data||[],this.listeners.data.push({handler:t,cb:e}),this.socket.on("data",t)}send(e){if(!this.aesKey)throw c;if(this.status!==exports.SocketStatus.Connected)throw o;this.socket.emit("data",f({type:d.EncryptedMessage,data:e,key:this.aesKey}))}}function E(e){const{message:t,key:s,cb:n}=e;try{const e=k({message:t,key:s});n.success(e.data)}catch(e){n.error(e)}}function k(e){const{message:t,key:s}=e,o=JSON.parse(t),i=o.t;switch(i){case d.KeyExchange:return{type:i,data:o.d};case d.EncryptedMessage:if(!o.s)throw a;if(!s)throw c;return{type:i,data:n.decryptMessage(o.d,s,o.s).decryptedMessage};default:throw h}}function f(e){const{type:t,data:s,key:o}=e,i={t:t,d:s};switch(t){case d.KeyExchange:break;case d.EncryptedMessage:if(!o)throw c;const e=n.encryptMessage(s,o);i.d=e.encryptedMessage,i.s=e.iv;break;default:throw h}return JSON.stringify(i)}exports.createRandomString=n.createRandomString,exports.ERR_MESSAGE_SALT_IS_MISSING=a,exports.ERR_MESSAGE_TYPE_IS_UNKNOWN=h,exports.ERR_SESSION_IS_EXPIRED=r,exports.ERR_SHARED_SECRET_NOT_EXIST=c,exports.ERR_SOCKET_CONNECT_TO_SERVER_FAILED=i,exports.ERR_SOCKET_IS_NOT_CONNECTED=o,exports.POMSocket=u,exports.getSocket=function(e,t){return new u(e,t)}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@automata-network/pom-socket", | ||
"version": "0.0.2", | ||
"version": "0.0.3", | ||
"description": "A socket clinet for automata's Proof Of Machinehood", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
119
src/index.ts
@@ -120,7 +120,18 @@ import {Client} from 'diffie-hellman-ts'; | ||
const handleConnectedEvent = () => { | ||
this.connectedEventReceived = true; | ||
if (this.connectedEventListener) { | ||
this.connectedEventListener.resolve(); | ||
this.connectedEventListener = undefined; | ||
} | ||
this.socket.off('connected', handleConnectedEvent); | ||
}; | ||
return new Promise<SocketConnectionResult>((resolve, reject) => { | ||
this.socket.once('connect', () => { | ||
const handleConnectEvent = () => { | ||
if (!hasSessionId) { | ||
if (sid) { | ||
resolve({ | ||
resolvePromise({ | ||
dhSharedPublicNumber: this.sharedPublicNumber, | ||
@@ -134,3 +145,3 @@ sessionId: sid, | ||
} else { | ||
resolve({ | ||
resolvePromise({ | ||
dhSharedPublicNumber: this.sharedPublicNumber, | ||
@@ -141,22 +152,24 @@ sessionId: (this.socket.auth as any).sessionID, | ||
} | ||
}); | ||
if (!hasSessionId) { | ||
this.socket.once('setupSession', sessionId => { | ||
if (connected) { | ||
resolve({ | ||
dhSharedPublicNumber: this.sharedPublicNumber, | ||
sessionId, | ||
hkdfSalt: hkdfSalt, | ||
}); | ||
} else { | ||
sid = sessionId; | ||
} | ||
}); | ||
} | ||
this.socket.off('connect', handleConnectEvent); | ||
}; | ||
this.socket.once('disconnect', reason => { | ||
// TODO: handle session expired event | ||
const handleSetupSessionEvent = (sessionId: string) => { | ||
if (connected) { | ||
resolvePromise({ | ||
dhSharedPublicNumber: this.sharedPublicNumber, | ||
sessionId, | ||
hkdfSalt: hkdfSalt, | ||
}); | ||
} else { | ||
sid = sessionId; | ||
} | ||
if (this.manualReconnectionCount < 3) { | ||
this.socket.off('setupSession', handleSetupSessionEvent); | ||
}; | ||
const handleDisconnectEvent = (reason: string) => { | ||
if (reason === 'io server disconnect') { | ||
rejectPromise(ERR_SESSION_IS_EXPIRED); | ||
} else if (this.manualReconnectionCount < 3) { | ||
this.manualReconnectionCount += 1; | ||
@@ -166,6 +179,6 @@ | ||
.then(data => { | ||
resolve(data); | ||
resolvePromise(data); | ||
}) | ||
.catch(e => { | ||
reject(e); | ||
rejectPromise(e); | ||
}); | ||
@@ -175,19 +188,46 @@ } else { | ||
reject(new Error(reason)); | ||
rejectPromise(new Error(reason)); | ||
} | ||
}); | ||
this.socket.once('connect_error', error => { | ||
reject(error); | ||
}); | ||
this.socket.off('disconnect', handleSetupSessionEvent); | ||
}; | ||
this.socket.once('connected', () => { | ||
this.connectedEventReceived = true; | ||
if (this.connectedEventListener) { | ||
this.connectedEventListener.resolve(); | ||
this.connectedEventListener = undefined; | ||
const handleConnectErrorEvent = (e: Error) => { | ||
console.log('handleConnectErrorEvent', e); | ||
if (e.message === 'invalid session or expired!') { | ||
rejectPromise(ERR_SESSION_IS_EXPIRED); | ||
} else { | ||
rejectPromise(e); | ||
} | ||
}); | ||
this.socket.off('connect_error', handleConnectErrorEvent); | ||
}; | ||
const rejectPromise = (e: Error) => { | ||
this.socket.off('connect', handleConnectEvent); | ||
this.socket.off('setupSession', handleSetupSessionEvent); | ||
this.socket.off('disconnect', handleDisconnectEvent); | ||
this.socket.off('connect_error', handleConnectErrorEvent); | ||
reject(e); | ||
}; | ||
const resolvePromise = (result: SocketConnectionResult) => { | ||
this.socket.off('connect', handleConnectEvent); | ||
this.socket.off('setupSession', handleSetupSessionEvent); | ||
this.socket.off('disconnect', handleDisconnectEvent); | ||
this.socket.off('connect_error', handleConnectErrorEvent); | ||
resolve(result); | ||
}; | ||
this.socket.on('connect', handleConnectEvent); | ||
this.socket.on('disconnect', handleDisconnectEvent); | ||
this.socket.on('connect_error', handleConnectErrorEvent); | ||
if (!hasSessionId) { | ||
this.socket.on('setupSession', handleSetupSessionEvent); | ||
} | ||
this.socket.on('connected', handleConnectedEvent); | ||
this.socket.on('data', handleKeyExchangeEvent); | ||
@@ -272,5 +312,12 @@ | ||
once(cb: Callback) { | ||
this.socket.once('data', message => { | ||
const handler = (message: string) => { | ||
decryptData({message, key: this.aesKey, cb}); | ||
}); | ||
this.off(cb); | ||
}; | ||
this.listeners['data'] = this.listeners['data'] || []; | ||
this.listeners['data'].push({handler, cb}); | ||
this.socket.on('data', handler); | ||
} | ||
@@ -277,0 +324,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
44137
502