index.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. var process = require('process')
  2. // Handle SIGINT
  3. process.on('SIGINT', () => {
  4. console.info("SIGINT Received, exiting...")
  5. process.exit(0)
  6. })
  7. // Handle SIGTERM
  8. process.on('SIGTERM', () => {
  9. console.info("SIGTERM Received, exiting...")
  10. process.exit(0)
  11. })
  12. const parser = require('ua-parser-js');
  13. const { uniqueNamesGenerator, animals, colors } = require('unique-names-generator');
  14. class SnapdropServer {
  15. constructor(port) {
  16. const WebSocket = require('ws');
  17. this._wss = new WebSocket.Server({ port: port });
  18. this._wss.on('connection', (socket, request) => this._onConnection(new Peer(socket, request)));
  19. this._wss.on('headers', (headers, response) => this._onHeaders(headers, response));
  20. this._rooms = {};
  21. console.log('Snapdrop is running on port', port);
  22. }
  23. _onConnection(peer) {
  24. this._joinRoom(peer);
  25. peer.socket.on('message', message => this._onMessage(peer, message));
  26. this._keepAlive(peer);
  27. // send displayName
  28. this._send(peer, { type: 'displayName', message: peer.name.displayName });
  29. }
  30. _onHeaders(headers, response) {
  31. if (response.headers.cookie && response.headers.cookie.indexOf('peerid=') > -1) return;
  32. response.peerId = Peer.uuid();
  33. headers.push('Set-Cookie: peerid=' + response.peerId + "; SameSite=Strict; Secure");
  34. }
  35. _onMessage(sender, message) {
  36. // Try to parse message
  37. try {
  38. message = JSON.parse(message);
  39. } catch (e) {
  40. return; // TODO: handle malformed JSON
  41. }
  42. switch (message.type) {
  43. case 'disconnect':
  44. this._leaveRoom(sender);
  45. break;
  46. case 'pong':
  47. sender.lastBeat = Date.now();
  48. break;
  49. }
  50. // relay message to recipient
  51. if (message.to && this._rooms[sender.ip]) {
  52. const recipientId = message.to; // TODO: sanitize
  53. const recipient = this._rooms[sender.ip][recipientId];
  54. delete message.to;
  55. // add sender id
  56. message.sender = sender.id;
  57. this._send(recipient, message);
  58. return;
  59. }
  60. }
  61. _joinRoom(peer) {
  62. // if room doesn't exist, create it
  63. if (!this._rooms[peer.ip]) {
  64. this._rooms[peer.ip] = {};
  65. }
  66. // notify all other peers
  67. for (const otherPeerId in this._rooms[peer.ip]) {
  68. const otherPeer = this._rooms[peer.ip][otherPeerId];
  69. this._send(otherPeer, {
  70. type: 'peer-joined',
  71. peer: peer.getInfo()
  72. });
  73. }
  74. // notify peer about the other peers
  75. const otherPeers = [];
  76. for (const otherPeerId in this._rooms[peer.ip]) {
  77. otherPeers.push(this._rooms[peer.ip][otherPeerId].getInfo());
  78. }
  79. this._send(peer, {
  80. type: 'peers',
  81. peers: otherPeers
  82. });
  83. // add peer to room
  84. this._rooms[peer.ip][peer.id] = peer;
  85. }
  86. _leaveRoom(peer) {
  87. if (!this._rooms[peer.ip] || !this._rooms[peer.ip][peer.id]) return;
  88. this._cancelKeepAlive(this._rooms[peer.ip][peer.id]);
  89. // delete the peer
  90. delete this._rooms[peer.ip][peer.id];
  91. peer.socket.terminate();
  92. //if room is empty, delete the room
  93. if (!Object.keys(this._rooms[peer.ip]).length) {
  94. delete this._rooms[peer.ip];
  95. } else {
  96. // notify all other peers
  97. for (const otherPeerId in this._rooms[peer.ip]) {
  98. const otherPeer = this._rooms[peer.ip][otherPeerId];
  99. this._send(otherPeer, { type: 'peer-left', peerId: peer.id });
  100. }
  101. }
  102. }
  103. _send(peer, message) {
  104. if (!peer) return;
  105. if (this._wss.readyState !== this._wss.OPEN) return;
  106. message = JSON.stringify(message);
  107. peer.socket.send(message, error => '');
  108. }
  109. _keepAlive(peer) {
  110. this._cancelKeepAlive(peer);
  111. var timeout = 30000;
  112. if (!peer.lastBeat) {
  113. peer.lastBeat = Date.now();
  114. }
  115. if (Date.now() - peer.lastBeat > 2 * timeout) {
  116. this._leaveRoom(peer);
  117. return;
  118. }
  119. this._send(peer, { type: 'ping' });
  120. peer.timerId = setTimeout(() => this._keepAlive(peer), timeout);
  121. }
  122. _cancelKeepAlive(peer) {
  123. if (peer && peer.timerId) {
  124. clearTimeout(peer.timerId);
  125. }
  126. }
  127. }
  128. class Peer {
  129. constructor(socket, request) {
  130. // set socket
  131. this.socket = socket;
  132. // set remote ip
  133. this._setIP(request);
  134. // set peer id
  135. this._setPeerId(request)
  136. // is WebRTC supported ?
  137. this.rtcSupported = request.url.indexOf('webrtc') > -1;
  138. // set name
  139. this._setName(request);
  140. // for keepalive
  141. this.timerId = 0;
  142. this.lastBeat = Date.now();
  143. }
  144. _setIP(request) {
  145. if (request.headers['x-forwarded-for']) {
  146. this.ip = request.headers['x-forwarded-for'].split(/\s*,\s*/)[0];
  147. } else {
  148. this.ip = request.connection.remoteAddress;
  149. }
  150. // IPv4 and IPv6 use different values to refer to localhost
  151. if (this.ip == '::1' || this.ip == '::ffff:127.0.0.1') {
  152. this.ip = '127.0.0.1';
  153. }
  154. }
  155. _setPeerId(request) {
  156. if (request.peerId) {
  157. this.id = request.peerId;
  158. } else {
  159. this.id = request.headers.cookie.replace('peerid=', '');
  160. }
  161. }
  162. toString() {
  163. return `<Peer id=${this.id} ip=${this.ip} rtcSupported=${this.rtcSupported}>`
  164. }
  165. _setName(req) {
  166. var ua = parser(req.headers['user-agent']);
  167. this.name = {
  168. model: ua.device.model,
  169. os: ua.os.name,
  170. browser: ua.browser.name,
  171. type: ua.device.type,
  172. displayName: uniqueNamesGenerator({ length: 2, separator: ' ', dictionaries: [colors, animals], style: 'capital' })
  173. };
  174. }
  175. getInfo() {
  176. return {
  177. id: this.id,
  178. name: this.name,
  179. rtcSupported: this.rtcSupported
  180. }
  181. }
  182. // return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  183. static uuid() {
  184. let uuid = '',
  185. ii;
  186. for (ii = 0; ii < 32; ii += 1) {
  187. switch (ii) {
  188. case 8:
  189. case 20:
  190. uuid += '-';
  191. uuid += (Math.random() * 16 | 0).toString(16);
  192. break;
  193. case 12:
  194. uuid += '-';
  195. uuid += '4';
  196. break;
  197. case 16:
  198. uuid += '-';
  199. uuid += (Math.random() * 4 | 8).toString(16);
  200. break;
  201. default:
  202. uuid += (Math.random() * 16 | 0).toString(16);
  203. }
  204. }
  205. return uuid;
  206. };
  207. }
  208. const server = new SnapdropServer(process.env.PORT || 3000);