14 Commits 5b0e5425ef ... 9bec4f50f2

Author SHA1 Message Date
  Alyssa Rosenzweig 9bec4f50f2 Merge branch 'bad-otr-dont-use' 5 years ago
  Alyssa Rosenzweig 8bebc41a79 Appease eslint 5 years ago
  Alyssa Rosenzweig a12eb237d6 Whitelist strikethrough 5 years ago
  Alyssa Rosenzweig ba975d445d Integrate sanitize 5 years ago
  Alyssa Rosenzweig 226d63f673 Merge branch 'master' into bad-otr-dont-use 5 years ago
  Alyssa Rosenzweig f1b4f7c9e6 Deduplicate carbons 5 years ago
  Alyssa Rosenzweig ab16f2d509 Switch from requiring encryption to whitespace tag (don't regress non-OTR) 5 years ago
  Alyssa Rosenzweig 53d22eae5d Handle actions client-side 5 years ago
  Alyssa Rosenzweig c8b4f76cb5 Carbon plaintexts 5 years ago
  Alyssa Rosenzweig 23f0d86740 Fix regression with group chats 5 years ago
  Alyssa Rosenzweig 7da704f11a Merge branch 'master' into bad-otr-dont-use 5 years ago
  Alyssa Rosenzweig d92085f515 Add OTR vendored deps 5 years ago
  Alyssa Rosenzweig 67bf0d0900 Fix entrypoint for sent messages 5 years ago
  Alyssa Rosenzweig 086558cb16 Quick and dirty (read: bad) integrate of otr.js 5 years ago
6 changed files with 7354 additions and 5 deletions
  1. 5 0
      index.html
  2. 115 5
      src/main.js
  3. 1705 0
      vendor/otr/bigint.js
  4. 2434 0
      vendor/otr/crypto.js
  5. 455 0
      vendor/otr/eventemitter.js
  6. 2640 0
      vendor/otr/otr.js

+ 5 - 0
index.html

@@ -121,6 +121,11 @@
         <script src="vendor/emoji.js"></script>
         <script src="vendor/countries-rev.js"></script>
 
+        <script src="vendor/otr/bigint.js"></script>
+        <script src="vendor/otr/crypto.js"></script>
+        <script src="vendor/otr/eventemitter.js"></script>
+        <script src="vendor/otr/otr.js"></script>
+
         <script src="src/emoji-emoticon-to-unicode.js"></script>
         <script src="src/emojify.js"></script>
         <script src="src/emoji-font.js"></script>

+ 115 - 5
src/main.js

@@ -23,6 +23,24 @@
 
 'use strict';
 
+let otrKey = null;
+
+if (!localStorage.otrKey) {
+    otrKey = new window.DSA();
+    localStorage.otrKey = otrKey.packPrivate();
+} else {
+    otrKey = window.DSA.parsePrivate(localStorage.otrKey);
+}
+
+const otrTag = window.OTR.makeInstanceTag();
+
+const otrOptions = {
+    fragment_size: 800,
+    send_interval: 200,
+    priv: otrKey,
+    instance_tag: otrTag
+};
+
 const {
     accountDropdown: tmplAccountDropdown,
     accountDropdownOption: tmplAccountDropdownOption,
@@ -489,7 +507,11 @@ const flushMessageGroup = function() {
 /* Applies /me to a message body */
 
 const meify = function(author, msg) {
-    return `<em>${author.alias} ${msg}</em>`;
+    if (!msg.startsWith('/me '))
+        return msg;
+
+    const sans_me = msg.slice('/me '.length);
+    return `<em>${author.alias} ${sans_me}</em>`;
 };
 
 const displayMessage = function(message, flush) {
@@ -517,11 +539,15 @@ const displayMessage = function(message, flush) {
         }
     }
 
+    /* Process the message content. This must be client-side to support
+     * end-to-end encryption */
+
+    const meified = meify(authorDetails, message.content);
+    const sanitized = window.sanitizeHtmlString(meified);
+
     const messageHTML = tmplMessage(Object.assign({}, message, {
         authorDetails,
-
-        /* Sanitized on the backend */
-        contentHTML: message.isAction ? meify(authorDetails, message.content) : message.content
+        contentHTML: sanitized,
     }));
 
     if (lastGroup.author !== authorDetails.id) {
@@ -550,7 +576,71 @@ const displayMessage = function(message, flush) {
     }
 };
 
+/* Enables OTR with a buddy if it's not already, returning the OTR obejct */
+
+const getBuddyOTR = (buddy) => {
+    /* Check for OTR */
+    const roomDetails = getRoomDetails(buddy);
+
+    if (!roomDetails.otr) {
+        /* Initialize OTR with this person */
+        roomDetails.otr = new window.OTR(otrOptions);
+
+        /* Set aggressive policy for now */
+        roomDetails.otr.REQUIRE_ENCRYPTION = false;
+        roomDetails.otr.ALLOW_V3 = false;
+        roomDetails.otr.SEND_WHITESPACE_TAG = true;
+        roomDetails.otr.WHITESPACE_START_AKE = true;
+
+        roomDetails.otr.on('io', (msg, meta) => {
+            /* We got a message to pass directly to the socket */
+            console.log('->' + msg, meta);
+            window.backendMessage(buddy, msg);
+        });
+
+        roomDetails.otr.on('ui', (msg, encrypted, meta) => {
+            console.log('<- ' + msg, encrypted, meta);
+            /* We got a (decrypted?) message, hooray */
+            onReceiveMessageDisplay({
+                flags: 0,
+                buddy: buddy,
+                content: msg
+            }, true);
+        });
+
+        roomDetails.otr.on('status', function (state) {
+            console.log(state);
+        });
+
+        roomDetails.otr.on('error', (err, sev) => {
+            console.error(err, sev);
+        });
+    }
+
+    return roomDetails.otr;
+};
+
 const onReceiveMessage = function(message, flush) {
+    if (message.chat) {
+        /* mpOTR not supported */
+        onReceiveMessageDisplay(message, flush);
+    } else if (message.buddy) {
+        if (message.flags & PURPLE_MESSAGE_SEND) {
+            /* Carbon of a message we sent, either on our machine or
+             * elsewhere. If it's OTR, we ignore it since it effectively
+             * doesn't exist. If it's plain-text, pass is through as is */
+
+            if (!message.content.includes('?OTR')) {
+                onReceiveMessageDisplay(message, flush);
+            }
+        } else {
+            /* Message received, feed through OTR */
+            getBuddyOTR(message.buddy).receiveMsg(message.content);
+        }
+    }
+};
+
+const onReceiveMessageDisplay = function(message, flush) {
     const isOurMessage = message.flags & PURPLE_MESSAGE_SEND;
 
     const roomDetails = getRoomDetails(message.chat || message.buddy);
@@ -853,8 +943,28 @@ const submitChatMessage = () => {
     /* Obviously if we've wiped the input, we're done typing */
     sendTypingState(TYPING_NONE);
 
+    const emojied = window.emojify(content);
+
     if (content.length) {
-        window.backendMessage(chatPaneRoomID, window.emojify(content));
+        if (getRoomType(chatPaneRoomID) === 'buddy') {
+            /* Feed through OTR */
+            const otr = getBuddyOTR(chatPaneRoomID);
+            otr.sendMsg(emojied);
+
+            /* Mirror for ourselves, if it'll be OTR-encrypted (such that we
+             * need the manual carbon) */
+
+            if (otr.msgstate === window.OTR.CONST.MSGSTATE_ENCRYPTED) {
+                onReceiveMessageDisplay({
+                    flags: PURPLE_MESSAGE_SEND,
+                    buddy: chatPaneRoomID,
+                    content: emojied
+                }, true);
+            }
+        } else {
+            /* mpOTR not supported */
+            window.backendMessage(chatPaneRoomID, emojied);
+        }
     }
 };
 

File diff suppressed because it is too large
+ 1705 - 0
vendor/otr/bigint.js


File diff suppressed because it is too large
+ 2434 - 0
vendor/otr/crypto.js


+ 455 - 0
vendor/otr/eventemitter.js

@@ -0,0 +1,455 @@
+/*!
+ * EventEmitter v4.2.3 - git.io/ee
+ * Oliver Caldwell
+ * MIT license
+ * @preserve
+ */
+
+(function () {
+	'use strict';
+
+	/**
+	 * Class for managing events.
+	 * Can be extended to provide event functionality in other classes.
+	 *
+	 * @class EventEmitter Manages event registering and emitting.
+	 */
+	function EventEmitter() {}
+
+	// Shortcuts to improve speed and size
+
+	// Easy access to the prototype
+	var proto = EventEmitter.prototype;
+
+	/**
+	 * Finds the index of the listener for the event in it's storage array.
+	 *
+	 * @param {Function[]} listeners Array of listeners to search through.
+	 * @param {Function} listener Method to look for.
+	 * @return {Number} Index of the specified listener, -1 if not found
+	 * @api private
+	 */
+	function indexOfListener(listeners, listener) {
+		var i = listeners.length;
+		while (i--) {
+			if (listeners[i].listener === listener) {
+				return i;
+			}
+		}
+
+		return -1;
+	}
+
+	/**
+	 * Alias a method while keeping the context correct, to allow for overwriting of target method.
+	 *
+	 * @param {String} name The name of the target method.
+	 * @return {Function} The aliased method
+	 * @api private
+	 */
+	function alias(name) {
+		return function aliasClosure() {
+			return this[name].apply(this, arguments);
+		};
+	}
+
+	/**
+	 * Returns the listener array for the specified event.
+	 * Will initialise the event object and listener arrays if required.
+	 * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
+	 * Each property in the object response is an array of listener functions.
+	 *
+	 * @param {String|RegExp} evt Name of the event to return the listeners from.
+	 * @return {Function[]|Object} All listener functions for the event.
+	 */
+	proto.getListeners = function getListeners(evt) {
+		var events = this._getEvents();
+		var response;
+		var key;
+
+		// Return a concatenated array of all matching events if
+		// the selector is a regular expression.
+		if (typeof evt === 'object') {
+			response = {};
+			for (key in events) {
+				if (events.hasOwnProperty(key) && evt.test(key)) {
+					response[key] = events[key];
+				}
+			}
+		}
+		else {
+			response = events[evt] || (events[evt] = []);
+		}
+
+		return response;
+	};
+
+	/**
+	 * Takes a list of listener objects and flattens it into a list of listener functions.
+	 *
+	 * @param {Object[]} listeners Raw listener objects.
+	 * @return {Function[]} Just the listener functions.
+	 */
+	proto.flattenListeners = function flattenListeners(listeners) {
+		var flatListeners = [];
+		var i;
+
+		for (i = 0; i < listeners.length; i += 1) {
+			flatListeners.push(listeners[i].listener);
+		}
+
+		return flatListeners;
+	};
+
+	/**
+	 * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
+	 *
+	 * @param {String|RegExp} evt Name of the event to return the listeners from.
+	 * @return {Object} All listener functions for an event in an object.
+	 */
+	proto.getListenersAsObject = function getListenersAsObject(evt) {
+		var listeners = this.getListeners(evt);
+		var response;
+
+		if (listeners instanceof Array) {
+			response = {};
+			response[evt] = listeners;
+		}
+
+		return response || listeners;
+	};
+
+	/**
+	 * Adds a listener function to the specified event.
+	 * The listener will not be added if it is a duplicate.
+	 * If the listener returns true then it will be removed after it is called.
+	 * If you pass a regular expression as the event name then the listener will be added to all events that match it.
+	 *
+	 * @param {String|RegExp} evt Name of the event to attach the listener to.
+	 * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.addListener = function addListener(evt, listener) {
+		var listeners = this.getListenersAsObject(evt);
+		var listenerIsWrapped = typeof listener === 'object';
+		var key;
+
+		for (key in listeners) {
+			if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
+				listeners[key].push(listenerIsWrapped ? listener : {
+					listener: listener,
+					once: false
+				});
+			}
+		}
+
+		return this;
+	};
+
+	/**
+	 * Alias of addListener
+	 */
+	proto.on = alias('addListener');
+
+	/**
+	 * Semi-alias of addListener. It will add a listener that will be
+	 * automatically removed after it's first execution.
+	 *
+	 * @param {String|RegExp} evt Name of the event to attach the listener to.
+	 * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.addOnceListener = function addOnceListener(evt, listener) {
+		return this.addListener(evt, {
+			listener: listener,
+			once: true
+		});
+	};
+
+	/**
+	 * Alias of addOnceListener.
+	 */
+	proto.once = alias('addOnceListener');
+
+	/**
+	 * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
+	 * You need to tell it what event names should be matched by a regex.
+	 *
+	 * @param {String} evt Name of the event to create.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.defineEvent = function defineEvent(evt) {
+		this.getListeners(evt);
+		return this;
+	};
+
+	/**
+	 * Uses defineEvent to define multiple events.
+	 *
+	 * @param {String[]} evts An array of event names to define.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.defineEvents = function defineEvents(evts) {
+		for (var i = 0; i < evts.length; i += 1) {
+			this.defineEvent(evts[i]);
+		}
+		return this;
+	};
+
+	/**
+	 * Removes a listener function from the specified event.
+	 * When passed a regular expression as the event name, it will remove the listener from all events that match it.
+	 *
+	 * @param {String|RegExp} evt Name of the event to remove the listener from.
+	 * @param {Function} listener Method to remove from the event.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.removeListener = function removeListener(evt, listener) {
+		var listeners = this.getListenersAsObject(evt);
+		var index;
+		var key;
+
+		for (key in listeners) {
+			if (listeners.hasOwnProperty(key)) {
+				index = indexOfListener(listeners[key], listener);
+
+				if (index !== -1) {
+					listeners[key].splice(index, 1);
+				}
+			}
+		}
+
+		return this;
+	};
+
+	/**
+	 * Alias of removeListener
+	 */
+	proto.off = alias('removeListener');
+
+	/**
+	 * Adds listeners in bulk using the manipulateListeners method.
+	 * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
+	 * You can also pass it a regular expression to add the array of listeners to all events that match it.
+	 * Yeah, this function does quite a bit. That's probably a bad thing.
+	 *
+	 * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
+	 * @param {Function[]} [listeners] An optional array of listener functions to add.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.addListeners = function addListeners(evt, listeners) {
+		// Pass through to manipulateListeners
+		return this.manipulateListeners(false, evt, listeners);
+	};
+
+	/**
+	 * Removes listeners in bulk using the manipulateListeners method.
+	 * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
+	 * You can also pass it an event name and an array of listeners to be removed.
+	 * You can also pass it a regular expression to remove the listeners from all events that match it.
+	 *
+	 * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
+	 * @param {Function[]} [listeners] An optional array of listener functions to remove.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.removeListeners = function removeListeners(evt, listeners) {
+		// Pass through to manipulateListeners
+		return this.manipulateListeners(true, evt, listeners);
+	};
+
+	/**
+	 * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
+	 * The first argument will determine if the listeners are removed (true) or added (false).
+	 * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
+	 * You can also pass it an event name and an array of listeners to be added/removed.
+	 * You can also pass it a regular expression to manipulate the listeners of all events that match it.
+	 *
+	 * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
+	 * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
+	 * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
+		var i;
+		var value;
+		var single = remove ? this.removeListener : this.addListener;
+		var multiple = remove ? this.removeListeners : this.addListeners;
+
+		// If evt is an object then pass each of it's properties to this method
+		if (typeof evt === 'object' && !(evt instanceof RegExp)) {
+			for (i in evt) {
+				if (evt.hasOwnProperty(i) && (value = evt[i])) {
+					// Pass the single listener straight through to the singular method
+					if (typeof value === 'function') {
+						single.call(this, i, value);
+					}
+					else {
+						// Otherwise pass back to the multiple function
+						multiple.call(this, i, value);
+					}
+				}
+			}
+		}
+		else {
+			// So evt must be a string
+			// And listeners must be an array of listeners
+			// Loop over it and pass each one to the multiple method
+			i = listeners.length;
+			while (i--) {
+				single.call(this, evt, listeners[i]);
+			}
+		}
+
+		return this;
+	};
+
+	/**
+	 * Removes all listeners from a specified event.
+	 * If you do not specify an event then all listeners will be removed.
+	 * That means every event will be emptied.
+	 * You can also pass a regex to remove all events that match it.
+	 *
+	 * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.removeEvent = function removeEvent(evt) {
+		var type = typeof evt;
+		var events = this._getEvents();
+		var key;
+
+		// Remove different things depending on the state of evt
+		if (type === 'string') {
+			// Remove all listeners for the specified event
+			delete events[evt];
+		}
+		else if (type === 'object') {
+			// Remove all events matching the regex.
+			for (key in events) {
+				if (events.hasOwnProperty(key) && evt.test(key)) {
+					delete events[key];
+				}
+			}
+		}
+		else {
+			// Remove all listeners in all events
+			delete this._events;
+		}
+
+		return this;
+	};
+
+	/**
+	 * Emits an event of your choice.
+	 * When emitted, every listener attached to that event will be executed.
+	 * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
+	 * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
+	 * So they will not arrive within the array on the other side, they will be separate.
+	 * You can also pass a regular expression to emit to all events that match it.
+	 *
+	 * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
+	 * @param {Array} [args] Optional array of arguments to be passed to each listener.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.emitEvent = function emitEvent(evt, args) {
+		var listeners = this.getListenersAsObject(evt);
+		var listener;
+		var i;
+		var key;
+		var response;
+
+		for (key in listeners) {
+			if (listeners.hasOwnProperty(key)) {
+				i = listeners[key].length;
+
+				while (i--) {
+					// If the listener returns true then it shall be removed from the event
+					// The function is executed either with a basic call or an apply if there is an args array
+					listener = listeners[key][i];
+
+					if (listener.once === true) {
+						this.removeListener(evt, listener.listener);
+					}
+
+					response = listener.listener.apply(this, args || []);
+
+					if (response === this._getOnceReturnValue()) {
+						this.removeListener(evt, listener.listener);
+					}
+				}
+			}
+		}
+
+		return this;
+	};
+
+	/**
+	 * Alias of emitEvent
+	 */
+	proto.trigger = alias('emitEvent');
+
+	/**
+	 * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
+	 * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
+	 *
+	 * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
+	 * @param {...*} Optional additional arguments to be passed to each listener.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.emit = function emit(evt) {
+		var args = Array.prototype.slice.call(arguments, 1);
+		return this.emitEvent(evt, args);
+	};
+
+	/**
+	 * Sets the current value to check against when executing listeners. If a
+	 * listeners return value matches the one set here then it will be removed
+	 * after execution. This value defaults to true.
+	 *
+	 * @param {*} value The new value to check for when executing listeners.
+	 * @return {Object} Current instance of EventEmitter for chaining.
+	 */
+	proto.setOnceReturnValue = function setOnceReturnValue(value) {
+		this._onceReturnValue = value;
+		return this;
+	};
+
+	/**
+	 * Fetches the current value to check against when executing listeners. If
+	 * the listeners return value matches this one then it should be removed
+	 * automatically. It will return true by default.
+	 *
+	 * @return {*|Boolean} The current value to check for or the default, true.
+	 * @api private
+	 */
+	proto._getOnceReturnValue = function _getOnceReturnValue() {
+		if (this.hasOwnProperty('_onceReturnValue')) {
+			return this._onceReturnValue;
+		}
+		else {
+			return true;
+		}
+	};
+
+	/**
+	 * Fetches the events object and creates one if required.
+	 *
+	 * @return {Object} The events storage object.
+	 * @api private
+	 */
+	proto._getEvents = function _getEvents() {
+		return this._events || (this._events = {});
+	};
+
+	// Expose the class either via AMD, CommonJS or the global object
+	if (typeof define === 'function' && define.amd) {
+		define(function () {
+			return EventEmitter;
+		});
+	}
+	else if (typeof module === 'object' && module.exports){
+		module.exports = EventEmitter;
+	}
+	else {
+		this.EventEmitter = EventEmitter;
+	}
+}.call(this));

File diff suppressed because it is too large
+ 2640 - 0
vendor/otr/otr.js