'use strict';

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _values = require('babel-runtime/core-js/object/values');

var _values2 = _interopRequireDefault(_values);

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

var _verifyKeyAndStartSession = function () {
    var _ref3 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(olmDevice, oneTimeKey, userId, deviceInfo) {
        var deviceId, sid;
        return _regenerator2.default.wrap(function _callee3$(_context4) {
            while (1) {
                switch (_context4.prev = _context4.next) {
                    case 0:
                        deviceId = deviceInfo.deviceId;
                        _context4.prev = 1;
                        _context4.next = 4;
                        return (0, _bluebird.resolve)(_verifySignature(olmDevice, oneTimeKey, userId, deviceId, deviceInfo.getFingerprint()));

                    case 4:
                        _context4.next = 10;
                        break;

                    case 6:
                        _context4.prev = 6;
                        _context4.t0 = _context4['catch'](1);

                        _logger2.default.error("Unable to verify signature on one-time key for device " + userId + ":" + deviceId + ":", _context4.t0);
                        return _context4.abrupt('return', null);

                    case 10:
                        sid = void 0;
                        _context4.prev = 11;
                        _context4.next = 14;
                        return (0, _bluebird.resolve)(olmDevice.createOutboundSession(deviceInfo.getIdentityKey(), oneTimeKey.key));

                    case 14:
                        sid = _context4.sent;
                        _context4.next = 21;
                        break;

                    case 17:
                        _context4.prev = 17;
                        _context4.t1 = _context4['catch'](11);

                        // possibly a bad key
                        _logger2.default.error("Error starting session with device " + userId + ":" + deviceId + ": " + _context4.t1);
                        return _context4.abrupt('return', null);

                    case 21:

                        _logger2.default.log("Started new sessionid " + sid + " for device " + userId + ":" + deviceId);
                        return _context4.abrupt('return', sid);

                    case 23:
                    case 'end':
                        return _context4.stop();
                }
            }
        }, _callee3, this, [[1, 6], [11, 17]]);
    }));

    return function _verifyKeyAndStartSession(_x12, _x13, _x14, _x15) {
        return _ref3.apply(this, arguments);
    };
}();

/**
 * Verify the signature on an object
 *
 * @param {module:crypto/OlmDevice} olmDevice olm wrapper to use for verify op
 *
 * @param {Object} obj object to check signature on. Note that this will be
 * stripped of its 'signatures' and 'unsigned' properties.
 *
 * @param {string} signingUserId  ID of the user whose signature should be checked
 *
 * @param {string} signingDeviceId  ID of the device whose signature should be checked
 *
 * @param {string} signingKey   base64-ed ed25519 public key
 *
 * Returns a promise which resolves (to undefined) if the the signature is good,
 * or rejects with an Error if it is bad.
 */


var _logger = require('../logger');

var _logger2 = _interopRequireDefault(_logger);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var anotherjson = require('another-json'); /*
                                           Copyright 2016 OpenMarket Ltd
                                           Copyright 2019 New Vector Ltd
                                           
                                           Licensed under the Apache License, Version 2.0 (the "License");
                                           you may not use this file except in compliance with the License.
                                           You may obtain a copy of the License at
                                           
                                               http://www.apache.org/licenses/LICENSE-2.0
                                           
                                           Unless required by applicable law or agreed to in writing, software
                                           distributed under the License is distributed on an "AS IS" BASIS,
                                           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                                           See the License for the specific language governing permissions and
                                           limitations under the License.
                                           */

/**
 * @module olmlib
 *
 * Utilities common to olm encryption algorithms
 */

var utils = require("../utils");

/**
 * matrix algorithm tag for olm
 */
module.exports.OLM_ALGORITHM = "m.olm.v1.curve25519-aes-sha2";

/**
 * matrix algorithm tag for megolm
 */
module.exports.MEGOLM_ALGORITHM = "m.megolm.v1.aes-sha2";

/**
 * matrix algorithm tag for megolm backups
 */
module.exports.MEGOLM_BACKUP_ALGORITHM = "m.megolm_backup.v1.curve25519-aes-sha2";

/**
 * Encrypt an event payload for an Olm device
 *
 * @param {Object<string, string>} resultsObject  The `ciphertext` property
 *   of the m.room.encrypted event to which to add our result
 *
 * @param {string} ourUserId
 * @param {string} ourDeviceId
 * @param {module:crypto/OlmDevice} olmDevice olm.js wrapper
 * @param {string} recipientUserId
 * @param {module:crypto/deviceinfo} recipientDevice
 * @param {object} payloadFields fields to include in the encrypted payload
 *
 * Returns a promise which resolves (to undefined) when the payload
 *    has been encrypted into `resultsObject`
 */
module.exports.encryptMessageForDevice = function () {
    var _ref = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee(resultsObject, ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice, payloadFields) {
        var deviceKey, sessionId, payload;
        return _regenerator2.default.wrap(function _callee$(_context) {
            while (1) {
                switch (_context.prev = _context.next) {
                    case 0:
                        deviceKey = recipientDevice.getIdentityKey();
                        _context.next = 3;
                        return (0, _bluebird.resolve)(olmDevice.getSessionIdForDevice(deviceKey));

                    case 3:
                        sessionId = _context.sent;

                        if (!(sessionId === null)) {
                            _context.next = 6;
                            break;
                        }

                        return _context.abrupt('return');

                    case 6:

                        _logger2.default.log("Using sessionid " + sessionId + " for device " + recipientUserId + ":" + recipientDevice.deviceId);

                        payload = {
                            sender: ourUserId,
                            sender_device: ourDeviceId,

                            // Include the Ed25519 key so that the recipient knows what
                            // device this message came from.
                            // We don't need to include the curve25519 key since the
                            // recipient will already know this from the olm headers.
                            // When combined with the device keys retrieved from the
                            // homeserver signed by the ed25519 key this proves that
                            // the curve25519 key and the ed25519 key are owned by
                            // the same device.
                            keys: {
                                "ed25519": olmDevice.deviceEd25519Key
                            },

                            // include the recipient device details in the payload,
                            // to avoid unknown key attacks, per
                            // https://github.com/vector-im/vector-web/issues/2483
                            recipient: recipientUserId,
                            recipient_keys: {
                                "ed25519": recipientDevice.getFingerprint()
                            }
                        };

                        // TODO: technically, a bunch of that stuff only needs to be included for
                        // pre-key messages: after that, both sides know exactly which devices are
                        // involved in the session. If we're looking to reduce data transfer in the
                        // future, we could elide them for subsequent messages.

                        utils.extend(payload, payloadFields);

                        _context.next = 11;
                        return (0, _bluebird.resolve)(olmDevice.encryptMessage(deviceKey, sessionId, (0, _stringify2.default)(payload)));

                    case 11:
                        resultsObject[deviceKey] = _context.sent;

                    case 12:
                    case 'end':
                        return _context.stop();
                }
            }
        }, _callee, this);
    }));

    return function (_x, _x2, _x3, _x4, _x5, _x6, _x7) {
        return _ref.apply(this, arguments);
    };
}();

/**
 * Try to make sure we have established olm sessions for the given devices.
 *
 * @param {module:crypto/OlmDevice} olmDevice
 *
 * @param {module:base-apis~MatrixBaseApis} baseApis
 *
 * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser
 *    map from userid to list of devices to ensure sessions for
 *
 * @param {bolean} force If true, establish a new session even if one already exists.
 *     Optional.
 *
 * @return {module:client.Promise} resolves once the sessions are complete, to
 *    an Object mapping from userId to deviceId to
 *    {@link module:crypto~OlmSessionResult}
 */
module.exports.ensureOlmSessionsForDevices = function () {
    var _ref2 = (0, _bluebird.coroutine)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(olmDevice, baseApis, devicesByUser, force) {
        var _this = this;

        var devicesWithoutSession, result, resolveSession, userId, devices, _loop, j, oneTimeKeyAlgorithm, res, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, resolver, otk_res, promises, _loop2, _userId, _ret2;

        return _regenerator2.default.wrap(function _callee2$(_context3) {
            while (1) {
                switch (_context3.prev = _context3.next) {
                    case 0:
                        devicesWithoutSession = [
                            // [userId, deviceId], ...
                        ];
                        result = {};
                        resolveSession = {};
                        _context3.t0 = _regenerator2.default.keys(devicesByUser);

                    case 4:
                        if ((_context3.t1 = _context3.t0()).done) {
                            _context3.next = 19;
                            break;
                        }

                        userId = _context3.t1.value;

                        if (devicesByUser.hasOwnProperty(userId)) {
                            _context3.next = 8;
                            break;
                        }

                        return _context3.abrupt('continue', 4);

                    case 8:
                        result[userId] = {};
                        devices = devicesByUser[userId];
                        _loop = /*#__PURE__*/_regenerator2.default.mark(function _loop(j) {
                            var deviceInfo, deviceId, key, sessionId;
                            return _regenerator2.default.wrap(function _loop$(_context2) {
                                while (1) {
                                    switch (_context2.prev = _context2.next) {
                                        case 0:
                                            deviceInfo = devices[j];
                                            deviceId = deviceInfo.deviceId;
                                            key = deviceInfo.getIdentityKey();

                                            if (!olmDevice._sessionsInProgress[key]) {
                                                // pre-emptively mark the session as in-progress to avoid race
                                                // conditions.  If we find that we already have a session, then
                                                // we'll resolve
                                                olmDevice._sessionsInProgress[key] = new _bluebird2.default(function (_resolve2, _reject) {
                                                    resolveSession[key] = {
                                                        resolve: function resolve() {
                                                            delete olmDevice._sessionsInProgress[key];
                                                            _resolve2.apply(undefined, arguments);
                                                        },
                                                        reject: function reject() {
                                                            delete olmDevice._sessionsInProgress[key];
                                                            _reject.apply(undefined, arguments);
                                                        }
                                                    };
                                                });
                                            }
                                            _context2.next = 6;
                                            return (0, _bluebird.resolve)(olmDevice.getSessionIdForDevice(key, resolveSession[key]));

                                        case 6:
                                            sessionId = _context2.sent;

                                            if (sessionId !== null && resolveSession[key]) {
                                                // we found a session, but we had marked the session as
                                                // in-progress, so unmark it and unblock anything that was
                                                // waiting
                                                delete olmDevice._sessionsInProgress[key];
                                                resolveSession[key].resolve();
                                                delete resolveSession[key];
                                            }
                                            if (sessionId === null || force) {
                                                devicesWithoutSession.push([userId, deviceId]);
                                            }
                                            result[userId][deviceId] = {
                                                device: deviceInfo,
                                                sessionId: sessionId
                                            };

                                        case 10:
                                        case 'end':
                                            return _context2.stop();
                                    }
                                }
                            }, _loop, _this);
                        });
                        j = 0;

                    case 12:
                        if (!(j < devices.length)) {
                            _context3.next = 17;
                            break;
                        }

                        return _context3.delegateYield(_loop(j), 't2', 14);

                    case 14:
                        j++;
                        _context3.next = 12;
                        break;

                    case 17:
                        _context3.next = 4;
                        break;

                    case 19:
                        if (!(devicesWithoutSession.length === 0)) {
                            _context3.next = 21;
                            break;
                        }

                        return _context3.abrupt('return', result);

                    case 21:
                        oneTimeKeyAlgorithm = "signed_curve25519";
                        res = void 0;
                        _context3.prev = 23;
                        _context3.next = 26;
                        return (0, _bluebird.resolve)(baseApis.claimOneTimeKeys(devicesWithoutSession, oneTimeKeyAlgorithm));

                    case 26:
                        res = _context3.sent;
                        _context3.next = 52;
                        break;

                    case 29:
                        _context3.prev = 29;
                        _context3.t3 = _context3['catch'](23);
                        _iteratorNormalCompletion = true;
                        _didIteratorError = false;
                        _iteratorError = undefined;
                        _context3.prev = 34;

                        for (_iterator = (0, _getIterator3.default)((0, _values2.default)(resolveSession)); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                            resolver = _step.value;

                            resolver.resolve();
                        }
                        _context3.next = 42;
                        break;

                    case 38:
                        _context3.prev = 38;
                        _context3.t4 = _context3['catch'](34);
                        _didIteratorError = true;
                        _iteratorError = _context3.t4;

                    case 42:
                        _context3.prev = 42;
                        _context3.prev = 43;

                        if (!_iteratorNormalCompletion && _iterator.return) {
                            _iterator.return();
                        }

                    case 45:
                        _context3.prev = 45;

                        if (!_didIteratorError) {
                            _context3.next = 48;
                            break;
                        }

                        throw _iteratorError;

                    case 48:
                        return _context3.finish(45);

                    case 49:
                        return _context3.finish(42);

                    case 50:
                        _logger2.default.log("failed to claim one-time keys", _context3.t3, devicesWithoutSession);
                        throw _context3.t3;

                    case 52:
                        otk_res = res.one_time_keys || {};
                        promises = [];

                        _loop2 = function _loop2(_userId) {
                            if (!devicesByUser.hasOwnProperty(_userId)) {
                                return 'continue';
                            }
                            var userRes = otk_res[_userId] || {};
                            var devices = devicesByUser[_userId];

                            var _loop3 = function _loop3(j) {
                                var deviceInfo = devices[j];
                                var deviceId = deviceInfo.deviceId;
                                var key = deviceInfo.getIdentityKey();
                                if (result[_userId][deviceId].sessionId && !force) {
                                    // we already have a result for this device
                                    return 'continue';
                                }

                                var deviceRes = userRes[deviceId] || {};
                                var oneTimeKey = null;
                                for (var keyId in deviceRes) {
                                    if (keyId.indexOf(oneTimeKeyAlgorithm + ":") === 0) {
                                        oneTimeKey = deviceRes[keyId];
                                    }
                                }

                                if (!oneTimeKey) {
                                    var msg = "No one-time keys (alg=" + oneTimeKeyAlgorithm + ") for device " + _userId + ":" + deviceId;
                                    _logger2.default.warn(msg);
                                    if (resolveSession[key]) {
                                        resolveSession[key].resolve();
                                    }
                                    return 'continue';
                                }

                                promises.push(_verifyKeyAndStartSession(olmDevice, oneTimeKey, _userId, deviceInfo).then(function (sid) {
                                    if (resolveSession[key]) {
                                        resolveSession[key].resolve(sid);
                                    }
                                    result[_userId][deviceId].sessionId = sid;
                                }, function (e) {
                                    if (resolveSession[key]) {
                                        resolveSession[key].resolve();
                                    }
                                    throw e;
                                }));
                            };

                            for (var j = 0; j < devices.length; j++) {
                                var _ret3 = _loop3(j);

                                if (_ret3 === 'continue') continue;
                            }
                        };

                        _context3.t5 = _regenerator2.default.keys(devicesByUser);

                    case 56:
                        if ((_context3.t6 = _context3.t5()).done) {
                            _context3.next = 63;
                            break;
                        }

                        _userId = _context3.t6.value;
                        _ret2 = _loop2(_userId);

                        if (!(_ret2 === 'continue')) {
                            _context3.next = 61;
                            break;
                        }

                        return _context3.abrupt('continue', 56);

                    case 61:
                        _context3.next = 56;
                        break;

                    case 63:
                        _context3.next = 65;
                        return (0, _bluebird.resolve)(_bluebird2.default.all(promises));

                    case 65:
                        return _context3.abrupt('return', result);

                    case 66:
                    case 'end':
                        return _context3.stop();
                }
            }
        }, _callee2, this, [[23, 29], [34, 38, 42, 50], [43,, 45, 49]]);
    }));

    return function (_x8, _x9, _x10, _x11) {
        return _ref2.apply(this, arguments);
    };
}();

var _verifySignature = module.exports.verifySignature = function () {
    var _ref4 = (0, _bluebird.method)(function (olmDevice, obj, signingUserId, signingDeviceId, signingKey) {
        var signKeyId = "ed25519:" + signingDeviceId;
        var signatures = obj.signatures || {};
        var userSigs = signatures[signingUserId] || {};
        var signature = userSigs[signKeyId];
        if (!signature) {
            throw Error("No signature");
        }

        // prepare the canonical json: remove unsigned and signatures, and stringify with
        // anotherjson
        delete obj.unsigned;
        delete obj.signatures;
        var json = anotherjson.stringify(obj);

        olmDevice.verifySignature(signingKey, json, signature);
    });

    return function (_x16, _x17, _x18, _x19, _x20) {
        return _ref4.apply(this, arguments);
    };
}();
//# sourceMappingURL=olmlib.js.map