This is an automated email from the git hooks/post-receive script.
meskio pushed a commit to branch main in repository pluggable-transports/snowflake-webext.
commit 31deee329a8b364067c0e57a7c780dee38290b75 Author: WofWca wofwca@protonmail.com AuthorDate: Sat Jun 18 18:49:27 2022 +0300
refactor: simplify variable declarations --- broker.js | 10 +++------- init-testing.js | 17 ++++++----------- proxypair.js | 22 +++++++++------------- snowflake.js | 33 +++++++++++++-------------------- util.js | 50 ++++++++++++++++++++------------------------------ 5 files changed, 51 insertions(+), 81 deletions(-)
diff --git a/broker.js b/broker.js index e993a48..8d084e0 100644 --- a/broker.js +++ b/broker.js @@ -41,8 +41,7 @@ class Broker { // TODO: Actually support multiple clients. getClientOffer(id, numClientsConnected) { return new Promise((fulfill, reject) => { - var xhr; - xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.DONE !== xhr.readyState) { return; @@ -81,10 +80,9 @@ class Broker { // Assumes getClientOffer happened, and a WebRTC SDP answer has been generated. // Sends it back to the broker, which passes it to back to the original client. sendAnswer(id, answer) { - var xhr; dbg(id + ' - Sending answer back to broker...\n'); dbg(answer.sdp); - xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.DONE !== xhr.readyState) { return; @@ -109,11 +107,9 @@ class Broker { // urlSuffix for the broker is different depending on what action // is desired. _postRequest(xhr, urlSuffix, payload) { - var err; try { xhr.open('POST', this.url + urlSuffix); - } catch (error) { - err = error; + } catch (err) { /* An exception happens here when, for example, NoScript allows the domain on which the proxy badge runs, but not the domain to which it's trying diff --git a/init-testing.js b/init-testing.js index 7724004..0905b80 100644 --- a/init-testing.js +++ b/init-testing.js @@ -16,8 +16,7 @@ class DebugUI extends UI {
// Status bar setStatus(msg) { - var txt; - txt = document.createTextNode('Status: ' + msg); + const txt = document.createTextNode('Status: ' + msg); while (this.$status.firstChild) { this.$status.removeChild(this.$status.firstChild); } @@ -83,18 +82,14 @@ var snowflake, query, debug, ui, silenceNotifications, log, dbg, init; };
init = function() { - var broker, config, ui; - config = new Config("testing"); + const config = new Config("testing"); if ('off' !== query['ratelimit']) { config.rateLimitBytes = Params.getByteCount(query, 'ratelimit', config.rateLimitBytes); } - ui = null; - if (document.getElementById('status') !== null) { - ui = new DebugUI(); - } else { - ui = new UI(); - } - broker = new Broker(config); + const ui = document.getElementById('status') !== null + ? new DebugUI() + : new UI(); + const broker = new Broker(config); snowflake = new Snowflake(config, ui, broker); log('== snowflake proxy =='); if (Util.snowflakeIsDisabled(config.cookieName)) { diff --git a/proxypair.js b/proxypair.js index 1d9689e..e423b59 100644 --- a/proxypair.js +++ b/proxypair.js @@ -47,8 +47,7 @@ class ProxyPair { }; // OnDataChannel triggered remotely from the client when connection succeeds. return this.pc.ondatachannel = (dc) => { - var channel; - channel = dc.channel; + const channel = dc.channel; dbg('Data Channel established...'); this.prepareDataChannel(channel); return this.client = channel; @@ -99,7 +98,6 @@ class ProxyPair {
// Assumes WebRTC datachannel is connected. connectRelay() { - var params, peer_ip, ref; dbg('Connecting to relay...'); // Get a remote IP address from the PeerConnection, if possible. Add it to // the WebSocket URL's query string if available. @@ -108,8 +106,9 @@ class ProxyPair { // are not marked experimental, were undefined when I tried them in Firefox // 52.2.0. // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/remoteDes... - peer_ip = Parse.ipFromSDP((ref = this.pc.remoteDescription) != null ? ref.sdp : void 0); - params = []; + const desc = this.pc.remoteDescription; + const peer_ip = Parse.ipFromSDP(desc!= null ? desc.sdp : undefined); + const params = []; if (peer_ip != null) { params.push(["client_ip", peer_ip]); } @@ -174,8 +173,7 @@ class ProxyPair { }
onError(event) { - var ws; - ws = event.target; + const ws = event.target; log(ws.label + ' error.'); return this.close(); } @@ -204,25 +202,23 @@ class ProxyPair {
// Send as much data in both directions as the rate limit currently allows. flush() { - var busy, checkChunks; if (this.flush_timeout_id) { clearTimeout(this.flush_timeout_id); } this.flush_timeout_id = null; - busy = true; - checkChunks = () => { - var chunk; + let busy = true; + const checkChunks = () => { busy = false; // WebRTC --> websocket if (this.relayIsReady() && this.relay.bufferedAmount < this.MAX_BUFFER && this.c2rSchedule.length > 0) { - chunk = this.c2rSchedule.shift(); + const chunk = this.c2rSchedule.shift(); this.rateLimit.update(chunk.byteLength); this.relay.send(chunk); busy = true; } // websocket --> WebRTC if (this.webrtcIsReady() && this.client.bufferedAmount < this.MAX_BUFFER && this.r2cSchedule.length > 0) { - chunk = this.r2cSchedule.shift(); + const chunk = this.r2cSchedule.shift(); this.rateLimit.update(chunk.byteLength); this.client.send(chunk); return busy = true; diff --git a/snowflake.js b/snowflake.js index 301d4fd..7354b97 100644 --- a/snowflake.js +++ b/snowflake.js @@ -52,16 +52,15 @@ class Snowflake { // Regularly poll Broker for clients to serve until this snowflake is // serving at capacity, at which point stop polling. pollBroker() { - var msg, pair, recv; // Poll broker for clients. - pair = this.makeProxyPair(); + const pair = this.makeProxyPair(); if (!pair) { log('At client capacity.'); return; } log('Polling broker..'); // Do nothing until a new proxyPair is available. - msg = 'Polling for client ... '; + let msg = 'Polling for client ... '; if (this.retries > 0) { msg += '[retries: ' + this.retries + ']'; } @@ -69,7 +68,7 @@ class Snowflake { //update NAT type console.log("NAT type: " + this.ui.natType); this.broker.setNATType(this.ui.natType); - recv = this.broker.getClientOffer(pair.id, this.proxyPairs.length); + const recv = this.broker.getClientOffer(pair.id, this.proxyPairs.length); recv.then((resp) => { var clientNAT = resp.NAT; if (!this.receiveOffer(pair, resp.Offer, resp.RelayURL)) { @@ -114,13 +113,11 @@ class Snowflake { // Receive an SDP offer from some client assigned by the Broker, // |pair| - an available ProxyPair. receiveOffer(pair, desc, relayURL) { - var e, offer, sdp; - try { if (relayURL !== undefined) { - let relayURLParsed = new URL(relayURL); - let hostname = relayURLParsed.hostname; - let protocol = relayURLParsed.protocol; + const relayURLParsed = new URL(relayURL); + const hostname = relayURLParsed.hostname; + const protocol = relayURLParsed.protocol; if (protocol !== "wss:") { log('incorrect relay url protocol'); return false; @@ -131,29 +128,27 @@ class Snowflake { } pair.setRelayURL(relayURL); } - offer = JSON.parse(desc); + const offer = JSON.parse(desc); dbg('Received:\n\n' + offer.sdp + '\n'); - sdp = new RTCSessionDescription(offer); + const sdp = new RTCSessionDescription(offer); if (pair.receiveWebRTCOffer(sdp)) { this.sendAnswer(pair); return true; } else { return false; } - } catch (error) { - e = error; + } catch (e) { log('ERROR: Unable to receive Offer: ' + e); return false; } }
sendAnswer(pair) { - var fail, next; - next = function (sdp) { + const next = function (sdp) { dbg('webrtc: Answer ready.'); pair.pc.setLocalDescription(sdp).catch(fail); }; - fail = function () { + const fail = function () { pair.close(); dbg('webrtc: Failed to create or set Answer'); }; @@ -167,8 +162,7 @@ class Snowflake { if (this.proxyPairs.length >= this.config.maxNumClients) { return null; } - var pair; - pair = new ProxyPair(this.relayAddr, this.rateLimit, this.config); + const pair = new ProxyPair(this.relayAddr, this.rateLimit, this.config); this.proxyPairs.push(pair);
log('Snowflake IDs: ' + (this.proxyPairs.map(function (p) { @@ -176,9 +170,8 @@ class Snowflake { })).join(' | '));
pair.onCleanup = () => { - var ind; // Delete from the list of proxy pairs. - ind = this.proxyPairs.indexOf(pair); + const ind = this.proxyPairs.indexOf(pair); if (ind > -1) { this.proxyPairs.splice(ind, 1); } diff --git a/util.js b/util.js index 710ad51..9a7673b 100644 --- a/util.js +++ b/util.js @@ -69,8 +69,7 @@ class Util { // Sends it back to the broker, which passes it back to the original client. static sendOffer(offer) { return new Promise((fulfill, reject) => { - var xhr; - xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); xhr.timeout = 30 * 1000; xhr.onreadystatechange = function() { if (xhr.DONE !== xhr.readyState) { @@ -104,20 +103,16 @@ class Parse { // object mapping cookies names to values. Returns null on error. // http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-8747038 static cookie(cookies) { - var i, j, len, name, result, string, strings, value; - result = {}; - strings = []; - if (cookies) { - strings = cookies.split(';'); - } - for (i = 0, len = strings.length; i < len; i++) { - string = strings[i]; - j = string.indexOf('='); + const result = {}; + const strings = cookies ? cookies.split(';') : []; + for (let i = 0, len = strings.length; i < len; i++) { + const string = strings[i]; + const j = string.indexOf('='); if (-1 === j) { return null; } - name = decodeURIComponent(string.substr(0, j).trim()); - value = decodeURIComponent(string.substr(j + 1).trim()); + const name = decodeURIComponent(string.substr(0, j).trim()); + const value = decodeURIComponent(string.substr(j + 1).trim()); if (!(name in result)) { result[name] = value; } @@ -128,8 +123,7 @@ class Parse { // 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) { - var host, m, port; - m = null; + let m = null; if (!m) { // IPv6 syntax. m = spec.match(/^[([\0-9a-fA-F:.]+)]:([0-9]+)$/); @@ -142,8 +136,8 @@ class Parse { // TODO: Domain match return null; } - host = m[1]; - port = parseInt(m[2], 10); + const host = m[1]; + const port = parseInt(m[2], 10); if (isNaN(port) || port < 0 || port > 65535) { return null; } @@ -184,17 +178,16 @@ class Parse { // https://tools.ietf.org/html/rfc4566#section-5.7 // https://tools.ietf.org/html/rfc5245#section-15 static ipFromSDP(sdp) { - var i, len, m, pattern, ref; console.log(sdp); - ref = [ + const ref = [ /^a=candidate:[a-zA-Z0-9+/]+ \d+ udp \d+ ([\d.]+) /mg, /^a=candidate:[a-zA-Z0-9+/]+ \d+ udp \d+ ([0-9A-Fa-f:.]+) /mg, /^c=IN IP4 ([\d.]+)(?:(?:/\d+)?/\d+)?(:? |$)/mg, /^c=IN IP6 ([0-9A-Fa-f:.]+)(?:/\d+)?(:? |$)/mg ]; - for (i = 0, len = ref.length; i < len; i++) { - pattern = ref[i]; - m = pattern.exec(sdp); + for (let i = 0, len = ref.length; i < len; i++) { + const pattern = ref[i]; + let m = pattern.exec(sdp); while (m != null) { if(Parse.isRemoteIP(m[1])) return m[1]; m = pattern.exec(sdp); @@ -205,9 +198,8 @@ class Parse { // Parse the mapped port out of an ice candidate returned from the // onicecandidate callback static portFromCandidate(c) { - var m, pattern; - pattern = /(?:[\d.]+|[0-9A-Fa-f:.]+) (\d+) typ srflx/m; - m = pattern.exec(c); + const pattern = /(?:[\d.]+|[0-9A-Fa-f:.]+) (\d+) typ srflx/m; + const m = pattern.exec(c); if (m != null) { return m[1]; } @@ -247,8 +239,7 @@ class Params { if (!query.has(param)) { return defaultValue; } - var val; - val = query.get(param); + const val = query.get(param); if ('true' === val || '1' === val || '' === val) { return true; } @@ -279,9 +270,8 @@ class BucketRateLimit { }
age() { - var delta, now; - now = new Date(); - delta = (now - this.lastUpdate) / 1000.0; + const now = new Date(); + const delta = (now - this.lastUpdate) / 1000.0; this.lastUpdate = now; this.amount -= delta * this.capacity / this.time; if (this.amount < 0.0) {