index.js 7.4 KB

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