From 583ddc3e57c9d219789e869009c05cd0ccaffbc0 Mon Sep 17 00:00:00 2001 From: Richard van der Hoff Date: Wed, 22 Jun 2016 07:25:24 +0100 Subject: [PATCH] Configure encryption on m.room.encryption events This is the first step in having a cross-room "enable encryption" button. If encryption is enabled, add an event handler which will set up encryption when we receive an m.room.encryption event (either at initial /sync, or in subsequent syncs.) --- lib/client.js | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/client.js b/lib/client.js index ad74f58af..b4932c3f4 100644 --- a/lib/client.js +++ b/lib/client.js @@ -142,6 +142,7 @@ function MatrixClient(opts) { this.sessionStore.storeEndToEndDevicesForUser( opts.userId, myDevices ); + setupCryptoEventHandler(this); } this.scheduler = opts.scheduler; if (this.scheduler) { @@ -632,6 +633,44 @@ MatrixClient.prototype.isEventSenderVerified = function(event) { return false; }; +/** + * Register a listener for m.room.encryption events which will enable encryption + * for a room. + * + * @param {MatrixClient} client + */ +function setupCryptoEventHandler(client) { + client.on("event", function(event) { + if (event.getType() != "m.room.encryption") { + return; + } + onCryptoEvent(client, event); + }); +} + +function onCryptoEvent(client, event) { + var roomId = event.getRoomId(); + + // if we already have encryption in this room, we should ignore this event + // (for now at least. maybe we should alert the user somehow?) + var content = event.getContent(); + var existingConfig = client.sessionStore.getEndToEndRoom(roomId); + if (existingConfig) { + if (JSON.stringify(existingConfig) != JSON.stringify(content)) { + console.error("Ignoring m.room.encryption event which requests " + + "a change of config in " + roomId); + return; + } + } + + try { + client.setRoomEncryption(roomId, content).done(); + } catch (e) { + console.error("Error configuring encryption in room " + roomId + + ": " + e); + } +} + /** * Enable end-to-end encryption for a room. * @param {string} roomId The room ID to enable encryption in. @@ -640,12 +679,16 @@ MatrixClient.prototype.isEventSenderVerified = function(event) { */ MatrixClient.prototype.setRoomEncryption = function(roomId, config) { if (!this._olmDevice) { - return q.reject(new Error("End-to-End encryption disabled")); + throw new Error("End-to-End encryption disabled"); } var self = this; if (config.algorithm === OLM_ALGORITHM) { + // remove spurious keys + config = { + algorithm: OLM_ALGORITHM, + }; this.sessionStore.storeEndToEndRoom(roomId, config); var room = this.getRoom(roomId);