[tor-commits] [pluggable-transports/snowflake-webext] branch main updated: refactor: simplify `relayAddr` code

gitolite role git at cupani.torproject.org
Wed Nov 9 16:29:24 UTC 2022


This is an automated email from the git hooks/post-receive script.

cohosh pushed a commit to branch main
in repository pluggable-transports/snowflake-webext.

The following commit(s) were added to refs/heads/main by this push:
     new 21a2af4  refactor: simplify `relayAddr` code
21a2af4 is described below

commit 21a2af4af1bf933a9927f1ec0b0e549cbab1546a
Author: WofWca <wofwca at protonmail.com>
AuthorDate: Tue Nov 8 17:23:57 2022 +0400

    refactor: simplify `relayAddr` code
    
    All the removed things can be substituted with native URL.
    Also bump Node in CI configs to 10, where URL is available
    on the global object
---
 .gitlab-ci.yml         |  2 +-
 .travis.yml            |  2 +-
 README.md              |  1 -
 config.js              |  5 +---
 init-badge.js          |  3 +--
 init-node.js           |  2 --
 init-testing.js        |  1 -
 init-webext.js         |  3 +--
 proxypair.js           | 15 ++++--------
 snowflake.js           | 14 +----------
 spec/proxypair.spec.js |  6 ++---
 spec/snowflake.spec.js |  7 ------
 spec/util.spec.js      | 31 ------------------------
 spec/websocket.spec.js | 41 -------------------------------
 util.js                | 30 -----------------------
 websocket.js           | 66 +++++---------------------------------------------
 16 files changed, 20 insertions(+), 209 deletions(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 21a0218..8e5de5d 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,4 +1,4 @@
-image: node:8
+image: node:10
 
 before_script:
   - npm install
diff --git a/.travis.yml b/.travis.yml
index cea2037..7a2d9fa 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,7 @@
 language: node_js
 
 node_js:
-    - 8
+    - 10
 
 dist: xenial
 
diff --git a/README.md b/README.md
index 418e0c6..94569bd 100644
--- a/README.md
+++ b/README.md
@@ -197,7 +197,6 @@ var broker = new Broker(config.brokerUrl);
 
 var snowflake = new Snowflake(config, ui, broker);
 
-snowflake.setRelayAddr(config.relayAddr);
 snowflake.beginServingClients();
 ```
 
diff --git a/config.js b/config.js
index 2fc8c05..3f6d440 100644
--- a/config.js
+++ b/config.js
@@ -7,10 +7,7 @@ class Config {
 
 Config.prototype.brokerUrl = 'snowflake-broker.freehaven.net';
 
-Config.prototype.relayAddr = {
-  host: 'snowflake.freehaven.net',
-  port: '443'
-};
+Config.prototype.defaultRelayAddr = 'wss://snowflake.freehaven.net';
 
 // Original non-wss relay:
 // host: '192.81.135.242'
diff --git a/init-badge.js b/init-badge.js
index 0c4c00f..4f57348 100644
--- a/init-badge.js
+++ b/init-badge.js
@@ -174,13 +174,12 @@ var
   };
 
   tryProbe = function() {
-    WS.probeWebsocket(config.relayAddr)
+    WS.probeWebsocket(config.defaultRelayAddr)
     .then(
       () => {
         ui.turnOn();
         dbg('Contacting Broker at ' + broker.url);
         log('Starting snowflake');
-        snowflake.setRelayAddr(config.relayAddr);
         snowflake.beginServingClients();
       },
       () => {
diff --git a/init-node.js b/init-node.js
index 66c0fa4..e76e7dd 100644
--- a/init-node.js
+++ b/init-node.js
@@ -22,6 +22,4 @@ log('== snowflake proxy ==');
 
 dbg('Contacting Broker at ' + broker.url);
 
-snowflake.setRelayAddr(config.relayAddr);
-
 snowflake.beginServingClients();
diff --git a/init-testing.js b/init-testing.js
index 235f2b3..c1f6217 100644
--- a/init-testing.js
+++ b/init-testing.js
@@ -117,7 +117,6 @@ var
     }
     // Otherwise, begin setting up WebRTC and acting as a proxy.
     dbg('Contacting Broker at ' + broker.url);
-    snowflake.setRelayAddr(config.relayAddr);
     return snowflake.beginServingClients();
   };
 
diff --git a/init-webext.js b/init-webext.js
index daa8e9a..0a6c2b9 100644
--- a/init-webext.js
+++ b/init-webext.js
@@ -69,7 +69,7 @@ class WebExtUI extends UI {
   }
 
   tryProbe() {
-    WS.probeWebsocket(config.relayAddr)
+    WS.probeWebsocket(config.defaultRelayAddr)
     .then(
       () => {
         this.missingFeature = false;
@@ -280,7 +280,6 @@ var
     // Otherwise, begin setting up WebRTC and acting as a proxy.
     dbg('Contacting Broker at ' + broker.url);
     log('Starting snowflake');
-    snowflake.setRelayAddr(config.relayAddr);
     snowflake.beginServingClients();
   };
 
diff --git a/proxypair.js b/proxypair.js
index f3df964..c2dbdcd 100644
--- a/proxypair.js
+++ b/proxypair.js
@@ -12,11 +12,10 @@ Broker with an WebRTC answer.
 class ProxyPair {
 
   /**
-   * @param relayAddr the destination relay
    * @param {*} rateLimit specifies a rate limit on traffic
    * @param {Config} config
    */
-  constructor(relayAddr, rateLimit, config) {
+  constructor(rateLimit, config) {
     this.prepareDataChannel = this.prepareDataChannel.bind(this);
     this.connectRelay = this.connectRelay.bind(this);
     this.onClientToRelayMessage = this.onClientToRelayMessage.bind(this);
@@ -24,9 +23,8 @@ class ProxyPair {
     this.onError = this.onError.bind(this);
     this.flush = this.flush.bind(this);
 
-    /** @type {string | undefined} */
-    this.relayURL = undefined;
-    this.relayAddr = relayAddr;
+    /** @type {string | URL} */
+    this.relayURL = config.defaultRelayAddr;
     this.rateLimit = rateLimit;
     this.config = config;
     this.pcConfig = config.pcConfig;
@@ -175,10 +173,7 @@ class ProxyPair {
     if (peer_ip != null) {
       params.push(["client_ip", peer_ip]);
     }
-    const relay = this.relay =
-      (this.relayURL === undefined) ?
-        WS.makeWebsocket(this.relayAddr, params) :
-        WS.makeWebsocketFromURL(this.relayURL, params);
+    const relay = this.relay = WS.makeWebsocket(this.relayURL, params);
     relay.label = 'websocket-relay';
     relay.onopen = () => {
       clearTimeout(this.connectToRelayTimeoutId);
@@ -329,7 +324,7 @@ class ProxyPair {
   }
 
   /**
-   * @param {typeof this.relayURL} relayURL
+   * @param {URL | string} relayURL
    */
   setRelayURL(relayURL) {
     this.relayURL = relayURL;
diff --git a/snowflake.js b/snowflake.js
index c62ee62..30b3296 100644
--- a/snowflake.js
+++ b/snowflake.js
@@ -37,17 +37,6 @@ class Snowflake {
     this.retries = 0;
   }
 
-  /**
-   * Set the target relay address spec, which is expected to be websocket.
-   * TODO: Should potentially fetch the target from broker later, or modify
-   * entirely for the Tor-independent version.
-   * @param {{ host: string; port: string; }} relayAddr
-   */
-  setRelayAddr(relayAddr) {
-    this.relayAddr = relayAddr;
-    log('Using ' + relayAddr.host + ':' + relayAddr.port + ' as Relay.');
-  }
-
   /**
    * Start asking the broker for clients and serving them.
    */
@@ -171,7 +160,7 @@ class Snowflake {
    * @private
    */
   makeProxyPair() {
-    const pair = new ProxyPair(this.relayAddr, this.rateLimit, this.config);
+    const pair = new ProxyPair(this.rateLimit, this.config);
     this.proxyPairs.push(pair);
 
     log('Snowflake IDs: ' + (this.proxyPairs.map(p => p.id)).join(' | '));
@@ -225,7 +214,6 @@ class Snowflake {
 
 }
 
-Snowflake.prototype.relayAddr = null;
 Snowflake.prototype.rateLimit = null;
 
 Snowflake.MESSAGE = {
diff --git a/spec/proxypair.spec.js b/spec/proxypair.spec.js
index 3b8bc0a..c624dbf 100644
--- a/spec/proxypair.spec.js
+++ b/spec/proxypair.spec.js
@@ -36,14 +36,14 @@ var arrayMatching = function(sample) {
 
 describe('ProxyPair', function() {
 
-  var config, destination, fakeRelay, pp, rateLimit;
-  fakeRelay = Parse.address('0.0.0.0:12345');
+  var config, destination, pp, rateLimit;
   rateLimit = new DummyRateLimit;
   config = new Config;
+  config.defaultRelayAddr = 'wss://0.0.0.0:12345';
   destination = [];
 
   // Using the mock PeerConnection definition from spec/snowflake.spec.js
-  var pp = new ProxyPair(fakeRelay, rateLimit, config);
+  var pp = new ProxyPair(rateLimit, config);
 
   beforeEach(function() {
     return pp.begin();
diff --git a/spec/snowflake.spec.js b/spec/snowflake.spec.js
index bac49d0..24ee11e 100644
--- a/spec/snowflake.spec.js
+++ b/spec/snowflake.spec.js
@@ -58,13 +58,6 @@ describe('Snowflake', function() {
     expect(s.retries).toBe(0);
   });
 
-  it('sets relay address correctly', function() {
-    var s;
-    s = new Snowflake(config, ui, new FakeBroker());
-    s.setRelayAddr('foo');
-    expect(s.relayAddr).toEqual('foo');
-  });
-
   it('initalizes WebRTC connection', function() {
     var s;
     s = new Snowflake(config, ui, new FakeBroker());
diff --git a/spec/util.spec.js b/spec/util.spec.js
index 0789f9e..e1cd193 100644
--- a/spec/util.spec.js
+++ b/spec/util.spec.js
@@ -41,37 +41,6 @@ describe('Parse', function() {
 
   });
 
-  describe('address', function() {
-
-    it('parses IPv4', function() {
-      expect(Parse.address('')).toBeNull();
-      expect(Parse.address('3.3.3.3:4444')).toEqual({
-        host: '3.3.3.3',
-        port: 4444
-      });
-      expect(Parse.address('3.3.3.3')).toBeNull();
-      expect(Parse.address('3.3.3.3:0x1111')).toBeNull();
-      expect(Parse.address('3.3.3.3:-4444')).toBeNull();
-      expect(Parse.address('3.3.3.3:65536')).toBeNull();
-    });
-
-    it('parses IPv6', function() {
-      expect(Parse.address('[1:2::a:f]:4444')).toEqual({
-        host: '1:2::a:f',
-        port: 4444
-      });
-      expect(Parse.address('[1:2::a:f]')).toBeNull();
-      expect(Parse.address('[1:2::a:f]:0x1111')).toBeNull();
-      expect(Parse.address('[1:2::a:f]:-4444')).toBeNull();
-      expect(Parse.address('[1:2::a:f]:65536')).toBeNull();
-      expect(Parse.address('[1:2::ffff:1.2.3.4]:4444')).toEqual({
-        host: '1:2::ffff:1.2.3.4',
-        port: 4444
-      });
-    });
-
-  });
-
   describe('byte count', function() {
 
     it('returns null for bad inputs', function() {
diff --git a/spec/websocket.spec.js b/spec/websocket.spec.js
deleted file mode 100644
index 6c2ef2e..0000000
--- a/spec/websocket.spec.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/* global expect, it, describe, WS */
-
-/*
-jasmine tests for Snowflake websocket
-*/
-
-describe('BuildUrl', function() {
-
-  it('should parse just protocol and host', function() {
-    expect(WS.buildUrl('http', 'example.com')).toBe('http://example.com');
-  });
-
-  it('should handle different ports', function() {
-    expect(WS.buildUrl('http', 'example.com', 80)).toBe('http://example.com');
-    expect(WS.buildUrl('http', 'example.com', 81)).toBe('http://example.com:81');
-    expect(WS.buildUrl('http', 'example.com', 443)).toBe('http://example.com:443');
-    expect(WS.buildUrl('http', 'example.com', 444)).toBe('http://example.com:444');
-  });
-
-  it('should handle paths', function() {
-    expect(WS.buildUrl('http', 'example.com', 80, '/')).toBe('http://example.com/');
-    expect(WS.buildUrl('http', 'example.com', 80, '/test?k=%#v')).toBe('http://example.com/test%3Fk%3D%25%23v');
-    expect(WS.buildUrl('http', 'example.com', 80, '/test')).toBe('http://example.com/test');
-  });
-
-  it('should handle params', function() {
-    expect(WS.buildUrl('http', 'example.com', 80, '/test', [['k', '%#v']])).toBe('http://example.com/test?k=%25%23v');
-    expect(WS.buildUrl('http', 'example.com', 80, '/test', [['a', 'b'], ['c', 'd']])).toBe('http://example.com/test?a=b&c=d');
-  });
-
-  it('should handle ips', function() {
-    expect(WS.buildUrl('http', '1.2.3.4')).toBe('http://1.2.3.4');
-    expect(WS.buildUrl('http', '1:2::3:4')).toBe('http://[1:2::3:4]');
-  });
-
-  it('should handle bogus', function() {
-    expect(WS.buildUrl('http', 'bog][us')).toBe('http://bog%5D%5Bus');
-    expect(WS.buildUrl('http', 'bog:u]s')).toBe('http://bog%3Au%5Ds');
-  });
-
-});
diff --git a/util.js b/util.js
index 7c865e8..9b9ffa8 100644
--- a/util.js
+++ b/util.js
@@ -131,36 +131,6 @@ class Parse {
     return result;
   }
 
-  /**
-   * @param {string} spec
-   * Parse an address in the form 'host:port'. Returns an Object with keys 'host'
-   * (String) and 'port' (int). Returns null on error.
-   */
-  static address(spec) {
-    let m = null;
-    if (!m) {
-      // IPv6 syntax.
-      m = spec.match(/^\[([\0-9a-fA-F:.]+)\]:([0-9]+)$/);
-    }
-    if (!m) {
-      // IPv4 syntax.
-      m = spec.match(/^([0-9.]+):([0-9]+)$/);
-    }
-    if (!m) {
-      // TODO: Domain match
-      return null;
-    }
-    const host = m[1];
-    const port = parseInt(m[2], 10);
-    if (isNaN(port) || port < 0 || port > 65535) {
-      return null;
-    }
-    return {
-      host: host,
-      port: port
-    };
-  }
-
   /**
    * Parse a count of bytes. A suffix of 'k', 'm', or 'g' (or uppercase)
    * does what you would think. Returns null on error.
diff --git a/websocket.js b/websocket.js
index ed236c3..4b56756 100644
--- a/websocket.js
+++ b/websocket.js
@@ -2,65 +2,15 @@
 Only websocket-specific stuff.
 */
 
+// eslint-disable-next-line no-unused-vars
 class WS {
-
-  /**
-   * Build an escaped URL string from unescaped components. Only scheme and host
-   * are required. See RFC 3986, section 3.
-   */
-  static buildUrl(scheme, host, port, path, params) {
-    const parts = [];
-    parts.push(encodeURIComponent(scheme));
-    parts.push('://');
-    // If it contains a colon but no square brackets, treat it as IPv6.
-    if (host.match(/:/) && !host.match(/[[\]]/)) {
-      parts.push('[');
-      parts.push(host);
-      parts.push(']');
-    } else {
-      parts.push(encodeURIComponent(host));
-    }
-    if (undefined !== port && this.DEFAULT_PORTS[scheme] !== port) {
-      parts.push(':');
-      parts.push(encodeURIComponent(port.toString()));
-    }
-    if (undefined !== path && '' !== path) {
-      if (!path.match(/^\//)) {
-        path = '/' + path;
-      }
-      path = path.replace(/[^/]+/, function (m) {
-        return encodeURIComponent(m);
-      });
-      parts.push(path);
-    }
-    if (undefined !== params) {
-      parts.push('?');
-      parts.push(new URLSearchParams(params).toString());
-    }
-    return parts.join('');
-  }
-
-  static makeWebsocket(addr, params) {
-    const wsProtocol = this.WSS_ENABLED ? 'wss' : 'ws';
-    const url = this.buildUrl(wsProtocol, addr.host, addr.port, '/', params);
-    const ws = new WebSocket(url);
-    /*
-    'User agents can use this as a hint for how to handle incoming binary data:
-    if the attribute is set to 'blob', it is safe to spool it to disk, and if it
-    is set to 'arraybuffer', it is likely more efficient to keep the data in
-    memory.'
-    */
-    ws.binaryType = 'arraybuffer';
-    return ws;
-  }
-
   /**
    * Creates a websocket connection from a URL and params to override
    * @param {URL|string} url
    * @param {URLSearchParams|string[][]} params
    * @return {WebSocket}
    */
-  static makeWebsocketFromURL(url, params) {
+  static makeWebsocket(url, params) {
     let parsedURL = new URL(url);
     let urlpa = new URLSearchParams(params);
     urlpa.forEach(function (value, key) {
@@ -78,9 +28,12 @@ class WS {
     return ws;
   }
 
+  /**
+   * @param {URL | string} addr
+   */
   static probeWebsocket(addr) {
     return /** @type {Promise<void>} */(new Promise((resolve, reject) => {
-      const ws = WS.makeWebsocket(addr);
+      const ws = WS.makeWebsocket(addr, []);
       ws.onopen = () => {
         resolve();
         ws.close();
@@ -93,10 +46,3 @@ class WS {
   }
 
 }
-
-WS.WSS_ENABLED = true;
-
-WS.DEFAULT_PORTS = {
-  http: 80,
-  https: 443
-};

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.


More information about the tor-commits mailing list