index.js 6.7 KB

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