(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } module.exports = _arrayLikeToArray; },{}],2:[function(require,module,exports){ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = _arrayWithHoles; },{}],3:[function(require,module,exports){ var arrayLikeToArray = require("./arrayLikeToArray"); function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray(arr); } module.exports = _arrayWithoutHoles; },{"./arrayLikeToArray":1}],4:[function(require,module,exports){ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } module.exports = _assertThisInitialized; },{}],5:[function(require,module,exports){ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } module.exports = _asyncToGenerator; },{}],6:[function(require,module,exports){ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = _classCallCheck; },{}],7:[function(require,module,exports){ var setPrototypeOf = require("./setPrototypeOf"); var isNativeReflectConstruct = require("./isNativeReflectConstruct"); function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { module.exports = _construct = Reflect.construct; } else { module.exports = _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } module.exports = _construct; },{"./isNativeReflectConstruct":15,"./setPrototypeOf":21}],8:[function(require,module,exports){ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } module.exports = _createClass; },{}],9:[function(require,module,exports){ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; },{}],10:[function(require,module,exports){ function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } module.exports = _getPrototypeOf; },{}],11:[function(require,module,exports){ var setPrototypeOf = require("./setPrototypeOf"); function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } module.exports = _inherits; },{"./setPrototypeOf":21}],12:[function(require,module,exports){ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } module.exports = _interopRequireDefault; },{}],13:[function(require,module,exports){ var _typeof = require("../helpers/typeof"); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } module.exports = _interopRequireWildcard; },{"../helpers/typeof":24}],14:[function(require,module,exports){ function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } module.exports = _isNativeFunction; },{}],15:[function(require,module,exports){ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } module.exports = _isNativeReflectConstruct; },{}],16:[function(require,module,exports){ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } module.exports = _iterableToArray; },{}],17:[function(require,module,exports){ function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } module.exports = _iterableToArrayLimit; },{}],18:[function(require,module,exports){ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableRest; },{}],19:[function(require,module,exports){ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableSpread; },{}],20:[function(require,module,exports){ var _typeof = require("../helpers/typeof"); var assertThisInitialized = require("./assertThisInitialized"); function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } module.exports = _possibleConstructorReturn; },{"../helpers/typeof":24,"./assertThisInitialized":4}],21:[function(require,module,exports){ function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf; },{}],22:[function(require,module,exports){ var arrayWithHoles = require("./arrayWithHoles"); var iterableToArrayLimit = require("./iterableToArrayLimit"); var unsupportedIterableToArray = require("./unsupportedIterableToArray"); var nonIterableRest = require("./nonIterableRest"); function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); } module.exports = _slicedToArray; },{"./arrayWithHoles":2,"./iterableToArrayLimit":17,"./nonIterableRest":18,"./unsupportedIterableToArray":25}],23:[function(require,module,exports){ var arrayWithoutHoles = require("./arrayWithoutHoles"); var iterableToArray = require("./iterableToArray"); var unsupportedIterableToArray = require("./unsupportedIterableToArray"); var nonIterableSpread = require("./nonIterableSpread"); function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); } module.exports = _toConsumableArray; },{"./arrayWithoutHoles":3,"./iterableToArray":16,"./nonIterableSpread":19,"./unsupportedIterableToArray":25}],24:[function(require,module,exports){ function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { module.exports = _typeof = function _typeof(obj) { return typeof obj; }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = _typeof; },{}],25:[function(require,module,exports){ var arrayLikeToArray = require("./arrayLikeToArray"); function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } module.exports = _unsupportedIterableToArray; },{"./arrayLikeToArray":1}],26:[function(require,module,exports){ var getPrototypeOf = require("./getPrototypeOf"); var setPrototypeOf = require("./setPrototypeOf"); var isNativeFunction = require("./isNativeFunction"); var construct = require("./construct"); function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct(Class, arguments, getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } module.exports = _wrapNativeSuper; },{"./construct":7,"./getPrototypeOf":10,"./isNativeFunction":14,"./setPrototypeOf":21}],27:[function(require,module,exports){ module.exports = require("regenerator-runtime"); },{"regenerator-runtime":47}],28:[function(require,module,exports){ /* Copyright 2015 Mark Haines * * 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. */ 'use strict'; var escaped = /[\\\"\x00-\x1F]/g; var escapes = {}; for (var i = 0; i < 0x20; ++i) { escapes[String.fromCharCode(i)] = ( '\\U' + ('0000' + i.toString(16)).slice(-4).toUpperCase() ); } escapes['\b'] = '\\b'; escapes['\t'] = '\\t'; escapes['\n'] = '\\n'; escapes['\f'] = '\\f'; escapes['\r'] = '\\r'; escapes['\"'] = '\\\"'; escapes['\\'] = '\\\\'; function escapeString(value) { escaped.lastIndex = 0; return value.replace(escaped, function(c) { return escapes[c]; }); } function stringify(value) { switch (typeof value) { case 'string': return '"' + escapeString(value) + '"'; case 'number': return isFinite(value) ? value : 'null'; case 'boolean': return value; case 'object': if (value === null) { return 'null'; } if (Array.isArray(value)) { return stringifyArray(value); } return stringifyObject(value); default: throw new Error('Cannot stringify: ' + typeof value); } } function stringifyArray(array) { var sep = '['; var result = ''; for (var i = 0; i < array.length; ++i) { result += sep; sep = ','; result += stringify(array[i]); } if (sep != ',') { return '[]'; } else { return result + ']'; } } function stringifyObject(object) { var sep = '{'; var result = ''; var keys = Object.keys(object); keys.sort(); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; result += sep + '"' + escapeString(key) + '":'; sep = ','; result += stringify(object[key]); } if (sep != ',') { return '{}'; } else { return result + '}'; } } /** */ module.exports = {stringify: stringify}; },{}],29:[function(require,module,exports){ 'use strict' // base-x encoding / decoding // Copyright (c) 2018 base-x contributors // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. // @ts-ignore var _Buffer = require('safe-buffer').Buffer function base (ALPHABET) { if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } var BASE_MAP = new Uint8Array(256) for (var j = 0; j < BASE_MAP.length; j++) { BASE_MAP[j] = 255 } for (var i = 0; i < ALPHABET.length; i++) { var x = ALPHABET.charAt(i) var xc = x.charCodeAt(0) if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } BASE_MAP[xc] = i } var BASE = ALPHABET.length var LEADER = ALPHABET.charAt(0) var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up function encode (source) { if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) } if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') } if (source.length === 0) { return '' } // Skip & count leading zeroes. var zeroes = 0 var length = 0 var pbegin = 0 var pend = source.length while (pbegin !== pend && source[pbegin] === 0) { pbegin++ zeroes++ } // Allocate enough space in big-endian base58 representation. var size = ((pend - pbegin) * iFACTOR + 1) >>> 0 var b58 = new Uint8Array(size) // Process the bytes. while (pbegin !== pend) { var carry = source[pbegin] // Apply "b58 = b58 * 256 + ch". var i = 0 for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { carry += (256 * b58[it1]) >>> 0 b58[it1] = (carry % BASE) >>> 0 carry = (carry / BASE) >>> 0 } if (carry !== 0) { throw new Error('Non-zero carry') } length = i pbegin++ } // Skip leading zeroes in base58 result. var it2 = size - length while (it2 !== size && b58[it2] === 0) { it2++ } // Translate the result into a string. var str = LEADER.repeat(zeroes) for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) } return str } function decodeUnsafe (source) { if (typeof source !== 'string') { throw new TypeError('Expected String') } if (source.length === 0) { return _Buffer.alloc(0) } var psz = 0 // Skip leading spaces. if (source[psz] === ' ') { return } // Skip and count leading '1's. var zeroes = 0 var length = 0 while (source[psz] === LEADER) { zeroes++ psz++ } // Allocate enough space in big-endian base256 representation. var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up. var b256 = new Uint8Array(size) // Process the characters. while (source[psz]) { // Decode character var carry = BASE_MAP[source.charCodeAt(psz)] // Invalid character if (carry === 255) { return } var i = 0 for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { carry += (BASE * b256[it3]) >>> 0 b256[it3] = (carry % 256) >>> 0 carry = (carry / 256) >>> 0 } if (carry !== 0) { throw new Error('Non-zero carry') } length = i psz++ } // Skip trailing spaces. if (source[psz] === ' ') { return } // Skip leading zeroes in b256. var it4 = size - length while (it4 !== size && b256[it4] === 0) { it4++ } var vch = _Buffer.allocUnsafe(zeroes + (size - it4)) vch.fill(0x00, 0, zeroes) var j = zeroes while (it4 !== size) { vch[j++] = b256[it4++] } return vch } function decode (string) { var buffer = decodeUnsafe(string) if (buffer) { return buffer } throw new Error('Non-base' + BASE + ' character') } return { encode: encode, decodeUnsafe: decodeUnsafe, decode: decode } } module.exports = base },{"safe-buffer":48}],30:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk( uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) )) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } },{}],31:[function(require,module,exports){ // Browser Request // // 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. // UMD HEADER START (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { // UMD HEADER END var XHR = XMLHttpRequest if (!XHR) throw new Error('missing XMLHttpRequest') request.log = { 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop } var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes // // request // function request(options, callback) { // The entry-point to the API: prep the options object and pass the real work to run_xhr. if(typeof callback !== 'function') throw new Error('Bad callback given: ' + callback) if(!options) throw new Error('No options given') var options_onResponse = options.onResponse; // Save this for later. if(typeof options === 'string') options = {'uri':options}; else options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating. options.onResponse = options_onResponse // And put it back. if (options.verbose) request.log = getLogger(); if(options.url) { options.uri = options.url; delete options.url; } if(!options.uri && options.uri !== "") throw new Error("options.uri is a required argument"); if(typeof options.uri != "string") throw new Error("options.uri must be a string"); var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect'] for (var i = 0; i < unsupported_options.length; i++) if(options[ unsupported_options[i] ]) throw new Error("options." + unsupported_options[i] + " is not supported") options.callback = callback options.method = options.method || 'GET'; options.headers = options.headers || {}; options.body = options.body || null options.timeout = options.timeout || request.DEFAULT_TIMEOUT if(options.headers.host) throw new Error("Options.headers.host is not supported"); if(options.json) { options.headers.accept = options.headers.accept || 'application/json' if(options.method !== 'GET') options.headers['content-type'] = 'application/json' if(typeof options.json !== 'boolean') options.body = JSON.stringify(options.json) else if(typeof options.body !== 'string') options.body = JSON.stringify(options.body) } //BEGIN QS Hack var serialize = function(obj) { var str = []; for(var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); } if(options.qs){ var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs); if(options.uri.indexOf('?') !== -1){ //no get params options.uri = options.uri+'&'+qs; }else{ //existing get params options.uri = options.uri+'?'+qs; } } //END QS Hack //BEGIN FORM Hack var multipart = function(obj) { //todo: support file type (useful?) var result = {}; result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000); var lines = []; for(var p in obj){ if (obj.hasOwnProperty(p)) { lines.push( '--'+result.boundry+"\n"+ 'Content-Disposition: form-data; name="'+p+'"'+"\n"+ "\n"+ obj[p]+"\n" ); } } lines.push( '--'+result.boundry+'--' ); result.body = lines.join(''); result.length = result.body.length; result.type = 'multipart/form-data; boundary='+result.boundry; return result; } if(options.form){ if(typeof options.form == 'string') throw('form name unsupported'); if(options.method === 'POST'){ var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase(); options.headers['content-type'] = encoding; switch(encoding){ case 'application/x-www-form-urlencoded': options.body = serialize(options.form).replace(/%20/g, "+"); break; case 'multipart/form-data': var multi = multipart(options.form); //options.headers['content-length'] = multi.length; options.body = multi.body; options.headers['content-type'] = multi.type; break; default : throw new Error('unsupported encoding:'+encoding); } } } //END FORM Hack // If onResponse is boolean true, call back immediately when the response is known, // not when the full request is complete. options.onResponse = options.onResponse || noop if(options.onResponse === true) { options.onResponse = callback options.callback = noop } // XXX Browsers do not like this. //if(options.body) // options.headers['content-length'] = options.body.length; // HTTP basic authentication if(!options.headers.authorization && options.auth) options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password); return run_xhr(options) } var req_seq = 0 function run_xhr(options) { var xhr = new XHR , timed_out = false , is_cors = is_crossDomain(options.uri) , supports_cors = ('withCredentials' in xhr) req_seq += 1 xhr.seq_id = req_seq xhr.id = req_seq + ': ' + options.method + ' ' + options.uri xhr._id = xhr.id // I know I will type "_id" from habit all the time. if(is_cors && !supports_cors) { var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri) cors_err.cors = 'unsupported' return options.callback(cors_err, xhr) } xhr.timeoutTimer = setTimeout(too_late, options.timeout) function too_late() { timed_out = true var er = new Error('ETIMEDOUT') er.code = 'ETIMEDOUT' er.duration = options.timeout request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout }) return options.callback(er, xhr) } // Some states can be skipped over, so remember what is still incomplete. var did = {'response':false, 'loading':false, 'end':false} xhr.onreadystatechange = on_state_change xhr.open(options.method, options.uri, true) // asynchronous if(is_cors) xhr.withCredentials = !! options.withCredentials xhr.send(options.body) return xhr function on_state_change(event) { if(timed_out) return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id}) request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out}) if(xhr.readyState === XHR.OPENED) { request.log.debug('Request started', {'id':xhr.id}) for (var key in options.headers) xhr.setRequestHeader(key, options.headers[key]) } else if(xhr.readyState === XHR.HEADERS_RECEIVED) on_response() else if(xhr.readyState === XHR.LOADING) { on_response() on_loading() } else if(xhr.readyState === XHR.DONE) { on_response() on_loading() on_end() } } function on_response() { if(did.response) return did.response = true request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status}) clearTimeout(xhr.timeoutTimer) xhr.statusCode = xhr.status // Node request compatibility // Detect failed CORS requests. if(is_cors && xhr.statusCode == 0) { var cors_err = new Error('CORS request rejected: ' + options.uri) cors_err.cors = 'rejected' // Do not process this request further. did.loading = true did.end = true return options.callback(cors_err, xhr) } options.onResponse(null, xhr) } function on_loading() { if(did.loading) return did.loading = true request.log.debug('Response body loading', {'id':xhr.id}) // TODO: Maybe simulate "data" events by watching xhr.responseText } function on_end() { if(did.end) return did.end = true request.log.debug('Request done', {'id':xhr.id}) xhr.body = xhr.responseText if(options.json) { try { xhr.body = JSON.parse(xhr.responseText) } catch (er) { return options.callback(er, xhr) } } options.callback(null, xhr, xhr.body) } } // request request.withCredentials = false; request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; // // defaults // request.defaults = function(options, requester) { var def = function (method) { var d = function (params, callback) { if(typeof params === 'string') params = {'uri': params}; else { params = JSON.parse(JSON.stringify(params)); } for (var i in options) { if (params[i] === undefined) params[i] = options[i] } return method(params, callback) } return d } var de = def(request) de.get = def(request.get) de.post = def(request.post) de.put = def(request.put) de.head = def(request.head) return de } // // HTTP method shortcuts // var shortcuts = [ 'get', 'put', 'post', 'head' ]; shortcuts.forEach(function(shortcut) { var method = shortcut.toUpperCase(); var func = shortcut.toLowerCase(); request[func] = function(opts) { if(typeof opts === 'string') opts = {'method':method, 'uri':opts}; else { opts = JSON.parse(JSON.stringify(opts)); opts.method = method; } var args = [opts].concat(Array.prototype.slice.apply(arguments, [1])); return request.apply(this, args); } }) // // CouchDB shortcut // request.couch = function(options, callback) { if(typeof options === 'string') options = {'uri':options} // Just use the request API to do JSON. options.json = true if(options.body) options.json = options.body delete options.body callback = callback || noop var xhr = request(options, couch_handler) return xhr function couch_handler(er, resp, body) { if(er) return callback(er, resp, body) if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) { // The body is a Couch JSON object indicating the error. er = new Error('CouchDB error: ' + (body.error.reason || body.error.error)) for (var key in body) er[key] = body[key] return callback(er, resp, body); } return callback(er, resp, body); } } // // Utility // function noop() {} function getLogger() { var logger = {} , levels = ['trace', 'debug', 'info', 'warn', 'error'] , level, i for(i = 0; i < levels.length; i++) { level = levels[i] logger[level] = noop if(typeof console !== 'undefined' && console && console[level]) logger[level] = formatted(console, level) } return logger } function formatted(obj, method) { return formatted_logger function formatted_logger(str, context) { if(typeof context === 'object') str += ' ' + JSON.stringify(context) return obj[method].call(obj, str) } } // Return whether a URL is a cross-domain request. function is_crossDomain(url) { var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/ // jQuery #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set var ajaxLocation try { ajaxLocation = location.href } catch (e) { // Use the href attribute of an A element since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [] , parts = rurl.exec(url.toLowerCase() ) var result = !!( parts && ( parts[1] != ajaxLocParts[1] || parts[2] != ajaxLocParts[2] || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443)) ) ) //console.debug('is_crossDomain('+url+') -> ' + result) return result } // MIT License from http://phpjs.org/functions/base64_encode:358 function b64_enc (data) { // Encodes string using MIME base64 algorithm var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = []; if (!data) { return data; } // assume utf8 data // data = this.utf8_encode(data+''); do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1<<16 | o2<<8 | o3; h1 = bits>>18 & 0x3f; h2 = bits>>12 & 0x3f; h3 = bits>>6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); switch (data.length % 3) { case 1: enc = enc.slice(0, -2) + '=='; break; case 2: enc = enc.slice(0, -1) + '='; break; } return enc; } return request; //UMD FOOTER START })); //UMD FOOTER END },{}],32:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],33:[function(require,module,exports){ var basex = require('base-x') var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' module.exports = basex(ALPHABET) },{"base-x":29}],34:[function(require,module,exports){ (function (Buffer){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } }).call(this,require("buffer").Buffer) },{"base64-js":30,"buffer":34,"ieee754":37}],35:[function(require,module,exports){ /*! * content-type * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 * * parameter = token "=" ( token / quoted-string ) * token = 1*tchar * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" * / DIGIT / ALPHA * ; any VCHAR, except delimiters * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text * obs-text = %x80-FF * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) */ var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 * * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) * obs-text = %x80-FF */ var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g /** * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 */ var QUOTE_REGEXP = /([\\"])/g /** * RegExp to match type in RFC 7231 sec 3.1.1.1 * * media-type = type "/" subtype * type = token * subtype = token */ var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** * Module exports. * @public */ exports.format = format exports.parse = parse /** * Format object to media type. * * @param {object} obj * @return {string} * @public */ function format (obj) { if (!obj || typeof obj !== 'object') { throw new TypeError('argument obj is required') } var parameters = obj.parameters var type = obj.type if (!type || !TYPE_REGEXP.test(type)) { throw new TypeError('invalid type') } var string = type // append parameters if (parameters && typeof parameters === 'object') { var param var params = Object.keys(parameters).sort() for (var i = 0; i < params.length; i++) { param = params[i] if (!TOKEN_REGEXP.test(param)) { throw new TypeError('invalid parameter name') } string += '; ' + param + '=' + qstring(parameters[param]) } } return string } /** * Parse media type to object. * * @param {string|object} string * @return {Object} * @public */ function parse (string) { if (!string) { throw new TypeError('argument string is required') } // support req/res-like objects as argument var header = typeof string === 'object' ? getcontenttype(string) : string if (typeof header !== 'string') { throw new TypeError('argument string is required to be a string') } var index = header.indexOf(';') var type = index !== -1 ? header.substr(0, index).trim() : header.trim() if (!TYPE_REGEXP.test(type)) { throw new TypeError('invalid media type') } var obj = new ContentType(type.toLowerCase()) // parse parameters if (index !== -1) { var key var match var value PARAM_REGEXP.lastIndex = index while ((match = PARAM_REGEXP.exec(header))) { if (match.index !== index) { throw new TypeError('invalid parameter format') } index += match[0].length key = match[1].toLowerCase() value = match[2] if (value[0] === '"') { // remove quotes and escapes value = value .substr(1, value.length - 2) .replace(QESC_REGEXP, '$1') } obj.parameters[key] = value } if (index !== header.length) { throw new TypeError('invalid parameter format') } } return obj } /** * Get content-type from req/res objects. * * @param {object} * @return {Object} * @private */ function getcontenttype (obj) { var header if (typeof obj.getHeader === 'function') { // res-like header = obj.getHeader('content-type') } else if (typeof obj.headers === 'object') { // req-like header = obj.headers && obj.headers['content-type'] } if (typeof header !== 'string') { throw new TypeError('content-type header is missing from object') } return header } /** * Quote a string if necessary. * * @param {string} val * @return {string} * @private */ function qstring (val) { var str = String(val) // no need to quote tokens if (TOKEN_REGEXP.test(str)) { return str } if (str.length > 0 && !TEXT_REGEXP.test(str)) { throw new TypeError('invalid parameter value') } return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } /** * Class to represent a content type. * @private */ function ContentType (type) { this.parameters = Object.create(null) this.type = type } },{}],36:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var objectCreate = Object.create || objectCreatePolyfill var objectKeys = Object.keys || objectKeysPolyfill var bind = Function.prototype.bind || functionBindPolyfill function EventEmitter() { if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { this._events = objectCreate(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; var hasDefineProperty; try { var o = {}; if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); hasDefineProperty = o.x === 0; } catch (err) { hasDefineProperty = false } if (hasDefineProperty) { Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { // check whether the input is a positive number (whose value is zero or // greater and not a NaN). if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number'); defaultMaxListeners = arg; } }); } else { EventEmitter.defaultMaxListeners = defaultMaxListeners; } // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events; var doError = (type === 'error'); events = this._events; if (events) doError = (doError && events.error == null); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { if (arguments.length > 1) er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Unhandled "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = objectCreate(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' "' + String(type) + '" listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit.'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; if (typeof console === 'object' && console.warn) { console.warn('%s: %s', w.name, w.message); } } } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; switch (arguments.length) { case 0: return this.listener.call(this.target); case 1: return this.listener.call(this.target, arguments[0]); case 2: return this.listener.call(this.target, arguments[0], arguments[1]); case 3: return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]); default: var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) args[i] = arguments[i]; this.listener.apply(this.target, args); } } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = bind.call(onceWrapper, state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = objectCreate(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else spliceOne(list, position); if (list.length === 1) events[type] = list[0]; if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = objectCreate(null); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = objectCreate(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = objectKeys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = objectCreate(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (!events) return []; var evlistener = events[type]; if (!evlistener) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function objectCreatePolyfill(proto) { var F = function() {}; F.prototype = proto; return new F; } function objectKeysPolyfill(obj) { var keys = []; for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } return k; } function functionBindPolyfill(context) { var fn = this; return function () { return fn.apply(context, arguments); }; } },{}],37:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],38:[function(require,module,exports){ /* * loglevel - https://github.com/pimterry/loglevel * * Copyright (c) 2013 Tim Perry * Licensed under the MIT license. */ (function (root, definition) { "use strict"; if (typeof define === 'function' && define.amd) { define(definition); } else if (typeof module === 'object' && module.exports) { module.exports = definition(); } else { root.log = definition(); } }(this, function () { "use strict"; // Slightly dubious tricks to cut down minimized file size var noop = function() {}; var undefinedType = "undefined"; var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && ( /Trident\/|MSIE /.test(window.navigator.userAgent) ); var logMethods = [ "trace", "debug", "info", "warn", "error" ]; // Cross-browser bind equivalent that works at least back to IE6 function bindMethod(obj, methodName) { var method = obj[methodName]; if (typeof method.bind === 'function') { return method.bind(obj); } else { try { return Function.prototype.bind.call(method, obj); } catch (e) { // Missing bind shim or IE8 + Modernizr, fallback to wrapping return function() { return Function.prototype.apply.apply(method, [obj, arguments]); }; } } } // Trace() doesn't print the message in IE, so for that case we need to wrap it function traceForIE() { if (console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { // In old IE, native console methods themselves don't have apply(). Function.prototype.apply.apply(console.log, [console, arguments]); } } if (console.trace) console.trace(); } // Build the best logging method possible for this env // Wherever possible we want to bind, not wrap, to preserve stack traces function realMethod(methodName) { if (methodName === 'debug') { methodName = 'log'; } if (typeof console === undefinedType) { return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives } else if (methodName === 'trace' && isIE) { return traceForIE; } else if (console[methodName] !== undefined) { return bindMethod(console, methodName); } else if (console.log !== undefined) { return bindMethod(console, 'log'); } else { return noop; } } // These private functions always need `this` to be set properly function replaceLoggingMethods(level, loggerName) { /*jshint validthis:true */ for (var i = 0; i < logMethods.length; i++) { var methodName = logMethods[i]; this[methodName] = (i < level) ? noop : this.methodFactory(methodName, level, loggerName); } // Define log.log as an alias for log.debug this.log = this.debug; } // In old IE versions, the console isn't present until you first open it. // We build realMethod() replacements here that regenerate logging methods function enableLoggingWhenConsoleArrives(methodName, level, loggerName) { return function () { if (typeof console !== undefinedType) { replaceLoggingMethods.call(this, level, loggerName); this[methodName].apply(this, arguments); } }; } // By default, we use closely bound real methods wherever possible, and // otherwise we wait for a console to appear, and then try again. function defaultMethodFactory(methodName, level, loggerName) { /*jshint validthis:true */ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments); } function Logger(name, defaultLevel, factory) { var self = this; var currentLevel; var storageKey = "loglevel"; if (name) { storageKey += ":" + name; } function persistLevelIfPossible(levelNum) { var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); if (typeof window === undefinedType) return; // Use localStorage if available try { window.localStorage[storageKey] = levelName; return; } catch (ignore) {} // Use session cookie as fallback try { window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";"; } catch (ignore) {} } function getPersistedLevel() { var storedLevel; if (typeof window === undefinedType) return; try { storedLevel = window.localStorage[storageKey]; } catch (ignore) {} // Fallback to cookies if local storage gives us nothing if (typeof storedLevel === undefinedType) { try { var cookie = window.document.cookie; var location = cookie.indexOf( encodeURIComponent(storageKey) + "="); if (location !== -1) { storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1]; } } catch (ignore) {} } // If the stored level is not valid, treat it as if nothing was stored. if (self.levels[storedLevel] === undefined) { storedLevel = undefined; } return storedLevel; } /* * * Public logger API - see https://github.com/pimterry/loglevel for details * */ self.name = name; self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, "ERROR": 4, "SILENT": 5}; self.methodFactory = factory || defaultMethodFactory; self.getLevel = function () { return currentLevel; }; self.setLevel = function (level, persist) { if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) { level = self.levels[level.toUpperCase()]; } if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) { currentLevel = level; if (persist !== false) { // defaults to true persistLevelIfPossible(level); } replaceLoggingMethods.call(self, level, name); if (typeof console === undefinedType && level < self.levels.SILENT) { return "No console available for logging"; } } else { throw "log.setLevel() called with invalid level: " + level; } }; self.setDefaultLevel = function (level) { if (!getPersistedLevel()) { self.setLevel(level, false); } }; self.enableAll = function(persist) { self.setLevel(self.levels.TRACE, persist); }; self.disableAll = function(persist) { self.setLevel(self.levels.SILENT, persist); }; // Initialize with the right level var initialLevel = getPersistedLevel(); if (initialLevel == null) { initialLevel = defaultLevel == null ? "WARN" : defaultLevel; } self.setLevel(initialLevel, false); } /* * * Top-level API * */ var defaultLogger = new Logger(); var _loggersByName = {}; defaultLogger.getLogger = function getLogger(name) { if (typeof name !== "string" || name === "") { throw new TypeError("You must supply a name when creating a logger."); } var logger = _loggersByName[name]; if (!logger) { logger = _loggersByName[name] = new Logger( name, defaultLogger.getLevel(), defaultLogger.methodFactory); } return logger; }; // Grab the current global log variable in case of overwrite var _log = (typeof window !== undefinedType) ? window.log : undefined; defaultLogger.noConflict = function() { if (typeof window !== undefinedType && window.log === defaultLogger) { window.log = _log; } return defaultLogger; }; defaultLogger.getLoggers = function getLoggers() { return _loggersByName; }; return defaultLogger; })); },{}],39:[function(require,module,exports){ 'use strict'; var replace = String.prototype.replace; var percentTwenties = /%20/g; var util = require('./utils'); var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = util.assign( { 'default': Format.RFC3986, formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } } }, Format ); },{"./utils":43}],40:[function(require,module,exports){ 'use strict'; var stringify = require('./stringify'); var parse = require('./parse'); var formats = require('./formats'); module.exports = { formats: formats, parse: parse, stringify: stringify }; },{"./formats":39,"./parse":41,"./stringify":42}],41:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function (val, options) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } return val; }; // This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the ✓ character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); val = utils.maybeMap( parseArrayValue(part.slice(pos + 1), options), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); } ); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options, valuesParsed) { var leaf = valuesParsed ? val : parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; // eslint-disable-line no-param-reassign } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = options.depth > 0 && brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; },{"./utils":43}],42:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'; }; var stringify = function stringify( object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = utils.maybeMap(obj, function (value) { if (value instanceof Date) { return serializeDate(value); } return value; }).join(','); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key') : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key'); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value'))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; var value = obj[key]; if (skipNulls && value === null) { continue; } var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? '.' + key : '[' + key + ']'); pushToArray(values, stringify( value, keyPrefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset )); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.formatter, options.encodeValuesOnly, options.charset )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('✓') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; },{"./formats":39,"./utils":43}],43:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (typeof source !== 'object') { if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, merge: merge }; },{}],44:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],45:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],46:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":44,"./encode":45}],47:[function(require,module,exports){ /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var runtime = (function (exports) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } exports.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. exports.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl ); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. typeof module === "object" ? module.exports : {} )); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } },{}],48:[function(require,module,exports){ /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":34}],49:[function(require,module,exports){ module.exports={ "0": "O", "1": "l", "֭": "֖", "֮": "֘", "֨": "֙", "֤": "֚", "᪴": "ۛ", "⃛": "ۛ", "ؙ": "̓", "ࣳ": "̓", "̓": "̓", "̕": "̓", "ُ": "̓", "ٝ": "̔", "֜": "́", "֝": "́", "ؘ": "́", "݇": "́", "́": "́", "॔": "́", "َ": "́", "̀": "̀", "॓": "̀", "̌": "̆", "꙼": "̆", "٘": "̆", "ٚ": "̆", "ͮ": "̆", "ۨ": "̆̇", "̐": "̆̇", "ँ": "̆̇", "ঁ": "̆̇", "ઁ": "̆̇", "ଁ": "̆̇", "ఀ": "̆̇", "ಁ": "̆̇", "ഁ": "̆̇", "𑒿": "̆̇", "᳐": "̂", "̑": "̂", "ٛ": "̂", "߮": "̂", "꛰": "̂", "֯": "̊", "۟": "̊", "៓": "̊", "゚": "̊", "ْ": "̊", "ஂ": "̊", "ံ": "̊", "ំ": "̊", "𑌀": "̊", "ํ": "̊", "ໍ": "̊", "ͦ": "̊", "ⷪ": "̊", "࣫": "̈", "߳": "̈", "ً": "̋", "ࣰ": "̋", "͂": "̃", "ٓ": "̃", "ׄ": "̇", "۬": "̇", "݀": "̇", "࣪": "̇", "݁": "̇", "͘": "̇", "ֹ": "̇", "ֺ": "̇", "ׂ": "̇", "ׁ": "̇", "߭": "̇", "ं": "̇", "ਂ": "̇", "ં": "̇", "்": "̇", "̷": "̸", "᪷": "̨", "̢": "̨", "ͅ": "̨", "᳒": "̄", "̅": "̄", "ٙ": "̄", "߫": "̄", "꛱": "̄", "᳚": "̎", "ٗ": "̒", "͗": "͐", "ࣿ": "͐", "ࣸ": "͐", "ऀ": "͒", "᳭": "̖", "᳜": "̩", "ٖ": "̩", "᳕": "̫", "͇": "̳", "ࣹ": "͔", "ࣺ": "͕", "゛": "゙", "゜": "゚", "̶": "̵", "〬": "̉", "ׅ": "̣", "࣭": "̣", "᳝": "̣", "ִ": "̣", "ٜ": "̣", "़": "̣", "়": "̣", "਼": "̣", "઼": "̣", "଼": "̣", "𑇊": "̣", "𑓃": "̣", "𐨺": "̣", "࣮": "̤", "᳞": "̤", "༷": "̥", "〭": "̥", "̧": "̦", "̡": "̦", "̹": "̦", "᳙": "̭", "᳘": "̮", "॒": "̱", "̠": "̱", "ࣱ": "ٌ", "ࣨ": "ٌ", "ࣥ": "ٌ", "ﱞ": "ﹲّ", "ࣲ": "ٍ", "ﱟ": "ﹴّ", "ﳲ": "ﹷّ", "ﱠ": "ﹶّ", "ﳳ": "ﹹّ", "ﱡ": "ﹸّ", "ؚ": "ِ", "̗": "ِ", "ﳴ": "ﹻّ", "ﱢ": "ﹺّ", "ﱣ": "ﹼٰ", "ٟ": "ٕ", "̍": "ٰ", "݂": "ܼ", "ਃ": "ঃ", "ః": "ঃ", "ಃ": "ঃ", "ഃ": "ঃ", "ඃ": "ঃ", "း": "ঃ", "𑓁": "ঃ", "់": "่", "່": "่", "້": "้", "໊": "๊", "໋": "๋", "꙯": "⃩", "\u2028": " ", "\u2029": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", " ": " ", "ߺ": "_", "﹍": "_", "﹎": "_", "﹏": "_", "‐": "-", "‑": "-", "‒": "-", "–": "-", "﹘": "-", "۔": "-", "⁃": "-", "˗": "-", "−": "-", "➖": "-", "Ⲻ": "-", "⨩": "-̓", "⸚": "-̈", "﬩": "-̇", "∸": "-̇", "⨪": "-̣", "꓾": "-.", "~": "〜", "؍": ",", "٫": ",", "‚": ",", "¸": ",", "ꓹ": ",", "⸲": "،", "٬": "،", ";": ";", "⸵": "؛", "ः": ":", "ઃ": ":", ":": ":", "։": ":", "܃": ":", "܄": ":", "᛬": ":", "︰": ":", "᠃": ":", "᠉": ":", "⁚": ":", "׃": ":", "˸": ":", "꞉": ":", "∶": ":", "ː": ":", "ꓽ": ":", "⩴": "::=", "⧴": ":→", "!": "!", "ǃ": "!", "ⵑ": "!", "‼": "!!", "⁉": "!?", "ʔ": "?", "Ɂ": "?", "ॽ": "?", "Ꭾ": "?", "ꛫ": "?", "⁈": "?!", "⁇": "??", "⸮": "؟", "𝅭": ".", "․": ".", "܁": ".", "܂": ".", "꘎": ".", "𐩐": ".", "٠": ".", "۰": ".", "ꓸ": ".", "ꓻ": ".,", "‥": "..", "ꓺ": "..", "…": "...", "꛴": "꛳꛳", "・": "·", "・": "·", "᛫": "·", "·": "·", "⸱": "·", "𐄁": "·", "•": "·", "‧": "·", "∙": "·", "⋅": "·", "ꞏ": "·", "ᐧ": "·", "⋯": "···", "ⵈ": "···", "ᑄ": "·<", "⋗": "·>", "ᐷ": "·>", "ᑀ": "·>", "ᔯ": "·4", "ᑾ": "·b", "ᒀ": "·ḃ", "ᑺ": "·d", "ᒘ": "·J", "ᒶ": "·L", "ᑶ": "·P", "ᑗ": "·U", "ᐺ": "·V", "ᐼ": "·Ʌ", "ᒮ": "·Γ", "ᐎ": "·Δ", "ᑙ": "·Ո", "ᐌ": "·ᐁ", "ᐐ": "·ᐄ", "ᐒ": "·ᐅ", "ᐔ": "·ᐆ", "ᐗ": "·ᐊ", "ᐙ": "·ᐋ", "ᐾ": "·ᐲ", "ᑂ": "·ᐴ", "ᑆ": "·ᐹ", "ᑛ": "·ᑏ", "ᑔ": "·ᑐ", "ᑝ": "·ᑐ", "ᑟ": "·ᑑ", "ᑡ": "·ᑕ", "ᑣ": "·ᑖ", "ᑴ": "·ᑫ", "ᑸ": "·ᑮ", "ᑼ": "·ᑰ", "ᒒ": "·ᒉ", "ᒔ": "·ᒋ", "ᒖ": "·ᒌ", "ᒚ": "·ᒎ", "ᒜ": "·ᒐ", "ᒞ": "·ᒑ", "ᒬ": "·ᒣ", "ᒰ": "·ᒦ", "ᒲ": "·ᒧ", "ᒴ": "·ᒨ", "ᒸ": "·ᒫ", "ᓉ": "·ᓀ", "ᣆ": "·ᓂ", "ᣈ": "·ᓃ", "ᣊ": "·ᓄ", "ᣌ": "·ᓅ", "ᓋ": "·ᓇ", "ᓍ": "·ᓈ", "ᓜ": "·ᓓ", "ᓞ": "·ᓕ", "ᓠ": "·ᓖ", "ᓢ": "·ᓗ", "ᓤ": "·ᓘ", "ᓦ": "·ᓚ", "ᓨ": "·ᓛ", "ᓶ": "·ᓭ", "ᓸ": "·ᓯ", "ᓺ": "·ᓰ", "ᓼ": "·ᓱ", "ᓾ": "·ᓲ", "ᔀ": "·ᓴ", "ᔂ": "·ᓵ", "ᔗ": "·ᔐ", "ᔙ": "·ᔑ", "ᔛ": "·ᔒ", "ᔝ": "·ᔓ", "ᔟ": "·ᔔ", "ᔡ": "·ᔕ", "ᔣ": "·ᔖ", "ᔱ": "·ᔨ", "ᔳ": "·ᔩ", "ᔵ": "·ᔪ", "ᔷ": "·ᔫ", "ᔹ": "·ᔭ", "ᔻ": "·ᔮ", "ᣎ": "·ᕃ", "ᣏ": "·ᕆ", "ᣐ": "·ᕇ", "ᣑ": "·ᕈ", "ᣒ": "·ᕉ", "ᣓ": "·ᕋ", "ᕎ": "·ᕌ", "ᕛ": "·ᕚ", "ᕨ": "·ᕧ", "ᢳ": "·ᢱ", "ᢶ": "·ᢴ", "ᢹ": "·ᢸ", "ᣂ": "·ᣀ", "꠰": "।", "॥": "।।", "᰼": "᰻᰻", "။": "၊၊", "᪩": "᪨᪨", "᪫": "᪪᪨", "᭟": "᭞᭞", "𐩗": "𐩖𐩖", "𑑌": "𑑋𑑋", "𑙂": "𑙁𑙁", "𑱂": "𑱁𑱁", "᱿": "᱾᱾", "՝": "'", "'": "'", "‘": "'", "’": "'", "‛": "'", "′": "'", "‵": "'", "՚": "'", "׳": "'", "`": "'", "`": "'", "`": "'", "´": "'", "΄": "'", "´": "'", "᾽": "'", "᾿": "'", "῾": "'", "ʹ": "'", "ʹ": "'", "ˈ": "'", "ˊ": "'", "ˋ": "'", "˴": "'", "ʻ": "'", "ʽ": "'", "ʼ": "'", "ʾ": "'", "ꞌ": "'", "י": "'", "ߴ": "'", "ߵ": "'", "ᑊ": "'", "ᛌ": "'", "𖽑": "'", "𖽒": "'", "᳓": "''", "\"": "''", """: "''", "“": "''", "”": "''", "‟": "''", "″": "''", "‶": "''", "〃": "''", "״": "''", "˝": "''", "ʺ": "''", "˶": "''", "ˮ": "''", "ײ": "''", "‴": "'''", "‷": "'''", "⁗": "''''", "Ɓ": "'B", "Ɗ": "'D", "ʼn": "'n", "Ƥ": "'P", "Ƭ": "'T", "Ƴ": "'Y", "[": "(", "❨": "(", "❲": "(", "〔": "(", "﴾": "(", "⸨": "((", "㈠": "(ー)", "⑵": "(2)", "⒇": "(2O)", "⑶": "(3)", "⑷": "(4)", "⑸": "(5)", "⑹": "(6)", "⑺": "(7)", "⑻": "(8)", "⑼": "(9)", "⒜": "(a)", "🄐": "(A)", "⒝": "(b)", "🄑": "(B)", "⒞": "(c)", "🄒": "(C)", "⒟": "(d)", "🄓": "(D)", "⒠": "(e)", "🄔": "(E)", "⒡": "(f)", "🄕": "(F)", "⒢": "(g)", "🄖": "(G)", "⒣": "(h)", "🄗": "(H)", "⒤": "(i)", "⒥": "(j)", "🄙": "(J)", "⒦": "(k)", "🄚": "(K)", "⑴": "(l)", "🄘": "(l)", "⒧": "(l)", "🄛": "(L)", "⑿": "(l2)", "⒀": "(l3)", "⒁": "(l4)", "⒂": "(l5)", "⒃": "(l6)", "⒄": "(l7)", "⒅": "(l8)", "⒆": "(l9)", "⑾": "(ll)", "⑽": "(lO)", "🄜": "(M)", "⒩": "(n)", "🄝": "(N)", "⒪": "(o)", "🄞": "(O)", "⒫": "(p)", "🄟": "(P)", "⒬": "(q)", "🄠": "(Q)", "⒭": "(r)", "🄡": "(R)", "⒨": "(rn)", "⒮": "(s)", "🄢": "(S)", "🄪": "(S)", "⒯": "(t)", "🄣": "(T)", "⒰": "(u)", "🄤": "(U)", "⒱": "(v)", "🄥": "(V)", "⒲": "(w)", "🄦": "(W)", "⒳": "(x)", "🄧": "(X)", "⒴": "(y)", "🄨": "(Y)", "⒵": "(z)", "🄩": "(Z)", "㈀": "(ᄀ)", "㈎": "(가)", "㈁": "(ᄂ)", "㈏": "(나)", "㈂": "(ᄃ)", "㈐": "(다)", "㈃": "(ᄅ)", "㈑": "(라)", "㈄": "(ᄆ)", "㈒": "(마)", "㈅": "(ᄇ)", "㈓": "(바)", "㈆": "(ᄉ)", "㈔": "(사)", "㈇": "(ᄋ)", "㈕": "(아)", "㈝": "(오전)", "㈞": "(오후)", "㈈": "(ᄌ)", "㈖": "(자)", "㈜": "(주)", "㈉": "(ᄎ)", "㈗": "(차)", "㈊": "(ᄏ)", "㈘": "(카)", "㈋": "(ᄐ)", "㈙": "(타)", "㈌": "(ᄑ)", "㈚": "(파)", "㈍": "(ᄒ)", "㈛": "(하)", "㈦": "(七)", "㈢": "(三)", "🉁": "(三)", "㈨": "(九)", "㈡": "(二)", "🉂": "(二)", "㈤": "(五)", "㈹": "(代)", "㈽": "(企)", "㉁": "(休)", "㈧": "(八)", "㈥": "(六)", "㈸": "(労)", "🉇": "(勝)", "㈩": "(十)", "㈿": "(協)", "㈴": "(名)", "㈺": "(呼)", "㈣": "(四)", "㈯": "(土)", "㈻": "(学)", "🉃": "(安)", "🉅": "(打)", "🉈": "(敗)", "㈰": "(日)", "㈪": "(月)", "㈲": "(有)", "㈭": "(木)", "🉀": "(本)", "㈱": "(株)", "㈬": "(水)", "㈫": "(火)", "🉄": "(点)", "㈵": "(特)", "🉆": "(盗)", "㈼": "(監)", "㈳": "(社)", "㈷": "(祝)", "㉀": "(祭)", "㉂": "(自)", "㉃": "(至)", "㈶": "(財)", "㈾": "(資)", "㈮": "(金)", "]": ")", "❩": ")", "❳": ")", "〕": ")", "﴿": ")", "⸩": "))", "❴": "{", "𝄔": "{", "❵": "}", "〚": "⟦", "〛": "⟧", "⟨": "❬", "〈": "❬", "〈": "❬", "㇛": "❬", "く": "❬", "𡿨": "❬", "⟩": "❭", "〉": "❭", "〉": "❭", "^": "︿", "⸿": "¶", "⁎": "*", "٭": "*", "∗": "*", "𐌟": "*", "᜵": "/", "⁁": "/", "∕": "/", "⁄": "/", "╱": "/", "⟋": "/", "⧸": "/", "𝈺": "/", "㇓": "/", "〳": "/", "Ⳇ": "/", "ノ": "/", "丿": "/", "⼃": "/", "⧶": "/̄", "⫽": "//", "⫻": "///", "\": "\\", "﹨": "\\", "∖": "\\", "⟍": "\\", "⧵": "\\", "⧹": "\\", "𝈏": "\\", "𝈻": "\\", "㇔": "\\", "丶": "\\", "⼂": "\\", "⳹": "\\\\", "⑊": "\\\\", "⟈": "\\ᑕ", "ꝸ": "&", "૰": "॰", "𑂻": "॰", "𑇇": "॰", "⚬": "॰", "𑇛": "꣼", "៙": "๏", "៕": "๚", "៚": "๛", "༌": "་", "༎": "།།", "˄": "^", "ˆ": "^", "꙾": "ˇ", "˘": "ˇ", "‾": "ˉ", "﹉": "ˉ", "﹊": "ˉ", "﹋": "ˉ", "﹌": "ˉ", "¯": "ˉ", " ̄": "ˉ", "▔": "ˉ", "ъ": "ˉb", "ꙑ": "ˉbi", "͵": "ˏ", "˻": "˪", "꜖": "˪", "꜔": "˫", "。": "˳", "⸰": "°", "˚": "°", "∘": "°", "○": "°", "◦": "°", "⍜": "°̲", "⍤": "°̈", "℃": "°C", "℉": "°F", "௵": "௳", "༛": "༚༚", "༟": "༚༝", "࿎": "༝༚", "༞": "༝༝", "Ⓒ": "©", "Ⓡ": "®", "Ⓟ": "℗", "𝈛": "⅄", "⯬": "↞", "⯭": "↟", "⯮": "↠", "⯯": "↡", "↵": "↲", "⥥": "⇃⇂", "⥯": "⇃ᛚ", "𝛛": "∂", "𝜕": "∂", "𝝏": "∂", "𝞉": "∂", "𝟃": "∂", "𞣌": "∂", "𞣍": "∂̵", "ð": "∂̵", "⌀": "∅", "𝛁": "∇", "𝛻": "∇", "𝜵": "∇", "𝝯": "∇", "𝞩": "∇", "𑢨": "∇", "⍢": "∇̈", "⍫": "∇̴", "█": "∎", "■": "∎", "⨿": "∐", "᛭": "+", "➕": "+", "𐊛": "+", "⨣": "+̂", "⨢": "+̊", "⨤": "+̃", "∔": "+̇", "⨥": "+̣", "⨦": "+̰", "⨧": "+₂", "➗": "÷", "‹": "<", "❮": "<", "˂": "<", "𝈶": "<", "ᐸ": "<", "ᚲ": "<", "⋖": "<·", "Ⲵ": "<·", "ᑅ": "<·", "≪": "<<", "⋘": "<<<", "᐀": "=", "⹀": "=", "゠": "=", "꓿": "=", "≚": "=̆", "≙": "=̂", "≗": "=̊", "≐": "=̇", "≑": "=̣̇", "⩮": "=⃰", "⩵": "==", "⩶": "===", "≞": "=ͫ", "›": ">", "❯": ">", "˃": ">", "𝈷": ">", "ᐳ": ">", "𖼿": ">", "ᑁ": ">·", "⪥": "><", "≫": ">>", "⨠": ">>", "⋙": ">>>", "⁓": "~", "˜": "~", "῀": "~", "∼": "~", "⍨": "~̈", "⸞": "~̇", "⩪": "~̇", "⸟": "~̣", "𞣈": "∠", "⋀": "∧", "∯": "∮∮", "∰": "∮∮∮", "⸫": "∴", "⸪": "∵", "⸬": "∷", "𑇞": "≈", "♎": "≏", "🝞": "≏", "≣": "≡", "⨃": "⊍", "⨄": "⊎", "𝈸": "⊏", "𝈹": "⊐", "⨅": "⊓", "⨆": "⊔", "⨂": "⊗", "⍟": "⊛", "🝱": "⊠", "🝕": "⊡", "◁": "⊲", "▷": "⊳", "⍣": "⋆̈", "︴": "⌇", "◠": "⌒", "⨽": "⌙", "⌥": "⌤", "⧇": "⌻", "◎": "⌾", "⦾": "⌾", "⧅": "⍂", "⦰": "⍉", "⏃": "⍋", "⏂": "⍎", "⏁": "⍕", "⏆": "⍭", "☸": "⎈", "︵": "⏜", "︶": "⏝", "︷": "⏞", "︸": "⏟", "︹": "⏠", "︺": "⏡", "▱": "⏥", "⏼": "⏻", "︱": "│", "|": "│", "┃": "│", "┏": "┌", "┣": "├", "▐": "▌", "▗": "▖", "▝": "▘", "☐": "□", "■": "▪", "▸": "▶", "►": "▶", "⳩": "☧", "🜊": "☩", "🌒": "☽", "🌙": "☽", "⏾": "☾", "🌘": "☾", "⧙": "⦚", "🜺": "⧟", "⨾": "⨟", "𐆠": "⳨", "♩": "𝅘𝅥", "♪": "𝅘𝅥𝅮", "⓪": "🄍", "↺": "🄎", "˙": "ॱ", "ൎ": "ॱ", "-": "ー", "—": "ー", "―": "ー", "─": "ー", "━": "ー", "㇐": "ー", "ꟷ": "ー", "ᅳ": "ー", "ㅡ": "ー", "一": "ー", "⼀": "ー", "ᆖ": "ーー", "ힹ": "ーᅡ", "ힺ": "ーᅥ", "ힻ": "ーᅥ丨", "ힼ": "ーᅩ", "ᆕ": "ーᅮ", "ᅴ": "ー丨", "ㅢ": "ー丨", "ᆗ": "ー丨ᅮ", "🄏": "$⃠", "₤": "£", "〒": "₸", "〶": "₸", "᭜": "᭐", "꧆": "꧐", "𑓑": "১", "೧": "౧", "ၥ": "၁", "①": "➀", "⑩": "➉", "⏨": "₁₀", "𝟐": "2", "𝟚": "2", "𝟤": "2", "𝟮": "2", "𝟸": "2", "🯲": "2", "Ꝛ": "2", "Ƨ": "2", "Ϩ": "2", "Ꙅ": "2", "ᒿ": "2", "ꛯ": "2", "ꧏ": "٢", "۲": "٢", "૨": "२", "𑓒": "২", "೨": "౨", "②": "➁", "ƻ": "2̵", "🄃": "2,", "⒉": "2.", "㏵": "22日", "㍮": "22点", "㏶": "23日", "㍯": "23点", "㏷": "24日", "㍰": "24点", "㏸": "25日", "㏹": "26日", "㏺": "27日", "㏻": "28日", "㏼": "29日", "㏴": "2l日", "㍭": "2l点", "⒛": "2O.", "㏳": "2O日", "㍬": "2O点", "෩": "෨ා", "෯": "෨ී", "㏡": "2日", "㋁": "2月", "㍚": "2点", "𝈆": "3", "𝟑": "3", "𝟛": "3", "𝟥": "3", "𝟯": "3", "𝟹": "3", "🯳": "3", "Ɜ": "3", "Ȝ": "3", "Ʒ": "3", "Ꝫ": "3", "Ⳍ": "3", "З": "3", "Ӡ": "3", "𖼻": "3", "𑣊": "3", "۳": "٣", "𞣉": "٣", "૩": "३", "③": "➂", "Ҙ": "3̦", "🄄": "3,", "⒊": "3.", "㏾": "3l日", "㏽": "3O日", "㏢": "3日", "㋂": "3月", "㍛": "3点", "𝟒": "4", "𝟜": "4", "𝟦": "4", "𝟰": "4", "𝟺": "4", "🯴": "4", "Ꮞ": "4", "𑢯": "4", "۴": "٤", "૪": "४", "④": "➃", "🄅": "4,", "⒋": "4.", "ᔰ": "4·", "㏣": "4日", "㋃": "4月", "㍜": "4点", "𝟓": "5", "𝟝": "5", "𝟧": "5", "𝟱": "5", "𝟻": "5", "🯵": "5", "Ƽ": "5", "𑢻": "5", "⑤": "➄", "🄆": "5,", "⒌": "5.", "㏤": "5日", "㋄": "5月", "㍝": "5点", "𝟔": "6", "𝟞": "6", "𝟨": "6", "𝟲": "6", "𝟼": "6", "🯶": "6", "Ⳓ": "6", "б": "6", "Ꮾ": "6", "𑣕": "6", "۶": "٦", "𑓖": "৬", "⑥": "➅", "🄇": "6,", "⒍": "6.", "㏥": "6日", "㋅": "6月", "㍞": "6点", "𝈒": "7", "𝟕": "7", "𝟟": "7", "𝟩": "7", "𝟳": "7", "𝟽": "7", "🯷": "7", "𐓒": "7", "𑣆": "7", "⑦": "➆", "🄈": "7,", "⒎": "7.", "㏦": "7日", "㋆": "7月", "㍟": "7点", "ଃ": "8", "৪": "8", "੪": "8", "𞣋": "8", "𝟖": "8", "𝟠": "8", "𝟪": "8", "𝟴": "8", "𝟾": "8", "🯸": "8", "ȣ": "8", "Ȣ": "8", "𐌚": "8", "૮": "८", "⑧": "➇", "🄉": "8,", "⒏": "8.", "㏧": "8日", "㋇": "8月", "㍠": "8点", "੧": "9", "୨": "9", "৭": "9", "൭": "9", "𝟗": "9", "𝟡": "9", "𝟫": "9", "𝟵": "9", "𝟿": "9", "🯹": "9", "Ꝯ": "9", "Ⳋ": "9", "𑣌": "9", "𑢬": "9", "𑣖": "9", "१": "٩", "𑣤": "٩", "۹": "٩", "೯": "౯", "⑨": "➈", "🄊": "9,", "⒐": "9.", "㏨": "9日", "㋈": "9月", "㍡": "9点", "⍺": "a", "a": "a", "𝐚": "a", "𝑎": "a", "𝒂": "a", "𝒶": "a", "𝓪": "a", "𝔞": "a", "𝕒": "a", "𝖆": "a", "𝖺": "a", "𝗮": "a", "𝘢": "a", "𝙖": "a", "𝚊": "a", "ɑ": "a", "α": "a", "𝛂": "a", "𝛼": "a", "𝜶": "a", "𝝰": "a", "𝞪": "a", "а": "a", "ⷶ": "ͣ", "A": "A", "𝐀": "A", "𝐴": "A", "𝑨": "A", "𝒜": "A", "𝓐": "A", "𝔄": "A", "𝔸": "A", "𝕬": "A", "𝖠": "A", "𝗔": "A", "𝘈": "A", "𝘼": "A", "𝙰": "A", "Α": "A", "𝚨": "A", "𝛢": "A", "𝜜": "A", "𝝖": "A", "𝞐": "A", "А": "A", "Ꭺ": "A", "ᗅ": "A", "ꓮ": "A", "𖽀": "A", "𐊠": "A", "⍶": "a̲", "ǎ": "ă", "Ǎ": "Ă", "ȧ": "å", "Ȧ": "Å", "ẚ": "ả", "℀": "a/c", "℁": "a/s", "ꜳ": "aa", "Ꜳ": "AA", "æ": "ae", "ӕ": "ae", "Æ": "AE", "Ӕ": "AE", "ꜵ": "ao", "Ꜵ": "AO", "🜇": "AR", "ꜷ": "au", "Ꜷ": "AU", "ꜹ": "av", "ꜻ": "av", "Ꜹ": "AV", "Ꜻ": "AV", "ꜽ": "ay", "Ꜽ": "AY", "ꭺ": "ᴀ", "∀": "Ɐ", "𝈗": "Ɐ", "ᗄ": "Ɐ", "ꓯ": "Ɐ", "𐐟": "Ɒ", "𝐛": "b", "𝑏": "b", "𝒃": "b", "𝒷": "b", "𝓫": "b", "𝔟": "b", "𝕓": "b", "𝖇": "b", "𝖻": "b", "𝗯": "b", "𝘣": "b", "𝙗": "b", "𝚋": "b", "Ƅ": "b", "Ь": "b", "Ꮟ": "b", "ᑲ": "b", "ᖯ": "b", "B": "B", "ℬ": "B", "𝐁": "B", "𝐵": "B", "𝑩": "B", "𝓑": "B", "𝔅": "B", "𝔹": "B", "𝕭": "B", "𝖡": "B", "𝗕": "B", "𝘉": "B", "𝘽": "B", "𝙱": "B", "Ꞵ": "B", "Β": "B", "𝚩": "B", "𝛣": "B", "𝜝": "B", "𝝗": "B", "𝞑": "B", "В": "B", "Ᏼ": "B", "ᗷ": "B", "ꓐ": "B", "𐊂": "B", "𐊡": "B", "𐌁": "B", "ɓ": "b̔", "ᑳ": "ḃ", "ƃ": "b̄", "Ƃ": "b̄", "Б": "b̄", "ƀ": "b̵", "ҍ": "b̵", "Ҍ": "b̵", "ѣ": "b̵", "Ѣ": "b̵", "ᑿ": "b·", "ᒁ": "ḃ·", "ᒈ": "b'", "Ы": "bl", "в": "ʙ", "ᏼ": "ʙ", "c": "c", "ⅽ": "c", "𝐜": "c", "𝑐": "c", "𝒄": "c", "𝒸": "c", "𝓬": "c", "𝔠": "c", "𝕔": "c", "𝖈": "c", "𝖼": "c", "𝗰": "c", "𝘤": "c", "𝙘": "c", "𝚌": "c", "ᴄ": "c", "ϲ": "c", "ⲥ": "c", "с": "c", "ꮯ": "c", "𐐽": "c", "ⷭ": "ͨ", "🝌": "C", "𑣲": "C", "𑣩": "C", "C": "C", "Ⅽ": "C", "ℂ": "C", "ℭ": "C", "𝐂": "C", "𝐶": "C", "𝑪": "C", "𝒞": "C", "𝓒": "C", "𝕮": "C", "𝖢": "C", "𝗖": "C", "𝘊": "C", "𝘾": "C", "𝙲": "C", "Ϲ": "C", "Ⲥ": "C", "С": "C", "Ꮯ": "C", "ꓚ": "C", "𐊢": "C", "𐌂": "C", "𐐕": "C", "𐔜": "C", "¢": "c̸", "ȼ": "c̸", "₡": "C⃫", "🅮": "C⃠", "ç": "c̦", "ҫ": "c̦", "Ç": "C̦", "Ҫ": "C̦", "Ƈ": "C'", "℅": "c/o", "℆": "c/u", "🅭": "㏄\t⃝", "⋴": "ꞓ", "ɛ": "ꞓ", "ε": "ꞓ", "ϵ": "ꞓ", "𝛆": "ꞓ", "𝛜": "ꞓ", "𝜀": "ꞓ", "𝜖": "ꞓ", "𝜺": "ꞓ", "𝝐": "ꞓ", "𝝴": "ꞓ", "𝞊": "ꞓ", "𝞮": "ꞓ", "𝟄": "ꞓ", "ⲉ": "ꞓ", "є": "ꞓ", "ԑ": "ꞓ", "ꮛ": "ꞓ", "𑣎": "ꞓ", "𐐩": "ꞓ", "€": "Ꞓ", "Ⲉ": "Ꞓ", "Є": "Ꞓ", "⍷": "ꞓ̲", "ͽ": "ꜿ", "Ͽ": "Ꜿ", "ⅾ": "d", "ⅆ": "d", "𝐝": "d", "𝑑": "d", "𝒅": "d", "𝒹": "d", "𝓭": "d", "𝔡": "d", "𝕕": "d", "𝖉": "d", "𝖽": "d", "𝗱": "d", "𝘥": "d", "𝙙": "d", "𝚍": "d", "ԁ": "d", "Ꮷ": "d", "ᑯ": "d", "ꓒ": "d", "Ⅾ": "D", "ⅅ": "D", "𝐃": "D", "𝐷": "D", "𝑫": "D", "𝒟": "D", "𝓓": "D", "𝔇": "D", "𝔻": "D", "𝕯": "D", "𝖣": "D", "𝗗": "D", "𝘋": "D", "𝘿": "D", "𝙳": "D", "Ꭰ": "D", "ᗞ": "D", "ᗪ": "D", "ꓓ": "D", "ɗ": "d̔", "ɖ": "d̨", "ƌ": "d̄", "đ": "d̵", "Đ": "D̵", "Ð": "D̵", "Ɖ": "D̵", "₫": "ḏ̵", "ꝺ": "Ꝺ", "ᑻ": "d·", "ᒇ": "d'", "ʤ": "dȝ", "dz": "dz", "ʣ": "dz", "Dz": "Dz", "DZ": "DZ", "dž": "dž", "Dž": "Dž", "DŽ": "DŽ", "ʥ": "dʑ", "ꭰ": "ᴅ", "⸹": "ẟ", "δ": "ẟ", "𝛅": "ẟ", "𝛿": "ẟ", "𝜹": "ẟ", "𝝳": "ẟ", "𝞭": "ẟ", "ծ": "ẟ", "ᕷ": "ẟ", "℮": "e", "e": "e", "ℯ": "e", "ⅇ": "e", "𝐞": "e", "𝑒": "e", "𝒆": "e", "𝓮": "e", "𝔢": "e", "𝕖": "e", "𝖊": "e", "𝖾": "e", "𝗲": "e", "𝘦": "e", "𝙚": "e", "𝚎": "e", "ꬲ": "e", "е": "e", "ҽ": "e", "ⷷ": "ͤ", "⋿": "E", "E": "E", "ℰ": "E", "𝐄": "E", "𝐸": "E", "𝑬": "E", "𝓔": "E", "𝔈": "E", "𝔼": "E", "𝕰": "E", "𝖤": "E", "𝗘": "E", "𝘌": "E", "𝙀": "E", "𝙴": "E", "Ε": "E", "𝚬": "E", "𝛦": "E", "𝜠": "E", "𝝚": "E", "𝞔": "E", "Е": "E", "ⴹ": "E", "Ꭼ": "E", "ꓰ": "E", "𑢦": "E", "𑢮": "E", "𐊆": "E", "ě": "ĕ", "Ě": "Ĕ", "ɇ": "e̸", "Ɇ": "E̸", "ҿ": "ę", "ꭼ": "ᴇ", "ə": "ǝ", "ә": "ǝ", "∃": "Ǝ", "ⴺ": "Ǝ", "ꓱ": "Ǝ", "ɚ": "ǝ˞", "ᴔ": "ǝo", "ꭁ": "ǝo̸", "ꭂ": "ǝo̵", "Ә": "Ə", "𝈡": "Ɛ", "ℇ": "Ɛ", "Ԑ": "Ɛ", "Ꮛ": "Ɛ", "𖼭": "Ɛ", "𐐁": "Ɛ", "ᶟ": "ᵋ", "ᴈ": "ɜ", "з": "ɜ", "ҙ": "ɜ̦", "𐑂": "ɞ", "ꞝ": "ʚ", "𐐪": "ʚ", "𝐟": "f", "𝑓": "f", "𝒇": "f", "𝒻": "f", "𝓯": "f", "𝔣": "f", "𝕗": "f", "𝖋": "f", "𝖿": "f", "𝗳": "f", "𝘧": "f", "𝙛": "f", "𝚏": "f", "ꬵ": "f", "ꞙ": "f", "ſ": "f", "ẝ": "f", "ք": "f", "𝈓": "F", "ℱ": "F", "𝐅": "F", "𝐹": "F", "𝑭": "F", "𝓕": "F", "𝔉": "F", "𝔽": "F", "𝕱": "F", "𝖥": "F", "𝗙": "F", "𝘍": "F", "𝙁": "F", "𝙵": "F", "Ꞙ": "F", "Ϝ": "F", "𝟊": "F", "ᖴ": "F", "ꓝ": "F", "𑣂": "F", "𑢢": "F", "𐊇": "F", "𐊥": "F", "𐔥": "F", "ƒ": "f̦", "Ƒ": "F̦", "ᵮ": "f̴", "℻": "FAX", "ff": "ff", "ffi": "ffi", "ffl": "ffl", "fi": "fi", "fl": "fl", "ʩ": "fŋ", "ᖵ": "Ⅎ", "ꓞ": "Ⅎ", "𝈰": "ꟻ", "ᖷ": "ꟻ", "g": "g", "ℊ": "g", "𝐠": "g", "𝑔": "g", "𝒈": "g", "𝓰": "g", "𝔤": "g", "𝕘": "g", "𝖌": "g", "𝗀": "g", "𝗴": "g", "𝘨": "g", "𝙜": "g", "𝚐": "g", "ɡ": "g", "ᶃ": "g", "ƍ": "g", "ց": "g", "𝐆": "G", "𝐺": "G", "𝑮": "G", "𝒢": "G", "𝓖": "G", "𝔊": "G", "𝔾": "G", "𝕲": "G", "𝖦": "G", "𝗚": "G", "𝘎": "G", "𝙂": "G", "𝙶": "G", "Ԍ": "G", "Ꮐ": "G", "Ᏻ": "G", "ꓖ": "G", "ᶢ": "ᵍ", "ɠ": "g̔", "ǧ": "ğ", "Ǧ": "Ğ", "ǵ": "ģ", "ǥ": "g̵", "Ǥ": "G̵", "Ɠ": "G'", "ԍ": "ɢ", "ꮐ": "ɢ", "ᏻ": "ɢ", "h": "h", "ℎ": "h", "𝐡": "h", "𝒉": "h", "𝒽": "h", "𝓱": "h", "𝔥": "h", "𝕙": "h", "𝖍": "h", "𝗁": "h", "𝗵": "h", "𝘩": "h", "𝙝": "h", "𝚑": "h", "һ": "h", "հ": "h", "Ꮒ": "h", "H": "H", "ℋ": "H", "ℌ": "H", "ℍ": "H", "𝐇": "H", "𝐻": "H", "𝑯": "H", "𝓗": "H", "𝕳": "H", "𝖧": "H", "𝗛": "H", "𝘏": "H", "𝙃": "H", "𝙷": "H", "Η": "H", "𝚮": "H", "𝛨": "H", "𝜢": "H", "𝝜": "H", "𝞖": "H", "Ⲏ": "H", "Н": "H", "Ꮋ": "H", "ᕼ": "H", "ꓧ": "H", "𐋏": "H", "ᵸ": "ᴴ", "ɦ": "h̔", "ꚕ": "h̔", "Ᏺ": "h̔", "Ⱨ": "H̩", "Ң": "H̩", "ħ": "h̵", "ℏ": "h̵", "ћ": "h̵", "Ħ": "H̵", "Ӊ": "H̦", "Ӈ": "H̦", "н": "ʜ", "ꮋ": "ʜ", "ң": "ʜ̩", "ӊ": "ʜ̦", "ӈ": "ʜ̦", "Ԋ": "Ƕ", "ꮀ": "ⱶ", "Ͱ": "Ⱶ", "Ꭸ": "Ⱶ", "Ꮀ": "Ⱶ", "ꚱ": "Ⱶ", "ꞕ": "ꜧ", "˛": "i", "⍳": "i", "i": "i", "ⅰ": "i", "ℹ": "i", "ⅈ": "i", "𝐢": "i", "𝑖": "i", "𝒊": "i", "𝒾": "i", "𝓲": "i", "𝔦": "i", "𝕚": "i", "𝖎": "i", "𝗂": "i", "𝗶": "i", "𝘪": "i", "𝙞": "i", "𝚒": "i", "ı": "i", "𝚤": "i", "ɪ": "i", "ɩ": "i", "ι": "i", "ι": "i", "ͺ": "i", "𝛊": "i", "𝜄": "i", "𝜾": "i", "𝝸": "i", "𝞲": "i", "і": "i", "ꙇ": "i", "ӏ": "i", "ꭵ": "i", "Ꭵ": "i", "𑣃": "i", "ⓛ": "Ⓘ", "⍸": "i̲", "ǐ": "ĭ", "Ǐ": "Ĭ", "ɨ": "i̵", "ᵻ": "i̵", "ᵼ": "i̵", "ⅱ": "ii", "ⅲ": "iii", "ij": "ij", "ⅳ": "iv", "ⅸ": "ix", "j": "j", "ⅉ": "j", "𝐣": "j", "𝑗": "j", "𝒋": "j", "𝒿": "j", "𝓳": "j", "𝔧": "j", "𝕛": "j", "𝖏": "j", "𝗃": "j", "𝗷": "j", "𝘫": "j", "𝙟": "j", "𝚓": "j", "ϳ": "j", "ј": "j", "J": "J", "𝐉": "J", "𝐽": "J", "𝑱": "J", "𝒥": "J", "𝓙": "J", "𝔍": "J", "𝕁": "J", "𝕵": "J", "𝖩": "J", "𝗝": "J", "𝘑": "J", "𝙅": "J", "𝙹": "J", "Ʝ": "J", "Ϳ": "J", "Ј": "J", "Ꭻ": "J", "ᒍ": "J", "ꓙ": "J", "ɉ": "j̵", "Ɉ": "J̵", "ᒙ": "J·", "𝚥": "ȷ", "յ": "ȷ", "ꭻ": "ᴊ", "𝐤": "k", "𝑘": "k", "𝒌": "k", "𝓀": "k", "𝓴": "k", "𝔨": "k", "𝕜": "k", "𝖐": "k", "𝗄": "k", "𝗸": "k", "𝘬": "k", "𝙠": "k", "𝚔": "k", "K": "K", "K": "K", "𝐊": "K", "𝐾": "K", "𝑲": "K", "𝒦": "K", "𝓚": "K", "𝔎": "K", "𝕂": "K", "𝕶": "K", "𝖪": "K", "𝗞": "K", "𝘒": "K", "𝙆": "K", "𝙺": "K", "Κ": "K", "𝚱": "K", "𝛫": "K", "𝜥": "K", "𝝟": "K", "𝞙": "K", "Ⲕ": "K", "К": "K", "Ꮶ": "K", "ᛕ": "K", "ꓗ": "K", "𐔘": "K", "ƙ": "k̔", "Ⱪ": "K̩", "Қ": "K̩", "₭": "K̵", "Ꝁ": "K̵", "Ҟ": "K̵", "Ƙ": "K'", "׀": "l", "|": "l", "∣": "l", "⏽": "l", "│": "l", "١": "l", "۱": "l", "𐌠": "l", "𞣇": "l", "𝟏": "l", "𝟙": "l", "𝟣": "l", "𝟭": "l", "𝟷": "l", "🯱": "l", "I": "l", "I": "l", "Ⅰ": "l", "ℐ": "l", "ℑ": "l", "𝐈": "l", "𝐼": "l", "𝑰": "l", "𝓘": "l", "𝕀": "l", "𝕴": "l", "𝖨": "l", "𝗜": "l", "𝘐": "l", "𝙄": "l", "𝙸": "l", "Ɩ": "l", "l": "l", "ⅼ": "l", "ℓ": "l", "𝐥": "l", "𝑙": "l", "𝒍": "l", "𝓁": "l", "𝓵": "l", "𝔩": "l", "𝕝": "l", "𝖑": "l", "𝗅": "l", "𝗹": "l", "𝘭": "l", "𝙡": "l", "𝚕": "l", "ǀ": "l", "Ι": "l", "𝚰": "l", "𝛪": "l", "𝜤": "l", "𝝞": "l", "𝞘": "l", "Ⲓ": "l", "І": "l", "Ӏ": "l", "ו": "l", "ן": "l", "ا": "l", "𞸀": "l", "𞺀": "l", "ﺎ": "l", "ﺍ": "l", "ߊ": "l", "ⵏ": "l", "ᛁ": "l", "ꓲ": "l", "𖼨": "l", "𐊊": "l", "𐌉": "l", "𝈪": "L", "Ⅼ": "L", "ℒ": "L", "𝐋": "L", "𝐿": "L", "𝑳": "L", "𝓛": "L", "𝔏": "L", "𝕃": "L", "𝕷": "L", "𝖫": "L", "𝗟": "L", "𝘓": "L", "𝙇": "L", "𝙻": "L", "Ⳑ": "L", "Ꮮ": "L", "ᒪ": "L", "ꓡ": "L", "𖼖": "L", "𑢣": "L", "𑢲": "L", "𐐛": "L", "𐔦": "L", "ﴼ": "l̋", "ﴽ": "l̋", "ł": "l̸", "Ł": "L̸", "ɭ": "l̨", "Ɨ": "l̵", "ƚ": "l̵", "ɫ": "l̴", "إ": "lٕ", "ﺈ": "lٕ", "ﺇ": "lٕ", "ٳ": "lٕ", "ŀ": "l·", "Ŀ": "l·", "ᒷ": "l·", "🄂": "l,", "⒈": "l.", "ױ": "l'", "⒓": "l2.", "㏫": "l2日", "㋋": "l2月", "㍤": "l2点", "⒔": "l3.", "㏬": "l3日", "㍥": "l3点", "⒕": "l4.", "㏭": "l4日", "㍦": "l4点", "⒖": "l5.", "㏮": "l5日", "㍧": "l5点", "⒗": "l6.", "㏯": "l6日", "㍨": "l6点", "⒘": "l7.", "㏰": "l7日", "㍩": "l7点", "⒙": "l8.", "㏱": "l8日", "㍪": "l8点", "⒚": "l9.", "㏲": "l9日", "㍫": "l9点", "lj": "lj", "IJ": "lJ", "Lj": "Lj", "LJ": "LJ", "‖": "ll", "∥": "ll", "Ⅱ": "ll", "ǁ": "ll", "װ": "ll", "𐆙": "l̵l̵", "⒒": "ll.", "Ⅲ": "lll", "𐆘": "l̵l̵S̵", "㏪": "ll日", "㋊": "ll月", "㍣": "ll点", "Ю": "lO", "⒑": "lO.", "㏩": "lO日", "㋉": "lO月", "㍢": "lO点", "ʪ": "ls", "₶": "lt", "Ⅳ": "lV", "Ⅸ": "lX", "ɮ": "lȝ", "ʫ": "lz", "أ": "lٴ", "ﺄ": "lٴ", "ﺃ": "lٴ", "ٲ": "lٴ", "ٵ": "lٴ", "ﷳ": "lكبر", "ﷲ": "lللّٰo", "㏠": "l日", "㋀": "l月", "㍙": "l点", "ⳑ": "ʟ", "ꮮ": "ʟ", "𐑃": "ʟ", "M": "M", "Ⅿ": "M", "ℳ": "M", "𝐌": "M", "𝑀": "M", "𝑴": "M", "𝓜": "M", "𝔐": "M", "𝕄": "M", "𝕸": "M", "𝖬": "M", "𝗠": "M", "𝘔": "M", "𝙈": "M", "𝙼": "M", "Μ": "M", "𝚳": "M", "𝛭": "M", "𝜧": "M", "𝝡": "M", "𝞛": "M", "Ϻ": "M", "Ⲙ": "M", "М": "M", "Ꮇ": "M", "ᗰ": "M", "ᛖ": "M", "ꓟ": "M", "𐊰": "M", "𐌑": "M", "Ӎ": "M̦", "🝫": "MB", "ⷨ": "ᷟ", "𝐧": "n", "𝑛": "n", "𝒏": "n", "𝓃": "n", "𝓷": "n", "𝔫": "n", "𝕟": "n", "𝖓": "n", "𝗇": "n", "𝗻": "n", "𝘯": "n", "𝙣": "n", "𝚗": "n", "ո": "n", "ռ": "n", "N": "N", "ℕ": "N", "𝐍": "N", "𝑁": "N", "𝑵": "N", "𝒩": "N", "𝓝": "N", "𝔑": "N", "𝕹": "N", "𝖭": "N", "𝗡": "N", "𝘕": "N", "𝙉": "N", "𝙽": "N", "Ν": "N", "𝚴": "N", "𝛮": "N", "𝜨": "N", "𝝢": "N", "𝞜": "N", "Ⲛ": "N", "ꓠ": "N", "𐔓": "N", "𐆎": "N̊", "ɳ": "n̨", "ƞ": "n̩", "η": "n̩", "𝛈": "n̩", "𝜂": "n̩", "𝜼": "n̩", "𝝶": "n̩", "𝞰": "n̩", "Ɲ": "N̦", "ᵰ": "n̴", "nj": "nj", "Nj": "Nj", "NJ": "NJ", "№": "No", "ͷ": "ᴎ", "и": "ᴎ", "𐑍": "ᴎ", "ņ": "ɲ", "ం": "o", "ಂ": "o", "ം": "o", "ං": "o", "०": "o", "੦": "o", "૦": "o", "௦": "o", "౦": "o", "೦": "o", "൦": "o", "๐": "o", "໐": "o", "၀": "o", "٥": "o", "۵": "o", "o": "o", "ℴ": "o", "𝐨": "o", "𝑜": "o", "𝒐": "o", "𝓸": "o", "𝔬": "o", "𝕠": "o", "𝖔": "o", "𝗈": "o", "𝗼": "o", "𝘰": "o", "𝙤": "o", "𝚘": "o", "ᴏ": "o", "ᴑ": "o", "ꬽ": "o", "ο": "o", "𝛐": "o", "𝜊": "o", "𝝄": "o", "𝝾": "o", "𝞸": "o", "σ": "o", "𝛔": "o", "𝜎": "o", "𝝈": "o", "𝞂": "o", "𝞼": "o", "ⲟ": "o", "о": "o", "ჿ": "o", "օ": "o", "ס": "o", "ه": "o", "𞸤": "o", "𞹤": "o", "𞺄": "o", "ﻫ": "o", "ﻬ": "o", "ﻪ": "o", "ﻩ": "o", "ھ": "o", "ﮬ": "o", "ﮭ": "o", "ﮫ": "o", "ﮪ": "o", "ہ": "o", "ﮨ": "o", "ﮩ": "o", "ﮧ": "o", "ﮦ": "o", "ە": "o", "ഠ": "o", "ဝ": "o", "𐓪": "o", "𑣈": "o", "𑣗": "o", "𐐬": "o", "߀": "O", "০": "O", "୦": "O", "〇": "O", "𑓐": "O", "𑣠": "O", "𝟎": "O", "𝟘": "O", "𝟢": "O", "𝟬": "O", "𝟶": "O", "🯰": "O", "O": "O", "𝐎": "O", "𝑂": "O", "𝑶": "O", "𝒪": "O", "𝓞": "O", "𝔒": "O", "𝕆": "O", "𝕺": "O", "𝖮": "O", "𝗢": "O", "𝘖": "O", "𝙊": "O", "𝙾": "O", "Ο": "O", "𝚶": "O", "𝛰": "O", "𝜪": "O", "𝝤": "O", "𝞞": "O", "Ⲟ": "O", "О": "O", "Օ": "O", "ⵔ": "O", "ዐ": "O", "ଠ": "O", "𐓂": "O", "ꓳ": "O", "𑢵": "O", "𐊒": "O", "𐊫": "O", "𐐄": "O", "𐔖": "O", "⁰": "º", "ᵒ": "º", "ǒ": "ŏ", "Ǒ": "Ŏ", "ۿ": "ô", "Ő": "Ö", "ø": "o̸", "ꬾ": "o̸", "Ø": "O̸", "ⵁ": "O̸", "Ǿ": "Ó̸", "ɵ": "o̵", "ꝋ": "o̵", "ө": "o̵", "ѳ": "o̵", "ꮎ": "o̵", "ꮻ": "o̵", "⊖": "O̵", "⊝": "O̵", "⍬": "O̵", "𝈚": "O̵", "🜔": "O̵", "Ɵ": "O̵", "Ꝋ": "O̵", "θ": "O̵", "ϑ": "O̵", "𝛉": "O̵", "𝛝": "O̵", "𝜃": "O̵", "𝜗": "O̵", "𝜽": "O̵", "𝝑": "O̵", "𝝷": "O̵", "𝞋": "O̵", "𝞱": "O̵", "𝟅": "O̵", "Θ": "O̵", "ϴ": "O̵", "𝚯": "O̵", "𝚹": "O̵", "𝛩": "O̵", "𝛳": "O̵", "𝜣": "O̵", "𝜭": "O̵", "𝝝": "O̵", "𝝧": "O̵", "𝞗": "O̵", "𝞡": "O̵", "Ө": "O̵", "Ѳ": "O̵", "ⴱ": "O̵", "Ꮎ": "O̵", "Ꮻ": "O̵", "ꭴ": "ơ", "ﳙ": "oٰ", "🄁": "O,", "🄀": "O.", "ơ": "o'", "Ơ": "O'", "Ꭴ": "O'", "%": "º/₀", "٪": "º/₀", "⁒": "º/₀", "‰": "º/₀₀", "؉": "º/₀₀", "‱": "º/₀₀₀", "؊": "º/₀₀₀", "œ": "oe", "Œ": "OE", "ɶ": "oᴇ", "∞": "oo", "ꝏ": "oo", "ꚙ": "oo", "Ꝏ": "OO", "Ꚙ": "OO", "ﳗ": "oج", "ﱑ": "oج", "ﳘ": "oم", "ﱒ": "oم", "ﶓ": "oمج", "ﶔ": "oمم", "ﱓ": "oى", "ﱔ": "oى", "ൟ": "oരo", "တ": "oာ", "㍘": "O点", "ↄ": "ɔ", "ᴐ": "ɔ", "ͻ": "ɔ", "𐑋": "ɔ", "Ↄ": "Ɔ", "Ͻ": "Ɔ", "ꓛ": "Ɔ", "𐐣": "Ɔ", "ꬿ": "ɔ̸", "ꭢ": "ɔe", "𐐿": "ɷ", "⍴": "p", "p": "p", "𝐩": "p", "𝑝": "p", "𝒑": "p", "𝓅": "p", "𝓹": "p", "𝔭": "p", "𝕡": "p", "𝖕": "p", "𝗉": "p", "𝗽": "p", "𝘱": "p", "𝙥": "p", "𝚙": "p", "ρ": "p", "ϱ": "p", "𝛒": "p", "𝛠": "p", "𝜌": "p", "𝜚": "p", "𝝆": "p", "𝝔": "p", "𝞀": "p", "𝞎": "p", "𝞺": "p", "𝟈": "p", "ⲣ": "p", "р": "p", "P": "P", "ℙ": "P", "𝐏": "P", "𝑃": "P", "𝑷": "P", "𝒫": "P", "𝓟": "P", "𝔓": "P", "𝕻": "P", "𝖯": "P", "𝗣": "P", "𝘗": "P", "𝙋": "P", "𝙿": "P", "Ρ": "P", "𝚸": "P", "𝛲": "P", "𝜬": "P", "𝝦": "P", "𝞠": "P", "Ⲣ": "P", "Р": "P", "Ꮲ": "P", "ᑭ": "P", "ꓑ": "P", "𐊕": "P", "ƥ": "p̔", "ᵽ": "p̵", "ᑷ": "p·", "ᒆ": "P'", "ᴩ": "ᴘ", "ꮲ": "ᴘ", "φ": "ɸ", "ϕ": "ɸ", "𝛗": "ɸ", "𝛟": "ɸ", "𝜑": "ɸ", "𝜙": "ɸ", "𝝋": "ɸ", "𝝓": "ɸ", "𝞅": "ɸ", "𝞍": "ɸ", "𝞿": "ɸ", "𝟇": "ɸ", "ⲫ": "ɸ", "ф": "ɸ", "𝐪": "q", "𝑞": "q", "𝒒": "q", "𝓆": "q", "𝓺": "q", "𝔮": "q", "𝕢": "q", "𝖖": "q", "𝗊": "q", "𝗾": "q", "𝘲": "q", "𝙦": "q", "𝚚": "q", "ԛ": "q", "գ": "q", "զ": "q", "ℚ": "Q", "𝐐": "Q", "𝑄": "Q", "𝑸": "Q", "𝒬": "Q", "𝓠": "Q", "𝔔": "Q", "𝕼": "Q", "𝖰": "Q", "𝗤": "Q", "𝘘": "Q", "𝙌": "Q", "𝚀": "Q", "ⵕ": "Q", "ʠ": "q̔", "🜀": "QE", "ᶐ": "ɋ", "ᴋ": "ĸ", "κ": "ĸ", "ϰ": "ĸ", "𝛋": "ĸ", "𝛞": "ĸ", "𝜅": "ĸ", "𝜘": "ĸ", "𝜿": "ĸ", "𝝒": "ĸ", "𝝹": "ĸ", "𝞌": "ĸ", "𝞳": "ĸ", "𝟆": "ĸ", "ⲕ": "ĸ", "к": "ĸ", "ꮶ": "ĸ", "қ": "ĸ̩", "ҟ": "ĸ̵", "𝐫": "r", "𝑟": "r", "𝒓": "r", "𝓇": "r", "𝓻": "r", "𝔯": "r", "𝕣": "r", "𝖗": "r", "𝗋": "r", "𝗿": "r", "𝘳": "r", "𝙧": "r", "𝚛": "r", "ꭇ": "r", "ꭈ": "r", "ᴦ": "r", "ⲅ": "r", "г": "r", "ꮁ": "r", "𝈖": "R", "ℛ": "R", "ℜ": "R", "ℝ": "R", "𝐑": "R", "𝑅": "R", "𝑹": "R", "𝓡": "R", "𝕽": "R", "𝖱": "R", "𝗥": "R", "𝘙": "R", "𝙍": "R", "𝚁": "R", "Ʀ": "R", "Ꭱ": "R", "Ꮢ": "R", "𐒴": "R", "ᖇ": "R", "ꓣ": "R", "𖼵": "R", "ɽ": "r̨", "ɼ": "r̩", "ɍ": "r̵", "ғ": "r̵", "ᵲ": "r̴", "ґ": "r'", "𑣣": "rn", "m": "rn", "ⅿ": "rn", "𝐦": "rn", "𝑚": "rn", "𝒎": "rn", "𝓂": "rn", "𝓶": "rn", "𝔪": "rn", "𝕞": "rn", "𝖒": "rn", "𝗆": "rn", "𝗺": "rn", "𝘮": "rn", "𝙢": "rn", "𝚖": "rn", "𑜀": "rn", "₥": "rn̸", "ɱ": "rn̦", "ᵯ": "rn̴", "₨": "Rs", "ꭱ": "ʀ", "ꮢ": "ʀ", "я": "ᴙ", "ᵳ": "ɾ̴", "℩": "ɿ", "s": "s", "𝐬": "s", "𝑠": "s", "𝒔": "s", "𝓈": "s", "𝓼": "s", "𝔰": "s", "𝕤": "s", "𝖘": "s", "𝗌": "s", "𝘀": "s", "𝘴": "s", "𝙨": "s", "𝚜": "s", "ꜱ": "s", "ƽ": "s", "ѕ": "s", "ꮪ": "s", "𑣁": "s", "𐑈": "s", "S": "S", "𝐒": "S", "𝑆": "S", "𝑺": "S", "𝒮": "S", "𝓢": "S", "𝔖": "S", "𝕊": "S", "𝕾": "S", "𝖲": "S", "𝗦": "S", "𝘚": "S", "𝙎": "S", "𝚂": "S", "Ѕ": "S", "Տ": "S", "Ꮥ": "S", "Ꮪ": "S", "ꓢ": "S", "𖼺": "S", "𐊖": "S", "𐐠": "S", "ʂ": "s̨", "ᵴ": "s̴", "ꞵ": "ß", "β": "ß", "ϐ": "ß", "𝛃": "ß", "𝛽": "ß", "𝜷": "ß", "𝝱": "ß", "𝞫": "ß", "Ᏸ": "ß", "🝜": "sss", "st": "st", "∫": "ʃ", "ꭍ": "ʃ", "∑": "Ʃ", "⅀": "Ʃ", "Σ": "Ʃ", "𝚺": "Ʃ", "𝛴": "Ʃ", "𝜮": "Ʃ", "𝝨": "Ʃ", "𝞢": "Ʃ", "ⵉ": "Ʃ", "∬": "ʃʃ", "∭": "ʃʃʃ", "⨌": "ʃʃʃʃ", "𝐭": "t", "𝑡": "t", "𝒕": "t", "𝓉": "t", "𝓽": "t", "𝔱": "t", "𝕥": "t", "𝖙": "t", "𝗍": "t", "𝘁": "t", "𝘵": "t", "𝙩": "t", "𝚝": "t", "⊤": "T", "⟙": "T", "🝨": "T", "T": "T", "𝐓": "T", "𝑇": "T", "𝑻": "T", "𝒯": "T", "𝓣": "T", "𝔗": "T", "𝕋": "T", "𝕿": "T", "𝖳": "T", "𝗧": "T", "𝘛": "T", "𝙏": "T", "𝚃": "T", "Τ": "T", "𝚻": "T", "𝛵": "T", "𝜯": "T", "𝝩": "T", "𝞣": "T", "Ⲧ": "T", "Т": "T", "Ꭲ": "T", "ꓔ": "T", "𖼊": "T", "𑢼": "T", "𐊗": "T", "𐊱": "T", "𐌕": "T", "ƭ": "t̔", "⍡": "T̈", "Ⱦ": "T̸", "Ț": "Ţ", "Ʈ": "T̨", "Ҭ": "T̩", "₮": "T⃫", "ŧ": "t̵", "Ŧ": "T̵", "ᵵ": "t̴", "Ⴀ": "Ꞇ", "Ꜩ": "T3", "ʨ": "tɕ", "℡": "TEL", "ꝷ": "tf", "ʦ": "ts", "ʧ": "tʃ", "ꜩ": "tȝ", "τ": "ᴛ", "𝛕": "ᴛ", "𝜏": "ᴛ", "𝝉": "ᴛ", "𝞃": "ᴛ", "𝞽": "ᴛ", "т": "ᴛ", "ꭲ": "ᴛ", "ҭ": "ᴛ̩", "ţ": "ƫ", "ț": "ƫ", "Ꮏ": "ƫ", "𝐮": "u", "𝑢": "u", "𝒖": "u", "𝓊": "u", "𝓾": "u", "𝔲": "u", "𝕦": "u", "𝖚": "u", "𝗎": "u", "𝘂": "u", "𝘶": "u", "𝙪": "u", "𝚞": "u", "ꞟ": "u", "ᴜ": "u", "ꭎ": "u", "ꭒ": "u", "ʋ": "u", "υ": "u", "𝛖": "u", "𝜐": "u", "𝝊": "u", "𝞄": "u", "𝞾": "u", "ս": "u", "𐓶": "u", "𑣘": "u", "∪": "U", "⋃": "U", "𝐔": "U", "𝑈": "U", "𝑼": "U", "𝒰": "U", "𝓤": "U", "𝔘": "U", "𝕌": "U", "𝖀": "U", "𝖴": "U", "𝗨": "U", "𝘜": "U", "𝙐": "U", "𝚄": "U", "Ս": "U", "ሀ": "U", "𐓎": "U", "ᑌ": "U", "ꓴ": "U", "𖽂": "U", "𑢸": "U", "ǔ": "ŭ", "Ǔ": "Ŭ", "ᵾ": "u̵", "ꮜ": "u̵", "Ʉ": "U̵", "Ꮜ": "U̵", "ᑘ": "U·", "ᑧ": "U'", "ᵫ": "ue", "ꭣ": "uo", "ṃ": "ꭑ", "պ": "ɰ", "ሣ": "ɰ", "℧": "Ʊ", "ᘮ": "Ʊ", "ᘴ": "Ʊ", "ᵿ": "ʊ̵", "∨": "v", "⋁": "v", "v": "v", "ⅴ": "v", "𝐯": "v", "𝑣": "v", "𝒗": "v", "𝓋": "v", "𝓿": "v", "𝔳": "v", "𝕧": "v", "𝖛": "v", "𝗏": "v", "𝘃": "v", "𝘷": "v", "𝙫": "v", "𝚟": "v", "ᴠ": "v", "ν": "v", "𝛎": "v", "𝜈": "v", "𝝂": "v", "𝝼": "v", "𝞶": "v", "ѵ": "v", "ט": "v", "𑜆": "v", "ꮩ": "v", "𑣀": "v", "𝈍": "V", "٧": "V", "۷": "V", "Ⅴ": "V", "𝐕": "V", "𝑉": "V", "𝑽": "V", "𝒱": "V", "𝓥": "V", "𝔙": "V", "𝕍": "V", "𝖁": "V", "𝖵": "V", "𝗩": "V", "𝘝": "V", "𝙑": "V", "𝚅": "V", "Ѵ": "V", "ⴸ": "V", "Ꮩ": "V", "ᐯ": "V", "ꛟ": "V", "ꓦ": "V", "𖼈": "V", "𑢠": "V", "𐔝": "V", "𐆗": "V̵", "ᐻ": "V·", "🝬": "VB", "ⅵ": "vi", "ⅶ": "vii", "ⅷ": "viii", "Ⅵ": "Vl", "Ⅶ": "Vll", "Ⅷ": "Vlll", "🜈": "Vᷤ", "ᴧ": "ʌ", "𐓘": "ʌ", "٨": "Ʌ", "۸": "Ʌ", "Λ": "Ʌ", "𝚲": "Ʌ", "𝛬": "Ʌ", "𝜦": "Ʌ", "𝝠": "Ʌ", "𝞚": "Ʌ", "Л": "Ʌ", "ⴷ": "Ʌ", "𐒰": "Ʌ", "ᐱ": "Ʌ", "ꛎ": "Ʌ", "ꓥ": "Ʌ", "𖼽": "Ʌ", "𐊍": "Ʌ", "Ӆ": "Ʌ̦", "ᐽ": "Ʌ·", "ɯ": "w", "𝐰": "w", "𝑤": "w", "𝒘": "w", "𝓌": "w", "𝔀": "w", "𝔴": "w", "𝕨": "w", "𝖜": "w", "𝗐": "w", "𝘄": "w", "𝘸": "w", "𝙬": "w", "𝚠": "w", "ᴡ": "w", "ѡ": "w", "ԝ": "w", "ա": "w", "𑜊": "w", "𑜎": "w", "𑜏": "w", "ꮃ": "w", "𑣯": "W", "𑣦": "W", "𝐖": "W", "𝑊": "W", "𝑾": "W", "𝒲": "W", "𝓦": "W", "𝔚": "W", "𝕎": "W", "𝖂": "W", "𝖶": "W", "𝗪": "W", "𝘞": "W", "𝙒": "W", "𝚆": "W", "Ԝ": "W", "Ꮃ": "W", "Ꮤ": "W", "ꓪ": "W", "ѽ": "w҆҇", "𑓅": "ẇ", "₩": "W̵", "ꝡ": "w̦", "ᴍ": "ʍ", "м": "ʍ", "ꮇ": "ʍ", "ӎ": "ʍ̦", "᙮": "x", "×": "x", "⤫": "x", "⤬": "x", "⨯": "x", "x": "x", "ⅹ": "x", "𝐱": "x", "𝑥": "x", "𝒙": "x", "𝓍": "x", "𝔁": "x", "𝔵": "x", "𝕩": "x", "𝖝": "x", "𝗑": "x", "𝘅": "x", "𝘹": "x", "𝙭": "x", "𝚡": "x", "х": "x", "ᕁ": "x", "ᕽ": "x", "ⷯ": "ͯ", "᙭": "X", "╳": "X", "𐌢": "X", "𑣬": "X", "X": "X", "Ⅹ": "X", "𝐗": "X", "𝑋": "X", "𝑿": "X", "𝒳": "X", "𝓧": "X", "𝔛": "X", "𝕏": "X", "𝖃": "X", "𝖷": "X", "𝗫": "X", "𝘟": "X", "𝙓": "X", "𝚇": "X", "Ꭓ": "X", "Χ": "X", "𝚾": "X", "𝛸": "X", "𝜲": "X", "𝝬": "X", "𝞦": "X", "Ⲭ": "X", "Х": "X", "ⵝ": "X", "ᚷ": "X", "ꓫ": "X", "𐊐": "X", "𐊴": "X", "𐌗": "X", "𐔧": "X", "⨰": "ẋ", "Ҳ": "X̩", "𐆖": "X̵", "ⅺ": "xi", "ⅻ": "xii", "Ⅺ": "Xl", "Ⅻ": "Xll", "ɣ": "y", "ᶌ": "y", "y": "y", "𝐲": "y", "𝑦": "y", "𝒚": "y", "𝓎": "y", "𝔂": "y", "𝔶": "y", "𝕪": "y", "𝖞": "y", "𝗒": "y", "𝘆": "y", "𝘺": "y", "𝙮": "y", "𝚢": "y", "ʏ": "y", "ỿ": "y", "ꭚ": "y", "γ": "y", "ℽ": "y", "𝛄": "y", "𝛾": "y", "𝜸": "y", "𝝲": "y", "𝞬": "y", "у": "y", "ү": "y", "ყ": "y", "𑣜": "y", "Y": "Y", "𝐘": "Y", "𝑌": "Y", "𝒀": "Y", "𝒴": "Y", "𝓨": "Y", "𝔜": "Y", "𝕐": "Y", "𝖄": "Y", "𝖸": "Y", "𝗬": "Y", "𝘠": "Y", "𝙔": "Y", "𝚈": "Y", "Υ": "Y", "ϒ": "Y", "𝚼": "Y", "𝛶": "Y", "𝜰": "Y", "𝝪": "Y", "𝞤": "Y", "Ⲩ": "Y", "У": "Y", "Ү": "Y", "Ꭹ": "Y", "Ꮍ": "Y", "ꓬ": "Y", "𖽃": "Y", "𑢤": "Y", "𐊲": "Y", "ƴ": "y̔", "ɏ": "y̵", "ұ": "y̵", "¥": "Y̵", "Ɏ": "Y̵", "Ұ": "Y̵", "ʒ": "ȝ", "ꝫ": "ȝ", "ⳍ": "ȝ", "ӡ": "ȝ", "ჳ": "ȝ", "𝐳": "z", "𝑧": "z", "𝒛": "z", "𝓏": "z", "𝔃": "z", "𝔷": "z", "𝕫": "z", "𝖟": "z", "𝗓": "z", "𝘇": "z", "𝘻": "z", "𝙯": "z", "𝚣": "z", "ᴢ": "z", "ꮓ": "z", "𑣄": "z", "𐋵": "Z", "𑣥": "Z", "Z": "Z", "ℤ": "Z", "ℨ": "Z", "𝐙": "Z", "𝑍": "Z", "𝒁": "Z", "𝒵": "Z", "𝓩": "Z", "𝖅": "Z", "𝖹": "Z", "𝗭": "Z", "𝘡": "Z", "𝙕": "Z", "𝚉": "Z", "Ζ": "Z", "𝚭": "Z", "𝛧": "Z", "𝜡": "Z", "𝝛": "Z", "𝞕": "Z", "Ꮓ": "Z", "ꓜ": "Z", "𑢩": "Z", "ʐ": "z̨", "ƶ": "z̵", "Ƶ": "Z̵", "ȥ": "z̦", "Ȥ": "Z̦", "ᵶ": "z̴", "ƿ": "þ", "ϸ": "þ", "Ϸ": "Þ", "𐓄": "Þ", "⁹": "ꝰ", "ᴤ": "ƨ", "ϩ": "ƨ", "ꙅ": "ƨ", "ь": "ƅ", "ꮟ": "ƅ", "ы": "ƅi", "ꭾ": "ɂ", "ˤ": "ˁ", "ꛍ": "ʡ", "⊙": "ʘ", "☉": "ʘ", "⨀": "ʘ", "Ꙩ": "ʘ", "ⵙ": "ʘ", "𐓃": "ʘ", "ℾ": "Γ", "𝚪": "Γ", "𝛤": "Γ", "𝜞": "Γ", "𝝘": "Γ", "𝞒": "Γ", "Ⲅ": "Γ", "Г": "Γ", "Ꮁ": "Γ", "ᒥ": "Γ", "𖼇": "Γ", "Ғ": "Γ̵", "ᒯ": "Γ·", "Ґ": "Γ'", "∆": "Δ", "△": "Δ", "🜂": "Δ", "𝚫": "Δ", "𝛥": "Δ", "𝜟": "Δ", "𝝙": "Δ", "𝞓": "Δ", "Ⲇ": "Δ", "ⵠ": "Δ", "ᐃ": "Δ", "𖼚": "Δ", "𐊅": "Δ", "𐊣": "Δ", "⍙": "Δ̲", "ᐏ": "Δ·", "ᐬ": "Δᐠ", "𝟋": "ϝ", "𝛇": "ζ", "𝜁": "ζ", "𝜻": "ζ", "𝝵": "ζ", "𝞯": "ζ", "ⳤ": "ϗ", "𝛌": "λ", "𝜆": "λ", "𝝀": "λ", "𝝺": "λ", "𝞴": "λ", "Ⲗ": "λ", "𐓛": "λ", "µ": "μ", "𝛍": "μ", "𝜇": "μ", "𝝁": "μ", "𝝻": "μ", "𝞵": "μ", "𝛏": "ξ", "𝜉": "ξ", "𝝃": "ξ", "𝝽": "ξ", "𝞷": "ξ", "𝚵": "Ξ", "𝛯": "Ξ", "𝜩": "Ξ", "𝝣": "Ξ", "𝞝": "Ξ", "ϖ": "π", "ℼ": "π", "𝛑": "π", "𝛡": "π", "𝜋": "π", "𝜛": "π", "𝝅": "π", "𝝕": "π", "𝝿": "π", "𝞏": "π", "𝞹": "π", "𝟉": "π", "ᴨ": "π", "п": "π", "∏": "Π", "ℿ": "Π", "𝚷": "Π", "𝛱": "Π", "𝜫": "Π", "𝝥": "Π", "𝞟": "Π", "Ⲡ": "Π", "П": "Π", "ꛛ": "Π", "𐊭": "Ϙ", "𐌒": "Ϙ", "ϛ": "ς", "𝛓": "ς", "𝜍": "ς", "𝝇": "ς", "𝞁": "ς", "𝞻": "ς", "𝚽": "Φ", "𝛷": "Φ", "𝜱": "Φ", "𝝫": "Φ", "𝞥": "Φ", "Ⲫ": "Φ", "Ф": "Φ", "Փ": "Φ", "ቀ": "Φ", "ᛰ": "Φ", "𐊳": "Φ", "ꭓ": "χ", "ꭕ": "χ", "𝛘": "χ", "𝜒": "χ", "𝝌": "χ", "𝞆": "χ", "𝟀": "χ", "ⲭ": "χ", "𝛙": "ψ", "𝜓": "ψ", "𝝍": "ψ", "𝞇": "ψ", "𝟁": "ψ", "ѱ": "ψ", "𐓹": "ψ", "𝚿": "Ψ", "𝛹": "Ψ", "𝜳": "Ψ", "𝝭": "Ψ", "𝞧": "Ψ", "Ⲯ": "Ψ", "Ѱ": "Ψ", "𐓑": "Ψ", "ᛘ": "Ψ", "𐊵": "Ψ", "⍵": "ω", "ꞷ": "ω", "𝛚": "ω", "𝜔": "ω", "𝝎": "ω", "𝞈": "ω", "𝟂": "ω", "ⲱ": "ω", "ꙍ": "ω", "Ω": "Ω", "𝛀": "Ω", "𝛺": "Ω", "𝜴": "Ω", "𝝮": "Ω", "𝞨": "Ω", "ᘯ": "Ω", "ᘵ": "Ω", "𐊶": "Ω", "⍹": "ω̲", "ώ": "ῴ", "☰": "Ⲷ", "Ⳝ": "Ϭ", "җ": "ж̩", "Җ": "Ж̩", "𝈋": "И", "Ͷ": "И", "ꚡ": "И", "𐐥": "И", "Й": "Ѝ", "Ҋ": "Ѝ̦", "ѝ": "й", "ҋ": "й̦", "𐒼": "Ӄ", "ᴫ": "л", "ӆ": "л̦", "ꭠ": "љ", "𐓫": "ꙩ", "ᷮ": "ⷬ", "𐓍": "Ћ", "𝈂": "Ӿ", "𝈢": "Ѡ", "Ꮗ": "Ѡ", "ᗯ": "Ѡ", "Ѽ": "Ѡ҆҇", "ᣭ": "Ѡ·", "Ꞷ": "Ꙍ", "ӌ": "ҷ", "Ӌ": "Ҷ", "Ҿ": "Ҽ̨", "ⲽ": "ш", "Ⲽ": "Ш", "Ꙑ": "Ъl", "℈": "Э", "🜁": "Ꙙ", "𖼜": "Ꙙ", "ꦒ": "ⰿ", "և": "եւ", "ኔ": "ձ", "ﬔ": "մե", "ﬕ": "մի", "ﬗ": "մխ", "ﬓ": "մն", "∩": "Ո", "⋂": "Ո", "𝉅": "Ո", "በ": "Ո", "ᑎ": "Ո", "ꓵ": "Ո", "ᑚ": "Ո·", "ᑨ": "Ո'", "ﬖ": "վն", "₽": "Ք", "˓": "ՙ", "ʿ": "ՙ", "ℵ": "א", "ﬡ": "א", "אָ": "אַ", "אּ": "אַ", "ﭏ": "אל", "ℶ": "ב", "ℷ": "ג", "ℸ": "ד", "ﬢ": "ד", "ﬣ": "ה", "יּ": "יִ", "ﬤ": "כ", "ﬥ": "ל", "ﬦ": "ם", "ﬠ": "ע", "ﬧ": "ר", "שׂ": "שׁ", "שּ": "שׁ", "שּׂ": "שּׁ", "ﬨ": "ת", "ﺀ": "ء", "۽": "ء͈", "ﺂ": "آ", "ﺁ": "آ", "ﭑ": "ٱ", "ﭐ": "ٱ", "𞸁": "ب", "𞸡": "ب", "𞹡": "ب", "𞺁": "ب", "𞺡": "ب", "ﺑ": "ب", "ﺒ": "ب", "ﺐ": "ب", "ﺏ": "ب", "ݑ": "بۛ", "ࢶ": "بۢ", "ࢡ": "بٔ", "ﲠ": "بo", "ﳢ": "بo", "ﲜ": "بج", "ﰅ": "بج", "ﲝ": "بح", "ﰆ": "بح", "ﷂ": "بحى", "ﲞ": "بخ", "ﰇ": "بخ", "ﳒ": "بخ", "ﱋ": "بخ", "ﶞ": "بخى", "ﱪ": "بر", "ﱫ": "بز", "ﲟ": "بم", "ﳡ": "بم", "ﱬ": "بم", "ﰈ": "بم", "ﱭ": "بن", "ﱮ": "بى", "ﰉ": "بى", "ﱯ": "بى", "ﰊ": "بى", "ﭔ": "ٻ", "ﭕ": "ٻ", "ﭓ": "ٻ", "ﭒ": "ٻ", "ې": "ٻ", "ﯦ": "ٻ", "ﯧ": "ٻ", "ﯥ": "ٻ", "ﯤ": "ٻ", "ﭜ": "ڀ", "ﭝ": "ڀ", "ﭛ": "ڀ", "ﭚ": "ڀ", "ࢩ": "ݔ", "ݧ": "ݔ", "⍥": "ة", "ö": "ة", "ﺔ": "ة", "ﺓ": "ة", "ۃ": "ة", "𞸕": "ت", "𞸵": "ت", "𞹵": "ت", "𞺕": "ت", "𞺵": "ت", "ﺗ": "ت", "ﺘ": "ت", "ﺖ": "ت", "ﺕ": "ت", "ﲥ": "تo", "ﳤ": "تo", "ﲡ": "تج", "ﰋ": "تج", "ﵐ": "تجم", "ﶠ": "تجى", "ﶟ": "تجى", "ﲢ": "تح", "ﰌ": "تح", "ﵒ": "تحج", "ﵑ": "تحج", "ﵓ": "تحم", "ﲣ": "تخ", "ﰍ": "تخ", "ﵔ": "تخم", "ﶢ": "تخى", "ﶡ": "تخى", "ﱰ": "تر", "ﱱ": "تز", "ﲤ": "تم", "ﳣ": "تم", "ﱲ": "تم", "ﰎ": "تم", "ﵕ": "تمج", "ﵖ": "تمح", "ﵗ": "تمخ", "ﶤ": "تمى", "ﶣ": "تمى", "ﱳ": "تن", "ﱴ": "تى", "ﰏ": "تى", "ﱵ": "تى", "ﰐ": "تى", "ﭠ": "ٺ", "ﭡ": "ٺ", "ﭟ": "ٺ", "ﭞ": "ٺ", "ﭤ": "ٿ", "ﭥ": "ٿ", "ﭣ": "ٿ", "ﭢ": "ٿ", "𞸂": "ج", "𞸢": "ج", "𞹂": "ج", "𞹢": "ج", "𞺂": "ج", "𞺢": "ج", "ﺟ": "ج", "ﺠ": "ج", "ﺞ": "ج", "ﺝ": "ج", "ﲧ": "جح", "ﰕ": "جح", "ﶦ": "جحى", "ﶾ": "جحى", "ﷻ": "جل جلlلo", "ﲨ": "جم", "ﰖ": "جم", "ﵙ": "جمح", "ﵘ": "جمح", "ﶧ": "جمى", "ﶥ": "جمى", "ﴝ": "جى", "ﴁ": "جى", "ﴞ": "جى", "ﴂ": "جى", "ﭸ": "ڃ", "ﭹ": "ڃ", "ﭷ": "ڃ", "ﭶ": "ڃ", "ﭴ": "ڄ", "ﭵ": "ڄ", "ﭳ": "ڄ", "ﭲ": "ڄ", "ﭼ": "چ", "ﭽ": "چ", "ﭻ": "چ", "ﭺ": "چ", "ﮀ": "ڇ", "ﮁ": "ڇ", "ﭿ": "ڇ", "ﭾ": "ڇ", "𞸇": "ح", "𞸧": "ح", "𞹇": "ح", "𞹧": "ح", "𞺇": "ح", "𞺧": "ح", "ﺣ": "ح", "ﺤ": "ح", "ﺢ": "ح", "ﺡ": "ح", "څ": "حۛ", "ځ": "حٔ", "ݲ": "حٔ", "ﲩ": "حج", "ﰗ": "حج", "ﶿ": "حجى", "ﲪ": "حم", "ﰘ": "حم", "ﵛ": "حمى", "ﵚ": "حمى", "ﴛ": "حى", "ﳿ": "حى", "ﴜ": "حى", "ﴀ": "حى", "𞸗": "خ", "𞸷": "خ", "𞹗": "خ", "𞹷": "خ", "𞺗": "خ", "𞺷": "خ", "ﺧ": "خ", "ﺨ": "خ", "ﺦ": "خ", "ﺥ": "خ", "ﲫ": "خج", "ﰙ": "خج", "ﰚ": "خح", "ﲬ": "خم", "ﰛ": "خم", "ﴟ": "خى", "ﴃ": "خى", "ﴠ": "خى", "ﴄ": "خى", "𐋡": "د", "𞸃": "د", "𞺃": "د", "𞺣": "د", "ﺪ": "د", "ﺩ": "د", "ڈ": "دؕ", "ﮉ": "دؕ", "ﮈ": "دؕ", "ڎ": "دۛ", "ﮇ": "دۛ", "ﮆ": "دۛ", "ۮ": "د̂", "ࢮ": "د̤̣", "𞸘": "ذ", "𞺘": "ذ", "𞺸": "ذ", "ﺬ": "ذ", "ﺫ": "ذ", "ﱛ": "ذٰ", "ڋ": "ڊؕ", "ﮅ": "ڌ", "ﮄ": "ڌ", "ﮃ": "ڍ", "ﮂ": "ڍ", "𞸓": "ر", "𞺓": "ر", "𞺳": "ر", "ﺮ": "ر", "ﺭ": "ر", "ڑ": "رؕ", "ﮍ": "رؕ", "ﮌ": "رؕ", "ژ": "رۛ", "ﮋ": "رۛ", "ﮊ": "رۛ", "ڒ": "ر̆", "ࢹ": "ر̆̇", "ۯ": "ر̂", "ݬ": "رٔ", "ﱜ": "رٰ", "ﷶ": "رسول", "﷼": "رىlل", "𞸆": "ز", "𞺆": "ز", "𞺦": "ز", "ﺰ": "ز", "ﺯ": "ز", "ࢲ": "ز̂", "ݱ": "ڗؕ", "𞸎": "س", "𞸮": "س", "𞹎": "س", "𞹮": "س", "𞺎": "س", "𞺮": "س", "ﺳ": "س", "ﺴ": "س", "ﺲ": "س", "ﺱ": "س", "ش": "سۛ", "𞸔": "سۛ", "𞸴": "سۛ", "𞹔": "سۛ", "𞹴": "سۛ", "𞺔": "سۛ", "𞺴": "سۛ", "ﺷ": "سۛ", "ﺸ": "سۛ", "ﺶ": "سۛ", "ﺵ": "سۛ", "ݾ": "س̂", "ﴱ": "سo", "ﳨ": "سo", "ﴲ": "سۛo", "ﳪ": "سۛo", "ﲭ": "سج", "ﴴ": "سج", "ﰜ": "سج", "ﴭ": "سۛج", "ﴷ": "سۛج", "ﴥ": "سۛج", "ﴉ": "سۛج", "ﵝ": "سجح", "ﵞ": "سجى", "ﵩ": "سۛجى", "ﲮ": "سح", "ﴵ": "سح", "ﰝ": "سح", "ﴮ": "سۛح", "ﴸ": "سۛح", "ﴦ": "سۛح", "ﴊ": "سۛح", "ﵜ": "سحج", "ﵨ": "سۛحم", "ﵧ": "سۛحم", "ﶪ": "سۛحى", "ﲯ": "سخ", "ﴶ": "سخ", "ﰞ": "سخ", "ﴯ": "سۛخ", "ﴹ": "سۛخ", "ﴧ": "سۛخ", "ﴋ": "سۛخ", "ﶨ": "سخى", "ﷆ": "سخى", "ﴪ": "سر", "ﴎ": "سر", "ﴩ": "سۛر", "ﴍ": "سۛر", "ﲰ": "سم", "ﳧ": "سم", "ﰟ": "سم", "ﴰ": "سۛم", "ﳩ": "سۛم", "ﴨ": "سۛم", "ﴌ": "سۛم", "ﵡ": "سمج", "ﵠ": "سمح", "ﵟ": "سمح", "ﵫ": "سۛمخ", "ﵪ": "سۛمخ", "ﵣ": "سمم", "ﵢ": "سمم", "ﵭ": "سۛمم", "ﵬ": "سۛمم", "ﴗ": "سى", "ﳻ": "سى", "ﴘ": "سى", "ﳼ": "سى", "ﴙ": "سۛى", "ﳽ": "سۛى", "ﴚ": "سۛى", "ﳾ": "سۛى", "𐋲": "ص", "𞸑": "ص", "𞸱": "ص", "𞹑": "ص", "𞹱": "ص", "𞺑": "ص", "𞺱": "ص", "ﺻ": "ص", "ﺼ": "ص", "ﺺ": "ص", "ﺹ": "ص", "ڞ": "صۛ", "ࢯ": "ص̤̣", "ﲱ": "صح", "ﰠ": "صح", "ﵥ": "صحح", "ﵤ": "صحح", "ﶩ": "صحى", "ﲲ": "صخ", "ﴫ": "صر", "ﴏ": "صر", "ﷵ": "صلعم", "ﷹ": "صلى", "ﷰ": "صلى", "ﷺ": "صلى lللo علىo وسلم", "ﲳ": "صم", "ﰡ": "صم", "ﷅ": "صمم", "ﵦ": "صمم", "ﴡ": "صى", "ﴅ": "صى", "ﴢ": "صى", "ﴆ": "صى", "𞸙": "ض", "𞸹": "ض", "𞹙": "ض", "𞹹": "ض", "𞺙": "ض", "𞺹": "ض", "ﺿ": "ض", "ﻀ": "ض", "ﺾ": "ض", "ﺽ": "ض", "ﲴ": "ضج", "ﰢ": "ضج", "ﲵ": "ضح", "ﰣ": "ضح", "ﵮ": "ضحى", "ﶫ": "ضحى", "ﲶ": "ضخ", "ﰤ": "ضخ", "ﵰ": "ضخم", "ﵯ": "ضخم", "ﴬ": "ضر", "ﴐ": "ضر", "ﲷ": "ضم", "ﰥ": "ضم", "ﴣ": "ضى", "ﴇ": "ضى", "ﴤ": "ضى", "ﴈ": "ضى", "𐋨": "ط", "𞸈": "ط", "𞹨": "ط", "𞺈": "ط", "𞺨": "ط", "ﻃ": "ط", "ﻄ": "ط", "ﻂ": "ط", "ﻁ": "ط", "ڟ": "طۛ", "ﲸ": "طح", "ﰦ": "طح", "ﴳ": "طم", "ﴺ": "طم", "ﰧ": "طم", "ﵲ": "طمح", "ﵱ": "طمح", "ﵳ": "طمم", "ﵴ": "طمى", "ﴑ": "طى", "ﳵ": "طى", "ﴒ": "طى", "ﳶ": "طى", "𞸚": "ظ", "𞹺": "ظ", "𞺚": "ظ", "𞺺": "ظ", "ﻇ": "ظ", "ﻈ": "ظ", "ﻆ": "ظ", "ﻅ": "ظ", "ﲹ": "ظم", "ﴻ": "ظم", "ﰨ": "ظم", "؏": "ع", "𞸏": "ع", "𞸯": "ع", "𞹏": "ع", "𞹯": "ع", "𞺏": "ع", "𞺯": "ع", "ﻋ": "ع", "ﻌ": "ع", "ﻊ": "ع", "ﻉ": "ع", "ﲺ": "عج", "ﰩ": "عج", "ﷄ": "عجم", "ﵵ": "عجم", "ﷷ": "علىo", "ﲻ": "عم", "ﰪ": "عم", "ﵷ": "عمم", "ﵶ": "عمم", "ﵸ": "عمى", "ﶶ": "عمى", "ﴓ": "عى", "ﳷ": "عى", "ﴔ": "عى", "ﳸ": "عى", "𞸛": "غ", "𞸻": "غ", "𞹛": "غ", "𞹻": "غ", "𞺛": "غ", "𞺻": "غ", "ﻏ": "غ", "ﻐ": "غ", "ﻎ": "غ", "ﻍ": "غ", "ﲼ": "غج", "ﰫ": "غج", "ﲽ": "غم", "ﰬ": "غم", "ﵹ": "غمم", "ﵻ": "غمى", "ﵺ": "غمى", "ﴕ": "غى", "ﳹ": "غى", "ﴖ": "غى", "ﳺ": "غى", "𞸐": "ف", "𞸰": "ف", "𞹰": "ف", "𞺐": "ف", "𞺰": "ف", "ﻓ": "ف", "ﻔ": "ف", "ﻒ": "ف", "ﻑ": "ف", "ڧ": "ف", "ﲾ": "فج", "ﰭ": "فج", "ﲿ": "فح", "ﰮ": "فح", "ﳀ": "فخ", "ﰯ": "فخ", "ﵽ": "فخم", "ﵼ": "فخم", "ﳁ": "فم", "ﰰ": "فم", "ﷁ": "فمى", "ﱼ": "فى", "ﰱ": "فى", "ﱽ": "فى", "ﰲ": "فى", "𞸞": "ڡ", "𞹾": "ڡ", "ࢻ": "ڡ", "ٯ": "ڡ", "𞸟": "ڡ", "𞹟": "ڡ", "ࢼ": "ڡ", "ڤ": "ڡۛ", "ﭬ": "ڡۛ", "ﭭ": "ڡۛ", "ﭫ": "ڡۛ", "ﭪ": "ڡۛ", "ڨ": "ڡۛ", "ࢤ": "ڢۛ", "ﭰ": "ڦ", "ﭱ": "ڦ", "ﭯ": "ڦ", "ﭮ": "ڦ", "𞸒": "ق", "𞸲": "ق", "𞹒": "ق", "𞹲": "ق", "𞺒": "ق", "𞺲": "ق", "ﻗ": "ق", "ﻘ": "ق", "ﻖ": "ق", "ﻕ": "ق", "ﳂ": "قح", "ﰳ": "قح", "ﷱ": "قلى", "ﳃ": "قم", "ﰴ": "قم", "ﶴ": "قمح", "ﵾ": "قمح", "ﵿ": "قمم", "ﶲ": "قمى", "ﱾ": "قى", "ﰵ": "قى", "ﱿ": "قى", "ﰶ": "قى", "𞸊": "ك", "𞸪": "ك", "𞹪": "ك", "ﻛ": "ك", "ﻜ": "ك", "ﻚ": "ك", "ﻙ": "ك", "ک": "ك", "ﮐ": "ك", "ﮑ": "ك", "ﮏ": "ك", "ﮎ": "ك", "ڪ": "ك", "ڭ": "كۛ", "ﯕ": "كۛ", "ﯖ": "كۛ", "ﯔ": "كۛ", "ﯓ": "كۛ", "ݣ": "كۛ", "ﲀ": "كl", "ﰷ": "كl", "ﳄ": "كج", "ﰸ": "كج", "ﳅ": "كح", "ﰹ": "كح", "ﳆ": "كخ", "ﰺ": "كخ", "ﳇ": "كل", "ﳫ": "كل", "ﲁ": "كل", "ﰻ": "كل", "ﳈ": "كم", "ﳬ": "كم", "ﲂ": "كم", "ﰼ": "كم", "ﷃ": "كمم", "ﶻ": "كمم", "ﶷ": "كمى", "ﲃ": "كى", "ﰽ": "كى", "ﲄ": "كى", "ﰾ": "كى", "ݢ": "ڬ", "ﮔ": "گ", "ﮕ": "گ", "ﮓ": "گ", "ﮒ": "گ", "ࢰ": "گ", "ڴ": "گۛ", "ﮜ": "ڱ", "ﮝ": "ڱ", "ﮛ": "ڱ", "ﮚ": "ڱ", "ﮘ": "ڳ", "ﮙ": "ڳ", "ﮗ": "ڳ", "ﮖ": "ڳ", "𞸋": "ل", "𞸫": "ل", "𞹋": "ل", "𞺋": "ل", "𞺫": "ل", "ﻟ": "ل", "ﻠ": "ل", "ﻞ": "ل", "ﻝ": "ل", "ڷ": "لۛ", "ڵ": "ل̆", "ﻼ": "لl", "ﻻ": "لl", "ﻺ": "لlٕ", "ﻹ": "لlٕ", "ﻸ": "لlٴ", "ﻷ": "لlٴ", "ﳍ": "لo", "ﻶ": "لآ", "ﻵ": "لآ", "ﳉ": "لج", "ﰿ": "لج", "ﶃ": "لجج", "ﶄ": "لجج", "ﶺ": "لجم", "ﶼ": "لجم", "ﶬ": "لجى", "ﳊ": "لح", "ﱀ": "لح", "ﶵ": "لحم", "ﶀ": "لحم", "ﶂ": "لحى", "ﶁ": "لحى", "ﳋ": "لخ", "ﱁ": "لخ", "ﶆ": "لخم", "ﶅ": "لخم", "ﳌ": "لم", "ﳭ": "لم", "ﲅ": "لم", "ﱂ": "لم", "ﶈ": "لمح", "ﶇ": "لمح", "ﶭ": "لمى", "ﲆ": "لى", "ﱃ": "لى", "ﲇ": "لى", "ﱄ": "لى", "𞸌": "م", "𞸬": "م", "𞹬": "م", "𞺌": "م", "𞺬": "م", "ﻣ": "م", "ﻤ": "م", "ﻢ": "م", "ﻡ": "م", "ࢧ": "مۛ", "۾": "م͈", "ﲈ": "مl", "ﳎ": "مج", "ﱅ": "مج", "ﶌ": "مجح", "ﶒ": "مجخ", "ﶍ": "مجم", "ﷀ": "مجى", "ﳏ": "مح", "ﱆ": "مح", "ﶉ": "محج", "ﶊ": "محم", "ﷴ": "محمد", "ﶋ": "محى", "ﳐ": "مخ", "ﱇ": "مخ", "ﶎ": "مخج", "ﶏ": "مخم", "ﶹ": "مخى", "ﳑ": "مم", "ﲉ": "مم", "ﱈ": "مم", "ﶱ": "ممى", "ﱉ": "مى", "ﱊ": "مى", "𞸍": "ن", "𞸭": "ن", "𞹍": "ن", "𞹭": "ن", "𞺍": "ن", "𞺭": "ن", "ﻧ": "ن", "ﻨ": "ن", "ﻦ": "ن", "ﻥ": "ن", "ݨ": "نؕ", "ݩ": "ن̆", "ﳖ": "نo", "ﳯ": "نo", "ﶸ": "نجح", "ﶽ": "نجح", "ﶘ": "نجم", "ﶗ": "نجم", "ﶙ": "نجى", "ﷇ": "نجى", "ﳓ": "نح", "ﱌ": "نح", "ﶕ": "نحم", "ﶖ": "نحى", "ﶳ": "نحى", "ﳔ": "نخ", "ﱍ": "نخ", "ﲊ": "نر", "ﲋ": "نز", "ﳕ": "نم", "ﳮ": "نم", "ﲌ": "نم", "ﱎ": "نم", "ﶛ": "نمى", "ﶚ": "نمى", "ﲍ": "نن", "ﲎ": "نى", "ﱏ": "نى", "ﲏ": "نى", "ﱐ": "نى", "ۂ": "ۀ", "ﮥ": "ۀ", "ﮤ": "ۀ", "𐋤": "و", "𞸅": "و", "𞺅": "و", "𞺥": "و", "ﻮ": "و", "ﻭ": "و", "ࢱ": "و", "ۋ": "وۛ", "ﯟ": "وۛ", "ﯞ": "وۛ", "ۇ": "و̓", "ﯘ": "و̓", "ﯗ": "و̓", "ۆ": "و̆", "ﯚ": "و̆", "ﯙ": "و̆", "ۉ": "و̂", "ﯣ": "و̂", "ﯢ": "و̂", "ۈ": "وٰ", "ﯜ": "وٰ", "ﯛ": "وٰ", "ؤ": "وٴ", "ﺆ": "وٴ", "ﺅ": "وٴ", "ٶ": "وٴ", "ٷ": "و̓ٴ", "ﯝ": "و̓ٴ", "ﷸ": "وسلم", "ﯡ": "ۅ", "ﯠ": "ۅ", "ٮ": "ى", "𞸜": "ى", "𞹼": "ى", "ں": "ى", "𞸝": "ى", "𞹝": "ى", "ﮟ": "ى", "ﮞ": "ى", "ࢽ": "ى", "ﯨ": "ى", "ﯩ": "ى", "ﻰ": "ى", "ﻯ": "ى", "ي": "ى", "𞸉": "ى", "𞸩": "ى", "𞹉": "ى", "𞹩": "ى", "𞺉": "ى", "𞺩": "ى", "ﻳ": "ى", "ﻴ": "ى", "ﻲ": "ى", "ﻱ": "ى", "ی": "ى", "ﯾ": "ى", "ﯿ": "ى", "ﯽ": "ى", "ﯼ": "ى", "ے": "ى", "ﮯ": "ى", "ﮮ": "ى", "ٹ": "ىؕ", "ﭨ": "ىؕ", "ﭩ": "ىؕ", "ﭧ": "ىؕ", "ﭦ": "ىؕ", "ڻ": "ىؕ", "ﮢ": "ىؕ", "ﮣ": "ىؕ", "ﮡ": "ىؕ", "ﮠ": "ىؕ", "پ": "ىۛ", "ﭘ": "ىۛ", "ﭙ": "ىۛ", "ﭗ": "ىۛ", "ﭖ": "ىۛ", "ث": "ىۛ", "𞸖": "ىۛ", "𞸶": "ىۛ", "𞹶": "ىۛ", "𞺖": "ىۛ", "𞺶": "ىۛ", "ﺛ": "ىۛ", "ﺜ": "ىۛ", "ﺚ": "ىۛ", "ﺙ": "ىۛ", "ڽ": "ىۛ", "ۑ": "ىۛ", "ؿ": "ىۛ", "ࢷ": "ىۛۢ", "ݖ": "ى̆", "ێ": "ى̆", "ࢺ": "ى̆̇", "ؽ": "ى̂", "ࢨ": "ىٔ", "ﲐ": "ىٰ", "ﱝ": "ىٰ", "ﳞ": "ىo", "ﳱ": "ىo", "ﳦ": "ىۛo", "ئ": "ىٴ", "ﺋ": "ىٴ", "ﺌ": "ىٴ", "ﺊ": "ىٴ", "ﺉ": "ىٴ", "ٸ": "ىٴ", "ﯫ": "ىٴl", "ﯪ": "ىٴl", "ﲛ": "ىٴo", "ﳠ": "ىٴo", "ﯭ": "ىٴo", "ﯬ": "ىٴo", "ﯸ": "ىٴٻ", "ﯷ": "ىٴٻ", "ﯶ": "ىٴٻ", "ﲗ": "ىٴج", "ﰀ": "ىٴج", "ﲘ": "ىٴح", "ﰁ": "ىٴح", "ﲙ": "ىٴخ", "ﱤ": "ىٴر", "ﱥ": "ىٴز", "ﲚ": "ىٴم", "ﳟ": "ىٴم", "ﱦ": "ىٴم", "ﰂ": "ىٴم", "ﱧ": "ىٴن", "ﯯ": "ىٴو", "ﯮ": "ىٴو", "ﯱ": "ىٴو̓", "ﯰ": "ىٴو̓", "ﯳ": "ىٴو̆", "ﯲ": "ىٴو̆", "ﯵ": "ىٴوٰ", "ﯴ": "ىٴوٰ", "ﯻ": "ىٴى", "ﯺ": "ىٴى", "ﱨ": "ىٴى", "ﯹ": "ىٴى", "ﰃ": "ىٴى", "ﱩ": "ىٴى", "ﰄ": "ىٴى", "ﳚ": "ىج", "ﱕ": "ىج", "ﰑ": "ىۛج", "ﶯ": "ىجى", "ﳛ": "ىح", "ﱖ": "ىح", "ﶮ": "ىحى", "ﳜ": "ىخ", "ﱗ": "ىخ", "ﲑ": "ىر", "ﱶ": "ىۛر", "ﲒ": "ىز", "ﱷ": "ىۛز", "ﳝ": "ىم", "ﳰ": "ىم", "ﲓ": "ىم", "ﱘ": "ىم", "ﲦ": "ىۛم", "ﳥ": "ىۛم", "ﱸ": "ىۛم", "ﰒ": "ىۛم", "ﶝ": "ىمم", "ﶜ": "ىمم", "ﶰ": "ىمى", "ﲔ": "ىن", "ﱹ": "ىۛن", "ﲕ": "ىى", "ﱙ": "ىى", "ﲖ": "ىى", "ﱚ": "ىى", "ﱺ": "ىۛى", "ﰓ": "ىۛى", "ﱻ": "ىۛى", "ﰔ": "ىۛى", "ﮱ": "ۓ", "ﮰ": "ۓ", "𐊸": "ⵀ", "⁞": "ⵂ", "⸽": "ⵂ", "⦙": "ⵂ", "︙": "ⵗ", "⁝": "ⵗ", "⋮": "ⵗ", "Մ": "ሆ", "Ռ": "ቡ", "Ի": "ኮ", "Պ": "ጣ", "आ": "अा", "ऒ": "अाॆ", "ओ": "अाे", "औ": "अाै", "ऄ": "अॆ", "ऑ": "अॉ", "ऍ": "एॅ", "ऎ": "एॆ", "ऐ": "एे", "ई": "र्इ", "ઽ": "ऽ", "𑇜": "ꣻ", "𑇋": "ऺ", "ુ": "ु", "ૂ": "ू", "ੋ": "ॆ", "੍": "्", "્": "्", "আ": "অা", "ৠ": "ঋৃ", "ৡ": "ঋৃ", "𑒒": "ঘ", "𑒔": "চ", "𑒖": "জ", "𑒘": "ঞ", "𑒙": "ট", "𑒛": "ড", "𑒪": "ণ", "𑒞": "ত", "𑒟": "থ", "𑒠": "দ", "𑒡": "ধ", "𑒢": "ন", "𑒣": "প", "𑒩": "ব", "𑒧": "ম", "𑒨": "য", "𑒫": "র", "𑒝": "ল", "𑒭": "ষ", "𑒮": "স", "𑓄": "ঽ", "𑒰": "া", "𑒱": "ি", "𑒹": "ে", "𑒼": "ো", "𑒾": "ৌ", "𑓂": "্", "𑒽": "ৗ", "ਉ": "ੳੁ", "ਊ": "ੳੂ", "ਆ": "ਅਾ", "ਐ": "ਅੈ", "ਔ": "ਅੌ", "ਇ": "ੲਿ", "ਈ": "ੲੀ", "ਏ": "ੲੇ", "આ": "અા", "ઑ": "અાૅ", "ઓ": "અાે", "ઔ": "અાૈ", "ઍ": "અૅ", "એ": "અે", "ઐ": "અૈ", "ଆ": "ଅା", "௮": "அ", "ர": "ஈ", "ா": "ஈ", "௫": "ஈு", "௨": "உ", "ഉ": "உ", "ஊ": "உள", "ഊ": "உൗ", "௭": "எ", "௷": "எவ", "ஜ": "ஐ", "ജ": "ஐ", "௧": "க", "௪": "ச", "௬": "சு", "௲": "சூ", "ഺ": "டி", "ണ": "ண", "௺": "நீ", "௴": "மீ", "௰": "ய", "ഴ": "ழ", "ௗ": "ள", "ை": "ன", "ശ": "ஶ", "௸": "ஷ", "ി": "ி", "ീ": "ி", "ொ": "ெஈ", "ௌ": "ெள", "ோ": "ேஈ", "ಅ": "అ", "ಆ": "ఆ", "ಇ": "ఇ", "ౠ": "ఋా", "ౡ": "ఌా", "ಒ": "ఒ", "ఔ": "ఒౌ", "ಔ": "ఒౌ", "ఓ": "ఒౕ", "ಓ": "ఒౕ", "ಜ": "జ", "ಞ": "ఞ", "ఢ": "డ̣", "ಣ": "ణ", "థ": "ధּ", "భ": "బ̣", "ಯ": "య", "ఠ": "రּ", "ಱ": "ఱ", "ಲ": "ల", "ష": "వ̣", "హ": "వా", "మ": "వు", "ూ": "ుా", "ౄ": "ృా", "ೡ": "ಌಾ", "ഈ": "ഇൗ", "ഐ": "എെ", "ഓ": "ഒാ", "ഔ": "ഒൗ", "ൡ": "ഞ", "൫": "ദ്ര", "൹": "നു", "ഌ": "നു", "ങ": "നു", "൯": "ന്", "ൻ": "ന്", "൬": "ന്ന", "൚": "ന്മ", "റ": "ര", "൪": "ര്", "ർ": "ര്", "൮": "വ്ര", "൶": "ഹ്മ", "ൂ": "ു", "ൃ": "ു", "ൈ": "െെ", "෪": "ජ", "෫": "ද", "𑐓": "𑐴𑑂𑐒", "𑐙": "𑐴𑑂𑐘", "𑐤": "𑐴𑑂𑐣", "𑐪": "𑐴𑑂𑐩", "𑐭": "𑐴𑑂𑐬", "𑐯": "𑐴𑑂𑐮", "𑗘": "𑖂", "𑗙": "𑖂", "𑗚": "𑖃", "𑗛": "𑖄", "𑗜": "𑖲", "𑗝": "𑖳", "ฃ": "ข", "ด": "ค", "ต": "ค", "ม": "ฆ", "ຈ": "จ", "ซ": "ช", "ฏ": "ฎ", "ท": "ฑ", "ບ": "บ", "ປ": "ป", "ຝ": "ฝ", "ພ": "พ", "ຟ": "ฟ", "ฦ": "ภ", "ຍ": "ย", "។": "ฯ", "ๅ": "า", "ำ": "̊า", "ិ": "ิ", "ី": "ี", "ឹ": "ึ", "ឺ": "ื", "ຸ": "ุ", "ູ": "ู", "แ": "เเ", "ໜ": "ຫນ", "ໝ": "ຫມ", "ຳ": "̊າ", "༂": "འུྂཿ", "༃": "འུྂ༔", "ཪ": "ར", "ༀ": "ཨོཾ", "ཷ": "ྲཱྀ", "ཹ": "ླཱྀ", "𑲲": "𑲪", "ႁ": "ဂှ", "က": "ဂာ", "ၰ": "ဃှ", "ၦ": "ပှ", "ဟ": "ပာ", "ၯ": "ပာှ", "ၾ": "ၽှ", "ဩ": "သြ", "ဪ": "သြော်", "႞": "ႃ̊", "ឣ": "អ", "᧐": "ᦞ", "᧑": "ᦱ", "᪀": "ᩅ", "᪐": "ᩅ", "꩓": "ꨁ", "꩖": "ꨣ", "᭒": "ᬍ", "᭓": "ᬑ", "᭘": "ᬨ", "ꦣ": "ꦝ", "ᢖ": "ᡜ", "ᡕ": "ᠵ", "ῶ": "Ꮿ", "ᐍ": "ᐁ·", "ᐫ": "ᐁᐠ", "ᐑ": "ᐄ·", "ᐓ": "ᐅ·", "ᐭ": "ᐅᐠ", "ᐕ": "ᐆ·", "ᐘ": "ᐊ·", "ᐮ": "ᐊᐠ", "ᐚ": "ᐋ·", "ᣝ": "ᐞᣟ", "ᓑ": "ᐡ", "ᕀ": "ᐩ", "ᐿ": "ᐲ·", "ᑃ": "ᐴ·", "⍩": "ᐵ", "ᑇ": "ᐹ·", "ᑜ": "ᑏ·", "⸧": "ᑐ", "⊃": "ᑐ", "ᑞ": "ᑐ·", "ᑩ": "ᑐ'", "⟉": "ᑐ/", "⫗": "ᑐᑕ", "ᑠ": "ᑑ·", "⸦": "ᑕ", "⊂": "ᑕ", "ᑢ": "ᑕ·", "ᑪ": "ᑕ'", "ᑤ": "ᑖ·", "ᑵ": "ᑫ·", "ᒅ": "ᑫ'", "ᑹ": "ᑮ·", "ᑽ": "ᑰ·", "ᘃ": "ᒉ", "ᒓ": "ᒉ·", "ᒕ": "ᒋ·", "ᒗ": "ᒌ·", "ᒛ": "ᒎ·", "ᘂ": "ᒐ", "ᒝ": "ᒐ·", "ᒟ": "ᒑ·", "ᒭ": "ᒣ·", "ᒱ": "ᒦ·", "ᒳ": "ᒧ·", "ᒵ": "ᒨ·", "ᒹ": "ᒫ·", "ᓊ": "ᓀ·", "ᣇ": "ᓂ·", "ᣉ": "ᓃ·", "ᣋ": "ᓄ·", "ᣍ": "ᓅ·", "ᓌ": "ᓇ·", "ᓎ": "ᓈ·", "ᘄ": "ᓓ", "ᓝ": "ᓓ·", "ᓟ": "ᓕ·", "ᓡ": "ᓖ·", "ᓣ": "ᓗ·", "ᓥ": "ᓘ·", "ᘇ": "ᓚ", "ᓧ": "ᓚ·", "ᓩ": "ᓛ·", "ᓷ": "ᓭ·", "ᓹ": "ᓯ·", "ᓻ": "ᓰ·", "ᓽ": "ᓱ·", "ᓿ": "ᓲ·", "ᔁ": "ᓴ·", "ᔃ": "ᓵ·", "ᔌ": "ᔋ<", "ᔎ": "ᔋb", "ᔍ": "ᔋᑕ", "ᔏ": "ᔋᒐ", "ᔘ": "ᔐ·", "ᔚ": "ᔑ·", "ᔜ": "ᔒ·", "ᔞ": "ᔓ·", "ᔠ": "ᔔ·", "ᔢ": "ᔕ·", "ᔤ": "ᔖ·", "ᔲ": "ᔨ·", "ᔴ": "ᔩ·", "ᔶ": "ᔪ·", "ᔸ": "ᔫ·", "ᔺ": "ᔭ·", "ᔼ": "ᔮ·", "ᘢ": "ᕃ", "ᣠ": "ᕃ·", "ᘣ": "ᕆ", "ᘤ": "ᕊ", "ᕏ": "ᕌ·", "ᖃ": "ᕐb", "ᖄ": "ᕐḃ", "ᖁ": "ᕐd", "ᕿ": "ᕐP", "ᙯ": "ᕐᑫ", "ᕾ": "ᕐᑬ", "ᖀ": "ᕐᑮ", "ᖂ": "ᕐᑰ", "ᖅ": "ᕐᒃ", "ᕜ": "ᕚ·", "ᣣ": "ᕞ·", "ᣤ": "ᕦ·", "ᕩ": "ᕧ·", "ᣥ": "ᕫ·", "ᣨ": "ᖆ·", "ᖑ": "ᖕJ", "ᙰ": "ᖕᒉ", "ᖎ": "ᖕᒊ", "ᖏ": "ᖕᒋ", "ᖐ": "ᖕᒌ", "ᖒ": "ᖕᒎ", "ᖓ": "ᖕᒐ", "ᖔ": "ᖕᒑ", "ᙳ": "ᖖJ", "ᙱ": "ᖖᒋ", "ᙲ": "ᖖᒌ", "ᙴ": "ᖖᒎ", "ᙵ": "ᖖᒐ", "ᙶ": "ᖖᒑ", "ᣪ": "ᖗ·", "ᙷ": "ᖧ·", "ᙸ": "ᖨ·", "ᙹ": "ᖩ·", "ᙺ": "ᖪ·", "ᙻ": "ᖫ·", "ᙼ": "ᖬ·", "ᙽ": "ᖭ·", "⪫": "ᗒ", "⪪": "ᗕ", "ꓷ": "ᗡ", "ᣰ": "ᗴ·", "ᣲ": "ᘛ·", "ᶻ": "ᙆ", "ꓭ": "ᙠ", "ᶺ": "ᣔ", "ᴾ": "ᣖ", "ᣜ": "ᣟᐞ", "ˡ": "ᣳ", "ʳ": "ᣴ", "ˢ": "ᣵ", "ᣛ": "ᣵ", "ꚰ": "ᚹ", "ᛡ": "ᚼ", "⍿": "ᚽ", "ᛂ": "ᚽ", "𝈿": "ᛋ", "↑": "ᛏ", "↿": "ᛐ", "⥮": "ᛐ⇂", "⥣": "ᛐᛚ", "ⵣ": "ᛯ", "↾": "ᛚ", "⨡": "ᛚ", "⋄": "ᛜ", "◇": "ᛜ", "◊": "ᛜ", "♢": "ᛜ", "🝔": "ᛜ", "𑢷": "ᛜ", "𐊔": "ᛜ", "⍚": "ᛜ̲", "⋈": "ᛞ", "⨝": "ᛞ", "𐓐": "ᛦ", "↕": "ᛨ", "𐳼": "𐲂", "𐳺": "𐲥", "ㄱ": "ᄀ", "ᆨ": "ᄀ", "ᄁ": "ᄀᄀ", "ㄲ": "ᄀᄀ", "ᆩ": "ᄀᄀ", "ᇺ": "ᄀᄂ", "ᅚ": "ᄀᄃ", "ᇃ": "ᄀᄅ", "ᇻ": "ᄀᄇ", "ᆪ": "ᄀᄉ", "ㄳ": "ᄀᄉ", "ᇄ": "ᄀᄉᄀ", "ᇼ": "ᄀᄎ", "ᇽ": "ᄀᄏ", "ᇾ": "ᄀᄒ", "ㄴ": "ᄂ", "ᆫ": "ᄂ", "ᄓ": "ᄂᄀ", "ᇅ": "ᄂᄀ", "ᄔ": "ᄂᄂ", "ㅥ": "ᄂᄂ", "ᇿ": "ᄂᄂ", "ᄕ": "ᄂᄃ", "ㅦ": "ᄂᄃ", "ᇆ": "ᄂᄃ", "ퟋ": "ᄂᄅ", "ᄖ": "ᄂᄇ", "ᅛ": "ᄂᄉ", "ᇇ": "ᄂᄉ", "ㅧ": "ᄂᄉ", "ᅜ": "ᄂᄌ", "ᆬ": "ᄂᄌ", "ㄵ": "ᄂᄌ", "ퟌ": "ᄂᄎ", "ᇉ": "ᄂᄐ", "ᅝ": "ᄂᄒ", "ᆭ": "ᄂᄒ", "ㄶ": "ᄂᄒ", "ᇈ": "ᄂᅀ", "ㅨ": "ᄂᅀ", "ㄷ": "ᄃ", "ᆮ": "ᄃ", "ᄗ": "ᄃᄀ", "ᇊ": "ᄃᄀ", "ᄄ": "ᄃᄃ", "ㄸ": "ᄃᄃ", "ퟍ": "ᄃᄃ", "ퟎ": "ᄃᄃᄇ", "ᅞ": "ᄃᄅ", "ᇋ": "ᄃᄅ", "ꥠ": "ᄃᄆ", "ꥡ": "ᄃᄇ", "ퟏ": "ᄃᄇ", "ꥢ": "ᄃᄉ", "ퟐ": "ᄃᄉ", "ퟑ": "ᄃᄉᄀ", "ꥣ": "ᄃᄌ", "ퟒ": "ᄃᄌ", "ퟓ": "ᄃᄎ", "ퟔ": "ᄃᄐ", "ㄹ": "ᄅ", "ᆯ": "ᄅ", "ꥤ": "ᄅᄀ", "ᆰ": "ᄅᄀ", "ㄺ": "ᄅᄀ", "ꥥ": "ᄅᄀᄀ", "ퟕ": "ᄅᄀᄀ", "ᇌ": "ᄅᄀᄉ", "ㅩ": "ᄅᄀᄉ", "ퟖ": "ᄅᄀᄒ", "ᄘ": "ᄅᄂ", "ᇍ": "ᄅᄂ", "ꥦ": "ᄅᄃ", "ᇎ": "ᄅᄃ", "ㅪ": "ᄅᄃ", "ꥧ": "ᄅᄃᄃ", "ᇏ": "ᄅᄃᄒ", "ᄙ": "ᄅᄅ", "ᇐ": "ᄅᄅ", "ퟗ": "ᄅᄅᄏ", "ꥨ": "ᄅᄆ", "ᆱ": "ᄅᄆ", "ㄻ": "ᄅᄆ", "ᇑ": "ᄅᄆᄀ", "ᇒ": "ᄅᄆᄉ", "ퟘ": "ᄅᄆᄒ", "ꥩ": "ᄅᄇ", "ᆲ": "ᄅᄇ", "ㄼ": "ᄅᄇ", "ퟙ": "ᄅᄇᄃ", "ꥪ": "ᄅᄇᄇ", "ᇓ": "ᄅᄇᄉ", "ㅫ": "ᄅᄇᄉ", "ꥫ": "ᄅᄇᄋ", "ᇕ": "ᄅᄇᄋ", "ퟚ": "ᄅᄇᄑ", "ᇔ": "ᄅᄇᄒ", "ꥬ": "ᄅᄉ", "ᆳ": "ᄅᄉ", "ㄽ": "ᄅᄉ", "ᇖ": "ᄅᄉᄉ", "ᄛ": "ᄅᄋ", "ퟝ": "ᄅᄋ", "ꥭ": "ᄅᄌ", "ꥮ": "ᄅᄏ", "ᇘ": "ᄅᄏ", "ᆴ": "ᄅᄐ", "ㄾ": "ᄅᄐ", "ᆵ": "ᄅᄑ", "ㄿ": "ᄅᄑ", "ᄚ": "ᄅᄒ", "ㅀ": "ᄅᄒ", "ᄻ": "ᄅᄒ", "ᆶ": "ᄅᄒ", "ퟲ": "ᄅᄒ", "ᇗ": "ᄅᅀ", "ㅬ": "ᄅᅀ", "ퟛ": "ᄅᅌ", "ᇙ": "ᄅᅙ", "ㅭ": "ᄅᅙ", "ퟜ": "ᄅᅙᄒ", "ㅁ": "ᄆ", "ᆷ": "ᄆ", "ꥯ": "ᄆᄀ", "ᇚ": "ᄆᄀ", "ퟞ": "ᄆᄂ", "ퟟ": "ᄆᄂᄂ", "ꥰ": "ᄆᄃ", "ᇛ": "ᄆᄅ", "ퟠ": "ᄆᄆ", "ᄜ": "ᄆᄇ", "ㅮ": "ᄆᄇ", "ᇜ": "ᄆᄇ", "ퟡ": "ᄆᄇᄉ", "ꥱ": "ᄆᄉ", "ᇝ": "ᄆᄉ", "ㅯ": "ᄆᄉ", "ᇞ": "ᄆᄉᄉ", "ᄝ": "ᄆᄋ", "ㅱ": "ᄆᄋ", "ᇢ": "ᄆᄋ", "ퟢ": "ᄆᄌ", "ᇠ": "ᄆᄎ", "ᇡ": "ᄆᄒ", "ᇟ": "ᄆᅀ", "ㅰ": "ᄆᅀ", "ㅂ": "ᄇ", "ᆸ": "ᄇ", "ᄞ": "ᄇᄀ", "ㅲ": "ᄇᄀ", "ᄟ": "ᄇᄂ", "ᄠ": "ᄇᄃ", "ㅳ": "ᄇᄃ", "ퟣ": "ᄇᄃ", "ᇣ": "ᄇᄅ", "ퟤ": "ᄇᄅᄑ", "ퟥ": "ᄇᄆ", "ᄈ": "ᄇᄇ", "ㅃ": "ᄇᄇ", "ퟦ": "ᄇᄇ", "ᄬ": "ᄇᄇᄋ", "ㅹ": "ᄇᄇᄋ", "ᄡ": "ᄇᄉ", "ㅄ": "ᄇᄉ", "ᆹ": "ᄇᄉ", "ᄢ": "ᄇᄉᄀ", "ㅴ": "ᄇᄉᄀ", "ᄣ": "ᄇᄉᄃ", "ㅵ": "ᄇᄉᄃ", "ퟧ": "ᄇᄉᄃ", "ᄤ": "ᄇᄉᄇ", "ᄥ": "ᄇᄉᄉ", "ᄦ": "ᄇᄉᄌ", "ꥲ": "ᄇᄉᄐ", "ᄫ": "ᄇᄋ", "ㅸ": "ᄇᄋ", "ᇦ": "ᄇᄋ", "ᄧ": "ᄇᄌ", "ㅶ": "ᄇᄌ", "ퟨ": "ᄇᄌ", "ᄨ": "ᄇᄎ", "ퟩ": "ᄇᄎ", "ꥳ": "ᄇᄏ", "ᄩ": "ᄇᄐ", "ㅷ": "ᄇᄐ", "ᄪ": "ᄇᄑ", "ᇤ": "ᄇᄑ", "ꥴ": "ᄇᄒ", "ᇥ": "ᄇᄒ", "ㅅ": "ᄉ", "ᆺ": "ᄉ", "ᄭ": "ᄉᄀ", "ㅺ": "ᄉᄀ", "ᇧ": "ᄉᄀ", "ᄮ": "ᄉᄂ", "ㅻ": "ᄉᄂ", "ᄯ": "ᄉᄃ", "ㅼ": "ᄉᄃ", "ᇨ": "ᄉᄃ", "ᄰ": "ᄉᄅ", "ᇩ": "ᄉᄅ", "ᄱ": "ᄉᄆ", "ퟪ": "ᄉᄆ", "ᄲ": "ᄉᄇ", "ㅽ": "ᄉᄇ", "ᇪ": "ᄉᄇ", "ᄳ": "ᄉᄇᄀ", "ퟫ": "ᄉᄇᄋ", "ᄊ": "ᄉᄉ", "ㅆ": "ᄉᄉ", "ᆻ": "ᄉᄉ", "ퟬ": "ᄉᄉᄀ", "ퟭ": "ᄉᄉᄃ", "ꥵ": "ᄉᄉᄇ", "ᄴ": "ᄉᄉᄉ", "ᄵ": "ᄉᄋ", "ᄶ": "ᄉᄌ", "ㅾ": "ᄉᄌ", "ퟯ": "ᄉᄌ", "ᄷ": "ᄉᄎ", "ퟰ": "ᄉᄎ", "ᄸ": "ᄉᄏ", "ᄹ": "ᄉᄐ", "ퟱ": "ᄉᄐ", "ᄺ": "ᄉᄑ", "ퟮ": "ᄉᅀ", "ㅇ": "ᄋ", "ᆼ": "ᄋ", "ᅁ": "ᄋᄀ", "ᇬ": "ᄋᄀ", "ᇭ": "ᄋᄀᄀ", "ᅂ": "ᄋᄃ", "ꥶ": "ᄋᄅ", "ᅃ": "ᄋᄆ", "ᅄ": "ᄋᄇ", "ᅅ": "ᄋᄉ", "ᇱ": "ᄋᄉ", "ㆂ": "ᄋᄉ", "ᅇ": "ᄋᄋ", "ㆀ": "ᄋᄋ", "ᇮ": "ᄋᄋ", "ᅈ": "ᄋᄌ", "ᅉ": "ᄋᄎ", "ᇯ": "ᄋᄏ", "ᅊ": "ᄋᄐ", "ᅋ": "ᄋᄑ", "ꥷ": "ᄋᄒ", "ᅆ": "ᄋᅀ", "ᇲ": "ᄋᅀ", "ㆃ": "ᄋᅀ", "ㅈ": "ᄌ", "ᆽ": "ᄌ", "ퟷ": "ᄌᄇ", "ퟸ": "ᄌᄇᄇ", "ᅍ": "ᄌᄋ", "ᄍ": "ᄌᄌ", "ㅉ": "ᄌᄌ", "ퟹ": "ᄌᄌ", "ꥸ": "ᄌᄌᄒ", "ㅊ": "ᄎ", "ᆾ": "ᄎ", "ᅒ": "ᄎᄏ", "ᅓ": "ᄎᄒ", "ㅋ": "ᄏ", "ᆿ": "ᄏ", "ㅌ": "ᄐ", "ᇀ": "ᄐ", "ꥹ": "ᄐᄐ", "ㅍ": "ᄑ", "ᇁ": "ᄑ", "ᅖ": "ᄑᄇ", "ᇳ": "ᄑᄇ", "ퟺ": "ᄑᄉ", "ᅗ": "ᄑᄋ", "ㆄ": "ᄑᄋ", "ᇴ": "ᄑᄋ", "ퟻ": "ᄑᄐ", "ꥺ": "ᄑᄒ", "ㅎ": "ᄒ", "ᇂ": "ᄒ", "ᇵ": "ᄒᄂ", "ᇶ": "ᄒᄅ", "ᇷ": "ᄒᄆ", "ᇸ": "ᄒᄇ", "ꥻ": "ᄒᄉ", "ᅘ": "ᄒᄒ", "ㆅ": "ᄒᄒ", "ᄽ": "ᄼᄼ", "ᄿ": "ᄾᄾ", "ㅿ": "ᅀ", "ᇫ": "ᅀ", "ퟳ": "ᅀᄇ", "ퟴ": "ᅀᄇᄋ", "ㆁ": "ᅌ", "ᇰ": "ᅌ", "ퟵ": "ᅌᄆ", "ퟶ": "ᅌᄒ", "ᅏ": "ᅎᅎ", "ᅑ": "ᅐᅐ", "ㆆ": "ᅙ", "ᇹ": "ᅙ", "ꥼ": "ᅙᅙ", "ㅤ": "ᅠ", "ㅏ": "ᅡ", "ᆣ": "ᅡー", "ᅶ": "ᅡᅩ", "ᅷ": "ᅡᅮ", "ᅢ": "ᅡ丨", "ㅐ": "ᅡ丨", "ㅑ": "ᅣ", "ᅸ": "ᅣᅩ", "ᅹ": "ᅣᅭ", "ᆤ": "ᅣᅮ", "ᅤ": "ᅣ丨", "ㅒ": "ᅣ丨", "ㅓ": "ᅥ", "ᅼ": "ᅥー", "ᅺ": "ᅥᅩ", "ᅻ": "ᅥᅮ", "ᅦ": "ᅥ丨", "ㅔ": "ᅥ丨", "ㅕ": "ᅧ", "ᆥ": "ᅧᅣ", "ᅽ": "ᅧᅩ", "ᅾ": "ᅧᅮ", "ᅨ": "ᅧ丨", "ㅖ": "ᅧ丨", "ㅗ": "ᅩ", "ᅪ": "ᅩᅡ", "ㅘ": "ᅩᅡ", "ᅫ": "ᅩᅡ丨", "ㅙ": "ᅩᅡ丨", "ᆦ": "ᅩᅣ", "ᆧ": "ᅩᅣ丨", "ᅿ": "ᅩᅥ", "ᆀ": "ᅩᅥ丨", "ힰ": "ᅩᅧ", "ᆁ": "ᅩᅧ丨", "ᆂ": "ᅩᅩ", "ힱ": "ᅩᅩ丨", "ᆃ": "ᅩᅮ", "ᅬ": "ᅩ丨", "ㅚ": "ᅩ丨", "ㅛ": "ᅭ", "ힲ": "ᅭᅡ", "ힳ": "ᅭᅡ丨", "ᆄ": "ᅭᅣ", "ㆇ": "ᅭᅣ", "ᆆ": "ᅭᅣ", "ᆅ": "ᅭᅣ丨", "ㆈ": "ᅭᅣ丨", "ힴ": "ᅭᅥ", "ᆇ": "ᅭᅩ", "ᆈ": "ᅭ丨", "ㆉ": "ᅭ丨", "ㅜ": "ᅮ", "ᆉ": "ᅮᅡ", "ᆊ": "ᅮᅡ丨", "ᅯ": "ᅮᅥ", "ㅝ": "ᅮᅥ", "ᆋ": "ᅮᅥー", "ᅰ": "ᅮᅥ丨", "ㅞ": "ᅮᅥ丨", "ힵ": "ᅮᅧ", "ᆌ": "ᅮᅧ丨", "ᆍ": "ᅮᅮ", "ᅱ": "ᅮ丨", "ㅟ": "ᅮ丨", "ힶ": "ᅮ丨丨", "ㅠ": "ᅲ", "ᆎ": "ᅲᅡ", "ힷ": "ᅲᅡ丨", "ᆏ": "ᅲᅥ", "ᆐ": "ᅲᅥ丨", "ᆑ": "ᅲᅧ", "ㆊ": "ᅲᅧ", "ᆒ": "ᅲᅧ丨", "ㆋ": "ᅲᅧ丨", "ힸ": "ᅲᅩ", "ᆓ": "ᅲᅮ", "ᆔ": "ᅲ丨", "ㆌ": "ᅲ丨", "ㆍ": "ᆞ", "ퟅ": "ᆞᅡ", "ᆟ": "ᆞᅥ", "ퟆ": "ᆞᅥ丨", "ᆠ": "ᆞᅮ", "ᆢ": "ᆞᆞ", "ᆡ": "ᆞ丨", "ㆎ": "ᆞ丨", "ヘ": "へ", "⍁": "〼", "⧄": "〼", "꒞": "ꁊ", "꒬": "ꁐ", "꒜": "ꃀ", "꒨": "ꄲ", "꒿": "ꉙ", "꒾": "ꊱ", "꒔": "ꋍ", "꓀": "ꎫ", "꓂": "ꎵ", "꒺": "ꎿ", "꒰": "ꏂ", "꒧": "ꑘ", "⊥": "ꓕ", "⟂": "ꓕ", "𝈜": "ꓕ", "Ʇ": "ꓕ", "Ꞟ": "ꓤ", "⅁": "ꓨ", "⅂": "ꓶ", "𝈕": "ꓶ", "𝈫": "ꓶ", "𖼦": "ꓶ", "𐐑": "ꓶ", "⅃": "𖼀", "𑫦": "𑫥𑫯", "𑫨": "𑫥𑫥", "𑫩": "𑫥𑫥𑫯", "𑫪": "𑫥𑫥𑫰", "𑫧": "𑫥𑫰", "𑫴": "𑫳𑫯", "𑫶": "𑫳𑫳", "𑫷": "𑫳𑫳𑫯", "𑫸": "𑫳𑫳𑫰", "𑫵": "𑫳𑫰", "𑫬": "𑫫𑫯", "𑫭": "𑫫𑫫", "𑫮": "𑫫𑫫𑫯", "⊕": "𐊨", "⨁": "𐊨", "🜨": "𐊨", "Ꚛ": "𐊨", "▽": "𐊼", "𝈔": "𐊼", "🜄": "𐊼", "⧖": "𐋀", "ꞛ": "𐐺", "Ꞛ": "𐐒", "𐒠": "𐒆", "𐏑": "𐎂", "𐏓": "𐎓", "𒀸": "𐎚", "☥": "𐦞", "𓋹": "𐦞", "〹": "卄", "不": "不", "丽": "丽", "並": "並", "⎜": "丨", "⎟": "丨", "⎢": "丨", "⎥": "丨", "⎪": "丨", "⎮": "丨", "㇑": "丨", "ᅵ": "丨", "ㅣ": "丨", "⼁": "丨", "ᆜ": "丨ー", "ᆘ": "丨ᅡ", "ᆙ": "丨ᅣ", "ힽ": "丨ᅣᅩ", "ힾ": "丨ᅣ丨", "ힿ": "丨ᅧ", "ퟀ": "丨ᅧ丨", "ᆚ": "丨ᅩ", "ퟁ": "丨ᅩ丨", "ퟂ": "丨ᅭ", "ᆛ": "丨ᅮ", "ퟃ": "丨ᅲ", "ᆝ": "丨ᆞ", "ퟄ": "丨丨", "串": "串", "丸": "丸", "丹": "丹", "乁": "乁", "㇠": "乙", "⼄": "乙", "㇟": "乚", "⺃": "乚", "㇖": "乛", "⺂": "乛", "⻲": "亀", "亂": "亂", "㇚": "亅", "⼅": "亅", "了": "了", "ニ": "二", "⼆": "二", "𠄢": "𠄢", "⼇": "亠", "亮": "亮", "⼈": "人", "イ": "亻", "⺅": "亻", "什": "什", "仌": "仌", "令": "令", "你": "你", "倂": "併", "倂": "併", "侀": "侀", "來": "來", "例": "例", "侮": "侮", "侮": "侮", "侻": "侻", "便": "便", "值": "値", "倫": "倫", "偺": "偺", "備": "備", "像": "像", "僚": "僚", "僧": "僧", "僧": "僧", "㒞": "㒞", "⼉": "儿", "兀": "兀", "⺎": "兀", "充": "充", "免": "免", "免": "免", "兔": "兔", "兤": "兤", "⼊": "入", "內": "內", "全": "全", "兩": "兩", "ハ": "八", "⼋": "八", "六": "六", "具": "具", "𠔜": "𠔜", "𠔥": "𠔥", "冀": "冀", "㒹": "㒹", "⼌": "冂", "再": "再", "𠕋": "𠕋", "冒": "冒", "冕": "冕", "㒻": "㒻", "最": "最", "⼍": "冖", "冗": "冗", "冤": "冤", "⼎": "冫", "冬": "冬", "况": "况", "况": "况", "冷": "冷", "凉": "凉", "凌": "凌", "凜": "凜", "凞": "凞", "⼏": "几", "𠘺": "𠘺", "凵": "凵", "⼐": "凵", "⼑": "刀", "⺉": "刂", "刃": "刃", "切": "切", "切": "切", "列": "列", "利": "利", "㓟": "㓟", "刺": "刺", "刻": "刻", "剆": "剆", "割": "割", "剷": "剷", "劉": "劉", "𠠄": "𠠄", "カ": "力", "力": "力", "⼒": "力", "劣": "劣", "㔕": "㔕", "劳": "劳", "勇": "勇", "勇": "勇", "勉": "勉", "勉": "勉", "勒": "勒", "勞": "勞", "勤": "勤", "勤": "勤", "勵": "勵", "⼓": "勹", "勺": "勺", "勺": "勺", "包": "包", "匆": "匆", "𠣞": "𠣞", "⼔": "匕", "北": "北", "北": "北", "⼕": "匚", "⼖": "匸", "匿": "匿", "⼗": "十", "〸": "十", "〺": "卅", "卉": "卉", "࿖": "卍", "࿕": "卐", "卑": "卑", "卑": "卑", "博": "博", "ト": "卜", "⼘": "卜", "⼙": "卩", "⺋": "㔾", "即": "即", "卵": "卵", "卽": "卽", "卿": "卿", "卿": "卿", "卿": "卿", "⼚": "厂", "𠨬": "𠨬", "⼛": "厶", "參": "參", "⼜": "又", "及": "及", "叟": "叟", "𠭣": "𠭣", "ロ": "口", "⼝": "口", "囗": "口", "⼞": "口", "句": "句", "叫": "叫", "叱": "叱", "吆": "吆", "吏": "吏", "吝": "吝", "吸": "吸", "呂": "呂", "呈": "呈", "周": "周", "咞": "咞", "咢": "咢", "咽": "咽", "䎛": "㖈", "哶": "哶", "唐": "唐", "啓": "啓", "啟": "啓", "啕": "啕", "啣": "啣", "善": "善", "善": "善", "喇": "喇", "喙": "喙", "喙": "喙", "喝": "喝", "喝": "喝", "喫": "喫", "喳": "喳", "嗀": "嗀", "嗂": "嗂", "嗢": "嗢", "嘆": "嘆", "嘆": "嘆", "噑": "噑", "噴": "噴", "器": "器", "囹": "囹", "圖": "圖", "圗": "圗", "⼟": "土", "士": "土", "⼠": "土", "型": "型", "城": "城", "㦳": "㘽", "埴": "埴", "堍": "堍", "報": "報", "堲": "堲", "塀": "塀", "塚": "塚", "塚": "塚", "塞": "塞", "填": "塡", "壿": "墫", "墬": "墬", "墳": "墳", "壘": "壘", "壟": "壟", "𡓤": "𡓤", "壮": "壮", "売": "売", "壷": "壷", "⼡": "夂", "夆": "夆", "⼢": "夊", "タ": "夕", "⼣": "夕", "多": "多", "夢": "夢", "⼤": "大", "奄": "奄", "奈": "奈", "契": "契", "奔": "奔", "奢": "奢", "女": "女", "⼥": "女", "𡚨": "𡚨", "𡛪": "𡛪", "姘": "姘", "姬": "姬", "娛": "娛", "娧": "娧", "婢": "婢", "婦": "婦", "嬀": "媯", "㛮": "㛮", "㛼": "㛼", "媵": "媵", "嬈": "嬈", "嬨": "嬨", "嬾": "嬾", "嬾": "嬾", "⼦": "子", "⼧": "宀", "宅": "宅", "𡧈": "𡧈", "寃": "寃", "寘": "寘", "寧": "寧", "寧": "寧", "寧": "寧", "寮": "寮", "寳": "寳", "𡬘": "𡬘", "⼨": "寸", "寿": "寿", "将": "将", "⼩": "小", "尢": "尢", "⺐": "尢", "⼪": "尢", "⺏": "尣", "㞁": "㞁", "⼫": "尸", "尿": "尿", "屠": "屠", "屢": "屢", "層": "層", "履": "履", "屮": "屮", "屮": "屮", "⼬": "屮", "𡴋": "𡴋", "⼭": "山", "峀": "峀", "岍": "岍", "𡷤": "𡷤", "𡷦": "𡷦", "崙": "崙", "嵃": "嵃", "嵐": "嵐", "嵫": "嵫", "嵮": "嵮", "嵼": "嵼", "嶲": "嶲", "嶺": "嶺", "⼮": "巛", "巢": "巢", "エ": "工", "⼯": "工", "⼰": "己", "⺒": "巳", "㠯": "㠯", "巽": "巽", "⼱": "巾", "帲": "帡", "帨": "帨", "帽": "帽", "幩": "幩", "㡢": "㡢", "𢆃": "𢆃", "⼲": "干", "年": "年", "𢆟": "𢆟", "⺓": "幺", "⼳": "幺", "⼴": "广", "度": "度", "㡼": "㡼", "庰": "庰", "庳": "庳", "庶": "庶", "廊": "廊", "廊": "廊", "廉": "廉", "廒": "廒", "廓": "廓", "廙": "廙", "廬": "廬", "⼵": "廴", "廾": "廾", "⼶": "廾", "𢌱": "𢌱", "𢌱": "𢌱", "弄": "弄", "⼷": "弋", "⼸": "弓", "弢": "弢", "弢": "弢", "⼹": "彐", "⺔": "彑", "当": "当", "㣇": "㣇", "⼺": "彡", "形": "形", "彩": "彩", "彫": "彫", "⼻": "彳", "律": "律", "㣣": "㣣", "徚": "徚", "復": "復", "徭": "徭", "⼼": "心", "⺖": "忄", "⺗": "㣺", "忍": "忍", "志": "志", "念": "念", "忹": "忹", "怒": "怒", "怜": "怜", "恵": "恵", "㤜": "㤜", "㤺": "㤺", "悁": "悁", "悔": "悔", "悔": "悔", "惇": "惇", "惘": "惘", "惡": "惡", "𢛔": "𢛔", "愈": "愈", "慨": "慨", "慄": "慄", "慈": "慈", "慌": "慌", "慌": "慌", "慎": "慎", "慎": "慎", "慠": "慠", "慺": "慺", "憎": "憎", "憎": "憎", "憎": "憎", "憐": "憐", "憤": "憤", "憯": "憯", "憲": "憲", "𢡄": "𢡄", "𢡊": "𢡊", "懞": "懞", "懲": "懲", "懲": "懲", "懲": "懲", "懶": "懶", "懶": "懶", "戀": "戀", "⼽": "戈", "成": "成", "戛": "戛", "戮": "戮", "戴": "戴", "⼾": "戶", "戸": "戶", "⼿": "手", "⺘": "扌", "扝": "扝", "抱": "抱", "拉": "拉", "拏": "拏", "拓": "拓", "拔": "拔", "拼": "拼", "拾": "拾", "𢬌": "𢬌", "挽": "挽", "捐": "捐", "捨": "捨", "捻": "捻", "掃": "掃", "掠": "掠", "掩": "掩", "揄": "揄", "揤": "揤", "摒": "摒", "𢯱": "𢯱", "搜": "搜", "搢": "搢", "揅": "揅", "摩": "摩", "摷": "摷", "摾": "摾", "㨮": "㨮", "搉": "㩁", "撚": "撚", "撝": "撝", "擄": "擄", "㩬": "㩬", "⽀": "支", "⽁": "攴", "⺙": "攵", "敏": "敏", "敏": "敏", "敖": "敖", "敬": "敬", "數": "數", "𣀊": "𣀊", "⽂": "文", "⻫": "斉", "⽃": "斗", "料": "料", "⽄": "斤", "⽅": "方", "旅": "旅", "⽆": "无", "⺛": "旡", "既": "既", "旣": "旣", "⽇": "日", "易": "易", "曶": "㫚", "㫤": "㫤", "晉": "晉", "晩": "晚", "晴": "晴", "晴": "晴", "暑": "暑", "暑": "暑", "暈": "暈", "㬈": "㬈", "暜": "暜", "暴": "暴", "曆": "曆", "㬙": "㬙", "𣊸": "𣊸", "⽈": "曰", "更": "更", "書": "書", "⽉": "月", "𣍟": "𣍟", "肦": "朌", "胐": "朏", "胊": "朐", "脁": "朓", "胶": "㬵", "朗": "朗", "朗": "朗", "朗": "朗", "脧": "朘", "望": "望", "望": "望", "幐": "㬺", "䐠": "㬻", "𣎓": "𣎓", "膧": "朣", "𣎜": "𣎜", "⽊": "木", "李": "李", "杓": "杓", "杖": "杖", "杞": "杞", "𣏃": "𣏃", "柿": "杮", "杻": "杻", "枅": "枅", "林": "林", "㭉": "㭉", "𣏕": "𣏕", "柳": "柳", "柺": "柺", "栗": "栗", "栟": "栟", "桒": "桒", "𣑭": "𣑭", "梁": "梁", "梅": "梅", "梅": "梅", "梎": "梎", "梨": "梨", "椔": "椔", "楂": "楂", "㮝": "㮝", "㮝": "㮝", "槩": "㮣", "樧": "榝", "榣": "榣", "槪": "槪", "樂": "樂", "樂": "樂", "樂": "樂", "樓": "樓", "𣚣": "𣚣", "檨": "檨", "櫓": "櫓", "櫛": "櫛", "欄": "欄", "㰘": "㰘", "⽋": "欠", "次": "次", "𣢧": "𣢧", "歔": "歔", "㱎": "㱎", "⽌": "止", "⻭": "歯", "歲": "歲", "歷": "歷", "歹": "歹", "⽍": "歹", "⺞": "歺", "殟": "殟", "殮": "殮", "⽎": "殳", "殺": "殺", "殺": "殺", "殺": "殺", "殻": "殻", "𣪍": "𣪍", "⽏": "毋", "⺟": "母", "𣫺": "𣫺", "⽐": "比", "⽑": "毛", "⽒": "氏", "⺠": "民", "⽓": "气", "⽔": "水", "⺡": "氵", "⺢": "氺", "汎": "汎", "汧": "汧", "沈": "沈", "沿": "沿", "泌": "泌", "泍": "泍", "泥": "泥", "𣲼": "𣲼", "洛": "洛", "洞": "洞", "洴": "洴", "派": "派", "流": "流", "流": "流", "流": "流", "洖": "洖", "浩": "浩", "浪": "浪", "海": "海", "海": "海", "浸": "浸", "涅": "涅", "𣴞": "𣴞", "淋": "淋", "淚": "淚", "淪": "淪", "淹": "淹", "渚": "渚", "港": "港", "湮": "湮", "潙": "溈", "滋": "滋", "滋": "滋", "溜": "溜", "溺": "溺", "滇": "滇", "滑": "滑", "滛": "滛", "㴳": "㴳", "漏": "漏", "漢": "漢", "漢": "漢", "漣": "漣", "𣻑": "𣻑", "潮": "潮", "𣽞": "𣽞", "𣾎": "𣾎", "濆": "濆", "濫": "濫", "濾": "濾", "瀛": "瀛", "瀞": "瀞", "瀞": "瀞", "瀹": "瀹", "灊": "灊", "㶖": "㶖", "⽕": "火", "⺣": "灬", "灰": "灰", "灷": "灷", "災": "災", "炙": "炙", "炭": "炭", "烈": "烈", "烙": "烙", "煮": "煮", "煮": "煮", "𤉣": "𤉣", "煅": "煅", "煉": "煉", "𤋮": "𤋮", "熜": "熜", "燎": "燎", "燐": "燐", "𤎫": "𤎫", "爐": "爐", "爛": "爛", "爨": "爨", "⽖": "爪", "爫": "爫", "⺤": "爫", "爵": "爵", "爵": "爵", "⽗": "父", "⽘": "爻", "⺦": "丬", "⽙": "爿", "⽚": "片", "牐": "牐", "⽛": "牙", "𤘈": "𤘈", "⽜": "牛", "牢": "牢", "犀": "犀", "犕": "犕", "⽝": "犬", "⺨": "犭", "犯": "犯", "狀": "狀", "𤜵": "𤜵", "狼": "狼", "猪": "猪", "猪": "猪", "𤠔": "𤠔", "獵": "獵", "獺": "獺", "⽞": "玄", "率": "率", "率": "率", "⽟": "玉", "王": "王", "㺬": "㺬", "玥": "玥", "玲": "玲", "㺸": "㺸", "㺸": "㺸", "珞": "珞", "琉": "琉", "理": "理", "琢": "琢", "瑇": "瑇", "瑜": "瑜", "瑩": "瑩", "瑱": "瑱", "瑱": "瑱", "璅": "璅", "璉": "璉", "璘": "璘", "瓊": "瓊", "⽠": "瓜", "⽡": "瓦", "㼛": "㼛", "甆": "甆", "⽢": "甘", "⽣": "生", "甤": "甤", "⽤": "用", "⽥": "田", "画": "画", "甾": "甾", "𤰶": "𤰶", "留": "留", "略": "略", "異": "異", "異": "異", "𤲒": "𤲒", "⽦": "疋", "⽧": "疒", "痢": "痢", "瘐": "瘐", "瘟": "瘟", "瘝": "瘝", "療": "療", "癩": "癩", "⽨": "癶", "⽩": "白", "𤾡": "𤾡", "𤾸": "𤾸", "⽪": "皮", "⽫": "皿", "𥁄": "𥁄", "㿼": "㿼", "益": "益", "益": "益", "盛": "盛", "盧": "盧", "䀈": "䀈", "⽬": "目", "直": "直", "直": "直", "𥃲": "𥃲", "𥃳": "𥃳", "省": "省", "䀘": "䀘", "𥄙": "𥄙", "眞": "眞", "真": "真", "真": "真", "𥄳": "𥄳", "着": "着", "睊": "睊", "睊": "睊", "鿃": "䀹", "䀹": "䀹", "䀹": "䀹", "晣": "䀿", "䁆": "䁆", "瞋": "瞋", "𥉉": "𥉉", "瞧": "瞧", "⽭": "矛", "⽮": "矢", "⽯": "石", "䂖": "䂖", "𥐝": "𥐝", "硏": "研", "硎": "硎", "硫": "硫", "碌": "碌", "碌": "碌", "碑": "碑", "磊": "磊", "磌": "磌", "磌": "磌", "磻": "磻", "䃣": "䃣", "礪": "礪", "⽰": "示", "⺭": "礻", "礼": "礼", "社": "社", "祈": "祈", "祉": "祉", "𥘦": "𥘦", "祐": "祐", "祖": "祖", "祖": "祖", "祝": "祝", "神": "神", "祥": "祥", "視": "視", "視": "視", "祿": "祿", "𥚚": "𥚚", "禍": "禍", "禎": "禎", "福": "福", "福": "福", "𥛅": "𥛅", "禮": "禮", "⽱": "禸", "⽲": "禾", "秊": "秊", "䄯": "䄯", "秫": "秫", "稜": "稜", "穊": "穊", "穀": "穀", "穀": "穀", "穏": "穏", "⽳": "穴", "突": "突", "𥥼": "𥥼", "窱": "窱", "立": "立", "⽴": "立", "⻯": "竜", "𥪧": "𥪧", "𥪧": "𥪧", "竮": "竮", "⽵": "竹", "笠": "笠", "節": "節", "節": "節", "䈂": "䈂", "𥮫": "𥮫", "篆": "篆", "䈧": "䈧", "築": "築", "𥲀": "𥲀", "𥳐": "𥳐", "簾": "簾", "籠": "籠", "⽶": "米", "类": "类", "粒": "粒", "精": "精", "糒": "糒", "糖": "糖", "糨": "糨", "䊠": "䊠", "糣": "糣", "糧": "糧", "⽷": "糸", "⺯": "糹", "𥾆": "𥾆", "紀": "紀", "紐": "紐", "索": "索", "累": "累", "絶": "絕", "絣": "絣", "絛": "絛", "綠": "綠", "綾": "綾", "緇": "緇", "練": "練", "練": "練", "練": "練", "縂": "縂", "䌁": "䌁", "縉": "縉", "縷": "縷", "繁": "繁", "繅": "繅", "𦇚": "𦇚", "䌴": "䌴", "⽸": "缶", "𦈨": "𦈨", "缾": "缾", "𦉇": "𦉇", "⽹": "网", "⺫": "罒", "⺲": "罒", "⺱": "罓", "䍙": "䍙", "署": "署", "𦋙": "𦋙", "罹": "罹", "罺": "罺", "羅": "羅", "𦌾": "𦌾", "⽺": "羊", "羕": "羕", "羚": "羚", "羽": "羽", "⽻": "羽", "翺": "翺", "老": "老", "⽼": "老", "⺹": "耂", "者": "者", "者": "者", "者": "者", "⽽": "而", "𦓚": "𦓚", "⽾": "耒", "𦔣": "𦔣", "⽿": "耳", "聆": "聆", "聠": "聠", "𦖨": "𦖨", "聯": "聯", "聰": "聰", "聾": "聾", "⾀": "聿", "⺺": "肀", "⾁": "肉", "肋": "肋", "肭": "肭", "育": "育", "䏕": "䏕", "䏙": "䏙", "腁": "胼", "脃": "脃", "脾": "脾", "䐋": "䐋", "朡": "朡", "𦞧": "𦞧", "𦞵": "𦞵", "朦": "䑃", "臘": "臘", "⾂": "臣", "臨": "臨", "⾃": "自", "臭": "臭", "⾄": "至", "⾅": "臼", "舁": "舁", "舁": "舁", "舄": "舄", "⾆": "舌", "舘": "舘", "⾇": "舛", "⾈": "舟", "䑫": "䑫", "⾉": "艮", "良": "良", "⾊": "色", "⾋": "艸", "艹": "艹", "艹": "艹", "⺾": "艹", "⺿": "艹", "⻀": "艹", "芋": "芋", "芑": "芑", "芝": "芝", "花": "花", "芳": "芳", "芽": "芽", "若": "若", "若": "若", "苦": "苦", "𦬼": "𦬼", "茶": "茶", "荒": "荒", "荣": "荣", "茝": "茝", "茣": "茣", "莽": "莽", "荓": "荓", "菉": "菉", "菊": "菊", "菌": "菌", "菜": "菜", "菧": "菧", "華": "華", "菱": "菱", "著": "著", "著": "著", "𦰶": "𦰶", "莭": "莭", "落": "落", "葉": "葉", "蔿": "蒍", "𦳕": "𦳕", "𦵫": "𦵫", "蓮": "蓮", "蓱": "蓱", "蓳": "蓳", "蓼": "蓼", "蔖": "蔖", "䔫": "䔫", "蕤": "蕤", "𦼬": "𦼬", "藍": "藍", "䕝": "䕝", "𦾱": "𦾱", "䕡": "䕡", "藺": "藺", "蘆": "蘆", "䕫": "䕫", "蘒": "蘒", "蘭": "蘭", "𧃒": "𧃒", "虁": "蘷", "蘿": "蘿", "⾌": "虍", "⻁": "虎", "虐": "虐", "虜": "虜", "虜": "虜", "虧": "虧", "虩": "虩", "⾍": "虫", "蚩": "蚩", "蚈": "蚈", "蛢": "蛢", "蜎": "蜎", "蜨": "蜨", "蝫": "蝫", "蟡": "蟡", "蝹": "蝹", "蝹": "蝹", "螆": "螆", "䗗": "䗗", "𧏊": "𧏊", "螺": "螺", "蠁": "蠁", "䗹": "䗹", "蠟": "蠟", "⾎": "血", "行": "行", "⾏": "行", "衠": "衠", "衣": "衣", "⾐": "衣", "⻂": "衤", "裂": "裂", "𧙧": "𧙧", "裏": "裏", "裗": "裗", "裞": "裞", "裡": "裡", "裸": "裸", "裺": "裺", "䘵": "䘵", "褐": "褐", "襁": "襁", "襤": "襤", "⾑": "襾", "⻄": "西", "⻃": "覀", "覆": "覆", "見": "見", "⾒": "見", "𧢮": "𧢮", "⻅": "见", "⾓": "角", "⾔": "言", "𧥦": "𧥦", "詽": "訮", "訞": "䚶", "䚾": "䚾", "䛇": "䛇", "誠": "誠", "說": "說", "說": "說", "調": "調", "請": "請", "諒": "諒", "論": "論", "諭": "諭", "諭": "諭", "諸": "諸", "諸": "諸", "諾": "諾", "諾": "諾", "謁": "謁", "謁": "謁", "謹": "謹", "謹": "謹", "識": "識", "讀": "讀", "讏": "讆", "變": "變", "變": "變", "⻈": "讠", "⾕": "谷", "⾖": "豆", "豈": "豈", "豕": "豕", "⾗": "豕", "豣": "豜", "⾘": "豸", "𧲨": "𧲨", "⾙": "貝", "貫": "貫", "賁": "賁", "賂": "賂", "賈": "賈", "賓": "賓", "贈": "贈", "贈": "贈", "贛": "贛", "⻉": "贝", "⾚": "赤", "⾛": "走", "起": "起", "趆": "赿", "𧻓": "𧻓", "𧼯": "𧼯", "⾜": "足", "跋": "跋", "趼": "趼", "跺": "跥", "路": "路", "跰": "跰", "躛": "躗", "⾝": "身", "車": "車", "⾞": "車", "軔": "軔", "輧": "軿", "輦": "輦", "輪": "輪", "輸": "輸", "輸": "輸", "輻": "輻", "轢": "轢", "⻋": "车", "⾟": "辛", "辞": "辞", "辰": "辰", "⾠": "辰", "⾡": "辵", "辶": "辶", "⻌": "辶", "⻍": "辶", "巡": "巡", "連": "連", "逸": "逸", "逸": "逸", "遲": "遲", "遼": "遼", "𨗒": "𨗒", "𨗭": "𨗭", "邏": "邏", "⾢": "邑", "邔": "邔", "郎": "郎", "郞": "郎", "郞": "郎", "郱": "郱", "都": "都", "𨜮": "𨜮", "鄑": "鄑", "鄛": "鄛", "⾣": "酉", "酪": "酪", "醙": "醙", "醴": "醴", "⾤": "釆", "里": "里", "⾥": "里", "量": "量", "金": "金", "⾦": "金", "鈴": "鈴", "鈸": "鈸", "鉶": "鉶", "鋗": "鋗", "鋘": "鋘", "鉼": "鉼", "錄": "錄", "鍊": "鍊", "鎮": "鎭", "鏹": "鏹", "鐕": "鐕", "𨯺": "𨯺", "⻐": "钅", "⻑": "長", "⾧": "長", "⻒": "镸", "⻓": "长", "⾨": "門", "開": "開", "䦕": "䦕", "閭": "閭", "閷": "閷", "𨵷": "𨵷", "⻔": "门", "⾩": "阜", "⻏": "阝", "⻖": "阝", "阮": "阮", "陋": "陋", "降": "降", "陵": "陵", "陸": "陸", "陼": "陼", "隆": "隆", "隣": "隣", "䧦": "䧦", "⾪": "隶", "隷": "隷", "隸": "隷", "隸": "隷", "⾫": "隹", "雃": "雃", "離": "離", "難": "難", "難": "難", "⾬": "雨", "零": "零", "雷": "雷", "霣": "霣", "𩅅": "𩅅", "露": "露", "靈": "靈", "⾭": "靑", "⻘": "青", "靖": "靖", "靖": "靖", "𩇟": "𩇟", "⾮": "非", "⾯": "面", "𩈚": "𩈚", "⾰": "革", "䩮": "䩮", "䩶": "䩶", "⾱": "韋", "韛": "韛", "韠": "韠", "⻙": "韦", "⾲": "韭", "𩐊": "𩐊", "⾳": "音", "響": "響", "響": "響", "⾴": "頁", "䪲": "䪲", "頋": "頋", "頋": "頋", "頋": "頋", "領": "領", "頩": "頩", "𩒖": "𩒖", "頻": "頻", "頻": "頻", "類": "類", "⻚": "页", "⾵": "風", "𩖶": "𩖶", "⻛": "风", "⾶": "飛", "⻜": "飞", "⻝": "食", "⾷": "食", "⻟": "飠", "飢": "飢", "飯": "飯", "飼": "飼", "䬳": "䬳", "館": "館", "餩": "餩", "⻠": "饣", "⾸": "首", "⾹": "香", "馧": "馧", "⾺": "馬", "駂": "駂", "駱": "駱", "駾": "駾", "驪": "驪", "⻢": "马", "⾻": "骨", "䯎": "䯎", "⾼": "高", "⾽": "髟", "𩬰": "𩬰", "鬒": "鬒", "鬒": "鬒", "⾾": "鬥", "⾿": "鬯", "⿀": "鬲", "⿁": "鬼", "⻤": "鬼", "⿂": "魚", "魯": "魯", "鱀": "鱀", "鱗": "鱗", "⻥": "鱼", "⿃": "鳥", "鳽": "鳽", "䳎": "䳎", "鵧": "鵧", "䳭": "䳭", "𪃎": "𪃎", "鶴": "鶴", "𪄅": "𪄅", "䳸": "䳸", "鷺": "鷺", "𪈎": "𪈎", "鸞": "鸞", "鹃": "鹂", "⿄": "鹵", "鹿": "鹿", "⿅": "鹿", "𪊑": "𪊑", "麗": "麗", "麟": "麟", "⿆": "麥", "⻨": "麦", "麻": "麻", "⿇": "麻", "𪎒": "𪎒", "⿈": "黃", "⻩": "黄", "⿉": "黍", "黎": "黎", "䵖": "䵖", "⿊": "黑", "黒": "黑", "墨": "墨", "黹": "黹", "⿋": "黹", "⿌": "黽", "鼅": "鼅", "黾": "黾", "⿍": "鼎", "鼏": "鼏", "⿎": "鼓", "鼖": "鼖", "⿏": "鼠", "鼻": "鼻", "⿐": "鼻", "齃": "齃", "⿑": "齊", "⻬": "齐", "⿒": "齒", "𪘀": "𪘀", "⻮": "齿", "龍": "龍", "⿓": "龍", "龎": "龎", "⻰": "龙", "龜": "龜", "龜": "龜", "龜": "龜", "⿔": "龜", "⻳": "龟", "⿕": "龠" } },{}],50:[function(require,module,exports){ 'use strict'; var data = require('./data.json'); function escapeRegexp(str) { return str.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); } var REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g'); function replace_fn(match) { return data[match]; } function unhomoglyph(str) { return str.replace(REPLACE_RE, replace_fn); } module.exports = unhomoglyph; },{"./data.json":49}],51:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var punycode = require('punycode'); var util = require('./util'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"./util":52,"punycode":32,"querystring":46}],52:[function(require,module,exports){ 'use strict'; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; },{}],53:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.ReEmitter = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd Copyright 2017 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 */ var ReEmitter = /*#__PURE__*/function () { function ReEmitter(target) { (0, _classCallCheck2["default"])(this, ReEmitter); this.target = target; // We keep one bound event handler for each event name so we know // what event is arriving this.boundHandlers = {}; } (0, _createClass2["default"])(ReEmitter, [{ key: "_handleEvent", value: function _handleEvent(eventName) { var _this$target; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } (_this$target = this.target).emit.apply(_this$target, [eventName].concat(args)); } }, { key: "reEmit", value: function reEmit(source, eventNames) { // We include the source as the last argument for event handlers which may need it, // such as read receipt listeners on the client class which won't have the context // of the room. var forSource = function forSource(handler) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } handler.apply(void 0, args.concat([source])); }; var _iterator = _createForOfIteratorHelper(eventNames), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var eventName = _step.value; if (this.boundHandlers[eventName] === undefined) { this.boundHandlers[eventName] = this._handleEvent.bind(this, eventName); } var boundHandler = forSource.bind(this, this.boundHandlers[eventName]); source.on(eventName, boundHandler); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } }]); return ReEmitter; }(); exports.ReEmitter = ReEmitter; },{"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12}],54:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.AutoDiscovery = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _logger = require("./logger"); var _url = require("url"); /* Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 auto-discovery */ // Dev note: Auto discovery is part of the spec. // See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery /** * Description for what an automatically discovered client configuration * would look like. Although this is a class, it is recommended that it * be treated as an interface definition rather than as a class. * * Additional properties than those defined here may be present, and * should follow the Java package naming convention. */ var DiscoveredClientConfig = // eslint-disable-line no-unused-vars // Dev note: this is basically a copy/paste of the .well-known response // object as defined in the spec. It does have additional information, // however. Overall, this exists to serve as a place for documentation // and not functionality. // See https://matrix.org/docs/spec/client_server/r0.4.0.html#get-well-known-matrix-client function DiscoveredClientConfig() { (0, _classCallCheck2["default"])(this, DiscoveredClientConfig); /** * The homeserver configuration the client should use. This will * always be present on the object. * @type {{state: string, base_url: string}} The configuration. */ this["m.homeserver"] = { /** * The lookup result state. If this is anything other than * AutoDiscovery.SUCCESS then base_url may be falsey. Additionally, * if this is not AutoDiscovery.SUCCESS then the client should * assume the other properties in the client config (such as * the identity server configuration) are not valid. */ state: AutoDiscovery.PROMPT, /** * If the state is AutoDiscovery.FAIL_ERROR or .FAIL_PROMPT * then this will contain a human-readable (English) message * for what went wrong. If the state is none of those previously * mentioned, this will be falsey. */ error: "Something went wrong", /** * The base URL clients should use to talk to the homeserver, * particularly for the login process. May be falsey if the * state is not AutoDiscovery.SUCCESS. */ base_url: "https://matrix.org" }; /** * The identity server configuration the client should use. This * will always be present on teh object. * @type {{state: string, base_url: string}} The configuration. */ this["m.identity_server"] = { /** * The lookup result state. If this is anything other than * AutoDiscovery.SUCCESS then base_url may be falsey. */ state: AutoDiscovery.PROMPT, /** * The base URL clients should use for interacting with the * identity server. May be falsey if the state is not * AutoDiscovery.SUCCESS. */ base_url: "https://vector.im" }; }; /** * Utilities for automatically discovery resources, such as homeservers * for users to log in to. */ var AutoDiscovery = /*#__PURE__*/function () { function AutoDiscovery() { (0, _classCallCheck2["default"])(this, AutoDiscovery); } (0, _createClass2["default"])(AutoDiscovery, null, [{ key: "fromDiscoveryConfig", /** * Validates and verifies client configuration information for purposes * of logging in. Such information includes the homeserver URL * and identity server URL the client would want. Additional details * may also be included, and will be transparently brought into the * response object unaltered. * @param {string} wellknown The configuration object itself, as returned * by the .well-known auto-discovery endpoint. * @return {Promise} Resolves to the verified * configuration, which may include error states. Rejects on unexpected * failure, not when verification fails. */ value: function () { var _fromDiscoveryConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(wellknown) { var clientConfig, hsUrl, hsVersions, isUrl, failingClientConfig, isResponse; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // Step 1 is to get the config, which is provided to us here. // We default to an error state to make the first few checks easier to // write. We'll update the properties of this object over the duration // of this function. clientConfig = { "m.homeserver": { state: AutoDiscovery.FAIL_ERROR, error: AutoDiscovery.ERROR_INVALID, base_url: null }, "m.identity_server": { // Technically, we don't have a problem with the identity server // config at this point. state: AutoDiscovery.PROMPT, error: null, base_url: null } }; if (!(!wellknown || !wellknown["m.homeserver"])) { _context.next = 6; break; } _logger.logger.error("No m.homeserver key in config"); clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT; clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID; return _context.abrupt("return", Promise.resolve(clientConfig)); case 6: if (wellknown["m.homeserver"]["base_url"]) { _context.next = 11; break; } _logger.logger.error("No m.homeserver base_url in config"); clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT; clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL; return _context.abrupt("return", Promise.resolve(clientConfig)); case 11: // Step 2: Make sure the homeserver URL is valid *looking*. We'll make // sure it points to a homeserver in Step 3. hsUrl = this._sanitizeWellKnownUrl(wellknown["m.homeserver"]["base_url"]); if (hsUrl) { _context.next = 16; break; } _logger.logger.error("Invalid base_url for m.homeserver"); clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL; return _context.abrupt("return", Promise.resolve(clientConfig)); case 16: _context.next = 18; return this._fetchWellKnownObject("".concat(hsUrl, "/_matrix/client/versions")); case 18: hsVersions = _context.sent; if (!(!hsVersions || !hsVersions.raw["versions"])) { _context.next = 24; break; } _logger.logger.error("Invalid /versions response"); clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER; // Supply the base_url to the caller because they may be ignoring liveliness // errors, like this one. clientConfig["m.homeserver"].base_url = hsUrl; return _context.abrupt("return", Promise.resolve(clientConfig)); case 24: // Step 4: Now that the homeserver looks valid, update our client config. clientConfig["m.homeserver"] = { state: AutoDiscovery.SUCCESS, error: null, base_url: hsUrl }; // Step 5: Try to pull out the identity server configuration isUrl = ""; if (!wellknown["m.identity_server"]) { _context.next = 41; break; } // We prepare a failing identity server response to save lines later // in this branch. failingClientConfig = { "m.homeserver": clientConfig["m.homeserver"], "m.identity_server": { state: AutoDiscovery.FAIL_PROMPT, error: AutoDiscovery.ERROR_INVALID_IS, base_url: null } }; // Step 5a: Make sure the URL is valid *looking*. We'll make sure it // points to an identity server in Step 5b. isUrl = this._sanitizeWellKnownUrl(wellknown["m.identity_server"]["base_url"]); if (isUrl) { _context.next = 33; break; } _logger.logger.error("Invalid base_url for m.identity_server"); failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL; return _context.abrupt("return", Promise.resolve(failingClientConfig)); case 33: _context.next = 35; return this._fetchWellKnownObject("".concat(isUrl, "/_matrix/identity/api/v1")); case 35: isResponse = _context.sent; if (!(!isResponse || !isResponse.raw || isResponse.action !== "SUCCESS")) { _context.next = 41; break; } _logger.logger.error("Invalid /api/v1 response"); failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER; // Supply the base_url to the caller because they may be ignoring // liveliness errors, like this one. failingClientConfig["m.identity_server"].base_url = isUrl; return _context.abrupt("return", Promise.resolve(failingClientConfig)); case 41: // Step 6: Now that the identity server is valid, or never existed, // populate the IS section. if (isUrl && isUrl.length > 0) { clientConfig["m.identity_server"] = { state: AutoDiscovery.SUCCESS, error: null, base_url: isUrl }; } // Step 7: Copy any other keys directly into the clientConfig. This is for // things like custom configuration of services. Object.keys(wellknown).map(function (k) { if (k === "m.homeserver" || k === "m.identity_server") { // Only copy selected parts of the config to avoid overwriting // properties computed by the validation logic above. var notProps = ["error", "state", "base_url"]; for (var _i = 0, _Object$keys = Object.keys(wellknown[k]); _i < _Object$keys.length; _i++) { var prop = _Object$keys[_i]; if (notProps.includes(prop)) continue; clientConfig[k][prop] = wellknown[k][prop]; } } else { // Just copy the whole thing over otherwise clientConfig[k] = wellknown[k]; } }); // Step 8: Give the config to the caller (finally) return _context.abrupt("return", Promise.resolve(clientConfig)); case 44: case "end": return _context.stop(); } } }, _callee, this); })); function fromDiscoveryConfig(_x) { return _fromDiscoveryConfig.apply(this, arguments); } return fromDiscoveryConfig; }() /** * Attempts to automatically discover client configuration information * prior to logging in. Such information includes the homeserver URL * and identity server URL the client would want. Additional details * may also be discovered, and will be transparently included in the * response object unaltered. * @param {string} domain The homeserver domain to perform discovery * on. For example, "matrix.org". * @return {Promise} Resolves to the discovered * configuration, which may include error states. Rejects on unexpected * failure, not when discovery fails. */ }, { key: "findClientConfig", value: function () { var _findClientConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(domain) { var clientConfig, wellknown; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(!domain || typeof domain !== "string" || domain.length === 0)) { _context2.next = 2; break; } throw new Error("'domain' must be a string of non-zero length"); case 2: // We use a .well-known lookup for all cases. According to the spec, we // can do other discovery mechanisms if we want such as custom lookups // however we won't bother with that here (mostly because the spec only // supports .well-known right now). // // By using .well-known, we need to ensure we at least pull out a URL // for the homeserver. We don't really need an identity server configuration // but will return one anyways (with state PROMPT) to make development // easier for clients. If we can't get a homeserver URL, all bets are // off on the rest of the config and we'll assume it is invalid too. // We default to an error state to make the first few checks easier to // write. We'll update the properties of this object over the duration // of this function. clientConfig = { "m.homeserver": { state: AutoDiscovery.FAIL_ERROR, error: AutoDiscovery.ERROR_INVALID, base_url: null }, "m.identity_server": { // Technically, we don't have a problem with the identity server // config at this point. state: AutoDiscovery.PROMPT, error: null, base_url: null } }; // Step 1: Actually request the .well-known JSON file and make sure it // at least has a homeserver definition. _context2.next = 5; return this._fetchWellKnownObject("https://".concat(domain, "/.well-known/matrix/client")); case 5: wellknown = _context2.sent; if (!(!wellknown || wellknown.action !== "SUCCESS")) { _context2.next = 11; break; } _logger.logger.error("No response or error when parsing .well-known"); if (wellknown.reason) _logger.logger.error(wellknown.reason); if (wellknown.action === "IGNORE") { clientConfig["m.homeserver"] = { state: AutoDiscovery.PROMPT, error: null, base_url: null }; } else { // this can only ever be FAIL_PROMPT at this point. clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT; clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID; } return _context2.abrupt("return", Promise.resolve(clientConfig)); case 11: return _context2.abrupt("return", AutoDiscovery.fromDiscoveryConfig(wellknown.raw)); case 12: case "end": return _context2.stop(); } } }, _callee2, this); })); function findClientConfig(_x2) { return _findClientConfig.apply(this, arguments); } return findClientConfig; }() /** * Gets the raw discovery client configuration for the given domain name. * Should only be used if there's no validation to be done on the resulting * object, otherwise use findClientConfig(). * @param {string} domain The domain to get the client config for. * @returns {Promise} Resolves to the domain's client config. Can * be an empty object. */ }, { key: "getRawClientConfig", value: function () { var _getRawClientConfig = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(domain) { var response; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(!domain || typeof domain !== "string" || domain.length === 0)) { _context3.next = 2; break; } throw new Error("'domain' must be a string of non-zero length"); case 2: _context3.next = 4; return this._fetchWellKnownObject("https://".concat(domain, "/.well-known/matrix/client")); case 4: response = _context3.sent; if (response) { _context3.next = 7; break; } return _context3.abrupt("return", {}); case 7: return _context3.abrupt("return", response.raw || {}); case 8: case "end": return _context3.stop(); } } }, _callee3, this); })); function getRawClientConfig(_x3) { return _getRawClientConfig.apply(this, arguments); } return getRawClientConfig; }() /** * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and * is suitable for the requirements laid out by .well-known auto discovery. * If valid, the URL will also be stripped of any trailing slashes. * @param {string} url The potentially invalid URL to sanitize. * @return {string|boolean} The sanitized URL or a falsey value if the URL is invalid. * @private */ }, { key: "_sanitizeWellKnownUrl", value: function _sanitizeWellKnownUrl(url) { if (!url) return false; try { // We have to try and parse the URL using the NodeJS URL // library if we're on NodeJS and use the browser's URL // library when we're in a browser. To accomplish this, we // try the NodeJS version first and fall back to the browser. var parsed = null; try { if (_url.URL) parsed = new _url.URL(url);else parsed = new URL(url); } catch (e) { parsed = new URL(url); } if (!parsed || !parsed.hostname) return false; if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false; var port = parsed.port ? ":".concat(parsed.port) : ""; var path = parsed.pathname ? parsed.pathname : ""; var saferUrl = "".concat(parsed.protocol, "//").concat(parsed.hostname).concat(port).concat(path); if (saferUrl.endsWith("/")) { saferUrl = saferUrl.substring(0, saferUrl.length - 1); } return saferUrl; } catch (e) { _logger.logger.error(e); return false; } } /** * Fetches a JSON object from a given URL, as expected by all .well-known * related lookups. If the server gives a 404 then the `action` will be * IGNORE. If the server returns something that isn't JSON, the `action` * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT. * * The returned object will be a result of the call in object form with * the following properties: * raw: The JSON object returned by the server. * action: One of SUCCESS, IGNORE, or FAIL_PROMPT. * reason: Relatively human readable description of what went wrong. * error: The actual Error, if one exists. * @param {string} url The URL to fetch a JSON object from. * @return {Promise} Resolves to the returned state. * @private */ }, { key: "_fetchWellKnownObject", value: function () { var _fetchWellKnownObject2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(url) { return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: return _context4.abrupt("return", new Promise(function (resolve, reject) { var request = require("./matrix").getRequest(); if (!request) throw new Error("No request library available"); request({ method: "GET", uri: url, timeout: 5000 }, function (err, response, body) { if (err || response && (response.statusCode < 200 || response.statusCode >= 300)) { var action = "FAIL_PROMPT"; var reason = (err ? err.message : null) || "General failure"; if (response && response.statusCode === 404) { action = "IGNORE"; reason = AutoDiscovery.ERROR_MISSING_WELLKNOWN; } resolve({ raw: {}, action: action, reason: reason, error: err }); return; } try { resolve({ raw: JSON.parse(body), action: "SUCCESS" }); } catch (e) { var _reason = AutoDiscovery.ERROR_INVALID; if (e.name === "SyntaxError") { _reason = AutoDiscovery.ERROR_INVALID_JSON; } resolve({ raw: {}, action: "FAIL_PROMPT", reason: _reason, error: e }); } }); })); case 1: case "end": return _context4.stop(); } } }, _callee4); })); function _fetchWellKnownObject(_x4) { return _fetchWellKnownObject2.apply(this, arguments); } return _fetchWellKnownObject; }() }, { key: "ERROR_INVALID", // Dev note: the constants defined here are related to but not // exactly the same as those in the spec. This is to hopefully // translate the meaning of the states in the spec, but also // support our own if needed. get: function get() { return "Invalid homeserver discovery response"; } }, { key: "ERROR_GENERIC_FAILURE", get: function get() { return "Failed to get autodiscovery configuration from server"; } }, { key: "ERROR_INVALID_HS_BASE_URL", get: function get() { return "Invalid base_url for m.homeserver"; } }, { key: "ERROR_INVALID_HOMESERVER", get: function get() { return "Homeserver URL does not appear to be a valid Matrix homeserver"; } }, { key: "ERROR_INVALID_IS_BASE_URL", get: function get() { return "Invalid base_url for m.identity_server"; } }, { key: "ERROR_INVALID_IDENTITY_SERVER", get: function get() { return "Identity server URL does not appear to be a valid identity server"; } }, { key: "ERROR_INVALID_IS", get: function get() { return "Invalid identity server discovery response"; } }, { key: "ERROR_MISSING_WELLKNOWN", get: function get() { return "No .well-known JSON file found"; } }, { key: "ERROR_INVALID_JSON", get: function get() { return "Invalid JSON"; } }, { key: "ALL_ERRORS", get: function get() { return [AutoDiscovery.ERROR_INVALID, AutoDiscovery.ERROR_GENERIC_FAILURE, AutoDiscovery.ERROR_INVALID_HS_BASE_URL, AutoDiscovery.ERROR_INVALID_HOMESERVER, AutoDiscovery.ERROR_INVALID_IS_BASE_URL, AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER, AutoDiscovery.ERROR_INVALID_IS, AutoDiscovery.ERROR_MISSING_WELLKNOWN, AutoDiscovery.ERROR_INVALID_JSON]; } /** * The auto discovery failed. The client is expected to communicate * the error to the user and refuse logging in. * @return {string} * @constructor */ }, { key: "FAIL_ERROR", get: function get() { return "FAIL_ERROR"; } /** * The auto discovery failed, however the client may still recover * from the problem. The client is recommended to that the same * action it would for PROMPT while also warning the user about * what went wrong. The client may also treat this the same as * a FAIL_ERROR state. * @return {string} * @constructor */ }, { key: "FAIL_PROMPT", get: function get() { return "FAIL_PROMPT"; } /** * The auto discovery didn't fail but did not find anything of * interest. The client is expected to prompt the user for more * information, or fail if it prefers. * @return {string} * @constructor */ }, { key: "PROMPT", get: function get() { return "PROMPT"; } /** * The auto discovery was successful. * @return {string} * @constructor */ }, { key: "SUCCESS", get: function get() { return "SUCCESS"; } }]); return AutoDiscovery; }(); exports.AutoDiscovery = AutoDiscovery; },{"./logger":95,"./matrix":96,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/regenerator":27,"url":51}],55:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixBaseApis = MatrixBaseApis; var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _serviceTypes = require("./service-types"); var _logger = require("./logger"); var _pushprocessor = require("./pushprocessor"); var utils = _interopRequireWildcard(require("./utils")); var _httpApi = require("./http-api"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function termsUrlForService(serviceType, baseUrl) { switch (serviceType) { case _serviceTypes.SERVICE_TYPES.IS: return baseUrl + _httpApi.PREFIX_IDENTITY_V2 + '/terms'; case _serviceTypes.SERVICE_TYPES.IM: return baseUrl + '/_matrix/integrations/v1/terms'; default: throw new Error('Unsupported service type'); } } /** * Low-level wrappers for the Matrix APIs * * @constructor * * @param {Object} opts Configuration options * * @param {string} opts.baseUrl Required. The base URL to the client-server * HTTP API. * * @param {string} opts.idBaseUrl Optional. The base identity server URL for * identity server requests. * * @param {Function} opts.request Required. The function to invoke for HTTP * requests. The value of this property is typically require("request") * as it returns a function which meets the required interface. See * {@link requestFunction} for more information. * * @param {string} opts.accessToken The access_token for this user. * * @param {IdentityServerProvider} [opts.identityServer] * Optional. A provider object with one function `getAccessToken`, which is a * callback that returns a Promise of an identity access token to supply * with identity requests. If the object is unset, no access token will be * supplied. * See also https://github.com/vector-im/element-web/issues/10615 which seeks to * replace the previous approach of manual access tokens params with this * callback throughout the SDK. * * @param {Number=} opts.localTimeoutMs Optional. The default maximum amount of * time to wait before timing out HTTP requests. If not specified, there is no * timeout. * * @param {Object} opts.queryParams Optional. Extra query parameters to append * to all requests with this client. Useful for application services which require * ?user_id=. * * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use * Authorization header instead of query param to send the access token to the server. */ function MatrixBaseApis(opts) { utils.checkObjectHasKeys(opts, ["baseUrl", "request"]); this.baseUrl = opts.baseUrl; this.idBaseUrl = opts.idBaseUrl; this.identityServer = opts.identityServer; var httpOpts = { baseUrl: opts.baseUrl, idBaseUrl: opts.idBaseUrl, accessToken: opts.accessToken, request: opts.request, prefix: _httpApi.PREFIX_R0, onlyData: true, extraParams: opts.queryParams, localTimeoutMs: opts.localTimeoutMs, useAuthorizationHeader: opts.useAuthorizationHeader }; this._http = new _httpApi.MatrixHttpApi(this, httpOpts); this._txnCtr = 0; } /** * Get the Homeserver URL of this client * @return {string} Homeserver URL of this client */ MatrixBaseApis.prototype.getHomeserverUrl = function () { return this.baseUrl; }; /** * Get the Identity Server URL of this client * @param {boolean} stripProto whether or not to strip the protocol from the URL * @return {string} Identity Server URL of this client */ MatrixBaseApis.prototype.getIdentityServerUrl = function () { var stripProto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (stripProto && (this.idBaseUrl.startsWith("http://") || this.idBaseUrl.startsWith("https://"))) { return this.idBaseUrl.split("://")[1]; } return this.idBaseUrl; }; /** * Set the Identity Server URL of this client * @param {string} url New Identity Server URL */ MatrixBaseApis.prototype.setIdentityServerUrl = function (url) { this.idBaseUrl = utils.ensureNoTrailingSlash(url); this._http.setIdBaseUrl(this.idBaseUrl); }; /** * Get the access token associated with this account. * @return {?String} The access_token or null */ MatrixBaseApis.prototype.getAccessToken = function () { return this._http.opts.accessToken || null; }; /** * @return {boolean} true if there is a valid access_token for this client. */ MatrixBaseApis.prototype.isLoggedIn = function () { return this._http.opts.accessToken !== undefined; }; /** * Make up a new transaction id * * @return {string} a new, unique, transaction id */ MatrixBaseApis.prototype.makeTxnId = function () { return "m" + new Date().getTime() + "." + this._txnCtr++; }; // Registration/Login operations // ============================= /** * Check whether a username is available prior to registration. An error response * indicates an invalid/unavailable username. * @param {string} username The username to check the availability of. * @return {Promise} Resolves: to `true`. */ MatrixBaseApis.prototype.isUsernameAvailable = function (username) { return this._http.authedRequest(undefined, "GET", '/register/available', { username: username }).then(function (response) { return response.available; }); }; /** * @param {string} username * @param {string} password * @param {string} sessionId * @param {Object} auth * @param {Object} bindThreepids Set key 'email' to true to bind any email * threepid uses during registration in the ID server. Set 'msisdn' to * true to bind msisdn. * @param {string} guestAccessToken * @param {string} inhibitLogin * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.register = function (username, password, sessionId, auth, bindThreepids, guestAccessToken, inhibitLogin, callback) { // backwards compat if (bindThreepids === true) { bindThreepids = { email: true }; } else if (bindThreepids === null || bindThreepids === undefined) { bindThreepids = {}; } if (typeof inhibitLogin === 'function') { callback = inhibitLogin; inhibitLogin = undefined; } if (sessionId) { auth.session = sessionId; } var params = { auth: auth }; if (username !== undefined && username !== null) { params.username = username; } if (password !== undefined && password !== null) { params.password = password; } if (bindThreepids.email) { params.bind_email = true; } if (bindThreepids.msisdn) { params.bind_msisdn = true; } if (guestAccessToken !== undefined && guestAccessToken !== null) { params.guest_access_token = guestAccessToken; } if (inhibitLogin !== undefined && inhibitLogin !== null) { params.inhibit_login = inhibitLogin; } // Temporary parameter added to make the register endpoint advertise // msisdn flows. This exists because there are clients that break // when given stages they don't recognise. This parameter will cease // to be necessary once these old clients are gone. // Only send it if we send any params at all (the password param is // mandatory, so if we send any params, we'll send the password param) if (password !== undefined && password !== null) { params.x_show_msisdn = true; } return this.registerRequest(params, undefined, callback); }; /** * Register a guest account. * @param {Object=} opts Registration options * @param {Object} opts.body JSON HTTP body to provide. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.registerGuest = function (opts, callback) { opts = opts || {}; opts.body = opts.body || {}; return this.registerRequest(opts.body, "guest", callback); }; /** * @param {Object} data parameters for registration request * @param {string=} kind type of user to register. may be "guest" * @param {module:client.callback=} callback * @return {Promise} Resolves: to the /register response * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.registerRequest = function (data, kind, callback) { var params = {}; if (kind) { params.kind = kind; } return this._http.request(callback, "POST", "/register", params, data); }; /** * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.loginFlows = function (callback) { return this._http.request(callback, "GET", "/login"); }; /** * @param {string} loginType * @param {Object} data * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.login = function (loginType, data, callback) { var _this = this; var login_data = { type: loginType }; // merge data into login_data utils.extend(login_data, data); return this._http.authedRequest(function (error, response) { if (response && response.access_token && response.user_id) { _this._http.opts.accessToken = response.access_token; _this.credentials = { userId: response.user_id }; } if (callback) { callback(error, response); } }, "POST", "/login", undefined, login_data); }; /** * @param {string} user * @param {string} password * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.loginWithPassword = function (user, password, callback) { return this.login("m.login.password", { user: user, password: password }, callback); }; /** * @param {string} relayState URL Callback after SAML2 Authentication * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.loginWithSAML2 = function (relayState, callback) { return this.login("m.login.saml2", { relay_state: relayState }, callback); }; /** * @param {string} redirectUrl The URL to redirect to after the HS * authenticates with CAS. * @return {string} The HS URL to hit to begin the CAS login process. */ MatrixBaseApis.prototype.getCasLoginUrl = function (redirectUrl) { return this.getSsoLoginUrl(redirectUrl, "cas"); }; /** * @param {string} redirectUrl The URL to redirect to after the HS * authenticates with the SSO. * @param {string} loginType The type of SSO login we are doing (sso or cas). * Defaults to 'sso'. * @return {string} The HS URL to hit to begin the SSO login process. */ MatrixBaseApis.prototype.getSsoLoginUrl = function (redirectUrl, loginType) { if (loginType === undefined) { loginType = "sso"; } return this._http.getUrl("/login/" + loginType + "/redirect", { "redirectUrl": redirectUrl }, _httpApi.PREFIX_R0); }; /** * @param {string} token Login token previously received from homeserver * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.loginWithToken = function (token, callback) { return this.login("m.login.token", { token: token }, callback); }; /** * Logs out the current session. * Obviously, further calls that require authorisation should fail after this * method is called. The state of the MatrixClient object is not affected: * it is up to the caller to either reset or destroy the MatrixClient after * this method succeeds. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: On success, the empty object */ MatrixBaseApis.prototype.logout = function (callback) { return this._http.authedRequest(callback, "POST", '/logout'); }; /** * Deactivates the logged-in account. * Obviously, further calls that require authorisation should fail after this * method is called. The state of the MatrixClient object is not affected: * it is up to the caller to either reset or destroy the MatrixClient after * this method succeeds. * @param {object} auth Optional. Auth data to supply for User-Interactive auth. * @param {boolean} erase Optional. If set, send as `erase` attribute in the * JSON request body, indicating whether the account should be erased. Defaults * to false. * @return {Promise} Resolves: On success, the empty object */ MatrixBaseApis.prototype.deactivateAccount = function (auth, erase) { if (typeof erase === 'function') { throw new Error('deactivateAccount no longer accepts a callback parameter'); } var body = {}; if (auth) { body.auth = auth; } if (erase !== undefined) { body.erase = erase; } return this._http.authedRequest(undefined, "POST", '/account/deactivate', undefined, body); }; /** * Get the fallback URL to use for unknown interactive-auth stages. * * @param {string} loginType the type of stage being attempted * @param {string} authSessionId the auth session ID provided by the homeserver * * @return {string} HS URL to hit to for the fallback interface */ MatrixBaseApis.prototype.getFallbackAuthUrl = function (loginType, authSessionId) { var path = utils.encodeUri("/auth/$loginType/fallback/web", { $loginType: loginType }); return this._http.getUrl(path, { session: authSessionId }, _httpApi.PREFIX_R0); }; // Room operations // =============== /** * Create a new room. * @param {Object} options a list of options to pass to the /createRoom API. * @param {string} options.room_alias_name The alias localpart to assign to * this room. * @param {string} options.visibility Either 'public' or 'private'. * @param {string[]} options.invite A list of user IDs to invite to this room. * @param {string} options.name The name to give this room. * @param {string} options.topic The topic to give this room. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: {room_id: {string}, * room_alias: {string(opt)}} * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.createRoom = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(options, callback) { var invitesNeedingToken, identityAccessToken, _iterator, _step, invite; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // some valid options include: room_alias_name, visibility, invite // inject the id_access_token if inviting 3rd party addresses invitesNeedingToken = (options.invite_3pid || []).filter(function (i) { return !i.id_access_token; }); _context.t0 = invitesNeedingToken.length > 0 && this.identityServer && this.identityServer.getAccessToken; if (!_context.t0) { _context.next = 6; break; } _context.next = 5; return this.doesServerAcceptIdentityAccessToken(); case 5: _context.t0 = _context.sent; case 6: if (!_context.t0) { _context.next = 11; break; } _context.next = 9; return this.identityServer.getAccessToken(); case 9: identityAccessToken = _context.sent; if (identityAccessToken) { _iterator = _createForOfIteratorHelper(invitesNeedingToken); try { for (_iterator.s(); !(_step = _iterator.n()).done;) { invite = _step.value; invite.id_access_token = identityAccessToken; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } case 11: return _context.abrupt("return", this._http.authedRequest(callback, "POST", "/createRoom", undefined, options)); case 12: case "end": return _context.stop(); } } }, _callee, this); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(); /** * Fetches relations for a given event * @param {string} roomId the room of the event * @param {string} eventId the id of the event * @param {string} relationType the rel_type of the relations requested * @param {string} eventType the event type of the relations requested * @param {Object} opts options with optional values for the request. * @param {Object} opts.from the pagination token returned from a previous request as `next_batch` to return following relations. * @return {Object} the response, with chunk and next_batch. */ MatrixBaseApis.prototype.fetchRelations = /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(roomId, eventId, relationType, eventType, opts) { var queryParams, queryString, path, response; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: queryParams = {}; if (opts.from) { queryParams.from = opts.from; } queryString = utils.encodeParams(queryParams); path = utils.encodeUri("/rooms/$roomId/relations/$eventId/$relationType/$eventType?" + queryString, { $roomId: roomId, $eventId: eventId, $relationType: relationType, $eventType: eventType }); _context2.next = 6; return this._http.authedRequest(undefined, "GET", path, null, null, { prefix: _httpApi.PREFIX_UNSTABLE }); case 6: response = _context2.sent; return _context2.abrupt("return", response); case 8: case "end": return _context2.stop(); } } }, _callee2, this); })); return function (_x3, _x4, _x5, _x6, _x7) { return _ref2.apply(this, arguments); }; }(); /** * @param {string} roomId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.roomState = function (roomId, callback) { var path = utils.encodeUri("/rooms/$roomId/state", { $roomId: roomId }); return this._http.authedRequest(callback, "GET", path); }; /** * Get an event in a room by its event id. * @param {string} roomId * @param {string} eventId * @param {module:client.callback} callback Optional. * * @return {Promise} Resolves to an object containing the event. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.fetchRoomEvent = function (roomId, eventId, callback) { var path = utils.encodeUri("/rooms/$roomId/event/$eventId", { $roomId: roomId, $eventId: eventId }); return this._http.authedRequest(callback, "GET", path); }; /** * @param {string} roomId * @param {string} includeMembership the membership type to include in the response * @param {string} excludeMembership the membership type to exclude from the response * @param {string} atEventId the id of the event for which moment in the timeline the members should be returned for * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: dictionary of userid to profile information * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.members = function (roomId, includeMembership, excludeMembership, atEventId, callback) { var queryParams = {}; if (includeMembership) { queryParams.membership = includeMembership; } if (excludeMembership) { queryParams.not_membership = excludeMembership; } if (atEventId) { queryParams.at = atEventId; } var queryString = utils.encodeParams(queryParams); var path = utils.encodeUri("/rooms/$roomId/members?" + queryString, { $roomId: roomId }); return this._http.authedRequest(callback, "GET", path); }; /** * Upgrades a room to a new protocol version * @param {string} roomId * @param {string} newVersion The target version to upgrade to * @return {Promise} Resolves: Object with key 'replacement_room' * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.upgradeRoom = function (roomId, newVersion) { var path = utils.encodeUri("/rooms/$roomId/upgrade", { $roomId: roomId }); return this._http.authedRequest(undefined, "POST", path, undefined, { new_version: newVersion }); }; /** * @param {string} groupId * @return {Promise} Resolves: Group summary object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getGroupSummary = function (groupId) { var path = utils.encodeUri("/groups/$groupId/summary", { $groupId: groupId }); return this._http.authedRequest(undefined, "GET", path); }; /** * @param {string} groupId * @return {Promise} Resolves: Group profile object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getGroupProfile = function (groupId) { var path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId }); return this._http.authedRequest(undefined, "GET", path); }; /** * @param {string} groupId * @param {Object} profile The group profile object * @param {string=} profile.name Name of the group * @param {string=} profile.avatar_url MXC avatar URL * @param {string=} profile.short_description A short description of the room * @param {string=} profile.long_description A longer HTML description of the room * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setGroupProfile = function (groupId, profile) { var path = utils.encodeUri("/groups/$groupId/profile", { $groupId: groupId }); return this._http.authedRequest(undefined, "POST", path, undefined, profile); }; /** * @param {string} groupId * @param {object} policy The join policy for the group. Must include at * least a 'type' field which is 'open' if anyone can join the group * the group without prior approval, or 'invite' if an invite is * required to join. * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setGroupJoinPolicy = function (groupId, policy) { var path = utils.encodeUri("/groups/$groupId/settings/m.join_policy", { $groupId: groupId }); return this._http.authedRequest(undefined, "PUT", path, undefined, { 'm.join_policy': policy }); }; /** * @param {string} groupId * @return {Promise} Resolves: Group users list object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getGroupUsers = function (groupId) { var path = utils.encodeUri("/groups/$groupId/users", { $groupId: groupId }); return this._http.authedRequest(undefined, "GET", path); }; /** * @param {string} groupId * @return {Promise} Resolves: Group users list object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getGroupInvitedUsers = function (groupId) { var path = utils.encodeUri("/groups/$groupId/invited_users", { $groupId: groupId }); return this._http.authedRequest(undefined, "GET", path); }; /** * @param {string} groupId * @return {Promise} Resolves: Group rooms list object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getGroupRooms = function (groupId) { var path = utils.encodeUri("/groups/$groupId/rooms", { $groupId: groupId }); return this._http.authedRequest(undefined, "GET", path); }; /** * @param {string} groupId * @param {string} userId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.inviteUserToGroup = function (groupId, userId) { var path = utils.encodeUri("/groups/$groupId/admin/users/invite/$userId", { $groupId: groupId, $userId: userId }); return this._http.authedRequest(undefined, "PUT", path, undefined, {}); }; /** * @param {string} groupId * @param {string} userId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.removeUserFromGroup = function (groupId, userId) { var path = utils.encodeUri("/groups/$groupId/admin/users/remove/$userId", { $groupId: groupId, $userId: userId }); return this._http.authedRequest(undefined, "PUT", path, undefined, {}); }; /** * @param {string} groupId * @param {string} userId * @param {string} roleId Optional. * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addUserToGroupSummary = function (groupId, userId, roleId) { var path = utils.encodeUri(roleId ? "/groups/$groupId/summary/$roleId/users/$userId" : "/groups/$groupId/summary/users/$userId", { $groupId: groupId, $roleId: roleId, $userId: userId }); return this._http.authedRequest(undefined, "PUT", path, undefined, {}); }; /** * @param {string} groupId * @param {string} userId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.removeUserFromGroupSummary = function (groupId, userId) { var path = utils.encodeUri("/groups/$groupId/summary/users/$userId", { $groupId: groupId, $userId: userId }); return this._http.authedRequest(undefined, "DELETE", path, undefined, {}); }; /** * @param {string} groupId * @param {string} roomId * @param {string} categoryId Optional. * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addRoomToGroupSummary = function (groupId, roomId, categoryId) { var path = utils.encodeUri(categoryId ? "/groups/$groupId/summary/$categoryId/rooms/$roomId" : "/groups/$groupId/summary/rooms/$roomId", { $groupId: groupId, $categoryId: categoryId, $roomId: roomId }); return this._http.authedRequest(undefined, "PUT", path, undefined, {}); }; /** * @param {string} groupId * @param {string} roomId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.removeRoomFromGroupSummary = function (groupId, roomId) { var path = utils.encodeUri("/groups/$groupId/summary/rooms/$roomId", { $groupId: groupId, $roomId: roomId }); return this._http.authedRequest(undefined, "DELETE", path, undefined, {}); }; /** * @param {string} groupId * @param {string} roomId * @param {bool} isPublic Whether the room-group association is visible to non-members * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addRoomToGroup = function (groupId, roomId, isPublic) { if (isPublic === undefined) { isPublic = true; } var path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId", { $groupId: groupId, $roomId: roomId }); return this._http.authedRequest(undefined, "PUT", path, undefined, { "m.visibility": { type: isPublic ? "public" : "private" } }); }; /** * Configure the visibility of a room-group association. * @param {string} groupId * @param {string} roomId * @param {bool} isPublic Whether the room-group association is visible to non-members * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.updateGroupRoomVisibility = function (groupId, roomId, isPublic) { // NB: The /config API is generic but there's not much point in exposing this yet as synapse // is the only server to implement this. In future we should consider an API that allows // arbitrary configuration, i.e. "config/$configKey". var path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId/config/m.visibility", { $groupId: groupId, $roomId: roomId }); return this._http.authedRequest(undefined, "PUT", path, undefined, { type: isPublic ? "public" : "private" }); }; /** * @param {string} groupId * @param {string} roomId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.removeRoomFromGroup = function (groupId, roomId) { var path = utils.encodeUri("/groups/$groupId/admin/rooms/$roomId", { $groupId: groupId, $roomId: roomId }); return this._http.authedRequest(undefined, "DELETE", path, undefined, {}); }; /** * @param {string} groupId * @param {Object} opts Additional options to send alongside the acceptance. * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.acceptGroupInvite = function (groupId) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var path = utils.encodeUri("/groups/$groupId/self/accept_invite", { $groupId: groupId }); return this._http.authedRequest(undefined, "PUT", path, undefined, opts || {}); }; /** * @param {string} groupId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.joinGroup = function (groupId) { var path = utils.encodeUri("/groups/$groupId/self/join", { $groupId: groupId }); return this._http.authedRequest(undefined, "PUT", path, undefined, {}); }; /** * @param {string} groupId * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.leaveGroup = function (groupId) { var path = utils.encodeUri("/groups/$groupId/self/leave", { $groupId: groupId }); return this._http.authedRequest(undefined, "PUT", path, undefined, {}); }; /** * @return {Promise} Resolves: The groups to which the user is joined * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getJoinedGroups = function () { var path = utils.encodeUri("/joined_groups"); return this._http.authedRequest(undefined, "GET", path); }; /** * @param {Object} content Request content * @param {string} content.localpart The local part of the desired group ID * @param {Object} content.profile Group profile object * @return {Promise} Resolves: Object with key group_id: id of the created group * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.createGroup = function (content) { var path = utils.encodeUri("/create_group"); return this._http.authedRequest(undefined, "POST", path, undefined, content); }; /** * @param {string[]} userIds List of user IDs * @return {Promise} Resolves: Object as exmaple below * * { * "users": { * "@bob:example.com": { * "+example:example.com" * } * } * } * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getPublicisedGroups = function (userIds) { var path = utils.encodeUri("/publicised_groups"); return this._http.authedRequest(undefined, "POST", path, undefined, { user_ids: userIds }); }; /** * @param {string} groupId * @param {bool} isPublic Whether the user's membership of this group is made public * @return {Promise} Resolves: Empty object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setGroupPublicity = function (groupId, isPublic) { var path = utils.encodeUri("/groups/$groupId/self/update_publicity", { $groupId: groupId }); return this._http.authedRequest(undefined, "PUT", path, undefined, { publicise: isPublic }); }; /** * Retrieve a state event. * @param {string} roomId * @param {string} eventType * @param {string} stateKey * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getStateEvent = function (roomId, eventType, stateKey, callback) { var pathParams = { $roomId: roomId, $eventType: eventType, $stateKey: stateKey }; var path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); if (stateKey !== undefined) { path = utils.encodeUri(path + "/$stateKey", pathParams); } return this._http.authedRequest(callback, "GET", path); }; /** * @param {string} roomId * @param {string} eventType * @param {Object} content * @param {string} stateKey * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.sendStateEvent = function (roomId, eventType, content, stateKey, callback) { var pathParams = { $roomId: roomId, $eventType: eventType, $stateKey: stateKey }; var path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); if (stateKey !== undefined) { path = utils.encodeUri(path + "/$stateKey", pathParams); } return this._http.authedRequest(callback, "PUT", path, undefined, content); }; /** * @param {string} roomId * @param {Number} limit * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.roomInitialSync = function (roomId, limit, callback) { if (utils.isFunction(limit)) { callback = limit; limit = undefined; } var path = utils.encodeUri("/rooms/$roomId/initialSync", { $roomId: roomId }); if (!limit) { limit = 30; } return this._http.authedRequest(callback, "GET", path, { limit: limit }); }; /** * Set a marker to indicate the point in a room before which the user has read every * event. This can be retrieved from room account data (the event type is `m.fully_read`) * and displayed as a horizontal line in the timeline that is visually distinct to the * position of the user's own read receipt. * @param {string} roomId ID of the room that has been read * @param {string} rmEventId ID of the event that has been read * @param {string} rrEventId ID of the event tracked by the read receipt. This is here * for convenience because the RR and the RM are commonly updated at the same time as * each other. Optional. * @param {object} opts Options for the read markers. * @param {object} opts.hidden True to hide the read receipt from other users. This * property is currently unstable and may change in the future. * @return {Promise} Resolves: the empty object, {}. */ MatrixBaseApis.prototype.setRoomReadMarkersHttpRequest = function (roomId, rmEventId, rrEventId, opts) { var path = utils.encodeUri("/rooms/$roomId/read_markers", { $roomId: roomId }); var content = { "m.fully_read": rmEventId, "m.read": rrEventId, "m.hidden": Boolean(opts ? opts.hidden : false) }; return this._http.authedRequest(undefined, "POST", path, undefined, content); }; /** * @return {Promise} Resolves: A list of the user's current rooms * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getJoinedRooms = function () { var path = utils.encodeUri("/joined_rooms"); return this._http.authedRequest(undefined, "GET", path); }; /** * Retrieve membership info. for a room. * @param {string} roomId ID of the room to get membership for * @return {Promise} Resolves: A list of currently joined users * and their profile data. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getJoinedRoomMembers = function (roomId) { var path = utils.encodeUri("/rooms/$roomId/joined_members", { $roomId: roomId }); return this._http.authedRequest(undefined, "GET", path); }; // Room Directory operations // ========================= /** * @param {Object} options Options for this request * @param {string} options.server The remote server to query for the room list. * Optional. If unspecified, get the local home * server's public room list. * @param {number} options.limit Maximum number of entries to return * @param {string} options.since Token to paginate from * @param {object} options.filter Filter parameters * @param {string} options.filter.generic_search_term String to search for * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.publicRooms = function (options, callback) { if (typeof options == 'function') { callback = options; options = {}; } if (options === undefined) { options = {}; } var query_params = {}; if (options.server) { query_params.server = options.server; delete options.server; } if (Object.keys(options).length === 0 && Object.keys(query_params).length === 0) { return this._http.authedRequest(callback, "GET", "/publicRooms"); } else { return this._http.authedRequest(callback, "POST", "/publicRooms", query_params, options); } }; /** * Create an alias to room ID mapping. * @param {string} alias The room alias to create. * @param {string} roomId The room ID to link the alias to. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.createAlias = function (alias, roomId, callback) { var path = utils.encodeUri("/directory/room/$alias", { $alias: alias }); var data = { room_id: roomId }; return this._http.authedRequest(callback, "PUT", path, undefined, data); }; /** * Delete an alias to room ID mapping. This alias must be on your local server * and you must have sufficient access to do this operation. * @param {string} alias The room alias to delete. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deleteAlias = function (alias, callback) { var path = utils.encodeUri("/directory/room/$alias", { $alias: alias }); return this._http.authedRequest(callback, "DELETE", path, undefined, undefined); }; /** * @param {string} roomId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: an object with an `aliases` property, containing an array of local aliases * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.unstableGetLocalAliases = function (roomId, callback) { var path = utils.encodeUri("/rooms/$roomId/aliases", { $roomId: roomId }); var prefix = _httpApi.PREFIX_UNSTABLE + "/org.matrix.msc2432"; return this._http.authedRequest(callback, "GET", path, null, null, { prefix: prefix }); }; /** * Get room info for the given alias. * @param {string} alias The room alias to resolve. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Object with room_id and servers. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getRoomIdForAlias = function (alias, callback) { // TODO: deprecate this or resolveRoomAlias var path = utils.encodeUri("/directory/room/$alias", { $alias: alias }); return this._http.authedRequest(callback, "GET", path); }; /** * @param {string} roomAlias * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.resolveRoomAlias = function (roomAlias, callback) { // TODO: deprecate this or getRoomIdForAlias var path = utils.encodeUri("/directory/room/$alias", { $alias: roomAlias }); return this._http.request(callback, "GET", path); }; /** * Get the visibility of a room in the current HS's room directory * @param {string} roomId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getRoomDirectoryVisibility = function (roomId, callback) { var path = utils.encodeUri("/directory/list/room/$roomId", { $roomId: roomId }); return this._http.authedRequest(callback, "GET", path); }; /** * Set the visbility of a room in the current HS's room directory * @param {string} roomId * @param {string} visibility "public" to make the room visible * in the public directory, or "private" to make * it invisible. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setRoomDirectoryVisibility = function (roomId, visibility, callback) { var path = utils.encodeUri("/directory/list/room/$roomId", { $roomId: roomId }); return this._http.authedRequest(callback, "PUT", path, undefined, { "visibility": visibility }); }; /** * Set the visbility of a room bridged to a 3rd party network in * the current HS's room directory. * @param {string} networkId the network ID of the 3rd party * instance under which this room is published under. * @param {string} roomId * @param {string} visibility "public" to make the room visible * in the public directory, or "private" to make * it invisible. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setRoomDirectoryVisibilityAppService = function (networkId, roomId, visibility, callback) { var path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", { $networkId: networkId, $roomId: roomId }); return this._http.authedRequest(callback, "PUT", path, undefined, { "visibility": visibility }); }; // User Directory Operations // ========================= /** * Query the user directory with a term matching user IDs, display names and domains. * @param {object} opts options * @param {string} opts.term the term with which to search. * @param {number} opts.limit the maximum number of results to return. The server will * apply a limit if unspecified. * @return {Promise} Resolves: an array of results. */ MatrixBaseApis.prototype.searchUserDirectory = function (opts) { var body = { search_term: opts.term }; if (opts.limit !== undefined) { body.limit = opts.limit; } return this._http.authedRequest(undefined, "POST", "/user_directory/search", undefined, body); }; // Media operations // ================ /** * Upload a file to the media repository on the home server. * * @param {object} file The object to upload. On a browser, something that * can be sent to XMLHttpRequest.send (typically a File). Under node.js, * a a Buffer, String or ReadStream. * * @param {object} opts options object * * @param {string=} opts.name Name to give the file on the server. Defaults * to file.name. * * @param {boolean=} opts.includeFilename if false will not send the filename, * e.g for encrypted file uploads where filename leaks are undesirable. * Defaults to true. * * @param {string=} opts.type Content-type for the upload. Defaults to * file.type, or applicaton/octet-stream. * * @param {boolean=} opts.rawResponse Return the raw body, rather than * parsing the JSON. Defaults to false (except on node.js, where it * defaults to true for backwards compatibility). * * @param {boolean=} opts.onlyContentUri Just return the content URI, * rather than the whole body. Defaults to false (except on browsers, * where it defaults to true for backwards compatibility). Ignored if * opts.rawResponse is true. * * @param {Function=} opts.callback Deprecated. Optional. The callback to * invoke on success/failure. See the promise return values for more * information. * * @param {Function=} opts.progressHandler Optional. Called when a chunk of * data has been uploaded, with an object containing the fields `loaded` * (number of bytes transferred) and `total` (total size, if known). * * @return {Promise} Resolves to response object, as * determined by this.opts.onlyData, opts.rawResponse, and * opts.onlyContentUri. Rejects with an error (usually a MatrixError). */ MatrixBaseApis.prototype.uploadContent = function (file, opts) { return this._http.uploadContent(file, opts); }; /** * Cancel a file upload in progress * @param {Promise} promise The promise returned from uploadContent * @return {boolean} true if canceled, otherwise false */ MatrixBaseApis.prototype.cancelUpload = function (promise) { return this._http.cancelUpload(promise); }; /** * Get a list of all file uploads in progress * @return {array} Array of objects representing current uploads. * Currently in progress is element 0. Keys: * - promise: The promise associated with the upload * - loaded: Number of bytes uploaded * - total: Total number of bytes to upload */ MatrixBaseApis.prototype.getCurrentUploads = function () { return this._http.getCurrentUploads(); }; // Profile operations // ================== /** * @param {string} userId * @param {string} info The kind of info to retrieve (e.g. 'displayname', * 'avatar_url'). * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getProfileInfo = function (userId, info, callback) { if (utils.isFunction(info)) { callback = info; info = undefined; } var path = info ? utils.encodeUri("/profile/$userId/$info", { $userId: userId, $info: info }) : utils.encodeUri("/profile/$userId", { $userId: userId }); return this._http.authedRequest(callback, "GET", path); }; // Account operations // ================== /** * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getThreePids = function (callback) { var path = "/account/3pid"; return this._http.authedRequest(callback, "GET", path, undefined, undefined); }; /** * Add a 3PID to your homeserver account and optionally bind it to an identity * server as well. An identity server is required as part of the `creds` object. * * This API is deprecated, and you should instead use `addThreePidOnly` * for homeservers that support it. * * @param {Object} creds * @param {boolean} bind * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: on success * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addThreePid = function (creds, bind, callback) { var path = "/account/3pid"; var data = { 'threePidCreds': creds, 'bind': bind }; return this._http.authedRequest(callback, "POST", path, null, data); }; /** * Add a 3PID to your homeserver account. This API does not use an identity * server, as the homeserver is expected to handle 3PID ownership validation. * * You can check whether a homeserver supports this API via * `doesServerSupportSeparateAddAndBind`. * * @param {Object} data A object with 3PID validation data from having called * `account/3pid//requestToken` on the homeserver. * @return {Promise} Resolves: on success * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addThreePidOnly = /*#__PURE__*/function () { var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(data) { var path, prefix; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: path = "/account/3pid/add"; _context3.next = 3; return this.isVersionSupported("r0.6.0"); case 3: if (!_context3.sent) { _context3.next = 7; break; } _context3.t0 = _httpApi.PREFIX_R0; _context3.next = 8; break; case 7: _context3.t0 = _httpApi.PREFIX_UNSTABLE; case 8: prefix = _context3.t0; return _context3.abrupt("return", this._http.authedRequest(undefined, "POST", path, null, data, { prefix: prefix })); case 10: case "end": return _context3.stop(); } } }, _callee3, this); })); return function (_x8) { return _ref3.apply(this, arguments); }; }(); /** * Bind a 3PID for discovery onto an identity server via the homeserver. The * identity server handles 3PID ownership validation and the homeserver records * the new binding to track where all 3PIDs for the account are bound. * * You can check whether a homeserver supports this API via * `doesServerSupportSeparateAddAndBind`. * * @param {Object} data A object with 3PID validation data from having called * `validate//requestToken` on the identity server. It should also * contain `id_server` and `id_access_token` fields as well. * @return {Promise} Resolves: on success * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.bindThreePid = /*#__PURE__*/function () { var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(data) { var path, prefix; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: path = "/account/3pid/bind"; _context4.next = 3; return this.isVersionSupported("r0.6.0"); case 3: if (!_context4.sent) { _context4.next = 7; break; } _context4.t0 = _httpApi.PREFIX_R0; _context4.next = 8; break; case 7: _context4.t0 = _httpApi.PREFIX_UNSTABLE; case 8: prefix = _context4.t0; return _context4.abrupt("return", this._http.authedRequest(undefined, "POST", path, null, data, { prefix: prefix })); case 10: case "end": return _context4.stop(); } } }, _callee4, this); })); return function (_x9) { return _ref4.apply(this, arguments); }; }(); /** * Unbind a 3PID for discovery on an identity server via the homeserver. The * homeserver removes its record of the binding to keep an updated record of * where all 3PIDs for the account are bound. * * @param {string} medium The threepid medium (eg. 'email') * @param {string} address The threepid address (eg. 'bob@example.com') * this must be as returned by getThreePids. * @return {Promise} Resolves: on success * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.unbindThreePid = /*#__PURE__*/function () { var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(medium, address) { var path, data, prefix; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: path = "/account/3pid/unbind"; data = { medium: medium, address: address, id_server: this.getIdentityServerUrl(true) }; _context5.next = 4; return this.isVersionSupported("r0.6.0"); case 4: if (!_context5.sent) { _context5.next = 8; break; } _context5.t0 = _httpApi.PREFIX_R0; _context5.next = 9; break; case 8: _context5.t0 = _httpApi.PREFIX_UNSTABLE; case 9: prefix = _context5.t0; return _context5.abrupt("return", this._http.authedRequest(undefined, "POST", path, null, data, { prefix: prefix })); case 11: case "end": return _context5.stop(); } } }, _callee5, this); })); return function (_x10, _x11) { return _ref5.apply(this, arguments); }; }(); /** * @param {string} medium The threepid medium (eg. 'email') * @param {string} address The threepid address (eg. 'bob@example.com') * this must be as returned by getThreePids. * @return {Promise} Resolves: The server response on success * (generally the empty JSON object) * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deleteThreePid = function (medium, address) { var path = "/account/3pid/delete"; var data = { 'medium': medium, 'address': address }; return this._http.authedRequest(undefined, "POST", path, null, data); }; /** * Make a request to change your password. * @param {Object} authDict * @param {string} newPassword The new desired password. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setPassword = function (authDict, newPassword, callback) { var path = "/account/password"; var data = { 'auth': authDict, 'new_password': newPassword }; return this._http.authedRequest(callback, "POST", path, null, data); }; // Device operations // ================= /** * Gets all devices recorded for the logged-in user * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getDevices = function () { return this._http.authedRequest(undefined, 'GET', "/devices", undefined, undefined); }; /** * Update the given device * * @param {string} device_id device to update * @param {Object} body body of request * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setDeviceDetails = function (device_id, body) { var path = utils.encodeUri("/devices/$device_id", { $device_id: device_id }); return this._http.authedRequest(undefined, "PUT", path, undefined, body); }; /** * Delete the given device * * @param {string} device_id device to delete * @param {object} auth Optional. Auth data to supply for User-Interactive auth. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deleteDevice = function (device_id, auth) { var path = utils.encodeUri("/devices/$device_id", { $device_id: device_id }); var body = {}; if (auth) { body.auth = auth; } return this._http.authedRequest(undefined, "DELETE", path, undefined, body); }; /** * Delete multiple device * * @param {string[]} devices IDs of the devices to delete * @param {object} auth Optional. Auth data to supply for User-Interactive auth. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deleteMultipleDevices = function (devices, auth) { var body = { devices: devices }; if (auth) { body.auth = auth; } var path = "/delete_devices"; return this._http.authedRequest(undefined, "POST", path, undefined, body); }; // Push operations // =============== /** * Gets all pushers registered for the logged-in user * * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Array of objects representing pushers * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getPushers = function (callback) { var path = "/pushers"; return this._http.authedRequest(callback, "GET", path, undefined, undefined); }; /** * Adds a new pusher or updates an existing pusher * * @param {Object} pusher Object representing a pusher * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Empty json object on success * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setPusher = function (pusher, callback) { var path = "/pushers/set"; return this._http.authedRequest(callback, "POST", path, null, pusher); }; /** * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getPushRules = function (callback) { return this._http.authedRequest(callback, "GET", "/pushrules/").then(function (rules) { return _pushprocessor.PushProcessor.rewriteDefaultRules(rules); }); }; /** * @param {string} scope * @param {string} kind * @param {string} ruleId * @param {Object} body * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.addPushRule = function (scope, kind, ruleId, body, callback) { // NB. Scope not uri encoded because devices need the '/' var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { $kind: kind, $ruleId: ruleId }); return this._http.authedRequest(callback, "PUT", path, undefined, body); }; /** * @param {string} scope * @param {string} kind * @param {string} ruleId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.deletePushRule = function (scope, kind, ruleId, callback) { // NB. Scope not uri encoded because devices need the '/' var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { $kind: kind, $ruleId: ruleId }); return this._http.authedRequest(callback, "DELETE", path); }; /** * Enable or disable a push notification rule. * @param {string} scope * @param {string} kind * @param {string} ruleId * @param {boolean} enabled * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setPushRuleEnabled = function (scope, kind, ruleId, enabled, callback) { var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", { $kind: kind, $ruleId: ruleId }); return this._http.authedRequest(callback, "PUT", path, undefined, { "enabled": enabled }); }; /** * Set the actions for a push notification rule. * @param {string} scope * @param {string} kind * @param {string} ruleId * @param {array} actions * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.setPushRuleActions = function (scope, kind, ruleId, actions, callback) { var path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", { $kind: kind, $ruleId: ruleId }); return this._http.authedRequest(callback, "PUT", path, undefined, { "actions": actions }); }; // Search // ====== /** * Perform a server-side search. * @param {Object} opts * @param {string} opts.next_batch the batch token to pass in the query string * @param {Object} opts.body the JSON object to pass to the request body. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.search = function (opts, callback) { var queryparams = {}; if (opts.next_batch) { queryparams.next_batch = opts.next_batch; } return this._http.authedRequest(callback, "POST", "/search", queryparams, opts.body); }; // Crypto // ====== /** * Upload keys * * @param {Object} content body of upload request * * @param {Object=} opts this method no longer takes any opts, * used to take opts.device_id but this was not removed from the spec as a redundant parameter * * @param {module:client.callback=} callback * * @return {Promise} Resolves: result object. Rejects: with * an error response ({@link module:http-api.MatrixError}). */ MatrixBaseApis.prototype.uploadKeysRequest = function (content, opts, callback) { return this._http.authedRequest(callback, "POST", "/keys/upload", undefined, content); }; MatrixBaseApis.prototype.uploadKeySignatures = function (content) { return this._http.authedRequest(undefined, "POST", '/keys/signatures/upload', undefined, content, { prefix: _httpApi.PREFIX_UNSTABLE }); }; /** * Download device keys * * @param {string[]} userIds list of users to get keys for * * @param {Object=} opts * * @param {string=} opts.token sync token to pass in the query request, to help * the HS give the most recent results * * @return {Promise} Resolves: result object. Rejects: with * an error response ({@link module:http-api.MatrixError}). */ MatrixBaseApis.prototype.downloadKeysForUsers = function (userIds, opts) { if (utils.isFunction(opts)) { // opts used to be 'callback'. throw new Error('downloadKeysForUsers no longer accepts a callback parameter'); } opts = opts || {}; var content = { device_keys: {} }; if ('token' in opts) { content.token = opts.token; } userIds.forEach(function (u) { content.device_keys[u] = []; }); return this._http.authedRequest(undefined, "POST", "/keys/query", undefined, content); }; /** * Claim one-time keys * * @param {string[]} devices a list of [userId, deviceId] pairs * * @param {string} [key_algorithm = signed_curve25519] desired key type * * @param {number} [timeout] the time (in milliseconds) to wait for keys from remote * servers * * @return {Promise} Resolves: result object. Rejects: with * an error response ({@link module:http-api.MatrixError}). */ MatrixBaseApis.prototype.claimOneTimeKeys = function (devices, key_algorithm, timeout) { var queries = {}; if (key_algorithm === undefined) { key_algorithm = "signed_curve25519"; } for (var i = 0; i < devices.length; ++i) { var userId = devices[i][0]; var deviceId = devices[i][1]; var query = queries[userId] || {}; queries[userId] = query; query[deviceId] = key_algorithm; } var content = { one_time_keys: queries }; if (timeout) { content.timeout = timeout; } var path = "/keys/claim"; return this._http.authedRequest(undefined, "POST", path, undefined, content); }; /** * Ask the server for a list of users who have changed their device lists * between a pair of sync tokens * * @param {string} oldToken * @param {string} newToken * * @return {Promise} Resolves: result object. Rejects: with * an error response ({@link module:http-api.MatrixError}). */ MatrixBaseApis.prototype.getKeyChanges = function (oldToken, newToken) { var qps = { from: oldToken, to: newToken }; var path = "/keys/changes"; return this._http.authedRequest(undefined, "GET", path, qps, undefined); }; MatrixBaseApis.prototype.uploadDeviceSigningKeys = function (auth, keys) { var data = Object.assign({}, keys); if (auth) Object.assign(data, { auth: auth }); return this._http.authedRequest(undefined, "POST", "/keys/device_signing/upload", undefined, data, { prefix: _httpApi.PREFIX_UNSTABLE }); }; // Identity Server Operations // ========================== /** * Register with an Identity Server using the OpenID token from the user's * Homeserver, which can be retrieved via * {@link module:client~MatrixClient#getOpenIdToken}. * * Note that the `/account/register` endpoint (as well as IS authentication in * general) was added as part of the v2 API version. * * @param {object} hsOpenIdToken * @return {Promise} Resolves: with object containing an Identity * Server access token. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.registerWithIdentityServer = function (hsOpenIdToken) { if (!this.idBaseUrl) { throw new Error("No Identity Server base URL set"); } var uri = this.idBaseUrl + _httpApi.PREFIX_IDENTITY_V2 + "/account/register"; return this._http.requestOtherUrl(undefined, "POST", uri, null, hsOpenIdToken); }; /** * Requests an email verification token directly from an identity server. * * This API is used as part of binding an email for discovery on an identity * server. The validation data that results should be passed to the * `bindThreePid` method to complete the binding process. * * @param {string} email The email address to request a token for * @param {string} clientSecret A secret binary string generated by the client. * It is recommended this be around 16 ASCII characters. * @param {number} sendAttempt If an identity server sees a duplicate request * with the same sendAttempt, it will not send another email. * To request another email to be sent, use a larger value for * the sendAttempt param as was used in the previous request. * @param {string} nextLink Optional If specified, the client will be redirected * to this link after validation. * @param {module:client.callback} callback Optional. * @param {string} identityAccessToken The `access_token` field of the identity * server `/account/register` response (see {@link registerWithIdentityServer}). * * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. * @throws Error if no identity server is set */ MatrixBaseApis.prototype.requestEmailToken = /*#__PURE__*/function () { var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(email, clientSecret, sendAttempt, nextLink, callback, identityAccessToken) { var params; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: params = { client_secret: clientSecret, email: email, send_attempt: sendAttempt, next_link: nextLink }; _context6.next = 3; return this._http.idServerRequest(callback, "POST", "/validate/email/requestToken", params, _httpApi.PREFIX_IDENTITY_V2, identityAccessToken); case 3: return _context6.abrupt("return", _context6.sent); case 4: case "end": return _context6.stop(); } } }, _callee6, this); })); return function (_x12, _x13, _x14, _x15, _x16, _x17) { return _ref6.apply(this, arguments); }; }(); /** * Requests a MSISDN verification token directly from an identity server. * * This API is used as part of binding a MSISDN for discovery on an identity * server. The validation data that results should be passed to the * `bindThreePid` method to complete the binding process. * * @param {string} phoneCountry The ISO 3166-1 alpha-2 code for the country in * which phoneNumber should be parsed relative to. * @param {string} phoneNumber The phone number, in national or international * format * @param {string} clientSecret A secret binary string generated by the client. * It is recommended this be around 16 ASCII characters. * @param {number} sendAttempt If an identity server sees a duplicate request * with the same sendAttempt, it will not send another SMS. * To request another SMS to be sent, use a larger value for * the sendAttempt param as was used in the previous request. * @param {string} nextLink Optional If specified, the client will be redirected * to this link after validation. * @param {module:client.callback} callback Optional. * @param {string} identityAccessToken The `access_token` field of the Identity * Server `/account/register` response (see {@link registerWithIdentityServer}). * * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. * @throws Error if no identity server is set */ MatrixBaseApis.prototype.requestMsisdnToken = /*#__PURE__*/function () { var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink, callback, identityAccessToken) { var params; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: params = { client_secret: clientSecret, country: phoneCountry, phone_number: phoneNumber, send_attempt: sendAttempt, next_link: nextLink }; _context7.next = 3; return this._http.idServerRequest(callback, "POST", "/validate/msisdn/requestToken", params, _httpApi.PREFIX_IDENTITY_V2, identityAccessToken); case 3: return _context7.abrupt("return", _context7.sent); case 4: case "end": return _context7.stop(); } } }, _callee7, this); })); return function (_x18, _x19, _x20, _x21, _x22, _x23, _x24) { return _ref7.apply(this, arguments); }; }(); /** * Submits a MSISDN token to the identity server * * This is used when submitting the code sent by SMS to a phone number. * The ID server has an equivalent API for email but the js-sdk does * not expose this, since email is normally validated by the user clicking * a link rather than entering a code. * * @param {string} sid The sid given in the response to requestToken * @param {string} clientSecret A secret binary string generated by the client. * This must be the same value submitted in the requestToken call. * @param {string} msisdnToken The MSISDN token, as enetered by the user. * @param {string} identityAccessToken The `access_token` field of the Identity * Server `/account/register` response (see {@link registerWithIdentityServer}). * * @return {Promise} Resolves: Object, currently with no parameters. * @return {module:http-api.MatrixError} Rejects: with an error response. * @throws Error if No ID server is set */ MatrixBaseApis.prototype.submitMsisdnToken = /*#__PURE__*/function () { var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(sid, clientSecret, msisdnToken, identityAccessToken) { var params; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: params = { sid: sid, client_secret: clientSecret, token: msisdnToken }; _context8.next = 3; return this._http.idServerRequest(undefined, "POST", "/validate/msisdn/submitToken", params, _httpApi.PREFIX_IDENTITY_V2, identityAccessToken); case 3: return _context8.abrupt("return", _context8.sent); case 4: case "end": return _context8.stop(); } } }, _callee8, this); })); return function (_x25, _x26, _x27, _x28) { return _ref8.apply(this, arguments); }; }(); /** * Submits a MSISDN token to an arbitrary URL. * * This is used when submitting the code sent by SMS to a phone number in the * newer 3PID flow where the homeserver validates 3PID ownership (as part of * `requestAdd3pidMsisdnToken`). The homeserver response may include a * `submit_url` to specify where the token should be sent, and this helper can * be used to pass the token to this URL. * * @param {string} url The URL to submit the token to * @param {string} sid The sid given in the response to requestToken * @param {string} clientSecret A secret binary string generated by the client. * This must be the same value submitted in the requestToken call. * @param {string} msisdnToken The MSISDN token, as enetered by the user. * * @return {Promise} Resolves: Object, currently with no parameters. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.submitMsisdnTokenOtherUrl = function (url, sid, clientSecret, msisdnToken) { var params = { sid: sid, client_secret: clientSecret, token: msisdnToken }; return this._http.requestOtherUrl(undefined, "POST", url, undefined, params); }; /** * Gets the V2 hashing information from the identity server. Primarily useful for * lookups. * @param {string} identityAccessToken The access token for the identity server. * @returns {Promise} The hashing information for the identity server. */ MatrixBaseApis.prototype.getIdentityHashDetails = function (identityAccessToken) { return this._http.idServerRequest(undefined, "GET", "/hash_details", null, _httpApi.PREFIX_IDENTITY_V2, identityAccessToken); }; /** * Performs a hashed lookup of addresses against the identity server. This is * only supported on identity servers which have at least the version 2 API. * @param {Array>} addressPairs An array of 2 element arrays. * The first element of each pair is the address, the second is the 3PID medium. * Eg: ["email@example.org", "email"] * @param {string} identityAccessToken The access token for the identity server. * @returns {Promise>} A collection of address mappings to * found MXIDs. Results where no user could be found will not be listed. */ MatrixBaseApis.prototype.identityHashedLookup = /*#__PURE__*/function () { var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(addressPairs, // [["email@example.org", "email"], ["10005550000", "msisdn"]] identityAccessToken) { var params, hashes, localMapping, olmutil, response, foundAddresses, _i, _Object$keys, hashed, mxid, plainAddress; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: params = {// addresses: ["email@example.org", "10005550000"], // algorithm: "sha256", // pepper: "abc123" }; // Get hash information first before trying to do a lookup _context9.next = 3; return this.getIdentityHashDetails(identityAccessToken); case 3: hashes = _context9.sent; if (!(!hashes || !hashes['lookup_pepper'] || !hashes['algorithms'])) { _context9.next = 6; break; } throw new Error("Unsupported identity server: bad response"); case 6: params['pepper'] = hashes['lookup_pepper']; localMapping = {// hashed identifier => plain text address // For use in this function's return format }; // When picking an algorithm, we pick the hashed over no hashes if (!hashes['algorithms'].includes('sha256')) { _context9.next = 14; break; } // Abuse the olm hashing olmutil = new global.Olm.Utility(); params["addresses"] = addressPairs.map(function (p) { var addr = p[0].toLowerCase(); // lowercase to get consistent hashes var med = p[1].toLowerCase(); var hashed = olmutil.sha256("".concat(addr, " ").concat(med, " ").concat(params['pepper'])).replace(/\+/g, '-').replace(/\//g, '_'); // URL-safe base64 // Map the hash to a known (case-sensitive) address. We use the case // sensitive version because the caller might be expecting that. localMapping[hashed] = p[0]; return hashed; }); params["algorithm"] = "sha256"; _context9.next = 20; break; case 14: if (!hashes['algorithms'].includes('none')) { _context9.next = 19; break; } params["addresses"] = addressPairs.map(function (p) { var addr = p[0].toLowerCase(); // lowercase to get consistent hashes var med = p[1].toLowerCase(); var unhashed = "".concat(addr, " ").concat(med); // Map the unhashed values to a known (case-sensitive) address. We use // the case sensitive version because the caller might be expecting that. localMapping[unhashed] = p[0]; return unhashed; }); params["algorithm"] = "none"; _context9.next = 20; break; case 19: throw new Error("Unsupported identity server: unknown hash algorithm"); case 20: _context9.next = 22; return this._http.idServerRequest(undefined, "POST", "/lookup", params, _httpApi.PREFIX_IDENTITY_V2, identityAccessToken); case 22: response = _context9.sent; if (!(!response || !response['mappings'])) { _context9.next = 25; break; } return _context9.abrupt("return", []); case 25: // no results foundAddresses = [ /* {address: "plain@example.org", mxid} */ ]; _i = 0, _Object$keys = Object.keys(response['mappings']); case 27: if (!(_i < _Object$keys.length)) { _context9.next = 37; break; } hashed = _Object$keys[_i]; mxid = response['mappings'][hashed]; plainAddress = localMapping[hashed]; if (plainAddress) { _context9.next = 33; break; } throw new Error("Identity server returned more results than expected"); case 33: foundAddresses.push({ address: plainAddress, mxid: mxid }); case 34: _i++; _context9.next = 27; break; case 37: return _context9.abrupt("return", foundAddresses); case 38: case "end": return _context9.stop(); } } }, _callee9, this); })); return function (_x29, _x30) { return _ref9.apply(this, arguments); }; }(); /** * Looks up the public Matrix ID mapping for a given 3rd party * identifier from the Identity Server * * @param {string} medium The medium of the threepid, eg. 'email' * @param {string} address The textual address of the threepid * @param {module:client.callback} callback Optional. * @param {string} identityAccessToken The `access_token` field of the Identity * Server `/account/register` response (see {@link registerWithIdentityServer}). * * @return {Promise} Resolves: A threepid mapping * object or the empty object if no mapping * exists * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.lookupThreePid = /*#__PURE__*/function () { var _ref10 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(medium, address, callback, identityAccessToken) { var response, result, mapping; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return this.identityHashedLookup([[address, medium]], identityAccessToken); case 2: response = _context10.sent; result = response.find(function (p) { return p.address === address; }); if (result) { _context10.next = 7; break; } if (callback) callback(null, {}); return _context10.abrupt("return", {}); case 7: mapping = { address: address, medium: medium, mxid: result.mxid // We can't reasonably fill these parameters: // not_before // not_after // ts // signatures }; if (callback) callback(null, mapping); return _context10.abrupt("return", mapping); case 10: case "end": return _context10.stop(); } } }, _callee10, this); })); return function (_x31, _x32, _x33, _x34) { return _ref10.apply(this, arguments); }; }(); /** * Looks up the public Matrix ID mappings for multiple 3PIDs. * * @param {Array.>} query Array of arrays containing * [medium, address] * @param {string} identityAccessToken The `access_token` field of the Identity * Server `/account/register` response (see {@link registerWithIdentityServer}). * * @return {Promise} Resolves: Lookup results from IS. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.bulkLookupThreePids = /*#__PURE__*/function () { var _ref11 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(query, identityAccessToken) { var response, v1results, _iterator2, _step2, _loop; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _context11.next = 2; return this.identityHashedLookup( // We have to reverse the query order to get [address, medium] pairs query.map(function (p) { return [p[1], p[0]]; }), identityAccessToken); case 2: response = _context11.sent; v1results = []; _iterator2 = _createForOfIteratorHelper(response); try { _loop = function _loop() { var mapping = _step2.value; var originalQuery = query.find(function (p) { return p[1] === mapping.address; }); if (!originalQuery) { throw new Error("Identity sever returned unexpected results"); } v1results.push([originalQuery[0], // medium mapping.address, mapping.mxid]); }; for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { _loop(); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return _context11.abrupt("return", { threepids: v1results }); case 7: case "end": return _context11.stop(); } } }, _callee11, this); })); return function (_x35, _x36) { return _ref11.apply(this, arguments); }; }(); /** * Get account info from the Identity Server. This is useful as a neutral check * to verify that other APIs are likely to approve access by testing that the * token is valid, terms have been agreed, etc. * * @param {string} identityAccessToken The `access_token` field of the Identity * Server `/account/register` response (see {@link registerWithIdentityServer}). * * @return {Promise} Resolves: an object with account info. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixBaseApis.prototype.getIdentityAccount = function (identityAccessToken) { return this._http.idServerRequest(undefined, "GET", "/account", undefined, _httpApi.PREFIX_IDENTITY_V2, identityAccessToken); }; // Direct-to-device messaging // ========================== /** * Send an event to a specific list of devices * * @param {string} eventType type of event to send * @param {Object.>} contentMap * content to send. Map from user_id to device_id to content object. * @param {string=} txnId transaction id. One will be made up if not * supplied. * @return {Promise} Resolves to the result object */ MatrixBaseApis.prototype.sendToDevice = function (eventType, contentMap, txnId) { var path = utils.encodeUri("/sendToDevice/$eventType/$txnId", { $eventType: eventType, $txnId: txnId ? txnId : this.makeTxnId() }); var body = { messages: contentMap }; var targets = Object.keys(contentMap).reduce(function (obj, key) { obj[key] = Object.keys(contentMap[key]); return obj; }, {}); _logger.logger.log("PUT ".concat(path), targets); return this._http.authedRequest(undefined, "PUT", path, undefined, body); }; // Third party Lookup API // ====================== /** * Get the third party protocols that can be reached using * this HS * @return {Promise} Resolves to the result object */ MatrixBaseApis.prototype.getThirdpartyProtocols = function () { return this._http.authedRequest(undefined, "GET", "/thirdparty/protocols", undefined, undefined).then(function (response) { // sanity check if (!response || (0, _typeof2["default"])(response) !== 'object') { throw new Error("/thirdparty/protocols did not return an object: ".concat(response)); } return response; }); }; /** * Get information on how a specific place on a third party protocol * may be reached. * @param {string} protocol The protocol given in getThirdpartyProtocols() * @param {object} params Protocol-specific parameters, as given in the * response to getThirdpartyProtocols() * @return {Promise} Resolves to the result object */ MatrixBaseApis.prototype.getThirdpartyLocation = function (protocol, params) { var path = utils.encodeUri("/thirdparty/location/$protocol", { $protocol: protocol }); return this._http.authedRequest(undefined, "GET", path, params, undefined); }; /** * Get information on how a specific user on a third party protocol * may be reached. * @param {string} protocol The protocol given in getThirdpartyProtocols() * @param {object} params Protocol-specific parameters, as given in the * response to getThirdpartyProtocols() * @return {Promise} Resolves to the result object */ MatrixBaseApis.prototype.getThirdpartyUser = function (protocol, params) { var path = utils.encodeUri("/thirdparty/user/$protocol", { $protocol: protocol }); return this._http.authedRequest(undefined, "GET", path, params, undefined); }; MatrixBaseApis.prototype.getTerms = function (serviceType, baseUrl) { var url = termsUrlForService(serviceType, baseUrl); return this._http.requestOtherUrl(undefined, 'GET', url); }; MatrixBaseApis.prototype.agreeToTerms = function (serviceType, baseUrl, accessToken, termsUrls) { var url = termsUrlForService(serviceType, baseUrl); var headers = { Authorization: "Bearer " + accessToken }; return this._http.requestOtherUrl(undefined, 'POST', url, null, { user_accepts: termsUrls }, { headers: headers }); }; /** * Reports an event as inappropriate to the server, which may then notify the appropriate people. * @param {string} roomId The room in which the event being reported is located. * @param {string} eventId The event to report. * @param {number} score The score to rate this content as where -100 is most offensive and 0 is inoffensive. * @param {string} reason The reason the content is being reported. May be blank. * @returns {Promise} Resolves to an empty object if successful */ MatrixBaseApis.prototype.reportEvent = function (roomId, eventId, score, reason) { var path = utils.encodeUri("/rooms/$roomId/report/$eventId", { $roomId: roomId, $eventId: eventId }); return this._http.authedRequest(undefined, "POST", path, null, { score: score, reason: reason }); }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./http-api":92,"./logger":95,"./pushprocessor":109,"./service-types":113,"./utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/typeof":24,"@babel/runtime/regenerator":27}],56:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = {}; exports["default"] = void 0; var matrixcs = _interopRequireWildcard(require("./matrix")); Object.keys(matrixcs).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return matrixcs[key]; } }); }); var _browserRequest = _interopRequireDefault(require("browser-request")); var _qs = _interopRequireDefault(require("qs")); /* Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ matrixcs.request(function (opts, fn) { // We manually fix the query string for browser-request because // it doesn't correctly handle cases like ?via=one&via=two. Instead // we mimic `request`'s query string interface to make it all work // as expected. // browser-request will happily take the constructed string as the // query string without trying to modify it further. opts.qs = _qs["default"].stringify(opts.qs || {}, opts.qsStringifyOptions); return (0, _browserRequest["default"])(opts, fn); }); // just *accessing* indexedDB throws an exception in firefox with // indexeddb disabled. var indexedDB; try { indexedDB = global.indexedDB; } catch (e) {} // if our browser (appears to) support indexeddb, use an indexeddb crypto store. if (indexedDB) { matrixcs.setCryptoStoreFactory(function () { return new matrixcs.IndexedDBCryptoStore(indexedDB, "matrix-js-sdk:crypto"); }); } // We export 3 things to make browserify happy as well as downstream projects. // It's awkward, but required. var _default = matrixcs; // keep export for browserify package deps exports["default"] = _default; global.matrixcs = matrixcs; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./matrix":96,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"browser-request":31,"qs":40}],57:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixClient = MatrixClient; exports.CRYPTO_ENABLED = void 0; var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _url = _interopRequireDefault(require("url")); var _events = require("events"); var _baseApis = require("./base-apis"); var _filter = require("./filter"); var _sync = require("./sync"); var _event2 = require("./models/event"); var _eventTimeline = require("./models/event-timeline"); var _searchResult = require("./models/search-result"); var _stub = require("./store/stub"); var _call = require("./webrtc/call"); var utils = _interopRequireWildcard(require("./utils")); var _httpApi = require("./http-api"); var _contentRepo = require("./content-repo"); var ContentHelpers = _interopRequireWildcard(require("./content-helpers")); var olmlib = _interopRequireWildcard(require("./crypto/olmlib")); var _ReEmitter = require("./ReEmitter"); var _RoomList = require("./crypto/RoomList"); var _logger = require("./logger"); var _crypto = require("./crypto"); var _recoverykey = require("./crypto/recoverykey"); var _key_passphrase = require("./crypto/key_passphrase"); var _randomstring = require("./randomstring"); var _pushprocessor = require("./pushprocessor"); var _user = require("./models/user"); var _autodiscovery = require("./autodiscovery"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var SCROLLBACK_DELAY_MS = 3000; var CRYPTO_ENABLED = (0, _crypto.isCryptoAvailable)(); exports.CRYPTO_ENABLED = CRYPTO_ENABLED; var CAPABILITIES_CACHE_MS = 21600000; // 6 hours - an arbitrary value function keysFromRecoverySession(sessions, decryptionKey, roomId) { var keys = []; for (var _i = 0, _Object$entries = Object.entries(sessions); _i < _Object$entries.length; _i++) { var _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2), sessionId = _Object$entries$_i[0], sessionData = _Object$entries$_i[1]; try { var decrypted = keyFromRecoverySession(sessionData, decryptionKey); decrypted.session_id = sessionId; decrypted.room_id = roomId; keys.push(decrypted); } catch (e) { _logger.logger.log("Failed to decrypt megolm session from backup", e); } } return keys; } function keyFromRecoverySession(session, decryptionKey) { return JSON.parse(decryptionKey.decrypt(session.session_data.ephemeral, session.session_data.mac, session.session_data.ciphertext)); } /** * Construct a Matrix Client. Only directly construct this if you want to use * custom modules. Normally, {@link createClient} should be used * as it specifies 'sensible' defaults for these modules. * @constructor * @extends {external:EventEmitter} * @extends {module:base-apis~MatrixBaseApis} * * @param {Object} opts The configuration options for this client. * @param {string} opts.baseUrl Required. The base URL to the client-server * HTTP API. * @param {string} opts.idBaseUrl Optional. The base identity server URL for * identity server requests. * @param {Function} opts.request Required. The function to invoke for HTTP * requests. The value of this property is typically require("request") * as it returns a function which meets the required interface. See * {@link requestFunction} for more information. * * @param {string} opts.accessToken The access_token for this user. * * @param {string} opts.userId The user ID for this user. * * @param {Object} opts.deviceToImport Device data exported with * "exportDevice" method that must be imported to recreate this device. * Should only be useful for devices with end-to-end crypto enabled. * If provided, opts.deviceId and opts.userId should **NOT** be provided * (they are present in the exported data). * * @param {string} opts.pickleKey Key used to pickle olm objects or other * sensitive data. * * @param {IdentityServerProvider} [opts.identityServer] * Optional. A provider object with one function `getAccessToken`, which is a * callback that returns a Promise of an identity access token to supply * with identity requests. If the object is unset, no access token will be * supplied. * See also https://github.com/vector-im/element-web/issues/10615 which seeks to * replace the previous approach of manual access tokens params with this * callback throughout the SDK. * * @param {Object=} opts.store * The data store used for sync data from the homeserver. If not specified, * this client will not store any HTTP responses. The `createClient` helper * will create a default store if needed. * * @param {module:store/session/webstorage~WebStorageSessionStore} opts.sessionStore * A store to be used for end-to-end crypto session data. Most data has been * migrated out of here to `cryptoStore` instead. If not specified, * end-to-end crypto will be disabled. The `createClient` helper * _will not_ create this store at the moment. * * @param {module:crypto.store.base~CryptoStore} opts.cryptoStore * A store to be used for end-to-end crypto session data. If not specified, * end-to-end crypto will be disabled. The `createClient` helper will create * a default store if needed. * * @param {string=} opts.deviceId A unique identifier for this device; used for * tracking things like crypto keys and access tokens. If not specified, * end-to-end crypto will be disabled. * * @param {Object} opts.scheduler Optional. The scheduler to use. If not * specified, this client will not retry requests on failure. This client * will supply its own processing function to * {@link module:scheduler~MatrixScheduler#setProcessFunction}. * * @param {Object} opts.queryParams Optional. Extra query parameters to append * to all requests with this client. Useful for application services which require * ?user_id=. * * @param {Number=} opts.localTimeoutMs Optional. The default maximum amount of * time to wait before timing out HTTP requests. If not specified, there is no timeout. * * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use * Authorization header instead of query param to send the access token to the server. * * @param {boolean} [opts.timelineSupport = false] Set to true to enable * improved timeline support ({@link * module:client~MatrixClient#getEventTimeline getEventTimeline}). It is * disabled by default for compatibility with older clients - in particular to * maintain support for back-paginating the live timeline after a '/sync' * result with a gap. * * @param {boolean} [opts.unstableClientRelationAggregation = false] * Optional. Set to true to enable client-side aggregation of event relations * via `EventTimelineSet#getRelationsForEvent`. * This feature is currently unstable and the API may change without notice. * * @param {Array} [opts.verificationMethods] Optional. The verification method * that the application can handle. Each element should be an item from {@link * module:crypto~verificationMethods verificationMethods}, or a class that * implements the {$link module:crypto/verification/Base verifier interface}. * * @param {boolean} [opts.forceTURN] * Optional. Whether relaying calls through a TURN server should be forced. * * @param {boolean} [opts.fallbackICEServerAllowed] * Optional. Whether to allow a fallback ICE server should be used for negotiating a * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false. * * @param {boolean} [opts.usingExternalCrypto] * Optional. Whether to allow sending messages to encrypted rooms when encryption * is not available internally within this SDK. This is useful if you are using an external * E2E proxy, for example. Defaults to false. * * @param {object} opts.cryptoCallbacks Optional. Callbacks for crypto and cross-signing. * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {function} [opts.cryptoCallbacks.getCrossSigningKey] * Optional. Function to call when a cross-signing private key is needed. * Secure Secret Storage will be used by default if this is unset. * Args: * {string} type The type of key needed. Will be one of "master", * "self_signing", or "user_signing" * {Uint8Array} publicKey The public key matching the expected private key. * This can be passed to checkPrivateKey() along with the private key * in order to check that a given private key matches what is being * requested. * Should return a promise that resolves with the private key as a * UInt8Array or rejects with an error. * * @param {function} [opts.cryptoCallbacks.saveCrossSigningKeys] * Optional. Called when new private keys for cross-signing need to be saved. * Secure Secret Storage will be used by default if this is unset. * Args: * {object} keys the private keys to save. Map of key name to private key * as a UInt8Array. The getPrivateKey callback above will be called * with the corresponding key name when the keys are required again. * * @param {function} [opts.cryptoCallbacks.shouldUpgradeDeviceVerifications] * Optional. Called when there are device-to-device verifications that can be * upgraded into cross-signing verifications. * Args: * {object} users The users whose device verifications can be * upgraded to cross-signing verifications. This will be a map of user IDs * to objects with the properties `devices` (array of the user's devices * that verified their cross-signing key), and `crossSigningInfo` (the * user's cross-signing information) * Should return a promise which resolves with an array of the user IDs who * should be cross-signed. * * @param {function} [opts.cryptoCallbacks.getSecretStorageKey] * Optional. Function called when an encryption key for secret storage * is required. One or more keys will be described in the keys object. * The callback function should return a promise with an array of: * [, ] or null if it cannot provide * any of the keys. * Args: * {object} keys Information about the keys: * { * keys: { * : { * pubkey: {UInt8Array} * }, ... * } * } * {string} name the name of the value we want to read out of SSSS, for UI purposes. * * @param {function} [opts.cryptoCallbacks.cacheSecretStorageKey] * Optional. Function called when a new encryption key for secret storage * has been created. This allows the application a chance to cache this key if * desired to avoid user prompts. * Args: * {string} keyId the ID of the new key * {Uint8Array} key the new private key * * @param {function} [opts.cryptoCallbacks.onSecretRequested] * Optional. Function called when a request for a secret is received from another * device. * Args: * {string} name The name of the secret being requested. * {string} userId The user ID of the client requesting * {string} deviceId The device ID of the client requesting the secret. * {string} requestId The ID of the request. Used to match a * corresponding `crypto.secrets.request_cancelled`. The request ID will be * unique per sender, device pair. * {DeviceTrustLevel} deviceTrust: The trust status of the device requesting * the secret as returned by {@link module:client~MatrixClient#checkDeviceTrust}. */ function MatrixClient(opts) { var _this = this; opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl); opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl); _baseApis.MatrixBaseApis.call(this, opts); this.olmVersion = null; // Populated after initCrypto is done this.reEmitter = new _ReEmitter.ReEmitter(this); this.usingExternalCrypto = opts.usingExternalCrypto; this.store = opts.store || new _stub.StubStore(); this.deviceId = opts.deviceId || null; var userId = opts.userId || null; this.credentials = { userId: userId }; if (opts.deviceToImport) { if (this.deviceId) { _logger.logger.warn('not importing device because' + ' device ID is provided to constructor' + ' independently of exported data'); } else if (this.credentials.userId) { _logger.logger.warn('not importing device because' + ' user ID is provided to constructor' + ' independently of exported data'); } else if (!opts.deviceToImport.deviceId) { _logger.logger.warn('not importing device because no device ID in exported data'); } else { this.deviceId = opts.deviceToImport.deviceId; this.credentials.userId = opts.deviceToImport.userId; // will be used during async initialization of the crypto this._exportedOlmDeviceToImport = opts.deviceToImport.olmDevice; } } else if (opts.pickleKey) { this.pickleKey = opts.pickleKey; } this.scheduler = opts.scheduler; if (this.scheduler) { var self = this; this.scheduler.setProcessFunction( /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(eventToSend) { var room, res; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: room = self.getRoom(eventToSend.getRoomId()); if (eventToSend.status !== _event2.EventStatus.SENDING) { _updatePendingEventStatus(room, eventToSend, _event2.EventStatus.SENDING); } _context.next = 4; return _sendEventHttpRequest(self, eventToSend); case 4: res = _context.sent; if (room) { // ensure we update pending event before the next scheduler run so that any listeners to event id // updates on the synchronous event emitter get a chance to run first. room.updatePendingEvent(eventToSend, _event2.EventStatus.SENT, res.event_id); } return _context.abrupt("return", res); case 7: case "end": return _context.stop(); } } }, _callee); })); return function (_x) { return _ref.apply(this, arguments); }; }()); } this.clientRunning = false; this.callList = {// callId: MatrixCall }; // try constructing a MatrixCall to see if we are running in an environment // which has WebRTC. If we are, listen for and handle m.call.* events. var call = (0, _call.createNewMatrixCall)(this); this._supportsVoip = false; if (call) { setupCallEventHandler(this); this._supportsVoip = true; } this._syncingRetry = null; this._syncApi = null; this._peekSync = null; this._isGuest = false; this._ongoingScrollbacks = {}; this.timelineSupport = Boolean(opts.timelineSupport); this.urlPreviewCache = {}; // key=preview key, value=Promise for preview (may be an error) this._notifTimelineSet = null; this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation; this._crypto = null; this._cryptoStore = opts.cryptoStore; this._sessionStore = opts.sessionStore; this._verificationMethods = opts.verificationMethods; this._cryptoCallbacks = opts.cryptoCallbacks || {}; this._forceTURN = opts.forceTURN || false; this._fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false; // List of which rooms have encryption enabled: separate from crypto because // we still want to know which rooms are encrypted even if crypto is disabled: // we don't want to start sending unencrypted events to them. this._roomList = new _RoomList.RoomList(this._cryptoStore); // The pushprocessor caches useful things, so keep one and re-use it this._pushProcessor = new _pushprocessor.PushProcessor(this); // Promise to a response of the server's /versions response // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020 this._serverVersionsPromise = null; this._cachedCapabilities = null; // { capabilities: {}, lastUpdated: timestamp } this._clientWellKnown = undefined; this._clientWellKnownPromise = undefined; // The SDK doesn't really provide a clean way for events to recalculate the push // actions for themselves, so we have to kinda help them out when they are encrypted. // We do this so that push rules are correctly executed on events in their decrypted // state, such as highlights when the user's name is mentioned. this.on("Event.decrypted", function (event) { var oldActions = event.getPushActions(); var actions = _this._pushProcessor.actionsForEvent(event); event.setPushActions(actions); // Might as well while we're here var room = _this.getRoom(event.getRoomId()); if (!room) return; var currentCount = room.getUnreadNotificationCount("highlight"); // Ensure the unread counts are kept up to date if the event is encrypted // We also want to make sure that the notification count goes up if we already // have encrypted events to avoid other code from resetting 'highlight' to zero. var oldHighlight = oldActions && oldActions.tweaks ? !!oldActions.tweaks.highlight : false; var newHighlight = actions && actions.tweaks ? !!actions.tweaks.highlight : false; if (oldHighlight !== newHighlight || currentCount > 0) { // TODO: Handle mentions received while the client is offline // See also https://github.com/vector-im/element-web/issues/9069 if (!room.hasUserReadEvent(_this.getUserId(), event.getId())) { var newCount = currentCount; if (newHighlight && !oldHighlight) newCount++; if (!newHighlight && oldHighlight) newCount--; room.setUnreadNotificationCount("highlight", newCount); // Fix 'Mentions Only' rooms from not having the right badge count var totalCount = room.getUnreadNotificationCount('total'); if (totalCount < newCount) { room.setUnreadNotificationCount('total', newCount); } } } }); // Like above, we have to listen for read receipts from ourselves in order to // correctly handle notification counts on encrypted rooms. // This fixes https://github.com/vector-im/element-web/issues/9421 this.on("Room.receipt", function (event, room) { if (room && _this.isRoomEncrypted(room.roomId)) { // Figure out if we've read something or if it's just informational var content = event.getContent(); var isSelf = Object.keys(content).filter(function (eid) { return Object.keys(content[eid]['m.read']).includes(_this.getUserId()); }).length > 0; if (!isSelf) return; // Work backwards to determine how many events are unread. We also set // a limit for how back we'll look to avoid spinning CPU for too long. // If we hit the limit, we assume the count is unchanged. var maxHistory = 20; var events = room.getLiveTimeline().getEvents(); var highlightCount = 0; for (var i = events.length - 1; i >= 0; i--) { if (i === events.length - maxHistory) return; // limit reached var _event = events[i]; if (room.hasUserReadEvent(_this.getUserId(), _event.getId())) { // If the user has read the event, then the counting is done. break; } var pushActions = _this.getPushActionsForEvent(_event); highlightCount += pushActions.tweaks && pushActions.tweaks.highlight ? 1 : 0; } // Note: we don't need to handle 'total' notifications because the counts // will come from the server. room.setUnreadNotificationCount("highlight", highlightCount); } }); } utils.inherits(MatrixClient, _events.EventEmitter); utils.extend(MatrixClient.prototype, _baseApis.MatrixBaseApis.prototype); MatrixClient.prototype.exportDevice = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (this._crypto) { _context2.next = 3; break; } _logger.logger.warn('not exporting device if crypto is not enabled'); return _context2.abrupt("return"); case 3: _context2.t0 = this.credentials.userId; _context2.t1 = this.deviceId; _context2.next = 7; return this._crypto._olmDevice["export"](); case 7: _context2.t2 = _context2.sent; return _context2.abrupt("return", { userId: _context2.t0, deviceId: _context2.t1, olmDevice: _context2.t2 }); case 9: case "end": return _context2.stop(); } } }, _callee2, this); })); /** * Clear any data out of the persistent stores used by the client. * * @returns {Promise} Promise which resolves when the stores have been cleared. */ MatrixClient.prototype.clearStores = function () { if (this._clientRunning) { throw new Error("Cannot clear stores while client is running"); } var promises = []; promises.push(this.store.deleteAllData()); if (this._cryptoStore) { promises.push(this._cryptoStore.deleteAllData()); } return Promise.all(promises); }; /** * Get the user-id of the logged-in user * * @return {?string} MXID for the logged-in user, or null if not logged in */ MatrixClient.prototype.getUserId = function () { if (this.credentials && this.credentials.userId) { return this.credentials.userId; } return null; }; /** * Get the domain for this client's MXID * @return {?string} Domain of this MXID */ MatrixClient.prototype.getDomain = function () { if (this.credentials && this.credentials.userId) { return this.credentials.userId.replace(/^.*?:/, ''); } return null; }; /** * Get the local part of the current user ID e.g. "foo" in "@foo:bar". * @return {?string} The user ID localpart or null. */ MatrixClient.prototype.getUserIdLocalpart = function () { if (this.credentials && this.credentials.userId) { return this.credentials.userId.split(":")[0].substring(1); } return null; }; /** * Get the device ID of this client * @return {?string} device ID */ MatrixClient.prototype.getDeviceId = function () { return this.deviceId; }; /** * Check if the runtime environment supports VoIP calling. * @return {boolean} True if VoIP is supported. */ MatrixClient.prototype.supportsVoip = function () { return this._supportsVoip; }; /** * Set whether VoIP calls are forced to use only TURN * candidates. This is the same as the forceTURN option * when creating the client. * @param {bool} forceTURN True to force use of TURN servers */ MatrixClient.prototype.setForceTURN = function (forceTURN) { this._forceTURN = forceTURN; }; /** * Get the current sync state. * @return {?string} the sync state, which may be null. * @see module:client~MatrixClient#event:"sync" */ MatrixClient.prototype.getSyncState = function () { if (!this._syncApi) { return null; } return this._syncApi.getSyncState(); }; /** * Returns the additional data object associated with * the current sync state, or null if there is no * such data. * Sync errors, if available, are put in the 'error' key of * this object. * @return {?Object} */ MatrixClient.prototype.getSyncStateData = function () { if (!this._syncApi) { return null; } return this._syncApi.getSyncStateData(); }; /** * Whether the initial sync has completed. * @return {boolean} True if at least on sync has happened. */ MatrixClient.prototype.isInitialSyncComplete = function () { var state = this.getSyncState(); if (!state) { return false; } return state === "PREPARED" || state === "SYNCING"; }; /** * Return whether the client is configured for a guest account. * @return {boolean} True if this is a guest access_token (or no token is supplied). */ MatrixClient.prototype.isGuest = function () { return this._isGuest; }; /** * Return the provided scheduler, if any. * @return {?module:scheduler~MatrixScheduler} The scheduler or null */ MatrixClient.prototype.getScheduler = function () { return this.scheduler; }; /** * Set whether this client is a guest account. This method is experimental * and may change without warning. * @param {boolean} isGuest True if this is a guest account. */ MatrixClient.prototype.setGuest = function (isGuest) { // EXPERIMENTAL: // If the token is a macaroon, it should be encoded in it that it is a 'guest' // access token, which means that the SDK can determine this entirely without // the dev manually flipping this flag. this._isGuest = isGuest; }; /** * Retry a backed off syncing request immediately. This should only be used when * the user explicitly attempts to retry their lost connection. * @return {boolean} True if this resulted in a request being retried. */ MatrixClient.prototype.retryImmediately = function () { return this._syncApi.retryImmediately(); }; /** * Return the global notification EventTimelineSet, if any * * @return {EventTimelineSet} the globl notification EventTimelineSet */ MatrixClient.prototype.getNotifTimelineSet = function () { return this._notifTimelineSet; }; /** * Set the global notification EventTimelineSet * * @param {EventTimelineSet} notifTimelineSet */ MatrixClient.prototype.setNotifTimelineSet = function (notifTimelineSet) { this._notifTimelineSet = notifTimelineSet; }; /** * Gets the capabilities of the homeserver. Always returns an object of * capability keys and their options, which may be empty. * @param {boolean} fresh True to ignore any cached values. * @return {Promise} Resolves to the capabilities of the homeserver * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getCapabilities = function () { var _this2 = this; var fresh = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var now = new Date().getTime(); if (this._cachedCapabilities && !fresh) { if (now < this._cachedCapabilities.expiration) { _logger.logger.log("Returning cached capabilities"); return Promise.resolve(this._cachedCapabilities.capabilities); } } // We swallow errors because we need a default object anyhow return this._http.authedRequest(undefined, "GET", "/capabilities")["catch"](function (e) { _logger.logger.error(e); return null; // otherwise consume the error }).then(function (r) { if (!r) r = {}; var capabilities = r["capabilities"] || {}; // If the capabilities missed the cache, cache it for a shorter amount // of time to try and refresh them later. var cacheMs = Object.keys(capabilities).length ? CAPABILITIES_CACHE_MS : 60000 + Math.random() * 5000; _this2._cachedCapabilities = { capabilities: capabilities, expiration: now + cacheMs }; _logger.logger.log("Caching capabilities: ", capabilities); return capabilities; }); }; // Crypto bits // =========== /** * Initialise support for end-to-end encryption in this client * * You should call this method after creating the matrixclient, but *before* * calling `startClient`, if you want to support end-to-end encryption. * * It will return a Promise which will resolve when the crypto layer has been * successfully initialised. */ MatrixClient.prototype.initCrypto = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { var userId, crypto; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if ((0, _crypto.isCryptoAvailable)()) { _context3.next = 2; break; } throw new Error("End-to-end encryption not supported in this js-sdk build: did " + "you remember to load the olm library?"); case 2: if (!this._crypto) { _context3.next = 5; break; } _logger.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient"); return _context3.abrupt("return"); case 5: if (this._sessionStore) { _context3.next = 7; break; } throw new Error("Cannot enable encryption: no sessionStore provided"); case 7: if (this._cryptoStore) { _context3.next = 9; break; } throw new Error("Cannot enable encryption: no cryptoStore provided"); case 9: _logger.logger.log("Crypto: Starting up crypto store..."); _context3.next = 12; return this._cryptoStore.startup(); case 12: // initialise the list of encrypted rooms (whether or not crypto is enabled) _logger.logger.log("Crypto: initialising roomlist..."); _context3.next = 15; return this._roomList.init(); case 15: userId = this.getUserId(); if (!(userId === null)) { _context3.next = 18; break; } throw new Error("Cannot enable encryption on MatrixClient with unknown userId: " + "ensure userId is passed in createClient()."); case 18: if (!(this.deviceId === null)) { _context3.next = 20; break; } throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: " + "ensure deviceId is passed in createClient()."); case 20: crypto = new _crypto.Crypto(this, this._sessionStore, userId, this.deviceId, this.store, this._cryptoStore, this._roomList, this._verificationMethods); this.reEmitter.reEmit(crypto, ["crypto.keyBackupFailed", "crypto.keyBackupSessionsRemaining", "crypto.roomKeyRequest", "crypto.roomKeyRequestCancellation", "crypto.warning", "crypto.devicesUpdated", "crypto.willUpdateDevices", "deviceVerificationChanged", "userTrustStatusChanged", "crossSigning.keysChanged"]); _logger.logger.log("Crypto: initialising crypto object..."); _context3.next = 25; return crypto.init({ exportedOlmDevice: this._exportedOlmDeviceToImport, pickleKey: this.pickleKey }); case 25: delete this._exportedOlmDeviceToImport; this.olmVersion = _crypto.Crypto.getOlmVersion(); // if crypto initialisation was successful, tell it to attach its event // handlers. crypto.registerEventHandlers(this); this._crypto = crypto; case 29: case "end": return _context3.stop(); } } }, _callee3, this); })); /** * Is end-to-end crypto enabled for this client. * @return {boolean} True if end-to-end is enabled. */ MatrixClient.prototype.isCryptoEnabled = function () { return this._crypto !== null; }; /** * Get the Ed25519 key for this device * * @return {?string} base64-encoded ed25519 key. Null if crypto is * disabled. */ MatrixClient.prototype.getDeviceEd25519Key = function () { if (!this._crypto) { return null; } return this._crypto.getDeviceEd25519Key(); }; /** * Get the Curve25519 key for this device * * @return {?string} base64-encoded curve25519 key. Null if crypto is * disabled. */ MatrixClient.prototype.getDeviceCurve25519Key = function () { if (!this._crypto) { return null; } return this._crypto.getDeviceCurve25519Key(); }; /** * Upload the device keys to the homeserver. * @return {object} A promise that will resolve when the keys are uploaded. */ MatrixClient.prototype.uploadKeys = function () { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.uploadDeviceKeys(); }; /** * Download the keys for a list of users and stores the keys in the session * store. * @param {Array} userIds The users to fetch. * @param {bool} forceDownload Always download the keys even if cached. * * @return {Promise} A promise which resolves to a map userId->deviceId->{@link * module:crypto~DeviceInfo|DeviceInfo}. */ MatrixClient.prototype.downloadKeys = function (userIds, forceDownload) { if (this._crypto === null) { return Promise.reject(new Error("End-to-end encryption disabled")); } return this._crypto.downloadKeys(userIds, forceDownload); }; /** * Get the stored device keys for a user id * * @param {string} userId the user to list keys for. * * @return {module:crypto/deviceinfo[]} list of devices */ MatrixClient.prototype.getStoredDevicesForUser = function (userId) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.getStoredDevicesForUser(userId) || []; }; /** * Get the stored device key for a user id and device id * * @param {string} userId the user to list keys for. * @param {string} deviceId unique identifier for the device * * @return {module:crypto/deviceinfo} device or null */ MatrixClient.prototype.getStoredDevice = function (userId, deviceId) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.getStoredDevice(userId, deviceId) || null; }; /** * Mark the given device as verified * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {boolean=} verified whether to mark the device as verified. defaults * to 'true'. * * @returns {Promise} * * @fires module:client~event:MatrixClient"deviceVerificationChanged" */ MatrixClient.prototype.setDeviceVerified = function (userId, deviceId, verified) { if (verified === undefined) { verified = true; } var prom = _setDeviceVerification(this, userId, deviceId, verified, null); // if one of the user's own devices is being marked as verified / unverified, // check the key backup status, since whether or not we use this depends on // whether it has a signature from a verified device if (userId == this.credentials.userId) { this._crypto.checkKeyBackup(); } return prom; }; /** * Mark the given device as blocked/unblocked * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {boolean=} blocked whether to mark the device as blocked. defaults * to 'true'. * * @returns {Promise} * * @fires module:client~event:MatrixClient"deviceVerificationChanged" */ MatrixClient.prototype.setDeviceBlocked = function (userId, deviceId, blocked) { if (blocked === undefined) { blocked = true; } return _setDeviceVerification(this, userId, deviceId, null, blocked); }; /** * Mark the given device as known/unknown * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {boolean=} known whether to mark the device as known. defaults * to 'true'. * * @returns {Promise} * * @fires module:client~event:MatrixClient"deviceVerificationChanged" */ MatrixClient.prototype.setDeviceKnown = function (userId, deviceId, known) { if (known === undefined) { known = true; } return _setDeviceVerification(this, userId, deviceId, null, null, known); }; function _setDeviceVerification(_x2, _x3, _x4, _x5, _x6, _x7) { return _setDeviceVerification2.apply(this, arguments); } /** * Request a key verification from another user, using a DM. * * @param {string} userId the user to request verification with * @param {string} roomId the room to use for verification * * @returns {Promise} resolves to a VerificationRequest * when the request has been sent to the other party. */ function _setDeviceVerification2() { _setDeviceVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee29(client, userId, deviceId, verified, blocked, known) { return _regenerator["default"].wrap(function _callee29$(_context29) { while (1) { switch (_context29.prev = _context29.next) { case 0: if (client._crypto) { _context29.next = 2; break; } throw new Error("End-to-End encryption disabled"); case 2: _context29.next = 4; return client._crypto.setDeviceVerification(userId, deviceId, verified, blocked, known); case 4: case "end": return _context29.stop(); } } }, _callee29); })); return _setDeviceVerification2.apply(this, arguments); } MatrixClient.prototype.requestVerificationDM = function (userId, roomId) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.requestVerificationDM(userId, roomId); }; /** * Finds a DM verification request that is already in progress for the given room id * * @param {string} roomId the room to use for verification * * @returns {module:crypto/verification/request/VerificationRequest?} the VerificationRequest that is in progress, if any */ MatrixClient.prototype.findVerificationRequestDMInProgress = function (roomId) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.findVerificationRequestDMInProgress(roomId); }; /** * Returns all to-device verification requests that are already in progress for the given user id * * @param {string} userId the ID of the user to query * * @returns {module:crypto/verification/request/VerificationRequest[]} the VerificationRequests that are in progress */ MatrixClient.prototype.getVerificationRequestsToDeviceInProgress = function (userId) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.getVerificationRequestsToDeviceInProgress(userId); }; /** * Request a key verification from another user. * * @param {string} userId the user to request verification with * @param {Array} devices array of device IDs to send requests to. Defaults to * all devices owned by the user * * @returns {Promise} resolves to a VerificationRequest * when the request has been sent to the other party. */ MatrixClient.prototype.requestVerification = function (userId, devices) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.requestVerification(userId, devices); }; /** * Begin a key verification. * * @param {string} method the verification method to use * @param {string} userId the user to verify keys with * @param {string} deviceId the device to verify * * @returns {module:crypto/verification/Base} a verification object */ MatrixClient.prototype.beginKeyVerification = function (method, userId, deviceId) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.beginKeyVerification(method, userId, deviceId); }; /** * Set the global override for whether the client should ever send encrypted * messages to unverified devices. This provides the default for rooms which * do not specify a value. * * @param {boolean} value whether to blacklist all unverified devices by default */ MatrixClient.prototype.setGlobalBlacklistUnverifiedDevices = function (value) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } this._crypto.setGlobalBlacklistUnverifiedDevices(value); }; /** * @return {boolean} whether to blacklist all unverified devices by default */ MatrixClient.prototype.getGlobalBlacklistUnverifiedDevices = function () { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.getGlobalBlacklistUnverifiedDevices(); }; /** * Set whether sendMessage in a room with unknown and unverified devices * should throw an error and not send them message. This has 'Global' for * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently * no room-level equivalent for this setting. * * This API is currently UNSTABLE and may change or be removed without notice. * * @param {boolean} value whether error on unknown devices */ MatrixClient.prototype.setGlobalErrorOnUnknownDevices = function (value) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } this._crypto.setGlobalErrorOnUnknownDevices(value); }; /** * @return {boolean} whether to error on unknown devices * * This API is currently UNSTABLE and may change or be removed without notice. */ MatrixClient.prototype.getGlobalErrorOnUnknownDevices = function () { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.getGlobalErrorOnUnknownDevices(); }; /** * Add methods that call the corresponding method in this._crypto * * @param {class} MatrixClient the class to add the method to * @param {string} names the names of the methods to call */ function wrapCryptoFuncs(MatrixClient, names) { var _iterator = _createForOfIteratorHelper(names), _step; try { var _loop = function _loop() { var name = _step.value; MatrixClient.prototype[name] = function () { var _this$_crypto; if (!this._crypto) { // eslint-disable-line no-invalid-this throw new Error("End-to-end encryption disabled"); } return (_this$_crypto = this._crypto)[name].apply(_this$_crypto, arguments); // eslint-disable-line no-invalid-this }; }; for (_iterator.s(); !(_step = _iterator.n()).done;) { _loop(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } /** * Get the user's cross-signing key ID. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#getCrossSigningId * @param {string} [type=master] The type of key to get the ID of. One of * "master", "self_signing", or "user_signing". Defaults to "master". * * @returns {string} the key ID */ /** * Get the cross signing information for a given user. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#getStoredCrossSigningForUser * @param {string} userId the user ID to get the cross-signing info for. * * @returns {CrossSigningInfo} the cross signing information for the user. */ /** * Check whether a given user is trusted. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#checkUserTrust * @param {string} userId The ID of the user to check. * * @returns {UserTrustLevel} */ /** * Check whether a given device is trusted. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#checkDeviceTrust * @param {string} userId The ID of the user whose devices is to be checked. * @param {string} deviceId The ID of the device to check * * @returns {DeviceTrustLevel} */ /** * Check the copy of our cross-signing key that we have in the device list and * see if we can get the private key. If so, mark it as trusted. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#checkOwnCrossSigningTrust */ /** * Checks that a given cross-signing private key matches a given public key. * This can be used by the getCrossSigningKey callback to verify that the * private key it is about to supply is the one that was requested. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#checkCrossSigningPrivateKey * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ /** * Perform any background tasks that can be done before a message is ready to * send, in order to speed up sending of the message. * * @function module:client~MatrixClient#prepareToEncrypt * @param {module:models/room} room the room the event is in */ /** * Checks whether cross signing: * - is enabled on this account and trusted by this device * - has private keys either cached locally or stored in secret storage * * If this function returns false, bootstrapCrossSigning() can be used * to fix things such that it returns true. That is to say, after * bootstrapCrossSigning() completes successfully, this function should * return true. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#isCrossSigningReady * @return {bool} True if cross-signing is ready to be used on this device */ /** * Bootstrap cross-signing by creating keys if needed. If everything is already * set up, then no changes are made, so this is safe to run to ensure * cross-signing is ready for use. * * This function: * - creates new cross-signing keys if they are not found locally cached nor in * secret storage (if it has been setup) * * The cross-signing API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#bootstrapCrossSigning * @param {function} opts.authUploadDeviceSigningKeys Function * called to await an interactive auth flow when uploading device signing keys. * @param {bool} [opts.setupNewCrossSigning] Optional. Reset even if keys * already exist. * Args: * {function} A function that makes the request requiring auth. Receives the * auth data as an object. Can be called multiple times, first with an empty * authDict, to obtain the flows. */ wrapCryptoFuncs(MatrixClient, ["getCrossSigningId", "getStoredCrossSigningForUser", "checkUserTrust", "checkDeviceTrust", "checkOwnCrossSigningTrust", "checkCrossSigningPrivateKey", "legacyDeviceVerification", "prepareToEncrypt", "isCrossSigningReady", "bootstrapCrossSigning", "getCryptoTrustCrossSignedDevices", "setCryptoTrustCrossSignedDevices", "countSessionsNeedingBackup"]); /** * Get information about the encryption of an event * * @function module:client~MatrixClient#getEventEncryptionInfo * * @param {module:models/event.MatrixEvent} event event to be checked * * @return {object} An object with the fields: * - encrypted: whether the event is encrypted (if not encrypted, some of the * other properties may not be set) * - senderKey: the sender's key * - algorithm: the algorithm used to encrypt the event * - authenticated: whether we can be sure that the owner of the senderKey * sent the event * - sender: the sender's device information, if available * - mismatchedSender: if the event's ed25519 and curve25519 keys don't match * (only meaningful if `sender` is set) */ /** * Create a recovery key from a user-supplied passphrase. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#createRecoveryKeyFromPassphrase * @param {string} password Passphrase string that can be entered by the user * when restoring the backup as an alternative to entering the recovery key. * Optional. * @returns {Promise} Object with public key metadata, encoded private * recovery key which should be disposed of after displaying to the user, * and raw private key to avoid round tripping if needed. */ /** * Checks whether secret storage: * - is enabled on this account * - is storing cross-signing private keys * - is storing session backup key (if enabled) * * If this function returns false, bootstrapSecretStorage() can be used * to fix things such that it returns true. That is to say, after * bootstrapSecretStorage() completes successfully, this function should * return true. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#isSecretStorageReady * @return {bool} True if secret storage is ready to be used on this device */ /** * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is * already set up, then no changes are made, so this is safe to run to ensure secret * storage is ready for use. * * This function * - creates a new Secure Secret Storage key if no default key exists * - if a key backup exists, it is migrated to store the key in the Secret * Storage * - creates a backup if none exists, and one is requested * - migrates Secure Secret Storage to use the latest algorithm, if an outdated * algorithm is found * * @function module:client~MatrixClient#bootstrapSecretStorage * @param {function} [opts.createSecretStorageKey] Optional. Function * called to await a secret storage key creation flow. * Returns: * {Promise} Object with public key metadata, encoded private * recovery key which should be disposed of after displaying to the user, * and raw private key to avoid round tripping if needed. * @param {object} [opts.keyBackupInfo] The current key backup object. If passed, * the passphrase and recovery key from this backup will be used. * @param {bool} [opts.setupNewKeyBackup] If true, a new key backup version will be * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo * is supplied. * @param {bool} [opts.setupNewSecretStorage] Optional. Reset even if keys already exist. * @param {func} [opts.getKeyBackupPassphrase] Optional. Function called to get the user's * current key backup passphrase. Should return a promise that resolves with a Buffer * containing the key, or rejects if the key cannot be obtained. * Returns: * {Promise} A promise which resolves to key creation data for * SecretStorage#addKey: an object with `passphrase` and/or `pubkey` fields. */ /** * Add a key for encrypting secrets. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#addSecretStorageKey * @param {string} algorithm the algorithm used by the key * @param {object} opts the options for the algorithm. The properties used * depend on the algorithm given. * @param {string} [keyName] the name of the key. If not given, a random * name will be generated. * * @return {string} the name of the key */ /** * Check whether we have a key with a given ID. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#hasSecretStorageKey * @param {string} [keyId = default key's ID] The ID of the key to check * for. Defaults to the default key ID if not provided. * @return {boolean} Whether we have the key. */ /** * Store an encrypted secret on the server. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#storeSecret * @param {string} name The name of the secret * @param {string} secret The secret contents. * @param {Array} keys The IDs of the keys to use to encrypt the secret or null/undefined * to use the default (will throw if no default key is set). */ /** * Get a secret from storage. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#getSecret * @param {string} name the name of the secret * * @return {string} the contents of the secret */ /** * Check if a secret is stored on the server. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#isSecretStored * @param {string} name the name of the secret * @param {boolean} checkKey check if the secret is encrypted by a trusted * key * * @return {object?} map of key name to key info the secret is encrypted * with, or null if it is not present or not encrypted with a trusted * key */ /** * Request a secret from another device. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#requestSecret * @param {string} name the name of the secret to request * @param {string[]} devices the devices to request the secret from * * @return {string} the contents of the secret */ /** * Get the current default key ID for encrypting secrets. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#getDefaultSecretStorageKeyId * * @return {string} The default key ID or null if no default key ID is set */ /** * Set the current default key ID for encrypting secrets. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#setDefaultSecretStorageKeyId * @param {string} keyId The new default key ID */ /** * Checks that a given secret storage private key matches a given public key. * This can be used by the getSecretStorageKey callback to verify that the * private key it is about to supply is the one that was requested. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @function module:client~MatrixClient#checkSecretStoragePrivateKey * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ wrapCryptoFuncs(MatrixClient, ["getEventEncryptionInfo", "createRecoveryKeyFromPassphrase", "isSecretStorageReady", "bootstrapSecretStorage", "addSecretStorageKey", "hasSecretStorageKey", "storeSecret", "getSecret", "isSecretStored", "requestSecret", "getDefaultSecretStorageKeyId", "setDefaultSecretStorageKeyId", "checkSecretStorageKey", "checkSecretStoragePrivateKey"]); /** * Get e2e information on the device that sent an event * * @param {MatrixEvent} event event to be checked * * @return {Promise} */ MatrixClient.prototype.getEventSenderDeviceInfo = /*#__PURE__*/function () { var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(event) { return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (this._crypto) { _context4.next = 2; break; } return _context4.abrupt("return", null); case 2: return _context4.abrupt("return", this._crypto.getEventSenderDeviceInfo(event)); case 3: case "end": return _context4.stop(); } } }, _callee4, this); })); return function (_x8) { return _ref4.apply(this, arguments); }; }(); /** * Check if the sender of an event is verified * * @param {MatrixEvent} event event to be checked * * @return {boolean} true if the sender of this event has been verified using * {@link module:client~MatrixClient#setDeviceVerified|setDeviceVerified}. */ MatrixClient.prototype.isEventSenderVerified = /*#__PURE__*/function () { var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(event) { var device; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this.getEventSenderDeviceInfo(event); case 2: device = _context5.sent; if (device) { _context5.next = 5; break; } return _context5.abrupt("return", false); case 5: return _context5.abrupt("return", device.isVerified()); case 6: case "end": return _context5.stop(); } } }, _callee5, this); })); return function (_x9) { return _ref5.apply(this, arguments); }; }(); /** * Cancel a room key request for this event if one is ongoing and resend the * request. * @param {MatrixEvent} event event of which to cancel and resend the room * key request. * @return {Promise} A promise that will resolve when the key request is queued */ MatrixClient.prototype.cancelAndResendEventRoomKeyRequest = function (event) { return event.cancelAndResendKeyRequest(this._crypto, this.getUserId()); }; /** * Enable end-to-end encryption for a room. This does not modify room state. * Any messages sent before the returned promise resolves will be sent unencrypted. * @param {string} roomId The room ID to enable encryption in. * @param {object} config The encryption config for the room. * @return {Promise} A promise that will resolve when encryption is set up. */ MatrixClient.prototype.setRoomEncryption = function (roomId, config) { if (!this._crypto) { throw new Error("End-to-End encryption disabled"); } return this._crypto.setRoomEncryption(roomId, config); }; /** * Whether encryption is enabled for a room. * @param {string} roomId the room id to query. * @return {bool} whether encryption is enabled. */ MatrixClient.prototype.isRoomEncrypted = function (roomId) { var room = this.getRoom(roomId); if (!room) { // we don't know about this room, so can't determine if it should be // encrypted. Let's assume not. return false; } // if there is an 'm.room.encryption' event in this room, it should be // encrypted (independently of whether we actually support encryption) var ev = room.currentState.getStateEvents("m.room.encryption", ""); if (ev) { return true; } // we don't have an m.room.encrypted event, but that might be because // the server is hiding it from us. Check the store to see if it was // previously encrypted. return this._roomList.isRoomEncrypted(roomId); }; /** * Forces the current outbound group session to be discarded such * that another one will be created next time an event is sent. * * @param {string} roomId The ID of the room to discard the session for * * This should not normally be necessary. */ MatrixClient.prototype.forceDiscardSession = function (roomId) { if (!this._crypto) { throw new Error("End-to-End encryption disabled"); } this._crypto.forceDiscardSession(roomId); }; /** * Get a list containing all of the room keys * * This should be encrypted before returning it to the user. * * @return {Promise} a promise which resolves to a list of * session export objects */ MatrixClient.prototype.exportRoomKeys = function () { if (!this._crypto) { return Promise.reject(new Error("End-to-end encryption disabled")); } return this._crypto.exportRoomKeys(); }; /** * Import a list of room keys previously exported by exportRoomKeys * * @param {Object[]} keys a list of session export objects * @param {Object} opts * @param {Function} opts.progressCallback called with an object that has a "stage" param * * @return {Promise} a promise which resolves when the keys * have been imported */ MatrixClient.prototype.importRoomKeys = function (keys, opts) { if (!this._crypto) { throw new Error("End-to-end encryption disabled"); } return this._crypto.importRoomKeys(keys, opts); }; /** * Force a re-check of the local key backup status against * what's on the server. * * @returns {Object} Object with backup info (as returned by * getKeyBackupVersion) in backupInfo and * trust information (as returned by isKeyBackupTrusted) * in trustInfo. */ MatrixClient.prototype.checkKeyBackup = function () { return this._crypto.checkKeyBackup(); }; /** * Get information about the current key backup. * @returns {Promise} Information object from API or null */ MatrixClient.prototype.getKeyBackupVersion = function () { return this._http.authedRequest(undefined, "GET", "/room_keys/version", undefined, undefined, { prefix: _httpApi.PREFIX_UNSTABLE }).then(function (res) { if (res.algorithm !== olmlib.MEGOLM_BACKUP_ALGORITHM) { var _err = "Unknown backup algorithm: " + res.algorithm; return Promise.reject(_err); } else if (!((0, _typeof2["default"])(res.auth_data) === "object") || !res.auth_data.public_key) { var _err2 = "Invalid backup data returned"; return Promise.reject(_err2); } else { return res; } })["catch"](function (e) { if (e.errcode === 'M_NOT_FOUND') { return null; } else { throw e; } }); }; /** * @param {object} info key backup info dict from getKeyBackupVersion() * @return {object} { * usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device * sigs: [ * valid: [bool], * device: [DeviceInfo], * ] * } */ MatrixClient.prototype.isKeyBackupTrusted = function (info) { return this._crypto.isKeyBackupTrusted(info); }; /** * @returns {bool} true if the client is configured to back up keys to * the server, otherwise false. If we haven't completed a successful check * of key backup status yet, returns null. */ MatrixClient.prototype.getKeyBackupEnabled = function () { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } if (!this._crypto._checkedForBackup) { return null; } return Boolean(this._crypto.backupKey); }; /** * Enable backing up of keys, using data previously returned from * getKeyBackupVersion. * * @param {object} info Backup information object as returned by getKeyBackupVersion */ MatrixClient.prototype.enableKeyBackup = function (info) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } this._crypto.backupInfo = info; if (this._crypto.backupKey) this._crypto.backupKey.free(); this._crypto.backupKey = new global.Olm.PkEncryption(); this._crypto.backupKey.set_recipient_key(info.auth_data.public_key); this.emit('crypto.keyBackupStatus', true); // There may be keys left over from a partially completed backup, so // schedule a send to check. this._crypto.scheduleKeyBackupSend(); }; /** * Disable backing up of keys. */ MatrixClient.prototype.disableKeyBackup = function () { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } this._crypto.backupInfo = null; if (this._crypto.backupKey) this._crypto.backupKey.free(); this._crypto.backupKey = null; this.emit('crypto.keyBackupStatus', false); }; /** * Set up the data required to create a new backup version. The backup version * will not be created and enabled until createKeyBackupVersion is called. * * @param {string} password Passphrase string that can be entered by the user * when restoring the backup as an alternative to entering the recovery key. * Optional. * @param {boolean} [opts.secureSecretStorage = false] Whether to use Secure * Secret Storage to store the key encrypting key backups. * Optional, defaults to false. * * @returns {Promise} Object that can be passed to createKeyBackupVersion and * additionally has a 'recovery_key' member with the user-facing recovery key string. */ MatrixClient.prototype.prepareKeyBackupVersion = /*#__PURE__*/function () { var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(password) { var _ref7, _ref7$secureSecretSto, secureSecretStorage, _yield$this$createRec, keyInfo, encodedPrivateKey, privateKey, authData, _args6 = arguments; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _ref7 = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : {}, _ref7$secureSecretSto = _ref7.secureSecretStorage, secureSecretStorage = _ref7$secureSecretSto === void 0 ? false : _ref7$secureSecretSto; if (!(this._crypto === null)) { _context6.next = 3; break; } throw new Error("End-to-end encryption disabled"); case 3: _context6.next = 5; return this.createRecoveryKeyFromPassphrase(password); case 5: _yield$this$createRec = _context6.sent; keyInfo = _yield$this$createRec.keyInfo; encodedPrivateKey = _yield$this$createRec.encodedPrivateKey; privateKey = _yield$this$createRec.privateKey; if (!secureSecretStorage) { _context6.next = 13; break; } _context6.next = 12; return this.storeSecret("m.megolm_backup.v1", (0, olmlib.encodeBase64)(privateKey)); case 12: _logger.logger.info("Key backup private key stored in secret storage"); case 13: // Reshape objects into form expected for key backup authData = { public_key: keyInfo.pubkey }; if (keyInfo.passphrase) { authData.private_key_salt = keyInfo.passphrase.salt; authData.private_key_iterations = keyInfo.passphrase.iterations; } return _context6.abrupt("return", { algorithm: olmlib.MEGOLM_BACKUP_ALGORITHM, auth_data: authData, recovery_key: encodedPrivateKey }); case 16: case "end": return _context6.stop(); } } }, _callee6, this); })); return function (_x10) { return _ref6.apply(this, arguments); }; }(); /** * Check whether the key backup private key is stored in secret storage. * @return {Promise} map of key name to key info the secret is * encrypted with, or null if it is not present or not encrypted with a * trusted key */ MatrixClient.prototype.isKeyBackupKeyStored = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: return _context7.abrupt("return", this.isSecretStored("m.megolm_backup.v1", false /* checkKey */ )); case 1: case "end": return _context7.stop(); } } }, _callee7, this); })); /** * Create a new key backup version and enable it, using the information return * from prepareKeyBackupVersion. * * @param {object} info Info object from prepareKeyBackupVersion * @returns {Promise} Object with 'version' param indicating the version created */ MatrixClient.prototype.createKeyBackupVersion = /*#__PURE__*/function () { var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(info) { var data, res; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!(this._crypto === null)) { _context8.next = 2; break; } throw new Error("End-to-end encryption disabled"); case 2: data = { algorithm: info.algorithm, auth_data: info.auth_data }; // Sign the backup auth data with the device key for backwards compat with // older devices with cross-signing. This can probably go away very soon in // favour of just signing with the cross-singing master key. _context8.next = 5; return this._crypto._signObject(data.auth_data); case 5: if (!(this._cryptoCallbacks.getCrossSigningKey && this._crypto._crossSigningInfo.getId())) { _context8.next = 8; break; } _context8.next = 8; return this._crypto._crossSigningInfo.signObject(data.auth_data, "master"); case 8: _context8.next = 10; return this._http.authedRequest(undefined, "POST", "/room_keys/version", undefined, data, { prefix: _httpApi.PREFIX_UNSTABLE }); case 10: res = _context8.sent; _context8.next = 13; return this.checkKeyBackup(); case 13: if (!this.getKeyBackupEnabled()) { _logger.logger.error("Key backup not usable even though we just created it"); } return _context8.abrupt("return", res); case 15: case "end": return _context8.stop(); } } }, _callee8, this); })); return function (_x11) { return _ref9.apply(this, arguments); }; }(); MatrixClient.prototype.deleteKeyBackupVersion = function (version) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } // If we're currently backing up to this backup... stop. // (We start using it automatically in createKeyBackupVersion // so this is symmetrical). if (this._crypto.backupInfo && this._crypto.backupInfo.version === version) { this.disableKeyBackup(); } var path = utils.encodeUri("/room_keys/version/$version", { $version: version }); return this._http.authedRequest(undefined, "DELETE", path, undefined, undefined, { prefix: _httpApi.PREFIX_UNSTABLE }); }; MatrixClient.prototype._makeKeyBackupPath = function (roomId, sessionId, version) { var path; if (sessionId !== undefined) { path = utils.encodeUri("/room_keys/keys/$roomId/$sessionId", { $roomId: roomId, $sessionId: sessionId }); } else if (roomId !== undefined) { path = utils.encodeUri("/room_keys/keys/$roomId", { $roomId: roomId }); } else { path = "/room_keys/keys"; } var queryData = version === undefined ? undefined : { version: version }; return { path: path, queryData: queryData }; }; /** * Back up session keys to the homeserver. * @param {string} roomId ID of the room that the keys are for Optional. * @param {string} sessionId ID of the session that the keys are for Optional. * @param {integer} version backup version Optional. * @param {object} data Object keys to send * @return {Promise} a promise that will resolve when the keys * are uploaded */ MatrixClient.prototype.sendKeyBackup = function (roomId, sessionId, version, data) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } var path = this._makeKeyBackupPath(roomId, sessionId, version); return this._http.authedRequest(undefined, "PUT", path.path, path.queryData, data, { prefix: _httpApi.PREFIX_UNSTABLE }); }; /** * Marks all group sessions as needing to be backed up and schedules them to * upload in the background as soon as possible. */ MatrixClient.prototype.scheduleAllGroupSessionsForBackup = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9() { return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: if (!(this._crypto === null)) { _context9.next = 2; break; } throw new Error("End-to-end encryption disabled"); case 2: _context9.next = 4; return this._crypto.scheduleAllGroupSessionsForBackup(); case 4: case "end": return _context9.stop(); } } }, _callee9, this); })); /** * Marks all group sessions as needing to be backed up without scheduling * them to upload in the background. * @returns {Promise} Resolves to the number of sessions requiring a backup. */ MatrixClient.prototype.flagAllGroupSessionsForBackup = function () { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } return this._crypto.flagAllGroupSessionsForBackup(); }; MatrixClient.prototype.isValidRecoveryKey = function (recoveryKey) { try { (0, _recoverykey.decodeRecoveryKey)(recoveryKey); return true; } catch (e) { return false; } }; /** * Get the raw key for a key backup from the password * Used when migrating key backups into SSSS * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {string} password Passphrase * @param {object} backupInfo Backup metadata from `checkKeyBackup` * @return {Promise} key backup key */ MatrixClient.prototype.keyBackupKeyFromPassword = function (password, backupInfo) { return (0, _key_passphrase.keyFromAuthData)(backupInfo.auth_data, password); }; /** * Get the raw key for a key backup from the recovery key * Used when migrating key backups into SSSS * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {string} recoveryKey The recovery key * @return {Buffer} key backup key */ MatrixClient.prototype.keyBackupKeyFromRecoveryKey = function (recoveryKey) { return (0, _recoverykey.decodeRecoveryKey)(recoveryKey); }; MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY = 'RESTORE_BACKUP_ERROR_BAD_KEY'; /** * Restore from an existing key backup via a passphrase. * * @param {string} password Passphrase * @param {string} [targetRoomId] Room ID to target a specific room. * Restores all rooms if omitted. * @param {string} [targetSessionId] Session ID to target a specific session. * Restores all sessions if omitted. * @param {object} backupInfo Backup metadata from `checkKeyBackup` * @param {object} opts Optional params such as callbacks * @return {Promise} Status of restoration with `total` and `imported` * key counts. */ MatrixClient.prototype.restoreKeyBackupWithPassword = /*#__PURE__*/function () { var _ref11 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(password, targetRoomId, targetSessionId, backupInfo, opts) { var privKey; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return (0, _key_passphrase.keyFromAuthData)(backupInfo.auth_data, password); case 2: privKey = _context10.sent; return _context10.abrupt("return", this._restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts)); case 4: case "end": return _context10.stop(); } } }, _callee10, this); })); return function (_x12, _x13, _x14, _x15, _x16) { return _ref11.apply(this, arguments); }; }(); /** * Restore from an existing key backup via a private key stored in secret * storage. * * @param {object} backupInfo Backup metadata from `checkKeyBackup` * @param {string} [targetRoomId] Room ID to target a specific room. * Restores all rooms if omitted. * @param {string} [targetSessionId] Session ID to target a specific session. * Restores all sessions if omitted. * @param {object} opts Optional params such as callbacks * @return {Promise} Status of restoration with `total` and `imported` * key counts. */ MatrixClient.prototype.restoreKeyBackupWithSecretStorage = /*#__PURE__*/function () { var _ref12 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(backupInfo, targetRoomId, targetSessionId, opts) { var storedKey, fixedKey, _yield$this$_crypto$g, _yield$this$_crypto$g2, keyId, privKey; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _context11.next = 2; return this.getSecret("m.megolm_backup.v1"); case 2: storedKey = _context11.sent; // ensure that the key is in the right format. If not, fix the key and // store the fixed version fixedKey = (0, _crypto.fixBackupKey)(storedKey); if (!fixedKey) { _context11.next = 12; break; } _context11.next = 7; return this._crypto.getSecretStorageKey(); case 7: _yield$this$_crypto$g = _context11.sent; _yield$this$_crypto$g2 = (0, _slicedToArray2["default"])(_yield$this$_crypto$g, 1); keyId = _yield$this$_crypto$g2[0]; _context11.next = 12; return this.storeSecret("m.megolm_backup.v1", fixedKey, [keyId]); case 12: privKey = (0, olmlib.decodeBase64)(fixedKey || storedKey); return _context11.abrupt("return", this._restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts)); case 14: case "end": return _context11.stop(); } } }, _callee11, this); })); return function (_x17, _x18, _x19, _x20) { return _ref12.apply(this, arguments); }; }(); /** * Restore from an existing key backup via an encoded recovery key. * * @param {string} recoveryKey Encoded recovery key * @param {string} [targetRoomId] Room ID to target a specific room. * Restores all rooms if omitted. * @param {string} [targetSessionId] Session ID to target a specific session. * Restores all sessions if omitted. * @param {object} backupInfo Backup metadata from `checkKeyBackup` * @param {object} opts Optional params such as callbacks * @return {Promise} Status of restoration with `total` and `imported` * key counts. */ MatrixClient.prototype.restoreKeyBackupWithRecoveryKey = function (recoveryKey, targetRoomId, targetSessionId, backupInfo, opts) { var privKey = (0, _recoverykey.decodeRecoveryKey)(recoveryKey); return this._restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts); }; /** * Restore from an existing key backup using a cached key, or fail * * @param {string} [targetRoomId] Room ID to target a specific room. * Restores all rooms if omitted. * @param {string} [targetSessionId] Session ID to target a specific session. * Restores all sessions if omitted. * @param {object} backupInfo Backup metadata from `checkKeyBackup` * @param {object} opts Optional params such as callbacks * @return {Promise} Status of restoration with `total` and `imported` * key counts. */ MatrixClient.prototype.restoreKeyBackupWithCache = /*#__PURE__*/function () { var _ref13 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(targetRoomId, targetSessionId, backupInfo, opts) { var privKey; return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return this._crypto.getSessionBackupPrivateKey(); case 2: privKey = _context12.sent; if (privKey) { _context12.next = 5; break; } throw new Error("Couldn't get key"); case 5: return _context12.abrupt("return", this._restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts)); case 6: case "end": return _context12.stop(); } } }, _callee12, this); })); return function (_x21, _x22, _x23, _x24) { return _ref13.apply(this, arguments); }; }(); MatrixClient.prototype._restoreKeyBackup = function (privKey, targetRoomId, targetSessionId, backupInfo) { var _this3 = this; var _ref14 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}, cacheCompleteCallback = _ref14.cacheCompleteCallback, progressCallback = _ref14.progressCallback; if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } var totalKeyCount = 0; var keys = []; var path = this._makeKeyBackupPath(targetRoomId, targetSessionId, backupInfo.version); var decryption = new global.Olm.PkDecryption(); var backupPubKey; try { backupPubKey = decryption.init_with_private_key(privKey); } catch (e) { decryption.free(); throw e; } // If the pubkey computed from the private data we've been given // doesn't match the one in the auth_data, the user has enetered // a different recovery key / the wrong passphrase. if (backupPubKey !== backupInfo.auth_data.public_key) { return Promise.reject({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY }); } // Cache the key, if possible. // This is async. this._crypto.storeSessionBackupPrivateKey(privKey)["catch"](function (e) { console.warn("Error caching session backup key:", e); }).then(cacheCompleteCallback); if (progressCallback) { progressCallback({ stage: "fetch" }); } return this._http.authedRequest(undefined, "GET", path.path, path.queryData, undefined, { prefix: _httpApi.PREFIX_UNSTABLE }).then(function (res) { if (res.rooms) { for (var _i2 = 0, _Object$entries2 = Object.entries(res.rooms); _i2 < _Object$entries2.length; _i2++) { var _Object$entries2$_i = (0, _slicedToArray2["default"])(_Object$entries2[_i2], 2), roomId = _Object$entries2$_i[0], roomData = _Object$entries2$_i[1]; if (!roomData.sessions) continue; totalKeyCount += Object.keys(roomData.sessions).length; var roomKeys = keysFromRecoverySession(roomData.sessions, decryption, roomId); var _iterator2 = _createForOfIteratorHelper(roomKeys), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var k = _step2.value; k.room_id = roomId; keys.push(k); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } } else if (res.sessions) { totalKeyCount = Object.keys(res.sessions).length; keys = keysFromRecoverySession(res.sessions, decryption, targetRoomId, keys); } else { totalKeyCount = 1; try { var key = keyFromRecoverySession(res, decryption); key.room_id = targetRoomId; key.session_id = targetSessionId; keys.push(key); } catch (e) { _logger.logger.log("Failed to decrypt megolm session from backup", e); } } return _this3.importRoomKeys(keys, { progressCallback: progressCallback, untrusted: true, source: "backup" }); }).then(function () { return _this3._crypto.setTrustedBackupPubKey(backupPubKey); }).then(function () { return { total: totalKeyCount, imported: keys.length }; })["finally"](function () { decryption.free(); }); }; MatrixClient.prototype.deleteKeysFromBackup = function (roomId, sessionId, version) { if (this._crypto === null) { throw new Error("End-to-end encryption disabled"); } var path = this._makeKeyBackupPath(roomId, sessionId, version); return this._http.authedRequest(undefined, "DELETE", path.path, path.queryData, undefined, { prefix: _httpApi.PREFIX_UNSTABLE }); }; // Group ops // ========= // Operations on groups that come down the sync stream (ie. ones the // user is a member of or invited to) /** * Get the group for the given group ID. * This function will return a valid group for any group for which a Group event * has been emitted. * @param {string} groupId The group ID * @return {Group} The Group or null if the group is not known or there is no data store. */ MatrixClient.prototype.getGroup = function (groupId) { return this.store.getGroup(groupId); }; /** * Retrieve all known groups. * @return {Group[]} A list of groups, or an empty list if there is no data store. */ MatrixClient.prototype.getGroups = function () { return this.store.getGroups(); }; /** * Get the config for the media repository. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves with an object containing the config. */ MatrixClient.prototype.getMediaConfig = function (callback) { return this._http.authedRequest(callback, "GET", "/config", undefined, undefined, { prefix: _httpApi.PREFIX_MEDIA_R0 }); }; // Room ops // ======== /** * Get the room for the given room ID. * This function will return a valid room for any room for which a Room event * has been emitted. Note in particular that other events, eg. RoomState.members * will be emitted for a room before this function will return the given room. * @param {string} roomId The room ID * @return {Room} The Room or null if it doesn't exist or there is no data store. */ MatrixClient.prototype.getRoom = function (roomId) { return this.store.getRoom(roomId); }; /** * Retrieve all known rooms. * @return {Room[]} A list of rooms, or an empty list if there is no data store. */ MatrixClient.prototype.getRooms = function () { return this.store.getRooms(); }; /** * Retrieve all rooms that should be displayed to the user * This is essentially getRooms() with some rooms filtered out, eg. old versions * of rooms that have been replaced or (in future) other rooms that have been * marked at the protocol level as not to be displayed to the user. * @return {Room[]} A list of rooms, or an empty list if there is no data store. */ MatrixClient.prototype.getVisibleRooms = function () { var allRooms = this.store.getRooms(); var replacedRooms = new Set(); var _iterator3 = _createForOfIteratorHelper(allRooms), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var r = _step3.value; var createEvent = r.currentState.getStateEvents('m.room.create', ''); // invites are included in this list and we don't know their create events yet if (createEvent) { var predecessor = createEvent.getContent()['predecessor']; if (predecessor && predecessor['room_id']) { replacedRooms.add(predecessor['room_id']); } } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return allRooms.filter(function (r) { var tombstone = r.currentState.getStateEvents('m.room.tombstone', ''); if (tombstone && replacedRooms.has(r.roomId)) { return false; } return true; }); }; /** * Retrieve a user. * @param {string} userId The user ID to retrieve. * @return {?User} A user or null if there is no data store or the user does * not exist. */ MatrixClient.prototype.getUser = function (userId) { return this.store.getUser(userId); }; /** * Retrieve all known users. * @return {User[]} A list of users, or an empty list if there is no data store. */ MatrixClient.prototype.getUsers = function () { return this.store.getUsers(); }; // User Account Data operations // ============================ /** * Set account data event for the current user. * It will retry the request up to 5 times. * @param {string} eventType The event type * @param {Object} contents the contents object for the event * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setAccountData = function (eventType, contents, callback) { var _this4 = this; var path = utils.encodeUri("/user/$userId/account_data/$type", { $userId: this.credentials.userId, $type: eventType }); var promise = (0, _httpApi.retryNetworkOperation)(5, function () { return _this4._http.authedRequest(undefined, "PUT", path, undefined, contents); }); if (callback) { promise.then(function (result) { return callback(null, result); }, callback); } return promise; }; /** * Get account data event of given type for the current user. * @param {string} eventType The event type * @return {?object} The contents of the given account data event */ MatrixClient.prototype.getAccountData = function (eventType) { return this.store.getAccountData(eventType); }; /** * Get account data event of given type for the current user. This variant * gets account data directly from the homeserver if the local store is not * ready, which can be useful very early in startup before the initial sync. * @param {string} eventType The event type * @return {Promise} Resolves: The contents of the given account * data event. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getAccountDataFromServer = /*#__PURE__*/function () { var _ref15 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(eventType) { var event, path, result; return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: if (!this.isInitialSyncComplete()) { _context13.next = 5; break; } event = this.store.getAccountData(eventType); if (event) { _context13.next = 4; break; } return _context13.abrupt("return", null); case 4: return _context13.abrupt("return", event.getContent()); case 5: path = utils.encodeUri("/user/$userId/account_data/$type", { $userId: this.credentials.userId, $type: eventType }); _context13.prev = 6; _context13.next = 9; return this._http.authedRequest(undefined, "GET", path, undefined); case 9: result = _context13.sent; return _context13.abrupt("return", result); case 13: _context13.prev = 13; _context13.t0 = _context13["catch"](6); if (!(_context13.t0.data && _context13.t0.data.errcode === 'M_NOT_FOUND')) { _context13.next = 17; break; } return _context13.abrupt("return", null); case 17: throw _context13.t0; case 18: case "end": return _context13.stop(); } } }, _callee13, this, [[6, 13]]); })); return function (_x25) { return _ref15.apply(this, arguments); }; }(); /** * Gets the users that are ignored by this client * @returns {string[]} The array of users that are ignored (empty if none) */ MatrixClient.prototype.getIgnoredUsers = function () { var event = this.getAccountData("m.ignored_user_list"); if (!event || !event.getContent() || !event.getContent()["ignored_users"]) return []; return Object.keys(event.getContent()["ignored_users"]); }; /** * Sets the users that the current user should ignore. * @param {string[]} userIds the user IDs to ignore * @param {module:client.callback} [callback] Optional. * @return {Promise} Resolves: Account data event * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setIgnoredUsers = function (userIds, callback) { var content = { ignored_users: {} }; userIds.map(function (u) { return content.ignored_users[u] = {}; }); return this.setAccountData("m.ignored_user_list", content, callback); }; /** * Gets whether or not a specific user is being ignored by this client. * @param {string} userId the user ID to check * @returns {boolean} true if the user is ignored, false otherwise */ MatrixClient.prototype.isUserIgnored = function (userId) { return this.getIgnoredUsers().indexOf(userId) !== -1; }; // Room operations // =============== /** * Join a room. If you have already joined the room, this will no-op. * @param {string} roomIdOrAlias The room ID or room alias to join. * @param {Object} opts Options when joining the room. * @param {boolean} opts.syncRoom True to do a room initial sync on the resulting * room. If false, the returned Room object will have no current state. * Default: true. * @param {boolean} opts.inviteSignUrl If the caller has a keypair 3pid invite, * the signing URL is passed in this parameter. * @param {string[]} opts.viaServers The server names to try and join through in * addition to those that are automatically chosen. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Room object. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.joinRoom = function (roomIdOrAlias, opts, callback) { // to help people when upgrading.. if (utils.isFunction(opts)) { throw new Error("Expected 'opts' object, got function."); } opts = opts || {}; if (opts.syncRoom === undefined) { opts.syncRoom = true; } var room = this.getRoom(roomIdOrAlias); if (room && room.hasMembershipState(this.credentials.userId, "join")) { return Promise.resolve(room); } var sign_promise = Promise.resolve(); if (opts.inviteSignUrl) { sign_promise = this._http.requestOtherUrl(undefined, 'POST', opts.inviteSignUrl, { mxid: this.credentials.userId }); } var queryString = {}; if (opts.viaServers) { queryString["server_name"] = opts.viaServers; } var reqOpts = { qsStringifyOptions: { arrayFormat: 'repeat' } }; var self = this; var prom = new Promise(function (resolve, reject) { sign_promise.then(function (signed_invite_object) { var data = {}; if (signed_invite_object) { data.third_party_signed = signed_invite_object; } var path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias }); return self._http.authedRequest(undefined, "POST", path, queryString, data, reqOpts); }).then(function (res) { var roomId = res.room_id; var syncApi = new _sync.SyncApi(self, self._clientOpts); var room = syncApi.createRoom(roomId); if (opts.syncRoom) {// v2 will do this for us // return syncApi.syncRoom(room); } return Promise.resolve(room); }).then(function (room) { _resolve(callback, resolve, room); }, function (err) { _reject(callback, reject, err); }); }); return prom; }; /** * Resend an event. * @param {MatrixEvent} event The event to resend. * @param {Room} room Optional. The room the event is in. Will update the * timeline entry if provided. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.resendEvent = function (event, room) { _updatePendingEventStatus(room, event, _event2.EventStatus.SENDING); return _sendEvent(this, room, event); }; /** * Cancel a queued or unsent event. * * @param {MatrixEvent} event Event to cancel * @throws Error if the event is not in QUEUED or NOT_SENT state */ MatrixClient.prototype.cancelPendingEvent = function (event) { if ([_event2.EventStatus.QUEUED, _event2.EventStatus.NOT_SENT].indexOf(event.status) < 0) { throw new Error("cannot cancel an event with status " + event.status); } // first tell the scheduler to forget about it, if it's queued if (this.scheduler) { this.scheduler.removeEventFromQueue(event); } // then tell the room about the change of state, which will remove it // from the room's list of pending events. var room = this.getRoom(event.getRoomId()); _updatePendingEventStatus(room, event, _event2.EventStatus.CANCELLED); }; /** * @param {string} roomId * @param {string} name * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setRoomName = function (roomId, name, callback) { return this.sendStateEvent(roomId, "m.room.name", { name: name }, undefined, callback); }; /** * @param {string} roomId * @param {string} topic * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setRoomTopic = function (roomId, topic, callback) { return this.sendStateEvent(roomId, "m.room.topic", { topic: topic }, undefined, callback); }; /** * @param {string} roomId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getRoomTags = function (roomId, callback) { var path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/", { $userId: this.credentials.userId, $roomId: roomId }); return this._http.authedRequest(callback, "GET", path, undefined); }; /** * @param {string} roomId * @param {string} tagName name of room tag to be set * @param {object} metadata associated with that tag to be stored * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setRoomTag = function (roomId, tagName, metadata, callback) { var path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { $userId: this.credentials.userId, $roomId: roomId, $tag: tagName }); return this._http.authedRequest(callback, "PUT", path, undefined, metadata); }; /** * @param {string} roomId * @param {string} tagName name of room tag to be removed * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.deleteRoomTag = function (roomId, tagName, callback) { var path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { $userId: this.credentials.userId, $roomId: roomId, $tag: tagName }); return this._http.authedRequest(callback, "DELETE", path, undefined, undefined); }; /** * @param {string} roomId * @param {string} eventType event type to be set * @param {object} content event content * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setRoomAccountData = function (roomId, eventType, content, callback) { var path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", { $userId: this.credentials.userId, $roomId: roomId, $type: eventType }); return this._http.authedRequest(callback, "PUT", path, undefined, content); }; /** * Set a user's power level. * @param {string} roomId * @param {string} userId * @param {Number} powerLevel * @param {MatrixEvent} event * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setPowerLevel = function (roomId, userId, powerLevel, event, callback) { var content = { users: {} }; if (event && event.getType() === "m.room.power_levels") { // take a copy of the content to ensure we don't corrupt // existing client state with a failed power level change content = utils.deepCopy(event.getContent()); } content.users[userId] = powerLevel; var path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", { $roomId: roomId }); return this._http.authedRequest(callback, "PUT", path, undefined, content); }; /** * @param {string} roomId * @param {string} eventType * @param {Object} content * @param {string} txnId Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendEvent = function (roomId, eventType, content, txnId, callback) { return this._sendCompleteEvent(roomId, { type: eventType, content: content }, txnId, callback); }; /** * @param {string} roomId * @param {object} eventObject An object with the partial structure of an event, to which event_id, user_id, room_id and origin_server_ts will be added. * @param {string} txnId the txnId. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype._sendCompleteEvent = function (roomId, eventObject, txnId, callback) { if (utils.isFunction(txnId)) { callback = txnId; txnId = undefined; } if (!txnId) { txnId = this.makeTxnId(); } // we always construct a MatrixEvent when sending because the store and // scheduler use them. We'll extract the params back out if it turns out // the client has no scheduler or store. var localEvent = new _event2.MatrixEvent(Object.assign(eventObject, { event_id: "~" + roomId + ":" + txnId, user_id: this.credentials.userId, sender: this.credentials.userId, room_id: roomId, origin_server_ts: new Date().getTime() })); var room = this.getRoom(roomId); // if this is a relation or redaction of an event // that hasn't been sent yet (e.g. with a local id starting with a ~) // then listen for the remote echo of that event so that by the time // this event does get sent, we have the correct event_id var targetId = localEvent.getAssociatedId(); if (targetId && targetId.startsWith("~")) { var target = room.getPendingEvents().find(function (e) { return e.getId() === targetId; }); target.once("Event.localEventIdReplaced", function () { localEvent.updateAssociatedId(target.getId()); }); } var type = localEvent.getType(); _logger.logger.log("sendEvent of type ".concat(type, " in ").concat(roomId, " with txnId ").concat(txnId)); localEvent.setTxnId(txnId); localEvent.setStatus(_event2.EventStatus.SENDING); // add this event immediately to the local store as 'sending'. if (room) { room.addPendingEvent(localEvent, txnId); } // addPendingEvent can change the state to NOT_SENT if it believes // that there's other events that have failed. We won't bother to // try sending the event if the state has changed as such. if (localEvent.status === _event2.EventStatus.NOT_SENT) { return Promise.reject(new Error("Event blocked by other events not yet sent")); } return _sendEvent(this, room, localEvent, callback); }; // encrypts the event if necessary // adds the event to the queue, or sends it // marks the event as sent/unsent // returns a promise which resolves with the result of the send request function _sendEvent(client, room, event, callback) { // Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections, // so that we can handle synchronous and asynchronous exceptions with the // same code path. return Promise.resolve().then(function () { var encryptionPromise = _encryptEventIfNeeded(client, event, room); if (!encryptionPromise) { return null; } _updatePendingEventStatus(room, event, _event2.EventStatus.ENCRYPTING); return encryptionPromise.then(function () { _updatePendingEventStatus(room, event, _event2.EventStatus.SENDING); }); }).then(function () { var promise; // this event may be queued if (client.scheduler) { // if this returns a promise then the scheduler has control now and will // resolve/reject when it is done. Internally, the scheduler will invoke // processFn which is set to this._sendEventHttpRequest so the same code // path is executed regardless. promise = client.scheduler.queueEvent(event); if (promise && client.scheduler.getQueueForEvent(event).length > 1) { // event is processed FIFO so if the length is 2 or more we know // this event is stuck behind an earlier event. _updatePendingEventStatus(room, event, _event2.EventStatus.QUEUED); } } if (!promise) { promise = _sendEventHttpRequest(client, event); if (room) { promise = promise.then(function (res) { room.updatePendingEvent(event, _event2.EventStatus.SENT, res.event_id); return res; }); } } return promise; }).then(function (res) { // the request was sent OK if (callback) { callback(null, res); } return res; }, function (err) { // the request failed to send. _logger.logger.error("Error sending event", err.stack || err); try { // set the error on the event before we update the status: // updating the status emits the event, so the state should be // consistent at that point. event.error = err; _updatePendingEventStatus(room, event, _event2.EventStatus.NOT_SENT); // also put the event object on the error: the caller will need this // to resend or cancel the event err.event = event; if (callback) { callback(err); } } catch (err2) { _logger.logger.error("Exception in error handler!", err2.stack || err); } throw err; }); } /** * Encrypt an event according to the configuration of the room, if necessary. * * @param {MatrixClient} client * * @param {module:models/event.MatrixEvent} event event to be sent * * @param {module:models/room?} room destination room. Null if the destination * is not a room we have seen over the sync pipe. * * @return {Promise?} Promise which resolves when the event has been * encrypted, or null if nothing was needed */ function _encryptEventIfNeeded(client, event, room) { if (event.isEncrypted()) { // this event has already been encrypted; this happens if the // encryption step succeeded, but the send step failed on the first // attempt. return null; } if (!client.isRoomEncrypted(event.getRoomId())) { // looks like this room isn't encrypted. return null; } if (!client._crypto && client.usingExternalCrypto) { // The client has opted to allow sending messages to encrypted // rooms even if the room is encrypted, and we haven't setup // crypto. This is useful for users of matrix-org/pantalaimon return null; } if (event.getType() === "m.reaction") { // For reactions, there is a very little gained by encrypting the entire // event, as relation data is already kept in the clear. Event // encryption for a reaction effectively only obscures the event type, // but the purpose is still obvious from the relation data, so nothing // is really gained. It also causes quite a few problems, such as: // * triggers notifications via default push rules // * prevents server-side bundling for reactions // The reaction key / content / emoji value does warrant encrypting, but // this will be handled separately by encrypting just this value. // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642 return null; } if (!client._crypto) { throw new Error("This room is configured to use encryption, but your client does " + "not support encryption."); } return client._crypto.encryptEvent(event, room); } /** * Returns the eventType that should be used taking encryption into account * for a given eventType. * @param {MatrixClient} client the client * @param {string} roomId the room for the events `eventType` relates to * @param {string} eventType the event type * @return {string} the event type taking encryption into account */ function _getEncryptedIfNeededEventType(client, roomId, eventType) { if (eventType === "m.reaction") { return eventType; } var isEncrypted = client.isRoomEncrypted(roomId); return isEncrypted ? "m.room.encrypted" : eventType; } function _updatePendingEventStatus(room, event, newStatus) { if (room) { room.updatePendingEvent(event, newStatus); } else { event.setStatus(newStatus); } } function _sendEventHttpRequest(client, event) { var txnId = event.getTxnId(); if (!txnId) { txnId = client.makeTxnId(); event.setTxnId(txnId); } var pathParams = { $roomId: event.getRoomId(), $eventType: event.getWireType(), $stateKey: event.getStateKey(), $txnId: txnId }; var path; if (event.isState()) { var pathTemplate = "/rooms/$roomId/state/$eventType"; if (event.getStateKey() && event.getStateKey().length > 0) { pathTemplate = "/rooms/$roomId/state/$eventType/$stateKey"; } path = utils.encodeUri(pathTemplate, pathParams); } else if (event.isRedaction()) { var _pathTemplate = "/rooms/$roomId/redact/$redactsEventId/$txnId"; path = utils.encodeUri(_pathTemplate, Object.assign({ $redactsEventId: event.event.redacts }, pathParams)); } else { path = utils.encodeUri("/rooms/$roomId/send/$eventType/$txnId", pathParams); } return client._http.authedRequest(undefined, "PUT", path, undefined, event.getWireContent()).then(function (res) { _logger.logger.log("Event sent to ".concat(event.getRoomId(), " with event id ").concat(res.event_id)); return res; }); } /** * @param {string} roomId * @param {string} eventId * @param {string} [txnId] transaction id. One will be made up if not * supplied. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.redactEvent = function (roomId, eventId, txnId, callback) { return this._sendCompleteEvent(roomId, { type: "m.room.redaction", content: {}, redacts: eventId }, txnId, callback); }; /** * @param {string} roomId * @param {Object} content * @param {string} txnId Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendMessage = function (roomId, content, txnId, callback) { if (utils.isFunction(txnId)) { callback = txnId; txnId = undefined; } return this.sendEvent(roomId, "m.room.message", content, txnId, callback); }; /** * @param {string} roomId * @param {string} body * @param {string} txnId Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendTextMessage = function (roomId, body, txnId, callback) { var content = ContentHelpers.makeTextMessage(body); return this.sendMessage(roomId, content, txnId, callback); }; /** * @param {string} roomId * @param {string} body * @param {string} txnId Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendNotice = function (roomId, body, txnId, callback) { var content = ContentHelpers.makeNotice(body); return this.sendMessage(roomId, content, txnId, callback); }; /** * @param {string} roomId * @param {string} body * @param {string} txnId Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendEmoteMessage = function (roomId, body, txnId, callback) { var content = ContentHelpers.makeEmoteMessage(body); return this.sendMessage(roomId, content, txnId, callback); }; /** * @param {string} roomId * @param {string} url * @param {Object} info * @param {string} text * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendImageMessage = function (roomId, url, info, text, callback) { if (utils.isFunction(text)) { callback = text; text = undefined; } if (!text) { text = "Image"; } var content = { msgtype: "m.image", url: url, info: info, body: text }; return this.sendMessage(roomId, content, callback); }; /** * @param {string} roomId * @param {string} url * @param {Object} info * @param {string} text * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendStickerMessage = function (roomId, url, info, text, callback) { if (utils.isFunction(text)) { callback = text; text = undefined; } if (!text) { text = "Sticker"; } var content = { url: url, info: info, body: text }; return this.sendEvent(roomId, "m.sticker", content, callback, undefined); }; /** * @param {string} roomId * @param {string} body * @param {string} htmlBody * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendHtmlMessage = function (roomId, body, htmlBody, callback) { var content = ContentHelpers.makeHtmlMessage(body, htmlBody); return this.sendMessage(roomId, content, callback); }; /** * @param {string} roomId * @param {string} body * @param {string} htmlBody * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendHtmlNotice = function (roomId, body, htmlBody, callback) { var content = ContentHelpers.makeHtmlNotice(body, htmlBody); return this.sendMessage(roomId, content, callback); }; /** * @param {string} roomId * @param {string} body * @param {string} htmlBody * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendHtmlEmote = function (roomId, body, htmlBody, callback) { var content = ContentHelpers.makeHtmlEmote(body, htmlBody); return this.sendMessage(roomId, content, callback); }; /** * Send a receipt. * @param {Event} event The event being acknowledged * @param {string} receiptType The kind of receipt e.g. "m.read" * @param {object} opts Additional content to send alongside the receipt. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendReceipt = function (event, receiptType, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } if (this.isGuest()) { return Promise.resolve({}); // guests cannot send receipts so don't bother. } var path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", { $roomId: event.getRoomId(), $receiptType: receiptType, $eventId: event.getId() }); var promise = this._http.authedRequest(callback, "POST", path, undefined, opts || {}); var room = this.getRoom(event.getRoomId()); if (room) { room._addLocalEchoReceipt(this.credentials.userId, event, receiptType); } return promise; }; /** * Send a read receipt. * @param {Event} event The event that has been read. * @param {object} opts The options for the read receipt. * @param {boolean} opts.hidden True to prevent the receipt from being sent to * other users and homeservers. Default false (send to everyone). This * property is unstable and may change in the future. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendReadReceipt = /*#__PURE__*/function () { var _ref16 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(event, opts, callback) { var eventId, room, addlContent; return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: if (typeof opts === 'function') { callback = opts; opts = {}; } if (!opts) opts = {}; eventId = event.getId(); room = this.getRoom(event.getRoomId()); if (!(room && room.hasPendingEvent(eventId))) { _context14.next = 6; break; } throw new Error("Cannot set read receipt to a pending event (".concat(eventId, ")")); case 6: addlContent = { "m.hidden": Boolean(opts.hidden) }; return _context14.abrupt("return", this.sendReceipt(event, "m.read", addlContent, callback)); case 8: case "end": return _context14.stop(); } } }, _callee14, this); })); return function (_x26, _x27, _x28) { return _ref16.apply(this, arguments); }; }(); /** * Set a marker to indicate the point in a room before which the user has read every * event. This can be retrieved from room account data (the event type is `m.fully_read`) * and displayed as a horizontal line in the timeline that is visually distinct to the * position of the user's own read receipt. * @param {string} roomId ID of the room that has been read * @param {string} rmEventId ID of the event that has been read * @param {string} rrEvent the event tracked by the read receipt. This is here for * convenience because the RR and the RM are commonly updated at the same time as each * other. The local echo of this receipt will be done if set. Optional. * @param {object} opts Options for the read markers * @param {object} opts.hidden True to hide the receipt from other users and homeservers. * This property is unstable and may change in the future. * @return {Promise} Resolves: the empty object, {}. */ MatrixClient.prototype.setRoomReadMarkers = /*#__PURE__*/function () { var _ref17 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(roomId, rmEventId, rrEvent, opts) { var room, rrEventId; return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: room = this.getRoom(roomId); if (!(room && room.hasPendingEvent(rmEventId))) { _context15.next = 3; break; } throw new Error("Cannot set read marker to a pending event (".concat(rmEventId, ")")); case 3: if (!rrEvent) { _context15.next = 8; break; } rrEventId = rrEvent.getId(); if (!(room && room.hasPendingEvent(rrEventId))) { _context15.next = 7; break; } throw new Error("Cannot set read receipt to a pending event (".concat(rrEventId, ")")); case 7: if (room) { room._addLocalEchoReceipt(this.credentials.userId, rrEvent, "m.read"); } case 8: return _context15.abrupt("return", this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, opts)); case 9: case "end": return _context15.stop(); } } }, _callee15, this); })); return function (_x29, _x30, _x31, _x32) { return _ref17.apply(this, arguments); }; }(); /** * Get a preview of the given URL as of (roughly) the given point in time, * described as an object with OpenGraph keys and associated values. * Attributes may be synthesized where actual OG metadata is lacking. * Caches results to prevent hammering the server. * @param {string} url The URL to get preview data for * @param {Number} ts The preferred point in time that the preview should * describe (ms since epoch). The preview returned will either be the most * recent one preceding this timestamp if available, or failing that the next * most recent available preview. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Object of OG metadata. * @return {module:http-api.MatrixError} Rejects: with an error response. * May return synthesized attributes if the URL lacked OG meta. */ MatrixClient.prototype.getUrlPreview = function (url, ts, callback) { // bucket the timestamp to the nearest minute to prevent excessive spam to the server // Surely 60-second accuracy is enough for anyone. ts = Math.floor(ts / 60000) * 60000; var key = ts + "_" + url; // If there's already a request in flight (or we've handled it), return that instead. var cachedPreview = this.urlPreviewCache[key]; if (cachedPreview) { if (callback) { cachedPreview.then(callback)["catch"](callback); } return cachedPreview; } var resp = this._http.authedRequest(callback, "GET", "/preview_url", { url: url, ts: ts }, undefined, { prefix: _httpApi.PREFIX_MEDIA_R0 }); // TODO: Expire the URL preview cache sometimes this.urlPreviewCache[key] = resp; return resp; }; /** * @param {string} roomId * @param {boolean} isTyping * @param {Number} timeoutMs * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.sendTyping = function (roomId, isTyping, timeoutMs, callback) { if (this.isGuest()) { return Promise.resolve({}); // guests cannot send typing notifications so don't bother. } var path = utils.encodeUri("/rooms/$roomId/typing/$userId", { $roomId: roomId, $userId: this.credentials.userId }); var data = { typing: isTyping }; if (isTyping) { data.timeout = timeoutMs ? timeoutMs : 20000; } return this._http.authedRequest(callback, "PUT", path, undefined, data); }; /** * Determines the history of room upgrades for a given room, as far as the * client can see. Returns an array of Rooms where the first entry is the * oldest and the last entry is the newest (likely current) room. If the * provided room is not found, this returns an empty list. This works in * both directions, looking for older and newer rooms of the given room. * @param {string} roomId The room ID to search from * @param {boolean} verifyLinks If true, the function will only return rooms * which can be proven to be linked. For example, rooms which have a create * event pointing to an old room which the client is not aware of or doesn't * have a matching tombstone would not be returned. * @return {Room[]} An array of rooms representing the upgrade * history. */ MatrixClient.prototype.getRoomUpgradeHistory = function (roomId) { var verifyLinks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var currentRoom = this.getRoom(roomId); if (!currentRoom) return []; var upgradeHistory = [currentRoom]; // Work backwards first, looking at create events. var createEvent = currentRoom.currentState.getStateEvents("m.room.create", ""); while (createEvent) { _logger.logger.log("Looking at ".concat(createEvent.getId())); var predecessor = createEvent.getContent()['predecessor']; if (predecessor && predecessor['room_id']) { _logger.logger.log("Looking at predecessor ".concat(predecessor['room_id'])); var refRoom = this.getRoom(predecessor['room_id']); if (!refRoom) break; // end of the chain if (verifyLinks) { var tombstone = refRoom.currentState.getStateEvents("m.room.tombstone", ""); if (!tombstone || tombstone.getContent()['replacement_room'] !== refRoom.roomId) { break; } } // Insert at the front because we're working backwards from the currentRoom upgradeHistory.splice(0, 0, refRoom); createEvent = refRoom.currentState.getStateEvents("m.room.create", ""); } else { // No further create events to look at break; } } // Work forwards next, looking at tombstone events var tombstoneEvent = currentRoom.currentState.getStateEvents("m.room.tombstone", ""); while (tombstoneEvent) { var _refRoom = this.getRoom(tombstoneEvent.getContent()['replacement_room']); if (!_refRoom) break; // end of the chain if (_refRoom.roomId === currentRoom.roomId) break; // Tombstone is referencing it's own room if (verifyLinks) { createEvent = _refRoom.currentState.getStateEvents("m.room.create", ""); if (!createEvent || !createEvent.getContent()['predecessor']) break; var _predecessor = createEvent.getContent()['predecessor']; if (_predecessor['room_id'] !== currentRoom.roomId) break; } // Push to the end because we're looking forwards upgradeHistory.push(_refRoom); var roomIds = new Set(upgradeHistory.map(function (ref) { return ref.roomId; })); if (roomIds.size < upgradeHistory.length) { // The last room added to the list introduced a previous roomId // To avoid recursion, return the last rooms - 1 return upgradeHistory.slice(0, upgradeHistory.length - 1); } // Set the current room to the reference room so we know where we're at currentRoom = _refRoom; tombstoneEvent = currentRoom.currentState.getStateEvents("m.room.tombstone", ""); } return upgradeHistory; }; /** * @param {string} roomId * @param {string} userId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.invite = function (roomId, userId, callback) { return _membershipChange(this, roomId, userId, "invite", undefined, callback); }; /** * Invite a user to a room based on their email address. * @param {string} roomId The room to invite the user to. * @param {string} email The email address to invite. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.inviteByEmail = function (roomId, email, callback) { return this.inviteByThreePid(roomId, "email", email, callback); }; /** * Invite a user to a room based on a third-party identifier. * @param {string} roomId The room to invite the user to. * @param {string} medium The medium to invite the user e.g. "email". * @param {string} address The address for the specified medium. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.inviteByThreePid = /*#__PURE__*/function () { var _ref18 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(roomId, medium, address, callback) { var path, identityServerUrl, params, identityAccessToken; return _regenerator["default"].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: path = utils.encodeUri("/rooms/$roomId/invite", { $roomId: roomId }); identityServerUrl = this.getIdentityServerUrl(true); if (identityServerUrl) { _context16.next = 4; break; } return _context16.abrupt("return", Promise.reject(new _httpApi.MatrixError({ error: "No supplied identity server URL", errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM" }))); case 4: params = { id_server: identityServerUrl, medium: medium, address: address }; _context16.t0 = this.identityServer && this.identityServer.getAccessToken; if (!_context16.t0) { _context16.next = 10; break; } _context16.next = 9; return this.doesServerAcceptIdentityAccessToken(); case 9: _context16.t0 = _context16.sent; case 10: if (!_context16.t0) { _context16.next = 15; break; } _context16.next = 13; return this.identityServer.getAccessToken(); case 13: identityAccessToken = _context16.sent; if (identityAccessToken) { params.id_access_token = identityAccessToken; } case 15: return _context16.abrupt("return", this._http.authedRequest(callback, "POST", path, undefined, params)); case 16: case "end": return _context16.stop(); } } }, _callee16, this); })); return function (_x33, _x34, _x35, _x36) { return _ref18.apply(this, arguments); }; }(); /** * @param {string} roomId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.leave = function (roomId, callback) { return _membershipChange(this, roomId, undefined, "leave", undefined, callback); }; /** * Leaves all rooms in the chain of room upgrades based on the given room. By * default, this will leave all the previous and upgraded rooms, including the * given room. To only leave the given room and any previous rooms, keeping the * upgraded (modern) rooms untouched supply `false` to `includeFuture`. * @param {string} roomId The room ID to start leaving at * @param {boolean} includeFuture If true, the whole chain (past and future) of * upgraded rooms will be left. * @return {Promise} Resolves when completed with an object keyed * by room ID and value of the error encountered when leaving or null. */ MatrixClient.prototype.leaveRoomChain = function (roomId) { var _this5 = this; var includeFuture = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var upgradeHistory = this.getRoomUpgradeHistory(roomId); var eligibleToLeave = upgradeHistory; if (!includeFuture) { eligibleToLeave = []; var _iterator4 = _createForOfIteratorHelper(upgradeHistory), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var room = _step4.value; eligibleToLeave.push(room); if (room.roomId === roomId) { break; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } var populationResults = {}; // {roomId: Error} var promises = []; var doLeave = function doLeave(roomId) { return _this5.leave(roomId).then(function () { populationResults[roomId] = null; })["catch"](function (err) { populationResults[roomId] = err; return null; // suppress error }); }; var _iterator5 = _createForOfIteratorHelper(eligibleToLeave), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _room = _step5.value; promises.push(doLeave(_room.roomId)); } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return Promise.all(promises).then(function () { return populationResults; }); }; /** * @param {string} roomId * @param {string} userId * @param {string} reason Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.ban = function (roomId, userId, reason, callback) { return _membershipChange(this, roomId, userId, "ban", reason, callback); }; /** * @param {string} roomId * @param {boolean} deleteRoom True to delete the room from the store on success. * Default: true. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.forget = function (roomId, deleteRoom, callback) { if (deleteRoom === undefined) { deleteRoom = true; } var promise = _membershipChange(this, roomId, undefined, "forget", undefined, callback); if (!deleteRoom) { return promise; } var self = this; return promise.then(function (response) { self.store.removeRoom(roomId); self.emit("deleteRoom", roomId); return response; }); }; /** * @param {string} roomId * @param {string} userId * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Object (currently empty) * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.unban = function (roomId, userId, callback) { // unbanning != set their state to leave: this used to be // the case, but was then changed so that leaving was always // a revoking of priviledge, otherwise two people racing to // kick / ban someone could end up banning and then un-banning // them. var path = utils.encodeUri("/rooms/$roomId/unban", { $roomId: roomId }); var data = { user_id: userId }; return this._http.authedRequest(callback, "POST", path, undefined, data); }; /** * @param {string} roomId * @param {string} userId * @param {string} reason Optional. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.kick = function (roomId, userId, reason, callback) { return _setMembershipState(this, roomId, userId, "leave", reason, callback); }; /** * This is an internal method. * @param {MatrixClient} client * @param {string} roomId * @param {string} userId * @param {string} membershipValue * @param {string} reason * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ function _setMembershipState(client, roomId, userId, membershipValue, reason, callback) { if (utils.isFunction(reason)) { callback = reason; reason = undefined; } var path = utils.encodeUri("/rooms/$roomId/state/m.room.member/$userId", { $roomId: roomId, $userId: userId }); return client._http.authedRequest(callback, "PUT", path, undefined, { membership: membershipValue, reason: reason }); } /** * This is an internal method. * @param {MatrixClient} client * @param {string} roomId * @param {string} userId * @param {string} membership * @param {string} reason * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ function _membershipChange(client, roomId, userId, membership, reason, callback) { if (utils.isFunction(reason)) { callback = reason; reason = undefined; } var path = utils.encodeUri("/rooms/$room_id/$membership", { $room_id: roomId, $membership: membership }); return client._http.authedRequest(callback, "POST", path, undefined, { user_id: userId, // may be undefined e.g. on leave reason: reason }); } /** * Obtain a dict of actions which should be performed for this event according * to the push rules for this user. Caches the dict on the event. * @param {MatrixEvent} event The event to get push actions for. * @return {module:pushprocessor~PushAction} A dict of actions to perform. */ MatrixClient.prototype.getPushActionsForEvent = function (event) { if (!event.getPushActions()) { event.setPushActions(this._pushProcessor.actionsForEvent(event)); } return event.getPushActions(); }; // Profile operations // ================== /** * @param {string} info The kind of info to set (e.g. 'avatar_url') * @param {Object} data The JSON object to set. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setProfileInfo = function (info, data, callback) { var path = utils.encodeUri("/profile/$userId/$info", { $userId: this.credentials.userId, $info: info }); return this._http.authedRequest(callback, "PUT", path, undefined, data); }; /** * @param {string} name * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setDisplayName = function (name, callback) { return this.setProfileInfo("displayname", { displayname: name }, callback); }; /** * @param {string} url * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setAvatarUrl = function (url, callback) { return this.setProfileInfo("avatar_url", { avatar_url: url }, callback); }; /** * Turn an MXC URL into an HTTP one. This method is experimental and * may change. * @param {string} mxcUrl The MXC URL * @param {Number} width The desired width of the thumbnail. * @param {Number} height The desired height of the thumbnail. * @param {string} resizeMethod The thumbnail resize method to use, either * "crop" or "scale". * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs * directly. Fetching such URLs will leak information about the user to * anyone they share a room with. If false, will return null for such URLs. * @return {?string} the avatar URL or null. */ MatrixClient.prototype.mxcUrlToHttp = function (mxcUrl, width, height, resizeMethod, allowDirectLinks) { return (0, _contentRepo.getHttpUriForMxc)(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks); }; /** * Sets a new status message for the user. The message may be null/falsey * to clear the message. * @param {string} newMessage The new message to set. * @return {Promise} Resolves: to nothing * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype._unstable_setStatusMessage = function (newMessage) { var _this6 = this; var type = "im.vector.user_status"; return Promise.all(this.getRooms().map(function (room) { var isJoined = room.getMyMembership() === "join"; var looksLikeDm = room.getInvitedAndJoinedMemberCount() === 2; if (!isJoined || !looksLikeDm) { return Promise.resolve(); } // Check power level separately as it's a bit more expensive. var maySend = room.currentState.mayClientSendStateEvent(type, _this6); if (!maySend) { return Promise.resolve(); } return _this6.sendStateEvent(room.roomId, type, { status: newMessage }, _this6.getUserId()); })); }; /** * @param {Object} opts Options to apply * @param {string} opts.presence One of "online", "offline" or "unavailable" * @param {string} opts.status_msg The status message to attach. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. * @throws If 'presence' isn't a valid presence enum value. */ MatrixClient.prototype.setPresence = function (opts, callback) { var path = utils.encodeUri("/presence/$userId/status", { $userId: this.credentials.userId }); if (typeof opts === "string") { opts = { presence: opts }; } var validStates = ["offline", "online", "unavailable"]; if (validStates.indexOf(opts.presence) == -1) { throw new Error("Bad presence value: " + opts.presence); } return this._http.authedRequest(callback, "PUT", path, undefined, opts); }; /** * Retrieve older messages from the given room and put them in the timeline. * * If this is called multiple times whilst a request is ongoing, the same * Promise will be returned. If there was a problem requesting scrollback, there * will be a small delay before another request can be made (to prevent tight-looping * when there is no connection). * * @param {Room} room The room to get older messages in. * @param {Integer} limit Optional. The maximum number of previous events to * pull in. Default: 30. * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: Room. If you are at the beginning * of the timeline, Room.oldState.paginationToken will be * null. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.scrollback = function (room, limit, callback) { if (utils.isFunction(limit)) { callback = limit; limit = undefined; } limit = limit || 30; var timeToWaitMs = 0; var info = this._ongoingScrollbacks[room.roomId] || {}; if (info.promise) { return info.promise; } else if (info.errorTs) { var timeWaitedMs = Date.now() - info.errorTs; timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0); } if (room.oldState.paginationToken === null) { return Promise.resolve(room); // already at the start. } // attempt to grab more events from the store first var numAdded = this.store.scrollback(room, limit).length; if (numAdded === limit) { // store contained everything we needed. return Promise.resolve(room); } // reduce the required number of events appropriately limit = limit - numAdded; var self = this; var prom = new Promise(function (resolve, reject) { // wait for a time before doing this request // (which may be 0 in order not to special case the code paths) (0, utils.sleep)(timeToWaitMs).then(function () { return self._createMessagesRequest(room.roomId, room.oldState.paginationToken, limit, 'b'); }).then(function (res) { var matrixEvents = utils.map(res.chunk, _PojoToMatrixEventMapper(self)); if (res.state) { var stateEvents = utils.map(res.state, _PojoToMatrixEventMapper(self)); room.currentState.setUnknownStateEvents(stateEvents); } room.addEventsToTimeline(matrixEvents, true, room.getLiveTimeline()); room.oldState.paginationToken = res.end; if (res.chunk.length === 0) { room.oldState.paginationToken = null; } self.store.storeEvents(room, matrixEvents, res.end, true); self._ongoingScrollbacks[room.roomId] = null; _resolve(callback, resolve, room); }, function (err) { self._ongoingScrollbacks[room.roomId] = { errorTs: Date.now() }; _reject(callback, reject, err); }); }); info = { promise: prom, errorTs: null }; this._ongoingScrollbacks[room.roomId] = info; return prom; }; /** * Get an EventTimeline for the given event * *

If the EventTimelineSet object already has the given event in its store, the * corresponding timeline will be returned. Otherwise, a /context request is * made, and used to construct an EventTimeline. * * @param {EventTimelineSet} timelineSet The timelineSet to look for the event in * @param {string} eventId The ID of the event to look for * * @return {Promise} Resolves: * {@link module:models/event-timeline~EventTimeline} including the given * event */ MatrixClient.prototype.getEventTimeline = function (timelineSet, eventId) { // don't allow any timeline support unless it's been enabled. if (!this.timelineSupport) { throw new Error("timeline support is disabled. Set the 'timelineSupport'" + " parameter to true when creating MatrixClient to enable" + " it."); } if (timelineSet.getTimelineForEvent(eventId)) { return Promise.resolve(timelineSet.getTimelineForEvent(eventId)); } var path = utils.encodeUri("/rooms/$roomId/context/$eventId", { $roomId: timelineSet.room.roomId, $eventId: eventId }); var params = undefined; if (this._clientOpts.lazyLoadMembers) { params = { filter: JSON.stringify(_filter.Filter.LAZY_LOADING_MESSAGES_FILTER) }; } // TODO: we should implement a backoff (as per scrollback()) to deal more // nicely with HTTP errors. var self = this; var promise = self._http.authedRequest(undefined, "GET", path, params).then(function (res) { if (!res.event) { throw new Error("'event' not in '/context' result - homeserver too old?"); } // by the time the request completes, the event might have ended up in // the timeline. if (timelineSet.getTimelineForEvent(eventId)) { return timelineSet.getTimelineForEvent(eventId); } // we start with the last event, since that's the point at which we // have known state. // events_after is already backwards; events_before is forwards. res.events_after.reverse(); var events = res.events_after.concat([res.event]).concat(res.events_before); var matrixEvents = utils.map(events, self.getEventMapper()); var timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId()); if (!timeline) { timeline = timelineSet.addTimeline(); timeline.initialiseState(utils.map(res.state, self.getEventMapper())); timeline.getState(_eventTimeline.EventTimeline.FORWARDS).paginationToken = res.end; } else { var stateEvents = utils.map(res.state, self.getEventMapper()); timeline.getState(_eventTimeline.EventTimeline.BACKWARDS).setUnknownStateEvents(stateEvents); } timelineSet.addEventsToTimeline(matrixEvents, true, timeline, res.start); // there is no guarantee that the event ended up in "timeline" (we // might have switched to a neighbouring timeline) - so check the // room's index again. On the other hand, there's no guarantee the // event ended up anywhere, if it was later redacted, so we just // return the timeline we first thought of. var tl = timelineSet.getTimelineForEvent(eventId) || timeline; return tl; }); return promise; }; /** * Makes a request to /messages with the appropriate lazy loading filter set. * XXX: if we do get rid of scrollback (as it's not used at the moment), * we could inline this method again in paginateEventTimeline as that would * then be the only call-site * @param {string} roomId * @param {string} fromToken * @param {number} limit the maximum amount of events the retrieve * @param {string} dir 'f' or 'b' * @param {Filter} timelineFilter the timeline filter to pass * @return {Promise} */ MatrixClient.prototype._createMessagesRequest = function (roomId, fromToken, limit, dir) { var timelineFilter = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var path = utils.encodeUri("/rooms/$roomId/messages", { $roomId: roomId }); if (limit === undefined) { limit = 30; } var params = { from: fromToken, limit: limit, dir: dir }; var filter = null; if (this._clientOpts.lazyLoadMembers) { // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER, // so the timelineFilter doesn't get written into it below filter = Object.assign({}, _filter.Filter.LAZY_LOADING_MESSAGES_FILTER); } if (timelineFilter) { // XXX: it's horrific that /messages' filter parameter doesn't match // /sync's one - see https://matrix.org/jira/browse/SPEC-451 filter = filter || {}; Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()); } if (filter) { params.filter = JSON.stringify(filter); } return this._http.authedRequest(undefined, "GET", path, params); }; /** * Take an EventTimeline, and back/forward-fill results. * * @param {module:models/event-timeline~EventTimeline} eventTimeline timeline * object to be updated * @param {Object} [opts] * @param {bool} [opts.backwards = false] true to fill backwards, * false to go forwards * @param {number} [opts.limit = 30] number of events to request * * @return {Promise} Resolves to a boolean: false if there are no * events and we reached either end of the timeline; else true. */ MatrixClient.prototype.paginateEventTimeline = function (eventTimeline, opts) { var isNotifTimeline = eventTimeline.getTimelineSet() === this._notifTimelineSet; // TODO: we should implement a backoff (as per scrollback()) to deal more // nicely with HTTP errors. opts = opts || {}; var backwards = opts.backwards || false; if (isNotifTimeline) { if (!backwards) { throw new Error("paginateNotifTimeline can only paginate backwards"); } } var dir = backwards ? _eventTimeline.EventTimeline.BACKWARDS : _eventTimeline.EventTimeline.FORWARDS; var token = eventTimeline.getPaginationToken(dir); if (!token) { // no token - no results. return Promise.resolve(false); } var pendingRequest = eventTimeline._paginationRequests[dir]; if (pendingRequest) { // already a request in progress - return the existing promise return pendingRequest; } var path; var params; var promise; var self = this; if (isNotifTimeline) { path = "/notifications"; params = { limit: 'limit' in opts ? opts.limit : 30, only: 'highlight' }; if (token && token !== "end") { params.from = token; } promise = this._http.authedRequest(undefined, "GET", path, params, undefined).then(function (res) { var token = res.next_token; var matrixEvents = []; for (var i = 0; i < res.notifications.length; i++) { var notification = res.notifications[i]; var event = self.getEventMapper()(notification.event); event.setPushActions(_pushprocessor.PushProcessor.actionListToActionsObject(notification.actions)); event.event.room_id = notification.room_id; // XXX: gutwrenching matrixEvents[i] = event; } eventTimeline.getTimelineSet().addEventsToTimeline(matrixEvents, backwards, eventTimeline, token); // if we've hit the end of the timeline, we need to stop trying to // paginate. We need to keep the 'forwards' token though, to make sure // we can recover from gappy syncs. if (backwards && !res.next_token) { eventTimeline.setPaginationToken(null, dir); } return res.next_token ? true : false; })["finally"](function () { eventTimeline._paginationRequests[dir] = null; }); eventTimeline._paginationRequests[dir] = promise; } else { var room = this.getRoom(eventTimeline.getRoomId()); if (!room) { throw new Error("Unknown room " + eventTimeline.getRoomId()); } promise = this._createMessagesRequest(eventTimeline.getRoomId(), token, opts.limit, dir, eventTimeline.getFilter()); promise.then(function (res) { if (res.state) { var roomState = eventTimeline.getState(dir); var stateEvents = utils.map(res.state, self.getEventMapper()); roomState.setUnknownStateEvents(stateEvents); } var token = res.end; var matrixEvents = utils.map(res.chunk, self.getEventMapper()); eventTimeline.getTimelineSet().addEventsToTimeline(matrixEvents, backwards, eventTimeline, token); // if we've hit the end of the timeline, we need to stop trying to // paginate. We need to keep the 'forwards' token though, to make sure // we can recover from gappy syncs. if (backwards && res.end == res.start) { eventTimeline.setPaginationToken(null, dir); } return res.end != res.start; })["finally"](function () { eventTimeline._paginationRequests[dir] = null; }); eventTimeline._paginationRequests[dir] = promise; } return promise; }; /** * Reset the notifTimelineSet entirely, paginating in some historical notifs as * a starting point for subsequent pagination. */ MatrixClient.prototype.resetNotifTimelineSet = function () { if (!this._notifTimelineSet) { return; } // FIXME: This thing is a total hack, and results in duplicate events being // added to the timeline both from /sync and /notifications, and lots of // slow and wasteful processing and pagination. The correct solution is to // extend /messages or /search or something to filter on notifications. // use the fictitious token 'end'. in practice we would ideally give it // the oldest backwards pagination token from /sync, but /sync doesn't // know about /notifications, so we have no choice but to start paginating // from the current point in time. This may well overlap with historical // notifs which are then inserted into the timeline by /sync responses. this._notifTimelineSet.resetLiveTimeline('end', null); // we could try to paginate a single event at this point in order to get // a more valid pagination token, but it just ends up with an out of order // timeline. given what a mess this is and given we're going to have duplicate // events anyway, just leave it with the dummy token for now. /* this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), { backwards: true, limit: 1 }); */ }; /** * Peek into a room and receive updates about the room. This only works if the * history visibility for the room is world_readable. * @param {String} roomId The room to attempt to peek into. * @return {Promise} Resolves: Room object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.peekInRoom = function (roomId) { if (this._peekSync) { this._peekSync.stopPeeking(); } this._peekSync = new _sync.SyncApi(this, this._clientOpts); return this._peekSync.peek(roomId); }; /** * Stop any ongoing room peeking. */ MatrixClient.prototype.stopPeeking = function () { if (this._peekSync) { this._peekSync.stopPeeking(); this._peekSync = null; } }; /** * Set r/w flags for guest access in a room. * @param {string} roomId The room to configure guest access in. * @param {Object} opts Options * @param {boolean} opts.allowJoin True to allow guests to join this room. This * implicitly gives guests write access. If false or not given, guests are * explicitly forbidden from joining the room. * @param {boolean} opts.allowRead True to set history visibility to * be world_readable. This gives guests read access *from this point forward*. * If false or not given, history visibility is not modified. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setGuestAccess = function (roomId, opts) { var writePromise = this.sendStateEvent(roomId, "m.room.guest_access", { guest_access: opts.allowJoin ? "can_join" : "forbidden" }); var readPromise = Promise.resolve(); if (opts.allowRead) { readPromise = this.sendStateEvent(roomId, "m.room.history_visibility", { history_visibility: "world_readable" }); } return Promise.all([readPromise, writePromise]); }; // Registration/Login operations // ============================= /** * Requests an email verification token for the purposes of registration. * This API requests a token from the homeserver. * The doesServerRequireIdServerParam() method can be used to determine if * the server requires the id_server parameter to be provided. * * Parameters and return value are as for requestEmailToken * @param {string} email As requestEmailToken * @param {string} clientSecret As requestEmailToken * @param {number} sendAttempt As requestEmailToken * @param {string} nextLink As requestEmailToken * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype.requestRegisterEmailToken = function (email, clientSecret, sendAttempt, nextLink) { return this._requestTokenFromEndpoint("/register/email/requestToken", { email: email, client_secret: clientSecret, send_attempt: sendAttempt, next_link: nextLink }); }; /** * Requests a text message verification token for the purposes of registration. * This API requests a token from the homeserver. * The doesServerRequireIdServerParam() method can be used to determine if * the server requires the id_server parameter to be provided. * * @param {string} phoneCountry The ISO 3166-1 alpha-2 code for the country in which * phoneNumber should be parsed relative to. * @param {string} phoneNumber The phone number, in national or international format * @param {string} clientSecret As requestEmailToken * @param {number} sendAttempt As requestEmailToken * @param {string} nextLink As requestEmailToken * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype.requestRegisterMsisdnToken = function (phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) { return this._requestTokenFromEndpoint("/register/msisdn/requestToken", { country: phoneCountry, phone_number: phoneNumber, client_secret: clientSecret, send_attempt: sendAttempt, next_link: nextLink }); }; /** * Requests an email verification token for the purposes of adding a * third party identifier to an account. * This API requests a token from the homeserver. * The doesServerRequireIdServerParam() method can be used to determine if * the server requires the id_server parameter to be provided. * If an account with the given email address already exists and is * associated with an account other than the one the user is authed as, * it will either send an email to the address informing them of this * or return M_THREEPID_IN_USE (which one is up to the Home Server). * * @param {string} email As requestEmailToken * @param {string} clientSecret As requestEmailToken * @param {number} sendAttempt As requestEmailToken * @param {string} nextLink As requestEmailToken * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype.requestAdd3pidEmailToken = function (email, clientSecret, sendAttempt, nextLink) { return this._requestTokenFromEndpoint("/account/3pid/email/requestToken", { email: email, client_secret: clientSecret, send_attempt: sendAttempt, next_link: nextLink }); }; /** * Requests a text message verification token for the purposes of adding a * third party identifier to an account. * This API proxies the Identity Server /validate/email/requestToken API, * adding specific behaviour for the addition of phone numbers to an * account, as requestAdd3pidEmailToken. * * @param {string} phoneCountry As requestRegisterMsisdnToken * @param {string} phoneNumber As requestRegisterMsisdnToken * @param {string} clientSecret As requestEmailToken * @param {number} sendAttempt As requestEmailToken * @param {string} nextLink As requestEmailToken * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype.requestAdd3pidMsisdnToken = function (phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) { return this._requestTokenFromEndpoint("/account/3pid/msisdn/requestToken", { country: phoneCountry, phone_number: phoneNumber, client_secret: clientSecret, send_attempt: sendAttempt, next_link: nextLink }); }; /** * Requests an email verification token for the purposes of resetting * the password on an account. * This API proxies the Identity Server /validate/email/requestToken API, * adding specific behaviour for the password resetting. Specifically, * if no account with the given email address exists, it may either * return M_THREEPID_NOT_FOUND or send an email * to the address informing them of this (which one is up to the Home Server). * * requestEmailToken calls the equivalent API directly on the ID server, * therefore bypassing the password reset specific logic. * * @param {string} email As requestEmailToken * @param {string} clientSecret As requestEmailToken * @param {number} sendAttempt As requestEmailToken * @param {string} nextLink As requestEmailToken * @param {module:client.callback} callback Optional. As requestEmailToken * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype.requestPasswordEmailToken = function (email, clientSecret, sendAttempt, nextLink) { return this._requestTokenFromEndpoint("/account/password/email/requestToken", { email: email, client_secret: clientSecret, send_attempt: sendAttempt, next_link: nextLink }); }; /** * Requests a text message verification token for the purposes of resetting * the password on an account. * This API proxies the Identity Server /validate/email/requestToken API, * adding specific behaviour for the password resetting, as requestPasswordEmailToken. * * @param {string} phoneCountry As requestRegisterMsisdnToken * @param {string} phoneNumber As requestRegisterMsisdnToken * @param {string} clientSecret As requestEmailToken * @param {number} sendAttempt As requestEmailToken * @param {string} nextLink As requestEmailToken * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype.requestPasswordMsisdnToken = function (phoneCountry, phoneNumber, clientSecret, sendAttempt, nextLink) { return this._requestTokenFromEndpoint("/account/password/msisdn/requestToken", { country: phoneCountry, phone_number: phoneNumber, client_secret: clientSecret, send_attempt: sendAttempt, next_link: nextLink }); }; /** * Internal utility function for requesting validation tokens from usage-specific * requestToken endpoints. * * @param {string} endpoint The endpoint to send the request to * @param {object} params Parameters for the POST request * @return {Promise} Resolves: As requestEmailToken */ MatrixClient.prototype._requestTokenFromEndpoint = /*#__PURE__*/function () { var _ref19 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(endpoint, params) { var postParams, idServerUrl, identityAccessToken; return _regenerator["default"].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: postParams = Object.assign({}, params); // If the HS supports separate add and bind, then requestToken endpoints // don't need an IS as they are all validated by the HS directly. _context17.next = 3; return this.doesServerSupportSeparateAddAndBind(); case 3: _context17.t0 = !_context17.sent; if (!_context17.t0) { _context17.next = 6; break; } _context17.t0 = this.idBaseUrl; case 6: if (!_context17.t0) { _context17.next = 21; break; } idServerUrl = _url["default"].parse(this.idBaseUrl); if (idServerUrl.host) { _context17.next = 10; break; } throw new Error("Invalid ID server URL: " + this.idBaseUrl); case 10: postParams.id_server = idServerUrl.host; _context17.t1 = this.identityServer && this.identityServer.getAccessToken; if (!_context17.t1) { _context17.next = 16; break; } _context17.next = 15; return this.doesServerAcceptIdentityAccessToken(); case 15: _context17.t1 = _context17.sent; case 16: if (!_context17.t1) { _context17.next = 21; break; } _context17.next = 19; return this.identityServer.getAccessToken(); case 19: identityAccessToken = _context17.sent; if (identityAccessToken) { postParams.id_access_token = identityAccessToken; } case 21: return _context17.abrupt("return", this._http.request(undefined, "POST", endpoint, undefined, postParams)); case 22: case "end": return _context17.stop(); } } }, _callee17, this); })); return function (_x37, _x38) { return _ref19.apply(this, arguments); }; }(); // Push operations // =============== /** * Get the room-kind push rule associated with a room. * @param {string} scope "global" or device-specific. * @param {string} roomId the id of the room. * @return {object} the rule or undefined. */ MatrixClient.prototype.getRoomPushRule = function (scope, roomId) { // There can be only room-kind push rule per room // and its id is the room id. if (this.pushRules) { for (var i = 0; i < this.pushRules[scope].room.length; i++) { var rule = this.pushRules[scope].room[i]; if (rule.rule_id === roomId) { return rule; } } } else { throw new Error("SyncApi.sync() must be done before accessing to push rules."); } }; /** * Set a room-kind muting push rule in a room. * The operation also updates MatrixClient.pushRules at the end. * @param {string} scope "global" or device-specific. * @param {string} roomId the id of the room. * @param {string} mute the mute state. * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.setRoomMutePushRule = function (scope, roomId, mute) { var self = this; var deferred; var hasDontNotifyRule; // Get the existing room-kind push rule if any var roomPushRule = this.getRoomPushRule(scope, roomId); if (roomPushRule) { if (0 <= roomPushRule.actions.indexOf("dont_notify")) { hasDontNotifyRule = true; } } if (!mute) { // Remove the rule only if it is a muting rule if (hasDontNotifyRule) { deferred = this.deletePushRule(scope, "room", roomPushRule.rule_id); } } else { if (!roomPushRule) { deferred = this.addPushRule(scope, "room", roomId, { actions: ["dont_notify"] }); } else if (!hasDontNotifyRule) { // Remove the existing one before setting the mute push rule // This is a workaround to SYN-590 (Push rule update fails) deferred = utils.defer(); this.deletePushRule(scope, "room", roomPushRule.rule_id).then(function () { self.addPushRule(scope, "room", roomId, { actions: ["dont_notify"] }).then(function () { deferred.resolve(); }, function (err) { deferred.reject(err); }); }, function (err) { deferred.reject(err); }); deferred = deferred.promise; } } if (deferred) { return new Promise(function (resolve, reject) { // Update this.pushRules when the operation completes deferred.then(function () { self.getPushRules().then(function (result) { self.pushRules = result; resolve(); }, function (err) { reject(err); }); }, function (err) { // Update it even if the previous operation fails. This can help the // app to recover when push settings has been modifed from another client self.getPushRules().then(function (result) { self.pushRules = result; reject(err); }, function (err2) { reject(err); }); }); }); } }; // Search // ====== /** * Perform a server-side search for messages containing the given text. * @param {Object} opts Options for the search. * @param {string} opts.query The text to query. * @param {string=} opts.keys The keys to search on. Defaults to all keys. One * of "content.body", "content.name", "content.topic". * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.searchMessageText = function (opts, callback) { var roomEvents = { search_term: opts.query }; if ('keys' in opts) { roomEvents.keys = opts.keys; } return this.search({ body: { search_categories: { room_events: roomEvents } } }, callback); }; /** * Perform a server-side search for room events. * * The returned promise resolves to an object containing the fields: * * * {number} count: estimate of the number of results * * {string} next_batch: token for back-pagination; if undefined, there are * no more results * * {Array} highlights: a list of words to highlight from the stemming * algorithm * * {Array} results: a list of results * * Each entry in the results list is a {module:models/search-result.SearchResult}. * * @param {Object} opts * @param {string} opts.term the term to search for * @param {Object} opts.filter a JSON filter object to pass in the request * @return {Promise} Resolves: result object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.searchRoomEvents = function (opts) { // TODO: support groups var body = { search_categories: { room_events: { search_term: opts.term, filter: opts.filter, order_by: "recent", event_context: { before_limit: 1, after_limit: 1, include_profile: true } } } }; var searchResults = { _query: body, results: [], highlights: [] }; return this.search({ body: body }).then(this._processRoomEventsSearch.bind(this, searchResults)); }; /** * Take a result from an earlier searchRoomEvents call, and backfill results. * * @param {object} searchResults the results object to be updated * @return {Promise} Resolves: updated result object * @return {Error} Rejects: with an error response. */ MatrixClient.prototype.backPaginateRoomEventsSearch = function (searchResults) { // TODO: we should implement a backoff (as per scrollback()) to deal more // nicely with HTTP errors. if (!searchResults.next_batch) { return Promise.reject(new Error("Cannot backpaginate event search any further")); } if (searchResults.pendingRequest) { // already a request in progress - return the existing promise return searchResults.pendingRequest; } var searchOpts = { body: searchResults._query, next_batch: searchResults.next_batch }; var promise = this.search(searchOpts).then(this._processRoomEventsSearch.bind(this, searchResults))["finally"](function () { searchResults.pendingRequest = null; }); searchResults.pendingRequest = promise; return promise; }; /** * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the * response from the API call and updates the searchResults * * @param {Object} searchResults * @param {Object} response * @return {Object} searchResults * @private */ MatrixClient.prototype._processRoomEventsSearch = function (searchResults, response) { var room_events = response.search_categories.room_events; searchResults.count = room_events.count; searchResults.next_batch = room_events.next_batch; // combine the highlight list with our existing list; build an object // to avoid O(N^2) fail var highlights = {}; room_events.highlights.forEach(function (hl) { highlights[hl] = 1; }); searchResults.highlights.forEach(function (hl) { highlights[hl] = 1; }); // turn it back into a list. searchResults.highlights = Object.keys(highlights); // append the new results to our existing results for (var i = 0; i < room_events.results.length; i++) { var sr = _searchResult.SearchResult.fromJson(room_events.results[i], this.getEventMapper()); searchResults.results.push(sr); } return searchResults; }; /** * Populate the store with rooms the user has left. * @return {Promise} Resolves: TODO - Resolved when the rooms have * been added to the data store. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.syncLeftRooms = function () { // Guard against multiple calls whilst ongoing and multiple calls post success if (this._syncedLeftRooms) { return Promise.resolve([]); // don't call syncRooms again if it succeeded. } if (this._syncLeftRoomsPromise) { return this._syncLeftRoomsPromise; // return the ongoing request } var self = this; var syncApi = new _sync.SyncApi(this, this._clientOpts); this._syncLeftRoomsPromise = syncApi.syncLeftRooms(); // cleanup locks this._syncLeftRoomsPromise.then(function (res) { _logger.logger.log("Marking success of sync left room request"); self._syncedLeftRooms = true; // flip the bit on success })["finally"](function () { self._syncLeftRoomsPromise = null; // cleanup ongoing request state }); return this._syncLeftRoomsPromise; }; // Filters // ======= /** * Create a new filter. * @param {Object} content The HTTP body for the request * @return {Filter} Resolves to a Filter object. * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.createFilter = function (content) { var self = this; var path = utils.encodeUri("/user/$userId/filter", { $userId: this.credentials.userId }); return this._http.authedRequest(undefined, "POST", path, undefined, content).then(function (response) { // persist the filter var filter = _filter.Filter.fromJson(self.credentials.userId, response.filter_id, content); self.store.storeFilter(filter); return filter; }); }; /** * Retrieve a filter. * @param {string} userId The user ID of the filter owner * @param {string} filterId The filter ID to retrieve * @param {boolean} allowCached True to allow cached filters to be returned. * Default: True. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getFilter = function (userId, filterId, allowCached) { if (allowCached) { var filter = this.store.getFilter(userId, filterId); if (filter) { return Promise.resolve(filter); } } var self = this; var path = utils.encodeUri("/user/$userId/filter/$filterId", { $userId: userId, $filterId: filterId }); return this._http.authedRequest(undefined, "GET", path, undefined, undefined).then(function (response) { // persist the filter var filter = _filter.Filter.fromJson(userId, filterId, response); self.store.storeFilter(filter); return filter; }); }; /** * @param {string} filterName * @param {Filter} filter * @return {Promise} Filter ID */ MatrixClient.prototype.getOrCreateFilter = /*#__PURE__*/function () { var _ref20 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(filterName, filter) { var filterId, existingId, existingFilter, oldDef, newDef, createdFilter; return _regenerator["default"].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: filterId = this.store.getFilterIdByName(filterName); existingId = undefined; if (!filterId) { _context18.next = 15; break; } _context18.prev = 3; _context18.next = 6; return this.getFilter(this.credentials.userId, filterId, true); case 6: existingFilter = _context18.sent; if (existingFilter) { oldDef = existingFilter.getDefinition(); newDef = filter.getDefinition(); if (utils.deepCompare(oldDef, newDef)) { // super, just use that. // debuglog("Using existing filter ID %s: %s", filterId, // JSON.stringify(oldDef)); existingId = filterId; } } _context18.next = 14; break; case 10: _context18.prev = 10; _context18.t0 = _context18["catch"](3); if (!(_context18.t0.errcode !== "M_UNKNOWN" && _context18.t0.errcode !== "M_NOT_FOUND")) { _context18.next = 14; break; } throw _context18.t0; case 14: // if the filter doesn't exist anymore on the server, remove from store if (!existingId) { this.store.setFilterIdByName(filterName, undefined); } case 15: if (!existingId) { _context18.next = 17; break; } return _context18.abrupt("return", existingId); case 17: _context18.next = 19; return this.createFilter(filter.getDefinition()); case 19: createdFilter = _context18.sent; // debuglog("Created new filter ID %s: %s", createdFilter.filterId, // JSON.stringify(createdFilter.getDefinition())); this.store.setFilterIdByName(filterName, createdFilter.filterId); return _context18.abrupt("return", createdFilter.filterId); case 22: case "end": return _context18.stop(); } } }, _callee18, this, [[3, 10]]); })); return function (_x39, _x40) { return _ref20.apply(this, arguments); }; }(); /** * Gets a bearer token from the Home Server that the user can * present to a third party in order to prove their ownership * of the Matrix account they are logged into. * @return {Promise} Resolves: Token object * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.getOpenIdToken = function () { var path = utils.encodeUri("/user/$userId/openid/request_token", { $userId: this.credentials.userId }); return this._http.authedRequest(undefined, "POST", path, undefined, {}); }; // VoIP operations // =============== /** * @param {module:client.callback} callback Optional. * @return {Promise} Resolves: TODO * @return {module:http-api.MatrixError} Rejects: with an error response. */ MatrixClient.prototype.turnServer = function (callback) { return this._http.authedRequest(callback, "GET", "/voip/turnServer"); }; /** * Get the TURN servers for this home server. * @return {Array} The servers or an empty list. */ MatrixClient.prototype.getTurnServers = function () { return this._turnServers || []; }; /** * Set whether to allow a fallback ICE server should be used for negotiating a * WebRTC connection if the homeserver doesn't provide any servers. Defaults to * false. * * @param {boolean} allow */ MatrixClient.prototype.setFallbackICEServerAllowed = function (allow) { this._fallbackICEServerAllowed = allow; }; /** * Get whether to allow a fallback ICE server should be used for negotiating a * WebRTC connection if the homeserver doesn't provide any servers. Defaults to * false. * * @returns {boolean} */ MatrixClient.prototype.isFallbackICEServerAllowed = function () { return this._fallbackICEServerAllowed; }; // Synapse-specific APIs // ===================== /** * Determines if the current user is an administrator of the Synapse homeserver. * Returns false if untrue or the homeserver does not appear to be a Synapse * homeserver. This function is implementation specific and may change * as a result. * @return {boolean} true if the user appears to be a Synapse administrator. */ MatrixClient.prototype.isSynapseAdministrator = function () { var path = utils.encodeUri("/_synapse/admin/v1/users/$userId/admin", { $userId: this.getUserId() }); return this._http.authedRequest(undefined, 'GET', path, undefined, undefined, { prefix: '' }).then(function (r) { return r['admin']; }); // pull out the specific boolean we want }; /** * Performs a whois lookup on a user using Synapse's administrator API. * This function is implementation specific and may change as a * result. * @param {string} userId the User ID to look up. * @return {object} the whois response - see Synapse docs for information. */ MatrixClient.prototype.whoisSynapseUser = function (userId) { var path = utils.encodeUri("/_synapse/admin/v1/whois/$userId", { $userId: userId }); return this._http.authedRequest(undefined, 'GET', path, undefined, undefined, { prefix: '' }); }; /** * Deactivates a user using Synapse's administrator API. This * function is implementation specific and may change as a result. * @param {string} userId the User ID to deactivate. * @return {object} the deactivate response - see Synapse docs for information. */ MatrixClient.prototype.deactivateSynapseUser = function (userId) { var path = utils.encodeUri("/_synapse/admin/v1/deactivate/$userId", { $userId: userId }); return this._http.authedRequest(undefined, 'POST', path, undefined, undefined, { prefix: '' }); }; // Higher level APIs // ================= // TODO: stuff to handle: // local echo // event dup suppression? - apparently we should still be doing this // tracking current display name / avatar per-message // pagination // re-sending (including persisting pending messages to be sent) // - Need a nice way to callback the app for arbitrary events like // displayname changes // due to ambiguity (or should this be on a chat-specific layer)? // reconnect after connectivity outages /** * High level helper method to begin syncing and poll for new events. To listen for these * events, add a listener for {@link module:client~MatrixClient#event:"event"} * via {@link module:client~MatrixClient#on}. Alternatively, listen for specific * state change events. * @param {Object=} opts Options to apply when syncing. * @param {Number=} opts.initialSyncLimit The event limit= to apply * to initial sync. Default: 8. * @param {Boolean=} opts.includeArchivedRooms True to put archived=true * on the /initialSync request. Default: false. * @param {Boolean=} opts.resolveInvitesToProfiles True to do /profile requests * on every invite event if the displayname/avatar_url is not known for this user ID. * Default: false. * * @param {String=} opts.pendingEventOrdering Controls where pending messages * appear in a room's timeline. If "chronological", messages will appear * in the timeline when the call to sendEvent was made. If * "detached", pending messages will appear in a separate list, * accessbile via {@link module:models/room#getPendingEvents}. Default: * "chronological". * * @param {Number=} opts.pollTimeout The number of milliseconds to wait on /sync. * Default: 30000 (30 seconds). * * @param {Filter=} opts.filter The filter to apply to /sync calls. This will override * the opts.initialSyncLimit, which would normally result in a timeline limit filter. * * @param {Boolean=} opts.disablePresence True to perform syncing without automatically * updating presence. * @param {Boolean=} opts.lazyLoadMembers True to not load all membership events during * initial sync but fetch them when needed by calling `loadOutOfBandMembers` * This will override the filter option at this moment. * @param {Number=} opts.clientWellKnownPollPeriod The number of seconds between polls * to /.well-known/matrix/client, undefined to disable. This should be in the order of hours. * Default: undefined. */ MatrixClient.prototype.startClient = /*#__PURE__*/function () { var _ref21 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(opts) { var _this7 = this; var userId; return _regenerator["default"].wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: if (!this.clientRunning) { _context19.next = 2; break; } return _context19.abrupt("return"); case 2: this.clientRunning = true; // backwards compat for when 'opts' was 'historyLen'. if (typeof opts === "number") { opts = { initialSyncLimit: opts }; } // Create our own user object artificially (instead of waiting for sync) // so it's always available, even if the user is not in any rooms etc. userId = this.getUserId(); if (userId) { this.store.storeUser(new _user.User(userId)); } if (this._crypto) { this._crypto.uploadDeviceKeys(); this._crypto.start(); } // periodically poll for turn servers if we support voip checkTurnServers(this); if (this._syncApi) { // This shouldn't happen since we thought the client was not running _logger.logger.error("Still have sync object whilst not running: stopping old one"); this._syncApi.stop(); } // shallow-copy the opts dict before modifying and storing it opts = Object.assign({}, opts); opts.crypto = this._crypto; opts.canResetEntireTimeline = function (roomId) { if (!_this7._canResetTimelineCallback) { return false; } return _this7._canResetTimelineCallback(roomId); }; this._clientOpts = opts; this._syncApi = new _sync.SyncApi(this, opts); this._syncApi.sync(); if (opts.clientWellKnownPollPeriod !== undefined) { this._clientWellKnownIntervalID = setInterval(function () { _this7._fetchClientWellKnown(); }, 1000 * opts.clientWellKnownPollPeriod); this._fetchClientWellKnown(); } case 16: case "end": return _context19.stop(); } } }, _callee19, this); })); return function (_x41) { return _ref21.apply(this, arguments); }; }(); MatrixClient.prototype._fetchClientWellKnown = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20() { return _regenerator["default"].wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: // `getRawClientConfig` does not throw or reject on network errors, instead // it absorbs errors and returns `{}`. this._clientWellKnownPromise = _autodiscovery.AutoDiscovery.getRawClientConfig(this.getDomain()); _context20.next = 3; return this._clientWellKnownPromise; case 3: this._clientWellKnown = _context20.sent; this.emit("WellKnown.client", this._clientWellKnown); case 5: case "end": return _context20.stop(); } } }, _callee20, this); })); MatrixClient.prototype.getClientWellKnown = function () { return this._clientWellKnown; }; MatrixClient.prototype.waitForClientWellKnown = function () { return this._clientWellKnownPromise; }; /** * store client options with boolean/string/numeric values * to know in the next session what flags the sync data was * created with (e.g. lazy loading) * @param {object} opts the complete set of client options * @return {Promise} for store operation */ MatrixClient.prototype._storeClientOptions = function () { var primTypes = ["boolean", "string", "number"]; var serializableOpts = Object.entries(this._clientOpts).filter(function (_ref23) { var _ref24 = (0, _slicedToArray2["default"])(_ref23, 2), key = _ref24[0], value = _ref24[1]; return primTypes.includes((0, _typeof2["default"])(value)); }).reduce(function (obj, _ref25) { var _ref26 = (0, _slicedToArray2["default"])(_ref25, 2), key = _ref26[0], value = _ref26[1]; obj[key] = value; return obj; }, {}); return this.store.storeClientOptions(serializableOpts); }; /** * High level helper method to stop the client from polling and allow a * clean shutdown. */ MatrixClient.prototype.stopClient = function () { _logger.logger.log('stopping MatrixClient'); this.clientRunning = false; // TODO: f.e. Room => self.store.storeRoom(room) ? if (this._syncApi) { this._syncApi.stop(); this._syncApi = null; } if (this._crypto) { this._crypto.stop(); } if (this._peekSync) { this._peekSync.stopPeeking(); } global.clearTimeout(this._checkTurnServersTimeoutID); if (this._clientWellKnownIntervalID !== undefined) { global.clearInterval(this._clientWellKnownIntervalID); } }; /** * Get the API versions supported by the server, along with any * unstable APIs it supports * @return {Promise} The server /versions response */ MatrixClient.prototype.getVersions = function () { if (this._serverVersionsPromise) { return this._serverVersionsPromise; } this._serverVersionsPromise = this._http.request(undefined, // callback "GET", "/_matrix/client/versions", undefined, // queryParams undefined, // data { prefix: '' }); return this._serverVersionsPromise; }; /** * Check if a particular spec version is supported by the server. * @param {string} version The spec version (such as "r0.5.0") to check for. * @return {Promise} Whether it is supported */ MatrixClient.prototype.isVersionSupported = /*#__PURE__*/function () { var _ref27 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21(version) { var _yield$this$getVersio, versions; return _regenerator["default"].wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: _context21.next = 2; return this.getVersions(); case 2: _yield$this$getVersio = _context21.sent; versions = _yield$this$getVersio.versions; return _context21.abrupt("return", versions && versions.includes(version)); case 5: case "end": return _context21.stop(); } } }, _callee21, this); })); return function (_x42) { return _ref27.apply(this, arguments); }; }(); /** * Query the server to see if it support members lazy loading * @return {Promise} true if server supports lazy loading */ MatrixClient.prototype.doesServerSupportLazyLoading = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22() { var response, versions, unstableFeatures; return _regenerator["default"].wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: _context22.next = 2; return this.getVersions(); case 2: response = _context22.sent; if (response) { _context22.next = 5; break; } return _context22.abrupt("return", false); case 5: versions = response["versions"]; unstableFeatures = response["unstable_features"]; return _context22.abrupt("return", versions && versions.includes("r0.5.0") || unstableFeatures && unstableFeatures["m.lazy_load_members"]); case 8: case "end": return _context22.stop(); } } }, _callee22, this); })); /** * Query the server to see if the `id_server` parameter is required * when registering with an 3pid, adding a 3pid or resetting password. * @return {Promise} true if id_server parameter is required */ MatrixClient.prototype.doesServerRequireIdServerParam = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23() { var response, versions, unstableFeatures; return _regenerator["default"].wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: _context23.next = 2; return this.getVersions(); case 2: response = _context23.sent; if (response) { _context23.next = 5; break; } return _context23.abrupt("return", true); case 5: versions = response["versions"]; // Supporting r0.6.0 is the same as having the flag set to false if (!(versions && versions.includes("r0.6.0"))) { _context23.next = 8; break; } return _context23.abrupt("return", false); case 8: unstableFeatures = response["unstable_features"]; if (unstableFeatures) { _context23.next = 11; break; } return _context23.abrupt("return", true); case 11: if (!(unstableFeatures["m.require_identity_server"] === undefined)) { _context23.next = 15; break; } return _context23.abrupt("return", true); case 15: return _context23.abrupt("return", unstableFeatures["m.require_identity_server"]); case 16: case "end": return _context23.stop(); } } }, _callee23, this); })); /** * Query the server to see if the `id_access_token` parameter can be safely * passed to the homeserver. Some homeservers may trigger errors if they are not * prepared for the new parameter. * @return {Promise} true if id_access_token can be sent */ MatrixClient.prototype.doesServerAcceptIdentityAccessToken = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24() { var response, versions, unstableFeatures; return _regenerator["default"].wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: _context24.next = 2; return this.getVersions(); case 2: response = _context24.sent; if (response) { _context24.next = 5; break; } return _context24.abrupt("return", false); case 5: versions = response["versions"]; unstableFeatures = response["unstable_features"]; return _context24.abrupt("return", versions && versions.includes("r0.6.0") || unstableFeatures && unstableFeatures["m.id_access_token"]); case 8: case "end": return _context24.stop(); } } }, _callee24, this); })); /** * Query the server to see if it supports separate 3PID add and bind functions. * This affects the sequence of API calls clients should use for these operations, * so it's helpful to be able to check for support. * @return {Promise} true if separate functions are supported */ MatrixClient.prototype.doesServerSupportSeparateAddAndBind = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee25() { var response, versions, unstableFeatures; return _regenerator["default"].wrap(function _callee25$(_context25) { while (1) { switch (_context25.prev = _context25.next) { case 0: _context25.next = 2; return this.getVersions(); case 2: response = _context25.sent; if (response) { _context25.next = 5; break; } return _context25.abrupt("return", false); case 5: versions = response["versions"]; unstableFeatures = response["unstable_features"]; return _context25.abrupt("return", versions && versions.includes("r0.6.0") || unstableFeatures && unstableFeatures["m.separate_add_and_bind"]); case 8: case "end": return _context25.stop(); } } }, _callee25, this); })); /** * Query the server to see if it lists support for an unstable feature * in the /versions response * @param {string} feature the feature name * @return {Promise} true if the feature is supported */ MatrixClient.prototype.doesServerSupportUnstableFeature = /*#__PURE__*/function () { var _ref32 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee26(feature) { var response, unstableFeatures; return _regenerator["default"].wrap(function _callee26$(_context26) { while (1) { switch (_context26.prev = _context26.next) { case 0: _context26.next = 2; return this.getVersions(); case 2: response = _context26.sent; if (response) { _context26.next = 5; break; } return _context26.abrupt("return", false); case 5: unstableFeatures = response["unstable_features"]; return _context26.abrupt("return", unstableFeatures && !!unstableFeatures[feature]); case 7: case "end": return _context26.stop(); } } }, _callee26, this); })); return function (_x43) { return _ref32.apply(this, arguments); }; }(); /** * Query the server to see if it is forcing encryption to be enabled for * a given room preset, based on the /versions response. * @param {string} presetName The name of the preset to check. * @returns {Promise} true if the server is forcing encryption * for the preset. */ MatrixClient.prototype.doesServerForceEncryptionForPreset = /*#__PURE__*/function () { var _ref33 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee27(presetName) { var response, unstableFeatures; return _regenerator["default"].wrap(function _callee27$(_context27) { while (1) { switch (_context27.prev = _context27.next) { case 0: _context27.next = 2; return this.getVersions(); case 2: response = _context27.sent; if (response) { _context27.next = 5; break; } return _context27.abrupt("return", false); case 5: unstableFeatures = response["unstable_features"]; return _context27.abrupt("return", unstableFeatures && !!unstableFeatures["io.element.e2ee_forced.".concat(presetName)]); case 7: case "end": return _context27.stop(); } } }, _callee27, this); })); return function (_x44) { return _ref33.apply(this, arguments); }; }(); /** * Get if lazy loading members is being used. * @return {boolean} Whether or not members are lazy loaded by this client */ MatrixClient.prototype.hasLazyLoadMembersEnabled = function () { return !!this._clientOpts.lazyLoadMembers; }; /** * Set a function which is called when /sync returns a 'limited' response. * It is called with a room ID and returns a boolean. It should return 'true' if the SDK * can SAFELY remove events from this room. It may not be safe to remove events if there * are other references to the timelines for this room, e.g because the client is * actively viewing events in this room. * Default: returns false. * @param {Function} cb The callback which will be invoked. */ MatrixClient.prototype.setCanResetTimelineCallback = function (cb) { this._canResetTimelineCallback = cb; }; /** * Get the callback set via `setCanResetTimelineCallback`. * @return {?Function} The callback or null */ MatrixClient.prototype.getCanResetTimelineCallback = function () { return this._canResetTimelineCallback; }; /** * Returns relations for a given event. Handles encryption transparently, * with the caveat that the amount of events returned might be 0, even though you get a nextBatch. * When the returned promise resolves, all messages should have finished trying to decrypt. * @param {string} roomId the room of the event * @param {string} eventId the id of the event * @param {string} relationType the rel_type of the relations requested * @param {string} eventType the event type of the relations requested * @param {Object} opts options with optional values for the request. * @param {Object} opts.from the pagination token returned from a previous request as `nextBatch` to return following relations. * @return {Object} an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available. */ MatrixClient.prototype.relations = /*#__PURE__*/function () { var _ref34 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee28(roomId, eventId, relationType, eventType) { var opts, fetchedEventType, result, mapper, originalEvent, events, allEvents, _args28 = arguments; return _regenerator["default"].wrap(function _callee28$(_context28) { while (1) { switch (_context28.prev = _context28.next) { case 0: opts = _args28.length > 4 && _args28[4] !== undefined ? _args28[4] : {}; fetchedEventType = _getEncryptedIfNeededEventType(this, roomId, eventType); _context28.next = 4; return this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts); case 4: result = _context28.sent; mapper = this.getEventMapper(); if (result.original_event) { originalEvent = mapper(result.original_event); } events = result.chunk.map(mapper); if (!(fetchedEventType === "m.room.encrypted")) { _context28.next = 13; break; } allEvents = originalEvent ? events.concat(originalEvent) : events; _context28.next = 12; return Promise.all(allEvents.map(function (e) { return new Promise(function (resolve) { return e.once("Event.decrypted", resolve); }); })); case 12: events = events.filter(function (e) { return e.getType() === eventType; }); case 13: return _context28.abrupt("return", { originalEvent: originalEvent, events: events, nextBatch: result.next_batch }); case 14: case "end": return _context28.stop(); } } }, _callee28, this); })); return function (_x45, _x46, _x47, _x48) { return _ref34.apply(this, arguments); }; }(); function setupCallEventHandler(client) { var candidatesByCall = {// callId: [Candidate] }; // The sync code always emits one event at a time, so it will patiently // wait for us to finish processing a call invite before delivering the // next event, even if that next event is a hangup. We therefore accumulate // all our call events and then process them on the 'sync' event, ie. // each time a sync has completed. This way, we can avoid emitting incoming // call events if we get both the invite and answer/hangup in the same sync. // This happens quite often, eg. replaying sync from storage, catchup sync // after loading and after we've been offline for a bit. var callEventBuffer = []; function evaluateEventBuffer() { if (client.getSyncState() === "SYNCING") { // don't process any events until they are all decrypted if (callEventBuffer.some(function (e) { return e.isBeingDecrypted(); })) return; var ignoreCallIds = {}; // Set // inspect the buffer and mark all calls which have been answered // or hung up before passing them to the call event handler. for (var i = callEventBuffer.length - 1; i >= 0; i--) { var ev = callEventBuffer[i]; if (ev.getType() === "m.call.answer" || ev.getType() === "m.call.hangup") { ignoreCallIds[ev.getContent().call_id] = "yep"; } } // now loop through the buffer chronologically and inject them callEventBuffer.forEach(function (e) { if (e.getType() === "m.call.invite" && ignoreCallIds[e.getContent().call_id]) { // This call has previously been answered or hung up: ignore it return; } try { callEventHandler(e); } catch (e) { _logger.logger.error("Caught exception handling call event", e); } }); callEventBuffer = []; } } client.on("sync", evaluateEventBuffer); function onEvent(event) { // any call events or ones that might be once they're decrypted if (event.getType().indexOf("m.call.") === 0 || event.isBeingDecrypted()) { // queue up for processing once all events from this sync have been // processed (see above). callEventBuffer.push(event); } if (event.isBeingDecrypted() || event.isDecryptionFailure()) { // add an event listener for once the event is decrypted. event.once("Event.decrypted", function () { if (event.getType().indexOf("m.call.") === -1) return; if (callEventBuffer.includes(event)) { // we were waiting for that event to decrypt, so recheck the buffer evaluateEventBuffer(); } else { // This one wasn't buffered so just run the event handler for it // straight away try { callEventHandler(event); } catch (e) { _logger.logger.error("Caught exception handling call event", e); } } }); } } client.on("event", onEvent); function callEventHandler(event) { var content = event.getContent(); var call = content.call_id ? client.callList[content.call_id] : undefined; var i; //console.info("RECV %s content=%s", event.getType(), JSON.stringify(content)); if (event.getType() === "m.call.invite") { if (event.getSender() === client.credentials.userId) { return; // ignore invites you send } if (event.getAge() > content.lifetime) { return; // expired call } if (call && call.state === "ended") { return; // stale/old invite event } if (call) { _logger.logger.log("WARN: Already have a MatrixCall with id %s but got an " + "invite. Clobbering.", content.call_id); } call = (0, _call.createNewMatrixCall)(client, event.getRoomId(), { forceTURN: client._forceTURN }); if (!call) { _logger.logger.log("Incoming call ID " + content.call_id + " but this client " + "doesn't support WebRTC"); // don't hang up the call: there could be other clients // connected that do support WebRTC and declining the // the call on their behalf would be really annoying. return; } call.callId = content.call_id; call._initWithInvite(event); client.callList[call.callId] = call; // if we stashed candidate events for that call ID, play them back now if (candidatesByCall[call.callId]) { for (i = 0; i < candidatesByCall[call.callId].length; i++) { call._gotRemoteIceCandidate(candidatesByCall[call.callId][i]); } } // Were we trying to call that user (room)? var existingCall; var existingCalls = utils.values(client.callList); for (i = 0; i < existingCalls.length; ++i) { var thisCall = existingCalls[i]; if (call.roomId === thisCall.roomId && thisCall.direction === 'outbound' && ["wait_local_media", "create_offer", "invite_sent"].indexOf(thisCall.state) !== -1) { existingCall = thisCall; break; } } if (existingCall) { // If we've only got to wait_local_media or create_offer and // we've got an invite, pick the incoming call because we know // we haven't sent our invite yet otherwise, pick whichever // call has the lowest call ID (by string comparison) if (existingCall.state === 'wait_local_media' || existingCall.state === 'create_offer' || existingCall.callId > call.callId) { _logger.logger.log("Glare detected: answering incoming call " + call.callId + " and canceling outgoing call " + existingCall.callId); existingCall._replacedBy(call); call.answer(); } else { _logger.logger.log("Glare detected: rejecting incoming call " + call.callId + " and keeping outgoing call " + existingCall.callId); call.hangup(); } } else { client.emit("Call.incoming", call); } } else if (event.getType() === 'm.call.answer') { if (!call) { return; } if (event.getSender() === client.credentials.userId) { if (call.state === 'ringing') { call._onAnsweredElsewhere(content); } } else { call._receivedAnswer(content); } } else if (event.getType() === 'm.call.candidates') { if (event.getSender() === client.credentials.userId) { return; } if (!call) { // store the candidates; we may get a call eventually. if (!candidatesByCall[content.call_id]) { candidatesByCall[content.call_id] = []; } candidatesByCall[content.call_id] = candidatesByCall[content.call_id].concat(content.candidates); } else { for (i = 0; i < content.candidates.length; i++) { call._gotRemoteIceCandidate(content.candidates[i]); } } } else if (event.getType() === 'm.call.hangup') { // Note that we also observe our own hangups here so we can see // if we've already rejected a call that would otherwise be valid if (!call) { // if not live, store the fact that the call has ended because // we're probably getting events backwards so // the hangup will come before the invite call = (0, _call.createNewMatrixCall)(client, event.getRoomId()); if (call) { call.callId = content.call_id; call._initWithHangup(event); client.callList[content.call_id] = call; } } else { if (call.state !== 'ended') { call._onHangupReceived(content); delete client.callList[content.call_id]; } } } } } function checkTurnServers(client) { if (!client._supportsVoip) { return; } client.turnServer().then(function (res) { if (res.uris) { _logger.logger.log("Got TURN URIs: " + res.uris + " refresh in " + res.ttl + " secs"); // map the response to a format that can be fed to // RTCPeerConnection var servers = { urls: res.uris, username: res.username, credential: res.password }; client._turnServers = [servers]; // re-fetch when we're about to reach the TTL client._checkTurnServersTimeoutID = setTimeout(function () { checkTurnServers(client); }, (res.ttl || 60 * 60) * 1000 * 0.9); } }, function (err) { _logger.logger.error("Failed to get TURN URIs"); client._checkTurnServersTimeoutID = setTimeout(function () { checkTurnServers(client); }, 60000); }); } function _reject(callback, reject, err) { if (callback) { callback(err); } reject(err); } function _resolve(callback, resolve, res) { if (callback) { callback(null, res); } resolve(res); } function _PojoToMatrixEventMapper(client, options) { var preventReEmit = Boolean(options && options.preventReEmit); function mapper(plainOldJsObject) { var event = new _event2.MatrixEvent(plainOldJsObject); if (event.isEncrypted()) { if (!preventReEmit) { client.reEmitter.reEmit(event, ["Event.decrypted"]); } event.attemptDecryption(client._crypto); } var room = client.getRoom(event.getRoomId()); if (room && !preventReEmit) { room.reEmitter.reEmit(event, ["Event.replaced"]); } return event; } return mapper; } /** * @param {object} [options] * @param {bool} options.preventReEmit don't reemit events emitted on an event mapped by this mapper on the client * @return {Function} */ MatrixClient.prototype.getEventMapper = function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; return _PojoToMatrixEventMapper(this, options); }; /** * The app may wish to see if we have a key cached without * triggering a user interaction. * @return {object} */ MatrixClient.prototype.getCrossSigningCacheCallbacks = function () { return this._crypto && this._crypto._crossSigningInfo.getCacheCallbacks(); }; // Identity Server Operations // ========================== /** * Generates a random string suitable for use as a client secret. This * method is experimental and may change. * @return {string} A new client secret */ MatrixClient.prototype.generateClientSecret = function () { return (0, _randomstring.randomString)(32); }; // MatrixClient Event JSDocs /** * Fires whenever the SDK receives a new event. *

* This is only fired for live events received via /sync - it is not fired for * events received over context, search, or pagination APIs. * * @event module:client~MatrixClient#"event" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @example * matrixClient.on("event", function(event){ * var sender = event.getSender(); * }); */ /** * Fires whenever the SDK receives a new to-device event. * @event module:client~MatrixClient#"toDeviceEvent" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @example * matrixClient.on("toDeviceEvent", function(event){ * var sender = event.getSender(); * }); */ /** * Fires whenever the SDK's syncing state is updated. The state can be one of: *

    * *
  • PREPARED: The client has synced with the server at least once and is * ready for methods to be called on it. This will be immediately followed by * a state of SYNCING. This is the equivalent of "syncComplete" in the * previous API.
  • * *
  • CATCHUP: The client has detected the connection to the server might be * available again and will now try to do a sync again. As this sync might take * a long time (depending how long ago was last synced, and general server * performance) the client is put in this mode so the UI can reflect trying * to catch up with the server after losing connection.
  • * *
  • SYNCING : The client is currently polling for new events from the server. * This will be called after processing latest events from a sync.
  • * *
  • ERROR : The client has had a problem syncing with the server. If this is * called before PREPARED then there was a problem performing the initial * sync. If this is called after PREPARED then there was a problem polling * the server for updates. This may be called multiple times even if the state is * already ERROR. This is the equivalent of "syncError" in the previous * API.
  • * *
  • RECONNECTING: The sync connection has dropped, but not (yet) in a way that * should be considered erroneous. *
  • * *
  • STOPPED: The client has stopped syncing with server due to stopClient * being called. *
  • *
* State transition diagram: *
 *                                          +---->STOPPED
 *                                          |
 *              +----->PREPARED -------> SYNCING <--+
 *              |                        ^  |  ^    |
 *              |      CATCHUP ----------+  |  |    |
 *              |        ^                  V  |    |
 *   null ------+        |  +------- RECONNECTING   |
 *              |        V  V                       |
 *              +------->ERROR ---------------------+
 *
 * NB: 'null' will never be emitted by this event.
 *
 * 
* Transitions: *
    * *
  • null -> PREPARED : Occurs when the initial sync is completed * first time. This involves setting up filters and obtaining push rules. * *
  • null -> ERROR : Occurs when the initial sync failed first time. * *
  • ERROR -> PREPARED : Occurs when the initial sync succeeds * after previously failing. * *
  • PREPARED -> SYNCING : Occurs immediately after transitioning * to PREPARED. Starts listening for live updates rather than catching up. * *
  • SYNCING -> RECONNECTING : Occurs when the live update fails. * *
  • RECONNECTING -> RECONNECTING : Can occur if the update calls * continue to fail, but the keepalive calls (to /versions) succeed. * *
  • RECONNECTING -> ERROR : Occurs when the keepalive call also fails * *
  • ERROR -> SYNCING : Occurs when the client has performed a * live update after having previously failed. * *
  • ERROR -> ERROR : Occurs when the client has failed to keepalive * for a second time or more.
  • * *
  • SYNCING -> SYNCING : Occurs when the client has performed a live * update. This is called after processing.
  • * *
  • * -> STOPPED : Occurs once the client has stopped syncing or * trying to sync after stopClient has been called.
  • *
* * @event module:client~MatrixClient#"sync" * * @param {string} state An enum representing the syncing state. One of "PREPARED", * "SYNCING", "ERROR", "STOPPED". * * @param {?string} prevState An enum representing the previous syncing state. * One of "PREPARED", "SYNCING", "ERROR", "STOPPED" or null. * * @param {?Object} data Data about this transition. * * @param {MatrixError} data.error The matrix error if state=ERROR. * * @param {String} data.oldSyncToken The 'since' token passed to /sync. * null for the first successful sync since this client was * started. Only present if state=PREPARED or * state=SYNCING. * * @param {String} data.nextSyncToken The 'next_batch' result from /sync, which * will become the 'since' token for the next call to /sync. Only present if * state=PREPARED or state=SYNCING. * * @param {boolean} data.catchingUp True if we are working our way through a * backlog of events after connecting. Only present if state=SYNCING. * * @example * matrixClient.on("sync", function(state, prevState, data) { * switch (state) { * case "ERROR": * // update UI to say "Connection Lost" * break; * case "SYNCING": * // update UI to remove any "Connection Lost" message * break; * case "PREPARED": * // the client instance is ready to be queried. * var rooms = matrixClient.getRooms(); * break; * } * }); */ /** * Fires whenever the sdk learns about a new group. This event * is experimental and may change. * @event module:client~MatrixClient#"Group" * @param {Group} group The newly created, fully populated group. * @example * matrixClient.on("Group", function(group){ * var groupId = group.groupId; * }); */ /** * Fires whenever a new Room is added. This will fire when you are invited to a * room, as well as when you join a room. This event is experimental and * may change. * @event module:client~MatrixClient#"Room" * @param {Room} room The newly created, fully populated room. * @example * matrixClient.on("Room", function(room){ * var roomId = room.roomId; * }); */ /** * Fires whenever a Room is removed. This will fire when you forget a room. * This event is experimental and may change. * @event module:client~MatrixClient#"deleteRoom" * @param {string} roomId The deleted room ID. * @example * matrixClient.on("deleteRoom", function(roomId){ * // update UI from getRooms() * }); */ /** * Fires whenever an incoming call arrives. * @event module:client~MatrixClient#"Call.incoming" * @param {module:webrtc/call~MatrixCall} call The incoming call. * @example * matrixClient.on("Call.incoming", function(call){ * call.answer(); // auto-answer * }); */ /** * Fires whenever the login session the JS SDK is using is no * longer valid and the user must log in again. * NB. This only fires when action is required from the user, not * when then login session can be renewed by using a refresh token. * @event module:client~MatrixClient#"Session.logged_out" * @example * matrixClient.on("Session.logged_out", function(errorObj){ * // show the login screen * }); */ /** * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response * to a HTTP request. * @event module:client~MatrixClient#"no_consent" * @example * matrixClient.on("no_consent", function(message, contentUri) { * console.info(message + ' Go to ' + contentUri); * }); */ /** * Fires when a device is marked as verified/unverified/blocked/unblocked by * {@link module:client~MatrixClient#setDeviceVerified|MatrixClient.setDeviceVerified} or * {@link module:client~MatrixClient#setDeviceBlocked|MatrixClient.setDeviceBlocked}. * * @event module:client~MatrixClient#"deviceVerificationChanged" * @param {string} userId the owner of the verified device * @param {string} deviceId the id of the verified device * @param {module:crypto/deviceinfo} deviceInfo updated device information */ /** * Fires when the trust status of a user changes * If userId is the userId of the logged in user, this indicated a change * in the trust status of the cross-signing data on the account. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @event module:client~MatrixClient#"userTrustStatusChanged" * @param {string} userId the userId of the user in question * @param {UserTrustLevel} trustLevel The new trust level of the user */ /** * Fires when the user's cross-signing keys have changed or cross-signing * has been enabled/disabled. The client can use getStoredCrossSigningForUser * with the user ID of the logged in user to check if cross-signing is * enabled on the account. If enabled, it can test whether the current key * is trusted using with checkUserTrust with the user ID of the logged * in user. The checkOwnCrossSigningTrust function may be used to reconcile * the trust in the account key. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @event module:client~MatrixClient#"crossSigning.keysChanged" */ /** * Fires whenever new user-scoped account_data is added. * @event module:client~MatrixClient#"accountData" * @param {MatrixEvent} event The event describing the account_data just added * @param {MatrixEvent} event The previous account data, if known. * @example * matrixClient.on("accountData", function(event, oldEvent){ * myAccountData[event.type] = event.content; * }); */ /** * Fires whenever the stored devices for a user have changed * @event module:client~MatrixClient#"crypto.devicesUpdated" * @param {String[]} users A list of user IDs that were updated * @param {bool} initialFetch If true, the store was empty (apart * from our own device) and has been seeded. */ /** * Fires whenever the stored devices for a user will be updated * @event module:client~MatrixClient#"crypto.willUpdateDevices" * @param {String[]} users A list of user IDs that will be updated * @param {bool} initialFetch If true, the store is empty (apart * from our own device) and is being seeded. */ /** * Fires whenever the status of e2e key backup changes, as returned by getKeyBackupEnabled() * @event module:client~MatrixClient#"crypto.keyBackupStatus" * @param {bool} enabled true if key backup has been enabled, otherwise false * @example * matrixClient.on("crypto.keyBackupStatus", function(enabled){ * if (enabled) { * [...] * } * }); */ /** * Fires when we want to suggest to the user that they restore their megolm keys * from backup or by cross-signing the device. * * @event module:client~MatrixClient#"crypto.suggestKeyRestore" */ /** * Fires when a key verification is requested. * @event module:client~MatrixClient#"crypto.verification.request" * @param {object} data * @param {MatrixEvent} data.event the original verification request message * @param {Array} data.methods the verification methods that can be used * @param {Number} data.timeout the amount of milliseconds that should be waited * before cancelling the request automatically. * @param {Function} data.beginKeyVerification a function to call if a key * verification should be performed. The function takes one argument: the * name of the key verification method (taken from data.methods) to use. * @param {Function} data.cancel a function to call if the key verification is * rejected. */ /** * Fires when a key verification is requested with an unknown method. * @event module:client~MatrixClient#"crypto.verification.request.unknown" * @param {string} userId the user ID who requested the key verification * @param {Function} cancel a function that will send a cancellation message to * reject the key verification. */ /** * Fires when a secret request has been cancelled. If the client is prompting * the user to ask whether they want to share a secret, the prompt can be * dismissed. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @event module:client~MatrixClient#"crypto.secrets.requestCancelled" * @param {object} data * @param {string} data.user_id The user ID of the client that had requested the secret. * @param {string} data.device_id The device ID of the client that had requested the * secret. * @param {string} data.request_id The ID of the original request. */ /** * Fires when the client .well-known info is fetched. * * @event module:client~MatrixClient#"WellKnown.client" * @param {object} data The JSON object returned by the server */ // EventEmitter JSDocs /** * The {@link https://nodejs.org/api/events.html|EventEmitter} class. * @external EventEmitter * @see {@link https://nodejs.org/api/events.html} */ /** * Adds a listener to the end of the listeners array for the specified event. * No checks are made to see if the listener has already been added. Multiple * calls passing the same combination of event and listener will result in the * listener being added multiple times. * @function external:EventEmitter#on * @param {string} event The event to listen for. * @param {Function} listener The function to invoke. * @return {EventEmitter} for call chaining. */ /** * Alias for {@link external:EventEmitter#on}. * @function external:EventEmitter#addListener * @param {string} event The event to listen for. * @param {Function} listener The function to invoke. * @return {EventEmitter} for call chaining. */ /** * Adds a one time listener for the event. This listener is invoked only * the next time the event is fired, after which it is removed. * @function external:EventEmitter#once * @param {string} event The event to listen for. * @param {Function} listener The function to invoke. * @return {EventEmitter} for call chaining. */ /** * Remove a listener from the listener array for the specified event. * Caution: changes array indices in the listener array behind the * listener. * @function external:EventEmitter#removeListener * @param {string} event The event to listen for. * @param {Function} listener The function to invoke. * @return {EventEmitter} for call chaining. */ /** * Removes all listeners, or those of the specified event. It's not a good idea * to remove listeners that were added elsewhere in the code, especially when * it's on an emitter that you didn't create (e.g. sockets or file streams). * @function external:EventEmitter#removeAllListeners * @param {string} event Optional. The event to remove listeners for. * @return {EventEmitter} for call chaining. */ /** * Execute each of the listeners in order with the supplied arguments. * @function external:EventEmitter#emit * @param {string} event The event to emit. * @param {Function} listener The function to invoke. * @return {boolean} true if event had listeners, false otherwise. */ /** * By default EventEmitters will print a warning if more than 10 listeners are * added for a particular event. This is a useful default which helps finding * memory leaks. Obviously not all Emitters should be limited to 10. This * function allows that to be increased. Set to zero for unlimited. * @function external:EventEmitter#setMaxListeners * @param {Number} n The max number of listeners. * @return {EventEmitter} for call chaining. */ // MatrixClient Callback JSDocs /** * The standard MatrixClient callback interface. Functions which accept this * will specify 2 return arguments. These arguments map to the 2 parameters * specified in this callback. * @callback module:client.callback * @param {Object} err The error value, the "rejected" value or null. * @param {Object} data The data returned, the "resolved" value. */ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./ReEmitter":53,"./autodiscovery":54,"./base-apis":55,"./content-helpers":58,"./content-repo":59,"./crypto":73,"./crypto/RoomList":65,"./crypto/key_passphrase":74,"./crypto/olmlib":75,"./crypto/recoverykey":76,"./filter":91,"./http-api":92,"./logger":95,"./models/event":100,"./models/event-timeline":99,"./models/search-result":107,"./models/user":108,"./pushprocessor":109,"./randomstring":110,"./store/stub":119,"./sync":121,"./utils":123,"./webrtc/call":124,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/typeof":24,"@babel/runtime/regenerator":27,"events":36,"url":51}],58:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeHtmlMessage = makeHtmlMessage; exports.makeHtmlNotice = makeHtmlNotice; exports.makeHtmlEmote = makeHtmlEmote; exports.makeTextMessage = makeTextMessage; exports.makeNotice = makeNotice; exports.makeEmoteMessage = makeEmoteMessage; /* Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 ContentHelpers */ /** * Generates the content for a HTML Message event * @param {string} body the plaintext body of the message * @param {string} htmlBody the HTML representation of the message * @returns {{msgtype: string, format: string, body: string, formatted_body: string}} */ function makeHtmlMessage(body, htmlBody) { return { msgtype: "m.text", format: "org.matrix.custom.html", body: body, formatted_body: htmlBody }; } /** * Generates the content for a HTML Notice event * @param {string} body the plaintext body of the notice * @param {string} htmlBody the HTML representation of the notice * @returns {{msgtype: string, format: string, body: string, formatted_body: string}} */ function makeHtmlNotice(body, htmlBody) { return { msgtype: "m.notice", format: "org.matrix.custom.html", body: body, formatted_body: htmlBody }; } /** * Generates the content for a HTML Emote event * @param {string} body the plaintext body of the emote * @param {string} htmlBody the HTML representation of the emote * @returns {{msgtype: string, format: string, body: string, formatted_body: string}} */ function makeHtmlEmote(body, htmlBody) { return { msgtype: "m.emote", format: "org.matrix.custom.html", body: body, formatted_body: htmlBody }; } /** * Generates the content for a Plaintext Message event * @param {string} body the plaintext body of the emote * @returns {{msgtype: string, body: string}} */ function makeTextMessage(body) { return { msgtype: "m.text", body: body }; } /** * Generates the content for a Plaintext Notice event * @param {string} body the plaintext body of the notice * @returns {{msgtype: string, body: string}} */ function makeNotice(body) { return { msgtype: "m.notice", body: body }; } /** * Generates the content for a Plaintext Emote event * @param {string} body the plaintext body of the emote * @returns {{msgtype: string, body: string}} */ function makeEmoteMessage(body) { return { msgtype: "m.emote", body: body }; } },{}],59:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.getHttpUriForMxc = getHttpUriForMxc; var utils = _interopRequireWildcard(require("./utils")); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 content-repo */ /** * Get the HTTP URL for an MXC URI. * @param {string} baseUrl The base homeserver url which has a content repo. * @param {string} mxc The mxc:// URI. * @param {Number} width The desired width of the thumbnail. * @param {Number} height The desired height of the thumbnail. * @param {string} resizeMethod The thumbnail resize method to use, either * "crop" or "scale". * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs * directly. Fetching such URLs will leak information about the user to * anyone they share a room with. If false, will return the emptry string * for such URLs. * @return {string} The complete URL to the content. */ function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks) { if (typeof mxc !== "string" || !mxc) { return ''; } if (mxc.indexOf("mxc://") !== 0) { if (allowDirectLinks) { return mxc; } else { return ''; } } var serverAndMediaId = mxc.slice(6); // strips mxc:// var prefix = "/_matrix/media/r0/download/"; var params = {}; if (width) { params.width = Math.round(width); } if (height) { params.height = Math.round(height); } if (resizeMethod) { params.method = resizeMethod; } if (utils.keys(params).length > 0) { // these are thumbnailing params so they probably want the // thumbnailing API... prefix = "/_matrix/media/r0/thumbnail/"; } var fragmentOffset = serverAndMediaId.indexOf("#"); var fragment = ""; if (fragmentOffset >= 0) { fragment = serverAndMediaId.substr(fragmentOffset); serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset); } return baseUrl + prefix + serverAndMediaId + (utils.keys(params).length === 0 ? "" : "?" + utils.encodeParams(params)) + fragment; } },{"./utils":123,"@babel/runtime/helpers/interopRequireWildcard":13}],60:[function(require,module,exports){ (function (global,Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.createCryptoStoreCacheCallbacks = createCryptoStoreCacheCallbacks; exports.requestKeysDuringVerification = requestKeysDuringVerification; exports.DeviceTrustLevel = exports.UserTrustLevel = exports.CrossSigningLevel = exports.CrossSigningInfo = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _olmlib = require("./olmlib"); var _events = require("events"); var _logger = require("../logger"); var _indexeddbCryptoStore = require("../crypto/store/indexeddb-crypto-store"); var _aes = require("./aes"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var KEY_REQUEST_TIMEOUT_MS = 1000 * 60; function publicKeyFromKeyInfo(keyInfo) { // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey } // We assume only a single key, and we want the bare form without type // prefix, so we select the values. return Object.values(keyInfo.keys)[0]; } var CrossSigningInfo = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(CrossSigningInfo, _EventEmitter); var _super = _createSuper(CrossSigningInfo); /** * Information about a user's cross-signing keys * * @class * * @param {string} userId the user that the information is about * @param {object} callbacks Callbacks used to interact with the app * Requires getCrossSigningKey and saveCrossSigningKeys * @param {object} cacheCallbacks Callbacks used to interact with the cache */ function CrossSigningInfo(userId, callbacks, cacheCallbacks) { var _this; (0, _classCallCheck2["default"])(this, CrossSigningInfo); _this = _super.call(this); // you can't change the userId Object.defineProperty((0, _assertThisInitialized2["default"])(_this), 'userId', { enumerable: true, value: userId }); _this._callbacks = callbacks || {}; _this._cacheCallbacks = cacheCallbacks || {}; _this.keys = {}; _this.firstUse = true; // This tracks whether we've ever verified this user with any identity. // When you verify a user, any devices online at the time that receive // the verifying signature via the homeserver will latch this to true // and can use it in the future to detect cases where the user has // become unverifed later for any reason. _this.crossSigningVerifiedBefore = false; return _this; } (0, _createClass2["default"])(CrossSigningInfo, [{ key: "toStorage", value: function toStorage() { return { keys: this.keys, firstUse: this.firstUse, crossSigningVerifiedBefore: this.crossSigningVerifiedBefore }; } /** * Calls the app callback to ask for a private key * * @param {string} type The key type ("master", "self_signing", or "user_signing") * @param {string} expectedPubkey The matching public key or undefined to use * the stored public key for the given key type. * @returns {Array} An array with [ public key, Olm.PkSigning ] */ }, { key: "getCrossSigningKey", value: function () { var _getCrossSigningKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(type, expectedPubkey) { var shouldCache, validateKey, privkey, cacheresult, result; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: validateKey = function _validateKey(key) { if (!key) return; var signing = new global.Olm.PkSigning(); var gotPubkey = signing.init_with_seed(key); if (gotPubkey === expectedPubkey) { return [gotPubkey, signing]; } signing.free(); }; shouldCache = ["master", "self_signing", "user_signing"].indexOf(type) >= 0; if (this._callbacks.getCrossSigningKey) { _context.next = 4; break; } throw new Error("No getCrossSigningKey callback supplied"); case 4: if (expectedPubkey === undefined) { expectedPubkey = this.getId(type); } if (!(this._cacheCallbacks.getCrossSigningKeyCache && shouldCache)) { _context.next = 9; break; } _context.next = 8; return this._cacheCallbacks.getCrossSigningKeyCache(type, expectedPubkey); case 8: privkey = _context.sent; case 9: cacheresult = validateKey(privkey); if (!cacheresult) { _context.next = 12; break; } return _context.abrupt("return", cacheresult); case 12: _context.next = 14; return this._callbacks.getCrossSigningKey(type, expectedPubkey); case 14: privkey = _context.sent; result = validateKey(privkey); if (!result) { _context.next = 21; break; } if (!(this._cacheCallbacks.storeCrossSigningKeyCache && shouldCache)) { _context.next = 20; break; } _context.next = 20; return this._cacheCallbacks.storeCrossSigningKeyCache(type, privkey); case 20: return _context.abrupt("return", result); case 21: if (privkey) { _context.next = 23; break; } throw new Error("getCrossSigningKey callback for " + type + " returned falsey"); case 23: throw new Error("Key type " + type + " from getCrossSigningKey callback did not match"); case 24: case "end": return _context.stop(); } } }, _callee, this); })); function getCrossSigningKey(_x, _x2) { return _getCrossSigningKey.apply(this, arguments); } return getCrossSigningKey; }() /** * Check whether the private keys exist in secret storage. * XXX: This could be static, be we often seem to have an instance when we * want to know this anyway... * * @param {SecretStorage} secretStorage The secret store using account data * @returns {object} map of key name to key info the secret is encrypted * with, or null if it is not present or not encrypted with a trusted * key */ }, { key: "isStoredInSecretStorage", value: function () { var _isStoredInSecretStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(secretStorage) { var stored, intersect, _i2, _arr, type; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: intersect = function _intersect(s) { for (var _i = 0, _Object$keys = Object.keys(stored); _i < _Object$keys.length; _i++) { var k = _Object$keys[_i]; if (!s[k]) { delete stored[k]; } } }; _context2.next = 3; return secretStorage.isStored("m.cross_signing.master", false); case 3: _context2.t0 = _context2.sent; if (_context2.t0) { _context2.next = 6; break; } _context2.t0 = {}; case 6: stored = _context2.t0; _i2 = 0, _arr = ["self_signing", "user_signing"]; case 8: if (!(_i2 < _arr.length)) { _context2.next = 21; break; } type = _arr[_i2]; _context2.t1 = intersect; _context2.next = 13; return secretStorage.isStored("m.cross_signing.".concat(type), false); case 13: _context2.t2 = _context2.sent; if (_context2.t2) { _context2.next = 16; break; } _context2.t2 = {}; case 16: _context2.t3 = _context2.t2; (0, _context2.t1)(_context2.t3); case 18: _i2++; _context2.next = 8; break; case 21: return _context2.abrupt("return", Object.keys(stored).length ? stored : null); case 22: case "end": return _context2.stop(); } } }, _callee2); })); function isStoredInSecretStorage(_x3) { return _isStoredInSecretStorage.apply(this, arguments); } return isStoredInSecretStorage; }() /** * Store private keys in secret storage for use by other devices. This is * typically called in conjunction with the creation of new cross-signing * keys. * * @param {Map} keys The keys to store * @param {SecretStorage} secretStorage The secret store using account data */ }, { key: "isStoredInKeyCache", /** * Check whether the private keys exist in the local key cache. * * @param {string} [type] The type of key to get. One of "master", * "self_signing", or "user_signing". Optional, will check all by default. * @returns {boolean} True if all keys are stored in the local cache. */ value: function () { var _isStoredInKeyCache = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(type) { var cacheCallbacks, types, _i3, _types, t; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: cacheCallbacks = this._cacheCallbacks; if (cacheCallbacks) { _context3.next = 3; break; } return _context3.abrupt("return", false); case 3: types = type ? [type] : ["master", "self_signing", "user_signing"]; _i3 = 0, _types = types; case 5: if (!(_i3 < _types.length)) { _context3.next = 14; break; } t = _types[_i3]; _context3.next = 9; return cacheCallbacks.getCrossSigningKeyCache(t); case 9: if (_context3.sent) { _context3.next = 11; break; } return _context3.abrupt("return", false); case 11: _i3++; _context3.next = 5; break; case 14: return _context3.abrupt("return", true); case 15: case "end": return _context3.stop(); } } }, _callee3, this); })); function isStoredInKeyCache(_x4) { return _isStoredInKeyCache.apply(this, arguments); } return isStoredInKeyCache; }() /** * Get cross-signing private keys from the local cache. * * @returns {Map} A map from key type (string) to private key (Uint8Array) */ }, { key: "getCrossSigningKeysFromCache", value: function () { var _getCrossSigningKeysFromCache = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var keys, cacheCallbacks, _i4, _arr2, type, privKey; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: keys = new Map(); cacheCallbacks = this._cacheCallbacks; if (cacheCallbacks) { _context4.next = 4; break; } return _context4.abrupt("return", keys); case 4: _i4 = 0, _arr2 = ["master", "self_signing", "user_signing"]; case 5: if (!(_i4 < _arr2.length)) { _context4.next = 16; break; } type = _arr2[_i4]; _context4.next = 9; return cacheCallbacks.getCrossSigningKeyCache(type); case 9: privKey = _context4.sent; if (privKey) { _context4.next = 12; break; } return _context4.abrupt("continue", 13); case 12: keys.set(type, privKey); case 13: _i4++; _context4.next = 5; break; case 16: return _context4.abrupt("return", keys); case 17: case "end": return _context4.stop(); } } }, _callee4, this); })); function getCrossSigningKeysFromCache() { return _getCrossSigningKeysFromCache.apply(this, arguments); } return getCrossSigningKeysFromCache; }() /** * Get the ID used to identify the user. This can also be used to test for * the existence of a given key type. * * @param {string} type The type of key to get the ID of. One of "master", * "self_signing", or "user_signing". Defaults to "master". * * @return {string} the ID */ }, { key: "getId", value: function getId(type) { type = type || "master"; if (!this.keys[type]) return null; var keyInfo = this.keys[type]; return publicKeyFromKeyInfo(keyInfo); } /** * Create new cross-signing keys for the given key types. The public keys * will be held in this class, while the private keys are passed off to the * `saveCrossSigningKeys` application callback. * * @param {CrossSigningLevel} level The key types to reset */ }, { key: "resetKeys", value: function () { var _resetKeys = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(level) { var privateKeys, keys, masterSigning, masterPub, _yield$this$getCrossS, _yield$this$getCrossS2, sskSigning, sskPub, uskSigning, uskPub; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (this._callbacks.saveCrossSigningKeys) { _context5.next = 2; break; } throw new Error("No saveCrossSigningKeys callback supplied"); case 2: if (!(level === undefined || level & CrossSigningLevel.MASTER || !this.keys.master)) { _context5.next = 6; break; } level = CrossSigningLevel.MASTER | CrossSigningLevel.USER_SIGNING | CrossSigningLevel.SELF_SIGNING; _context5.next = 8; break; case 6: if (!(level === 0)) { _context5.next = 8; break; } return _context5.abrupt("return"); case 8: privateKeys = {}; keys = {}; _context5.prev = 10; if (!(level & CrossSigningLevel.MASTER)) { _context5.next = 18; break; } masterSigning = new global.Olm.PkSigning(); privateKeys.master = masterSigning.generate_seed(); masterPub = masterSigning.init_with_seed(privateKeys.master); keys.master = { user_id: this.userId, usage: ['master'], keys: (0, _defineProperty2["default"])({}, 'ed25519:' + masterPub, masterPub) }; _context5.next = 24; break; case 18: _context5.next = 20; return this.getCrossSigningKey("master"); case 20: _yield$this$getCrossS = _context5.sent; _yield$this$getCrossS2 = (0, _slicedToArray2["default"])(_yield$this$getCrossS, 2); masterPub = _yield$this$getCrossS2[0]; masterSigning = _yield$this$getCrossS2[1]; case 24: if (level & CrossSigningLevel.SELF_SIGNING) { sskSigning = new global.Olm.PkSigning(); try { privateKeys.self_signing = sskSigning.generate_seed(); sskPub = sskSigning.init_with_seed(privateKeys.self_signing); keys.self_signing = { user_id: this.userId, usage: ['self_signing'], keys: (0, _defineProperty2["default"])({}, 'ed25519:' + sskPub, sskPub) }; (0, _olmlib.pkSign)(keys.self_signing, masterSigning, this.userId, masterPub); } finally { sskSigning.free(); } } if (level & CrossSigningLevel.USER_SIGNING) { uskSigning = new global.Olm.PkSigning(); try { privateKeys.user_signing = uskSigning.generate_seed(); uskPub = uskSigning.init_with_seed(privateKeys.user_signing); keys.user_signing = { user_id: this.userId, usage: ['user_signing'], keys: (0, _defineProperty2["default"])({}, 'ed25519:' + uskPub, uskPub) }; (0, _olmlib.pkSign)(keys.user_signing, masterSigning, this.userId, masterPub); } finally { uskSigning.free(); } } Object.assign(this.keys, keys); this._callbacks.saveCrossSigningKeys(privateKeys); case 28: _context5.prev = 28; if (masterSigning) { masterSigning.free(); } return _context5.finish(28); case 31: case "end": return _context5.stop(); } } }, _callee5, this, [[10,, 28, 31]]); })); function resetKeys(_x5) { return _resetKeys.apply(this, arguments); } return resetKeys; }() /** * unsets the keys, used when another session has reset the keys, to disable cross-signing */ }, { key: "clearKeys", value: function clearKeys() { this.keys = {}; } }, { key: "setKeys", value: function setKeys(keys) { var signingKeys = {}; if (keys.master) { if (keys.master.user_id !== this.userId) { var error = "Mismatched user ID " + keys.master.user_id + " in master key from " + this.userId; _logger.logger.error(error); throw new Error(error); } if (!this.keys.master) { // this is the first key we've seen, so first-use is true this.firstUse = true; } else if (publicKeyFromKeyInfo(keys.master) !== this.getId()) { // this is a different key, so first-use is false this.firstUse = false; } // otherwise, same key, so no change signingKeys.master = keys.master; } else if (this.keys.master) { signingKeys.master = this.keys.master; } else { throw new Error("Tried to set cross-signing keys without a master key"); } var masterKey = publicKeyFromKeyInfo(signingKeys.master); // verify signatures if (keys.user_signing) { if (keys.user_signing.user_id !== this.userId) { var _error = "Mismatched user ID " + keys.master.user_id + " in user_signing key from " + this.userId; _logger.logger.error(_error); throw new Error(_error); } try { (0, _olmlib.pkVerify)(keys.user_signing, masterKey, this.userId); } catch (e) { _logger.logger.error("invalid signature on user-signing key"); // FIXME: what do we want to do here? throw e; } } if (keys.self_signing) { if (keys.self_signing.user_id !== this.userId) { var _error2 = "Mismatched user ID " + keys.master.user_id + " in self_signing key from " + this.userId; _logger.logger.error(_error2); throw new Error(_error2); } try { (0, _olmlib.pkVerify)(keys.self_signing, masterKey, this.userId); } catch (e) { _logger.logger.error("invalid signature on self-signing key"); // FIXME: what do we want to do here? throw e; } } // if everything checks out, then save the keys if (keys.master) { this.keys.master = keys.master; // if the master key is set, then the old self-signing and // user-signing keys are obsolete this.keys.self_signing = null; this.keys.user_signing = null; } if (keys.self_signing) { this.keys.self_signing = keys.self_signing; } if (keys.user_signing) { this.keys.user_signing = keys.user_signing; } } }, { key: "updateCrossSigningVerifiedBefore", value: function updateCrossSigningVerifiedBefore(isCrossSigningVerified) { // It is critical that this value latches forward from false to true but // never back to false to avoid a downgrade attack. if (!this.crossSigningVerifiedBefore && isCrossSigningVerified) { this.crossSigningVerifiedBefore = true; } } }, { key: "signObject", value: function () { var _signObject = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(data, type) { var _yield$this$getCrossS3, _yield$this$getCrossS4, pubkey, signing; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (this.keys[type]) { _context6.next = 2; break; } throw new Error("Attempted to sign with " + type + " key but no such key present"); case 2: _context6.next = 4; return this.getCrossSigningKey(type); case 4: _yield$this$getCrossS3 = _context6.sent; _yield$this$getCrossS4 = (0, _slicedToArray2["default"])(_yield$this$getCrossS3, 2); pubkey = _yield$this$getCrossS4[0]; signing = _yield$this$getCrossS4[1]; _context6.prev = 8; (0, _olmlib.pkSign)(data, signing, this.userId, pubkey); return _context6.abrupt("return", data); case 11: _context6.prev = 11; signing.free(); return _context6.finish(11); case 14: case "end": return _context6.stop(); } } }, _callee6, this, [[8,, 11, 14]]); })); function signObject(_x6, _x7) { return _signObject.apply(this, arguments); } return signObject; }() }, { key: "signUser", value: function () { var _signUser = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(key) { return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: if (this.keys.user_signing) { _context7.next = 3; break; } _logger.logger.info("No user signing key: not signing user"); return _context7.abrupt("return"); case 3: return _context7.abrupt("return", this.signObject(key.keys.master, "user_signing")); case 4: case "end": return _context7.stop(); } } }, _callee7, this); })); function signUser(_x8) { return _signUser.apply(this, arguments); } return signUser; }() }, { key: "signDevice", value: function () { var _signDevice = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(userId, device) { return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!(userId !== this.userId)) { _context8.next = 2; break; } throw new Error("Trying to sign ".concat(userId, "'s device; can only sign our own device")); case 2: if (this.keys.self_signing) { _context8.next = 5; break; } _logger.logger.info("No self signing key: not signing device"); return _context8.abrupt("return"); case 5: return _context8.abrupt("return", this.signObject({ algorithms: device.algorithms, keys: device.keys, device_id: device.deviceId, user_id: userId }, "self_signing")); case 6: case "end": return _context8.stop(); } } }, _callee8, this); })); function signDevice(_x9, _x10) { return _signDevice.apply(this, arguments); } return signDevice; }() /** * Check whether a given user is trusted. * * @param {CrossSigningInfo} userCrossSigning Cross signing info for user * * @returns {UserTrustLevel} */ }, { key: "checkUserTrust", value: function checkUserTrust(userCrossSigning) { // if we're checking our own key, then it's trusted if the master key // and self-signing key match if (this.userId === userCrossSigning.userId && this.getId() && this.getId() === userCrossSigning.getId() && this.getId("self_signing") && this.getId("self_signing") === userCrossSigning.getId("self_signing")) { return new UserTrustLevel(true, true, this.firstUse); } if (!this.keys.user_signing) { // If there's no user signing key, they can't possibly be verified. // They may be TOFU trusted though. return new UserTrustLevel(false, false, userCrossSigning.firstUse); } var userTrusted; var userMaster = userCrossSigning.keys.master; var uskId = this.getId('user_signing'); try { (0, _olmlib.pkVerify)(userMaster, uskId, this.userId); userTrusted = true; } catch (e) { userTrusted = false; } return new UserTrustLevel(userTrusted, userCrossSigning.crossSigningVerifiedBefore, userCrossSigning.firstUse); } /** * Check whether a given device is trusted. * * @param {CrossSigningInfo} userCrossSigning Cross signing info for user * @param {module:crypto/deviceinfo} device The device to check * @param {bool} localTrust Whether the device is trusted locally * @param {bool} trustCrossSignedDevices Whether we trust cross signed devices * * @returns {DeviceTrustLevel} */ }, { key: "checkDeviceTrust", value: function checkDeviceTrust(userCrossSigning, device, localTrust, trustCrossSignedDevices) { var userTrust = this.checkUserTrust(userCrossSigning); var userSSK = userCrossSigning.keys.self_signing; if (!userSSK) { // if the user has no self-signing key then we cannot make any // trust assertions about this device from cross-signing return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices); } var deviceObj = deviceToObject(device, userCrossSigning.userId); try { // if we can verify the user's SSK from their master key... (0, _olmlib.pkVerify)(userSSK, userCrossSigning.getId(), userCrossSigning.userId); // ...and this device's key from their SSK... (0, _olmlib.pkVerify)(deviceObj, publicKeyFromKeyInfo(userSSK), userCrossSigning.userId); // ...then we trust this device as much as far as we trust the user return DeviceTrustLevel.fromUserTrustLevel(userTrust, localTrust, trustCrossSignedDevices); } catch (e) { return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices); } } /** * @returns {object} Cache callbacks */ }, { key: "getCacheCallbacks", value: function getCacheCallbacks() { return this._cacheCallbacks; } }], [{ key: "fromStorage", value: function fromStorage(obj, userId) { var res = new CrossSigningInfo(userId); for (var prop in obj) { if (obj.hasOwnProperty(prop)) { res[prop] = obj[prop]; } } return res; } }, { key: "storeInSecretStorage", value: function () { var _storeInSecretStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(keys, secretStorage) { var _iterator, _step, _step$value, type, privateKey, encodedKey; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _iterator = _createForOfIteratorHelper(keys); _context9.prev = 1; _iterator.s(); case 3: if ((_step = _iterator.n()).done) { _context9.next = 10; break; } _step$value = (0, _slicedToArray2["default"])(_step.value, 2), type = _step$value[0], privateKey = _step$value[1]; encodedKey = (0, _olmlib.encodeBase64)(privateKey); _context9.next = 8; return secretStorage.store("m.cross_signing.".concat(type), encodedKey); case 8: _context9.next = 3; break; case 10: _context9.next = 15; break; case 12: _context9.prev = 12; _context9.t0 = _context9["catch"](1); _iterator.e(_context9.t0); case 15: _context9.prev = 15; _iterator.f(); return _context9.finish(15); case 18: case "end": return _context9.stop(); } } }, _callee9, null, [[1, 12, 15, 18]]); })); function storeInSecretStorage(_x11, _x12) { return _storeInSecretStorage.apply(this, arguments); } return storeInSecretStorage; }() /** * Get private keys from secret storage created by some other device. This * also passes the private keys to the app-specific callback. * * @param {string} type The type of key to get. One of "master", * "self_signing", or "user_signing". * @param {SecretStorage} secretStorage The secret store using account data * @return {Uint8Array} The private key */ }, { key: "getFromSecretStorage", value: function () { var _getFromSecretStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(type, secretStorage) { var encodedKey; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return secretStorage.get("m.cross_signing.".concat(type)); case 2: encodedKey = _context10.sent; if (encodedKey) { _context10.next = 5; break; } return _context10.abrupt("return", null); case 5: return _context10.abrupt("return", (0, _olmlib.decodeBase64)(encodedKey)); case 6: case "end": return _context10.stop(); } } }, _callee10); })); function getFromSecretStorage(_x13, _x14) { return _getFromSecretStorage.apply(this, arguments); } return getFromSecretStorage; }() }]); return CrossSigningInfo; }(_events.EventEmitter); exports.CrossSigningInfo = CrossSigningInfo; function deviceToObject(device, userId) { return { algorithms: device.algorithms, keys: device.keys, device_id: device.deviceId, user_id: userId, signatures: device.signatures }; } var CrossSigningLevel = { MASTER: 4, USER_SIGNING: 2, SELF_SIGNING: 1 }; /** * Represents the ways in which we trust a user */ exports.CrossSigningLevel = CrossSigningLevel; var UserTrustLevel = /*#__PURE__*/function () { function UserTrustLevel(crossSigningVerified, crossSigningVerifiedBefore, tofu) { (0, _classCallCheck2["default"])(this, UserTrustLevel); this._crossSigningVerified = crossSigningVerified; this._crossSigningVerifiedBefore = crossSigningVerifiedBefore; this._tofu = tofu; } /** * @returns {bool} true if this user is verified via any means */ (0, _createClass2["default"])(UserTrustLevel, [{ key: "isVerified", value: function isVerified() { return this.isCrossSigningVerified(); } /** * @returns {bool} true if this user is verified via cross signing */ }, { key: "isCrossSigningVerified", value: function isCrossSigningVerified() { return this._crossSigningVerified; } /** * @returns {bool} true if we ever verified this user before (at least for * the history of verifications observed by this device). */ }, { key: "wasCrossSigningVerified", value: function wasCrossSigningVerified() { return this._crossSigningVerifiedBefore; } /** * @returns {bool} true if this user's key is trusted on first use */ }, { key: "isTofu", value: function isTofu() { return this._tofu; } }]); return UserTrustLevel; }(); /** * Represents the ways in which we trust a device */ exports.UserTrustLevel = UserTrustLevel; var DeviceTrustLevel = /*#__PURE__*/function () { function DeviceTrustLevel(crossSigningVerified, tofu, localVerified, trustCrossSignedDevices) { (0, _classCallCheck2["default"])(this, DeviceTrustLevel); this._crossSigningVerified = crossSigningVerified; this._tofu = tofu; this._localVerified = localVerified; this._trustCrossSignedDevices = trustCrossSignedDevices; } (0, _createClass2["default"])(DeviceTrustLevel, [{ key: "isVerified", /** * @returns {bool} true if this device is verified via any means */ value: function isVerified() { return Boolean(this.isLocallyVerified() || this._trustCrossSignedDevices && this.isCrossSigningVerified()); } /** * @returns {bool} true if this device is verified via cross signing */ }, { key: "isCrossSigningVerified", value: function isCrossSigningVerified() { return this._crossSigningVerified; } /** * @returns {bool} true if this device is verified locally */ }, { key: "isLocallyVerified", value: function isLocallyVerified() { return this._localVerified; } /** * @returns {bool} true if this device is trusted from a user's key * that is trusted on first use */ }, { key: "isTofu", value: function isTofu() { return this._tofu; } }], [{ key: "fromUserTrustLevel", value: function fromUserTrustLevel(userTrustLevel, localVerified, trustCrossSignedDevices) { return new DeviceTrustLevel(userTrustLevel._crossSigningVerified, userTrustLevel._tofu, localVerified, trustCrossSignedDevices); } }]); return DeviceTrustLevel; }(); exports.DeviceTrustLevel = DeviceTrustLevel; function createCryptoStoreCacheCallbacks(store, olmdevice) { return { getCrossSigningKeyCache: function () { var _getCrossSigningKeyCache = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(type, _expectedPublicKey) { var key, pickleKey, decrypted; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _context11.next = 2; return new Promise(function (resolve) { return store.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { store.getSecretStorePrivateKey(txn, resolve, type); }); }); case 2: key = _context11.sent; if (!(key && key.ciphertext)) { _context11.next = 11; break; } pickleKey = Buffer.from(olmdevice._pickleKey); _context11.next = 7; return (0, _aes.decryptAES)(key, pickleKey, type); case 7: decrypted = _context11.sent; return _context11.abrupt("return", (0, _olmlib.decodeBase64)(decrypted)); case 11: return _context11.abrupt("return", key); case 12: case "end": return _context11.stop(); } } }, _callee11); })); function getCrossSigningKeyCache(_x15, _x16) { return _getCrossSigningKeyCache.apply(this, arguments); } return getCrossSigningKeyCache; }(), storeCrossSigningKeyCache: function () { var _storeCrossSigningKeyCache = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(type, key) { var pickleKey; return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: if (key instanceof Uint8Array) { _context12.next = 2; break; } throw new Error("storeCrossSigningKeyCache expects Uint8Array, got ".concat(key)); case 2: pickleKey = Buffer.from(olmdevice._pickleKey); _context12.next = 5; return (0, _aes.encryptAES)((0, _olmlib.encodeBase64)(key), pickleKey, type); case 5: key = _context12.sent; return _context12.abrupt("return", store.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { store.storeSecretStorePrivateKey(txn, type, key); })); case 7: case "end": return _context12.stop(); } } }, _callee12); })); function storeCrossSigningKeyCache(_x17, _x18) { return _storeCrossSigningKeyCache.apply(this, arguments); } return storeCrossSigningKeyCache; }() }; } /** * Request cross-signing keys from another device during verification. * * @param {module:base-apis~MatrixBaseApis} baseApis base Matrix API interface * @param {string} userId The user ID being verified * @param {string} deviceId The device ID being verified */ function requestKeysDuringVerification(_x19, _x20, _x21) { return _requestKeysDuringVerification.apply(this, arguments); } function _requestKeysDuringVerification() { _requestKeysDuringVerification = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(baseApis, userId, deviceId) { return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: if (!(baseApis.getUserId() !== userId)) { _context15.next = 2; break; } return _context15.abrupt("return"); case 2: console.log("Cross-signing: Self-verification done; requesting keys"); // This happens asynchronously, and we're not concerned about waiting for // it. We return here in order to test. return _context15.abrupt("return", new Promise(function (resolve, reject) { var client = baseApis; var original = client._crypto._crossSigningInfo; // We already have all of the infrastructure we need to validate and // cache cross-signing keys, so instead of replicating that, here we set // up callbacks that request them from the other device and call // CrossSigningInfo.getCrossSigningKey() to validate/cache var crossSigning = new CrossSigningInfo(original.userId, { getCrossSigningKey: function () { var _getCrossSigningKey2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(type) { var _client$requestSecret, promise, result, decoded; return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: console.debug("Cross-signing: requesting secret", type, deviceId); _client$requestSecret = client.requestSecret("m.cross_signing.".concat(type), [deviceId]), promise = _client$requestSecret.promise; _context13.next = 4; return promise; case 4: result = _context13.sent; decoded = (0, _olmlib.decodeBase64)(result); return _context13.abrupt("return", Uint8Array.from(decoded)); case 7: case "end": return _context13.stop(); } } }, _callee13); })); function getCrossSigningKey(_x22) { return _getCrossSigningKey2.apply(this, arguments); } return getCrossSigningKey; }() }, original._cacheCallbacks); crossSigning.keys = original.keys; // XXX: get all keys out if we get one key out // https://github.com/vector-im/element-web/issues/12604 // then change here to reject on the timeout // Requests can be ignored, so don't wait around forever var timeout = new Promise(function (resolve, reject) { setTimeout(resolve, KEY_REQUEST_TIMEOUT_MS, new Error("Timeout")); }); // also request and cache the key backup key var backupKeyPromise = new Promise( /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(resolve) { var cachedKey, secretReq, base64Key, decodedKey, backupInfo; return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return client._crypto.getSessionBackupPrivateKey(); case 2: cachedKey = _context14.sent; if (cachedKey) { _context14.next = 18; break; } _logger.logger.info("No cached backup key found. Requesting..."); secretReq = client.requestSecret('m.megolm_backup.v1', [deviceId]); _context14.next = 8; return secretReq.promise; case 8: base64Key = _context14.sent; _logger.logger.info("Got key backup key, decoding..."); decodedKey = (0, _olmlib.decodeBase64)(base64Key); _logger.logger.info("Decoded backup key, storing..."); client._crypto.storeSessionBackupPrivateKey(Uint8Array.from(decodedKey)); _logger.logger.info("Backup key stored. Starting backup restore..."); _context14.next = 16; return client.getKeyBackupVersion(); case 16: backupInfo = _context14.sent; // no need to await for this - just let it go in the bg client.restoreKeyBackupWithCache(undefined, undefined, backupInfo).then(function () { _logger.logger.info("Backup restored."); }); case 18: resolve(); case 19: case "end": return _context14.stop(); } } }, _callee14); })); return function (_x23) { return _ref.apply(this, arguments); }; }()); // We call getCrossSigningKey() for its side-effects return Promise.race([Promise.all([crossSigning.getCrossSigningKey("master"), crossSigning.getCrossSigningKey("self_signing"), crossSigning.getCrossSigningKey("user_signing"), backupKeyPromise]), timeout]).then(resolve, reject); })["catch"](function (e) { console.warn("Cross-signing: failure while requesting keys:", e); })); case 4: case "end": return _context15.stop(); } } }, _callee15); })); return _requestKeysDuringVerification.apply(this, arguments); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"../crypto/store/indexeddb-crypto-store":78,"../logger":95,"./aes":67,"./olmlib":75,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"buffer":34,"events":36}],61:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.DeviceList = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _events = require("events"); var _logger = require("../logger"); var _deviceinfo = require("./deviceinfo"); var _CrossSigning = require("./CrossSigning"); var olmlib = _interopRequireWildcard(require("./olmlib")); var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store"); var _utils = require("../utils"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /* State transition diagram for DeviceList._deviceTrackingStatus * * | * stopTrackingDeviceList V * +---------------------> NOT_TRACKED * | | * +<--------------------+ | startTrackingDeviceList * | | V * | +-------------> PENDING_DOWNLOAD <--------------------+-+ * | | ^ | | | * | | restart download | | start download | | invalidateUserDeviceList * | | client failed | | | | * | | | V | | * | +------------ DOWNLOAD_IN_PROGRESS -------------------+ | * | | | | * +<-------------------+ | download successful | * ^ V | * +----------------------- UP_TO_DATE ------------------------+ */ // constants for DeviceList._deviceTrackingStatus var TRACKING_STATUS_NOT_TRACKED = 0; var TRACKING_STATUS_PENDING_DOWNLOAD = 1; var TRACKING_STATUS_DOWNLOAD_IN_PROGRESS = 2; var TRACKING_STATUS_UP_TO_DATE = 3; /** * @alias module:crypto/DeviceList */ var DeviceList = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(DeviceList, _EventEmitter); var _super = _createSuper(DeviceList); function DeviceList(baseApis, cryptoStore, olmDevice) { var _this; (0, _classCallCheck2["default"])(this, DeviceList); _this = _super.call(this); _this._cryptoStore = cryptoStore; // userId -> { // deviceId -> { // [device info] // } // } _this._devices = {}; // userId -> { // [key info] // } _this._crossSigningInfo = {}; // map of identity keys to the user who owns it _this._userByIdentityKey = {}; // which users we are tracking device status for. // userId -> TRACKING_STATUS_* _this._deviceTrackingStatus = {}; // loaded from storage in load() // The 'next_batch' sync token at the point the data was writen, // ie. a token representing the point immediately after the // moment represented by the snapshot in the db. _this._syncToken = null; _this._serialiser = new DeviceListUpdateSerialiser(baseApis, olmDevice, (0, _assertThisInitialized2["default"])(_this)); // userId -> promise _this._keyDownloadsInProgressByUser = {}; // Set whenever changes are made other than setting the sync token _this._dirty = false; // Promise resolved when device data is saved _this._savePromise = null; // Function that resolves the save promise _this._resolveSavePromise = null; // The time the save is scheduled for _this._savePromiseTime = null; // The timer used to delay the save _this._saveTimer = null; // True if we have fetched data from the server or loaded a non-empty // set of device data from the store _this._hasFetched = null; return _this; } /** * Load the device tracking state from storage */ (0, _createClass2["default"])(DeviceList, [{ key: "load", value: function () { var _load = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var _this2 = this; var _i3, _Object$keys3, u; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_DEVICE_DATA], function (txn) { _this2._cryptoStore.getEndToEndDeviceData(txn, function (deviceData) { _this2._hasFetched = Boolean(deviceData && deviceData.devices); _this2._devices = deviceData ? deviceData.devices : {}, _this2._crossSigningInfo = deviceData ? deviceData.crossSigningInfo || {} : {}; _this2._deviceTrackingStatus = deviceData ? deviceData.trackingStatus : {}; _this2._syncToken = deviceData ? deviceData.syncToken : null; _this2._userByIdentityKey = {}; for (var _i = 0, _Object$keys = Object.keys(_this2._devices); _i < _Object$keys.length; _i++) { var user = _Object$keys[_i]; var userDevices = _this2._devices[user]; for (var _i2 = 0, _Object$keys2 = Object.keys(userDevices); _i2 < _Object$keys2.length; _i2++) { var device = _Object$keys2[_i2]; var idKey = userDevices[device].keys['curve25519:' + device]; if (idKey !== undefined) { _this2._userByIdentityKey[idKey] = user; } } } }); }); case 2: for (_i3 = 0, _Object$keys3 = Object.keys(this._deviceTrackingStatus); _i3 < _Object$keys3.length; _i3++) { u = _Object$keys3[_i3]; // if a download was in progress when we got shut down, it isn't any more. if (this._deviceTrackingStatus[u] == TRACKING_STATUS_DOWNLOAD_IN_PROGRESS) { this._deviceTrackingStatus[u] = TRACKING_STATUS_PENDING_DOWNLOAD; } } case 3: case "end": return _context.stop(); } } }, _callee, this); })); function load() { return _load.apply(this, arguments); } return load; }() }, { key: "stop", value: function stop() { if (this._saveTimer !== null) { clearTimeout(this._saveTimer); } } /** * Save the device tracking state to storage, if any changes are * pending other than updating the sync token * * The actual save will be delayed by a short amount of time to * aggregate multiple writes to the database. * * @param {integer} delay Time in ms before which the save actually happens. * By default, the save is delayed for a short period in order to batch * multiple writes, but this behaviour can be disabled by passing 0. * * @return {Promise} true if the data was saved, false if * it was not (eg. because no changes were pending). The promise * will only resolve once the data is saved, so may take some time * to resolve. */ }, { key: "saveIfDirty", value: function () { var _saveIfDirty = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(delay) { var _this3 = this; var targetTime, savePromise, resolveSavePromise; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (this._dirty) { _context2.next = 2; break; } return _context2.abrupt("return", Promise.resolve(false)); case 2: // Delay saves for a bit so we can aggregate multiple saves that happen // in quick succession (eg. when a whole room's devices are marked as known) if (delay === undefined) delay = 500; targetTime = Date.now + delay; if (this._savePromiseTime && targetTime < this._savePromiseTime) { // There's a save scheduled but for after we would like: cancel // it & schedule one for the time we want clearTimeout(this._saveTimer); this._saveTimer = null; this._savePromiseTime = null; // (but keep the save promise since whatever called save before // will still want to know when the save is done) } savePromise = this._savePromise; if (savePromise === null) { savePromise = new Promise(function (resolve, reject) { _this3._resolveSavePromise = resolve; }); this._savePromise = savePromise; } if (this._saveTimer === null) { resolveSavePromise = this._resolveSavePromise; this._savePromiseTime = targetTime; this._saveTimer = setTimeout(function () { _logger.logger.log('Saving device tracking data', _this3._syncToken); // null out savePromise now (after the delay but before the write), // otherwise we could return the existing promise when the save has // actually already happened. _this3._savePromiseTime = null; _this3._saveTimer = null; _this3._savePromise = null; _this3._resolveSavePromise = null; _this3._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_DEVICE_DATA], function (txn) { _this3._cryptoStore.storeEndToEndDeviceData({ devices: _this3._devices, crossSigningInfo: _this3._crossSigningInfo, trackingStatus: _this3._deviceTrackingStatus, syncToken: _this3._syncToken }, txn); }).then(function () { // The device list is considered dirty until the write // completes. _this3._dirty = false; resolveSavePromise(); }, function (err) { _logger.logger.error('Failed to save device tracking data', _this3._syncToken); _logger.logger.error(err); }); }, delay); } return _context2.abrupt("return", savePromise); case 9: case "end": return _context2.stop(); } } }, _callee2, this); })); function saveIfDirty(_x) { return _saveIfDirty.apply(this, arguments); } return saveIfDirty; }() /** * Gets the sync token last set with setSyncToken * * @return {string} The sync token */ }, { key: "getSyncToken", value: function getSyncToken() { return this._syncToken; } /** * Sets the sync token that the app will pass as the 'since' to the /sync * endpoint next time it syncs. * The sync token must always be set after any changes made as a result of * data in that sync since setting the sync token to a newer one will mean * those changed will not be synced from the server if a new client starts * up with that data. * * @param {string} st The sync token */ }, { key: "setSyncToken", value: function setSyncToken(st) { this._syncToken = st; } /** * Ensures up to date keys for a list of users are stored in the session store, * downloading and storing them if they're not (or if forceDownload is * true). * @param {Array} userIds The users to fetch. * @param {bool} forceDownload Always download the keys even if cached. * * @return {Promise} A promise which resolves to a map userId->deviceId->{@link * module:crypto/deviceinfo|DeviceInfo}. */ }, { key: "downloadKeys", value: function downloadKeys(userIds, forceDownload) { var _this4 = this; var usersToDownload = []; var promises = []; userIds.forEach(function (u) { var trackingStatus = _this4._deviceTrackingStatus[u]; if (_this4._keyDownloadsInProgressByUser[u]) { // already a key download in progress/queued for this user; its results // will be good enough for us. _logger.logger.log("downloadKeys: already have a download in progress for " + "".concat(u, ": awaiting its result")); promises.push(_this4._keyDownloadsInProgressByUser[u]); } else if (forceDownload || trackingStatus != TRACKING_STATUS_UP_TO_DATE) { usersToDownload.push(u); } }); if (usersToDownload.length != 0) { _logger.logger.log("downloadKeys: downloading for", usersToDownload); var downloadPromise = this._doKeyDownload(usersToDownload); promises.push(downloadPromise); } if (promises.length === 0) { _logger.logger.log("downloadKeys: already have all necessary keys"); } return Promise.all(promises).then(function () { return _this4._getDevicesFromStore(userIds); }); } /** * Get the stored device keys for a list of user ids * * @param {string[]} userIds the list of users to list keys for. * * @return {Object} userId->deviceId->{@link module:crypto/deviceinfo|DeviceInfo}. */ }, { key: "_getDevicesFromStore", value: function _getDevicesFromStore(userIds) { var stored = {}; var self = this; userIds.map(function (u) { stored[u] = {}; var devices = self.getStoredDevicesForUser(u) || []; devices.map(function (dev) { stored[u][dev.deviceId] = dev; }); }); return stored; } /** * Returns a list of all user IDs the DeviceList knows about * * @return {array} All known user IDs */ }, { key: "getKnownUserIds", value: function getKnownUserIds() { return Object.keys(this._devices); } /** * Get the stored device keys for a user id * * @param {string} userId the user to list keys for. * * @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't * managed to get a list of devices for this user yet. */ }, { key: "getStoredDevicesForUser", value: function getStoredDevicesForUser(userId) { var devs = this._devices[userId]; if (!devs) { return null; } var res = []; for (var deviceId in devs) { if (devs.hasOwnProperty(deviceId)) { res.push(_deviceinfo.DeviceInfo.fromStorage(devs[deviceId], deviceId)); } } return res; } /** * Get the stored device data for a user, in raw object form * * @param {string} userId the user to get data for * * @return {Object} deviceId->{object} devices, or undefined if * there is no data for this user. */ }, { key: "getRawStoredDevicesForUser", value: function getRawStoredDevicesForUser(userId) { return this._devices[userId]; } }, { key: "getStoredCrossSigningForUser", value: function getStoredCrossSigningForUser(userId) { if (!this._crossSigningInfo[userId]) return null; return _CrossSigning.CrossSigningInfo.fromStorage(this._crossSigningInfo[userId], userId); } }, { key: "storeCrossSigningForUser", value: function storeCrossSigningForUser(userId, info) { this._crossSigningInfo[userId] = info; this._dirty = true; } /** * Get the stored keys for a single device * * @param {string} userId * @param {string} deviceId * * @return {module:crypto/deviceinfo?} device, or undefined * if we don't know about this device */ }, { key: "getStoredDevice", value: function getStoredDevice(userId, deviceId) { var devs = this._devices[userId]; if (!devs || !devs[deviceId]) { return undefined; } return _deviceinfo.DeviceInfo.fromStorage(devs[deviceId], deviceId); } /** * Get a user ID by one of their device's curve25519 identity key * * @param {string} algorithm encryption algorithm * @param {string} senderKey curve25519 key to match * * @return {string} user ID */ }, { key: "getUserByIdentityKey", value: function getUserByIdentityKey(algorithm, senderKey) { if (algorithm !== olmlib.OLM_ALGORITHM && algorithm !== olmlib.MEGOLM_ALGORITHM) { // we only deal in olm keys return null; } return this._userByIdentityKey[senderKey]; } /** * Find a device by curve25519 identity key * * @param {string} algorithm encryption algorithm * @param {string} senderKey curve25519 key to match * * @return {module:crypto/deviceinfo?} */ }, { key: "getDeviceByIdentityKey", value: function getDeviceByIdentityKey(algorithm, senderKey) { var userId = this.getUserByIdentityKey(algorithm, senderKey); if (!userId) { return null; } var devices = this._devices[userId]; if (!devices) { return null; } for (var deviceId in devices) { if (!devices.hasOwnProperty(deviceId)) { continue; } var device = devices[deviceId]; for (var keyId in device.keys) { if (!device.keys.hasOwnProperty(keyId)) { continue; } if (keyId.indexOf("curve25519:") !== 0) { continue; } var deviceKey = device.keys[keyId]; if (deviceKey == senderKey) { return _deviceinfo.DeviceInfo.fromStorage(device, deviceId); } } } // doesn't match a known device return null; } /** * Replaces the list of devices for a user with the given device list * * @param {string} u The user ID * @param {Object} devs New device info for user */ }, { key: "storeDevicesForUser", value: function storeDevicesForUser(u, devs) { // remove previous devices from _userByIdentityKey if (this._devices[u] !== undefined) { for (var _i4 = 0, _Object$entries = Object.entries(this._devices[u]); _i4 < _Object$entries.length; _i4++) { var _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i4], 2), deviceId = _Object$entries$_i[0], dev = _Object$entries$_i[1]; var identityKey = dev.keys['curve25519:' + deviceId]; delete this._userByIdentityKey[identityKey]; } } this._devices[u] = devs; // add new ones for (var _i5 = 0, _Object$entries2 = Object.entries(devs); _i5 < _Object$entries2.length; _i5++) { var _Object$entries2$_i = (0, _slicedToArray2["default"])(_Object$entries2[_i5], 2), _deviceId = _Object$entries2$_i[0], _dev = _Object$entries2$_i[1]; var _identityKey = _dev.keys['curve25519:' + _deviceId]; this._userByIdentityKey[_identityKey] = u; } this._dirty = true; } /** * flag the given user for device-list tracking, if they are not already. * * This will mean that a subsequent call to refreshOutdatedDeviceLists() * will download the device list for the user, and that subsequent calls to * invalidateUserDeviceList will trigger more updates. * * @param {String} userId */ }, { key: "startTrackingDeviceList", value: function startTrackingDeviceList(userId) { // sanity-check the userId. This is mostly paranoia, but if synapse // can't parse the userId we give it as an mxid, it 500s the whole // request and we can never update the device lists again (because // the broken userId is always 'invalid' and always included in any // refresh request). // By checking it is at least a string, we can eliminate a class of // silly errors. if (typeof userId !== 'string') { throw new Error('userId must be a string; was ' + userId); } if (!this._deviceTrackingStatus[userId]) { _logger.logger.log('Now tracking device list for ' + userId); this._deviceTrackingStatus[userId] = TRACKING_STATUS_PENDING_DOWNLOAD; // we don't yet persist the tracking status, since there may be a lot // of calls; we save all data together once the sync is done this._dirty = true; } } /** * Mark the given user as no longer being tracked for device-list updates. * * This won't affect any in-progress downloads, which will still go on to * complete; it will just mean that we don't think that we have an up-to-date * list for future calls to downloadKeys. * * @param {String} userId */ }, { key: "stopTrackingDeviceList", value: function stopTrackingDeviceList(userId) { if (this._deviceTrackingStatus[userId]) { _logger.logger.log('No longer tracking device list for ' + userId); this._deviceTrackingStatus[userId] = TRACKING_STATUS_NOT_TRACKED; // we don't yet persist the tracking status, since there may be a lot // of calls; we save all data together once the sync is done this._dirty = true; } } /** * Set all users we're currently tracking to untracked * * This will flag each user whose devices we are tracking as in need of an * update. */ }, { key: "stopTrackingAllDeviceLists", value: function stopTrackingAllDeviceLists() { for (var _i6 = 0, _Object$keys4 = Object.keys(this._deviceTrackingStatus); _i6 < _Object$keys4.length; _i6++) { var userId = _Object$keys4[_i6]; this._deviceTrackingStatus[userId] = TRACKING_STATUS_NOT_TRACKED; } this._dirty = true; } /** * Mark the cached device list for the given user outdated. * * If we are not tracking this user's devices, we'll do nothing. Otherwise * we flag the user as needing an update. * * This doesn't actually set off an update, so that several users can be * batched together. Call refreshOutdatedDeviceLists() for that. * * @param {String} userId */ }, { key: "invalidateUserDeviceList", value: function invalidateUserDeviceList(userId) { if (this._deviceTrackingStatus[userId]) { _logger.logger.log("Marking device list outdated for", userId); this._deviceTrackingStatus[userId] = TRACKING_STATUS_PENDING_DOWNLOAD; // we don't yet persist the tracking status, since there may be a lot // of calls; we save all data together once the sync is done this._dirty = true; } } /** * If we have users who have outdated device lists, start key downloads for them * * @returns {Promise} which completes when the download completes; normally there * is no need to wait for this (it's mostly for the unit tests). */ }, { key: "refreshOutdatedDeviceLists", value: function refreshOutdatedDeviceLists() { this.saveIfDirty(); var usersToDownload = []; for (var _i7 = 0, _Object$keys5 = Object.keys(this._deviceTrackingStatus); _i7 < _Object$keys5.length; _i7++) { var userId = _Object$keys5[_i7]; var stat = this._deviceTrackingStatus[userId]; if (stat == TRACKING_STATUS_PENDING_DOWNLOAD) { usersToDownload.push(userId); } } return this._doKeyDownload(usersToDownload); } /** * Set the stored device data for a user, in raw object form * Used only by internal class DeviceListUpdateSerialiser * * @param {string} userId the user to get data for * * @param {Object} devices deviceId->{object} the new devices */ }, { key: "_setRawStoredDevicesForUser", value: function _setRawStoredDevicesForUser(userId, devices) { // remove old devices from _userByIdentityKey if (this._devices[userId] !== undefined) { for (var _i8 = 0, _Object$entries3 = Object.entries(this._devices[userId]); _i8 < _Object$entries3.length; _i8++) { var _Object$entries3$_i = (0, _slicedToArray2["default"])(_Object$entries3[_i8], 2), deviceId = _Object$entries3$_i[0], dev = _Object$entries3$_i[1]; var identityKey = dev.keys['curve25519:' + deviceId]; delete this._userByIdentityKey[identityKey]; } } this._devices[userId] = devices; // add new devices into _userByIdentityKey for (var _i9 = 0, _Object$entries4 = Object.entries(devices); _i9 < _Object$entries4.length; _i9++) { var _Object$entries4$_i = (0, _slicedToArray2["default"])(_Object$entries4[_i9], 2), _deviceId2 = _Object$entries4$_i[0], _dev2 = _Object$entries4$_i[1]; var _identityKey2 = _dev2.keys['curve25519:' + _deviceId2]; this._userByIdentityKey[_identityKey2] = userId; } } }, { key: "setRawStoredCrossSigningForUser", value: function setRawStoredCrossSigningForUser(userId, info) { this._crossSigningInfo[userId] = info; } /** * Fire off download update requests for the given users, and update the * device list tracking status for them, and the * _keyDownloadsInProgressByUser map for them. * * @param {String[]} users list of userIds * * @return {Promise} resolves when all the users listed have * been updated. rejects if there was a problem updating any of the * users. */ }, { key: "_doKeyDownload", value: function _doKeyDownload(users) { var _this5 = this; if (users.length === 0) { // nothing to do return Promise.resolve(); } var prom = this._serialiser.updateDevicesForUsers(users, this._syncToken).then(function () { finished(true); }, function (e) { _logger.logger.error('Error downloading keys for ' + users + ":", e); finished(false); throw e; }); users.forEach(function (u) { _this5._keyDownloadsInProgressByUser[u] = prom; var stat = _this5._deviceTrackingStatus[u]; if (stat == TRACKING_STATUS_PENDING_DOWNLOAD) { _this5._deviceTrackingStatus[u] = TRACKING_STATUS_DOWNLOAD_IN_PROGRESS; } }); var finished = function finished(success) { _this5.emit("crypto.willUpdateDevices", users, !_this5._hasFetched); users.forEach(function (u) { _this5._dirty = true; // we may have queued up another download request for this user // since we started this request. If that happens, we should // ignore the completion of the first one. if (_this5._keyDownloadsInProgressByUser[u] !== prom) { _logger.logger.log('Another update in the queue for', u, '- not marking up-to-date'); return; } delete _this5._keyDownloadsInProgressByUser[u]; var stat = _this5._deviceTrackingStatus[u]; if (stat == TRACKING_STATUS_DOWNLOAD_IN_PROGRESS) { if (success) { // we didn't get any new invalidations since this download started: // this user's device list is now up to date. _this5._deviceTrackingStatus[u] = TRACKING_STATUS_UP_TO_DATE; _logger.logger.log("Device list for", u, "now up to date"); } else { _this5._deviceTrackingStatus[u] = TRACKING_STATUS_PENDING_DOWNLOAD; } } }); _this5.saveIfDirty(); _this5.emit("crypto.devicesUpdated", users, !_this5._hasFetched); _this5._hasFetched = true; }; return prom; } }]); return DeviceList; }(_events.EventEmitter); /** * Serialises updates to device lists * * Ensures that results from /keys/query are not overwritten if a second call * completes *before* an earlier one. * * It currently does this by ensuring only one call to /keys/query happens at a * time (and queuing other requests up). */ exports.DeviceList = DeviceList; var DeviceListUpdateSerialiser = /*#__PURE__*/function () { /* * @param {object} baseApis Base API object * @param {object} olmDevice The Olm Device * @param {object} deviceList The device list object */ function DeviceListUpdateSerialiser(baseApis, olmDevice, deviceList) { (0, _classCallCheck2["default"])(this, DeviceListUpdateSerialiser); this._baseApis = baseApis; this._olmDevice = olmDevice; this._deviceList = deviceList; // the device list to be updated this._downloadInProgress = false; // users which are queued for download // userId -> true this._keyDownloadsQueuedByUser = {}; // deferred which is resolved when the queued users are downloaded. // // non-null indicates that we have users queued for download. this._queuedQueryDeferred = null; this._syncToken = null; // The sync token we send with the requests } /** * Make a key query request for the given users * * @param {String[]} users list of user ids * * @param {String} syncToken sync token to pass in the query request, to * help the HS give the most recent results * * @return {Promise} resolves when all the users listed have * been updated. rejects if there was a problem updating any of the * users. */ (0, _createClass2["default"])(DeviceListUpdateSerialiser, [{ key: "updateDevicesForUsers", value: function updateDevicesForUsers(users, syncToken) { var _this6 = this; users.forEach(function (u) { _this6._keyDownloadsQueuedByUser[u] = true; }); if (!this._queuedQueryDeferred) { this._queuedQueryDeferred = (0, _utils.defer)(); } // We always take the new sync token and just use the latest one we've // been given, since it just needs to be at least as recent as the // sync response the device invalidation message arrived in this._syncToken = syncToken; if (this._downloadInProgress) { // just queue up these users _logger.logger.log('Queued key download for', users); return this._queuedQueryDeferred.promise; } // start a new download. return this._doQueuedQueries(); } }, { key: "_doQueuedQueries", value: function _doQueuedQueries() { var _this7 = this; if (this._downloadInProgress) { throw new Error("DeviceListUpdateSerialiser._doQueuedQueries called with request active"); } var downloadUsers = Object.keys(this._keyDownloadsQueuedByUser); this._keyDownloadsQueuedByUser = {}; var deferred = this._queuedQueryDeferred; this._queuedQueryDeferred = null; _logger.logger.log('Starting key download for', downloadUsers); this._downloadInProgress = true; var opts = {}; if (this._syncToken) { opts.token = this._syncToken; } this._baseApis.downloadKeysForUsers(downloadUsers, opts).then( /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(res) { var dk, masterKeys, ssks, usks, _iterator, _step, userId; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: dk = res.device_keys || {}; masterKeys = res.master_keys || {}; ssks = res.self_signing_keys || {}; usks = res.user_signing_keys || {}; // yield to other things that want to execute in between users, to // avoid wedging the CPU // (https://github.com/vector-im/element-web/issues/3158) // // of course we ought to do this in a web worker or similar, but // this serves as an easy solution for now. _iterator = _createForOfIteratorHelper(downloadUsers); _context3.prev = 5; _iterator.s(); case 7: if ((_step = _iterator.n()).done) { _context3.next = 21; break; } userId = _step.value; _context3.next = 11; return (0, _utils.sleep)(5); case 11: _context3.prev = 11; _context3.next = 14; return _this7._processQueryResponseForUser(userId, dk[userId], { master: masterKeys[userId], self_signing: ssks[userId], user_signing: usks[userId] }); case 14: _context3.next = 19; break; case 16: _context3.prev = 16; _context3.t0 = _context3["catch"](11); // log the error but continue, so that one bad key // doesn't kill the whole process _logger.logger.error("Error processing keys for ".concat(userId, ":"), _context3.t0); case 19: _context3.next = 7; break; case 21: _context3.next = 26; break; case 23: _context3.prev = 23; _context3.t1 = _context3["catch"](5); _iterator.e(_context3.t1); case 26: _context3.prev = 26; _iterator.f(); return _context3.finish(26); case 29: case "end": return _context3.stop(); } } }, _callee3, null, [[5, 23, 26, 29], [11, 16]]); })); return function (_x2) { return _ref.apply(this, arguments); }; }()).then(function () { _logger.logger.log('Completed key download for ' + downloadUsers); _this7._downloadInProgress = false; deferred.resolve(); // if we have queued users, fire off another request. if (_this7._queuedQueryDeferred) { _this7._doQueuedQueries(); } }, function (e) { _logger.logger.warn('Error downloading keys for ' + downloadUsers + ':', e); _this7._downloadInProgress = false; deferred.reject(e); }); return deferred.promise; } }, { key: "_processQueryResponseForUser", value: function () { var _processQueryResponseForUser2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(userId, dkResponse, crossSigningResponse) { var userStore, devs, storage, crossSigning; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _logger.logger.log('got device keys for ' + userId + ':', dkResponse); _logger.logger.log('got cross-signing keys for ' + userId + ':', crossSigningResponse); // map from deviceid -> deviceinfo for this user userStore = {}; devs = this._deviceList.getRawStoredDevicesForUser(userId); if (devs) { Object.keys(devs).forEach(function (deviceId) { var d = _deviceinfo.DeviceInfo.fromStorage(devs[deviceId], deviceId); userStore[deviceId] = d; }); } _context4.next = 7; return _updateStoredDeviceKeysForUser(this._olmDevice, userId, userStore, dkResponse || {}); case 7: // put the updates into the object that will be returned as our results storage = {}; Object.keys(userStore).forEach(function (deviceId) { storage[deviceId] = userStore[deviceId].toStorage(); }); this._deviceList._setRawStoredDevicesForUser(userId, storage); // FIXME: should we be ignoring empty cross-signing responses, or // should we be dropping the keys? if (crossSigningResponse && (crossSigningResponse.master || crossSigningResponse.self_signing || crossSigningResponse.user_signing)) { crossSigning = this._deviceList.getStoredCrossSigningForUser(userId) || new _CrossSigning.CrossSigningInfo(userId); crossSigning.setKeys(crossSigningResponse); this._deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage()); // NB. Unlike most events in the js-sdk, this one is internal to the // js-sdk and is not re-emitted this._deviceList.emit('userCrossSigningUpdated', userId); } case 11: case "end": return _context4.stop(); } } }, _callee4, this); })); function _processQueryResponseForUser(_x3, _x4, _x5) { return _processQueryResponseForUser2.apply(this, arguments); } return _processQueryResponseForUser; }() }]); return DeviceListUpdateSerialiser; }(); function _updateStoredDeviceKeysForUser(_x6, _x7, _x8, _x9) { return _updateStoredDeviceKeysForUser2.apply(this, arguments); } /* * Process a device in a /query response, and add it to the userStore * * returns (a promise for) true if a change was made, else false */ function _updateStoredDeviceKeysForUser2() { _updateStoredDeviceKeysForUser2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_olmDevice, userId, userStore, userResult) { var updated, deviceId, _deviceId3, deviceResult; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: updated = false; // remove any devices in the store which aren't in the response _context5.t0 = _regenerator["default"].keys(userStore); case 2: if ((_context5.t1 = _context5.t0()).done) { _context5.next = 9; break; } deviceId = _context5.t1.value; if (userStore.hasOwnProperty(deviceId)) { _context5.next = 6; break; } return _context5.abrupt("continue", 2); case 6: if (!(deviceId in userResult)) { _logger.logger.log("Device " + userId + ":" + deviceId + " has been removed"); delete userStore[deviceId]; updated = true; } _context5.next = 2; break; case 9: _context5.t2 = _regenerator["default"].keys(userResult); case 10: if ((_context5.t3 = _context5.t2()).done) { _context5.next = 27; break; } _deviceId3 = _context5.t3.value; if (userResult.hasOwnProperty(_deviceId3)) { _context5.next = 14; break; } return _context5.abrupt("continue", 10); case 14: deviceResult = userResult[_deviceId3]; // check that the user_id and device_id in the response object are // correct if (!(deviceResult.user_id !== userId)) { _context5.next = 18; break; } _logger.logger.warn("Mismatched user_id " + deviceResult.user_id + " in keys from " + userId + ":" + _deviceId3); return _context5.abrupt("continue", 10); case 18: if (!(deviceResult.device_id !== _deviceId3)) { _context5.next = 21; break; } _logger.logger.warn("Mismatched device_id " + deviceResult.device_id + " in keys from " + userId + ":" + _deviceId3); return _context5.abrupt("continue", 10); case 21: _context5.next = 23; return _storeDeviceKeys(_olmDevice, userStore, deviceResult); case 23: if (!_context5.sent) { _context5.next = 25; break; } updated = true; case 25: _context5.next = 10; break; case 27: return _context5.abrupt("return", updated); case 28: case "end": return _context5.stop(); } } }, _callee5); })); return _updateStoredDeviceKeysForUser2.apply(this, arguments); } function _storeDeviceKeys(_x10, _x11, _x12) { return _storeDeviceKeys2.apply(this, arguments); } function _storeDeviceKeys2() { _storeDeviceKeys2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(_olmDevice, userStore, deviceResult) { var deviceId, userId, signKeyId, signKey, unsigned, signatures, deviceStore; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (deviceResult.keys) { _context6.next = 2; break; } return _context6.abrupt("return", false); case 2: deviceId = deviceResult.device_id; userId = deviceResult.user_id; signKeyId = "ed25519:" + deviceId; signKey = deviceResult.keys[signKeyId]; if (signKey) { _context6.next = 9; break; } _logger.logger.warn("Device " + userId + ":" + deviceId + " has no ed25519 key"); return _context6.abrupt("return", false); case 9: unsigned = deviceResult.unsigned || {}; signatures = deviceResult.signatures || {}; _context6.prev = 11; _context6.next = 14; return olmlib.verifySignature(_olmDevice, deviceResult, userId, deviceId, signKey); case 14: _context6.next = 20; break; case 16: _context6.prev = 16; _context6.t0 = _context6["catch"](11); _logger.logger.warn("Unable to verify signature on device " + userId + ":" + deviceId + ":" + _context6.t0); return _context6.abrupt("return", false); case 20: if (!(deviceId in userStore)) { _context6.next = 27; break; } // already have this device. deviceStore = userStore[deviceId]; if (!(deviceStore.getFingerprint() != signKey)) { _context6.next = 25; break; } // this should only happen if the list has been MITMed; we are // best off sticking with the original keys. // // Should we warn the user about it somehow? _logger.logger.warn("Ed25519 key for device " + userId + ":" + deviceId + " has changed"); return _context6.abrupt("return", false); case 25: _context6.next = 28; break; case 27: userStore[deviceId] = deviceStore = new _deviceinfo.DeviceInfo(deviceId); case 28: deviceStore.keys = deviceResult.keys || {}; deviceStore.algorithms = deviceResult.algorithms || []; deviceStore.unsigned = unsigned; deviceStore.signatures = signatures; return _context6.abrupt("return", true); case 33: case "end": return _context6.stop(); } } }, _callee6, null, [[11, 16]]); })); return _storeDeviceKeys2.apply(this, arguments); } },{"../logger":95,"../utils":123,"./CrossSigning":60,"./deviceinfo":72,"./olmlib":75,"./store/indexeddb-crypto-store":78,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"events":36}],62:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.EncryptionSetupOperation = exports.EncryptionSetupBuilder = void 0; var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _logger = require("../logger"); var _event = require("../models/event"); var _events = require("events"); var _CrossSigning = require("./CrossSigning"); var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store"); var _httpApi = require("../http-api"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * Builds an EncryptionSetupOperation by calling any of the add.. methods. * Once done, `buildOperation()` can be called which allows to apply to operation. * * This is used as a helper by Crypto to keep track of all the network requests * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future) * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them * more than once. */ var EncryptionSetupBuilder = /*#__PURE__*/function () { /** * @param {Object.} accountData pre-existing account data, will only be read, not written. * @param {CryptoCallbacks} delegateCryptoCallbacks crypto callbacks to delegate to if the key isn't in cache yet */ function EncryptionSetupBuilder(accountData, delegateCryptoCallbacks) { (0, _classCallCheck2["default"])(this, EncryptionSetupBuilder); this.accountDataClientAdapter = new AccountDataClientAdapter(accountData); this.crossSigningCallbacks = new CrossSigningCallbacks(); this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks); this._crossSigningKeys = null; this._keySignatures = null; this._keyBackupInfo = null; } /** * Adds new cross-signing public keys * * @param {function} authUpload Function called to await an interactive auth * flow when uploading device signing keys. * Args: * {function} A function that makes the request requiring auth. Receives * the auth data as an object. Can be called multiple times, first with * an empty authDict, to obtain the flows. * @param {Object} keys the new keys */ (0, _createClass2["default"])(EncryptionSetupBuilder, [{ key: "addCrossSigningKeys", value: function addCrossSigningKeys(authUpload, keys) { this._crossSigningKeys = { authUpload: authUpload, keys: keys }; } /** * Adds the key backup info to be updated on the server * * Used either to create a new key backup, or add signatures * from the new MSK. * * @param {Object} keyBackupInfo as received from/sent to the server */ }, { key: "addSessionBackup", value: function addSessionBackup(keyBackupInfo) { this._keyBackupInfo = keyBackupInfo; } /** * Adds the session backup private key to be updated in the local cache * * Used after fixing the format of the key * * @param {Uint8Array} privateKey */ }, { key: "addSessionBackupPrivateKeyToCache", value: function addSessionBackupPrivateKeyToCache(privateKey) { this._sessionBackupPrivateKey = privateKey; } /** * Add signatures from a given user and device/x-sign key * Used to sign the new cross-signing key with the device key * * @param {String} userId * @param {String} deviceId * @param {String} signature */ }, { key: "addKeySignature", value: function addKeySignature(userId, deviceId, signature) { if (!this._keySignatures) { this._keySignatures = {}; } var userSignatures = this._keySignatures[userId] || {}; this._keySignatures[userId] = userSignatures; userSignatures[deviceId] = signature; } /** * @param {String} type * @param {Object} content * @return {Promise} */ }, { key: "setAccountData", value: function setAccountData(type, content) { return this.accountDataClientAdapter.setAccountData(type, content); } /** * builds the operation containing all the parts that have been added to the builder * @return {EncryptionSetupOperation} */ }, { key: "buildOperation", value: function buildOperation() { var accountData = this.accountDataClientAdapter._values; return new EncryptionSetupOperation(accountData, this._crossSigningKeys, this._keyBackupInfo, this._keySignatures); } /** * Stores the created keys locally. * * This does not yet store the operation in a way that it can be restored, * but that is the idea in the future. * * @param {Crypto} crypto * @return {Promise} */ }, { key: "persist", value: function () { var _persist = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(crypto) { var _this = this; var cacheCallbacks, _i, _arr, type, privateKey; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!this._crossSigningKeys) { _context.next = 14; break; } cacheCallbacks = (0, _CrossSigning.createCryptoStoreCacheCallbacks)(crypto._cryptoStore, crypto._olmDevice); _i = 0, _arr = ["master", "self_signing", "user_signing"]; case 3: if (!(_i < _arr.length)) { _context.next = 12; break; } type = _arr[_i]; _logger.logger.log("Cache ".concat(type, " cross-signing private key locally")); privateKey = this.crossSigningCallbacks.privateKeys.get(type); _context.next = 9; return cacheCallbacks.storeCrossSigningKeyCache(type, privateKey); case 9: _i++; _context.next = 3; break; case 12: _context.next = 14; return crypto._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { crypto._cryptoStore.storeCrossSigningKeys(txn, _this._crossSigningKeys.keys); }); case 14: if (!this._sessionBackupPrivateKey) { _context.next = 17; break; } _context.next = 17; return crypto.storeSessionBackupPrivateKey(this._sessionBackupPrivateKey); case 17: case "end": return _context.stop(); } } }, _callee, this); })); function persist(_x) { return _persist.apply(this, arguments); } return persist; }() }]); return EncryptionSetupBuilder; }(); /** * Can be created from EncryptionSetupBuilder, or * (in a follow-up PR, not implemented yet) restored from storage, to retry. * * It does not have knowledge of any private keys, unlike the builder. */ exports.EncryptionSetupBuilder = EncryptionSetupBuilder; var EncryptionSetupOperation = /*#__PURE__*/function () { /** * @param {Map} accountData * @param {Object} crossSigningKeys * @param {Object} keyBackupInfo * @param {Object} keySignatures */ function EncryptionSetupOperation(accountData, crossSigningKeys, keyBackupInfo, keySignatures) { (0, _classCallCheck2["default"])(this, EncryptionSetupOperation); this._accountData = accountData; this._crossSigningKeys = crossSigningKeys; this._keyBackupInfo = keyBackupInfo; this._keySignatures = keySignatures; } /** * Runs the (remaining part of, in the future) operation by sending requests to the server. * @param {Crypto} crypto */ (0, _createClass2["default"])(EncryptionSetupOperation, [{ key: "apply", value: function () { var _apply = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(crypto) { var baseApis, keys, _i2, _Object$entries, _Object$entries$_i, name, key, _iterator, _step, _step$value, type, content; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: baseApis = crypto._baseApis; // upload cross-signing keys if (!this._crossSigningKeys) { _context2.next = 7; break; } keys = {}; for (_i2 = 0, _Object$entries = Object.entries(this._crossSigningKeys.keys); _i2 < _Object$entries.length; _i2++) { _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i2], 2), name = _Object$entries$_i[0], key = _Object$entries$_i[1]; keys[name + "_key"] = key; } // We must only call `uploadDeviceSigningKeys` from inside this auth // helper to ensure we properly handle auth errors. _context2.next = 6; return this._crossSigningKeys.authUpload(function (authDict) { return baseApis.uploadDeviceSigningKeys(authDict, keys); }); case 6: // pass the new keys to the main instance of our own CrossSigningInfo. crypto._crossSigningInfo.setKeys(this._crossSigningKeys.keys); case 7: if (!this._accountData) { _context2.next = 25; break; } _iterator = _createForOfIteratorHelper(this._accountData); _context2.prev = 9; _iterator.s(); case 11: if ((_step = _iterator.n()).done) { _context2.next = 17; break; } _step$value = (0, _slicedToArray2["default"])(_step.value, 2), type = _step$value[0], content = _step$value[1]; _context2.next = 15; return baseApis.setAccountData(type, content); case 15: _context2.next = 11; break; case 17: _context2.next = 22; break; case 19: _context2.prev = 19; _context2.t0 = _context2["catch"](9); _iterator.e(_context2.t0); case 22: _context2.prev = 22; _iterator.f(); return _context2.finish(22); case 25: if (!this._keySignatures) { _context2.next = 28; break; } _context2.next = 28; return baseApis.uploadKeySignatures(this._keySignatures); case 28: if (!this._keyBackupInfo) { _context2.next = 36; break; } if (!this._keyBackupInfo.version) { _context2.next = 34; break; } _context2.next = 32; return baseApis._http.authedRequest(undefined, "PUT", "/room_keys/version/" + this._keyBackupInfo.version, undefined, { algorithm: this._keyBackupInfo.algorithm, auth_data: this._keyBackupInfo.auth_data }, { prefix: _httpApi.PREFIX_UNSTABLE }); case 32: _context2.next = 36; break; case 34: _context2.next = 36; return baseApis._http.authedRequest(undefined, "POST", "/room_keys/version", undefined, this._keyBackupInfo, { prefix: _httpApi.PREFIX_UNSTABLE }); case 36: case "end": return _context2.stop(); } } }, _callee2, this, [[9, 19, 22, 25]]); })); function apply(_x2) { return _apply.apply(this, arguments); } return apply; }() }]); return EncryptionSetupOperation; }(); /** * Catches account data set by SecretStorage during bootstrapping by * implementing the methods related to account data in MatrixClient */ exports.EncryptionSetupOperation = EncryptionSetupOperation; var AccountDataClientAdapter = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(AccountDataClientAdapter, _EventEmitter); var _super = _createSuper(AccountDataClientAdapter); /** * @param {Object.} accountData existing account data */ function AccountDataClientAdapter(accountData) { var _this2; (0, _classCallCheck2["default"])(this, AccountDataClientAdapter); _this2 = _super.call(this); _this2._existingValues = accountData; _this2._values = new Map(); return _this2; } /** * @param {String} type * @return {Promise} the content of the account data */ (0, _createClass2["default"])(AccountDataClientAdapter, [{ key: "getAccountDataFromServer", value: function getAccountDataFromServer(type) { return Promise.resolve(this.getAccountData(type)); } /** * @param {String} type * @return {Object} the content of the account data */ }, { key: "getAccountData", value: function getAccountData(type) { var modifiedValue = this._values.get(type); if (modifiedValue) { return modifiedValue; } var existingValue = this._existingValues[type]; if (existingValue) { return existingValue.getContent(); } return null; } /** * @param {String} type * @param {Object} content * @return {Promise} */ }, { key: "setAccountData", value: function setAccountData(type, content) { var _this3 = this; var lastEvent = this._values.get(type); this._values.set(type, content); // ensure accountData is emitted on the next tick, // as SecretStorage listens for it while calling this method // and it seems to rely on this. return Promise.resolve().then(function () { var event = new _event.MatrixEvent({ type: type, content: content }); _this3.emit("accountData", event, lastEvent); }); } }]); return AccountDataClientAdapter; }(_events.EventEmitter); /** * Catches the private cross-signing keys set during bootstrapping * by both cache callbacks (see createCryptoStoreCacheCallbacks) as non-cache callbacks. * See CrossSigningInfo constructor */ var CrossSigningCallbacks = /*#__PURE__*/function () { function CrossSigningCallbacks() { (0, _classCallCheck2["default"])(this, CrossSigningCallbacks); this.privateKeys = new Map(); } // cache callbacks (0, _createClass2["default"])(CrossSigningCallbacks, [{ key: "getCrossSigningKeyCache", value: function getCrossSigningKeyCache(type, expectedPublicKey) { return this.getCrossSigningKey(type, expectedPublicKey); } }, { key: "storeCrossSigningKeyCache", value: function storeCrossSigningKeyCache(type, key) { this.privateKeys.set(type, key); return Promise.resolve(); } // non-cache callbacks }, { key: "getCrossSigningKey", value: function getCrossSigningKey(type, _expectedPubkey) { return Promise.resolve(this.privateKeys.get(type)); } }, { key: "saveCrossSigningKeys", value: function saveCrossSigningKeys(privateKeys) { for (var _i3 = 0, _Object$entries2 = Object.entries(privateKeys); _i3 < _Object$entries2.length; _i3++) { var _Object$entries2$_i = (0, _slicedToArray2["default"])(_Object$entries2[_i3], 2), type = _Object$entries2$_i[0], privateKey = _Object$entries2$_i[1]; this.privateKeys.set(type, privateKey); } } }]); return CrossSigningCallbacks; }(); /** * Catches the 4S private key set during bootstrapping by implementing * the SecretStorage crypto callbacks */ var SSSSCryptoCallbacks = /*#__PURE__*/function () { function SSSSCryptoCallbacks(delegateCryptoCallbacks) { (0, _classCallCheck2["default"])(this, SSSSCryptoCallbacks); this._privateKeys = new Map(); this._delegateCryptoCallbacks = delegateCryptoCallbacks; } (0, _createClass2["default"])(SSSSCryptoCallbacks, [{ key: "getSecretStorageKey", value: function () { var _getSecretStorageKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(_ref, name) { var keys, _i4, _Object$keys, keyId, privateKey, result, _result, _keyId, _privateKey; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: keys = _ref.keys; _i4 = 0, _Object$keys = Object.keys(keys); case 2: if (!(_i4 < _Object$keys.length)) { _context3.next = 10; break; } keyId = _Object$keys[_i4]; privateKey = this._privateKeys.get(keyId); if (!privateKey) { _context3.next = 7; break; } return _context3.abrupt("return", [keyId, privateKey]); case 7: _i4++; _context3.next = 2; break; case 10: if (!this._delegateCryptoCallbacks) { _context3.next = 16; break; } _context3.next = 13; return this._delegateCryptoCallbacks.getSecretStorageKey({ keys: keys }, name); case 13: result = _context3.sent; if (result) { _result = (0, _slicedToArray2["default"])(result, 2), _keyId = _result[0], _privateKey = _result[1]; this._privateKeys.set(_keyId, _privateKey); } return _context3.abrupt("return", result); case 16: case "end": return _context3.stop(); } } }, _callee3, this); })); function getSecretStorageKey(_x3, _x4) { return _getSecretStorageKey.apply(this, arguments); } return getSecretStorageKey; }() }, { key: "addPrivateKey", value: function addPrivateKey(keyId, privKey) { this._privateKeys.set(keyId, privKey); // Also pass along to application to cache if it wishes if (this._delegateCryptoCallbacks && this._delegateCryptoCallbacks.cacheSecretStorageKey) { this._delegateCryptoCallbacks.cacheSecretStorageKey(keyId, privKey); } } }]); return SSSSCryptoCallbacks; }(); },{"../http-api":92,"../logger":95,"../models/event":100,"./CrossSigning":60,"./store/indexeddb-crypto-store":78,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"events":36}],63:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.OlmDevice = OlmDevice; exports.WITHHELD_MESSAGES = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _logger = require("../logger"); var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store"); var algorithms = _interopRequireWildcard(require("./algorithms")); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (_e) { function e(_x61) { return _e.apply(this, arguments); } e.toString = function () { return _e.toString(); }; return e; }(function (e) { throw e; }), f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function (_e2) { function e(_x62) { return _e2.apply(this, arguments); } e.toString = function () { return _e2.toString(); }; return e; }(function (e) { didErr = true; err = e; }), f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } // The maximum size of an event is 65K, and we base64 the content, so this is a // reasonable approximation to the biggest plaintext we can encrypt. var MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4; function checkPayloadLength(payloadString) { if (payloadString === undefined) { throw new Error("payloadString undefined"); } if (payloadString.length > MAX_PLAINTEXT_LENGTH) { // might as well fail early here rather than letting the olm library throw // a cryptic memory allocation error. // // Note that even if we manage to do the encryption, the message send may fail, // because by the time we've wrapped the ciphertext in the event object, it may // exceed 65K. But at least we won't just fail with "abort()" in that case. var err = new Error("Message too long (" + payloadString.length + " bytes). " + "The maximum for an encrypted message is " + MAX_PLAINTEXT_LENGTH + " bytes."); // TODO: [TypeScript] We should have our own error types err.data = { errcode: "M_TOO_LARGE", error: "Payload too large for encrypted message" }; throw err; } } /** * The type of object we use for importing and exporting megolm session data. * * @typedef {Object} module:crypto/OlmDevice.MegolmSessionData * @property {String} sender_key Sender's Curve25519 device key * @property {String[]} forwarding_curve25519_key_chain Devices which forwarded * this session to us (normally empty). * @property {Object} sender_claimed_keys Other keys the sender claims. * @property {String} room_id Room this session is used in * @property {String} session_id Unique id for the session * @property {String} session_key Base64'ed key data */ /** * Manages the olm cryptography functions. Each OlmDevice has a single * OlmAccount and a number of OlmSessions. * * Accounts and sessions are kept pickled in the cryptoStore. * * @constructor * @alias module:crypto/OlmDevice * * @param {Object} cryptoStore A store for crypto data * * @property {string} deviceCurve25519Key Curve25519 key for the account * @property {string} deviceEd25519Key Ed25519 key for the account */ function OlmDevice(cryptoStore) { this._cryptoStore = cryptoStore; this._pickleKey = "DEFAULT_KEY"; // don't know these until we load the account from storage in init() this.deviceCurve25519Key = null; this.deviceEd25519Key = null; this._maxOneTimeKeys = null; // we don't bother stashing outboundgroupsessions in the cryptoStore - // instead we keep them here. this._outboundGroupSessionStore = {}; // Store a set of decrypted message indexes for each group session. // This partially mitigates a replay attack where a MITM resends a group // message into the room. // // When we decrypt a message and the message index matches a previously // decrypted message, one possible cause of that is that we are decrypting // the same event, and may not indicate an actual replay attack. For // example, this could happen if we receive events, forget about them, and // then re-fetch them when we backfill. So we store the event ID and // timestamp corresponding to each message index when we first decrypt it, // and compare these against the event ID and timestamp every time we use // that same index. If they match, then we're probably decrypting the same // event and we don't consider it a replay attack. // // Keys are strings of form "||" // Values are objects of the form "{id: , timestamp: }" this._inboundGroupSessionMessageIndexes = {}; // Keep track of sessions that we're starting, so that we don't start // multiple sessions for the same device at the same time. this._sessionsInProgress = {}; // Used by olm to serialise prekey message decryptions this._olmPrekeyPromise = Promise.resolve(); } /** * Initialise the OlmAccount. This must be called before any other operations * on the OlmDevice. * * Data from an exported Olm device can be provided * in order to re-create this device. * * Attempts to load the OlmAccount from the crypto store, or creates one if none is * found. * * Reads the device keys from the OlmAccount object. * * @param {object} opts * @param {object} opts.fromExportedDevice (Optional) data from exported device * that must be re-created. * If present, opts.pickleKey is ignored * (exported data already provides a pickle key) * @param {object} opts.pickleKey (Optional) pickle key to set instead of default one */ OlmDevice.prototype.init = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var opts, e2eKeys, account, pickleKey, fromExportedDevice, _args = arguments; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; account = new global.Olm.Account(); pickleKey = opts.pickleKey, fromExportedDevice = opts.fromExportedDevice; _context.prev = 3; if (!fromExportedDevice) { _context.next = 11; break; } if (pickleKey) { console.warn('ignoring opts.pickleKey' + ' because opts.fromExportedDevice is present.'); } this._pickleKey = fromExportedDevice.pickleKey; _context.next = 9; return _initialiseFromExportedDevice(fromExportedDevice, this._cryptoStore, this._pickleKey, account); case 9: _context.next = 14; break; case 11: if (pickleKey) { this._pickleKey = pickleKey; } _context.next = 14; return _initialiseAccount(this._cryptoStore, this._pickleKey, account); case 14: e2eKeys = JSON.parse(account.identity_keys()); this._maxOneTimeKeys = account.max_number_of_one_time_keys(); case 16: _context.prev = 16; account.free(); return _context.finish(16); case 19: this.deviceCurve25519Key = e2eKeys.curve25519; this.deviceEd25519Key = e2eKeys.ed25519; case 21: case "end": return _context.stop(); } } }, _callee, this, [[3,, 16, 19]]); })); /** * Populates the crypto store using data that was exported from an existing device. * Note that for now only the “account” and “sessions” stores are populated; * Other stores will be as with a new device. * * @param {Object} exportedData Data exported from another device * through the “export” method. * @param {module:crypto/store/base~CryptoStore} cryptoStore storage for the crypto layer * @param {string} pickleKey the key that was used to pickle the exported data * @param {Olm.Account} account an olm account to initialize */ function _initialiseFromExportedDevice(_x, _x2, _x3, _x4) { return _initialiseFromExportedDevice2.apply(this, arguments); } function _initialiseFromExportedDevice2() { _initialiseFromExportedDevice2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22(exportedData, cryptoStore, pickleKey, account) { return _regenerator["default"].wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: _context22.next = 2; return cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { cryptoStore.storeAccount(txn, exportedData.pickledAccount); exportedData.sessions.forEach(function (session) { var deviceKey = session.deviceKey, sessionId = session.sessionId; var sessionInfo = { session: session.session, lastReceivedMessageTs: session.lastReceivedMessageTs }; cryptoStore.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn); }); }); case 2: account.unpickle(pickleKey, exportedData.pickledAccount); case 3: case "end": return _context22.stop(); } } }, _callee22); })); return _initialiseFromExportedDevice2.apply(this, arguments); } function _initialiseAccount(_x5, _x6, _x7) { return _initialiseAccount2.apply(this, arguments); } /** * @return {array} The version of Olm. */ function _initialiseAccount2() { _initialiseAccount2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23(cryptoStore, pickleKey, account) { return _regenerator["default"].wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: _context23.next = 2; return cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { cryptoStore.getAccount(txn, function (pickledAccount) { if (pickledAccount !== null) { account.unpickle(pickleKey, pickledAccount); } else { account.create(); pickledAccount = account.pickle(pickleKey); cryptoStore.storeAccount(txn, pickledAccount); } }); }); case 2: case "end": return _context23.stop(); } } }, _callee23); })); return _initialiseAccount2.apply(this, arguments); } OlmDevice.getOlmVersion = function () { return global.Olm.get_library_version(); }; /** * extract our OlmAccount from the crypto store and call the given function * with the account object * The `account` object is useable only within the callback passed to this * function and will be freed as soon the callback returns. It is *not* * useable for the rest of the lifetime of the transaction. * This function requires a live transaction object from cryptoStore.doTxn() * and therefore may only be called in a doTxn() callback. * * @param {*} txn Opaque transaction object from cryptoStore.doTxn() * @param {function} func * @private */ OlmDevice.prototype._getAccount = function (txn, func) { var _this = this; this._cryptoStore.getAccount(txn, function (pickledAccount) { var account = new global.Olm.Account(); try { account.unpickle(_this._pickleKey, pickledAccount); func(account); } finally { account.free(); } }); }; /* * Saves an account to the crypto store. * This function requires a live transaction object from cryptoStore.doTxn() * and therefore may only be called in a doTxn() callback. * * @param {*} txn Opaque transaction object from cryptoStore.doTxn() * @param {object} Olm.Account object * @private */ OlmDevice.prototype._storeAccount = function (txn, account) { this._cryptoStore.storeAccount(txn, account.pickle(this._pickleKey)); }; /** * Export data for re-creating the Olm device later. * TODO export data other than just account and (P2P) sessions. * * @return {Promise} The exported data */ OlmDevice.prototype["export"] = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var _this2 = this; var result; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: result = { pickleKey: this._pickleKey }; _context2.next = 3; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this2._cryptoStore.getAccount(txn, function (pickledAccount) { result.pickledAccount = pickledAccount; }); result.sessions = []; // Note that the pickledSession object we get in the callback // is not exactly the same thing you get in method _getSession // see documentation of IndexedDBCryptoStore.getAllEndToEndSessions _this2._cryptoStore.getAllEndToEndSessions(txn, function (pickledSession) { result.sessions.push(pickledSession); }); }); case 3: return _context2.abrupt("return", result); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); /** * extract an OlmSession from the session store and call the given function * The session is useable only within the callback passed to this * function and will be freed as soon the callback returns. It is *not* * useable for the rest of the lifetime of the transaction. * * @param {string} deviceKey * @param {string} sessionId * @param {*} txn Opaque transaction object from cryptoStore.doTxn() * @param {function} func * @private */ OlmDevice.prototype._getSession = function (deviceKey, sessionId, txn, func) { var _this3 = this; this._cryptoStore.getEndToEndSession(deviceKey, sessionId, txn, function (sessionInfo) { _this3._unpickleSession(sessionInfo, func); }); }; /** * Creates a session object from a session pickle and executes the given * function with it. The session object is destroyed once the function * returns. * * @param {object} sessionInfo * @param {function} func * @private */ OlmDevice.prototype._unpickleSession = function (sessionInfo, func) { var session = new global.Olm.Session(); try { session.unpickle(this._pickleKey, sessionInfo.session); var unpickledSessInfo = Object.assign({}, sessionInfo, { session: session }); func(unpickledSessInfo); } finally { session.free(); } }; /** * store our OlmSession in the session store * * @param {string} deviceKey * @param {object} sessionInfo {session: OlmSession, lastReceivedMessageTs: int} * @param {*} txn Opaque transaction object from cryptoStore.doTxn() * @private */ OlmDevice.prototype._saveSession = function (deviceKey, sessionInfo, txn) { var sessionId = sessionInfo.session.session_id(); var pickledSessionInfo = Object.assign(sessionInfo, { session: sessionInfo.session.pickle(this._pickleKey) }); this._cryptoStore.storeEndToEndSession(deviceKey, sessionId, pickledSessionInfo, txn); }; /** * get an OlmUtility and call the given function * * @param {function} func * @return {object} result of func * @private */ OlmDevice.prototype._getUtility = function (func) { var utility = new global.Olm.Utility(); try { return func(utility); } finally { utility.free(); } }; /** * Signs a message with the ed25519 key for this account. * * @param {string} message message to be signed * @return {Promise} base64-encoded signature */ OlmDevice.prototype.sign = /*#__PURE__*/function () { var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(message) { var _this4 = this; var result; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this4._getAccount(txn, function (account) { result = account.sign(message); }); }); case 2: return _context3.abrupt("return", result); case 3: case "end": return _context3.stop(); } } }, _callee3, this); })); return function (_x8) { return _ref3.apply(this, arguments); }; }(); /** * Get the current (unused, unpublished) one-time keys for this account. * * @return {object} one time keys; an object with the single property * curve25519, which is itself an object mapping key id to Curve25519 * key. */ OlmDevice.prototype.getOneTimeKeys = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var _this5 = this; var result; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this5._getAccount(txn, function (account) { result = JSON.parse(account.one_time_keys()); }); }); case 2: return _context4.abrupt("return", result); case 3: case "end": return _context4.stop(); } } }, _callee4, this); })); /** * Get the maximum number of one-time keys we can store. * * @return {number} number of keys */ OlmDevice.prototype.maxNumberOfOneTimeKeys = function () { return this._maxOneTimeKeys; }; /** * Marks all of the one-time keys as published. */ OlmDevice.prototype.markKeysAsPublished = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { var _this6 = this; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this6._getAccount(txn, function (account) { account.mark_keys_as_published(); _this6._storeAccount(txn, account); }); }); case 2: case "end": return _context5.stop(); } } }, _callee5, this); })); /** * Generate some new one-time keys * * @param {number} numKeys number of keys to generate * @return {Promise} Resolved once the account is saved back having generated the keys */ OlmDevice.prototype.generateOneTimeKeys = function (numKeys) { var _this7 = this; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this7._getAccount(txn, function (account) { account.generate_one_time_keys(numKeys); _this7._storeAccount(txn, account); }); }); }; /** * Generate a new outbound session * * The new session will be stored in the cryptoStore. * * @param {string} theirIdentityKey remote user's Curve25519 identity key * @param {string} theirOneTimeKey remote user's one-time Curve25519 key * @return {string} sessionId for the outbound session. */ OlmDevice.prototype.createOutboundSession = /*#__PURE__*/function () { var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(theirIdentityKey, theirOneTimeKey) { var _this8 = this; var newSessionId; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this8._getAccount(txn, function (account) { var session = new global.Olm.Session(); try { session.create_outbound(account, theirIdentityKey, theirOneTimeKey); newSessionId = session.session_id(); _this8._storeAccount(txn, account); var sessionInfo = { session: session, // Pretend we've received a message at this point, otherwise // if we try to send a message to the device, it won't use // this session lastReceivedMessageTs: Date.now() }; _this8._saveSession(theirIdentityKey, sessionInfo, txn); } finally { session.free(); } }); }); case 2: return _context6.abrupt("return", newSessionId); case 3: case "end": return _context6.stop(); } } }, _callee6, this); })); return function (_x9, _x10) { return _ref6.apply(this, arguments); }; }(); /** * Generate a new inbound session, given an incoming message * * @param {string} theirDeviceIdentityKey remote user's Curve25519 identity key * @param {number} messageType messageType field from the received message (must be 0) * @param {string} ciphertext base64-encoded body from the received message * * @return {{payload: string, session_id: string}} decrypted payload, and * session id of new session * * @raises {Error} if the received message was not valid (for instance, it * didn't use a valid one-time key). */ OlmDevice.prototype.createInboundSession = /*#__PURE__*/function () { var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(theirDeviceIdentityKey, messageType, ciphertext) { var _this9 = this; var result; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: if (!(messageType !== 0)) { _context7.next = 2; break; } throw new Error("Need messageType == 0 to create inbound session"); case 2: _context7.next = 4; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this9._getAccount(txn, function (account) { var session = new global.Olm.Session(); try { session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext); account.remove_one_time_keys(session); _this9._storeAccount(txn, account); var payloadString = session.decrypt(messageType, ciphertext); var sessionInfo = { session: session, // this counts as a received message: set last received message time // to now lastReceivedMessageTs: Date.now() }; _this9._saveSession(theirDeviceIdentityKey, sessionInfo, txn); result = { payload: payloadString, session_id: session.session_id() }; } finally { session.free(); } }); }); case 4: return _context7.abrupt("return", result); case 5: case "end": return _context7.stop(); } } }, _callee7, this); })); return function (_x11, _x12, _x13) { return _ref7.apply(this, arguments); }; }(); /** * Get a list of known session IDs for the given device * * @param {string} theirDeviceIdentityKey Curve25519 identity key for the * remote device * @return {Promise} a list of known session ids for the device */ OlmDevice.prototype.getSessionIdsForDevice = /*#__PURE__*/function () { var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(theirDeviceIdentityKey) { var _this10 = this; var sessionIds; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!this._sessionsInProgress[theirDeviceIdentityKey]) { _context8.next = 9; break; } _logger.logger.log("waiting for olm session to be created"); _context8.prev = 2; _context8.next = 5; return this._sessionsInProgress[theirDeviceIdentityKey]; case 5: _context8.next = 9; break; case 7: _context8.prev = 7; _context8.t0 = _context8["catch"](2); case 9: _context8.next = 11; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this10._cryptoStore.getEndToEndSessions(theirDeviceIdentityKey, txn, function (sessions) { sessionIds = Object.keys(sessions); }); }); case 11: return _context8.abrupt("return", sessionIds); case 12: case "end": return _context8.stop(); } } }, _callee8, this, [[2, 7]]); })); return function (_x14) { return _ref8.apply(this, arguments); }; }(); /** * Get the right olm session id for encrypting messages to the given identity key * * @param {string} theirDeviceIdentityKey Curve25519 identity key for the * remote device * @param {boolean} nowait Don't wait for an in-progress session to complete. * This should only be set to true of the calling function is the function * that marked the session as being in-progress. * @return {Promise} session id, or null if no established session */ OlmDevice.prototype.getSessionIdForDevice = /*#__PURE__*/function () { var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(theirDeviceIdentityKey, nowait) { var sessionInfos, idxOfBest, i, thisSessInfo, thisLastReceived, bestSessInfo, bestLastReceived; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this.getSessionInfoForDevice(theirDeviceIdentityKey, nowait); case 2: sessionInfos = _context9.sent; if (!(sessionInfos.length === 0)) { _context9.next = 5; break; } return _context9.abrupt("return", null); case 5: // Use the session that has most recently received a message idxOfBest = 0; for (i = 1; i < sessionInfos.length; i++) { thisSessInfo = sessionInfos[i]; thisLastReceived = thisSessInfo.lastReceivedMessageTs === undefined ? 0 : thisSessInfo.lastReceivedMessageTs; bestSessInfo = sessionInfos[idxOfBest]; bestLastReceived = bestSessInfo.lastReceivedMessageTs === undefined ? 0 : bestSessInfo.lastReceivedMessageTs; if (thisLastReceived > bestLastReceived || thisLastReceived === bestLastReceived && thisSessInfo.sessionId < bestSessInfo.sessionId) { idxOfBest = i; } } return _context9.abrupt("return", sessionInfos[idxOfBest].sessionId); case 8: case "end": return _context9.stop(); } } }, _callee9, this); })); return function (_x15, _x16) { return _ref9.apply(this, arguments); }; }(); /** * Get information on the active Olm sessions for a device. *

* Returns an array, with an entry for each active session. The first entry in * the result will be the one used for outgoing messages. Each entry contains * the keys 'hasReceivedMessage' (true if the session has received an incoming * message and is therefore past the pre-key stage), and 'sessionId'. * * @param {string} deviceIdentityKey Curve25519 identity key for the device * @param {boolean} nowait Don't wait for an in-progress session to complete. * This should only be set to true of the calling function is the function * that marked the session as being in-progress. * @return {Array.<{sessionId: string, hasReceivedMessage: Boolean}>} */ OlmDevice.prototype.getSessionInfoForDevice = /*#__PURE__*/function () { var _ref10 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(deviceIdentityKey, nowait) { var _this11 = this; var info; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: if (!(this._sessionsInProgress[deviceIdentityKey] && !nowait)) { _context10.next = 9; break; } _logger.logger.log("waiting for olm session to be created"); _context10.prev = 2; _context10.next = 5; return this._sessionsInProgress[deviceIdentityKey]; case 5: _context10.next = 9; break; case 7: _context10.prev = 7; _context10.t0 = _context10["catch"](2); case 9: info = []; _context10.next = 12; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this11._cryptoStore.getEndToEndSessions(deviceIdentityKey, txn, function (sessions) { var sessionIds = Object.keys(sessions).sort(); var _iterator = _createForOfIteratorHelper(sessionIds), _step; try { var _loop = function _loop() { var sessionId = _step.value; _this11._unpickleSession(sessions[sessionId], function (sessInfo) { info.push({ lastReceivedMessageTs: sessInfo.lastReceivedMessageTs, hasReceivedMessage: sessInfo.session.has_received_message(), sessionId: sessionId }); }); }; for (_iterator.s(); !(_step = _iterator.n()).done;) { _loop(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }); }); case 12: return _context10.abrupt("return", info); case 13: case "end": return _context10.stop(); } } }, _callee10, this, [[2, 7]]); })); return function (_x17, _x18) { return _ref10.apply(this, arguments); }; }(); /** * Encrypt an outgoing message using an existing session * * @param {string} theirDeviceIdentityKey Curve25519 identity key for the * remote device * @param {string} sessionId the id of the active session * @param {string} payloadString payload to be encrypted and sent * * @return {Promise} ciphertext */ OlmDevice.prototype.encryptMessage = /*#__PURE__*/function () { var _ref11 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(theirDeviceIdentityKey, sessionId, payloadString) { var _this12 = this; var res; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: checkPayloadLength(payloadString); _context11.next = 3; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this12._getSession(theirDeviceIdentityKey, sessionId, txn, function (sessionInfo) { var sessionDesc = sessionInfo.session.describe(); _logger.logger.log("encryptMessage: Olm Session ID " + sessionId + " to " + theirDeviceIdentityKey + ": " + sessionDesc); res = sessionInfo.session.encrypt(payloadString); _this12._saveSession(theirDeviceIdentityKey, sessionInfo, txn); }); }); case 3: return _context11.abrupt("return", res); case 4: case "end": return _context11.stop(); } } }, _callee11, this); })); return function (_x19, _x20, _x21) { return _ref11.apply(this, arguments); }; }(); /** * Decrypt an incoming message using an existing session * * @param {string} theirDeviceIdentityKey Curve25519 identity key for the * remote device * @param {string} sessionId the id of the active session * @param {number} messageType messageType field from the received message * @param {string} ciphertext base64-encoded body from the received message * * @return {Promise} decrypted payload. */ OlmDevice.prototype.decryptMessage = /*#__PURE__*/function () { var _ref12 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(theirDeviceIdentityKey, sessionId, messageType, ciphertext) { var _this13 = this; var payloadString; return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this13._getSession(theirDeviceIdentityKey, sessionId, txn, function (sessionInfo) { var sessionDesc = sessionInfo.session.describe(); _logger.logger.log("decryptMessage: Olm Session ID " + sessionId + " from " + theirDeviceIdentityKey + ": " + sessionDesc); payloadString = sessionInfo.session.decrypt(messageType, ciphertext); sessionInfo.lastReceivedMessageTs = Date.now(); _this13._saveSession(theirDeviceIdentityKey, sessionInfo, txn); }); }); case 2: return _context12.abrupt("return", payloadString); case 3: case "end": return _context12.stop(); } } }, _callee12, this); })); return function (_x22, _x23, _x24, _x25) { return _ref12.apply(this, arguments); }; }(); /** * Determine if an incoming messages is a prekey message matching an existing session * * @param {string} theirDeviceIdentityKey Curve25519 identity key for the * remote device * @param {string} sessionId the id of the active session * @param {number} messageType messageType field from the received message * @param {string} ciphertext base64-encoded body from the received message * * @return {Promise} true if the received message is a prekey message which matches * the given session. */ OlmDevice.prototype.matchesSession = /*#__PURE__*/function () { var _ref13 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(theirDeviceIdentityKey, sessionId, messageType, ciphertext) { var _this14 = this; var matches; return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: if (!(messageType !== 0)) { _context13.next = 2; break; } return _context13.abrupt("return", false); case 2: _context13.next = 4; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_SESSIONS], function (txn) { _this14._getSession(theirDeviceIdentityKey, sessionId, txn, function (sessionInfo) { matches = sessionInfo.session.matches_inbound(ciphertext); }); }); case 4: return _context13.abrupt("return", matches); case 5: case "end": return _context13.stop(); } } }, _callee13, this); })); return function (_x26, _x27, _x28, _x29) { return _ref13.apply(this, arguments); }; }(); OlmDevice.prototype.recordSessionProblem = /*#__PURE__*/function () { var _ref14 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(deviceKey, type, fixed) { return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return this._cryptoStore.storeEndToEndSessionProblem(deviceKey, type, fixed); case 2: case "end": return _context14.stop(); } } }, _callee14, this); })); return function (_x30, _x31, _x32) { return _ref14.apply(this, arguments); }; }(); OlmDevice.prototype.sessionMayHaveProblems = /*#__PURE__*/function () { var _ref15 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(deviceKey, timestamp) { return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _context15.next = 2; return this._cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp); case 2: return _context15.abrupt("return", _context15.sent); case 3: case "end": return _context15.stop(); } } }, _callee15, this); })); return function (_x33, _x34) { return _ref15.apply(this, arguments); }; }(); OlmDevice.prototype.filterOutNotifiedErrorDevices = /*#__PURE__*/function () { var _ref16 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(devices) { return _regenerator["default"].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: _context16.next = 2; return this._cryptoStore.filterOutNotifiedErrorDevices(devices); case 2: return _context16.abrupt("return", _context16.sent); case 3: case "end": return _context16.stop(); } } }, _callee16, this); })); return function (_x35) { return _ref16.apply(this, arguments); }; }(); // Outbound group session // ====================== /** * store an OutboundGroupSession in _outboundGroupSessionStore * * @param {Olm.OutboundGroupSession} session * @private */ OlmDevice.prototype._saveOutboundGroupSession = function (session) { var pickledSession = session.pickle(this._pickleKey); this._outboundGroupSessionStore[session.session_id()] = pickledSession; }; /** * extract an OutboundGroupSession from _outboundGroupSessionStore and call the * given function * * @param {string} sessionId * @param {function} func * @return {object} result of func * @private */ OlmDevice.prototype._getOutboundGroupSession = function (sessionId, func) { var pickled = this._outboundGroupSessionStore[sessionId]; if (pickled === undefined) { throw new Error("Unknown outbound group session " + sessionId); } var session = new global.Olm.OutboundGroupSession(); try { session.unpickle(this._pickleKey, pickled); return func(session); } finally { session.free(); } }; /** * Generate a new outbound group session * * @return {string} sessionId for the outbound session. */ OlmDevice.prototype.createOutboundGroupSession = function () { var session = new global.Olm.OutboundGroupSession(); try { session.create(); this._saveOutboundGroupSession(session); return session.session_id(); } finally { session.free(); } }; /** * Encrypt an outgoing message with an outbound group session * * @param {string} sessionId the id of the outboundgroupsession * @param {string} payloadString payload to be encrypted and sent * * @return {string} ciphertext */ OlmDevice.prototype.encryptGroupMessage = function (sessionId, payloadString) { var self = this; _logger.logger.log("encrypting msg with megolm session ".concat(sessionId)); checkPayloadLength(payloadString); return this._getOutboundGroupSession(sessionId, function (session) { var res = session.encrypt(payloadString); self._saveOutboundGroupSession(session); return res; }); }; /** * Get the session keys for an outbound group session * * @param {string} sessionId the id of the outbound group session * * @return {{chain_index: number, key: string}} current chain index, and * base64-encoded secret key. */ OlmDevice.prototype.getOutboundGroupSessionKey = function (sessionId) { return this._getOutboundGroupSession(sessionId, function (session) { return { chain_index: session.message_index(), key: session.session_key() }; }); }; // Inbound group session // ===================== /** * data stored in the session store about an inbound group session * * @typedef {Object} InboundGroupSessionData * @property {string} room_Id * @property {string} session pickled Olm.InboundGroupSession * @property {Object} keysClaimed * @property {Array} forwardingCurve25519KeyChain Devices involved in forwarding * this session to us (normally empty). */ /** * Unpickle a session from a sessionData object and invoke the given function. * The session is valid only until func returns. * * @param {Object} sessionData Object describing the session. * @param {function(Olm.InboundGroupSession)} func Invoked with the unpickled session * @return {*} result of func */ OlmDevice.prototype._unpickleInboundGroupSession = function (sessionData, func) { var session = new global.Olm.InboundGroupSession(); try { session.unpickle(this._pickleKey, sessionData.session); return func(session); } finally { session.free(); } }; /** * extract an InboundGroupSession from the crypto store and call the given function * * @param {string} roomId The room ID to extract the session for, or null to fetch * sessions for any room. * @param {string} senderKey * @param {string} sessionId * @param {*} txn Opaque transaction object from cryptoStore.doTxn() * @param {function(Olm.InboundGroupSession, InboundGroupSessionData)} func * function to call. * * @private */ OlmDevice.prototype._getInboundGroupSession = function (roomId, senderKey, sessionId, txn, func) { var _this15 = this; this._cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, function (sessionData, withheld) { if (sessionData === null) { func(null, null, withheld); return; } // if we were given a room ID, check that the it matches the original one for the session. This stops // the HS pretending a message was targeting a different room. if (roomId !== null && roomId !== sessionData.room_id) { throw new Error("Mismatched room_id for inbound group session (expected " + sessionData.room_id + ", was " + roomId + ")"); } _this15._unpickleInboundGroupSession(sessionData, function (session) { func(session, sessionData, withheld); }); }); }; /** * Add an inbound group session to the session store * * @param {string} roomId room in which this session will be used * @param {string} senderKey base64-encoded curve25519 key of the sender * @param {Array} forwardingCurve25519KeyChain Devices involved in forwarding * this session to us. * @param {string} sessionId session identifier * @param {string} sessionKey base64-encoded secret key * @param {Object} keysClaimed Other keys the sender claims. * @param {boolean} exportFormat true if the megolm keys are in export format * (ie, they lack an ed25519 signature) * @param {Object} [extraSessionData={}] any other data to be include with the session */ OlmDevice.prototype.addInboundGroupSession = /*#__PURE__*/function () { var _ref17 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(roomId, senderKey, forwardingCurve25519KeyChain, sessionId, sessionKey, keysClaimed, exportFormat) { var _this16 = this; var extraSessionData, _args17 = arguments; return _regenerator["default"].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: extraSessionData = _args17.length > 7 && _args17[7] !== undefined ? _args17[7] : {}; _context17.next = 3; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) { /* if we already have this session, consider updating it */ _this16._getInboundGroupSession(roomId, senderKey, sessionId, txn, function (existingSession, existingSessionData) { // new session. var session = new global.Olm.InboundGroupSession(); try { if (exportFormat) { session.import_session(sessionKey); } else { session.create(sessionKey); } if (sessionId != session.session_id()) { throw new Error("Mismatched group session ID from senderKey: " + senderKey); } if (existingSession) { _logger.logger.log("Update for megolm session " + senderKey + "/" + sessionId); if (existingSession.first_known_index() <= session.first_known_index()) { // existing session has lower index (i.e. can // decrypt more), so keep it _logger.logger.log("Keeping existing megolm session ".concat(sessionId)); return; } } _logger.logger.info("Storing megolm session " + senderKey + "/" + sessionId + " with first index " + session.first_known_index()); var sessionData = Object.assign({}, extraSessionData, { room_id: roomId, session: session.pickle(_this16._pickleKey), keysClaimed: keysClaimed, forwardingCurve25519KeyChain: forwardingCurve25519KeyChain }); _this16._cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn); } finally { session.free(); } }); }); case 3: case "end": return _context17.stop(); } } }, _callee17, this); })); return function (_x36, _x37, _x38, _x39, _x40, _x41, _x42) { return _ref17.apply(this, arguments); }; }(); /** * Record in the data store why an inbound group session was withheld. * * @param {string} roomId room that the session belongs to * @param {string} senderKey base64-encoded curve25519 key of the sender * @param {string} sessionId session identifier * @param {string} code reason code * @param {string} reason human-readable version of `code` */ OlmDevice.prototype.addInboundGroupSessionWithheld = /*#__PURE__*/function () { var _ref18 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(roomId, senderKey, sessionId, code, reason) { var _this17 = this; return _regenerator["default"].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: _context18.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) { _this17._cryptoStore.storeEndToEndInboundGroupSessionWithheld(senderKey, sessionId, { room_id: roomId, code: code, reason: reason }, txn); }); case 2: case "end": return _context18.stop(); } } }, _callee18, this); })); return function (_x43, _x44, _x45, _x46, _x47) { return _ref18.apply(this, arguments); }; }(); var WITHHELD_MESSAGES = { "m.unverified": "The sender has disabled encrypting to unverified devices.", "m.blacklisted": "The sender has blocked you.", "m.unauthorised": "You are not authorised to read the message.", "m.no_olm": "Unable to establish a secure channel." }; /** * Calculate the message to use for the exception when a session key is withheld. * * @param {object} withheld An object that describes why the key was withheld. * * @return {string} the message * * @private */ exports.WITHHELD_MESSAGES = WITHHELD_MESSAGES; function _calculateWithheldMessage(withheld) { if (withheld.code && withheld.code in WITHHELD_MESSAGES) { return WITHHELD_MESSAGES[withheld.code]; } else if (withheld.reason) { return withheld.reason; } else { return "decryption key withheld"; } } /** * Decrypt a received message with an inbound group session * * @param {string} roomId room in which the message was received * @param {string} senderKey base64-encoded curve25519 key of the sender * @param {string} sessionId session identifier * @param {string} body base64-encoded body of the encrypted message * @param {string} eventId ID of the event being decrypted * @param {Number} timestamp timestamp of the event being decrypted * * @return {null} the sessionId is unknown * * @return {Promise<{result: string, senderKey: string, * forwardingCurve25519KeyChain: Array, * keysClaimed: Object}>} */ OlmDevice.prototype.decryptGroupMessage = /*#__PURE__*/function () { var _ref19 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(roomId, senderKey, sessionId, body, eventId, timestamp) { var _this18 = this; var result, error; return _regenerator["default"].wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: _context19.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) { _this18._getInboundGroupSession(roomId, senderKey, sessionId, txn, function (session, sessionData, withheld) { if (session === null) { if (withheld) { error = new algorithms.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", _calculateWithheldMessage(withheld), { session: senderKey + '|' + sessionId }); } result = null; return; } var res; try { res = session.decrypt(body); } catch (e) { if (e && e.message === 'OLM.UNKNOWN_MESSAGE_INDEX' && withheld) { error = new algorithms.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", _calculateWithheldMessage(withheld), { session: senderKey + '|' + sessionId }); } else { error = e; } return; } var plaintext = res.plaintext; if (plaintext === undefined) { // Compatibility for older olm versions. plaintext = res; } else { // Check if we have seen this message index before to detect replay attacks. // If the event ID and timestamp are specified, and the match the event ID // and timestamp from the last time we used this message index, then we // don't consider it a replay attack. var messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index; if (messageIndexKey in _this18._inboundGroupSessionMessageIndexes) { var msgInfo = _this18._inboundGroupSessionMessageIndexes[messageIndexKey]; if (msgInfo.id !== eventId || msgInfo.timestamp !== timestamp) { error = new Error("Duplicate message index, possible replay attack: " + messageIndexKey); return; } } _this18._inboundGroupSessionMessageIndexes[messageIndexKey] = { id: eventId, timestamp: timestamp }; } sessionData.session = session.pickle(_this18._pickleKey); _this18._cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn); result = { result: plaintext, keysClaimed: sessionData.keysClaimed || {}, senderKey: senderKey, forwardingCurve25519KeyChain: sessionData.forwardingCurve25519KeyChain || [], untrusted: sessionData.untrusted }; }); }); case 2: if (!error) { _context19.next = 4; break; } throw error; case 4: return _context19.abrupt("return", result); case 5: case "end": return _context19.stop(); } } }, _callee19, this); })); return function (_x48, _x49, _x50, _x51, _x52, _x53) { return _ref19.apply(this, arguments); }; }(); /** * Determine if we have the keys for a given megolm session * * @param {string} roomId room in which the message was received * @param {string} senderKey base64-encoded curve25519 key of the sender * @param {string} sessionId session identifier * * @returns {Promise} true if we have the keys to this session */ OlmDevice.prototype.hasInboundSessionKeys = /*#__PURE__*/function () { var _ref20 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(roomId, senderKey, sessionId) { var _this19 = this; var result; return _regenerator["default"].wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: _context20.next = 2; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) { _this19._cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, function (sessionData) { if (sessionData === null) { result = false; return; } if (roomId !== sessionData.room_id) { _logger.logger.warn("requested keys for inbound group session ".concat(senderKey, "|") + "".concat(sessionId, ", with incorrect room_id ") + "(expected ".concat(sessionData.room_id, ", ") + "was ".concat(roomId, ")")); result = false; } else { result = true; } }); }); case 2: return _context20.abrupt("return", result); case 3: case "end": return _context20.stop(); } } }, _callee20, this); })); return function (_x54, _x55, _x56) { return _ref20.apply(this, arguments); }; }(); /** * Extract the keys to a given megolm session, for sharing * * @param {string} roomId room in which the message was received * @param {string} senderKey base64-encoded curve25519 key of the sender * @param {string} sessionId session identifier * @param {integer} chainIndex The chain index at which to export the session. * If omitted, export at the first index we know about. * * @returns {Promise<{chain_index: number, key: string, * forwarding_curve25519_key_chain: Array, * sender_claimed_ed25519_key: string * }>} * details of the session key. The key is a base64-encoded megolm key in * export format. * * @throws Error If the given chain index could not be obtained from the known * index (ie. the given chain index is before the first we have). */ OlmDevice.prototype.getInboundGroupSessionKey = /*#__PURE__*/function () { var _ref21 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21(roomId, senderKey, sessionId, chainIndex) { var _this20 = this; var result; return _regenerator["default"].wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: _context21.next = 2; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) { _this20._getInboundGroupSession(roomId, senderKey, sessionId, txn, function (session, sessionData) { if (session === null) { result = null; return; } if (chainIndex === undefined) { chainIndex = session.first_known_index(); } var exportedSession = session.export_session(chainIndex); var claimedKeys = sessionData.keysClaimed || {}; var senderEd25519Key = claimedKeys.ed25519 || null; result = { "chain_index": chainIndex, "key": exportedSession, "forwarding_curve25519_key_chain": sessionData.forwardingCurve25519KeyChain || [], "sender_claimed_ed25519_key": senderEd25519Key }; }); }); case 2: return _context21.abrupt("return", result); case 3: case "end": return _context21.stop(); } } }, _callee21, this); })); return function (_x57, _x58, _x59, _x60) { return _ref21.apply(this, arguments); }; }(); /** * Export an inbound group session * * @param {string} senderKey base64-encoded curve25519 key of the sender * @param {string} sessionId session identifier * @param {string} sessionData The session object from the store * @return {module:crypto/OlmDevice.MegolmSessionData} exported session data */ OlmDevice.prototype.exportInboundGroupSession = function (senderKey, sessionId, sessionData) { return this._unpickleInboundGroupSession(sessionData, function (session) { var messageIndex = session.first_known_index(); return { "sender_key": senderKey, "sender_claimed_keys": sessionData.keysClaimed, "room_id": sessionData.room_id, "session_id": sessionId, "session_key": session.export_session(messageIndex), "forwarding_curve25519_key_chain": session.forwardingCurve25519KeyChain || [], "first_known_index": session.first_known_index() }; }); }; // Utilities // ========= /** * Verify an ed25519 signature. * * @param {string} key ed25519 key * @param {string} message message which was signed * @param {string} signature base64-encoded signature to be checked * * @raises {Error} if there is a problem with the verification. If the key was * too small then the message will be "OLM.INVALID_BASE64". If the signature * was invalid then the message will be "OLM.BAD_MESSAGE_MAC". */ OlmDevice.prototype.verifySignature = function (key, message, signature) { this._getUtility(function (util) { util.ed25519_verify(key, message, signature); }); }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../logger":95,"./algorithms":69,"./store/indexeddb-crypto-store":78,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],64:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.OutgoingRoomKeyRequestManager = exports.ROOM_KEY_REQUEST_STATES = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _logger = require("../logger"); var utils = _interopRequireWildcard(require("../utils")); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * Internal module. Management of outgoing room key requests. * * See https://docs.google.com/document/d/1m4gQkcnJkxNuBmb5NoFCIadIY-DyqqNAS3lloE73BlQ * for draft documentation on what we're supposed to be implementing here. * * @module */ // delay between deciding we want some keys, and sending out the request, to // allow for (a) it turning up anyway, (b) grouping requests together var SEND_KEY_REQUESTS_DELAY_MS = 500; /** possible states for a room key request * * The state machine looks like: * * | (cancellation sent) * | .-------------------------------------------------. * | | | * V V (cancellation requested) | * UNSENT -----------------------------+ | * | | | * | | | * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND * V | Λ * SENT | | * |-------------------------------- | --------------' * | | (cancellation requested with intent * | | to resend the original request) * | | * | (cancellation requested) | * V | * CANCELLATION_PENDING | * | | * | (cancellation sent) | * V | * (deleted) <---------------------------+ * * @enum {number} */ var ROOM_KEY_REQUEST_STATES = { /** request not yet sent */ UNSENT: 0, /** request sent, awaiting reply */ SENT: 1, /** reply received, cancellation not yet sent */ CANCELLATION_PENDING: 2, /** * Cancellation not yet sent and will transition to UNSENT instead of * being deleted once the cancellation has been sent. */ CANCELLATION_PENDING_AND_WILL_RESEND: 3 }; exports.ROOM_KEY_REQUEST_STATES = ROOM_KEY_REQUEST_STATES; var OutgoingRoomKeyRequestManager = /*#__PURE__*/function () { function OutgoingRoomKeyRequestManager(baseApis, deviceId, cryptoStore) { (0, _classCallCheck2["default"])(this, OutgoingRoomKeyRequestManager); this._baseApis = baseApis; this._deviceId = deviceId; this._cryptoStore = cryptoStore; // handle for the delayed call to _sendOutgoingRoomKeyRequests. Non-null // if the callback has been set, or if it is still running. this._sendOutgoingRoomKeyRequestsTimer = null; // sanity check to ensure that we don't end up with two concurrent runs // of _sendOutgoingRoomKeyRequests this._sendOutgoingRoomKeyRequestsRunning = false; this._clientRunning = false; } /** * Called when the client is started. Sets background processes running. */ (0, _createClass2["default"])(OutgoingRoomKeyRequestManager, [{ key: "start", value: function start() { this._clientRunning = true; } /** * Called when the client is stopped. Stops any running background processes. */ }, { key: "stop", value: function stop() { _logger.logger.log('stopping OutgoingRoomKeyRequestManager'); // stop the timer on the next run this._clientRunning = false; } /** * Send any requests that have been queued */ }, { key: "sendQueuedRequests", value: function sendQueuedRequests() { this._startTimer(); } /** * Queue up a room key request, if we haven't already queued or sent one. * * The `requestBody` is compared (with a deep-equality check) against * previous queued or sent requests and if it matches, no change is made. * Otherwise, a request is added to the pending list, and a job is started * in the background to send it. * * @param {module:crypto~RoomKeyRequestBody} requestBody * @param {Array<{userId: string, deviceId: string}>} recipients * @param {boolean} resend whether to resend the key request if there is * already one * * @returns {Promise} resolves when the request has been added to the * pending list (or we have established that a similar request already * exists) */ }, { key: "queueRoomKeyRequest", value: function () { var _queueRoomKeyRequest = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(requestBody, recipients) { var resend, req, state, _state, updatedReq, _args = arguments; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: resend = _args.length > 2 && _args[2] !== undefined ? _args[2] : false; _context.next = 3; return this._cryptoStore.getOutgoingRoomKeyRequest(requestBody); case 3: req = _context.sent; if (req) { _context.next = 9; break; } _context.next = 7; return this._cryptoStore.getOrAddOutgoingRoomKeyRequest({ requestBody: requestBody, recipients: recipients, requestId: this._baseApis.makeTxnId(), state: ROOM_KEY_REQUEST_STATES.UNSENT }); case 7: _context.next = 36; break; case 9: _context.t0 = req.state; _context.next = _context.t0 === ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND ? 12 : _context.t0 === ROOM_KEY_REQUEST_STATES.UNSENT ? 12 : _context.t0 === ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING ? 13 : _context.t0 === ROOM_KEY_REQUEST_STATES.SENT ? 17 : 35; break; case 12: return _context.abrupt("return"); case 13: // existing request is about to be cancelled. If we want to // resend, then change the state so that it resends after // cancelling. Otherwise, just cancel the cancellation. state = resend ? ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND : ROOM_KEY_REQUEST_STATES.SENT; _context.next = 16; return this._cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING, { state: state, cancellationTxnId: this._baseApis.makeTxnId() }); case 16: return _context.abrupt("break", 36); case 17: if (!resend) { _context.next = 34; break; } _state = ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND; _context.next = 21; return this._cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.SENT, { state: _state, cancellationTxnId: this._baseApis.makeTxnId(), // need to use a new transaction ID so that // the request gets sent requestTxnId: this._baseApis.makeTxnId() }); case 21: updatedReq = _context.sent; if (updatedReq) { _context.next = 26; break; } _context.next = 25; return this.queueRoomKeyRequest(requestBody, recipients, resend); case 25: return _context.abrupt("return", _context.sent); case 26: _context.prev = 26; _context.next = 29; return this._sendOutgoingRoomKeyRequestCancellation(updatedReq, true); case 29: _context.next = 34; break; case 31: _context.prev = 31; _context.t1 = _context["catch"](26); _logger.logger.error("Error sending room key request cancellation;" + " will retry later.", _context.t1); case 34: return _context.abrupt("break", 36); case 35: throw new Error('unhandled state: ' + req.state); case 36: case "end": return _context.stop(); } } }, _callee, this, [[26, 31]]); })); function queueRoomKeyRequest(_x, _x2) { return _queueRoomKeyRequest.apply(this, arguments); } return queueRoomKeyRequest; }() /** * Cancel room key requests, if any match the given requestBody * * @param {module:crypto~RoomKeyRequestBody} requestBody * * @returns {Promise} resolves when the request has been updated in our * pending list. */ }, { key: "cancelRoomKeyRequest", value: function cancelRoomKeyRequest(requestBody) { var _this = this; return this._cryptoStore.getOutgoingRoomKeyRequest(requestBody).then(function (req) { if (!req) { // no request was made for this key return; } switch (req.state) { case ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING: case ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND: // nothing to do here return; case ROOM_KEY_REQUEST_STATES.UNSENT: // just delete it // FIXME: ghahah we may have attempted to send it, and // not yet got a successful response. So the server // may have seen it, so we still need to send a cancellation // in that case :/ _logger.logger.log('deleting unnecessary room key request for ' + stringifyRequestBody(requestBody)); return _this._cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.UNSENT); case ROOM_KEY_REQUEST_STATES.SENT: { // send a cancellation. return _this._cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.SENT, { state: ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING, cancellationTxnId: _this._baseApis.makeTxnId() }).then(function (updatedReq) { if (!updatedReq) { // updateOutgoingRoomKeyRequest couldn't find the // request in state ROOM_KEY_REQUEST_STATES.SENT, // so we must have raced with another tab to mark // the request cancelled. There is no point in // sending another cancellation since the other tab // will do it. _logger.logger.log('Tried to cancel room key request for ' + stringifyRequestBody(requestBody) + ' but it was already cancelled in another tab'); return; } // We don't want to wait for the timer, so we send it // immediately. (We might actually end up racing with the timer, // but that's ok: even if we make the request twice, we'll do it // with the same transaction_id, so only one message will get // sent). // // (We also don't want to wait for the response from the server // here, as it will slow down processing of received keys if we // do.) _this._sendOutgoingRoomKeyRequestCancellation(updatedReq)["catch"](function (e) { _logger.logger.error("Error sending room key request cancellation;" + " will retry later.", e); _this._startTimer(); }); }); } default: throw new Error('unhandled state: ' + req.state); } }); } /** * Look for room key requests by target device and state * * @param {string} userId Target user ID * @param {string} deviceId Target device ID * * @return {Promise} resolves to a list of all the * {@link module:crypto/store/base~OutgoingRoomKeyRequest} */ }, { key: "getOutgoingSentRoomKeyRequest", value: function getOutgoingSentRoomKeyRequest(userId, deviceId) { return this._cryptoStore.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, [ROOM_KEY_REQUEST_STATES.SENT]); } /** * Find anything in `sent` state, and kick it around the loop again. * This is intended for situations where something substantial has changed, and we * don't really expect the other end to even care about the cancellation. * For example, after initialization or self-verification. * @return {Promise} An array of `queueRoomKeyRequest` outputs. */ }, { key: "cancelAndResendAllOutgoingRequests", value: function () { var _cancelAndResendAllOutgoingRequests = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var _this2 = this; var outgoings; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this._cryptoStore.getAllOutgoingRoomKeyRequestsByState(ROOM_KEY_REQUEST_STATES.SENT); case 2: outgoings = _context2.sent; return _context2.abrupt("return", Promise.all(outgoings.map(function (_ref) { var requestBody = _ref.requestBody, recipients = _ref.recipients; return _this2.queueRoomKeyRequest(requestBody, recipients, true); }))); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); function cancelAndResendAllOutgoingRequests() { return _cancelAndResendAllOutgoingRequests.apply(this, arguments); } return cancelAndResendAllOutgoingRequests; }() // start the background timer to send queued requests, if the timer isn't // already running }, { key: "_startTimer", value: function _startTimer() { var _this3 = this; if (this._sendOutgoingRoomKeyRequestsTimer) { return; } var startSendingOutgoingRoomKeyRequests = function startSendingOutgoingRoomKeyRequests() { if (_this3._sendOutgoingRoomKeyRequestsRunning) { throw new Error("RoomKeyRequestSend already in progress!"); } _this3._sendOutgoingRoomKeyRequestsRunning = true; _this3._sendOutgoingRoomKeyRequests()["finally"](function () { _this3._sendOutgoingRoomKeyRequestsRunning = false; })["catch"](function (e) { // this should only happen if there is an indexeddb error, // in which case we're a bit stuffed anyway. _logger.logger.warn("error in OutgoingRoomKeyRequestManager: ".concat(e)); }); }; this._sendOutgoingRoomKeyRequestsTimer = global.setTimeout(startSendingOutgoingRoomKeyRequests, SEND_KEY_REQUESTS_DELAY_MS); } // look for and send any queued requests. Runs itself recursively until // there are no more requests, or there is an error (in which case, the // timer will be restarted before the promise resolves). }, { key: "_sendOutgoingRoomKeyRequests", value: function _sendOutgoingRoomKeyRequests() { var _this4 = this; if (!this._clientRunning) { this._sendOutgoingRoomKeyRequestsTimer = null; return Promise.resolve(); } return this._cryptoStore.getOutgoingRoomKeyRequestByState([ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING, ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND, ROOM_KEY_REQUEST_STATES.UNSENT]).then(function (req) { if (!req) { _this4._sendOutgoingRoomKeyRequestsTimer = null; return; } var prom; switch (req.state) { case ROOM_KEY_REQUEST_STATES.UNSENT: prom = _this4._sendOutgoingRoomKeyRequest(req); break; case ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING: prom = _this4._sendOutgoingRoomKeyRequestCancellation(req); break; case ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND: prom = _this4._sendOutgoingRoomKeyRequestCancellation(req, true); break; } return prom.then(function () { // go around the loop again return _this4._sendOutgoingRoomKeyRequests(); })["catch"](function (e) { _logger.logger.error("Error sending room key request; will retry later.", e); _this4._sendOutgoingRoomKeyRequestsTimer = null; }); }); } // given a RoomKeyRequest, send it and update the request record }, { key: "_sendOutgoingRoomKeyRequest", value: function _sendOutgoingRoomKeyRequest(req) { var _this5 = this; _logger.logger.log("Requesting keys for ".concat(stringifyRequestBody(req.requestBody)) + " from ".concat(stringifyRecipientList(req.recipients)) + "(id ".concat(req.requestId, ")")); var requestMessage = { action: "request", requesting_device_id: this._deviceId, request_id: req.requestId, body: req.requestBody }; return this._sendMessageToDevices(requestMessage, req.recipients, req.requestTxnId || req.requestId).then(function () { return _this5._cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.UNSENT, { state: ROOM_KEY_REQUEST_STATES.SENT }); }); } // Given a RoomKeyRequest, cancel it and delete the request record unless // andResend is set, in which case transition to UNSENT. }, { key: "_sendOutgoingRoomKeyRequestCancellation", value: function _sendOutgoingRoomKeyRequestCancellation(req, andResend) { var _this6 = this; _logger.logger.log("Sending cancellation for key request for " + "".concat(stringifyRequestBody(req.requestBody), " to ") + "".concat(stringifyRecipientList(req.recipients), " ") + "(cancellation id ".concat(req.cancellationTxnId, ")")); var requestMessage = { action: "request_cancellation", requesting_device_id: this._deviceId, request_id: req.requestId }; return this._sendMessageToDevices(requestMessage, req.recipients, req.cancellationTxnId).then(function () { if (andResend) { // We want to resend, so transition to UNSENT return _this6._cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING_AND_WILL_RESEND, { state: ROOM_KEY_REQUEST_STATES.UNSENT }); } return _this6._cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, ROOM_KEY_REQUEST_STATES.CANCELLATION_PENDING); }); } // send a RoomKeyRequest to a list of recipients }, { key: "_sendMessageToDevices", value: function _sendMessageToDevices(message, recipients, txnId) { var contentMap = {}; var _iterator = _createForOfIteratorHelper(recipients), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var recip = _step.value; if (!contentMap[recip.userId]) { contentMap[recip.userId] = {}; } contentMap[recip.userId][recip.deviceId] = message; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return this._baseApis.sendToDevice('m.room_key_request', contentMap, txnId); } }]); return OutgoingRoomKeyRequestManager; }(); exports.OutgoingRoomKeyRequestManager = OutgoingRoomKeyRequestManager; function stringifyRequestBody(requestBody) { // we assume that the request is for megolm keys, which are identified by // room id and session id return requestBody.room_id + " / " + requestBody.session_id; } function stringifyRecipientList(recipients) { return '[' + utils.map(recipients, function (r) { return "".concat(r.userId, ":").concat(r.deviceId); }).join(",") + ']'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../logger":95,"../utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],65:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RoomList = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store"); /* Copyright 2018, 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 crypto/RoomList * * Manages the list of encrypted rooms */ /** * @alias module:crypto/RoomList */ var RoomList = /*#__PURE__*/function () { function RoomList(cryptoStore) { (0, _classCallCheck2["default"])(this, RoomList); this._cryptoStore = cryptoStore; // Object of roomId -> room e2e info object (body of the m.room.encryption event) this._roomEncryption = {}; } (0, _createClass2["default"])(RoomList, [{ key: "init", value: function () { var _init = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var _this = this; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ROOMS], function (txn) { _this._cryptoStore.getEndToEndRooms(txn, function (result) { _this._roomEncryption = result; }); }); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function init() { return _init.apply(this, arguments); } return init; }() }, { key: "getRoomEncryption", value: function getRoomEncryption(roomId) { return this._roomEncryption[roomId] || null; } }, { key: "isRoomEncrypted", value: function isRoomEncrypted(roomId) { return Boolean(this.getRoomEncryption(roomId)); } }, { key: "setRoomEncryption", value: function () { var _setRoomEncryption = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(roomId, roomInfo) { var _this2 = this; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // important that this happens before calling into the store // as it prevents the Crypto::setRoomEncryption from calling // this twice for consecutive m.room.encryption events this._roomEncryption[roomId] = roomInfo; _context2.next = 3; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ROOMS], function (txn) { _this2._cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn); }); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function setRoomEncryption(_x, _x2) { return _setRoomEncryption.apply(this, arguments); } return setRoomEncryption; }() }]); return RoomList; }(); exports.RoomList = RoomList; },{"./store/indexeddb-crypto-store":78,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/regenerator":27}],66:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SecretStorage = exports.SECRET_STORAGE_ALGORITHM_V1_AES = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _events = require("events"); var _logger = require("../logger"); var olmlib = _interopRequireWildcard(require("./olmlib")); var _randomstring = require("../randomstring"); var _aes = require("./aes"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var SECRET_STORAGE_ALGORITHM_V1_AES = "m.secret_storage.v1.aes-hmac-sha2"; exports.SECRET_STORAGE_ALGORITHM_V1_AES = SECRET_STORAGE_ALGORITHM_V1_AES; var ZERO_STR = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; /** * Implements Secure Secret Storage and Sharing (MSC1946) * @module crypto/SecretStorage */ var SecretStorage = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(SecretStorage, _EventEmitter); var _super = _createSuper(SecretStorage); function SecretStorage(baseApis, cryptoCallbacks) { var _this; (0, _classCallCheck2["default"])(this, SecretStorage); _this = _super.call(this); _this._baseApis = baseApis; _this._cryptoCallbacks = cryptoCallbacks; _this._requests = {}; _this._incomingRequests = {}; return _this; } (0, _createClass2["default"])(SecretStorage, [{ key: "getDefaultKeyId", value: function () { var _getDefaultKeyId = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var defaultKey; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this._baseApis.getAccountDataFromServer('m.secret_storage.default_key'); case 2: defaultKey = _context.sent; if (defaultKey) { _context.next = 5; break; } return _context.abrupt("return", null); case 5: return _context.abrupt("return", defaultKey.key); case 6: case "end": return _context.stop(); } } }, _callee, this); })); function getDefaultKeyId() { return _getDefaultKeyId.apply(this, arguments); } return getDefaultKeyId; }() }, { key: "setDefaultKeyId", value: function setDefaultKeyId(keyId) { var _this2 = this; return new Promise( /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(resolve, reject) { var listener; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: listener = function listener(ev) { if (ev.getType() === 'm.secret_storage.default_key' && ev.getContent().key === keyId) { _this2._baseApis.removeListener('accountData', listener); resolve(); } }; _this2._baseApis.on('accountData', listener); _context2.prev = 2; _context2.next = 5; return _this2._baseApis.setAccountData('m.secret_storage.default_key', { key: keyId }); case 5: _context2.next = 11; break; case 7: _context2.prev = 7; _context2.t0 = _context2["catch"](2); _this2._baseApis.removeListener('accountData', listener); reject(_context2.t0); case 11: case "end": return _context2.stop(); } } }, _callee2, null, [[2, 7]]); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }()); } /** * Add a key for encrypting secrets. * * @param {string} algorithm the algorithm used by the key. * @param {object} opts the options for the algorithm. The properties used * depend on the algorithm given. * @param {string} [keyId] the ID of the key. If not given, a random * ID will be generated. * * @return {string} the ID of the key */ }, { key: "addKey", value: function () { var _addKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(algorithm, opts, keyId) { var keyData, _yield$SecretStorage$, iv, mac; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: keyData = { algorithm: algorithm }; if (!opts) opts = {}; if (opts.name) { keyData.name = opts.name; } if (!(algorithm === SECRET_STORAGE_ALGORITHM_V1_AES)) { _context3.next = 15; break; } if (opts.passphrase) { keyData.passphrase = opts.passphrase; } if (!opts.key) { _context3.next = 13; break; } _context3.next = 8; return SecretStorage._calculateKeyCheck(opts.key); case 8: _yield$SecretStorage$ = _context3.sent; iv = _yield$SecretStorage$.iv; mac = _yield$SecretStorage$.mac; keyData.iv = iv; keyData.mac = mac; case 13: _context3.next = 16; break; case 15: throw new Error("Unknown key algorithm ".concat(opts.algorithm)); case 16: if (keyId) { _context3.next = 21; break; } case 17: keyId = (0, _randomstring.randomString)(32); case 18: _context3.next = 20; return this._baseApis.getAccountDataFromServer("m.secret_storage.key.".concat(keyId)); case 20: if (_context3.sent) { _context3.next = 17; break; } case 21: _context3.next = 23; return this._baseApis.setAccountData("m.secret_storage.key.".concat(keyId), keyData); case 23: return _context3.abrupt("return", keyId); case 24: case "end": return _context3.stop(); } } }, _callee3, this); })); function addKey(_x3, _x4, _x5) { return _addKey.apply(this, arguments); } return addKey; }() /** * Get the key information for a given ID. * * @param {string} [keyId = default key's ID] The ID of the key to check * for. Defaults to the default key ID if not provided. * @returns {Array?} If the key was found, the return value is an array of * the form [keyId, keyInfo]. Otherwise, null is returned. */ }, { key: "getKey", value: function () { var _getKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(keyId) { var keyInfo; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (keyId) { _context4.next = 4; break; } _context4.next = 3; return this.getDefaultKeyId(); case 3: keyId = _context4.sent; case 4: if (keyId) { _context4.next = 6; break; } return _context4.abrupt("return", null); case 6: _context4.next = 8; return this._baseApis.getAccountDataFromServer("m.secret_storage.key." + keyId); case 8: keyInfo = _context4.sent; return _context4.abrupt("return", keyInfo ? [keyId, keyInfo] : null); case 10: case "end": return _context4.stop(); } } }, _callee4, this); })); function getKey(_x6) { return _getKey.apply(this, arguments); } return getKey; }() /** * Check whether we have a key with a given ID. * * @param {string} [keyId = default key's ID] The ID of the key to check * for. Defaults to the default key ID if not provided. * @return {boolean} Whether we have the key. */ }, { key: "hasKey", value: function () { var _hasKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(keyId) { return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this.getKey(keyId); case 2: return _context5.abrupt("return", !!_context5.sent); case 3: case "end": return _context5.stop(); } } }, _callee5, this); })); function hasKey(_x7) { return _hasKey.apply(this, arguments); } return hasKey; }() /** * Check whether a key matches what we expect based on the key info * * @param {Uint8Array} key the key to check * @param {object} info the key info * * @return {boolean} whether or not the key matches */ }, { key: "checkKey", value: function () { var _checkKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(key, info) { var _yield$SecretStorage$2, mac; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (!(info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES)) { _context6.next = 12; break; } if (!info.mac) { _context6.next = 9; break; } _context6.next = 4; return SecretStorage._calculateKeyCheck(key, info.iv); case 4: _yield$SecretStorage$2 = _context6.sent; mac = _yield$SecretStorage$2.mac; return _context6.abrupt("return", info.mac.replace(/=+$/g, '') === mac.replace(/=+$/g, '')); case 9: return _context6.abrupt("return", true); case 10: _context6.next = 13; break; case 12: throw new Error("Unknown algorithm"); case 13: case "end": return _context6.stop(); } } }, _callee6); })); function checkKey(_x8, _x9) { return _checkKey.apply(this, arguments); } return checkKey; }() }, { key: "store", /** * Store an encrypted secret on the server * * @param {string} name The name of the secret * @param {string} secret The secret contents. * @param {Array} keys The IDs of the keys to use to encrypt the secret * or null/undefined to use the default key. */ value: function () { var _store = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(name, secret, keys) { var encrypted, defaultKeyId, _iterator, _step, keyId, keyInfo, _keys, _yield$this$_getSecre, _yield$this$_getSecre2, encryption; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: encrypted = {}; if (keys) { _context7.next = 8; break; } _context7.next = 4; return this.getDefaultKeyId(); case 4: defaultKeyId = _context7.sent; if (defaultKeyId) { _context7.next = 7; break; } throw new Error("No keys specified and no default key present"); case 7: keys = [defaultKeyId]; case 8: if (!(keys.length === 0)) { _context7.next = 10; break; } throw new Error("Zero keys given to encrypt with!"); case 10: _iterator = _createForOfIteratorHelper(keys); _context7.prev = 11; _iterator.s(); case 13: if ((_step = _iterator.n()).done) { _context7.next = 35; break; } keyId = _step.value; _context7.next = 17; return this._baseApis.getAccountDataFromServer("m.secret_storage.key." + keyId); case 17: keyInfo = _context7.sent; if (keyInfo) { _context7.next = 20; break; } throw new Error("Unknown key: " + keyId); case 20: if (!(keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES)) { _context7.next = 32; break; } _keys = (0, _defineProperty2["default"])({}, keyId, keyInfo); _context7.next = 24; return this._getSecretStorageKey(_keys, name); case 24: _yield$this$_getSecre = _context7.sent; _yield$this$_getSecre2 = (0, _slicedToArray2["default"])(_yield$this$_getSecre, 2); encryption = _yield$this$_getSecre2[1]; _context7.next = 29; return encryption.encrypt(secret); case 29: encrypted[keyId] = _context7.sent; _context7.next = 33; break; case 32: _logger.logger.warn("unknown algorithm for secret storage key " + keyId + ": " + keyInfo.algorithm); // do nothing if we don't understand the encryption algorithm case 33: _context7.next = 13; break; case 35: _context7.next = 40; break; case 37: _context7.prev = 37; _context7.t0 = _context7["catch"](11); _iterator.e(_context7.t0); case 40: _context7.prev = 40; _iterator.f(); return _context7.finish(40); case 43: _context7.next = 45; return this._baseApis.setAccountData(name, { encrypted: encrypted }); case 45: case "end": return _context7.stop(); } } }, _callee7, this, [[11, 37, 40, 43]]); })); function store(_x10, _x11, _x12) { return _store.apply(this, arguments); } return store; }() /** * Temporary method to fix up existing accounts where secrets * are incorrectly stored without the 'encrypted' level * * @param {string} name The name of the secret * @param {object} secretInfo The account data object * @returns {object} The fixed object or null if no fix was performed */ }, { key: "_fixupStoredSecret", value: function () { var _fixupStoredSecret2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(name, secretInfo) { var keys, hasKey, newData; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: // We assume the secret was only stored passthrough for 1 // key - this was all the broken code supported. keys = Object.keys(secretInfo); if (!(keys.length === 1 && keys[0] !== 'encrypted' && secretInfo[keys[0]].passthrough)) { _context8.next = 13; break; } _context8.next = 4; return this.hasKey(keys[0]); case 4: hasKey = _context8.sent; if (!hasKey) { _context8.next = 13; break; } console.log("Fixing up passthrough secret: " + name); _context8.next = 9; return this.storePassthrough(name, keys[0]); case 9: _context8.next = 11; return this._baseApis.getAccountDataFromServer(name); case 11: newData = _context8.sent; return _context8.abrupt("return", newData); case 13: return _context8.abrupt("return", null); case 14: case "end": return _context8.stop(); } } }, _callee8, this); })); function _fixupStoredSecret(_x13, _x14) { return _fixupStoredSecret2.apply(this, arguments); } return _fixupStoredSecret; }() /** * Get a secret from storage. * * @param {string} name the name of the secret * * @return {string} the contents of the secret */ }, { key: "get", value: function () { var _get = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(name) { var secretInfo, keys, _i, _Object$keys, _keyId, keyInfo, encInfo, keyId, decryption, _yield$this$_getSecre3, _yield$this$_getSecre4, _encInfo; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this._baseApis.getAccountDataFromServer(name); case 2: secretInfo = _context9.sent; if (secretInfo) { _context9.next = 5; break; } return _context9.abrupt("return"); case 5: if (secretInfo.encrypted) { _context9.next = 11; break; } _context9.next = 8; return this._fixupStoredSecret(name, secretInfo); case 8: secretInfo = _context9.sent; if (!(!secretInfo || !secretInfo.encrypted)) { _context9.next = 11; break; } throw new Error("Content is not encrypted!"); case 11: // get possible keys to decrypt keys = {}; _i = 0, _Object$keys = Object.keys(secretInfo.encrypted); case 13: if (!(_i < _Object$keys.length)) { _context9.next = 23; break; } _keyId = _Object$keys[_i]; _context9.next = 17; return this._baseApis.getAccountDataFromServer("m.secret_storage.key." + _keyId); case 17: keyInfo = _context9.sent; encInfo = secretInfo.encrypted[_keyId]; // only use keys we understand the encryption algorithm of if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) { if (encInfo.iv && encInfo.ciphertext && encInfo.mac) { keys[_keyId] = keyInfo; } } case 20: _i++; _context9.next = 13; break; case 23: if (!(Object.keys(keys).length === 0)) { _context9.next = 25; break; } throw new Error("Could not decrypt ".concat(name, " because none of ") + "the keys it is encrypted with are for a supported algorithm"); case 25: _context9.prev = 25; _context9.next = 28; return this._getSecretStorageKey(keys, name); case 28: _yield$this$_getSecre3 = _context9.sent; _yield$this$_getSecre4 = (0, _slicedToArray2["default"])(_yield$this$_getSecre3, 2); keyId = _yield$this$_getSecre4[0]; decryption = _yield$this$_getSecre4[1]; _encInfo = secretInfo.encrypted[keyId]; // We don't actually need the decryption object if it's a passthrough // since we just want to return the key itself. It must be base64 // encoded, since this is how a key would normally be stored. if (!_encInfo.passthrough) { _context9.next = 35; break; } return _context9.abrupt("return", (0, olmlib.encodeBase64)(decryption.get_private_key())); case 35: _context9.next = 37; return decryption.decrypt(_encInfo); case 37: return _context9.abrupt("return", _context9.sent); case 38: _context9.prev = 38; if (decryption && decryption.free) decryption.free(); return _context9.finish(38); case 41: case "end": return _context9.stop(); } } }, _callee9, this, [[25,, 38, 41]]); })); function get(_x15) { return _get.apply(this, arguments); } return get; }() /** * Check if a secret is stored on the server. * * @param {string} name the name of the secret * @param {boolean} checkKey check if the secret is encrypted by a trusted key * * @return {object?} map of key name to key info the secret is encrypted * with, or null if it is not present or not encrypted with a trusted * key */ }, { key: "isStored", value: function () { var _isStored = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(name, checkKey) { var secretInfo, ret, _i2, _Object$keys2, keyId, keyInfo, encInfo; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return this._baseApis.getAccountDataFromServer(name); case 2: secretInfo = _context10.sent; if (secretInfo) { _context10.next = 5; break; } return _context10.abrupt("return", null); case 5: if (secretInfo.encrypted) { _context10.next = 11; break; } _context10.next = 8; return this._fixupStoredSecret(name, secretInfo); case 8: secretInfo = _context10.sent; if (!(!secretInfo || !secretInfo.encrypted)) { _context10.next = 11; break; } return _context10.abrupt("return", null); case 11: if (checkKey === undefined) checkKey = true; ret = {}; // filter secret encryption keys with supported algorithm _i2 = 0, _Object$keys2 = Object.keys(secretInfo.encrypted); case 14: if (!(_i2 < _Object$keys2.length)) { _context10.next = 26; break; } keyId = _Object$keys2[_i2]; _context10.next = 18; return this._baseApis.getAccountDataFromServer("m.secret_storage.key." + keyId); case 18: keyInfo = _context10.sent; if (keyInfo) { _context10.next = 21; break; } return _context10.abrupt("continue", 23); case 21: encInfo = secretInfo.encrypted[keyId]; // only use keys we understand the encryption algorithm of if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) { if (encInfo.iv && encInfo.ciphertext && encInfo.mac) { ret[keyId] = keyInfo; } } case 23: _i2++; _context10.next = 14; break; case 26: return _context10.abrupt("return", Object.keys(ret).length ? ret : null); case 27: case "end": return _context10.stop(); } } }, _callee10, this); })); function isStored(_x16, _x17) { return _isStored.apply(this, arguments); } return isStored; }() /** * Request a secret from another device * * @param {string} name the name of the secret to request * @param {string[]} devices the devices to request the secret from * * @return {string} the contents of the secret */ }, { key: "request", value: function request(name, devices) { var _this3 = this; var requestId = this._baseApis.makeTxnId(); var requestControl = this._requests[requestId] = { name: name, devices: devices }; var promise = new Promise(function (resolve, reject) { requestControl.resolve = resolve; requestControl.reject = reject; }); var cancel = function cancel(reason) { // send cancellation event var cancelData = { action: "request_cancellation", requesting_device_id: _this3._baseApis.deviceId, request_id: requestId }; var toDevice = {}; var _iterator2 = _createForOfIteratorHelper(devices), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var device = _step2.value; toDevice[device] = cancelData; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } _this3._baseApis.sendToDevice("m.secret.request", (0, _defineProperty2["default"])({}, _this3._baseApis.getUserId(), toDevice)); // and reject the promise so that anyone waiting on it will be // notified requestControl.reject(new Error(reason || "Cancelled")); }; // send request to devices var requestData = { name: name, action: "request", requesting_device_id: this._baseApis.deviceId, request_id: requestId }; var toDevice = {}; var _iterator3 = _createForOfIteratorHelper(devices), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var device = _step3.value; toDevice[device] = requestData; } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } _logger.logger.info("Request secret ".concat(name, " from ").concat(devices, ", id ").concat(requestId)); this._baseApis.sendToDevice("m.secret.request", (0, _defineProperty2["default"])({}, this._baseApis.getUserId(), toDevice)); return { request_id: requestId, promise: promise, cancel: cancel }; } }, { key: "_onRequestReceived", value: function () { var _onRequestReceived2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(event) { var sender, content, deviceId, secret, payload, encryptedContent, contentMap; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: sender = event.getSender(); content = event.getContent(); if (!(sender !== this._baseApis.getUserId() || !(content.name && content.action && content.requesting_device_id && content.request_id))) { _context11.next = 4; break; } return _context11.abrupt("return"); case 4: deviceId = content.requesting_device_id; // check if it's a cancel if (!(content.action === "request_cancellation")) { _context11.next = 9; break; } if (this._incomingRequests[deviceId] && this._incomingRequests[deviceId][content.request_id]) { _logger.logger.info("received request cancellation for secret (" + sender + ", " + deviceId + ", " + content.request_id + ")"); this.baseApis.emit("crypto.secrets.requestCancelled", { user_id: sender, device_id: deviceId, request_id: content.request_id }); } _context11.next = 32; break; case 9: if (!(content.action === "request")) { _context11.next = 32; break; } if (!(deviceId === this._baseApis.deviceId)) { _context11.next = 12; break; } return _context11.abrupt("return"); case 12: // check if we have the secret _logger.logger.info("received request for secret (" + sender + ", " + deviceId + ", " + content.request_id + ")"); if (this._cryptoCallbacks.onSecretRequested) { _context11.next = 15; break; } return _context11.abrupt("return"); case 15: _context11.next = 17; return this._cryptoCallbacks.onSecretRequested({ user_id: sender, device_id: deviceId, request_id: content.request_id, name: content.name, device_trust: this._baseApis.checkDeviceTrust(sender, deviceId) }); case 17: secret = _context11.sent; if (!secret) { _context11.next = 31; break; } _logger.logger.info("Preparing ".concat(content.name, " secret for ").concat(deviceId)); payload = { type: "m.secret.send", content: { request_id: content.request_id, secret: secret } }; encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: this._baseApis._crypto._olmDevice.deviceCurve25519Key, ciphertext: {} }; _context11.next = 24; return olmlib.ensureOlmSessionsForDevices(this._baseApis._crypto._olmDevice, this._baseApis, (0, _defineProperty2["default"])({}, sender, [this._baseApis.getStoredDevice(sender, deviceId)])); case 24: _context11.next = 26; return olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this._baseApis.getUserId(), this._baseApis.deviceId, this._baseApis._crypto._olmDevice, sender, this._baseApis.getStoredDevice(sender, deviceId), payload); case 26: contentMap = (0, _defineProperty2["default"])({}, sender, (0, _defineProperty2["default"])({}, deviceId, encryptedContent)); _logger.logger.info("Sending ".concat(content.name, " secret for ").concat(deviceId)); this._baseApis.sendToDevice("m.room.encrypted", contentMap); _context11.next = 32; break; case 31: _logger.logger.info("Request denied for ".concat(content.name, " secret for ").concat(deviceId)); case 32: case "end": return _context11.stop(); } } }, _callee11, this); })); function _onRequestReceived(_x18) { return _onRequestReceived2.apply(this, arguments); } return _onRequestReceived; }() }, { key: "_onSecretReceived", value: function _onSecretReceived(event) { if (event.getSender() !== this._baseApis.getUserId()) { // we shouldn't be receiving secrets from anyone else, so ignore // because someone could be trying to send us bogus data return; } var content = event.getContent(); _logger.logger.log("got secret share for request", content.request_id); var requestControl = this._requests[content.request_id]; if (requestControl) { // make sure that the device that sent it is one of the devices that // we requested from var deviceInfo = this._baseApis._crypto._deviceList.getDeviceByIdentityKey(olmlib.OLM_ALGORITHM, event.getSenderKey()); if (!deviceInfo) { _logger.logger.log("secret share from unknown device with key", event.getSenderKey()); return; } if (!requestControl.devices.includes(deviceInfo.deviceId)) { _logger.logger.log("unsolicited secret share from device", deviceInfo.deviceId); return; } _logger.logger.log("Successfully received secret ".concat(requestControl.name, " ") + "from ".concat(deviceInfo.deviceId)); requestControl.resolve(content.secret); } } }, { key: "_getSecretStorageKey", value: function () { var _getSecretStorageKey2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14(keys, name) { var returned, _returned, keyId, privateKey, decryption; return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: if (this._cryptoCallbacks.getSecretStorageKey) { _context14.next = 2; break; } throw new Error("No getSecretStorageKey callback supplied"); case 2: _context14.next = 4; return this._cryptoCallbacks.getSecretStorageKey({ keys: keys }, name); case 4: returned = _context14.sent; if (returned) { _context14.next = 7; break; } throw new Error("getSecretStorageKey callback returned falsey"); case 7: if (!(returned.length < 2)) { _context14.next = 9; break; } throw new Error("getSecretStorageKey callback returned invalid data"); case 9: _returned = (0, _slicedToArray2["default"])(returned, 2), keyId = _returned[0], privateKey = _returned[1]; if (keys[keyId]) { _context14.next = 12; break; } throw new Error("App returned unknown key from getSecretStorageKey!"); case 12: if (!(keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES)) { _context14.next = 17; break; } decryption = { encrypt: function () { var _encrypt = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(secret) { return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return (0, _aes.encryptAES)(secret, privateKey, name); case 2: return _context12.abrupt("return", _context12.sent); case 3: case "end": return _context12.stop(); } } }, _callee12); })); function encrypt(_x21) { return _encrypt.apply(this, arguments); } return encrypt; }(), decrypt: function () { var _decrypt = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(encInfo) { return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: _context13.next = 2; return (0, _aes.decryptAES)(encInfo, privateKey, name); case 2: return _context13.abrupt("return", _context13.sent); case 3: case "end": return _context13.stop(); } } }, _callee13); })); function decrypt(_x22) { return _decrypt.apply(this, arguments); } return decrypt; }() }; return _context14.abrupt("return", [keyId, decryption]); case 17: throw new Error("Unknown key type: " + keys[keyId].algorithm); case 18: case "end": return _context14.stop(); } } }, _callee14, this); })); function _getSecretStorageKey(_x19, _x20) { return _getSecretStorageKey2.apply(this, arguments); } return _getSecretStorageKey; }() }], [{ key: "_calculateKeyCheck", value: function () { var _calculateKeyCheck2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(key, iv) { return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _context15.next = 2; return (0, _aes.encryptAES)(ZERO_STR, key, "", iv); case 2: return _context15.abrupt("return", _context15.sent); case 3: case "end": return _context15.stop(); } } }, _callee15); })); function _calculateKeyCheck(_x23, _x24) { return _calculateKeyCheck2.apply(this, arguments); } return _calculateKeyCheck; }() }]); return SecretStorage; }(_events.EventEmitter); exports.SecretStorage = SecretStorage; },{"../logger":95,"../randomstring":110,"./aes":67,"./olmlib":75,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"events":36}],67:[function(require,module,exports){ (function (Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptAES = encryptAES; exports.decryptAES = decryptAES; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _utils = require("../utils"); var _olmlib = require("./olmlib"); /* Copyright 2020 The Matrix.org Foundation C.I.C. 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. */ var subtleCrypto = typeof window !== "undefined" && window.crypto ? window.crypto.subtle || window.crypto.webkitSubtle : null; // salt for HKDF, with 8 bytes of zeros var zerosalt = new Uint8Array(8); /** * encrypt a string in Node.js * * @param {string} data the plaintext to encrypt * @param {Uint8Array} key the encryption key to use * @param {string} name the name of the secret * @param {string} ivStr the initialization vector to use */ function encryptNode(_x, _x2, _x3, _x4) { return _encryptNode.apply(this, arguments); } /** * decrypt a string in Node.js * * @param {object} data the encrypted data * @param {string} data.ciphertext the ciphertext in base64 * @param {string} data.iv the initialization vector in base64 * @param {string} data.mac the HMAC in base64 * @param {Uint8Array} key the encryption key to use * @param {string} name the name of the secret */ function _encryptNode() { _encryptNode = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(data, key, name, ivStr) { var crypto, iv, _deriveKeysNode, _deriveKeysNode2, aesKey, hmacKey, cipher, ciphertext, hmac; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: crypto = (0, _utils.getCrypto)(); if (crypto) { _context.next = 3; break; } throw new Error("No usable crypto implementation"); case 3: if (ivStr) { iv = (0, _olmlib.decodeBase64)(ivStr); } else { iv = crypto.randomBytes(16); } // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary // (which would mean we wouldn't be able to decrypt on Android). The loss // of a single bit of iv is a price we have to pay. iv[8] &= 0x7f; _deriveKeysNode = deriveKeysNode(key, name), _deriveKeysNode2 = (0, _slicedToArray2["default"])(_deriveKeysNode, 2), aesKey = _deriveKeysNode2[0], hmacKey = _deriveKeysNode2[1]; cipher = crypto.createCipheriv("aes-256-ctr", aesKey, iv); ciphertext = cipher.update(data, "utf-8", "base64") + cipher["final"]("base64"); hmac = crypto.createHmac("sha256", hmacKey).update(ciphertext, "base64").digest("base64"); return _context.abrupt("return", { iv: (0, _olmlib.encodeBase64)(iv), ciphertext: ciphertext, mac: hmac }); case 10: case "end": return _context.stop(); } } }, _callee); })); return _encryptNode.apply(this, arguments); } function decryptNode(_x5, _x6, _x7) { return _decryptNode.apply(this, arguments); } function _decryptNode() { _decryptNode = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(data, key, name) { var crypto, _deriveKeysNode3, _deriveKeysNode4, aesKey, hmacKey, hmac, decipher; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: crypto = (0, _utils.getCrypto)(); if (crypto) { _context2.next = 3; break; } throw new Error("No usable crypto implementation"); case 3: _deriveKeysNode3 = deriveKeysNode(key, name), _deriveKeysNode4 = (0, _slicedToArray2["default"])(_deriveKeysNode3, 2), aesKey = _deriveKeysNode4[0], hmacKey = _deriveKeysNode4[1]; hmac = crypto.createHmac("sha256", hmacKey).update(data.ciphertext, "base64").digest("base64").replace(/=+$/g, ''); if (!(hmac !== data.mac.replace(/=+$/g, ''))) { _context2.next = 7; break; } throw new Error("Error decrypting secret ".concat(name, ": bad MAC")); case 7: decipher = crypto.createDecipheriv("aes-256-ctr", aesKey, (0, _olmlib.decodeBase64)(data.iv)); return _context2.abrupt("return", decipher.update(data.ciphertext, "base64", "utf-8") + decipher["final"]("utf-8")); case 9: case "end": return _context2.stop(); } } }, _callee2); })); return _decryptNode.apply(this, arguments); } function deriveKeysNode(key, name) { var crypto = (0, _utils.getCrypto)(); var prk = crypto.createHmac("sha256", zerosalt).update(key).digest(); var b = Buffer.alloc(1, 1); var aesKey = crypto.createHmac("sha256", prk).update(name, "utf-8").update(b).digest(); b[0] = 2; var hmacKey = crypto.createHmac("sha256", prk).update(aesKey).update(name, "utf-8").update(b).digest(); return [aesKey, hmacKey]; } /** * encrypt a string in Node.js * * @param {string} data the plaintext to encrypt * @param {Uint8Array} key the encryption key to use * @param {string} name the name of the secret * @param {string} ivStr the initialization vector to use */ function encryptBrowser(_x8, _x9, _x10, _x11) { return _encryptBrowser.apply(this, arguments); } /** * decrypt a string in the browser * * @param {object} data the encrypted data * @param {string} data.ciphertext the ciphertext in base64 * @param {string} data.iv the initialization vector in base64 * @param {string} data.mac the HMAC in base64 * @param {Uint8Array} key the encryption key to use * @param {string} name the name of the secret */ function _encryptBrowser() { _encryptBrowser = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(data, key, name, ivStr) { var iv, _yield$deriveKeysBrow, _yield$deriveKeysBrow2, aesKey, hmacKey, encodedData, ciphertext, hmac; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (ivStr) { iv = (0, _olmlib.decodeBase64)(ivStr); } else { iv = new Uint8Array(16); window.crypto.getRandomValues(iv); } // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary // (which would mean we wouldn't be able to decrypt on Android). The loss // of a single bit of iv is a price we have to pay. iv[8] &= 0x7f; _context3.next = 4; return deriveKeysBrowser(key, name); case 4: _yield$deriveKeysBrow = _context3.sent; _yield$deriveKeysBrow2 = (0, _slicedToArray2["default"])(_yield$deriveKeysBrow, 2); aesKey = _yield$deriveKeysBrow2[0]; hmacKey = _yield$deriveKeysBrow2[1]; encodedData = new TextEncoder().encode(data); _context3.next = 11; return subtleCrypto.encrypt({ name: "AES-CTR", counter: iv, length: 64 }, aesKey, encodedData); case 11: ciphertext = _context3.sent; _context3.next = 14; return subtleCrypto.sign({ name: 'HMAC' }, hmacKey, ciphertext); case 14: hmac = _context3.sent; return _context3.abrupt("return", { iv: (0, _olmlib.encodeBase64)(iv), ciphertext: (0, _olmlib.encodeBase64)(ciphertext), mac: (0, _olmlib.encodeBase64)(hmac) }); case 16: case "end": return _context3.stop(); } } }, _callee3); })); return _encryptBrowser.apply(this, arguments); } function decryptBrowser(_x12, _x13, _x14) { return _decryptBrowser.apply(this, arguments); } function _decryptBrowser() { _decryptBrowser = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(data, key, name) { var _yield$deriveKeysBrow3, _yield$deriveKeysBrow4, aesKey, hmacKey, ciphertext, plaintext; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return deriveKeysBrowser(key, name); case 2: _yield$deriveKeysBrow3 = _context4.sent; _yield$deriveKeysBrow4 = (0, _slicedToArray2["default"])(_yield$deriveKeysBrow3, 2); aesKey = _yield$deriveKeysBrow4[0]; hmacKey = _yield$deriveKeysBrow4[1]; ciphertext = (0, _olmlib.decodeBase64)(data.ciphertext); _context4.next = 9; return subtleCrypto.verify({ name: "HMAC" }, hmacKey, (0, _olmlib.decodeBase64)(data.mac), ciphertext); case 9: if (_context4.sent) { _context4.next = 11; break; } throw new Error("Error decrypting secret ".concat(name, ": bad MAC")); case 11: _context4.next = 13; return subtleCrypto.decrypt({ name: "AES-CTR", counter: (0, _olmlib.decodeBase64)(data.iv), length: 64 }, aesKey, ciphertext); case 13: plaintext = _context4.sent; return _context4.abrupt("return", new TextDecoder().decode(new Uint8Array(plaintext))); case 15: case "end": return _context4.stop(); } } }, _callee4); })); return _decryptBrowser.apply(this, arguments); } function deriveKeysBrowser(_x15, _x16) { return _deriveKeysBrowser.apply(this, arguments); } function _deriveKeysBrowser() { _deriveKeysBrowser = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(key, name) { var hkdfkey, keybits, aesKey, hmacKey, aesProm, hmacProm; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return subtleCrypto.importKey('raw', key, { name: "HKDF" }, false, ["deriveBits"]); case 2: hkdfkey = _context5.sent; _context5.next = 5; return subtleCrypto.deriveBits({ name: "HKDF", salt: zerosalt, info: new TextEncoder().encode(name), hash: "SHA-256" }, hkdfkey, 512); case 5: keybits = _context5.sent; aesKey = keybits.slice(0, 32); hmacKey = keybits.slice(32); aesProm = subtleCrypto.importKey('raw', aesKey, { name: 'AES-CTR' }, false, ['encrypt', 'decrypt']); hmacProm = subtleCrypto.importKey('raw', hmacKey, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign', 'verify']); _context5.next = 12; return Promise.all([aesProm, hmacProm]); case 12: return _context5.abrupt("return", _context5.sent); case 13: case "end": return _context5.stop(); } } }, _callee5); })); return _deriveKeysBrowser.apply(this, arguments); } function encryptAES() { return subtleCrypto ? encryptBrowser.apply(void 0, arguments) : encryptNode.apply(void 0, arguments); } function decryptAES() { return subtleCrypto ? decryptBrowser.apply(void 0, arguments) : decryptNode.apply(void 0, arguments); } }).call(this,require("buffer").Buffer) },{"../utils":123,"./olmlib":75,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"buffer":34}],68:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.registerAlgorithm = registerAlgorithm; exports.UnknownDeviceError = exports.DecryptionError = exports.DecryptionAlgorithm = exports.EncryptionAlgorithm = exports.DECRYPTION_CLASSES = exports.ENCRYPTION_CLASSES = void 0; var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /* Copyright 2016 OpenMarket 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. */ /** * Internal module. Defines the base classes of the encryption implementations * * @module */ /** * map of registered encryption algorithm classes. A map from string to {@link * module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm} class * * @type {Object.} */ var ENCRYPTION_CLASSES = {}; /** * map of registered encryption algorithm classes. Map from string to {@link * module:crypto/algorithms/base.DecryptionAlgorithm|DecryptionAlgorithm} class * * @type {Object.} */ exports.ENCRYPTION_CLASSES = ENCRYPTION_CLASSES; var DECRYPTION_CLASSES = {}; /** * base type for encryption implementations * * @alias module:crypto/algorithms/base.EncryptionAlgorithm * * @param {object} params parameters * @param {string} params.userId The UserID for the local user * @param {string} params.deviceId The identifier for this device. * @param {module:crypto} params.crypto crypto core * @param {module:crypto/OlmDevice} params.olmDevice olm.js wrapper * @param {module:base-apis~MatrixBaseApis} baseApis base matrix api interface * @param {string} params.roomId The ID of the room we will be sending to * @param {object} params.config The body of the m.room.encryption event */ exports.DECRYPTION_CLASSES = DECRYPTION_CLASSES; var EncryptionAlgorithm = /*#__PURE__*/function () { function EncryptionAlgorithm(params) { (0, _classCallCheck2["default"])(this, EncryptionAlgorithm); this._userId = params.userId; this._deviceId = params.deviceId; this._crypto = params.crypto; this._olmDevice = params.olmDevice; this._baseApis = params.baseApis; this._roomId = params.roomId; } /** * Perform any background tasks that can be done before a message is ready to * send, in order to speed up sending of the message. * * @param {module:models/room} room the room the event is in */ (0, _createClass2["default"])(EncryptionAlgorithm, [{ key: "prepareToEncrypt", value: function prepareToEncrypt(room) {} /** * Encrypt a message event * * @method module:crypto/algorithms/base.EncryptionAlgorithm.encryptMessage * @abstract * * @param {module:models/room} room * @param {string} eventType * @param {object} plaintext event content * * @return {Promise} Promise which resolves to the new event body */ /** * Called when the membership of a member of the room changes. * * @param {module:models/event.MatrixEvent} event event causing the change * @param {module:models/room-member} member user whose membership changed * @param {string=} oldMembership previous membership * @public */ }, { key: "onRoomMembership", value: function onRoomMembership(event, member, oldMembership) {} }]); return EncryptionAlgorithm; }(); /** * base type for decryption implementations * * @alias module:crypto/algorithms/base.DecryptionAlgorithm * @param {object} params parameters * @param {string} params.userId The UserID for the local user * @param {module:crypto} params.crypto crypto core * @param {module:crypto/OlmDevice} params.olmDevice olm.js wrapper * @param {module:base-apis~MatrixBaseApis} baseApis base matrix api interface * @param {string=} params.roomId The ID of the room we will be receiving * from. Null for to-device events. */ exports.EncryptionAlgorithm = EncryptionAlgorithm; var DecryptionAlgorithm = /*#__PURE__*/function () { function DecryptionAlgorithm(params) { (0, _classCallCheck2["default"])(this, DecryptionAlgorithm); this._userId = params.userId; this._crypto = params.crypto; this._olmDevice = params.olmDevice; this._baseApis = params.baseApis; this._roomId = params.roomId; } /** * Decrypt an event * * @method module:crypto/algorithms/base.DecryptionAlgorithm#decryptEvent * @abstract * * @param {MatrixEvent} event undecrypted event * * @return {Promise} promise which * resolves once we have finished decrypting. Rejects with an * `algorithms.DecryptionError` if there is a problem decrypting the event. */ /** * Handle a key event * * @method module:crypto/algorithms/base.DecryptionAlgorithm#onRoomKeyEvent * * @param {module:models/event.MatrixEvent} params event key event */ (0, _createClass2["default"])(DecryptionAlgorithm, [{ key: "onRoomKeyEvent", value: function onRoomKeyEvent(params) {} // ignore by default /** * Import a room key * * @param {module:crypto/OlmDevice.MegolmSessionData} session */ }, { key: "importRoomKey", value: function importRoomKey(session) {} // ignore by default /** * Determine if we have the keys necessary to respond to a room key request * * @param {module:crypto~IncomingRoomKeyRequest} keyRequest * @return {Promise} true if we have the keys and could (theoretically) share * them; else false. */ }, { key: "hasKeysForKeyRequest", value: function hasKeysForKeyRequest(keyRequest) { return Promise.resolve(false); } /** * Send the response to a room key request * * @param {module:crypto~IncomingRoomKeyRequest} keyRequest */ }, { key: "shareKeysWithDevice", value: function shareKeysWithDevice(keyRequest) { throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm"); } /** * Retry decrypting all the events from a sender that haven't been * decrypted yet. * * @param {string} senderKey the sender's key */ }, { key: "retryDecryptionFromSender", value: function () { var _retryDecryptionFromSender = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(senderKey) { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: case "end": return _context.stop(); } } }, _callee); })); function retryDecryptionFromSender(_x) { return _retryDecryptionFromSender.apply(this, arguments); } return retryDecryptionFromSender; }() }]); return DecryptionAlgorithm; }(); /** * Exception thrown when decryption fails * * @alias module:crypto/algorithms/base.DecryptionError * @param {string} msg user-visible message describing the problem * * @param {Object=} details key/value pairs reported in the logs but not shown * to the user. * * @extends Error */ exports.DecryptionAlgorithm = DecryptionAlgorithm; var DecryptionError = /*#__PURE__*/function (_Error) { (0, _inherits2["default"])(DecryptionError, _Error); var _super = _createSuper(DecryptionError); function DecryptionError(code, msg, details) { var _this; (0, _classCallCheck2["default"])(this, DecryptionError); _this = _super.call(this, msg); _this.code = code; _this.name = 'DecryptionError'; _this.detailedString = _detailedStringForDecryptionError((0, _assertThisInitialized2["default"])(_this), details); return _this; } return DecryptionError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); exports.DecryptionError = DecryptionError; function _detailedStringForDecryptionError(err, details) { var result = err.name + '[msg: ' + err.message; if (details) { result += ', ' + Object.keys(details).map(function (k) { return k + ': ' + details[k]; }).join(', '); } result += ']'; return result; } /** * Exception thrown specifically when we want to warn the user to consider * the security of their conversation before continuing * * @param {string} msg message describing the problem * @param {Object} devices userId -> {deviceId -> object} * set of unknown devices per user we're warning about * @extends Error */ var UnknownDeviceError = /*#__PURE__*/function (_Error2) { (0, _inherits2["default"])(UnknownDeviceError, _Error2); var _super2 = _createSuper(UnknownDeviceError); function UnknownDeviceError(msg, devices) { var _this2; (0, _classCallCheck2["default"])(this, UnknownDeviceError); _this2 = _super2.call(this, msg); _this2.name = "UnknownDeviceError"; _this2.devices = devices; return _this2; } return UnknownDeviceError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); /** * Registers an encryption/decryption class for a particular algorithm * * @param {string} algorithm algorithm tag to register for * * @param {class} encryptor {@link * module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm} * implementation * * @param {class} decryptor {@link * module:crypto/algorithms/base.DecryptionAlgorithm|DecryptionAlgorithm} * implementation */ exports.UnknownDeviceError = UnknownDeviceError; function registerAlgorithm(algorithm, encryptor, decryptor) { ENCRYPTION_CLASSES[algorithm] = encryptor; DECRYPTION_CLASSES[algorithm] = decryptor; } },{"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/wrapNativeSuper":26,"@babel/runtime/regenerator":27}],69:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); require("./olm"); require("./megolm"); var _base = require("./base"); Object.keys(_base).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _base[key]; } }); }); },{"./base":68,"./megolm":70,"./olm":71}],70:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _logger = require("../../logger"); var utils = _interopRequireWildcard(require("../../utils")); var olmlib = _interopRequireWildcard(require("../olmlib")); var _base = require("./base"); var _OlmDevice = require("../OlmDevice"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * @private * @constructor * * @param {string} sessionId * * @property {string} sessionId * @property {Number} useCount number of times this session has been used * @property {Number} creationTime when the session was created (ms since the epoch) * * @property {object} sharedWithDevices * devices with which we have shared the session key * userId -> {deviceId -> msgindex} */ function OutboundSessionInfo(sessionId) { this.sessionId = sessionId; this.useCount = 0; this.creationTime = new Date().getTime(); this.sharedWithDevices = {}; this.blockedDevicesNotified = {}; } /** * Check if it's time to rotate the session * * @param {Number} rotationPeriodMsgs * @param {Number} rotationPeriodMs * @return {Boolean} */ OutboundSessionInfo.prototype.needsRotation = function (rotationPeriodMsgs, rotationPeriodMs) { var sessionLifetime = new Date().getTime() - this.creationTime; if (this.useCount >= rotationPeriodMsgs || sessionLifetime >= rotationPeriodMs) { _logger.logger.log("Rotating megolm session after " + this.useCount + " messages, " + sessionLifetime + "ms"); return true; } return false; }; OutboundSessionInfo.prototype.markSharedWithDevice = function (userId, deviceId, chainIndex) { if (!this.sharedWithDevices[userId]) { this.sharedWithDevices[userId] = {}; } this.sharedWithDevices[userId][deviceId] = chainIndex; }; OutboundSessionInfo.prototype.markNotifiedBlockedDevice = function (userId, deviceId) { if (!this.blockedDevicesNotified[userId]) { this.blockedDevicesNotified[userId] = {}; } this.blockedDevicesNotified[userId][deviceId] = true; }; /** * Determine if this session has been shared with devices which it shouldn't * have been. * * @param {Object} devicesInRoom userId -> {deviceId -> object} * devices we should shared the session with. * * @return {Boolean} true if we have shared the session with devices which aren't * in devicesInRoom. */ OutboundSessionInfo.prototype.sharedWithTooManyDevices = function (devicesInRoom) { for (var userId in this.sharedWithDevices) { if (!this.sharedWithDevices.hasOwnProperty(userId)) { continue; } if (!devicesInRoom.hasOwnProperty(userId)) { _logger.logger.log("Starting new megolm session because we shared with " + userId); return true; } for (var deviceId in this.sharedWithDevices[userId]) { if (!this.sharedWithDevices[userId].hasOwnProperty(deviceId)) { continue; } if (!devicesInRoom[userId].hasOwnProperty(deviceId)) { _logger.logger.log("Starting new megolm session because we shared with " + userId + ":" + deviceId); return true; } } } }; /** * Megolm encryption implementation * * @constructor * @extends {module:crypto/algorithms/EncryptionAlgorithm} * * @param {object} params parameters, as per * {@link module:crypto/algorithms/EncryptionAlgorithm} */ function MegolmEncryption(params) { (0, utils.polyfillSuper)(this, _base.EncryptionAlgorithm, params); // the most recent attempt to set up a session. This is used to serialise // the session setups, so that we have a race-free view of which session we // are using, and which devices we have shared the keys with. It resolves // with an OutboundSessionInfo (or undefined, for the first message in the // room). this._setupPromise = Promise.resolve(); // Map of outbound sessions by sessions ID. Used if we need a particular // session (the session we're currently using to send is always obtained // using _setupPromise). this._outboundSessions = {}; // default rotation periods this._sessionRotationPeriodMsgs = 100; this._sessionRotationPeriodMs = 7 * 24 * 3600 * 1000; if (params.config.rotation_period_ms !== undefined) { this._sessionRotationPeriodMs = params.config.rotation_period_ms; } if (params.config.rotation_period_msgs !== undefined) { this._sessionRotationPeriodMsgs = params.config.rotation_period_msgs; } } utils.inherits(MegolmEncryption, _base.EncryptionAlgorithm); /** * @private * * @param {Object} devicesInRoom The devices in this room, indexed by user ID * @param {Object} blocked The devices that are blocked, indexed by user ID * @param {boolean} [singleOlmCreationPhase] Only perform one round of olm * session creation * * @return {Promise} Promise which resolves to the * OutboundSessionInfo when setup is complete. */ MegolmEncryption.prototype._ensureOutboundSession = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(devicesInRoom, blocked, singleOlmCreationPhase) { var _this = this; var session, prepareSession, returnSession, prom; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: returnSession = function _returnSession() { return session; }; // takes the previous OutboundSessionInfo, and considers whether to create // a new one. Also shares the key with any (new) devices in the room. // Updates `session` to hold the final OutboundSessionInfo. // // returns a promise which resolves once the keyshare is successful. prepareSession = /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(oldSession) { var shareMap, _i, _Object$entries, _Object$entries$_i, userId, userDevices, _i2, _Object$entries2, _Object$entries2$_i, deviceId, deviceInfo, _key, key, payload, _yield$olmlib$getExis, _yield$olmlib$getExis2, devicesWithoutSession, olmSessions; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: session = oldSession; // need to make a brand new session? if (session && session.needsRotation(_this._sessionRotationPeriodMsgs, _this._sessionRotationPeriodMs)) { _logger.logger.log("Starting new megolm session because we need to rotate."); session = null; } // determine if we have shared with anyone we shouldn't have if (session && session.sharedWithTooManyDevices(devicesInRoom)) { session = null; } if (session) { _context5.next = 10; break; } _logger.logger.log("Starting new megolm session for room ".concat(_this._roomId)); _context5.next = 7; return _this._prepareNewSession(); case 7: session = _context5.sent; _logger.logger.log("Started new megolm session ".concat(session.sessionId, " ") + "for room ".concat(_this._roomId)); _this._outboundSessions[session.sessionId] = session; case 10: // now check if we need to share with any devices shareMap = {}; _i = 0, _Object$entries = Object.entries(devicesInRoom); case 12: if (!(_i < _Object$entries.length)) { _context5.next = 27; break; } _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2), userId = _Object$entries$_i[0], userDevices = _Object$entries$_i[1]; _i2 = 0, _Object$entries2 = Object.entries(userDevices); case 15: if (!(_i2 < _Object$entries2.length)) { _context5.next = 24; break; } _Object$entries2$_i = (0, _slicedToArray2["default"])(_Object$entries2[_i2], 2), deviceId = _Object$entries2$_i[0], deviceInfo = _Object$entries2$_i[1]; _key = deviceInfo.getIdentityKey(); if (!(_key == _this._olmDevice.deviceCurve25519Key)) { _context5.next = 20; break; } return _context5.abrupt("continue", 21); case 20: if (!session.sharedWithDevices[userId] || session.sharedWithDevices[userId][deviceId] === undefined) { shareMap[userId] = shareMap[userId] || []; shareMap[userId].push(deviceInfo); } case 21: _i2++; _context5.next = 15; break; case 24: _i++; _context5.next = 12; break; case 27: key = _this._olmDevice.getOutboundGroupSessionKey(session.sessionId); payload = { type: "m.room_key", content: { algorithm: olmlib.MEGOLM_ALGORITHM, room_id: _this._roomId, session_id: session.sessionId, session_key: key.key, chain_index: key.chain_index } }; _context5.next = 31; return olmlib.getExistingOlmSessions(_this._olmDevice, _this._baseApis, shareMap); case 31: _yield$olmlib$getExis = _context5.sent; _yield$olmlib$getExis2 = (0, _slicedToArray2["default"])(_yield$olmlib$getExis, 2); devicesWithoutSession = _yield$olmlib$getExis2[0]; olmSessions = _yield$olmlib$getExis2[1]; _context5.next = 37; return Promise.all([(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return _this._shareKeyWithOlmSessions(session, key, payload, olmSessions); case 2: case "end": return _context.stop(); } } }, _callee); }))(), (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { var errorDevices, start, failedServers; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: errorDevices = []; // meanwhile, establish olm sessions for devices that we don't // already have a session for, and share keys with them. If // we're doing two phases of olm session creation, use a // shorter timeout when fetching one-time keys for the first // phase. start = Date.now(); failedServers = []; _context3.next = 5; return _this._shareKeyWithDevices(session, key, payload, devicesWithoutSession, errorDevices, singleOlmCreationPhase ? 10000 : 2000, failedServers); case 5: if (!(!singleOlmCreationPhase && Date.now() - start < 10000)) { _context3.next = 9; break; } // perform the second phase of olm session creation if requested, // and if the first phase didn't take too long (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var retryDevices, failedServerMap, _iterator, _step, server, failedDevices, _iterator2, _step2, _step2$value, _userId, _deviceInfo, userHS; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // Retry sending keys to devices that we were unable to establish // an olm session for. This time, we use a longer timeout, but we // do this in the background and don't block anything else while we // do this. We only need to retry users from servers that didn't // respond the first time. retryDevices = {}; failedServerMap = new Set(); _iterator = _createForOfIteratorHelper(failedServers); try { for (_iterator.s(); !(_step = _iterator.n()).done;) { server = _step.value; failedServerMap.add(server); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } failedDevices = []; _iterator2 = _createForOfIteratorHelper(errorDevices); try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { _step2$value = _step2.value, _userId = _step2$value.userId, _deviceInfo = _step2$value.deviceInfo; userHS = _userId.slice(_userId.indexOf(":") + 1); if (failedServerMap.has(userHS)) { retryDevices[_userId] = retryDevices[_userId] || []; retryDevices[_userId].push(_deviceInfo); } else { // if we aren't going to retry, then handle it // as a failed device failedDevices.push({ userId: _userId, deviceInfo: _deviceInfo }); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } _context2.next = 9; return _this._shareKeyWithDevices(session, key, payload, retryDevices, failedDevices, 30000); case 9: _context2.next = 11; return _this._notifyFailedOlmDevices(session, key, failedDevices); case 11: case "end": return _context2.stop(); } } }, _callee2); }))(); _context3.next = 11; break; case 9: _context3.next = 11; return _this._notifyFailedOlmDevices(session, key, errorDevices); case 11: case "end": return _context3.stop(); } } }, _callee3); }))(), (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var blockedMap, _i3, _Object$entries3, _Object$entries3$_i, _userId2, userBlockedDevices, _i4, _Object$entries4, _Object$entries4$_i, _deviceId, device; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: // also, notify blocked devices that they're blocked blockedMap = {}; for (_i3 = 0, _Object$entries3 = Object.entries(blocked); _i3 < _Object$entries3.length; _i3++) { _Object$entries3$_i = (0, _slicedToArray2["default"])(_Object$entries3[_i3], 2), _userId2 = _Object$entries3$_i[0], userBlockedDevices = _Object$entries3$_i[1]; for (_i4 = 0, _Object$entries4 = Object.entries(userBlockedDevices); _i4 < _Object$entries4.length; _i4++) { _Object$entries4$_i = (0, _slicedToArray2["default"])(_Object$entries4[_i4], 2), _deviceId = _Object$entries4$_i[0], device = _Object$entries4$_i[1]; if (!session.blockedDevicesNotified[_userId2] || session.blockedDevicesNotified[_userId2][_deviceId] === undefined) { blockedMap[_userId2] = blockedMap[_userId2] || {}; blockedMap[_userId2][_deviceId] = { device: device }; } } } _context4.next = 4; return _this._notifyBlockedDevices(session, blockedMap); case 4: case "end": return _context4.stop(); } } }, _callee4); }))()]); case 37: case "end": return _context5.stop(); } } }, _callee5); })); return function prepareSession(_x4) { return _ref2.apply(this, arguments); }; }(); // helper which returns the session prepared by prepareSession // first wait for the previous share to complete prom = this._setupPromise.then(prepareSession); // _setupPromise resolves to `session` whether or not the share succeeds this._setupPromise = prom.then(returnSession, returnSession); // but we return a promise which only resolves if the share was successful. return _context6.abrupt("return", prom.then(returnSession)); case 5: case "end": return _context6.stop(); } } }, _callee6, this); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }(); /** * @private * * @return {module:crypto/algorithms/megolm.OutboundSessionInfo} session */ MegolmEncryption.prototype._prepareNewSession = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { var sessionId, key; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: sessionId = this._olmDevice.createOutboundGroupSession(); key = this._olmDevice.getOutboundGroupSessionKey(sessionId); _context7.next = 4; return this._olmDevice.addInboundGroupSession(this._roomId, this._olmDevice.deviceCurve25519Key, [], sessionId, key.key, { ed25519: this._olmDevice.deviceEd25519Key }); case 4: if (this._crypto.backupInfo) { // don't wait for it to complete this._crypto.backupGroupSession(this._roomId, this._olmDevice.deviceCurve25519Key, [], sessionId, key.key)["catch"](function (e) { // This throws if the upload failed, but this is fine // since it will have written it to the db and will retry. _logger.logger.log("Failed to back up megolm session", e); }); } return _context7.abrupt("return", new OutboundSessionInfo(sessionId)); case 6: case "end": return _context7.stop(); } } }, _callee7, this); })); /** * Determines what devices in devicesByUser don't have an olm session as given * in devicemap. * * @private * * @param {object} devicemap the devices that have olm sessions, as returned by * olmlib.ensureOlmSessionsForDevices. * @param {object} devicesByUser a map of user IDs to array of deviceInfo * @param {array} [noOlmDevices] an array to fill with devices that don't have * olm sessions * * @return {array} an array of devices that don't have olm sessions. If * noOlmDevices is specified, then noOlmDevices will be returned. */ MegolmEncryption.prototype._getDevicesWithoutSessions = function (devicemap, devicesByUser, noOlmDevices) { noOlmDevices = noOlmDevices || []; for (var _i5 = 0, _Object$entries5 = Object.entries(devicesByUser); _i5 < _Object$entries5.length; _i5++) { var _Object$entries5$_i = (0, _slicedToArray2["default"])(_Object$entries5[_i5], 2), userId = _Object$entries5$_i[0], devicesToShareWith = _Object$entries5$_i[1]; var sessionResults = devicemap[userId]; var _iterator3 = _createForOfIteratorHelper(devicesToShareWith), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var deviceInfo = _step3.value; var deviceId = deviceInfo.deviceId; var sessionResult = sessionResults[deviceId]; if (!sessionResult.sessionId) { // no session with this device, probably because there // were no one-time keys. noOlmDevices.push({ userId: userId, deviceInfo: deviceInfo }); delete sessionResults[deviceId]; // ensureOlmSessionsForUsers has already done the logging, // so just skip it. continue; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } return noOlmDevices; }; /** * Splits the user device map into multiple chunks to reduce the number of * devices we encrypt to per API call. * * @private * * @param {object} devicesByUser map from userid to list of devices * * @return {array>} the blocked devices, split into chunks */ MegolmEncryption.prototype._splitDevices = function (devicesByUser) { var maxDevicesPerRequest = 20; // use an array where the slices of a content map gets stored var currentSlice = []; var mapSlices = [currentSlice]; for (var _i6 = 0, _Object$entries6 = Object.entries(devicesByUser); _i6 < _Object$entries6.length; _i6++) { var _Object$entries6$_i = (0, _slicedToArray2["default"])(_Object$entries6[_i6], 2), userId = _Object$entries6$_i[0], userDevices = _Object$entries6$_i[1]; for (var _i7 = 0, _Object$values = Object.values(userDevices); _i7 < _Object$values.length; _i7++) { var deviceInfo = _Object$values[_i7]; currentSlice.push({ userId: userId, deviceInfo: deviceInfo.device }); } // We do this in the per-user loop as we prefer that all messages to the // same user end up in the same API call to make it easier for the // server (e.g. only have to send one EDU if a remote user, etc). This // does mean that if a user has many devices we may go over the desired // limit, but its not a hard limit so that is fine. if (currentSlice.length > maxDevicesPerRequest) { // the current slice is filled up. Start inserting into the next slice currentSlice = []; mapSlices.push(currentSlice); } } if (currentSlice.length === 0) { mapSlices.pop(); } return mapSlices; }; /** * @private * * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session * * @param {number} chainIndex current chain index * * @param {object} userDeviceMap * mapping from userId to deviceInfo * * @param {object} payload fields to include in the encrypted payload * * @return {Promise} Promise which resolves once the key sharing * for the given userDeviceMap is generated and has been sent. */ MegolmEncryption.prototype._encryptAndSendKeysToDevices = function (session, chainIndex, userDeviceMap, payload) { var _this2 = this; var contentMap = {}; var promises = []; for (var i = 0; i < userDeviceMap.length; i++) { var encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: this._olmDevice.deviceCurve25519Key, ciphertext: {} }; var val = userDeviceMap[i]; var userId = val.userId; var deviceInfo = val.deviceInfo; var deviceId = deviceInfo.deviceId; if (!contentMap[userId]) { contentMap[userId] = {}; } contentMap[userId][deviceId] = encryptedContent; promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this._userId, this._deviceId, this._olmDevice, userId, deviceInfo, payload)); } return Promise.all(promises).then(function () { // prune out any devices that encryptMessageForDevice could not encrypt for, // in which case it will have just not added anything to the ciphertext object. // There's no point sending messages to devices if we couldn't encrypt to them, // since that's effectively a blank message. for (var _i8 = 0, _Object$keys = Object.keys(contentMap); _i8 < _Object$keys.length; _i8++) { var _userId3 = _Object$keys[_i8]; for (var _i9 = 0, _Object$keys2 = Object.keys(contentMap[_userId3]); _i9 < _Object$keys2.length; _i9++) { var _deviceId2 = _Object$keys2[_i9]; if (Object.keys(contentMap[_userId3][_deviceId2].ciphertext).length === 0) { _logger.logger.log("No ciphertext for device " + _userId3 + ":" + _deviceId2 + ": pruning"); delete contentMap[_userId3][_deviceId2]; } } // No devices left for that user? Strip that too. if (Object.keys(contentMap[_userId3]).length === 0) { _logger.logger.log("Pruned all devices for user " + _userId3); delete contentMap[_userId3]; } } // Is there anything left? if (Object.keys(contentMap).length === 0) { _logger.logger.log("No users left to send to: aborting"); return; } return _this2._baseApis.sendToDevice("m.room.encrypted", contentMap).then(function () { // store that we successfully uploaded the keys of the current slice for (var _i10 = 0, _Object$keys3 = Object.keys(contentMap); _i10 < _Object$keys3.length; _i10++) { var _userId4 = _Object$keys3[_i10]; for (var _i11 = 0, _Object$keys4 = Object.keys(contentMap[_userId4]); _i11 < _Object$keys4.length; _i11++) { var _deviceId3 = _Object$keys4[_i11]; session.markSharedWithDevice(_userId4, _deviceId3, chainIndex); } } }); }); }; /** * @private * * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session * * @param {array} userDeviceMap list of blocked devices to notify * * @param {object} payload fields to include in the notification payload * * @return {Promise} Promise which resolves once the notifications * for the given userDeviceMap is generated and has been sent. */ MegolmEncryption.prototype._sendBlockedNotificationsToDevices = /*#__PURE__*/function () { var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(session, userDeviceMap, payload) { var contentMap, _iterator4, _step4, val, _userId5, blockedInfo, deviceInfo, _deviceId4, message, _i12, _Object$keys5, userId, _i13, _Object$keys6, deviceId; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: contentMap = {}; _iterator4 = _createForOfIteratorHelper(userDeviceMap); try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { val = _step4.value; _userId5 = val.userId; blockedInfo = val.deviceInfo; deviceInfo = blockedInfo.deviceInfo; _deviceId4 = deviceInfo.deviceId; message = Object.assign({}, payload); message.code = blockedInfo.code; message.reason = blockedInfo.reason; if (message.code === "m.no_olm") { delete message.room_id; delete message.session_id; } if (!contentMap[_userId5]) { contentMap[_userId5] = {}; } contentMap[_userId5][_deviceId4] = message; } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } _context8.next = 5; return this._baseApis.sendToDevice("org.matrix.room_key.withheld", contentMap); case 5: // store that we successfully uploaded the keys of the current slice for (_i12 = 0, _Object$keys5 = Object.keys(contentMap); _i12 < _Object$keys5.length; _i12++) { userId = _Object$keys5[_i12]; for (_i13 = 0, _Object$keys6 = Object.keys(contentMap[userId]); _i13 < _Object$keys6.length; _i13++) { deviceId = _Object$keys6[_i13]; session.markNotifiedBlockedDevice(userId, deviceId); } } case 6: case "end": return _context8.stop(); } } }, _callee8, this); })); return function (_x5, _x6, _x7) { return _ref8.apply(this, arguments); }; }(); /** * Re-shares a megolm session key with devices if the key has already been * sent to them. * * @param {string} senderKey The key of the originating device for the session * @param {string} sessionId ID of the outbound session to share * @param {string} userId ID of the user who owns the target device * @param {module:crypto/deviceinfo} device The target device */ MegolmEncryption.prototype.reshareKeyWithDevice = /*#__PURE__*/function () { var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(senderKey, sessionId, userId, device) { var obSessionInfo, sentChainIndex, key, payload, encryptedContent; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: obSessionInfo = this._outboundSessions[sessionId]; if (obSessionInfo) { _context9.next = 4; break; } _logger.logger.debug("megolm session ".concat(sessionId, " not found: not re-sharing keys")); return _context9.abrupt("return"); case 4: if (!(obSessionInfo.sharedWithDevices[userId] === undefined)) { _context9.next = 7; break; } _logger.logger.debug("megolm session ".concat(sessionId, " never shared with user ").concat(userId)); return _context9.abrupt("return"); case 7: sentChainIndex = obSessionInfo.sharedWithDevices[userId][device.deviceId]; if (!(sentChainIndex === undefined)) { _context9.next = 11; break; } _logger.logger.debug("megolm session ID " + sessionId + " never shared with device " + userId + ":" + device.deviceId); return _context9.abrupt("return"); case 11: _context9.next = 13; return this._olmDevice.getInboundGroupSessionKey(this._roomId, senderKey, sessionId, sentChainIndex); case 13: key = _context9.sent; if (key) { _context9.next = 17; break; } _logger.logger.warn("No inbound session key found for megolm ".concat(sessionId, ": not re-sharing keys")); return _context9.abrupt("return"); case 17: _context9.next = 19; return olmlib.ensureOlmSessionsForDevices(this._olmDevice, this._baseApis, (0, _defineProperty2["default"])({}, userId, [device])); case 19: payload = { type: "m.forwarded_room_key", content: { algorithm: olmlib.MEGOLM_ALGORITHM, room_id: this._roomId, session_id: sessionId, session_key: key.key, chain_index: key.chain_index, sender_key: senderKey, sender_claimed_ed25519_key: key.sender_claimed_ed25519_key, forwarding_curve25519_key_chain: key.forwarding_curve25519_key_chain } }; encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: this._olmDevice.deviceCurve25519Key, ciphertext: {} }; _context9.next = 23; return olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this._userId, this._deviceId, this._olmDevice, userId, device, payload); case 23: _context9.next = 25; return this._baseApis.sendToDevice("m.room.encrypted", (0, _defineProperty2["default"])({}, userId, (0, _defineProperty2["default"])({}, device.deviceId, encryptedContent))); case 25: _logger.logger.debug("Re-shared key for megolm session ".concat(sessionId, " ") + "with ".concat(userId, ":").concat(device.deviceId)); case 26: case "end": return _context9.stop(); } } }, _callee9, this); })); return function (_x8, _x9, _x10, _x11) { return _ref9.apply(this, arguments); }; }(); /** * @private * * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session * * @param {object} key the session key as returned by * OlmDevice.getOutboundGroupSessionKey * * @param {object} payload the base to-device message payload for sharing keys * * @param {object} devicesByUser * map from userid to list of devices * * @param {array} errorDevices * array that will be populated with the devices that we can't get an * olm session for * * @param {Number} [otkTimeout] The timeout in milliseconds when requesting * one-time keys for establishing new olm sessions. * * @param {Array} [failedServers] An array to fill with remote servers that * failed to respond to one-time-key requests. */ MegolmEncryption.prototype._shareKeyWithDevices = /*#__PURE__*/function () { var _ref10 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(session, key, payload, devicesByUser, errorDevices, otkTimeout, failedServers) { var devicemap; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return olmlib.ensureOlmSessionsForDevices(this._olmDevice, this._baseApis, devicesByUser, otkTimeout, failedServers); case 2: devicemap = _context10.sent; this._getDevicesWithoutSessions(devicemap, devicesByUser, errorDevices); _context10.next = 6; return this._shareKeyWithOlmSessions(session, key, payload, devicemap); case 6: case "end": return _context10.stop(); } } }, _callee10, this); })); return function (_x12, _x13, _x14, _x15, _x16, _x17, _x18) { return _ref10.apply(this, arguments); }; }(); MegolmEncryption.prototype._shareKeyWithOlmSessions = /*#__PURE__*/function () { var _ref11 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(session, key, payload, devicemap) { var userDeviceMaps, i; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: userDeviceMaps = this._splitDevices(devicemap); i = 0; case 2: if (!(i < userDeviceMaps.length)) { _context11.next = 16; break; } _context11.prev = 3; _context11.next = 6; return this._encryptAndSendKeysToDevices(session, key.chain_index, userDeviceMaps[i], payload); case 6: _logger.logger.log("Completed megolm keyshare for ".concat(session.sessionId, " ") + "in ".concat(this._roomId, " (slice ").concat(i + 1, "/").concat(userDeviceMaps.length, ")")); _context11.next = 13; break; case 9: _context11.prev = 9; _context11.t0 = _context11["catch"](3); _logger.logger.log("megolm keyshare for ".concat(session.sessionId, " in ").concat(this._roomId, " ") + "(slice ".concat(i + 1, "/").concat(userDeviceMaps.length, ") failed")); throw _context11.t0; case 13: i++; _context11.next = 2; break; case 16: case "end": return _context11.stop(); } } }, _callee11, this, [[3, 9]]); })); return function (_x19, _x20, _x21, _x22) { return _ref11.apply(this, arguments); }; }(); /** * Notify devices that we weren't able to create olm sessions. * * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session * * @param {object} key * * @param {Array} failedDevices the devices that we were unable to * create olm sessions for, as returned by _shareKeyWithDevices */ MegolmEncryption.prototype._notifyFailedOlmDevices = /*#__PURE__*/function () { var _ref12 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(session, key, failedDevices) { var _iterator5, _step5, _step5$value, userId, deviceInfo, deviceId, filteredFailedDevices, blockedMap, _iterator6, _step6, _step6$value, _userId7, _deviceInfo2; return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: // mark the devices that failed as "handled" because we don't want to try // to claim a one-time-key for dead devices on every message. _iterator5 = _createForOfIteratorHelper(failedDevices); try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { _step5$value = _step5.value, userId = _step5$value.userId, deviceInfo = _step5$value.deviceInfo; deviceId = deviceInfo.deviceId; session.markSharedWithDevice(userId, deviceId, key.chain_index); } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } _context12.next = 4; return this._olmDevice.filterOutNotifiedErrorDevices(failedDevices); case 4: filteredFailedDevices = _context12.sent; blockedMap = {}; _iterator6 = _createForOfIteratorHelper(filteredFailedDevices); try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { _step6$value = _step6.value, _userId7 = _step6$value.userId, _deviceInfo2 = _step6$value.deviceInfo; blockedMap[_userId7] = blockedMap[_userId7] || {}; // we use a similar format to what // olmlib.ensureOlmSessionsForDevices returns, so that // we can use the same function to split blockedMap[_userId7][_deviceInfo2.deviceId] = { device: { code: "m.no_olm", reason: _OlmDevice.WITHHELD_MESSAGES["m.no_olm"], deviceInfo: _deviceInfo2 } }; } // send the notifications } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } _context12.next = 10; return this._notifyBlockedDevices(session, blockedMap); case 10: case "end": return _context12.stop(); } } }, _callee12, this); })); return function (_x23, _x24, _x25) { return _ref12.apply(this, arguments); }; }(); /** * Notify blocked devices that they have been blocked. * * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session * * @param {object} devicesByUser * map from userid to device ID to blocked data */ MegolmEncryption.prototype._notifyBlockedDevices = /*#__PURE__*/function () { var _ref13 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(session, devicesByUser) { var payload, userDeviceMaps, i; return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: payload = { room_id: this._roomId, session_id: session.sessionId, algorithm: olmlib.MEGOLM_ALGORITHM, sender_key: this._olmDevice.deviceCurve25519Key }; userDeviceMaps = this._splitDevices(devicesByUser); i = 0; case 3: if (!(i < userDeviceMaps.length)) { _context13.next = 17; break; } _context13.prev = 4; _context13.next = 7; return this._sendBlockedNotificationsToDevices(session, userDeviceMaps[i], payload); case 7: _logger.logger.log("Completed blacklist notification for ".concat(session.sessionId, " ") + "in ".concat(this._roomId, " (slice ").concat(i + 1, "/").concat(userDeviceMaps.length, ")")); _context13.next = 14; break; case 10: _context13.prev = 10; _context13.t0 = _context13["catch"](4); _logger.logger.log("blacklist notification for ".concat(session.sessionId, " in ") + "".concat(this._roomId, " (slice ").concat(i + 1, "/").concat(userDeviceMaps.length, ") failed")); throw _context13.t0; case 14: i++; _context13.next = 3; break; case 17: case "end": return _context13.stop(); } } }, _callee13, this, [[4, 10]]); })); return function (_x26, _x27) { return _ref13.apply(this, arguments); }; }(); /** * Perform any background tasks that can be done before a message is ready to * send, in order to speed up sending of the message. * * @param {module:models/room} room the room the event is in */ MegolmEncryption.prototype.prepareToEncrypt = function (room) { var _this3 = this; if (this.encryptionPreparation) { // We're already preparing something, so don't do anything else. // FIXME: check if we need to restart // (https://github.com/matrix-org/matrix-js-sdk/issues/1255) return; } _logger.logger.debug("Preparing to encrypt events for ".concat(this._roomId)); this.encryptionPreparation = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14() { var _yield$_this3$_getDev, _yield$_this3$_getDev2, devicesInRoom, blocked; return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return _this3._getDevicesInRoom(room); case 2: _yield$_this3$_getDev = _context14.sent; _yield$_this3$_getDev2 = (0, _slicedToArray2["default"])(_yield$_this3$_getDev, 2); devicesInRoom = _yield$_this3$_getDev2[0]; blocked = _yield$_this3$_getDev2[1]; if (_this3._crypto.getGlobalErrorOnUnknownDevices()) { // Drop unknown devices for now. When the message gets sent, we'll // throw an error, but we'll still be prepared to send to the known // devices. _this3._removeUnknownDevices(devicesInRoom); } _context14.next = 9; return _this3._ensureOutboundSession(devicesInRoom, blocked, true); case 9: delete _this3.encryptionPreparation; case 10: case "end": return _context14.stop(); } } }, _callee14); }))(); }; /** * @inheritdoc * * @param {module:models/room} room * @param {string} eventType * @param {object} content plaintext event content * * @return {Promise} Promise which resolves to the new event body */ MegolmEncryption.prototype.encryptMessage = /*#__PURE__*/function () { var _ref15 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(room, eventType, content) { var _yield$this$_getDevic, _yield$this$_getDevic2, devicesInRoom, blocked, session, payloadJson, ciphertext, encryptedContent; return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: _logger.logger.log("Starting to encrypt event for ".concat(this._roomId)); if (!this.encryptionPreparation) { _context15.next = 9; break; } _context15.prev = 2; _context15.next = 5; return this.encryptionPreparation; case 5: _context15.next = 9; break; case 7: _context15.prev = 7; _context15.t0 = _context15["catch"](2); case 9: _context15.next = 11; return this._getDevicesInRoom(room); case 11: _yield$this$_getDevic = _context15.sent; _yield$this$_getDevic2 = (0, _slicedToArray2["default"])(_yield$this$_getDevic, 2); devicesInRoom = _yield$this$_getDevic2[0]; blocked = _yield$this$_getDevic2[1]; // check if any of these devices are not yet known to the user. // if so, warn the user so they can verify or ignore. if (this._crypto.getGlobalErrorOnUnknownDevices()) { this._checkForUnknownDevices(devicesInRoom); } _context15.next = 18; return this._ensureOutboundSession(devicesInRoom, blocked); case 18: session = _context15.sent; payloadJson = { room_id: this._roomId, type: eventType, content: content }; ciphertext = this._olmDevice.encryptGroupMessage(session.sessionId, JSON.stringify(payloadJson)); encryptedContent = { algorithm: olmlib.MEGOLM_ALGORITHM, sender_key: this._olmDevice.deviceCurve25519Key, ciphertext: ciphertext, session_id: session.sessionId, // Include our device ID so that recipients can send us a // m.new_device message if they don't have our session key. // XXX: Do we still need this now that m.new_device messages // no longer exist since #483? device_id: this._deviceId }; session.useCount++; return _context15.abrupt("return", encryptedContent); case 24: case "end": return _context15.stop(); } } }, _callee15, this, [[2, 7]]); })); return function (_x28, _x29, _x30) { return _ref15.apply(this, arguments); }; }(); /** * Forces the current outbound group session to be discarded such * that another one will be created next time an event is sent. * * This should not normally be necessary. */ MegolmEncryption.prototype.forceDiscardSession = function () { this._setupPromise = this._setupPromise.then(function () { return null; }); }; /** * Checks the devices we're about to send to and see if any are entirely * unknown to the user. If so, warn the user, and mark them as known to * give the user a chance to go verify them before re-sending this message. * * @param {Object} devicesInRoom userId -> {deviceId -> object} * devices we should shared the session with. */ MegolmEncryption.prototype._checkForUnknownDevices = function (devicesInRoom) { var unknownDevices = {}; Object.keys(devicesInRoom).forEach(function (userId) { Object.keys(devicesInRoom[userId]).forEach(function (deviceId) { var device = devicesInRoom[userId][deviceId]; if (device.isUnverified() && !device.isKnown()) { if (!unknownDevices[userId]) { unknownDevices[userId] = {}; } unknownDevices[userId][deviceId] = device; } }); }); if (Object.keys(unknownDevices).length) { // it'd be kind to pass unknownDevices up to the user in this error throw new _base.UnknownDeviceError("This room contains unknown devices which have not been verified. " + "We strongly recommend you verify them before continuing.", unknownDevices); } }; /** * Remove unknown devices from a set of devices. The devicesInRoom parameter * will be modified. * * @param {Object} devicesInRoom userId -> {deviceId -> object} * devices we should shared the session with. */ MegolmEncryption.prototype._removeUnknownDevices = function (devicesInRoom) { for (var _i14 = 0, _Object$entries7 = Object.entries(devicesInRoom); _i14 < _Object$entries7.length; _i14++) { var _Object$entries7$_i = (0, _slicedToArray2["default"])(_Object$entries7[_i14], 2), userId = _Object$entries7$_i[0], userDevices = _Object$entries7$_i[1]; for (var _i15 = 0, _Object$entries8 = Object.entries(userDevices); _i15 < _Object$entries8.length; _i15++) { var _Object$entries8$_i = (0, _slicedToArray2["default"])(_Object$entries8[_i15], 2), deviceId = _Object$entries8$_i[0], device = _Object$entries8$_i[1]; if (device.isUnverified() && !device.isKnown()) { delete userDevices[deviceId]; } } if (Object.keys(userDevices).length === 0) { delete devicesInRoom[userId]; } } }; /** * Get the list of unblocked devices for all users in the room * * @param {module:models/room} room * * @return {Promise} Promise which resolves to an array whose * first element is a map from userId to deviceId to deviceInfo indicating * the devices that messages should be encrypted to, and whose second * element is a map from userId to deviceId to data indicating the devices * that are in the room but that have been blocked */ MegolmEncryption.prototype._getDevicesInRoom = /*#__PURE__*/function () { var _ref16 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(room) { var members, roomMembers, isBlacklisting, devices, blocked, userId, userDevices, deviceId, deviceTrust, blockedInfo; return _regenerator["default"].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: _context16.next = 2; return room.getEncryptionTargetMembers(); case 2: members = _context16.sent; roomMembers = utils.map(members, function (u) { return u.userId; }); // The global value is treated as a default for when rooms don't specify a value. isBlacklisting = this._crypto.getGlobalBlacklistUnverifiedDevices(); if (typeof room.getBlacklistUnverifiedDevices() === 'boolean') { isBlacklisting = room.getBlacklistUnverifiedDevices(); } // We are happy to use a cached version here: we assume that if we already // have a list of the user's devices, then we already share an e2e room // with them, which means that they will have announced any new devices via // device_lists in their /sync response. This cache should then be maintained // using all the device_lists changes and left fields. // See https://github.com/vector-im/element-web/issues/2305 for details. _context16.next = 8; return this._crypto.downloadKeys(roomMembers, false); case 8: devices = _context16.sent; blocked = {}; // remove any blocked devices _context16.t0 = _regenerator["default"].keys(devices); case 11: if ((_context16.t1 = _context16.t0()).done) { _context16.next = 27; break; } userId = _context16.t1.value; if (devices.hasOwnProperty(userId)) { _context16.next = 15; break; } return _context16.abrupt("continue", 11); case 15: userDevices = devices[userId]; _context16.t2 = _regenerator["default"].keys(userDevices); case 17: if ((_context16.t3 = _context16.t2()).done) { _context16.next = 25; break; } deviceId = _context16.t3.value; if (userDevices.hasOwnProperty(deviceId)) { _context16.next = 21; break; } return _context16.abrupt("continue", 17); case 21: deviceTrust = this._crypto.checkDeviceTrust(userId, deviceId); if (userDevices[deviceId].isBlocked() || !deviceTrust.isVerified() && isBlacklisting) { if (!blocked[userId]) { blocked[userId] = {}; } blockedInfo = userDevices[deviceId].isBlocked() ? { code: "m.blacklisted", reason: _OlmDevice.WITHHELD_MESSAGES["m.blacklisted"] } : { code: "m.unverified", reason: _OlmDevice.WITHHELD_MESSAGES["m.unverified"] }; blockedInfo.deviceInfo = userDevices[deviceId]; blocked[userId][deviceId] = blockedInfo; delete userDevices[deviceId]; } _context16.next = 17; break; case 25: _context16.next = 11; break; case 27: return _context16.abrupt("return", [devices, blocked]); case 28: case "end": return _context16.stop(); } } }, _callee16, this); })); return function (_x31) { return _ref16.apply(this, arguments); }; }(); /** * Megolm decryption implementation * * @constructor * @extends {module:crypto/algorithms/DecryptionAlgorithm} * * @param {object} params parameters, as per * {@link module:crypto/algorithms/DecryptionAlgorithm} */ function MegolmDecryption(params) { (0, utils.polyfillSuper)(this, _base.DecryptionAlgorithm, params); // events which we couldn't decrypt due to unknown sessions / indexes: map from // senderKey|sessionId to Set of MatrixEvents this._pendingEvents = {}; // this gets stubbed out by the unit tests. this.olmlib = olmlib; } utils.inherits(MegolmDecryption, _base.DecryptionAlgorithm); var PROBLEM_DESCRIPTIONS = { no_olm: "The sender was unable to establish a secure channel.", unknown: "The secure channel with the sender was corrupted." }; /** * @inheritdoc * * @param {MatrixEvent} event * * returns a promise which resolves to a * {@link module:crypto~EventDecryptionResult} once we have finished * decrypting, or rejects with an `algorithms.DecryptionError` if there is a * problem decrypting the event. */ MegolmDecryption.prototype.decryptEvent = /*#__PURE__*/function () { var _ref17 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(event) { var content, res, errorCode, problem, problemDescription, payload; return _regenerator["default"].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: content = event.getWireContent(); if (!(!content.sender_key || !content.session_id || !content.ciphertext)) { _context17.next = 3; break; } throw new _base.DecryptionError("MEGOLM_MISSING_FIELDS", "Missing fields in input"); case 3: // we add the event to the pending list *before* we start decryption. // // then, if the key turns up while decryption is in progress (and // decryption fails), we will schedule a retry. // (fixes https://github.com/vector-im/element-web/issues/5001) this._addEventToPendingList(event); _context17.prev = 4; _context17.next = 7; return this._olmDevice.decryptGroupMessage(event.getRoomId(), content.sender_key, content.session_id, content.ciphertext, event.getId(), event.getTs()); case 7: res = _context17.sent; _context17.next = 17; break; case 10: _context17.prev = 10; _context17.t0 = _context17["catch"](4); if (!(_context17.t0.name === "DecryptionError")) { _context17.next = 14; break; } throw _context17.t0; case 14: errorCode = "OLM_DECRYPT_GROUP_MESSAGE_ERROR"; if (_context17.t0 && _context17.t0.message === 'OLM.UNKNOWN_MESSAGE_INDEX') { this._requestKeysForEvent(event); errorCode = 'OLM_UNKNOWN_MESSAGE_INDEX'; } throw new _base.DecryptionError(errorCode, _context17.t0 ? _context17.t0.toString() : "Unknown Error: Error is undefined", { session: content.sender_key + '|' + content.session_id }); case 17: if (!(res === null)) { _context17.next = 27; break; } // We've got a message for a session we don't have. // // (XXX: We might actually have received this key since we started // decrypting, in which case we'll have scheduled a retry, and this // request will be redundant. We could probably check to see if the // event is still in the pending list; if not, a retry will have been // scheduled, so we needn't send out the request here.) this._requestKeysForEvent(event); // See if there was a problem with the olm session at the time the // event was sent. Use a fuzz factor of 2 minutes. _context17.next = 21; return this._olmDevice.sessionMayHaveProblems(content.sender_key, event.getTs() - 120000); case 21: problem = _context17.sent; if (!problem) { _context17.next = 26; break; } problemDescription = PROBLEM_DESCRIPTIONS[problem.type] || PROBLEM_DESCRIPTIONS.unknown; if (problem.fixed) { problemDescription += " Trying to create a new secure channel and re-requesting the keys."; } throw new _base.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", problemDescription, { session: content.sender_key + '|' + content.session_id }); case 26: throw new _base.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", "The sender's device has not sent us the keys for this message.", { session: content.sender_key + '|' + content.session_id }); case 27: // success. We can remove the event from the pending list, if that hasn't // already happened. this._removeEventFromPendingList(event); payload = JSON.parse(res.result); // belt-and-braces check that the room id matches that indicated by the HS // (this is somewhat redundant, since the megolm session is scoped to the // room, so neither the sender nor a MITM can lie about the room_id). if (!(payload.room_id !== event.getRoomId())) { _context17.next = 31; break; } throw new _base.DecryptionError("MEGOLM_BAD_ROOM", "Message intended for room " + payload.room_id); case 31: return _context17.abrupt("return", { clearEvent: payload, senderCurve25519Key: res.senderKey, claimedEd25519Key: res.keysClaimed.ed25519, forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain, untrusted: res.untrusted }); case 32: case "end": return _context17.stop(); } } }, _callee17, this, [[4, 10]]); })); return function (_x32) { return _ref17.apply(this, arguments); }; }(); MegolmDecryption.prototype._requestKeysForEvent = function (event) { var wireContent = event.getWireContent(); var recipients = event.getKeyRequestRecipients(this._userId); this._crypto.requestRoomKey({ room_id: event.getRoomId(), algorithm: wireContent.algorithm, sender_key: wireContent.sender_key, session_id: wireContent.session_id }, recipients); }; /** * Add an event to the list of those awaiting their session keys. * * @private * * @param {module:models/event.MatrixEvent} event */ MegolmDecryption.prototype._addEventToPendingList = function (event) { var content = event.getWireContent(); var senderKey = content.sender_key; var sessionId = content.session_id; if (!this._pendingEvents[senderKey]) { this._pendingEvents[senderKey] = new Map(); } var senderPendingEvents = this._pendingEvents[senderKey]; if (!senderPendingEvents.has(sessionId)) { senderPendingEvents.set(sessionId, new Set()); } senderPendingEvents.get(sessionId).add(event); }; /** * Remove an event from the list of those awaiting their session keys. * * @private * * @param {module:models/event.MatrixEvent} event */ MegolmDecryption.prototype._removeEventFromPendingList = function (event) { var content = event.getWireContent(); var senderKey = content.sender_key; var sessionId = content.session_id; var senderPendingEvents = this._pendingEvents[senderKey]; var pendingEvents = senderPendingEvents && senderPendingEvents.get(sessionId); if (!pendingEvents) { return; } pendingEvents["delete"](event); if (pendingEvents.size === 0) { senderPendingEvents["delete"](senderKey); } if (senderPendingEvents.size === 0) { delete this._pendingEvents[senderKey]; } }; /** * @inheritdoc * * @param {module:models/event.MatrixEvent} event key event */ MegolmDecryption.prototype.onRoomKeyEvent = function (event) { var _this4 = this; var content = event.getContent(); var sessionId = content.session_id; var senderKey = event.getSenderKey(); var forwardingKeyChain = []; var exportFormat = false; var keysClaimed; if (!content.room_id || !sessionId || !content.session_key) { _logger.logger.error("key event is missing fields"); return; } if (!senderKey) { _logger.logger.error("key event has no sender key (not encrypted?)"); return; } if (event.getType() == "m.forwarded_room_key") { exportFormat = true; forwardingKeyChain = content.forwarding_curve25519_key_chain; if (!utils.isArray(forwardingKeyChain)) { forwardingKeyChain = []; } // copy content before we modify it forwardingKeyChain = forwardingKeyChain.slice(); forwardingKeyChain.push(senderKey); senderKey = content.sender_key; if (!senderKey) { _logger.logger.error("forwarded_room_key event is missing sender_key field"); return; } var ed25519Key = content.sender_claimed_ed25519_key; if (!ed25519Key) { _logger.logger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field"); return; } keysClaimed = { ed25519: ed25519Key }; } else { keysClaimed = event.getKeysClaimed(); } return this._olmDevice.addInboundGroupSession(content.room_id, senderKey, forwardingKeyChain, sessionId, content.session_key, keysClaimed, exportFormat).then(function () { // have another go at decrypting events sent with this session. _this4._retryDecryption(senderKey, sessionId).then(function (success) { // cancel any outstanding room key requests for this session. // Only do this if we managed to decrypt every message in the // session, because if we didn't, we leave the other key // requests in the hopes that someone sends us a key that // includes an earlier index. if (success) { _this4._crypto.cancelRoomKeyRequest({ algorithm: content.algorithm, room_id: content.room_id, session_id: content.session_id, sender_key: senderKey }); } }); }).then(function () { if (_this4._crypto.backupInfo) { // don't wait for the keys to be backed up for the server _this4._crypto.backupGroupSession(content.room_id, senderKey, forwardingKeyChain, content.session_id, content.session_key, keysClaimed, exportFormat)["catch"](function (e) { // This throws if the upload failed, but this is fine // since it will have written it to the db and will retry. _logger.logger.log("Failed to back up megolm session", e); }); } })["catch"](function (e) { _logger.logger.error("Error handling m.room_key_event: ".concat(e)); }); }; /** * @inheritdoc * * @param {module:models/event.MatrixEvent} event key event */ MegolmDecryption.prototype.onRoomKeyWithheldEvent = /*#__PURE__*/function () { var _ref18 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18(event) { var content, senderKey, sender, device, encryptedContent; return _regenerator["default"].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: content = event.getContent(); senderKey = content.sender_key; if (!(content.code === "m.no_olm")) { _context18.next = 36; break; } sender = event.getSender(); _logger.logger.warn("".concat(sender, ":").concat(senderKey, " was unable to establish an olm session with us")); // if the sender says that they haven't been able to establish an olm // session, let's proactively establish one // Note: after we record that the olm session has had a problem, we // trigger retrying decryption for all the messages from the sender's // key, so that we can update the error message to indicate the olm // session problem. _context18.next = 7; return this._olmDevice.getSessionIdForDevice(senderKey); case 7: if (!_context18.sent) { _context18.next = 13; break; } // a session has already been established, so we don't need to // create a new one. _logger.logger.debug("New session already created. Not creating a new one."); _context18.next = 11; return this._olmDevice.recordSessionProblem(senderKey, "no_olm", true); case 11: this.retryDecryptionFromSender(senderKey); return _context18.abrupt("return"); case 13: device = this._crypto._deviceList.getDeviceByIdentityKey(content.algorithm, senderKey); if (device) { _context18.next = 24; break; } _context18.next = 17; return this._crypto.downloadKeys([sender], false); case 17: device = this._crypto._deviceList.getDeviceByIdentityKey(content.algorithm, senderKey); if (device) { _context18.next = 24; break; } _logger.logger.info("Couldn't find device for identity key " + senderKey + ": not establishing session"); _context18.next = 22; return this._olmDevice.recordSessionProblem(senderKey, "no_olm", false); case 22: this.retryDecryptionFromSender(senderKey); return _context18.abrupt("return"); case 24: _context18.next = 26; return olmlib.ensureOlmSessionsForDevices(this._olmDevice, this._baseApis, (0, _defineProperty2["default"])({}, sender, [device]), false); case 26: encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: this._olmDevice.deviceCurve25519Key, ciphertext: {} }; _context18.next = 29; return olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this._userId, this._deviceId, this._olmDevice, sender, device, { type: "m.dummy" }); case 29: _context18.next = 31; return this._olmDevice.recordSessionProblem(senderKey, "no_olm", true); case 31: this.retryDecryptionFromSender(senderKey); _context18.next = 34; return this._baseApis.sendToDevice("m.room.encrypted", (0, _defineProperty2["default"])({}, sender, (0, _defineProperty2["default"])({}, device.deviceId, encryptedContent))); case 34: _context18.next = 38; break; case 36: _context18.next = 38; return this._olmDevice.addInboundGroupSessionWithheld(content.room_id, senderKey, content.session_id, content.code, content.reason); case 38: case "end": return _context18.stop(); } } }, _callee18, this); })); return function (_x33) { return _ref18.apply(this, arguments); }; }(); /** * @inheritdoc */ MegolmDecryption.prototype.hasKeysForKeyRequest = function (keyRequest) { var body = keyRequest.requestBody; return this._olmDevice.hasInboundSessionKeys(body.room_id, body.sender_key, body.session_id // TODO: ratchet index ); }; /** * @inheritdoc */ MegolmDecryption.prototype.shareKeysWithDevice = function (keyRequest) { var _this5 = this; var userId = keyRequest.userId; var deviceId = keyRequest.deviceId; var deviceInfo = this._crypto.getStoredDevice(userId, deviceId); var body = keyRequest.requestBody; this.olmlib.ensureOlmSessionsForDevices(this._olmDevice, this._baseApis, (0, _defineProperty2["default"])({}, userId, [deviceInfo])).then(function (devicemap) { var olmSessionResult = devicemap[userId][deviceId]; if (!olmSessionResult.sessionId) { // no session with this device, probably because there // were no one-time keys. // // ensureOlmSessionsForUsers has already done the logging, // so just skip it. return null; } _logger.logger.log("sharing keys for session " + body.sender_key + "|" + body.session_id + " with device " + userId + ":" + deviceId); return _this5._buildKeyForwardingMessage(body.room_id, body.sender_key, body.session_id); }).then(function (payload) { var encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: _this5._olmDevice.deviceCurve25519Key, ciphertext: {} }; return _this5.olmlib.encryptMessageForDevice(encryptedContent.ciphertext, _this5._userId, _this5._deviceId, _this5._olmDevice, userId, deviceInfo, payload).then(function () { var contentMap = (0, _defineProperty2["default"])({}, userId, (0, _defineProperty2["default"])({}, deviceId, encryptedContent)); // TODO: retries return _this5._baseApis.sendToDevice("m.room.encrypted", contentMap); }); }); }; MegolmDecryption.prototype._buildKeyForwardingMessage = /*#__PURE__*/function () { var _ref19 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(roomId, senderKey, sessionId) { var key; return _regenerator["default"].wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: _context19.next = 2; return this._olmDevice.getInboundGroupSessionKey(roomId, senderKey, sessionId); case 2: key = _context19.sent; return _context19.abrupt("return", { type: "m.forwarded_room_key", content: { algorithm: olmlib.MEGOLM_ALGORITHM, room_id: roomId, sender_key: senderKey, sender_claimed_ed25519_key: key.sender_claimed_ed25519_key, session_id: sessionId, session_key: key.key, chain_index: key.chain_index, forwarding_curve25519_key_chain: key.forwarding_curve25519_key_chain } }); case 4: case "end": return _context19.stop(); } } }, _callee19, this); })); return function (_x34, _x35, _x36) { return _ref19.apply(this, arguments); }; }(); /** * @inheritdoc * * @param {module:crypto/OlmDevice.MegolmSessionData} session * @param {object} [opts={}] options for the import * @param {boolean} [opts.untrusted] whether the key should be considered as untrusted * @param {string} [opts.source] where the key came from */ MegolmDecryption.prototype.importRoomKey = function (session) { var _this6 = this; var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this._olmDevice.addInboundGroupSession(session.room_id, session.sender_key, session.forwarding_curve25519_key_chain, session.session_id, session.session_key, session.sender_claimed_keys, true, opts.untrusted ? { untrusted: opts.untrusted } : {}).then(function () { if (_this6._crypto.backupInfo && opts.source !== "backup") { // don't wait for it to complete _this6._crypto.backupGroupSession(session.room_id, session.sender_key, session.forwarding_curve25519_key_chain, session.session_id, session.session_key, session.sender_claimed_keys, true)["catch"](function (e) { // This throws if the upload failed, but this is fine // since it will have written it to the db and will retry. _logger.logger.log("Failed to back up megolm session", e); }); } // have another go at decrypting events sent with this session. _this6._retryDecryption(session.sender_key, session.session_id); }); }; /** * Have another go at decrypting events after we receive a key. Resolves once * decryption has been re-attempted on all events. * * @private * @param {String} senderKey * @param {String} sessionId * * @return {Boolean} whether all messages were successfully decrypted */ MegolmDecryption.prototype._retryDecryption = /*#__PURE__*/function () { var _ref20 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21(senderKey, sessionId) { var _this7 = this; var senderPendingEvents, pending; return _regenerator["default"].wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: senderPendingEvents = this._pendingEvents[senderKey]; if (senderPendingEvents) { _context21.next = 3; break; } return _context21.abrupt("return", true); case 3: pending = senderPendingEvents.get(sessionId); if (pending) { _context21.next = 6; break; } return _context21.abrupt("return", true); case 6: _logger.logger.debug("Retrying decryption on events", (0, _toConsumableArray2["default"])(pending)); _context21.next = 9; return Promise.all((0, _toConsumableArray2["default"])(pending).map( /*#__PURE__*/function () { var _ref21 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(ev) { return _regenerator["default"].wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: _context20.prev = 0; _context20.next = 3; return ev.attemptDecryption(_this7._crypto, true); case 3: _context20.next = 7; break; case 5: _context20.prev = 5; _context20.t0 = _context20["catch"](0); case 7: case "end": return _context20.stop(); } } }, _callee20, null, [[0, 5]]); })); return function (_x39) { return _ref21.apply(this, arguments); }; }())); case 9: return _context21.abrupt("return", !(this._pendingEvents[senderKey] || {})[sessionId]); case 10: case "end": return _context21.stop(); } } }, _callee21, this); })); return function (_x37, _x38) { return _ref20.apply(this, arguments); }; }(); MegolmDecryption.prototype.retryDecryptionFromSender = /*#__PURE__*/function () { var _ref22 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24(senderKey) { var _this8 = this; var senderPendingEvents; return _regenerator["default"].wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: senderPendingEvents = this._pendingEvents[senderKey]; if (senderPendingEvents) { _context24.next = 3; break; } return _context24.abrupt("return", true); case 3: delete this._pendingEvents[senderKey]; _context24.next = 6; return Promise.all((0, _toConsumableArray2["default"])(senderPendingEvents).map( /*#__PURE__*/function () { var _ref24 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23(_ref23) { var _ref25, _sessionId, pending; return _regenerator["default"].wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: _ref25 = (0, _slicedToArray2["default"])(_ref23, 2), _sessionId = _ref25[0], pending = _ref25[1]; _context23.next = 3; return Promise.all((0, _toConsumableArray2["default"])(pending).map( /*#__PURE__*/function () { var _ref26 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22(ev) { return _regenerator["default"].wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: _context22.prev = 0; _context22.next = 3; return ev.attemptDecryption(_this8._crypto); case 3: _context22.next = 7; break; case 5: _context22.prev = 5; _context22.t0 = _context22["catch"](0); case 7: case "end": return _context22.stop(); } } }, _callee22, null, [[0, 5]]); })); return function (_x42) { return _ref26.apply(this, arguments); }; }())); case 3: case "end": return _context23.stop(); } } }, _callee23); })); return function (_x41) { return _ref24.apply(this, arguments); }; }())); case 6: return _context24.abrupt("return", !this._pendingEvents[senderKey]); case 7: case "end": return _context24.stop(); } } }, _callee24, this); })); return function (_x40) { return _ref22.apply(this, arguments); }; }(); (0, _base.registerAlgorithm)(olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption); },{"../../logger":95,"../../utils":123,"../OlmDevice":63,"../olmlib":75,"./base":68,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/toConsumableArray":23,"@babel/runtime/regenerator":27}],71:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _logger = require("../../logger"); var utils = _interopRequireWildcard(require("../../utils")); var olmlib = _interopRequireWildcard(require("../olmlib")); var _deviceinfo = require("../deviceinfo"); var _base = require("./base"); /* Copyright 2016 OpenMarket 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. */ /** * Defines m.olm encryption/decryption * * @module crypto/algorithms/olm */ var DeviceVerification = _deviceinfo.DeviceInfo.DeviceVerification; /** * Olm encryption implementation * * @constructor * @extends {module:crypto/algorithms/EncryptionAlgorithm} * * @param {object} params parameters, as per * {@link module:crypto/algorithms/EncryptionAlgorithm} */ function OlmEncryption(params) { (0, utils.polyfillSuper)(this, _base.EncryptionAlgorithm, params); this._sessionPrepared = false; this._prepPromise = null; } utils.inherits(OlmEncryption, _base.EncryptionAlgorithm); /** * @private * @param {string[]} roomMembers list of currently-joined users in the room * @return {Promise} Promise which resolves when setup is complete */ OlmEncryption.prototype._ensureSession = function (roomMembers) { if (this._prepPromise) { // prep already in progress return this._prepPromise; } if (this._sessionPrepared) { // prep already done return Promise.resolve(); } var self = this; this._prepPromise = self._crypto.downloadKeys(roomMembers).then(function (res) { return self._crypto.ensureOlmSessionsForUsers(roomMembers); }).then(function () { self._sessionPrepared = true; })["finally"](function () { self._prepPromise = null; }); return this._prepPromise; }; /** * @inheritdoc * * @param {module:models/room} room * @param {string} eventType * @param {object} content plaintext event content * * @return {Promise} Promise which resolves to the new event body */ OlmEncryption.prototype.encryptMessage = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(room, eventType, content) { var members, users, self, payloadFields, encryptedContent, promises, i, userId, devices, j, deviceInfo, key; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return room.getEncryptionTargetMembers(); case 2: members = _context.sent; users = utils.map(members, function (u) { return u.userId; }); self = this; _context.next = 7; return this._ensureSession(users); case 7: payloadFields = { room_id: room.roomId, type: eventType, content: content }; encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: self._olmDevice.deviceCurve25519Key, ciphertext: {} }; promises = []; i = 0; case 11: if (!(i < users.length)) { _context.next = 29; break; } userId = users[i]; devices = self._crypto.getStoredDevicesForUser(userId); j = 0; case 15: if (!(j < devices.length)) { _context.next = 26; break; } deviceInfo = devices[j]; key = deviceInfo.getIdentityKey(); if (!(key == self._olmDevice.deviceCurve25519Key)) { _context.next = 20; break; } return _context.abrupt("continue", 23); case 20: if (!(deviceInfo.verified == DeviceVerification.BLOCKED)) { _context.next = 22; break; } return _context.abrupt("continue", 23); case 22: promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, self._userId, self._deviceId, self._olmDevice, userId, deviceInfo, payloadFields)); case 23: ++j; _context.next = 15; break; case 26: ++i; _context.next = 11; break; case 29: _context.next = 31; return Promise.all(promises).then(function () { return encryptedContent; }); case 31: return _context.abrupt("return", _context.sent); case 32: case "end": return _context.stop(); } } }, _callee, this); })); return function (_x, _x2, _x3) { return _ref.apply(this, arguments); }; }(); /** * Olm decryption implementation * * @constructor * @extends {module:crypto/algorithms/DecryptionAlgorithm} * @param {object} params parameters, as per * {@link module:crypto/algorithms/DecryptionAlgorithm} */ function OlmDecryption(params) { (0, utils.polyfillSuper)(this, _base.DecryptionAlgorithm, params); } utils.inherits(OlmDecryption, _base.DecryptionAlgorithm); /** * @inheritdoc * * @param {MatrixEvent} event * * returns a promise which resolves to a * {@link module:crypto~EventDecryptionResult} once we have finished * decrypting. Rejects with an `algorithms.DecryptionError` if there is a * problem decrypting the event. */ OlmDecryption.prototype.decryptEvent = /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(event) { var content, deviceKey, ciphertext, message, payloadString, payload, claimedKeys; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: content = event.getWireContent(); deviceKey = content.sender_key; ciphertext = content.ciphertext; if (ciphertext) { _context2.next = 5; break; } throw new _base.DecryptionError("OLM_MISSING_CIPHERTEXT", "Missing ciphertext"); case 5: if (this._olmDevice.deviceCurve25519Key in ciphertext) { _context2.next = 7; break; } throw new _base.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS", "Not included in recipients"); case 7: message = ciphertext[this._olmDevice.deviceCurve25519Key]; _context2.prev = 8; _context2.next = 11; return this._decryptMessage(deviceKey, message); case 11: payloadString = _context2.sent; _context2.next = 17; break; case 14: _context2.prev = 14; _context2.t0 = _context2["catch"](8); throw new _base.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE", "Bad Encrypted Message", { sender: deviceKey, err: _context2.t0 }); case 17: payload = JSON.parse(payloadString); // check that we were the intended recipient, to avoid unknown-key attack // https://github.com/vector-im/vector-web/issues/2483 if (!(payload.recipient != this._userId)) { _context2.next = 20; break; } throw new _base.DecryptionError("OLM_BAD_RECIPIENT", "Message was intented for " + payload.recipient); case 20: if (!(payload.recipient_keys.ed25519 != this._olmDevice.deviceEd25519Key)) { _context2.next = 22; break; } throw new _base.DecryptionError("OLM_BAD_RECIPIENT_KEY", "Message not intended for this device", { intended: payload.recipient_keys.ed25519, our_key: this._olmDevice.deviceEd25519Key }); case 22: if (!(payload.sender != event.getSender())) { _context2.next = 24; break; } throw new _base.DecryptionError("OLM_FORWARDED_MESSAGE", "Message forwarded from " + payload.sender, { reported_sender: event.getSender() }); case 24: if (!(payload.room_id !== event.getRoomId())) { _context2.next = 26; break; } throw new _base.DecryptionError("OLM_BAD_ROOM", "Message intended for room " + payload.room_id, { reported_room: event.room_id }); case 26: claimedKeys = payload.keys || {}; return _context2.abrupt("return", { clearEvent: payload, senderCurve25519Key: deviceKey, claimedEd25519Key: claimedKeys.ed25519 || null }); case 28: case "end": return _context2.stop(); } } }, _callee2, this, [[8, 14]]); })); return function (_x4) { return _ref2.apply(this, arguments); }; }(); /** * Attempt to decrypt an Olm message * * @param {string} theirDeviceIdentityKey Curve25519 identity key of the sender * @param {object} message message object, with 'type' and 'body' fields * * @return {string} payload, if decrypted successfully. */ OlmDecryption.prototype._decryptMessage = /*#__PURE__*/function () { var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(theirDeviceIdentityKey, message) { var _this = this; var myPromise; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(message.type !== 0)) { _context3.next = 4; break; } return _context3.abrupt("return", this._reallyDecryptMessage(theirDeviceIdentityKey, message)); case 4: myPromise = this._olmDevice._olmPrekeyPromise.then(function () { return _this._reallyDecryptMessage(theirDeviceIdentityKey, message); }); // we want the error, but don't propagate it to the next decryption this._olmDevice._olmPrekeyPromise = myPromise["catch"](function () {}); _context3.next = 8; return myPromise; case 8: return _context3.abrupt("return", _context3.sent); case 9: case "end": return _context3.stop(); } } }, _callee3, this); })); return function (_x5, _x6) { return _ref3.apply(this, arguments); }; }(); OlmDecryption.prototype._reallyDecryptMessage = /*#__PURE__*/function () { var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(theirDeviceIdentityKey, message) { var sessionIds, decryptionErrors, i, sessionId, payload, foundSession, res; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this._olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey); case 2: sessionIds = _context4.sent; // try each session in turn. decryptionErrors = {}; i = 0; case 5: if (!(i < sessionIds.length)) { _context4.next = 26; break; } sessionId = sessionIds[i]; _context4.prev = 7; _context4.next = 10; return this._olmDevice.decryptMessage(theirDeviceIdentityKey, sessionId, message.type, message.body); case 10: payload = _context4.sent; _logger.logger.log("Decrypted Olm message from " + theirDeviceIdentityKey + " with session " + sessionId); return _context4.abrupt("return", payload); case 15: _context4.prev = 15; _context4.t0 = _context4["catch"](7); _context4.next = 19; return this._olmDevice.matchesSession(theirDeviceIdentityKey, sessionId, message.type, message.body); case 19: foundSession = _context4.sent; if (!foundSession) { _context4.next = 22; break; } throw new Error("Error decrypting prekey message with existing session id " + sessionId + ": " + _context4.t0.message); case 22: // otherwise it's probably a message for another session; carry on, but // keep a record of the error decryptionErrors[sessionId] = _context4.t0.message; case 23: i++; _context4.next = 5; break; case 26: if (!(message.type !== 0)) { _context4.next = 30; break; } if (!(sessionIds.length === 0)) { _context4.next = 29; break; } throw new Error("No existing sessions"); case 29: throw new Error("Error decrypting non-prekey message with existing sessions: " + JSON.stringify(decryptionErrors)); case 30: _context4.prev = 30; _context4.next = 33; return this._olmDevice.createInboundSession(theirDeviceIdentityKey, message.type, message.body); case 33: res = _context4.sent; _context4.next = 40; break; case 36: _context4.prev = 36; _context4.t1 = _context4["catch"](30); decryptionErrors["(new)"] = _context4.t1.message; throw new Error("Error decrypting prekey message: " + JSON.stringify(decryptionErrors)); case 40: _logger.logger.log("created new inbound Olm session ID " + res.session_id + " with " + theirDeviceIdentityKey); return _context4.abrupt("return", res.payload); case 42: case "end": return _context4.stop(); } } }, _callee4, this, [[7, 15], [30, 36]]); })); return function (_x7, _x8) { return _ref4.apply(this, arguments); }; }(); (0, _base.registerAlgorithm)(olmlib.OLM_ALGORITHM, OlmEncryption, OlmDecryption); },{"../../logger":95,"../../utils":123,"../deviceinfo":72,"../olmlib":75,"./base":68,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DeviceInfo = DeviceInfo; /* Copyright 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 crypto/deviceinfo */ /** * Information about a user's device * * @constructor * @alias module:crypto/deviceinfo * * @property {string} deviceId the ID of this device * * @property {string[]} algorithms list of algorithms supported by this device * * @property {Object.} keys a map from * <key type>:<id> -> <base64-encoded key>> * * @property {module:crypto/deviceinfo.DeviceVerification} verified * whether the device has been verified/blocked by the user * * @property {boolean} known * whether the user knows of this device's existence (useful when warning * the user that a user has added new devices) * * @property {Object} unsigned additional data from the homeserver * * @param {string} deviceId id of the device */ function DeviceInfo(deviceId) { // you can't change the deviceId Object.defineProperty(this, 'deviceId', { enumerable: true, value: deviceId }); this.algorithms = []; this.keys = {}; this.verified = DeviceVerification.UNVERIFIED; this.known = false; this.unsigned = {}; this.signatures = {}; } /** * rehydrate a DeviceInfo from the session store * * @param {object} obj raw object from session store * @param {string} deviceId id of the device * * @return {module:crypto~DeviceInfo} new DeviceInfo */ DeviceInfo.fromStorage = function (obj, deviceId) { var res = new DeviceInfo(deviceId); for (var prop in obj) { if (obj.hasOwnProperty(prop)) { res[prop] = obj[prop]; } } return res; }; /** * Prepare a DeviceInfo for JSON serialisation in the session store * * @return {object} deviceinfo with non-serialised members removed */ DeviceInfo.prototype.toStorage = function () { return { algorithms: this.algorithms, keys: this.keys, verified: this.verified, known: this.known, unsigned: this.unsigned, signatures: this.signatures }; }; /** * Get the fingerprint for this device (ie, the Ed25519 key) * * @return {string} base64-encoded fingerprint of this device */ DeviceInfo.prototype.getFingerprint = function () { return this.keys["ed25519:" + this.deviceId]; }; /** * Get the identity key for this device (ie, the Curve25519 key) * * @return {string} base64-encoded identity key of this device */ DeviceInfo.prototype.getIdentityKey = function () { return this.keys["curve25519:" + this.deviceId]; }; /** * Get the configured display name for this device, if any * * @return {string?} displayname */ DeviceInfo.prototype.getDisplayName = function () { return this.unsigned.device_display_name || null; }; /** * Returns true if this device is blocked * * @return {Boolean} true if blocked */ DeviceInfo.prototype.isBlocked = function () { return this.verified == DeviceVerification.BLOCKED; }; /** * Returns true if this device is verified * * @return {Boolean} true if verified */ DeviceInfo.prototype.isVerified = function () { return this.verified == DeviceVerification.VERIFIED; }; /** * Returns true if this device is unverified * * @return {Boolean} true if unverified */ DeviceInfo.prototype.isUnverified = function () { return this.verified == DeviceVerification.UNVERIFIED; }; /** * Returns true if the user knows about this device's existence * * @return {Boolean} true if known */ DeviceInfo.prototype.isKnown = function () { return this.known == true; }; /** * @enum */ DeviceInfo.DeviceVerification = { VERIFIED: 1, UNVERIFIED: 0, BLOCKED: -1 }; var DeviceVerification = DeviceInfo.DeviceVerification; },{}],73:[function(require,module,exports){ (function (global,Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.isCryptoAvailable = isCryptoAvailable; exports.Crypto = Crypto; exports.fixBackupKey = fixBackupKey; exports.verificationMethods = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _anotherJson = _interopRequireDefault(require("another-json")); var _events = require("events"); var _ReEmitter = require("../ReEmitter"); var _logger = require("../logger"); var utils = _interopRequireWildcard(require("../utils")); var _OlmDevice = require("./OlmDevice"); var olmlib = _interopRequireWildcard(require("./olmlib")); var _DeviceList = require("./DeviceList"); var _deviceinfo = require("./deviceinfo"); var algorithms = _interopRequireWildcard(require("./algorithms")); var _CrossSigning = require("./CrossSigning"); var _EncryptionSetup = require("./EncryptionSetup"); var _SecretStorage = require("./SecretStorage"); var _OutgoingRoomKeyRequestManager = require("./OutgoingRoomKeyRequestManager"); var _indexeddbCryptoStore = require("./store/indexeddb-crypto-store"); var _QRCode = require("./verification/QRCode"); var _SAS = require("./verification/SAS"); var _key_passphrase = require("./key_passphrase"); var _recoverykey = require("./recoverykey"); var _VerificationRequest = require("./verification/request/VerificationRequest"); var _InRoomChannel = require("./verification/request/InRoomChannel"); var _ToDeviceChannel = require("./verification/request/ToDeviceChannel"); var _IllegalMethod = require("./verification/IllegalMethod"); var _errors = require("../errors"); var _aes = require("./aes"); var _defaultVerificationM; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var DeviceVerification = _deviceinfo.DeviceInfo.DeviceVerification; var defaultVerificationMethods = (_defaultVerificationM = {}, (0, _defineProperty2["default"])(_defaultVerificationM, _QRCode.ReciprocateQRCode.NAME, _QRCode.ReciprocateQRCode), (0, _defineProperty2["default"])(_defaultVerificationM, _SAS.SAS.NAME, _SAS.SAS), (0, _defineProperty2["default"])(_defaultVerificationM, _QRCode.SHOW_QR_CODE_METHOD, _IllegalMethod.IllegalMethod), (0, _defineProperty2["default"])(_defaultVerificationM, _QRCode.SCAN_QR_CODE_METHOD, _IllegalMethod.IllegalMethod), _defaultVerificationM); /** * verification method names */ var verificationMethods = { RECIPROCATE_QR_CODE: _QRCode.ReciprocateQRCode.NAME, SAS: _SAS.SAS.NAME }; exports.verificationMethods = verificationMethods; function isCryptoAvailable() { return Boolean(global.Olm); } var MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000; var KEY_BACKUP_KEYS_PER_REQUEST = 200; /** * Cryptography bits * * This module is internal to the js-sdk; the public API is via MatrixClient. * * @constructor * @alias module:crypto * * @internal * * @param {module:base-apis~MatrixBaseApis} baseApis base matrix api interface * * @param {module:store/session/webstorage~WebStorageSessionStore} sessionStore * Store to be used for end-to-end crypto session data * * @param {string} userId The user ID for the local user * * @param {string} deviceId The identifier for this device. * * @param {Object} clientStore the MatrixClient data store. * * @param {module:crypto/store/base~CryptoStore} cryptoStore * storage for the crypto layer. * * @param {RoomList} roomList An initialised RoomList object * * @param {Array} verificationMethods Array of verification methods to use. * Each element can either be a string from MatrixClient.verificationMethods * or a class that implements a verification method. */ function Crypto(baseApis, sessionStore, userId, deviceId, clientStore, cryptoStore, roomList, verificationMethods) { var _this = this; this._onDeviceListUserCrossSigningUpdated = this._onDeviceListUserCrossSigningUpdated.bind(this); this._trustCrossSignedDevices = true; this._reEmitter = new _ReEmitter.ReEmitter(this); this._baseApis = baseApis; this._sessionStore = sessionStore; this._userId = userId; this._deviceId = deviceId; this._clientStore = clientStore; this._cryptoStore = cryptoStore; this._roomList = roomList; if (verificationMethods) { this._verificationMethods = new Map(); var _iterator = _createForOfIteratorHelper(verificationMethods), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var method = _step.value; if (typeof method === "string") { if (defaultVerificationMethods[method]) { this._verificationMethods.set(method, defaultVerificationMethods[method]); } } else if (method.NAME) { this._verificationMethods.set(method.NAME, method); } else { console.warn("Excluding unknown verification method ".concat(method)); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { this._verificationMethods = defaultVerificationMethods; } // track whether this device's megolm keys are being backed up incrementally // to the server or not. // XXX: this should probably have a single source of truth from OlmAccount this.backupInfo = null; // The info dict from /room_keys/version this.backupKey = null; // The encryption key object this._checkedForBackup = false; // Have we checked the server for a backup we can use? this._sendingBackups = false; // Are we currently sending backups? this._olmDevice = new _OlmDevice.OlmDevice(cryptoStore); this._deviceList = new _DeviceList.DeviceList(baseApis, cryptoStore, this._olmDevice); // XXX: This isn't removed at any point, but then none of the event listeners // this class sets seem to be removed at any point... :/ this._deviceList.on('userCrossSigningUpdated', this._onDeviceListUserCrossSigningUpdated); this._reEmitter.reEmit(this._deviceList, ["crypto.devicesUpdated", "crypto.willUpdateDevices"]); // the last time we did a check for the number of one-time-keys on the // server. this._lastOneTimeKeyCheck = null; this._oneTimeKeyCheckInProgress = false; // EncryptionAlgorithm instance for each room this._roomEncryptors = {}; // map from algorithm to DecryptionAlgorithm instance, for each room this._roomDecryptors = {}; this._supportedAlgorithms = utils.keys(algorithms.DECRYPTION_CLASSES); this._deviceKeys = {}; this._globalBlacklistUnverifiedDevices = false; this._globalErrorOnUnknownDevices = true; this._outgoingRoomKeyRequestManager = new _OutgoingRoomKeyRequestManager.OutgoingRoomKeyRequestManager(baseApis, this._deviceId, this._cryptoStore); // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations // we received in the current sync. this._receivedRoomKeyRequests = []; this._receivedRoomKeyRequestCancellations = []; // true if we are currently processing received room key requests this._processingRoomKeyRequests = false; // controls whether device tracking is delayed // until calling encryptEvent or trackRoomDevices, // or done immediately upon enabling room encryption. this._lazyLoadMembers = false; // in case _lazyLoadMembers is true, // track if an initial tracking of all the room members // has happened for a given room. This is delayed // to avoid loading room members as long as possible. this._roomDeviceTrackingState = {}; // The timestamp of the last time we forced establishment // of a new session for each device, in milliseconds. // { // userId: { // deviceId: 1234567890000, // }, // } this._lastNewSessionForced = {}; this._toDeviceVerificationRequests = new _ToDeviceChannel.ToDeviceRequests(); this._inRoomVerificationRequests = new _InRoomChannel.InRoomRequests(); // This flag will be unset whilst the client processes a sync response // so that we don't start requesting keys until we've actually finished // processing the response. this._sendKeyRequestsImmediately = false; var cryptoCallbacks = this._baseApis._cryptoCallbacks || {}; var cacheCallbacks = (0, _CrossSigning.createCryptoStoreCacheCallbacks)(cryptoStore, this._olmDevice); this._crossSigningInfo = new _CrossSigning.CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks); this._secretStorage = new _SecretStorage.SecretStorage(baseApis, cryptoCallbacks); // Assuming no app-supplied callback, default to getting from SSSS. if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) { cryptoCallbacks.getCrossSigningKey = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(type) { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", _CrossSigning.CrossSigningInfo.getFromSecretStorage(type, _this._secretStorage)); case 1: case "end": return _context.stop(); } } }, _callee); })); return function (_x) { return _ref.apply(this, arguments); }; }(); } } utils.inherits(Crypto, _events.EventEmitter); /** * Initialise the crypto module so that it is ready for use * * Returns a promise which resolves once the crypto module is ready for use. * * @param {Object} opts keyword arguments. * @param {string} opts.exportedOlmDevice (Optional) data from exported device * that must be re-created. */ Crypto.prototype.init = /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(opts) { var _this2 = this; var _ref3, exportedOlmDevice, pickleKey, myDevices, deviceInfo; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _ref3 = opts || {}, exportedOlmDevice = _ref3.exportedOlmDevice, pickleKey = _ref3.pickleKey; _logger.logger.log("Crypto: initialising Olm..."); _context2.next = 4; return global.Olm.init(); case 4: _logger.logger.log(exportedOlmDevice ? "Crypto: initialising Olm device from exported device..." : "Crypto: initialising Olm device..."); _context2.next = 7; return this._olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey: pickleKey }); case 7: _logger.logger.log("Crypto: loading device list..."); _context2.next = 10; return this._deviceList.load(); case 10: // build our device keys: these will later be uploaded this._deviceKeys["ed25519:" + this._deviceId] = this._olmDevice.deviceEd25519Key; this._deviceKeys["curve25519:" + this._deviceId] = this._olmDevice.deviceCurve25519Key; _logger.logger.log("Crypto: fetching own devices..."); myDevices = this._deviceList.getRawStoredDevicesForUser(this._userId); if (!myDevices) { myDevices = {}; } if (!myDevices[this._deviceId]) { // add our own deviceinfo to the cryptoStore _logger.logger.log("Crypto: adding this device to the store..."); deviceInfo = { keys: this._deviceKeys, algorithms: this._supportedAlgorithms, verified: DeviceVerification.VERIFIED, known: true }; myDevices[this._deviceId] = deviceInfo; this._deviceList.storeDevicesForUser(this._userId, myDevices); this._deviceList.saveIfDirty(); } _context2.next = 18; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this2._cryptoStore.getCrossSigningKeys(txn, function (keys) { // can be an empty object after resetting cross-signing keys, see _storeTrustedSelfKeys if (keys && Object.keys(keys).length !== 0) { _logger.logger.log("Loaded cross-signing public keys from crypto store"); _this2._crossSigningInfo.setKeys(keys); } }); }); case 18: // make sure we are keeping track of our own devices // (this is important for key backups & things) this._deviceList.startTrackingDeviceList(this._userId); _logger.logger.log("Crypto: checking for key backup..."); this._checkAndStartKeyBackup(); case 21: case "end": return _context2.stop(); } } }, _callee2, this); })); return function (_x2) { return _ref2.apply(this, arguments); }; }(); /** * Whether to trust a others users signatures of their devices. * If false, devices will only be considered 'verified' if we have * verified that device individually (effectively disabling cross-signing). * * Default: true * * @return {bool} True if trusting cross-signed devices */ Crypto.prototype.getCryptoTrustCrossSignedDevices = function () { return this._trustCrossSignedDevices; }; /** * See getCryptoTrustCrossSignedDevices * This may be set before initCrypto() is called to ensure no races occur. * * @param {bool} val True to trust cross-signed devices */ Crypto.prototype.setCryptoTrustCrossSignedDevices = function (val) { this._trustCrossSignedDevices = val; var _iterator2 = _createForOfIteratorHelper(this._deviceList.getKnownUserIds()), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var userId = _step2.value; var devices = this._deviceList.getRawStoredDevicesForUser(userId); for (var _i = 0, _Object$keys = Object.keys(devices); _i < _Object$keys.length; _i++) { var deviceId = _Object$keys[_i]; var deviceTrust = this.checkDeviceTrust(userId, deviceId); // If the device is locally verified then isVerified() is always true, // so this will only have caused the value to change if the device is // cross-signing verified but not locally verified if (!deviceTrust.isLocallyVerified() && deviceTrust.isCrossSigningVerified()) { var deviceObj = this._deviceList.getStoredDevice(userId, deviceId); this.emit("deviceVerificationChanged", userId, deviceId, deviceObj); } } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } }; /** * Create a recovery key from a user-supplied passphrase. * * @param {string} password Passphrase string that can be entered by the user * when restoring the backup as an alternative to entering the recovery key. * Optional. * @returns {Promise} Object with public key metadata, encoded private * recovery key which should be disposed of after displaying to the user, * and raw private key to avoid round tripping if needed. */ Crypto.prototype.createRecoveryKeyFromPassphrase = /*#__PURE__*/function () { var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(password) { var decryption, keyInfo, derivation, privateKey, encodedPrivateKey; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: decryption = new global.Olm.PkDecryption(); _context3.prev = 1; keyInfo = {}; if (!password) { _context3.next = 11; break; } _context3.next = 6; return (0, _key_passphrase.keyFromPassphrase)(password); case 6: derivation = _context3.sent; keyInfo.passphrase = { algorithm: "m.pbkdf2", iterations: derivation.iterations, salt: derivation.salt }; keyInfo.pubkey = decryption.init_with_private_key(derivation.key); _context3.next = 12; break; case 11: keyInfo.pubkey = decryption.generate_key(); case 12: privateKey = decryption.get_private_key(); encodedPrivateKey = (0, _recoverykey.encodeRecoveryKey)(privateKey); return _context3.abrupt("return", { keyInfo: keyInfo, encodedPrivateKey: encodedPrivateKey, privateKey: privateKey }); case 15: _context3.prev = 15; if (decryption) decryption.free(); return _context3.finish(15); case 18: case "end": return _context3.stop(); } } }, _callee3, null, [[1,, 15, 18]]); })); return function (_x3) { return _ref4.apply(this, arguments); }; }(); /** * Checks whether cross signing: * - is enabled on this account and trusted by this device * - has private keys either cached locally or stored in secret storage * * If this function returns false, bootstrapCrossSigning() can be used * to fix things such that it returns true. That is to say, after * bootstrapCrossSigning() completes successfully, this function should * return true. * * The cross-signing API is currently UNSTABLE and may change without notice. * * @return {bool} True if cross-signing is ready to be used on this device */ Crypto.prototype.isCrossSigningReady = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var publicKeysOnDevice, privateKeysExistSomewhere; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: publicKeysOnDevice = this._crossSigningInfo.getId(); _context4.next = 3; return this._crossSigningInfo.isStoredInKeyCache(); case 3: _context4.t0 = _context4.sent; if (_context4.t0) { _context4.next = 8; break; } _context4.next = 7; return this._crossSigningInfo.isStoredInSecretStorage(this._secretStorage); case 7: _context4.t0 = _context4.sent; case 8: privateKeysExistSomewhere = _context4.t0; return _context4.abrupt("return", !!(publicKeysOnDevice && privateKeysExistSomewhere)); case 10: case "end": return _context4.stop(); } } }, _callee4, this); })); /** * Checks whether secret storage: * - is enabled on this account * - is storing cross-signing private keys * - is storing session backup key (if enabled) * * If this function returns false, bootstrapSecretStorage() can be used * to fix things such that it returns true. That is to say, after * bootstrapSecretStorage() completes successfully, this function should * return true. * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @return {bool} True if secret storage is ready to be used on this device */ Crypto.prototype.isSecretStorageReady = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { var secretStorageKeyInAccount, privateKeysInStorage, sessionBackupInStorage; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this._secretStorage.hasKey(); case 2: secretStorageKeyInAccount = _context5.sent; _context5.next = 5; return this._crossSigningInfo.isStoredInSecretStorage(this._secretStorage); case 5: privateKeysInStorage = _context5.sent; sessionBackupInStorage = !this._baseApis.getKeyBackupEnabled() || this._baseApis.isKeyBackupKeyStored(); return _context5.abrupt("return", !!(secretStorageKeyInAccount && privateKeysInStorage && sessionBackupInStorage)); case 8: case "end": return _context5.stop(); } } }, _callee5, this); })); /** * Bootstrap cross-signing by creating keys if needed. If everything is already * set up, then no changes are made, so this is safe to run to ensure * cross-signing is ready for use. * * This function: * - creates new cross-signing keys if they are not found locally cached nor in * secret storage (if it has been setup) * * The cross-signing API is currently UNSTABLE and may change without notice. * * @param {function} opts.authUploadDeviceSigningKeys Function * called to await an interactive auth flow when uploading device signing keys. * @param {bool} [opts.setupNewCrossSigning] Optional. Reset even if keys * already exist. * Args: * {function} A function that makes the request requiring auth. Receives the * auth data as an object. Can be called multiple times, first with an empty * authDict, to obtain the flows. */ Crypto.prototype.bootstrapCrossSigning = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { var _this3 = this; var _ref8, authUploadDeviceSigningKeys, setupNewCrossSigning, delegateCryptoCallbacks, builder, crossSigningInfo, resetCrossSigning, publicKeysOnDevice, privateKeysInCache, privateKeysInStorage, privateKeysExistSomewhere, crossSigningPrivateKeys, secretStorage, operation, _args7 = arguments; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _ref8 = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {}, authUploadDeviceSigningKeys = _ref8.authUploadDeviceSigningKeys, setupNewCrossSigning = _ref8.setupNewCrossSigning; _logger.logger.log("Bootstrapping cross-signing"); delegateCryptoCallbacks = this._baseApis._cryptoCallbacks; builder = new _EncryptionSetup.EncryptionSetupBuilder(this._baseApis.store.accountData, delegateCryptoCallbacks); crossSigningInfo = new _CrossSigning.CrossSigningInfo(this._userId, builder.crossSigningCallbacks, builder.crossSigningCallbacks); // Reset the cross-signing keys resetCrossSigning = /*#__PURE__*/function () { var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { var device, deviceSignature; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: crossSigningInfo.resetKeys(); // Sign master key with device key _context6.next = 3; return _this3._signObject(crossSigningInfo.keys.master); case 3: // Store auth flow helper function, as we need to call it when uploading // to ensure we handle auth errors properly. builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys); // Cross-sign own device device = _this3._deviceList.getStoredDevice(_this3._userId, _this3._deviceId); _context6.next = 7; return crossSigningInfo.signDevice(_this3._userId, device); case 7: deviceSignature = _context6.sent; builder.addKeySignature(_this3._userId, _this3._deviceId, deviceSignature); // Sign message key backup with cross-signing master key if (!_this3.backupInfo) { _context6.next = 13; break; } _context6.next = 12; return crossSigningInfo.signObject(_this3.backupInfo.auth_data, "master"); case 12: builder.addSessionBackup(_this3.backupInfo); case 13: case "end": return _context6.stop(); } } }, _callee6); })); return function resetCrossSigning() { return _ref9.apply(this, arguments); }; }(); publicKeysOnDevice = this._crossSigningInfo.getId(); _context7.next = 9; return this._crossSigningInfo.isStoredInKeyCache(); case 9: privateKeysInCache = _context7.sent; _context7.next = 12; return this._crossSigningInfo.isStoredInSecretStorage(this._secretStorage); case 12: privateKeysInStorage = _context7.sent; privateKeysExistSomewhere = privateKeysInCache || privateKeysInStorage; // Log all relevant state for easier parsing of debug logs. _logger.logger.log({ setupNewCrossSigning: setupNewCrossSigning, publicKeysOnDevice: publicKeysOnDevice, privateKeysInCache: privateKeysInCache, privateKeysInStorage: privateKeysInStorage, privateKeysExistSomewhere: privateKeysExistSomewhere }); if (!(!privateKeysExistSomewhere || setupNewCrossSigning)) { _context7.next = 21; break; } _logger.logger.log("Cross-signing private keys not found locally or in secret storage, " + "creating new keys"); // If a user has multiple devices, it important to only call bootstrap // as part of some UI flow (and not silently during startup), as they // may have setup cross-signing on a platform which has not saved keys // to secret storage, and this would reset them. In such a case, you // should prompt the user to verify any existing devices first (and // request private keys from those devices) before calling bootstrap. _context7.next = 19; return resetCrossSigning(); case 19: _context7.next = 29; break; case 21: if (!(publicKeysOnDevice && privateKeysInCache)) { _context7.next = 25; break; } _logger.logger.log("Cross-signing public keys trusted and private keys found locally"); _context7.next = 29; break; case 25: if (!privateKeysInStorage) { _context7.next = 29; break; } _logger.logger.log("Cross-signing private keys not found locally, but they are available " + "in secret storage, reading storage and caching locally"); _context7.next = 29; return this.checkOwnCrossSigningTrust(); case 29: // Assuming no app-supplied callback, default to storing new private keys in // secret storage if it exists. If it does not, it is assumed this will be // done as part of setting up secret storage later. crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys; if (!(crossSigningPrivateKeys.size && !this._baseApis._cryptoCallbacks.saveCrossSigningKeys)) { _context7.next = 38; break; } secretStorage = new _SecretStorage.SecretStorage(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks); _context7.next = 34; return secretStorage.hasKey(); case 34: if (!_context7.sent) { _context7.next = 38; break; } _logger.logger.log("Storing new cross-signing private keys in secret storage"); // This is writing to in-memory account data in // builder.accountDataClientAdapter so won't fail _context7.next = 38; return _CrossSigning.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage); case 38: operation = builder.buildOperation(); _context7.next = 41; return operation.apply(this); case 41: _context7.next = 43; return builder.persist(this); case 43: _logger.logger.log("Cross-signing ready"); case 44: case "end": return _context7.stop(); } } }, _callee7, this); })); /** * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is * already set up, then no changes are made, so this is safe to run to ensure secret * storage is ready for use. * * This function * - creates a new Secure Secret Storage key if no default key exists * - if a key backup exists, it is migrated to store the key in the Secret * Storage * - creates a backup if none exists, and one is requested * - migrates Secure Secret Storage to use the latest algorithm, if an outdated * algorithm is found * * The Secure Secret Storage API is currently UNSTABLE and may change without notice. * * @param {function} [opts.createSecretStorageKey] Optional. Function * called to await a secret storage key creation flow. * Returns: * {Promise} Object with public key metadata, encoded private * recovery key which should be disposed of after displaying to the user, * and raw private key to avoid round tripping if needed. * @param {object} [opts.keyBackupInfo] The current key backup object. If passed, * the passphrase and recovery key from this backup will be used. * @param {bool} [opts.setupNewKeyBackup] If true, a new key backup version will be * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo * is supplied. * @param {bool} [opts.setupNewSecretStorage] Optional. Reset even if keys already exist. * @param {func} [opts.getKeyBackupPassphrase] Optional. Function called to get the user's * current key backup passphrase. Should return a promise that resolves with a Buffer * containing the key, or rejects if the key cannot be obtained. * Returns: * {Promise} A promise which resolves to key creation data for * SecretStorage#addKey: an object with `passphrase` and/or `pubkey` fields. */ Crypto.prototype.bootstrapSecretStorage = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11() { var _this4 = this; var _ref11, _ref11$createSecretSt, createSecretStorageKey, keyBackupInfo, setupNewKeyBackup, setupNewSecretStorage, getKeyBackupPassphrase, delegateCryptoCallbacks, builder, secretStorage, newKeyId, createSSSS, ensureCanCheckPassphrase, oldSSSSKey, _ref15, _ref16, oldKeyId, oldKeyInfo, storageExists, _yield$createSecretSt, keyInfo, privateKey, backupKey, opts, crossSigningPrivateKeys, info, _privateKey, data, sessionBackupKey, fixedBackupKey, decodedBackupKey, operation, _args11 = arguments; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _ref11 = _args11.length > 0 && _args11[0] !== undefined ? _args11[0] : {}, _ref11$createSecretSt = _ref11.createSecretStorageKey, createSecretStorageKey = _ref11$createSecretSt === void 0 ? /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: return _context8.abrupt("return", {}); case 1: case "end": return _context8.stop(); } } }, _callee8); })) : _ref11$createSecretSt, keyBackupInfo = _ref11.keyBackupInfo, setupNewKeyBackup = _ref11.setupNewKeyBackup, setupNewSecretStorage = _ref11.setupNewSecretStorage, getKeyBackupPassphrase = _ref11.getKeyBackupPassphrase; _logger.logger.log("Bootstrapping Secure Secret Storage"); delegateCryptoCallbacks = this._baseApis._cryptoCallbacks; builder = new _EncryptionSetup.EncryptionSetupBuilder(this._baseApis.store.accountData, delegateCryptoCallbacks); secretStorage = new _SecretStorage.SecretStorage(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks); // the ID of the new SSSS key, if we create one newKeyId = null; // create a new SSSS key and set it as default createSSSS = /*#__PURE__*/function () { var _ref13 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(opts, privateKey) { var keyId; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: opts = opts || {}; if (privateKey) { opts.key = privateKey; } _context9.next = 4; return secretStorage.addKey(_SecretStorage.SECRET_STORAGE_ALGORITHM_V1_AES, opts); case 4: keyId = _context9.sent; if (privateKey) { // make the private key available to encrypt 4S secrets builder.ssssCryptoCallbacks.addPrivateKey(keyId, privateKey); } _context9.next = 8; return secretStorage.setDefaultKeyId(keyId); case 8: return _context9.abrupt("return", keyId); case 9: case "end": return _context9.stop(); } } }, _callee9); })); return function createSSSS(_x4, _x5) { return _ref13.apply(this, arguments); }; }(); ensureCanCheckPassphrase = /*#__PURE__*/function () { var _ref14 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(keyId, keyInfo) { var key, keyData, _yield$SecretStorage$, iv, mac; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: if (keyInfo.mac) { _context10.next = 16; break; } _context10.next = 3; return _this4._baseApis._cryptoCallbacks.getSecretStorageKey({ keys: (0, _defineProperty2["default"])({}, keyId, keyInfo) }, ""); case 3: key = _context10.sent; if (!key) { _context10.next = 16; break; } keyData = key[1]; builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyData); _context10.next = 9; return _SecretStorage.SecretStorage._calculateKeyCheck(keyData); case 9: _yield$SecretStorage$ = _context10.sent; iv = _yield$SecretStorage$.iv; mac = _yield$SecretStorage$.mac; keyInfo.iv = iv; keyInfo.mac = mac; _context10.next = 16; return builder.setAccountData("m.secret_storage.key.".concat(keyId), keyInfo); case 16: case "end": return _context10.stop(); } } }, _callee10); })); return function ensureCanCheckPassphrase(_x6, _x7) { return _ref14.apply(this, arguments); }; }(); _context11.next = 10; return this.getSecretStorageKey(); case 10: oldSSSSKey = _context11.sent; _ref15 = oldSSSSKey || [null, null], _ref16 = (0, _slicedToArray2["default"])(_ref15, 2), oldKeyId = _ref16[0], oldKeyInfo = _ref16[1]; storageExists = !setupNewSecretStorage && oldKeyInfo && oldKeyInfo.algorithm === _SecretStorage.SECRET_STORAGE_ALGORITHM_V1_AES; // Log all relevant state for easier parsing of debug logs. _logger.logger.log({ keyBackupInfo: keyBackupInfo, setupNewKeyBackup: setupNewKeyBackup, setupNewSecretStorage: setupNewSecretStorage, storageExists: storageExists, oldKeyInfo: oldKeyInfo }); if (!(!storageExists && !keyBackupInfo)) { _context11.next = 26; break; } // either we don't have anything, or we've been asked to restart // from scratch _logger.logger.log("Secret storage does not exist, creating new storage key"); // if we already have a usable default SSSS key and aren't resetting // SSSS just use it. otherwise, create a new one // Note: we leave the old SSSS key in place: there could be other // secrets using it, in theory. We could move them to the new key but a) // that would mean we'd need to prompt for the old passphrase, and b) // it's not clear that would be the right thing to do anyway. _context11.next = 18; return createSecretStorageKey(); case 18: _yield$createSecretSt = _context11.sent; keyInfo = _yield$createSecretSt.keyInfo; privateKey = _yield$createSecretSt.privateKey; _context11.next = 23; return createSSSS(keyInfo, privateKey); case 23: newKeyId = _context11.sent; _context11.next = 57; break; case 26: if (!(!storageExists && keyBackupInfo)) { _context11.next = 53; break; } // we have an existing backup, but no SSSS _logger.logger.log("Secret storage does not exist, using key backup key"); // if we have the backup key already cached, use it; otherwise use the // callback to prompt for the key _context11.next = 30; return this.getSessionBackupPrivateKey(); case 30: _context11.t0 = _context11.sent; if (_context11.t0) { _context11.next = 35; break; } _context11.next = 34; return getKeyBackupPassphrase(); case 34: _context11.t0 = _context11.sent; case 35: backupKey = _context11.t0; // create a new SSSS key and use the backup key as the new SSSS key opts = {}; if (keyBackupInfo.auth_data.private_key_salt && keyBackupInfo.auth_data.private_key_iterations) { opts.passphrase = { algorithm: "m.pbkdf2", iterations: keyBackupInfo.auth_data.private_key_iterations, salt: keyBackupInfo.auth_data.private_key_salt, bits: 256 }; } _context11.next = 40; return createSSSS(opts, backupKey); case 40: newKeyId = _context11.sent; _context11.next = 43; return secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(backupKey), [newKeyId]); case 43: if (!(this._crossSigningInfo.getId() && this._crossSigningInfo.isStoredInKeyCache("master"))) { _context11.next = 49; break; } _logger.logger.log("Adding cross-signing signature to key backup"); _context11.next = 47; return this._crossSigningInfo.signObject(keyBackupInfo.auth_data, "master"); case 47: _context11.next = 50; break; case 49: _logger.logger.warn("Cross-signing keys not available, skipping signature on key backup"); case 50: builder.addSessionBackup(keyBackupInfo); _context11.next = 57; break; case 53: // 4S is already set up _logger.logger.log("Secret storage exists"); if (!(oldKeyInfo && oldKeyInfo.algorithm === _SecretStorage.SECRET_STORAGE_ALGORITHM_V1_AES)) { _context11.next = 57; break; } _context11.next = 57; return ensureCanCheckPassphrase(oldKeyId, oldKeyInfo); case 57: _context11.t2 = !this._baseApis._cryptoCallbacks.saveCrossSigningKeys; if (!_context11.t2) { _context11.next = 62; break; } _context11.next = 61; return this.isCrossSigningReady(); case 61: _context11.t2 = _context11.sent; case 62: _context11.t1 = _context11.t2; if (!_context11.t1) { _context11.next = 70; break; } _context11.t3 = newKeyId; if (_context11.t3) { _context11.next = 69; break; } _context11.next = 68; return this._crossSigningInfo.isStoredInSecretStorage(secretStorage); case 68: _context11.t3 = !_context11.sent; case 69: _context11.t1 = _context11.t3; case 70: if (!_context11.t1) { _context11.next = 77; break; } _logger.logger.log("Copying cross-signing private keys from cache to secret storage"); _context11.next = 74; return this._crossSigningInfo.getCrossSigningKeysFromCache(); case 74: crossSigningPrivateKeys = _context11.sent; _context11.next = 77; return _CrossSigning.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage); case 77: if (!(setupNewKeyBackup && !keyBackupInfo)) { _context11.next = 96; break; } _logger.logger.log("Creating new message key backup version"); _context11.next = 81; return this._baseApis.prepareKeyBackupVersion(null /* random key */ , // don't write to secret storage, as it will write to this._secretStorage. // Here, we want to capture all the side-effects of bootstrapping, // and want to write to the local secretStorage object { secureSecretStorage: false }); case 81: info = _context11.sent; // write the key ourselves to 4S _privateKey = (0, _recoverykey.decodeRecoveryKey)(info.recovery_key); _context11.next = 85; return secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(_privateKey)); case 85: // create keyBackupInfo object to add to builder data = { algorithm: info.algorithm, auth_data: info.auth_data }; if (!(this._crossSigningInfo.getId() && this._crossSigningInfo.isStoredInKeyCache("master"))) { _context11.next = 92; break; } // sign with cross-sign master key _logger.logger.log("Adding cross-signing signature to key backup"); _context11.next = 90; return this._crossSigningInfo.signObject(data.auth_data, "master"); case 90: _context11.next = 93; break; case 92: _logger.logger.warn("Cross-signing keys not available, skipping signature on key backup"); case 93: _context11.next = 95; return this._signObject(data.auth_data); case 95: builder.addSessionBackup(data); case 96: _context11.next = 98; return secretStorage.get('m.megolm_backup.v1'); case 98: sessionBackupKey = _context11.sent; if (!sessionBackupKey) { _context11.next = 108; break; } _logger.logger.info("Got session backup key from secret storage: caching"); // fix up the backup key if it's in the wrong format, and replace // in secret storage fixedBackupKey = fixBackupKey(sessionBackupKey); if (!fixedBackupKey) { _context11.next = 105; break; } _context11.next = 105; return secretStorage.store("m.megolm_backup.v1", fixedBackupKey, [newKeyId || oldKeyId]); case 105: decodedBackupKey = new Uint8Array(olmlib.decodeBase64(fixedBackupKey || sessionBackupKey)); _context11.next = 108; return builder.addSessionBackupPrivateKeyToCache(decodedBackupKey); case 108: operation = builder.buildOperation(); _context11.next = 111; return operation.apply(this); case 111: _context11.next = 113; return builder.persist(this); case 113: _logger.logger.log("Secure Secret Storage ready"); case 114: case "end": return _context11.stop(); } } }, _callee11, this); })); /** * Fix up the backup key, that may be in the wrong format due to a bug in a * migration step. Some backup keys were stored as a comma-separated list of * integers, rather than a base64-encoded byte array. If this function is * passed a string that looks like a list of integers rather than a base64 * string, it will attempt to convert it to the right format. * * @param {string} key the key to check * @returns {null | string} If the key is in the wrong format, then the fixed * key will be returned. Otherwise null will be returned. * */ function fixBackupKey(key) { if (typeof key !== "string" || key.indexOf(",") < 0) { return null; } var fixedKey = Uint8Array.from(key.split(","), function (x) { return parseInt(x); }); return olmlib.encodeBase64(fixedKey); } Crypto.prototype.addSecretStorageKey = function (algorithm, opts, keyID) { return this._secretStorage.addKey(algorithm, opts, keyID); }; Crypto.prototype.hasSecretStorageKey = function (keyID) { return this._secretStorage.hasKey(keyID); }; Crypto.prototype.getSecretStorageKey = function (keyID) { return this._secretStorage.getKey(keyID); }; Crypto.prototype.storeSecret = function (name, secret, keys) { return this._secretStorage.store(name, secret, keys); }; Crypto.prototype.getSecret = function (name) { return this._secretStorage.get(name); }; Crypto.prototype.isSecretStored = function (name, checkKey) { return this._secretStorage.isStored(name, checkKey); }; Crypto.prototype.requestSecret = function (name, devices) { if (!devices) { devices = Object.keys(this._deviceList.getRawStoredDevicesForUser(this._userId)); } return this._secretStorage.request(name, devices); }; Crypto.prototype.getDefaultSecretStorageKeyId = function () { return this._secretStorage.getDefaultKeyId(); }; Crypto.prototype.setDefaultSecretStorageKeyId = function (k) { return this._secretStorage.setDefaultKeyId(k); }; Crypto.prototype.checkSecretStorageKey = function (key, info) { return this._secretStorage.checkKey(key, info); }; /** * Checks that a given secret storage private key matches a given public key. * This can be used by the getSecretStorageKey callback to verify that the * private key it is about to supply is the one that was requested. * * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ Crypto.prototype.checkSecretStoragePrivateKey = function (privateKey, expectedPublicKey) { var decryption = null; try { decryption = new global.Olm.PkDecryption(); var gotPubkey = decryption.init_with_private_key(privateKey); // make sure it agrees with the given pubkey return gotPubkey === expectedPublicKey; } finally { if (decryption) decryption.free(); } }; /** * Fetches the backup private key, if cached * @returns {Promise} the key, if any, or null */ Crypto.prototype.getSessionBackupPrivateKey = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12() { var _this5 = this; var key, pickleKey, decrypted; return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return new Promise(function (resolve) { _this5._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this5._cryptoStore.getSecretStorePrivateKey(txn, resolve, "m.megolm_backup.v1"); }); }); case 2: key = _context12.sent; if (!(key && typeof key === "string")) { _context12.next = 7; break; } key = new Uint8Array(olmlib.decodeBase64(fixBackupKey(key) || key)); _context12.next = 7; return this.storeSessionBackupPrivateKey(key); case 7: if (!(key && key.ciphertext)) { _context12.next = 13; break; } pickleKey = Buffer.from(this._olmDevice._pickleKey); _context12.next = 11; return (0, _aes.decryptAES)(key, pickleKey, "m.megolm_backup.v1"); case 11: decrypted = _context12.sent; key = olmlib.decodeBase64(decrypted); case 13: return _context12.abrupt("return", key); case 14: case "end": return _context12.stop(); } } }, _callee12, this); })); /** * Stores the session backup key to the cache * @param {Uint8Array} key the private key * @returns {Promise} so you can catch failures */ Crypto.prototype.storeSessionBackupPrivateKey = /*#__PURE__*/function () { var _ref18 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(key) { var _this6 = this; var pickleKey; return _regenerator["default"].wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: if (key instanceof Uint8Array) { _context13.next = 2; break; } throw new Error("storeSessionBackupPrivateKey expects Uint8Array, got ".concat(key)); case 2: pickleKey = Buffer.from(this._olmDevice._pickleKey); _context13.next = 5; return (0, _aes.encryptAES)(olmlib.encodeBase64(key), pickleKey, "m.megolm_backup.v1"); case 5: key = _context13.sent; return _context13.abrupt("return", this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this6._cryptoStore.storeSecretStorePrivateKey(txn, "m.megolm_backup.v1", key); })); case 7: case "end": return _context13.stop(); } } }, _callee13, this); })); return function (_x8) { return _ref18.apply(this, arguments); }; }(); /** * Checks that a given cross-signing private key matches a given public key. * This can be used by the getCrossSigningKey callback to verify that the * private key it is about to supply is the one that was requested. * * @param {Uint8Array} privateKey The private key * @param {string} expectedPublicKey The public key * @returns {boolean} true if the key matches, otherwise false */ Crypto.prototype.checkCrossSigningPrivateKey = function (privateKey, expectedPublicKey) { var signing = null; try { signing = new global.Olm.PkSigning(); var gotPubkey = signing.init_with_seed(privateKey); // make sure it agrees with the given pubkey return gotPubkey === expectedPublicKey; } finally { if (signing) signing.free(); } }; /** * Run various follow-up actions after cross-signing keys have changed locally * (either by resetting the keys for the account or by getting them from secret * storage), such as signing the current device, upgrading device * verifications, etc. */ Crypto.prototype._afterCrossSigningLocalKeyChange = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14() { var _this7 = this; var device, signedDevice, upload, shouldUpgradeCb, users, _i2, _Object$entries, _Object$entries$_i, userId, crossSigningInfo, upgradeInfo, usersToUpgrade, _iterator3, _step3, _userId; return _regenerator["default"].wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _logger.logger.info("Starting cross-signing key change post-processing"); // sign the current device with the new key, and upload to the server device = this._deviceList.getStoredDevice(this._userId, this._deviceId); _context14.next = 4; return this._crossSigningInfo.signDevice(this._userId, device); case 4: signedDevice = _context14.sent; _logger.logger.info("Starting background key sig upload for ".concat(this._deviceId)); upload = function upload(_ref20) { var shouldEmit = _ref20.shouldEmit; return _this7._baseApis.uploadKeySignatures((0, _defineProperty2["default"])({}, _this7._userId, (0, _defineProperty2["default"])({}, _this7._deviceId, signedDevice))).then(function (response) { var _ref21 = response || {}, failures = _ref21.failures; if (Object.keys(failures || []).length > 0) { if (shouldEmit) { _this7._baseApis.emit("crypto.keySignatureUploadFailure", failures, "_afterCrossSigningLocalKeyChange", upload // continuation ); } throw new _errors.KeySignatureUploadError("Key upload failed", { failures: failures }); } _logger.logger.info("Finished background key sig upload for ".concat(_this7._deviceId)); })["catch"](function (e) { _logger.logger.error("Error during background key sig upload for ".concat(_this7._deviceId), e); }); }; upload({ shouldEmit: true }); shouldUpgradeCb = this._baseApis._cryptoCallbacks.shouldUpgradeDeviceVerifications; if (!shouldUpgradeCb) { _context14.next = 53; break; } _logger.logger.info("Starting device verification upgrade"); // Check all users for signatures if upgrade callback present // FIXME: do this in batches users = {}; _i2 = 0, _Object$entries = Object.entries(this._deviceList._crossSigningInfo); case 13: if (!(_i2 < _Object$entries.length)) { _context14.next = 22; break; } _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i2], 2), userId = _Object$entries$_i[0], crossSigningInfo = _Object$entries$_i[1]; _context14.next = 17; return this._checkForDeviceVerificationUpgrade(userId, _CrossSigning.CrossSigningInfo.fromStorage(crossSigningInfo, userId)); case 17: upgradeInfo = _context14.sent; if (upgradeInfo) { users[userId] = upgradeInfo; } case 19: _i2++; _context14.next = 13; break; case 22: if (!(Object.keys(users).length > 0)) { _context14.next = 52; break; } _logger.logger.info("Found ".concat(Object.keys(users).length, " verif users to upgrade")); _context14.prev = 24; _context14.next = 27; return shouldUpgradeCb({ users: users }); case 27: usersToUpgrade = _context14.sent; if (!usersToUpgrade) { _context14.next = 47; break; } _iterator3 = _createForOfIteratorHelper(usersToUpgrade); _context14.prev = 30; _iterator3.s(); case 32: if ((_step3 = _iterator3.n()).done) { _context14.next = 39; break; } _userId = _step3.value; if (!(_userId in users)) { _context14.next = 37; break; } _context14.next = 37; return this._baseApis.setDeviceVerified(_userId, users[_userId].crossSigningInfo.getId()); case 37: _context14.next = 32; break; case 39: _context14.next = 44; break; case 41: _context14.prev = 41; _context14.t0 = _context14["catch"](30); _iterator3.e(_context14.t0); case 44: _context14.prev = 44; _iterator3.f(); return _context14.finish(44); case 47: _context14.next = 52; break; case 49: _context14.prev = 49; _context14.t1 = _context14["catch"](24); _logger.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading", _context14.t1); case 52: _logger.logger.info("Finished device verification upgrade"); case 53: _logger.logger.info("Finished cross-signing key change post-processing"); case 54: case "end": return _context14.stop(); } } }, _callee14, this, [[24, 49], [30, 41, 44, 47]]); })); /** * Check if a user's cross-signing key is a candidate for upgrading from device * verification. * * @param {string} userId the user whose cross-signing information is to be checked * @param {object} crossSigningInfo the cross-signing information to check */ Crypto.prototype._checkForDeviceVerificationUpgrade = /*#__PURE__*/function () { var _ref22 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15(userId, crossSigningInfo) { var trustLevel, devices, deviceIds; return _regenerator["default"].wrap(function _callee15$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: // only upgrade if this is the first cross-signing key that we've seen for // them, and if their cross-signing key isn't already verified trustLevel = this._crossSigningInfo.checkUserTrust(crossSigningInfo); if (!(crossSigningInfo.firstUse && !trustLevel.verified)) { _context15.next = 8; break; } devices = this._deviceList.getRawStoredDevicesForUser(userId); _context15.next = 5; return this._checkForValidDeviceSignature(userId, crossSigningInfo.keys.master, devices); case 5: deviceIds = _context15.sent; if (!deviceIds.length) { _context15.next = 8; break; } return _context15.abrupt("return", { devices: deviceIds.map(function (deviceId) { return _deviceinfo.DeviceInfo.fromStorage(devices[deviceId], deviceId); }), crossSigningInfo: crossSigningInfo }); case 8: case "end": return _context15.stop(); } } }, _callee15, this); })); return function (_x9, _x10) { return _ref22.apply(this, arguments); }; }(); /** * Check if the cross-signing key is signed by a verified device. * * @param {string} userId the user ID whose key is being checked * @param {object} key the key that is being checked * @param {object} devices the user's devices. Should be a map from device ID * to device info */ Crypto.prototype._checkForValidDeviceSignature = /*#__PURE__*/function () { var _ref23 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee16(userId, key, devices) { var deviceIds, _i3, _Object$keys2, signame, _signame$split, _signame$split2, deviceId; return _regenerator["default"].wrap(function _callee16$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: deviceIds = []; if (!(devices && key.signatures && key.signatures[userId])) { _context16.next = 18; break; } _i3 = 0, _Object$keys2 = Object.keys(key.signatures[userId]); case 3: if (!(_i3 < _Object$keys2.length)) { _context16.next = 18; break; } signame = _Object$keys2[_i3]; _signame$split = signame.split(':', 2), _signame$split2 = (0, _slicedToArray2["default"])(_signame$split, 2), deviceId = _signame$split2[1]; if (!(deviceId in devices && devices[deviceId].verified === DeviceVerification.VERIFIED)) { _context16.next = 15; break; } _context16.prev = 7; _context16.next = 10; return olmlib.verifySignature(this._olmDevice, key, userId, deviceId, devices[deviceId].keys[signame]); case 10: deviceIds.push(deviceId); _context16.next = 15; break; case 13: _context16.prev = 13; _context16.t0 = _context16["catch"](7); case 15: _i3++; _context16.next = 3; break; case 18: return _context16.abrupt("return", deviceIds); case 19: case "end": return _context16.stop(); } } }, _callee16, this, [[7, 13]]); })); return function (_x11, _x12, _x13) { return _ref23.apply(this, arguments); }; }(); /** * Get the user's cross-signing key ID. * * @param {string} [type=master] The type of key to get the ID of. One of * "master", "self_signing", or "user_signing". Defaults to "master". * * @returns {string} the key ID */ Crypto.prototype.getCrossSigningId = function (type) { return this._crossSigningInfo.getId(type); }; /** * Get the cross signing information for a given user. * * @param {string} userId the user ID to get the cross-signing info for. * * @returns {CrossSigningInfo} the cross signing informmation for the user. */ Crypto.prototype.getStoredCrossSigningForUser = function (userId) { return this._deviceList.getStoredCrossSigningForUser(userId); }; /** * Check whether a given user is trusted. * * @param {string} userId The ID of the user to check. * * @returns {UserTrustLevel} */ Crypto.prototype.checkUserTrust = function (userId) { var userCrossSigning = this._deviceList.getStoredCrossSigningForUser(userId); if (!userCrossSigning) { return new _CrossSigning.UserTrustLevel(false, false, false); } return this._crossSigningInfo.checkUserTrust(userCrossSigning); }; /** * Check whether a given device is trusted. * * @param {string} userId The ID of the user whose devices is to be checked. * @param {string} deviceId The ID of the device to check * * @returns {DeviceTrustLevel} */ Crypto.prototype.checkDeviceTrust = function (userId, deviceId) { var device = this._deviceList.getStoredDevice(userId, deviceId); return this._checkDeviceInfoTrust(userId, device); }; /** * Check whether a given deviceinfo is trusted. * * @param {string} userId The ID of the user whose devices is to be checked. * @param {module:crypto/deviceinfo?} device The device info object to check * * @returns {DeviceTrustLevel} */ Crypto.prototype._checkDeviceInfoTrust = function (userId, device) { var trustedLocally = !!(device && device.isVerified()); var userCrossSigning = this._deviceList.getStoredCrossSigningForUser(userId); if (device && userCrossSigning) { // The _trustCrossSignedDevices only affects trust of other people's cross-signing // signatures var trustCrossSig = this._trustCrossSignedDevices || userId === this._userId; return this._crossSigningInfo.checkDeviceTrust(userCrossSigning, device, trustedLocally, trustCrossSig); } else { return new _CrossSigning.DeviceTrustLevel(false, false, trustedLocally, false); } }; /* * Event handler for DeviceList's userNewDevices event */ Crypto.prototype._onDeviceListUserCrossSigningUpdated = /*#__PURE__*/function () { var _ref24 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee17(userId) { var newCrossSigning, seenPubkey, currentPubkey, changed, crossSigning; return _regenerator["default"].wrap(function _callee17$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: if (!(userId === this._userId)) { _context17.next = 15; break; } // An update to our own cross-signing key. // Get the new key first: newCrossSigning = this._deviceList.getStoredCrossSigningForUser(userId); seenPubkey = newCrossSigning ? newCrossSigning.getId() : null; currentPubkey = this._crossSigningInfo.getId(); changed = currentPubkey !== seenPubkey; if (!(currentPubkey && seenPubkey && !changed)) { _context17.next = 10; break; } _context17.next = 8; return this.checkOwnCrossSigningTrust(); case 8: _context17.next = 13; break; case 10: // We'll now be in a state where cross-signing on the account is not trusted // because our locally stored cross-signing keys will not match the ones // on the server for our account. So we clear our own stored cross-signing keys, // effectively disabling cross-signing until the user gets verified by the device // that reset the keys this._storeTrustedSelfKeys(null); // emit cross-signing has been disabled this.emit("crossSigning.keysChanged", {}); // as the trust for our own user has changed, // also emit an event for this this.emit("userTrustStatusChanged", this._userId, this.checkUserTrust(userId)); case 13: _context17.next = 20; break; case 15: _context17.next = 17; return this._checkDeviceVerifications(userId); case 17: // Update verified before latch using the current state and save the new // latch value in the device list store. crossSigning = this._deviceList.getStoredCrossSigningForUser(userId); if (crossSigning) { crossSigning.updateCrossSigningVerifiedBefore(this.checkUserTrust(userId).isCrossSigningVerified()); this._deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage()); } this.emit("userTrustStatusChanged", userId, this.checkUserTrust(userId)); case 20: case "end": return _context17.stop(); } } }, _callee17, this); })); return function (_x14) { return _ref24.apply(this, arguments); }; }(); /** * Check the copy of our cross-signing key that we have in the device list and * see if we can get the private key. If so, mark it as trusted. */ Crypto.prototype.checkOwnCrossSigningTrust = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee18() { var _this8 = this; var userId, newCrossSigning, seenPubkey, masterChanged, signing, ret, oldSelfSigningId, oldUserSigningId, selfSigningChanged, userSigningChanged, keySignatures, _signing, _ret, device, _signedDevice, _signing2, _ret2, masterKey, deviceSig, keysToUpload, _upload; return _regenerator["default"].wrap(function _callee18$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: userId = this._userId; // Before proceeding, ensure our cross-signing public keys have been // downloaded via the device list. _context18.next = 3; return this.downloadKeys([this._userId]); case 3: // If we see an update to our own master key, check it against the master // key we have and, if it matches, mark it as verified // First, get the new cross-signing info newCrossSigning = this._deviceList.getStoredCrossSigningForUser(userId); if (newCrossSigning) { _context18.next = 7; break; } _logger.logger.error("Got cross-signing update event for user " + userId + " but no new cross-signing information found!"); return _context18.abrupt("return"); case 7: seenPubkey = newCrossSigning.getId(); masterChanged = this._crossSigningInfo.getId() !== seenPubkey; if (!masterChanged) { _context18.next = 27; break; } _logger.logger.info("Got new master public key", seenPubkey); _logger.logger.info("Attempting to retrieve cross-signing master private key"); signing = null; _context18.prev = 13; _context18.next = 16; return this._crossSigningInfo.getCrossSigningKey('master', seenPubkey); case 16: ret = _context18.sent; signing = ret[1]; _logger.logger.info("Got cross-signing master private key"); _context18.next = 24; break; case 21: _context18.prev = 21; _context18.t0 = _context18["catch"](13); _logger.logger.error("Cross-signing master private key not available", _context18.t0); case 24: _context18.prev = 24; if (signing) signing.free(); return _context18.finish(24); case 27: oldSelfSigningId = this._crossSigningInfo.getId("self_signing"); oldUserSigningId = this._crossSigningInfo.getId("user_signing"); // Update the version of our keys in our cross-signing object and the local store this._storeTrustedSelfKeys(newCrossSigning.keys); selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId("self_signing"); userSigningChanged = oldUserSigningId !== newCrossSigning.getId("user_signing"); keySignatures = {}; if (!selfSigningChanged) { _context18.next = 56; break; } _logger.logger.info("Got new self-signing key", newCrossSigning.getId("self_signing")); _logger.logger.info("Attempting to retrieve cross-signing self-signing private key"); _signing = null; _context18.prev = 37; _context18.next = 40; return this._crossSigningInfo.getCrossSigningKey("self_signing", newCrossSigning.getId("self_signing")); case 40: _ret = _context18.sent; _signing = _ret[1]; _logger.logger.info("Got cross-signing self-signing private key"); _context18.next = 48; break; case 45: _context18.prev = 45; _context18.t1 = _context18["catch"](37); _logger.logger.error("Cross-signing self-signing private key not available", _context18.t1); case 48: _context18.prev = 48; if (_signing) _signing.free(); return _context18.finish(48); case 51: device = this._deviceList.getStoredDevice(this._userId, this._deviceId); _context18.next = 54; return this._crossSigningInfo.signDevice(this._userId, device); case 54: _signedDevice = _context18.sent; keySignatures[this._deviceId] = _signedDevice; case 56: if (!userSigningChanged) { _context18.next = 74; break; } _logger.logger.info("Got new user-signing key", newCrossSigning.getId("user_signing")); _logger.logger.info("Attempting to retrieve cross-signing user-signing private key"); _signing2 = null; _context18.prev = 60; _context18.next = 63; return this._crossSigningInfo.getCrossSigningKey("user_signing", newCrossSigning.getId("user_signing")); case 63: _ret2 = _context18.sent; _signing2 = _ret2[1]; _logger.logger.info("Got cross-signing user-signing private key"); _context18.next = 71; break; case 68: _context18.prev = 68; _context18.t2 = _context18["catch"](60); _logger.logger.error("Cross-signing user-signing private key not available", _context18.t2); case 71: _context18.prev = 71; if (_signing2) _signing2.free(); return _context18.finish(71); case 74: if (!masterChanged) { _context18.next = 80; break; } masterKey = this._crossSigningInfo.keys.master; _context18.next = 78; return this._signObject(masterKey); case 78: deviceSig = masterKey.signatures[this._userId]["ed25519:" + this._deviceId]; // Include only the _new_ device signature in the upload. // We may have existing signatures from deleted devices, which will cause // the entire upload to fail. keySignatures[this._crossSigningInfo.getId()] = Object.assign({}, masterKey, { signatures: (0, _defineProperty2["default"])({}, this._userId, (0, _defineProperty2["default"])({}, "ed25519:" + this._deviceId, deviceSig)) }); case 80: keysToUpload = Object.keys(keySignatures); if (keysToUpload.length) { _upload = function _upload(_ref26) { var shouldEmit = _ref26.shouldEmit; _logger.logger.info("Starting background key sig upload for ".concat(keysToUpload)); return _this8._baseApis.uploadKeySignatures((0, _defineProperty2["default"])({}, _this8._userId, keySignatures)).then(function (response) { var _ref27 = response || {}, failures = _ref27.failures; _logger.logger.info("Finished background key sig upload for ".concat(keysToUpload)); if (Object.keys(failures || []).length > 0) { if (shouldEmit) { _this8._baseApis.emit("crypto.keySignatureUploadFailure", failures, "checkOwnCrossSigningTrust", _upload); } throw new _errors.KeySignatureUploadError("Key upload failed", { failures: failures }); } })["catch"](function (e) { _logger.logger.error("Error during background key sig upload for ".concat(keysToUpload), e); }); }; _upload({ shouldEmit: true }); } this.emit("userTrustStatusChanged", userId, this.checkUserTrust(userId)); if (!masterChanged) { _context18.next = 87; break; } this._baseApis.emit("crossSigning.keysChanged", {}); _context18.next = 87; return this._afterCrossSigningLocalKeyChange(); case 87: _context18.next = 89; return this.checkKeyBackup(); case 89: case "end": return _context18.stop(); } } }, _callee18, this, [[13, 21, 24, 27], [37, 45, 48, 51], [60, 68, 71, 74]]); })); /** * Store a set of keys as our own, trusted, cross-signing keys. * * @param {object} keys The new trusted set of keys */ Crypto.prototype._storeTrustedSelfKeys = /*#__PURE__*/function () { var _ref28 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee19(keys) { var _this9 = this; return _regenerator["default"].wrap(function _callee19$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: if (keys) { this._crossSigningInfo.setKeys(keys); } else { this._crossSigningInfo.clearKeys(); } _context19.next = 3; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_ACCOUNT], function (txn) { _this9._cryptoStore.storeCrossSigningKeys(txn, _this9._crossSigningInfo.keys); }); case 3: case "end": return _context19.stop(); } } }, _callee19, this); })); return function (_x15) { return _ref28.apply(this, arguments); }; }(); /** * Check if the master key is signed by a verified device, and if so, prompt * the application to mark it as verified. * * @param {string} userId the user ID whose key should be checked */ Crypto.prototype._checkDeviceVerifications = /*#__PURE__*/function () { var _ref29 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee20(userId) { var shouldUpgradeCb, crossSigningInfo, upgradeInfo, usersToUpgrade; return _regenerator["default"].wrap(function _callee20$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: shouldUpgradeCb = this._baseApis._cryptoCallbacks.shouldUpgradeDeviceVerifications; if (shouldUpgradeCb) { _context20.next = 3; break; } return _context20.abrupt("return"); case 3: _logger.logger.info("Starting device verification upgrade for ".concat(userId)); if (!this._crossSigningInfo.keys.user_signing) { _context20.next = 17; break; } crossSigningInfo = this._deviceList.getStoredCrossSigningForUser(userId); if (!crossSigningInfo) { _context20.next = 17; break; } _context20.next = 9; return this._checkForDeviceVerificationUpgrade(userId, crossSigningInfo); case 9: upgradeInfo = _context20.sent; if (!upgradeInfo) { _context20.next = 17; break; } _context20.next = 13; return shouldUpgradeCb({ users: (0, _defineProperty2["default"])({}, userId, upgradeInfo) }); case 13: usersToUpgrade = _context20.sent; if (!usersToUpgrade.includes(userId)) { _context20.next = 17; break; } _context20.next = 17; return this._baseApis.setDeviceVerified(userId, crossSigningInfo.getId()); case 17: _logger.logger.info("Finished device verification upgrade for ".concat(userId)); case 18: case "end": return _context20.stop(); } } }, _callee20, this); })); return function (_x16) { return _ref29.apply(this, arguments); }; }(); /** * Check the server for an active key backup and * if one is present and has a valid signature from * one of the user's verified devices, start backing up * to it. */ Crypto.prototype._checkAndStartKeyBackup = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee21() { var backupInfo, trustInfo; return _regenerator["default"].wrap(function _callee21$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: _logger.logger.log("Checking key backup status..."); if (!this._baseApis.isGuest()) { _context21.next = 5; break; } _logger.logger.log("Skipping key backup check since user is guest"); this._checkedForBackup = true; return _context21.abrupt("return", null); case 5: _context21.prev = 5; _context21.next = 8; return this._baseApis.getKeyBackupVersion(); case 8: backupInfo = _context21.sent; _context21.next = 16; break; case 11: _context21.prev = 11; _context21.t0 = _context21["catch"](5); _logger.logger.log("Error checking for active key backup", _context21.t0); if (_context21.t0.httpStatus === 404) { // 404 is returned when the key backup does not exist, so that // counts as successfully checking. this._checkedForBackup = true; } return _context21.abrupt("return", null); case 16: this._checkedForBackup = true; _context21.next = 19; return this.isKeyBackupTrusted(backupInfo); case 19: trustInfo = _context21.sent; if (!(trustInfo.usable && !this.backupInfo)) { _context21.next = 25; break; } _logger.logger.log("Found usable key backup v" + backupInfo.version + ": enabling key backups"); this._baseApis.enableKeyBackup(backupInfo); _context21.next = 44; break; case 25: if (!(!trustInfo.usable && this.backupInfo)) { _context21.next = 30; break; } _logger.logger.log("No usable key backup: disabling key backup"); this._baseApis.disableKeyBackup(); _context21.next = 44; break; case 30: if (!(!trustInfo.usable && !this.backupInfo)) { _context21.next = 34; break; } _logger.logger.log("No usable key backup: not enabling key backup"); _context21.next = 44; break; case 34: if (!(trustInfo.usable && this.backupInfo)) { _context21.next = 44; break; } if (!(backupInfo.version !== this.backupInfo.version)) { _context21.next = 43; break; } _logger.logger.log("On backup version " + this.backupInfo.version + " but found " + "version " + backupInfo.version + ": switching."); this._baseApis.disableKeyBackup(); this._baseApis.enableKeyBackup(backupInfo); // We're now using a new backup, so schedule all the keys we have to be // uploaded to the new backup. This is a bit of a workaround to upload // keys to a new backup in *most* cases, but it won't cover all cases // because we don't remember what backup version we uploaded keys to: // see https://github.com/vector-im/element-web/issues/14833 _context21.next = 41; return this.scheduleAllGroupSessionsForBackup(); case 41: _context21.next = 44; break; case 43: _logger.logger.log("Backup version " + backupInfo.version + " still current"); case 44: return _context21.abrupt("return", { backupInfo: backupInfo, trustInfo: trustInfo }); case 45: case "end": return _context21.stop(); } } }, _callee21, this, [[5, 11]]); })); Crypto.prototype.setTrustedBackupPubKey = /*#__PURE__*/function () { var _ref31 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee22(trustedPubKey) { return _regenerator["default"].wrap(function _callee22$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: // This should be redundant post cross-signing is a thing, so just // plonk it in localStorage for now. this._sessionStore.setLocalTrustedBackupPubKey(trustedPubKey); _context22.next = 3; return this.checkKeyBackup(); case 3: case "end": return _context22.stop(); } } }, _callee22, this); })); return function (_x17) { return _ref31.apply(this, arguments); }; }(); /** * Forces a re-check of the key backup and enables/disables it * as appropriate. * * @return {Object} Object with backup info (as returned by * getKeyBackupVersion) in backupInfo and * trust information (as returned by isKeyBackupTrusted) * in trustInfo. */ Crypto.prototype.checkKeyBackup = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee23() { return _regenerator["default"].wrap(function _callee23$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: this._checkedForBackup = false; return _context23.abrupt("return", this._checkAndStartKeyBackup()); case 2: case "end": return _context23.stop(); } } }, _callee23, this); })); /** * @param {object} backupInfo key backup info dict from /room_keys/version * @return {object} { * usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device * sigs: [ * valid: [bool || null], // true: valid, false: invalid, null: cannot attempt validation * deviceId: [string], * device: [DeviceInfo || null], * ] * } */ Crypto.prototype.isKeyBackupTrusted = /*#__PURE__*/function () { var _ref33 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee24(backupInfo) { var ret, trustedPubkey, mySigs, _i4, _Object$keys3, keyId, keyIdParts, sigInfo, crossSigningId, device; return _regenerator["default"].wrap(function _callee24$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: ret = { usable: false, trusted_locally: false, sigs: [] }; if (!(!backupInfo || !backupInfo.algorithm || !backupInfo.auth_data || !backupInfo.auth_data.public_key || !backupInfo.auth_data.signatures)) { _context24.next = 4; break; } _logger.logger.info("Key backup is absent or missing required data"); return _context24.abrupt("return", ret); case 4: trustedPubkey = this._sessionStore.getLocalTrustedBackupPubKey(); if (backupInfo.auth_data.public_key === trustedPubkey) { _logger.logger.info("Backup public key " + trustedPubkey + " is trusted locally"); ret.trusted_locally = true; } mySigs = backupInfo.auth_data.signatures[this._userId] || []; _i4 = 0, _Object$keys3 = Object.keys(mySigs); case 8: if (!(_i4 < _Object$keys3.length)) { _context24.next = 54; break; } keyId = _Object$keys3[_i4]; keyIdParts = keyId.split(':'); if (!(keyIdParts[0] !== 'ed25519')) { _context24.next = 14; break; } _logger.logger.log("Ignoring unknown signature type: " + keyIdParts[0]); return _context24.abrupt("continue", 51); case 14: // Could be a cross-signing master key, but just say this is the device // ID for backwards compat sigInfo = { deviceId: keyIdParts[1] }; // first check to see if it's from our cross-signing key crossSigningId = this._crossSigningInfo.getId(); if (!(crossSigningId === sigInfo.deviceId)) { _context24.next = 30; break; } sigInfo.crossSigningId = true; _context24.prev = 18; _context24.next = 21; return olmlib.verifySignature(this._olmDevice, backupInfo.auth_data, this._userId, sigInfo.deviceId, crossSigningId); case 21: sigInfo.valid = true; _context24.next = 28; break; case 24: _context24.prev = 24; _context24.t0 = _context24["catch"](18); _logger.logger.warning("Bad signature from cross signing key " + crossSigningId, _context24.t0); sigInfo.valid = false; case 28: ret.sigs.push(sigInfo); return _context24.abrupt("continue", 51); case 30: // Now look for a sig from a device // At some point this can probably go away and we'll just support // it being signed by the cross-signing master key device = this._deviceList.getStoredDevice(this._userId, sigInfo.deviceId); if (!device) { _context24.next = 48; break; } sigInfo.device = device; _context24.next = 35; return this.checkDeviceTrust(this._userId, sigInfo.deviceId); case 35: sigInfo.deviceTrust = _context24.sent; _context24.prev = 36; _context24.next = 39; return olmlib.verifySignature(this._olmDevice, backupInfo.auth_data, this._userId, device.deviceId, device.getFingerprint()); case 39: sigInfo.valid = true; _context24.next = 46; break; case 42: _context24.prev = 42; _context24.t1 = _context24["catch"](36); _logger.logger.info("Bad signature from key ID " + keyId + " userID " + this._userId + " device ID " + device.deviceId + " fingerprint: " + device.getFingerprint(), backupInfo.auth_data, _context24.t1); sigInfo.valid = false; case 46: _context24.next = 50; break; case 48: sigInfo.valid = null; // Can't determine validity because we don't have the signing device _logger.logger.info("Ignoring signature from unknown key " + keyId); case 50: ret.sigs.push(sigInfo); case 51: _i4++; _context24.next = 8; break; case 54: ret.usable = ret.sigs.some(function (s) { return s.valid && (s.device && s.deviceTrust.isVerified() || s.crossSigningId); }); ret.usable |= ret.trusted_locally; return _context24.abrupt("return", ret); case 57: case "end": return _context24.stop(); } } }, _callee24, this, [[18, 24], [36, 42]]); })); return function (_x18) { return _ref33.apply(this, arguments); }; }(); /** */ Crypto.prototype.enableLazyLoading = function () { this._lazyLoadMembers = true; }; /** * Tell the crypto module to register for MatrixClient events which it needs to * listen for * * @param {external:EventEmitter} eventEmitter event source where we can register * for event notifications */ Crypto.prototype.registerEventHandlers = function (eventEmitter) { var crypto = this; eventEmitter.on("RoomMember.membership", function (event, member, oldMembership) { try { crypto._onRoomMembership(event, member, oldMembership); } catch (e) { _logger.logger.error("Error handling membership change:", e); } }); eventEmitter.on("toDeviceEvent", crypto._onToDeviceEvent.bind(crypto)); var timelineHandler = crypto._onTimelineEvent.bind(crypto); eventEmitter.on("Room.timeline", timelineHandler); eventEmitter.on("Event.decrypted", timelineHandler); }; /** Start background processes related to crypto */ Crypto.prototype.start = function () { this._outgoingRoomKeyRequestManager.start(); }; /** Stop background processes related to crypto */ Crypto.prototype.stop = function () { this._outgoingRoomKeyRequestManager.stop(); this._deviceList.stop(); }; /** * @return {string} The version of Olm. */ Crypto.getOlmVersion = function () { return _OlmDevice.OlmDevice.getOlmVersion(); }; /** * Get the Ed25519 key for this device * * @return {string} base64-encoded ed25519 key. */ Crypto.prototype.getDeviceEd25519Key = function () { return this._olmDevice.deviceEd25519Key; }; /** * Get the Curve25519 key for this device * * @return {string} base64-encoded curve25519 key. */ Crypto.prototype.getDeviceCurve25519Key = function () { return this._olmDevice.deviceCurve25519Key; }; /** * Set the global override for whether the client should ever send encrypted * messages to unverified devices. This provides the default for rooms which * do not specify a value. * * @param {boolean} value whether to blacklist all unverified devices by default */ Crypto.prototype.setGlobalBlacklistUnverifiedDevices = function (value) { this._globalBlacklistUnverifiedDevices = value; }; /** * @return {boolean} whether to blacklist all unverified devices by default */ Crypto.prototype.getGlobalBlacklistUnverifiedDevices = function () { return this._globalBlacklistUnverifiedDevices; }; /** * Set whether sendMessage in a room with unknown and unverified devices * should throw an error and not send them message. This has 'Global' for * symmertry with setGlobalBlacklistUnverifiedDevices but there is currently * no room-level equivalent for this setting. * * This API is currently UNSTABLE and may change or be removed without notice. * * @param {boolean} value whether error on unknown devices */ Crypto.prototype.setGlobalErrorOnUnknownDevices = function (value) { this._globalErrorOnUnknownDevices = value; }; /** * @return {boolean} whether to error on unknown devices * * This API is currently UNSTABLE and may change or be removed without notice. */ Crypto.prototype.getGlobalErrorOnUnknownDevices = function () { return this._globalErrorOnUnknownDevices; }; /** * Upload the device keys to the homeserver. * @return {object} A promise that will resolve when the keys are uploaded. */ Crypto.prototype.uploadDeviceKeys = function () { var crypto = this; var userId = crypto._userId; var deviceId = crypto._deviceId; var deviceKeys = { algorithms: crypto._supportedAlgorithms, device_id: deviceId, keys: crypto._deviceKeys, user_id: userId }; return crypto._signObject(deviceKeys).then(function () { return crypto._baseApis.uploadKeysRequest({ device_keys: deviceKeys }); }); }; /** * Stores the current one_time_key count which will be handled later (in a call of * onSyncCompleted). The count is e.g. coming from a /sync response. * * @param {Number} currentCount The current count of one_time_keys to be stored */ Crypto.prototype.updateOneTimeKeyCount = function (currentCount) { if (isFinite(currentCount)) { this._oneTimeKeyCount = currentCount; } else { throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number"); } }; // check if it's time to upload one-time keys, and do so if so. function _maybeUploadOneTimeKeys(crypto) { // frequency with which to check & upload one-time keys var uploadPeriod = 1000 * 60; // one minute // max number of keys to upload at once // Creating keys can be an expensive operation so we limit the // number we generate in one go to avoid blocking the application // for too long. var maxKeysPerCycle = 5; if (crypto._oneTimeKeyCheckInProgress) { return; } var now = Date.now(); if (crypto._lastOneTimeKeyCheck !== null && now - crypto._lastOneTimeKeyCheck < uploadPeriod) { // we've done a key upload recently. return; } crypto._lastOneTimeKeyCheck = now; // We need to keep a pool of one time public keys on the server so that // other devices can start conversations with us. But we can only store // a finite number of private keys in the olm Account object. // To complicate things further then can be a delay between a device // claiming a public one time key from the server and it sending us a // message. We need to keep the corresponding private key locally until // we receive the message. // But that message might never arrive leaving us stuck with duff // private keys clogging up our local storage. // So we need some kind of enginering compromise to balance all of // these factors. // Check how many keys we can store in the Account object. var maxOneTimeKeys = crypto._olmDevice.maxNumberOfOneTimeKeys(); // Try to keep at most half that number on the server. This leaves the // rest of the slots free to hold keys that have been claimed from the // server but we haven't recevied a message for. // If we run out of slots when generating new keys then olm will // discard the oldest private keys first. This will eventually clean // out stale private keys that won't receive a message. var keyLimit = Math.floor(maxOneTimeKeys / 2); function uploadLoop(keyCount) { if (keyLimit <= keyCount) { // If we don't need to generate any more keys then we are done. return Promise.resolve(); } var keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle); // Ask olm to generate new one time keys, then upload them to synapse. return crypto._olmDevice.generateOneTimeKeys(keysThisLoop).then(function () { return _uploadOneTimeKeys(crypto); }).then(function (res) { if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) { // if the response contains a more up to date value use this // for the next loop return uploadLoop(res.one_time_key_counts.signed_curve25519); } else { throw new Error("response for uploading keys does not contain " + "one_time_key_counts.signed_curve25519"); } }); } crypto._oneTimeKeyCheckInProgress = true; Promise.resolve().then(function () { if (crypto._oneTimeKeyCount !== undefined) { // We already have the current one_time_key count from a /sync response. // Use this value instead of asking the server for the current key count. return Promise.resolve(crypto._oneTimeKeyCount); } // ask the server how many keys we have return crypto._baseApis.uploadKeysRequest({}).then(function (res) { return res.one_time_key_counts.signed_curve25519 || 0; }); }).then(function (keyCount) { // Start the uploadLoop with the current keyCount. The function checks if // we need to upload new keys or not. // If there are too many keys on the server then we don't need to // create any more keys. return uploadLoop(keyCount); })["catch"](function (e) { _logger.logger.error("Error uploading one-time keys", e.stack || e); })["finally"](function () { // reset _oneTimeKeyCount to prevent start uploading based on old data. // it will be set again on the next /sync-response crypto._oneTimeKeyCount = undefined; crypto._oneTimeKeyCheckInProgress = false; }); } // returns a promise which resolves to the response function _uploadOneTimeKeys(_x19) { return _uploadOneTimeKeys2.apply(this, arguments); } /** * Download the keys for a list of users and stores the keys in the session * store. * @param {Array} userIds The users to fetch. * @param {bool} forceDownload Always download the keys even if cached. * * @return {Promise} A promise which resolves to a map userId->deviceId->{@link * module:crypto/deviceinfo|DeviceInfo}. */ function _uploadOneTimeKeys2() { _uploadOneTimeKeys2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee52(crypto) { var oneTimeKeys, oneTimeJson, promises, keyId, k, res; return _regenerator["default"].wrap(function _callee52$(_context52) { while (1) { switch (_context52.prev = _context52.next) { case 0: _context52.next = 2; return crypto._olmDevice.getOneTimeKeys(); case 2: oneTimeKeys = _context52.sent; oneTimeJson = {}; promises = []; for (keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { k = { key: oneTimeKeys.curve25519[keyId] }; oneTimeJson["signed_curve25519:" + keyId] = k; promises.push(crypto._signObject(k)); } } _context52.next = 8; return Promise.all(promises); case 8: _context52.next = 10; return crypto._baseApis.uploadKeysRequest({ one_time_keys: oneTimeJson }); case 10: res = _context52.sent; _context52.next = 13; return crypto._olmDevice.markKeysAsPublished(); case 13: return _context52.abrupt("return", res); case 14: case "end": return _context52.stop(); } } }, _callee52); })); return _uploadOneTimeKeys2.apply(this, arguments); } Crypto.prototype.downloadKeys = function (userIds, forceDownload) { return this._deviceList.downloadKeys(userIds, forceDownload); }; /** * Get the stored device keys for a user id * * @param {string} userId the user to list keys for. * * @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't * managed to get a list of devices for this user yet. */ Crypto.prototype.getStoredDevicesForUser = function (userId) { return this._deviceList.getStoredDevicesForUser(userId); }; /** * Get the stored keys for a single device * * @param {string} userId * @param {string} deviceId * * @return {module:crypto/deviceinfo?} device, or undefined * if we don't know about this device */ Crypto.prototype.getStoredDevice = function (userId, deviceId) { return this._deviceList.getStoredDevice(userId, deviceId); }; /** * Save the device list, if necessary * * @param {integer} delay Time in ms before which the save actually happens. * By default, the save is delayed for a short period in order to batch * multiple writes, but this behaviour can be disabled by passing 0. * * @return {Promise} true if the data was saved, false if * it was not (eg. because no changes were pending). The promise * will only resolve once the data is saved, so may take some time * to resolve. */ Crypto.prototype.saveDeviceList = function (delay) { return this._deviceList.saveIfDirty(delay); }; /** * Update the blocked/verified state of the given device * * @param {string} userId owner of the device * @param {string} deviceId unique identifier for the device or user's * cross-signing public key ID. * * @param {?boolean} verified whether to mark the device as verified. Null to * leave unchanged. * * @param {?boolean} blocked whether to mark the device as blocked. Null to * leave unchanged. * * @param {?boolean} known whether to mark that the user has been made aware of * the existence of this device. Null to leave unchanged * * @return {Promise} updated DeviceInfo */ Crypto.prototype.setDeviceVerification = /*#__PURE__*/function () { var _ref34 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee27(userId, deviceId, verified, blocked, known) { var _this10 = this; var xsk, device, _upload2, devices, dev, verificationStatus, knownStatus, _device, deviceTrust, _upload3, deviceObj; return _regenerator["default"].wrap(function _callee27$(_context27) { while (1) { switch (_context27.prev = _context27.next) { case 0: // get rid of any `undefined`s here so we can just check // for null rather than null or undefined if (verified === undefined) verified = null; if (blocked === undefined) blocked = null; if (known === undefined) known = null; // Check if the 'device' is actually a cross signing key // The js-sdk's verification treats cross-signing keys as devices // and so uses this method to mark them verified. xsk = this._deviceList.getStoredCrossSigningForUser(userId); if (!(xsk && xsk.getId() === deviceId)) { _context27.next = 23; break; } if (!(blocked !== null || known !== null)) { _context27.next = 7; break; } throw new Error("Cannot set blocked or known for a cross-signing key"); case 7: if (verified) { _context27.next = 9; break; } throw new Error("Cannot set a cross-signing key as unverified"); case 9: if (!this._crossSigningInfo.getId() && userId === this._crossSigningInfo.userId) { this._storeTrustedSelfKeys(xsk.keys); // This will cause our own user trust to change, so emit the event this.emit("userTrustStatusChanged", this._userId, this.checkUserTrust(userId)); } // Now sign the master key with our user signing key (unless it's ourself) if (!(userId !== this._userId)) { _context27.next = 22; break; } _logger.logger.info("Master key " + xsk.getId() + " for " + userId + " marked verified. Signing..."); _context27.next = 14; return this._crossSigningInfo.signUser(xsk); case 14: device = _context27.sent; if (!device) { _context27.next = 19; break; } _upload2 = /*#__PURE__*/function () { var _ref36 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee25(_ref35) { var shouldEmit, response, _ref37, failures; return _regenerator["default"].wrap(function _callee25$(_context25) { while (1) { switch (_context25.prev = _context25.next) { case 0: shouldEmit = _ref35.shouldEmit; _logger.logger.info("Uploading signature for " + userId + "..."); _context25.next = 4; return _this10._baseApis.uploadKeySignatures((0, _defineProperty2["default"])({}, userId, (0, _defineProperty2["default"])({}, deviceId, device))); case 4: response = _context25.sent; _ref37 = response || {}, failures = _ref37.failures; if (!(Object.keys(failures || []).length > 0)) { _context25.next = 9; break; } if (shouldEmit) { _this10._baseApis.emit("crypto.keySignatureUploadFailure", failures, "setDeviceVerification", _upload2); } /* Throwing here causes the process to be cancelled and the other * user to be notified */ throw new _errors.KeySignatureUploadError("Key upload failed", { failures: failures }); case 9: case "end": return _context25.stop(); } } }, _callee25); })); return function _upload2(_x25) { return _ref36.apply(this, arguments); }; }(); _context27.next = 19; return _upload2({ shouldEmit: true }); case 19: return _context27.abrupt("return", device); case 22: return _context27.abrupt("return", xsk); case 23: devices = this._deviceList.getRawStoredDevicesForUser(userId); if (!(!devices || !devices[deviceId])) { _context27.next = 26; break; } throw new Error("Unknown device " + userId + ":" + deviceId); case 26: dev = devices[deviceId]; verificationStatus = dev.verified; if (verified) { verificationStatus = DeviceVerification.VERIFIED; } else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) { verificationStatus = DeviceVerification.UNVERIFIED; } if (blocked) { verificationStatus = DeviceVerification.BLOCKED; } else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) { verificationStatus = DeviceVerification.UNVERIFIED; } knownStatus = dev.known; if (known !== null) { knownStatus = known; } if (dev.verified !== verificationStatus || dev.known !== knownStatus) { dev.verified = verificationStatus; dev.known = knownStatus; this._deviceList.storeDevicesForUser(userId, devices); this._deviceList.saveIfDirty(); } // do cross-signing if (!(verified && userId === this._userId)) { _context27.next = 47; break; } _logger.logger.info("Own device " + deviceId + " marked verified: signing"); // Signing only needed if other device not already signed deviceTrust = this.checkDeviceTrust(userId, deviceId); if (!deviceTrust.isCrossSigningVerified()) { _context27.next = 40; break; } _logger.logger.log("Own device ".concat(deviceId, " already cross-signing verified")); _context27.next = 43; break; case 40: _context27.next = 42; return this._crossSigningInfo.signDevice(userId, _deviceinfo.DeviceInfo.fromStorage(dev, deviceId)); case 42: _device = _context27.sent; case 43: if (!_device) { _context27.next = 47; break; } _upload3 = /*#__PURE__*/function () { var _ref39 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee26(_ref38) { var shouldEmit, response, _ref40, failures; return _regenerator["default"].wrap(function _callee26$(_context26) { while (1) { switch (_context26.prev = _context26.next) { case 0: shouldEmit = _ref38.shouldEmit; _logger.logger.info("Uploading signature for " + deviceId); _context26.next = 4; return _this10._baseApis.uploadKeySignatures((0, _defineProperty2["default"])({}, userId, (0, _defineProperty2["default"])({}, deviceId, _device))); case 4: response = _context26.sent; _ref40 = response || {}, failures = _ref40.failures; if (!(Object.keys(failures || []).length > 0)) { _context26.next = 9; break; } if (shouldEmit) { _this10._baseApis.emit("crypto.keySignatureUploadFailure", failures, "setDeviceVerification", _upload3 // continuation ); } throw new _errors.KeySignatureUploadError("Key upload failed", { failures: failures }); case 9: case "end": return _context26.stop(); } } }, _callee26); })); return function _upload3(_x26) { return _ref39.apply(this, arguments); }; }(); _context27.next = 47; return _upload3({ shouldEmit: true }); case 47: deviceObj = _deviceinfo.DeviceInfo.fromStorage(dev, deviceId); this.emit("deviceVerificationChanged", userId, deviceId, deviceObj); return _context27.abrupt("return", deviceObj); case 50: case "end": return _context27.stop(); } } }, _callee27, this); })); return function (_x20, _x21, _x22, _x23, _x24) { return _ref34.apply(this, arguments); }; }(); Crypto.prototype.findVerificationRequestDMInProgress = function (roomId) { return this._inRoomVerificationRequests.findRequestInProgress(roomId); }; Crypto.prototype.getVerificationRequestsToDeviceInProgress = function (userId) { return this._toDeviceVerificationRequests.getRequestsInProgress(userId); }; Crypto.prototype.requestVerificationDM = function (userId, roomId) { var existingRequest = this._inRoomVerificationRequests.findRequestInProgress(roomId); if (existingRequest) { return Promise.resolve(existingRequest); } var channel = new _InRoomChannel.InRoomChannel(this._baseApis, roomId, userId); return this._requestVerificationWithChannel(userId, channel, this._inRoomVerificationRequests); }; Crypto.prototype.requestVerification = function (userId, devices) { if (!devices) { devices = Object.keys(this._deviceList.getRawStoredDevicesForUser(userId)); } var existingRequest = this._toDeviceVerificationRequests.findRequestInProgress(userId, devices); if (existingRequest) { return Promise.resolve(existingRequest); } var channel = new _ToDeviceChannel.ToDeviceChannel(this._baseApis, userId, devices, _ToDeviceChannel.ToDeviceChannel.makeTransactionId()); return this._requestVerificationWithChannel(userId, channel, this._toDeviceVerificationRequests); }; Crypto.prototype._requestVerificationWithChannel = /*#__PURE__*/function () { var _ref41 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee28(userId, channel, requestsMap) { var request, racingRequest; return _regenerator["default"].wrap(function _callee28$(_context28) { while (1) { switch (_context28.prev = _context28.next) { case 0: request = new _VerificationRequest.VerificationRequest(channel, this._verificationMethods, this._baseApis); // if transaction id is already known, add request if (channel.transactionId) { requestsMap.setRequestByChannel(channel, request); } _context28.next = 4; return request.sendRequest(); case 4: // don't replace the request created by a racing remote echo racingRequest = requestsMap.getRequestByChannel(channel); if (racingRequest) { request = racingRequest; } else { _logger.logger.log("Crypto: adding new request to " + "requestsByTxnId with id ".concat(channel.transactionId, " ").concat(channel.roomId)); requestsMap.setRequestByChannel(channel, request); } return _context28.abrupt("return", request); case 7: case "end": return _context28.stop(); } } }, _callee28, this); })); return function (_x27, _x28, _x29) { return _ref41.apply(this, arguments); }; }(); Crypto.prototype.beginKeyVerification = function (method, userId, deviceId) { var transactionId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var request; if (transactionId) { request = this._toDeviceVerificationRequests.getRequestBySenderAndTxnId(userId, transactionId); if (!request) { throw new Error("No request found for user ".concat(userId, " with ") + "transactionId ".concat(transactionId)); } } else { transactionId = _ToDeviceChannel.ToDeviceChannel.makeTransactionId(); var channel = new _ToDeviceChannel.ToDeviceChannel(this._baseApis, userId, [deviceId], transactionId, deviceId); request = new _VerificationRequest.VerificationRequest(channel, this._verificationMethods, this._baseApis); this._toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request); } return request.beginKeyVerification(method, { userId: userId, deviceId: deviceId }); }; Crypto.prototype.legacyDeviceVerification = /*#__PURE__*/function () { var _ref42 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee29(userId, deviceId, method) { var transactionId, channel, request, verifier; return _regenerator["default"].wrap(function _callee29$(_context29) { while (1) { switch (_context29.prev = _context29.next) { case 0: transactionId = _ToDeviceChannel.ToDeviceChannel.makeTransactionId(); channel = new _ToDeviceChannel.ToDeviceChannel(this._baseApis, userId, [deviceId], transactionId, deviceId); request = new _VerificationRequest.VerificationRequest(channel, this._verificationMethods, this._baseApis); this._toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request); verifier = request.beginKeyVerification(method, { userId: userId, deviceId: deviceId }); // either reject by an error from verify() while sending .start // or resolve when the request receives the // local (fake remote) echo for sending the .start event _context29.next = 7; return Promise.race([verifier.verify(), request.waitFor(function (r) { return r.started; })]); case 7: return _context29.abrupt("return", request); case 8: case "end": return _context29.stop(); } } }, _callee29, this); })); return function (_x30, _x31, _x32) { return _ref42.apply(this, arguments); }; }(); /** * Get information on the active olm sessions with a user *

* Returns a map from device id to an object with keys 'deviceIdKey' (the * device's curve25519 identity key) and 'sessions' (an array of objects in the * same format as that returned by * {@link module:crypto/OlmDevice#getSessionInfoForDevice}). *

* This method is provided for debugging purposes. * * @param {string} userId id of user to inspect * * @return {Promise>} */ Crypto.prototype.getOlmSessionsForUser = /*#__PURE__*/function () { var _ref43 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee30(userId) { var devices, result, j, device, deviceKey, sessions; return _regenerator["default"].wrap(function _callee30$(_context30) { while (1) { switch (_context30.prev = _context30.next) { case 0: devices = this.getStoredDevicesForUser(userId) || []; result = {}; j = 0; case 3: if (!(j < devices.length)) { _context30.next = 13; break; } device = devices[j]; deviceKey = device.getIdentityKey(); _context30.next = 8; return this._olmDevice.getSessionInfoForDevice(deviceKey); case 8: sessions = _context30.sent; result[device.deviceId] = { deviceIdKey: deviceKey, sessions: sessions }; case 10: ++j; _context30.next = 3; break; case 13: return _context30.abrupt("return", result); case 14: case "end": return _context30.stop(); } } }, _callee30, this); })); return function (_x33) { return _ref43.apply(this, arguments); }; }(); /** * Get the device which sent an event * * @param {module:models/event.MatrixEvent} event event to be checked * * @return {module:crypto/deviceinfo?} */ Crypto.prototype.getEventSenderDeviceInfo = function (event) { var senderKey = event.getSenderKey(); var algorithm = event.getWireContent().algorithm; if (!senderKey || !algorithm) { return null; } var forwardingChain = event.getForwardingCurve25519KeyChain(); if (forwardingChain.length > 0) { // we got the key this event from somewhere else // TODO: check if we can trust the forwarders. return null; } if (event.isKeySourceUntrusted()) { // we got the key for this event from a source that we consider untrusted return null; } // senderKey is the Curve25519 identity key of the device which the event // was sent from. In the case of Megolm, it's actually the Curve25519 // identity key of the device which set up the Megolm session. var device = this._deviceList.getDeviceByIdentityKey(algorithm, senderKey); if (device === null) { // we haven't downloaded the details of this device yet. return null; } // so far so good, but now we need to check that the sender of this event // hadn't advertised someone else's Curve25519 key as their own. We do that // by checking the Ed25519 claimed by the event (or, in the case of megolm, // the event which set up the megolm session), to check that it matches the // fingerprint of the purported sending device. // // (see https://github.com/vector-im/vector-web/issues/2215) var claimedKey = event.getClaimedEd25519Key(); if (!claimedKey) { _logger.logger.warn("Event " + event.getId() + " claims no ed25519 key: " + "cannot verify sending device"); return null; } if (claimedKey !== device.getFingerprint()) { _logger.logger.warn("Event " + event.getId() + " claims ed25519 key " + claimedKey + "but sender device has key " + device.getFingerprint()); return null; } return device; }; /** * Get information about the encryption of an event * * @param {module:models/event.MatrixEvent} event event to be checked * * @return {object} An object with the fields: * - encrypted: whether the event is encrypted (if not encrypted, some of the * other properties may not be set) * - senderKey: the sender's key * - algorithm: the algorithm used to encrypt the event * - authenticated: whether we can be sure that the owner of the senderKey * sent the event * - sender: the sender's device information, if available * - mismatchedSender: if the event's ed25519 and curve25519 keys don't match * (only meaningful if `sender` is set) */ Crypto.prototype.getEventEncryptionInfo = function (event) { var ret = {}; ret.senderKey = event.getSenderKey(); ret.algorithm = event.getWireContent().algorithm; if (!ret.senderKey || !ret.algorithm) { ret.encrypted = false; return ret; } ret.encrypted = true; var forwardingChain = event.getForwardingCurve25519KeyChain(); if (forwardingChain.length > 0 || event.isKeySourceUntrusted()) { // we got the key this event from somewhere else // TODO: check if we can trust the forwarders. ret.authenticated = false; } else { ret.authenticated = true; } // senderKey is the Curve25519 identity key of the device which the event // was sent from. In the case of Megolm, it's actually the Curve25519 // identity key of the device which set up the Megolm session. ret.sender = this._deviceList.getDeviceByIdentityKey(ret.algorithm, ret.senderKey); // so far so good, but now we need to check that the sender of this event // hadn't advertised someone else's Curve25519 key as their own. We do that // by checking the Ed25519 claimed by the event (or, in the case of megolm, // the event which set up the megolm session), to check that it matches the // fingerprint of the purported sending device. // // (see https://github.com/vector-im/vector-web/issues/2215) var claimedKey = event.getClaimedEd25519Key(); if (!claimedKey) { _logger.logger.warn("Event " + event.getId() + " claims no ed25519 key: " + "cannot verify sending device"); ret.mismatchedSender = true; } if (ret.sender && claimedKey !== ret.sender.getFingerprint()) { _logger.logger.warn("Event " + event.getId() + " claims ed25519 key " + claimedKey + "but sender device has key " + ret.sender.getFingerprint()); ret.mismatchedSender = true; } return ret; }; /** * Forces the current outbound group session to be discarded such * that another one will be created next time an event is sent. * * @param {string} roomId The ID of the room to discard the session for * * This should not normally be necessary. */ Crypto.prototype.forceDiscardSession = function (roomId) { var alg = this._roomEncryptors[roomId]; if (alg === undefined) throw new Error("Room not encrypted"); if (alg.forceDiscardSession === undefined) { throw new Error("Room encryption algorithm doesn't support session discarding"); } alg.forceDiscardSession(); }; /** * Configure a room to use encryption (ie, save a flag in the cryptoStore). * * @param {string} roomId The room ID to enable encryption in. * * @param {object} config The encryption config for the room. * * @param {boolean=} inhibitDeviceQuery true to suppress device list query for * users in the room (for now). In case lazy loading is enabled, * the device query is always inhibited as the members are not tracked. */ Crypto.prototype.setRoomEncryption = /*#__PURE__*/function () { var _ref44 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee31(roomId, config, inhibitDeviceQuery) { var existingConfig, existingAlg, storeConfigPromise, AlgClass, alg; return _regenerator["default"].wrap(function _callee31$(_context31) { while (1) { switch (_context31.prev = _context31.next) { case 0: if (config.algorithm) { _context31.next = 3; break; } _logger.logger.log("Ignoring setRoomEncryption with no algorithm"); return _context31.abrupt("return"); case 3: // if state is being replayed from storage, we might already have a configuration // for this room as they are persisted as well. // We just need to make sure the algorithm is initialized in this case. // However, if the new config is different, // we should bail out as room encryption can't be changed once set. existingConfig = this._roomList.getRoomEncryption(roomId); if (!existingConfig) { _context31.next = 8; break; } if (!(JSON.stringify(existingConfig) != JSON.stringify(config))) { _context31.next = 8; break; } _logger.logger.error("Ignoring m.room.encryption event which requests " + "a change of config in " + roomId); return _context31.abrupt("return"); case 8: // if we already have encryption in this room, we should ignore this event, // as it would reset the encryption algorithm. // This is at least expected to be called twice, as sync calls onCryptoEvent // for both the timeline and state sections in the /sync response, // the encryption event would appear in both. // If it's called more than twice though, // it signals a bug on client or server. existingAlg = this._roomEncryptors[roomId]; if (!existingAlg) { _context31.next = 11; break; } return _context31.abrupt("return"); case 11: // _roomList.getRoomEncryption will not race with _roomList.setRoomEncryption // because it first stores in memory. We should await the promise only // after all the in-memory state (_roomEncryptors and _roomList) has been updated // to avoid races when calling this method multiple times. Hence keep a hold of the promise. storeConfigPromise = null; if (!existingConfig) { storeConfigPromise = this._roomList.setRoomEncryption(roomId, config); } AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm]; if (AlgClass) { _context31.next = 16; break; } throw new Error("Unable to encrypt with " + config.algorithm); case 16: alg = new AlgClass({ userId: this._userId, deviceId: this._deviceId, crypto: this, olmDevice: this._olmDevice, baseApis: this._baseApis, roomId: roomId, config: config }); this._roomEncryptors[roomId] = alg; if (!storeConfigPromise) { _context31.next = 21; break; } _context31.next = 21; return storeConfigPromise; case 21: if (this._lazyLoadMembers) { _context31.next = 28; break; } _logger.logger.log("Enabling encryption in " + roomId + "; " + "starting to track device lists for all users therein"); _context31.next = 25; return this.trackRoomDevices(roomId); case 25: // TODO: this flag is only not used from MatrixClient::setRoomEncryption // which is never used (inside Element at least) // but didn't want to remove it as it technically would // be a breaking change. if (!this.inhibitDeviceQuery) { this._deviceList.refreshOutdatedDeviceLists(); } _context31.next = 29; break; case 28: _logger.logger.log("Enabling encryption in " + roomId); case 29: case "end": return _context31.stop(); } } }, _callee31, this); })); return function (_x34, _x35, _x36) { return _ref44.apply(this, arguments); }; }(); /** * Make sure we are tracking the device lists for all users in this room. * * @param {string} roomId The room ID to start tracking devices in. * @returns {Promise} when all devices for the room have been fetched and marked to track */ Crypto.prototype.trackRoomDevices = function (roomId) { var _this11 = this; var trackMembers = /*#__PURE__*/function () { var _ref45 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee32() { var room, members; return _regenerator["default"].wrap(function _callee32$(_context32) { while (1) { switch (_context32.prev = _context32.next) { case 0: if (_this11._roomEncryptors[roomId]) { _context32.next = 2; break; } return _context32.abrupt("return"); case 2: room = _this11._clientStore.getRoom(roomId); if (room) { _context32.next = 5; break; } throw new Error("Unable to start tracking devices in unknown room ".concat(roomId)); case 5: _logger.logger.log("Starting to track devices for room ".concat(roomId, " ...")); _context32.next = 8; return room.getEncryptionTargetMembers(); case 8: members = _context32.sent; members.forEach(function (m) { _this11._deviceList.startTrackingDeviceList(m.userId); }); case 10: case "end": return _context32.stop(); } } }, _callee32); })); return function trackMembers() { return _ref45.apply(this, arguments); }; }(); var promise = this._roomDeviceTrackingState[roomId]; if (!promise) { promise = trackMembers(); this._roomDeviceTrackingState[roomId] = promise; } return promise; }; /** * @typedef {Object} module:crypto~OlmSessionResult * @property {module:crypto/deviceinfo} device device info * @property {string?} sessionId base64 olm session id; null if no session * could be established */ /** * Try to make sure we have established olm sessions for all known devices for * the given users. * * @param {string[]} users list of user ids * * @return {Promise} resolves once the sessions are complete, to * an Object mapping from userId to deviceId to * {@link module:crypto~OlmSessionResult} */ Crypto.prototype.ensureOlmSessionsForUsers = function (users) { var devicesByUser = {}; for (var i = 0; i < users.length; ++i) { var userId = users[i]; devicesByUser[userId] = []; var devices = this.getStoredDevicesForUser(userId) || []; for (var j = 0; j < devices.length; ++j) { var deviceInfo = devices[j]; var key = deviceInfo.getIdentityKey(); if (key == this._olmDevice.deviceCurve25519Key) { // don't bother setting up session to ourself continue; } if (deviceInfo.verified == DeviceVerification.BLOCKED) { // don't bother setting up sessions with blocked users continue; } devicesByUser[userId].push(deviceInfo); } } return olmlib.ensureOlmSessionsForDevices(this._olmDevice, this._baseApis, devicesByUser); }; /** * Get a list containing all of the room keys * * @return {module:crypto/OlmDevice.MegolmSessionData[]} a list of session export objects */ Crypto.prototype.exportRoomKeys = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee33() { var _this12 = this; var exportedSessions; return _regenerator["default"].wrap(function _callee33$(_context33) { while (1) { switch (_context33.prev = _context33.next) { case 0: exportedSessions = []; _context33.next = 3; return this._cryptoStore.doTxn('readonly', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], function (txn) { _this12._cryptoStore.getAllEndToEndInboundGroupSessions(txn, function (s) { if (s === null) return; var sess = _this12._olmDevice.exportInboundGroupSession(s.senderKey, s.sessionId, s.sessionData); delete sess.first_known_index; sess.algorithm = olmlib.MEGOLM_ALGORITHM; exportedSessions.push(sess); }); }); case 3: return _context33.abrupt("return", exportedSessions); case 4: case "end": return _context33.stop(); } } }, _callee33, this); })); /** * Import a list of room keys previously exported by exportRoomKeys * * @param {Object[]} keys a list of session export objects * @param {Object} opts * @param {Function} opts.progressCallback called with an object which has a stage param * @return {Promise} a promise which resolves once the keys have been imported */ Crypto.prototype.importRoomKeys = function (keys) { var _this13 = this; var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var successes = 0; var failures = 0; var total = keys.length; function updateProgress() { opts.progressCallback({ stage: "load_keys", successes: successes, failures: failures, total: total }); } return Promise.all(keys.map(function (key) { if (!key.room_id || !key.algorithm) { _logger.logger.warn("ignoring room key entry with missing fields", key); failures++; if (opts.progressCallback) { updateProgress(); } return null; } var alg = _this13._getRoomDecryptor(key.room_id, key.algorithm); return alg.importRoomKey(key, opts)["finally"](function (r) { successes++; if (opts.progressCallback) { updateProgress(); } }); })); }; /** * Schedules sending all keys waiting to be sent to the backup, if not already * scheduled. Retries if necessary. * * @param {number} maxDelay Maximum delay to wait in ms. 0 means no delay. */ Crypto.prototype.scheduleKeyBackupSend = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee34() { var maxDelay, delay, numFailures, numBackedUp, _args34 = arguments; return _regenerator["default"].wrap(function _callee34$(_context34) { while (1) { switch (_context34.prev = _context34.next) { case 0: maxDelay = _args34.length > 0 && _args34[0] !== undefined ? _args34[0] : 10000; if (!this._sendingBackups) { _context34.next = 3; break; } return _context34.abrupt("return"); case 3: this._sendingBackups = true; _context34.prev = 4; // wait between 0 and `maxDelay` seconds, to avoid backup // requests from different clients hitting the server all at // the same time when a new key is sent delay = Math.random() * maxDelay; _context34.next = 8; return (0, utils.sleep)(delay); case 8: numFailures = 0; // number of consecutive failures case 9: if (!1) { _context34.next = 36; break; } if (this.backupKey) { _context34.next = 12; break; } return _context34.abrupt("return"); case 12: _context34.prev = 12; _context34.next = 15; return this._backupPendingKeys(KEY_BACKUP_KEYS_PER_REQUEST); case 15: numBackedUp = _context34.sent; if (!(numBackedUp === 0)) { _context34.next = 18; break; } return _context34.abrupt("return"); case 18: numFailures = 0; _context34.next = 31; break; case 21: _context34.prev = 21; _context34.t0 = _context34["catch"](12); numFailures++; _logger.logger.log("Key backup request failed", _context34.t0); if (!_context34.t0.data) { _context34.next = 31; break; } if (!(_context34.t0.data.errcode == 'M_NOT_FOUND' || _context34.t0.data.errcode == 'M_WRONG_ROOM_KEYS_VERSION')) { _context34.next = 31; break; } _context34.next = 29; return this.checkKeyBackup(); case 29: // Backup version has changed or this backup version // has been deleted this.emit("crypto.keyBackupFailed", _context34.t0.data.errcode); throw _context34.t0; case 31: if (!numFailures) { _context34.next = 34; break; } _context34.next = 34; return (0, utils.sleep)(1000 * Math.pow(2, Math.min(numFailures - 1, 4))); case 34: _context34.next = 9; break; case 36: _context34.prev = 36; this._sendingBackups = false; return _context34.finish(36); case 39: case "end": return _context34.stop(); } } }, _callee34, this, [[4,, 36, 39], [12, 21]]); })); /** * Take some e2e keys waiting to be backed up and send them * to the backup. * * @param {integer} limit Maximum number of keys to back up * @returns {integer} Number of sessions backed up */ Crypto.prototype._backupPendingKeys = /*#__PURE__*/function () { var _ref48 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee35(limit) { var sessions, remaining, data, _iterator4, _step4, session, roomId, sessionData, firstKnownIndex, encrypted, forwardedCount, userId, device, verified; return _regenerator["default"].wrap(function _callee35$(_context35) { while (1) { switch (_context35.prev = _context35.next) { case 0: _context35.next = 2; return this._cryptoStore.getSessionsNeedingBackup(limit); case 2: sessions = _context35.sent; if (sessions.length) { _context35.next = 5; break; } return _context35.abrupt("return", 0); case 5: _context35.next = 7; return this._cryptoStore.countSessionsNeedingBackup(); case 7: remaining = _context35.sent; this.emit("crypto.keyBackupSessionsRemaining", remaining); data = {}; _iterator4 = _createForOfIteratorHelper(sessions); _context35.prev = 11; _iterator4.s(); case 13: if ((_step4 = _iterator4.n()).done) { _context35.next = 33; break; } session = _step4.value; roomId = session.sessionData.room_id; if (data[roomId] === undefined) { data[roomId] = { sessions: {} }; } _context35.next = 19; return this._olmDevice.exportInboundGroupSession(session.senderKey, session.sessionId, session.sessionData); case 19: sessionData = _context35.sent; sessionData.algorithm = olmlib.MEGOLM_ALGORITHM; delete sessionData.session_id; delete sessionData.room_id; firstKnownIndex = sessionData.first_known_index; delete sessionData.first_known_index; encrypted = this.backupKey.encrypt(JSON.stringify(sessionData)); forwardedCount = (sessionData.forwarding_curve25519_key_chain || []).length; userId = this._deviceList.getUserByIdentityKey(olmlib.MEGOLM_ALGORITHM, session.senderKey); device = this._deviceList.getDeviceByIdentityKey(olmlib.MEGOLM_ALGORITHM, session.senderKey); verified = this._checkDeviceInfoTrust(userId, device).isVerified(); data[roomId]['sessions'][session.sessionId] = { first_message_index: firstKnownIndex, forwarded_count: forwardedCount, is_verified: verified, session_data: encrypted }; case 31: _context35.next = 13; break; case 33: _context35.next = 38; break; case 35: _context35.prev = 35; _context35.t0 = _context35["catch"](11); _iterator4.e(_context35.t0); case 38: _context35.prev = 38; _iterator4.f(); return _context35.finish(38); case 41: _context35.next = 43; return this._baseApis.sendKeyBackup(undefined, undefined, this.backupInfo.version, { rooms: data }); case 43: _context35.next = 45; return this._cryptoStore.unmarkSessionsNeedingBackup(sessions); case 45: _context35.next = 47; return this._cryptoStore.countSessionsNeedingBackup(); case 47: remaining = _context35.sent; this.emit("crypto.keyBackupSessionsRemaining", remaining); return _context35.abrupt("return", sessions.length); case 50: case "end": return _context35.stop(); } } }, _callee35, this, [[11, 35, 38, 41]]); })); return function (_x37) { return _ref48.apply(this, arguments); }; }(); Crypto.prototype.backupGroupSession = /*#__PURE__*/function () { var _ref49 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee36(roomId, senderKey, forwardingCurve25519KeyChain, sessionId, sessionKey, keysClaimed, exportFormat) { return _regenerator["default"].wrap(function _callee36$(_context36) { while (1) { switch (_context36.prev = _context36.next) { case 0: if (this.backupInfo) { _context36.next = 2; break; } throw new Error("Key backups are not enabled"); case 2: _context36.next = 4; return this._cryptoStore.markSessionsNeedingBackup([{ senderKey: senderKey, sessionId: sessionId }]); case 4: // don't wait for this to complete: it will delay so // happens in the background this.scheduleKeyBackupSend(); case 5: case "end": return _context36.stop(); } } }, _callee36, this); })); return function (_x38, _x39, _x40, _x41, _x42, _x43, _x44) { return _ref49.apply(this, arguments); }; }(); /** * Marks all group sessions as needing to be backed up and schedules them to * upload in the background as soon as possible. */ Crypto.prototype.scheduleAllGroupSessionsForBackup = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee37() { return _regenerator["default"].wrap(function _callee37$(_context37) { while (1) { switch (_context37.prev = _context37.next) { case 0: _context37.next = 2; return this.flagAllGroupSessionsForBackup(); case 2: // Schedule keys to upload in the background as soon as possible. this.scheduleKeyBackupSend(0 /* maxDelay */ ); case 3: case "end": return _context37.stop(); } } }, _callee37, this); })); /** * Marks all group sessions as needing to be backed up without scheduling * them to upload in the background. * @returns {Promise} Resolves to the number of sessions now requiring a backup * (which will be equal to the number of sessions in the store). */ Crypto.prototype.flagAllGroupSessionsForBackup = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee38() { var _this14 = this; var remaining; return _regenerator["default"].wrap(function _callee38$(_context38) { while (1) { switch (_context38.prev = _context38.next) { case 0: _context38.next = 2; return this._cryptoStore.doTxn('readwrite', [_indexeddbCryptoStore.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, _indexeddbCryptoStore.IndexedDBCryptoStore.STORE_BACKUP], function (txn) { _this14._cryptoStore.getAllEndToEndInboundGroupSessions(txn, function (session) { if (session !== null) { _this14._cryptoStore.markSessionsNeedingBackup([session], txn); } }); }); case 2: _context38.next = 4; return this._cryptoStore.countSessionsNeedingBackup(); case 4: remaining = _context38.sent; this.emit("crypto.keyBackupSessionsRemaining", remaining); return _context38.abrupt("return", remaining); case 7: case "end": return _context38.stop(); } } }, _callee38, this); })); /** * Counts the number of end to end session keys that are waiting to be backed up * @returns {Promise} Resolves to the number of sessions requiring backup */ Crypto.prototype.countSessionsNeedingBackup = function () { return this._cryptoStore.countSessionsNeedingBackup(); }; /** * Perform any background tasks that can be done before a message is ready to * send, in order to speed up sending of the message. * * @param {module:models/room} room the room the event is in */ Crypto.prototype.prepareToEncrypt = function (room) { var roomId = room.roomId; var alg = this._roomEncryptors[roomId]; if (alg) { alg.prepareToEncrypt(room); } }; /* eslint-disable valid-jsdoc */ //https://github.com/eslint/eslint/issues/7307 /** * Encrypt an event according to the configuration of the room. * * @param {module:models/event.MatrixEvent} event event to be sent * * @param {module:models/room} room destination room. * * @return {Promise?} Promise which resolves when the event has been * encrypted, or null if nothing was needed */ /* eslint-enable valid-jsdoc */ Crypto.prototype.encryptEvent = /*#__PURE__*/function () { var _ref52 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee39(event, room) { var roomId, alg, content, mRelatesTo, encryptedContent; return _regenerator["default"].wrap(function _callee39$(_context39) { while (1) { switch (_context39.prev = _context39.next) { case 0: if (room) { _context39.next = 2; break; } throw new Error("Cannot send encrypted messages in unknown rooms"); case 2: roomId = event.getRoomId(); alg = this._roomEncryptors[roomId]; if (alg) { _context39.next = 6; break; } throw new Error("Room was previously configured to use encryption, but is " + "no longer. Perhaps the homeserver is hiding the " + "configuration event."); case 6: if (!this._roomDeviceTrackingState[roomId]) { this.trackRoomDevices(roomId); } // wait for all the room devices to be loaded _context39.next = 9; return this._roomDeviceTrackingState[roomId]; case 9: content = event.getContent(); // If event has an m.relates_to then we need // to put this on the wrapping event instead mRelatesTo = content['m.relates_to']; if (mRelatesTo) { // Clone content here so we don't remove `m.relates_to` from the local-echo content = Object.assign({}, content); delete content['m.relates_to']; } _context39.next = 14; return alg.encryptMessage(room, event.getType(), content); case 14: encryptedContent = _context39.sent; if (mRelatesTo) { encryptedContent['m.relates_to'] = mRelatesTo; } event.makeEncrypted("m.room.encrypted", encryptedContent, this._olmDevice.deviceCurve25519Key, this._olmDevice.deviceEd25519Key); case 17: case "end": return _context39.stop(); } } }, _callee39, this); })); return function (_x45, _x46) { return _ref52.apply(this, arguments); }; }(); /** * Decrypt a received event * * @param {MatrixEvent} event * * @return {Promise} resolves once we have * finished decrypting. Rejects with an `algorithms.DecryptionError` if there * is a problem decrypting the event. */ Crypto.prototype.decryptEvent = function (event) { if (event.isRedacted()) { return Promise.resolve({ clearEvent: { room_id: event.getRoomId(), type: "m.room.message", content: {} } }); } var content = event.getWireContent(); var alg = this._getRoomDecryptor(event.getRoomId(), content.algorithm); return alg.decryptEvent(event); }; /** * Handle the notification from /sync or /keys/changes that device lists have * been changed. * * @param {Object} syncData Object containing sync tokens associated with this sync * @param {Object} syncDeviceLists device_lists field from /sync, or response from * /keys/changes */ Crypto.prototype.handleDeviceListChanges = /*#__PURE__*/function () { var _ref53 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee40(syncData, syncDeviceLists) { return _regenerator["default"].wrap(function _callee40$(_context40) { while (1) { switch (_context40.prev = _context40.next) { case 0: if (syncData.oldSyncToken) { _context40.next = 2; break; } return _context40.abrupt("return"); case 2: _context40.next = 4; return this._evalDeviceListChanges(syncDeviceLists); case 4: case "end": return _context40.stop(); } } }, _callee40, this); })); return function (_x47, _x48) { return _ref53.apply(this, arguments); }; }(); /** * Send a request for some room keys, if we have not already done so * * @param {module:crypto~RoomKeyRequestBody} requestBody * @param {Array<{userId: string, deviceId: string}>} recipients * @param {boolean} resend whether to resend the key request if there is * already one * * @return {Promise} a promise that resolves when the key request is queued */ Crypto.prototype.requestRoomKey = function (requestBody, recipients) { var _this15 = this; var resend = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return this._outgoingRoomKeyRequestManager.queueRoomKeyRequest(requestBody, recipients, resend).then(function () { if (_this15._sendKeyRequestsImmediately) { _this15._outgoingRoomKeyRequestManager.sendQueuedRequests(); } })["catch"](function (e) { // this normally means we couldn't talk to the store _logger.logger.error('Error requesting key for event', e); }); }; /** * Cancel any earlier room key request * * @param {module:crypto~RoomKeyRequestBody} requestBody * parameters to match for cancellation */ Crypto.prototype.cancelRoomKeyRequest = function (requestBody) { this._outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody)["catch"](function (e) { _logger.logger.warn("Error clearing pending room key requests", e); }); }; /** * Re-send any outgoing key requests, eg after verification * @returns {Promise} */ Crypto.prototype.cancelAndResendAllOutgoingKeyRequests = function () { return this._outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests(); }; /** * handle an m.room.encryption event * * @param {module:models/event.MatrixEvent} event encryption event */ Crypto.prototype.onCryptoEvent = /*#__PURE__*/function () { var _ref54 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee41(event) { var roomId, content; return _regenerator["default"].wrap(function _callee41$(_context41) { while (1) { switch (_context41.prev = _context41.next) { case 0: roomId = event.getRoomId(); content = event.getContent(); _context41.prev = 2; _context41.next = 5; return this.setRoomEncryption(roomId, content, true); case 5: _context41.next = 10; break; case 7: _context41.prev = 7; _context41.t0 = _context41["catch"](2); _logger.logger.error("Error configuring encryption in room " + roomId + ":", _context41.t0); case 10: case "end": return _context41.stop(); } } }, _callee41, this, [[2, 7]]); })); return function (_x49) { return _ref54.apply(this, arguments); }; }(); /** * Called before the result of a sync is procesed * * @param {Object} syncData the data from the 'MatrixClient.sync' event */ Crypto.prototype.onSyncWillProcess = /*#__PURE__*/function () { var _ref55 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee42(syncData) { return _regenerator["default"].wrap(function _callee42$(_context42) { while (1) { switch (_context42.prev = _context42.next) { case 0: if (!syncData.oldSyncToken) { // If there is no old sync token, we start all our tracking from // scratch, so mark everything as untracked. onCryptoEvent will // be called for all e2e rooms during the processing of the sync, // at which point we'll start tracking all the users of that room. _logger.logger.log("Initial sync performed - resetting device tracking state"); this._deviceList.stopTrackingAllDeviceLists(); // we always track our own device list (for key backups etc) this._deviceList.startTrackingDeviceList(this._userId); this._roomDeviceTrackingState = {}; } this._sendKeyRequestsImmediately = false; case 2: case "end": return _context42.stop(); } } }, _callee42, this); })); return function (_x50) { return _ref55.apply(this, arguments); }; }(); /** * handle the completion of a /sync * * This is called after the processing of each successful /sync response. * It is an opportunity to do a batch process on the information received. * * @param {Object} syncData the data from the 'MatrixClient.sync' event */ Crypto.prototype.onSyncCompleted = /*#__PURE__*/function () { var _ref56 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee43(syncData) { var nextSyncToken; return _regenerator["default"].wrap(function _callee43$(_context43) { while (1) { switch (_context43.prev = _context43.next) { case 0: nextSyncToken = syncData.nextSyncToken; this._deviceList.setSyncToken(syncData.nextSyncToken); this._deviceList.saveIfDirty(); // catch up on any new devices we got told about during the sync. this._deviceList.lastKnownSyncToken = nextSyncToken; // we always track our own device list (for key backups etc) this._deviceList.startTrackingDeviceList(this._userId); this._deviceList.refreshOutdatedDeviceLists(); // we don't start uploading one-time keys until we've caught up with // to-device messages, to help us avoid throwing away one-time-keys that we // are about to receive messages for // (https://github.com/vector-im/element-web/issues/2782). if (!syncData.catchingUp) { _maybeUploadOneTimeKeys(this); this._processReceivedRoomKeyRequests(); // likewise don't start requesting keys until we've caught up // on to_device messages, otherwise we'll request keys that we're // just about to get. this._outgoingRoomKeyRequestManager.sendQueuedRequests(); // Sync has finished so send key requests straight away. this._sendKeyRequestsImmediately = true; } case 7: case "end": return _context43.stop(); } } }, _callee43, this); })); return function (_x51) { return _ref56.apply(this, arguments); }; }(); /** * Trigger the appropriate invalidations and removes for a given * device list * * @param {Object} deviceLists device_lists field from /sync, or response from * /keys/changes */ Crypto.prototype._evalDeviceListChanges = /*#__PURE__*/function () { var _ref57 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee44(deviceLists) { var _this16 = this; var e2eUserIds; return _regenerator["default"].wrap(function _callee44$(_context44) { while (1) { switch (_context44.prev = _context44.next) { case 0: if (deviceLists.changed && Array.isArray(deviceLists.changed)) { deviceLists.changed.forEach(function (u) { _this16._deviceList.invalidateUserDeviceList(u); }); } if (!(deviceLists.left && Array.isArray(deviceLists.left) && deviceLists.left.length)) { _context44.next = 8; break; } _context44.t0 = Set; _context44.next = 5; return this._getTrackedE2eUsers(); case 5: _context44.t1 = _context44.sent; e2eUserIds = new _context44.t0(_context44.t1); deviceLists.left.forEach(function (u) { if (!e2eUserIds.has(u)) { _this16._deviceList.stopTrackingDeviceList(u); } }); case 8: case "end": return _context44.stop(); } } }, _callee44, this); })); return function (_x52) { return _ref57.apply(this, arguments); }; }(); /** * Get a list of all the IDs of users we share an e2e room with * for which we are tracking devices already * * @returns {string[]} List of user IDs */ Crypto.prototype._getTrackedE2eUsers = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee45() { var e2eUserIds, _iterator5, _step5, room, members, _iterator6, _step6, member; return _regenerator["default"].wrap(function _callee45$(_context45) { while (1) { switch (_context45.prev = _context45.next) { case 0: e2eUserIds = []; _iterator5 = _createForOfIteratorHelper(this._getTrackedE2eRooms()); _context45.prev = 2; _iterator5.s(); case 4: if ((_step5 = _iterator5.n()).done) { _context45.next = 13; break; } room = _step5.value; _context45.next = 8; return room.getEncryptionTargetMembers(); case 8: members = _context45.sent; _iterator6 = _createForOfIteratorHelper(members); try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { member = _step6.value; e2eUserIds.push(member.userId); } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } case 11: _context45.next = 4; break; case 13: _context45.next = 18; break; case 15: _context45.prev = 15; _context45.t0 = _context45["catch"](2); _iterator5.e(_context45.t0); case 18: _context45.prev = 18; _iterator5.f(); return _context45.finish(18); case 21: return _context45.abrupt("return", e2eUserIds); case 22: case "end": return _context45.stop(); } } }, _callee45, this, [[2, 15, 18, 21]]); })); /** * Get a list of the e2e-enabled rooms we are members of, * and for which we are already tracking the devices * * @returns {module:models.Room[]} */ Crypto.prototype._getTrackedE2eRooms = function () { var _this17 = this; return this._clientStore.getRooms().filter(function (room) { // check for rooms with encryption enabled var alg = _this17._roomEncryptors[room.roomId]; if (!alg) { return false; } if (!_this17._roomDeviceTrackingState[room.roomId]) { return false; } // ignore any rooms which we have left var myMembership = room.getMyMembership(); return myMembership === "join" || myMembership === "invite"; }); }; Crypto.prototype._onToDeviceEvent = function (event) { var _this18 = this; try { _logger.logger.log("received to_device ".concat(event.getType(), " from: ") + "".concat(event.getSender(), " id: ").concat(event.getId())); if (event.getType() == "m.room_key" || event.getType() == "m.forwarded_room_key") { this._onRoomKeyEvent(event); } else if (event.getType() == "m.room_key_request") { this._onRoomKeyRequestEvent(event); } else if (event.getType() === "m.secret.request") { this._secretStorage._onRequestReceived(event); } else if (event.getType() === "m.secret.send") { this._secretStorage._onSecretReceived(event); } else if (event.getType() === "org.matrix.room_key.withheld") { this._onRoomKeyWithheldEvent(event); } else if (event.getContent().transaction_id) { this._onKeyVerificationMessage(event); } else if (event.getContent().msgtype === "m.bad.encrypted") { this._onToDeviceBadEncrypted(event); } else if (event.isBeingDecrypted()) { // once the event has been decrypted, try again event.once('Event.decrypted', function (ev) { _this18._onToDeviceEvent(ev); }); } } catch (e) { _logger.logger.error("Error handling toDeviceEvent:", e); } }; /** * Handle a key event * * @private * @param {module:models/event.MatrixEvent} event key event */ Crypto.prototype._onRoomKeyEvent = function (event) { var content = event.getContent(); if (!content.room_id || !content.algorithm) { _logger.logger.error("key event is missing fields"); return; } if (!this._checkedForBackup) { // don't bother awaiting on this - the important thing is that we retry if we // haven't managed to check before this._checkAndStartKeyBackup(); } var alg = this._getRoomDecryptor(content.room_id, content.algorithm); alg.onRoomKeyEvent(event); }; /** * Handle a key withheld event * * @private * @param {module:models/event.MatrixEvent} event key withheld event */ Crypto.prototype._onRoomKeyWithheldEvent = function (event) { var content = event.getContent(); if (content.code !== "m.no_olm" && (!content.room_id || !content.session_id) || !content.algorithm || !content.sender_key) { _logger.logger.error("key withheld event is missing fields"); return; } _logger.logger.info("Got room key withheld event from ".concat(event.getSender(), " (").concat(content.sender_key, ") ") + "for ".concat(content.algorithm, "/").concat(content.room_id, "/").concat(content.session_id, " ") + "with reason ".concat(content.code, " (").concat(content.reason, ")")); var alg = this._getRoomDecryptor(content.room_id, content.algorithm); if (alg.onRoomKeyWithheldEvent) { alg.onRoomKeyWithheldEvent(event); } if (!content.room_id) { // retry decryption for all events sent by the sender_key. This will // update the events to show a message indicating that the olm session was // wedged. var roomDecryptors = this._getRoomDecryptors(content.algorithm); var _iterator7 = _createForOfIteratorHelper(roomDecryptors), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var decryptor = _step7.value; decryptor.retryDecryptionFromSender(content.sender_key); } } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } } }; /** * Handle a general key verification event. * * @private * @param {module:models/event.MatrixEvent} event verification start event */ Crypto.prototype._onKeyVerificationMessage = function (event) { var _this19 = this; if (!_ToDeviceChannel.ToDeviceChannel.validateEvent(event, this._baseApis)) { return; } var createRequest = function createRequest(event) { if (!_ToDeviceChannel.ToDeviceChannel.canCreateRequest(_ToDeviceChannel.ToDeviceChannel.getEventType(event))) { return; } var content = event.getContent(); var deviceId = content && content.from_device; if (!deviceId) { return; } var userId = event.getSender(); var channel = new _ToDeviceChannel.ToDeviceChannel(_this19._baseApis, userId, [deviceId]); return new _VerificationRequest.VerificationRequest(channel, _this19._verificationMethods, _this19._baseApis); }; this._handleVerificationEvent(event, this._toDeviceVerificationRequests, createRequest); }; /** * Handle key verification requests sent as timeline events * * @private * @param {module:models/event.MatrixEvent} event the timeline event * @param {module:models/Room} room not used * @param {bool} atStart not used * @param {bool} removed not used * @param {bool} data.liveEvent whether this is a live event */ Crypto.prototype._onTimelineEvent = function (event, room, atStart, removed) { var _this20 = this; var _ref59 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}, liveEvent = _ref59.liveEvent; if (!_InRoomChannel.InRoomChannel.validateEvent(event, this._baseApis)) { return; } var createRequest = function createRequest(event) { var channel = new _InRoomChannel.InRoomChannel(_this20._baseApis, event.getRoomId()); return new _VerificationRequest.VerificationRequest(channel, _this20._verificationMethods, _this20._baseApis); }; this._handleVerificationEvent(event, this._inRoomVerificationRequests, createRequest, liveEvent); }; Crypto.prototype._handleVerificationEvent = /*#__PURE__*/function () { var _ref60 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee46(event, requestsMap, createRequest) { var isLiveEvent, request, isNewRequest, shouldEmit, _args46 = arguments; return _regenerator["default"].wrap(function _callee46$(_context46) { while (1) { switch (_context46.prev = _context46.next) { case 0: isLiveEvent = _args46.length > 3 && _args46[3] !== undefined ? _args46[3] : true; request = requestsMap.getRequest(event); isNewRequest = false; if (request) { _context46.next = 10; break; } request = createRequest(event); // a request could not be made from this event, so ignore event if (request) { _context46.next = 8; break; } _logger.logger.log("Crypto: could not find VerificationRequest for " + "".concat(event.getType(), ", and could not create one, so ignoring.")); return _context46.abrupt("return"); case 8: isNewRequest = true; requestsMap.setRequest(event, request); case 10: event.setVerificationRequest(request); _context46.prev = 11; _context46.next = 14; return request.channel.handleEvent(event, request, isLiveEvent); case 14: _context46.next = 19; break; case 16: _context46.prev = 16; _context46.t0 = _context46["catch"](11); _logger.logger.error("error while handling verification event: " + _context46.t0.message); case 19: shouldEmit = isNewRequest && !request.initiatedByMe && !request.invalid && // check it has enough events to pass the UNSENT stage !request.observeOnly; if (shouldEmit) { this._baseApis.emit("crypto.verification.request", request); } case 21: case "end": return _context46.stop(); } } }, _callee46, this, [[11, 16]]); })); return function (_x53, _x54, _x55) { return _ref60.apply(this, arguments); }; }(); /** * Handle a toDevice event that couldn't be decrypted * * @private * @param {module:models/event.MatrixEvent} event undecryptable event */ Crypto.prototype._onToDeviceBadEncrypted = /*#__PURE__*/function () { var _ref61 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee47(event) { var _this21 = this; var content, sender, algorithm, deviceKey, retryDecryption, lastNewSessionForced, device, devicesByUser, encryptedContent, requestsToResend, _iterator9, _step9, keyReq; return _regenerator["default"].wrap(function _callee47$(_context47) { while (1) { switch (_context47.prev = _context47.next) { case 0: content = event.getWireContent(); sender = event.getSender(); algorithm = content.algorithm; deviceKey = content.sender_key; // retry decryption for all events sent by the sender_key. This will // update the events to show a message indicating that the olm session was // wedged. retryDecryption = function retryDecryption() { var roomDecryptors = _this21._getRoomDecryptors(olmlib.MEGOLM_ALGORITHM); var _iterator8 = _createForOfIteratorHelper(roomDecryptors), _step8; try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { var decryptor = _step8.value; decryptor.retryDecryptionFromSender(deviceKey); } } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } }; if (!(sender === undefined || deviceKey === undefined || deviceKey === undefined)) { _context47.next = 7; break; } return _context47.abrupt("return"); case 7: // check when we last forced a new session with this device: if we've already done so // recently, don't do it again. this._lastNewSessionForced[sender] = this._lastNewSessionForced[sender] || {}; lastNewSessionForced = this._lastNewSessionForced[sender][deviceKey] || 0; if (!(lastNewSessionForced + MIN_FORCE_SESSION_INTERVAL_MS > Date.now())) { _context47.next = 15; break; } _logger.logger.debug("New session already forced with device " + sender + ":" + deviceKey + " at " + lastNewSessionForced + ": not forcing another"); _context47.next = 13; return this._olmDevice.recordSessionProblem(deviceKey, "wedged", true); case 13: retryDecryption(); return _context47.abrupt("return"); case 15: // establish a new olm session with this device since we're failing to decrypt messages // on a current session. // Note that an undecryptable message from another device could easily be spoofed - // is there anything we can do to mitigate this? device = this._deviceList.getDeviceByIdentityKey(algorithm, deviceKey); if (device) { _context47.next = 26; break; } _context47.next = 19; return this.downloadKeys([sender], false); case 19: device = this._deviceList.getDeviceByIdentityKey(algorithm, deviceKey); if (device) { _context47.next = 26; break; } _logger.logger.info("Couldn't find device for identity key " + deviceKey + ": not re-establishing session"); _context47.next = 24; return this._olmDevice.recordSessionProblem(deviceKey, "wedged", false); case 24: retryDecryption(); return _context47.abrupt("return"); case 26: devicesByUser = {}; devicesByUser[sender] = [device]; _context47.next = 30; return olmlib.ensureOlmSessionsForDevices(this._olmDevice, this._baseApis, devicesByUser, true); case 30: this._lastNewSessionForced[sender][deviceKey] = Date.now(); // Now send a blank message on that session so the other side knows about it. // (The keyshare request is sent in the clear so that won't do) // We send this first such that, as long as the toDevice messages arrive in the // same order we sent them, the other end will get this first, set up the new session, // then get the keyshare request and send the key over this new session (because it // is the session it has most recently received a message on). encryptedContent = { algorithm: olmlib.OLM_ALGORITHM, sender_key: this._olmDevice.deviceCurve25519Key, ciphertext: {} }; _context47.next = 34; return olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this._userId, this._deviceId, this._olmDevice, sender, device, { type: "m.dummy" }); case 34: _context47.next = 36; return this._olmDevice.recordSessionProblem(deviceKey, "wedged", true); case 36: retryDecryption(); _context47.next = 39; return this._baseApis.sendToDevice("m.room.encrypted", (0, _defineProperty2["default"])({}, sender, (0, _defineProperty2["default"])({}, device.deviceId, encryptedContent))); case 39: _context47.next = 41; return this._outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(sender, device.deviceId); case 41: requestsToResend = _context47.sent; _iterator9 = _createForOfIteratorHelper(requestsToResend); try { for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { keyReq = _step9.value; this.requestRoomKey(keyReq.requestBody, keyReq.recipients, true); } } catch (err) { _iterator9.e(err); } finally { _iterator9.f(); } case 44: case "end": return _context47.stop(); } } }, _callee47, this); })); return function (_x56) { return _ref61.apply(this, arguments); }; }(); /** * Handle a change in the membership state of a member of a room * * @private * @param {module:models/event.MatrixEvent} event event causing the change * @param {module:models/room-member} member user whose membership changed * @param {string=} oldMembership previous membership */ Crypto.prototype._onRoomMembership = function (event, member, oldMembership) { // this event handler is registered on the *client* (as opposed to the room // member itself), which means it is only called on changes to the *live* // membership state (ie, it is not called when we back-paginate, nor when // we load the state in the initialsync). // // Further, it is automatically registered and called when new members // arrive in the room. var roomId = member.roomId; var alg = this._roomEncryptors[roomId]; if (!alg) { // not encrypting in this room return; } // only mark users in this room as tracked if we already started tracking in this room // this way we don't start device queries after sync on behalf of this room which we won't use // the result of anyway, as we'll need to do a query again once all the members are fetched // by calling _trackRoomDevices if (this._roomDeviceTrackingState[roomId]) { if (member.membership == 'join') { _logger.logger.log('Join event for ' + member.userId + ' in ' + roomId); // make sure we are tracking the deviceList for this user this._deviceList.startTrackingDeviceList(member.userId); } else if (member.membership == 'invite' && this._clientStore.getRoom(roomId).shouldEncryptForInvitedMembers()) { _logger.logger.log('Invite event for ' + member.userId + ' in ' + roomId); this._deviceList.startTrackingDeviceList(member.userId); } } alg.onRoomMembership(event, member, oldMembership); }; /** * Called when we get an m.room_key_request event. * * @private * @param {module:models/event.MatrixEvent} event key request event */ Crypto.prototype._onRoomKeyRequestEvent = function (event) { var content = event.getContent(); if (content.action === "request") { // Queue it up for now, because they tend to arrive before the room state // events at initial sync, and we want to see if we know anything about the // room before passing them on to the app. var req = new IncomingRoomKeyRequest(event); this._receivedRoomKeyRequests.push(req); } else if (content.action === "request_cancellation") { var _req = new IncomingRoomKeyRequestCancellation(event); this._receivedRoomKeyRequestCancellations.push(_req); } }; /** * Process any m.room_key_request events which were queued up during the * current sync. * * @private */ Crypto.prototype._processReceivedRoomKeyRequests = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee48() { var _this22 = this; var requests, cancellations; return _regenerator["default"].wrap(function _callee48$(_context48) { while (1) { switch (_context48.prev = _context48.next) { case 0: if (!this._processingRoomKeyRequests) { _context48.next = 2; break; } return _context48.abrupt("return"); case 2: this._processingRoomKeyRequests = true; _context48.prev = 3; // we need to grab and clear the queues in the synchronous bit of this method, // so that we don't end up racing with the next /sync. requests = this._receivedRoomKeyRequests; this._receivedRoomKeyRequests = []; cancellations = this._receivedRoomKeyRequestCancellations; this._receivedRoomKeyRequestCancellations = []; // Process all of the requests, *then* all of the cancellations. // // This makes sure that if we get a request and its cancellation in the // same /sync result, then we process the request before the // cancellation (and end up with a cancelled request), rather than the // cancellation before the request (and end up with an outstanding // request which should have been cancelled.) _context48.next = 10; return Promise.all(requests.map(function (req) { return _this22._processReceivedRoomKeyRequest(req); })); case 10: _context48.next = 12; return Promise.all(cancellations.map(function (cancellation) { return _this22._processReceivedRoomKeyRequestCancellation(cancellation); })); case 12: _context48.next = 17; break; case 14: _context48.prev = 14; _context48.t0 = _context48["catch"](3); _logger.logger.error("Error processing room key requsts: ".concat(_context48.t0)); case 17: _context48.prev = 17; this._processingRoomKeyRequests = false; return _context48.finish(17); case 20: case "end": return _context48.stop(); } } }, _callee48, this, [[3, 14, 17, 20]]); })); /** * Helper for processReceivedRoomKeyRequests * * @param {IncomingRoomKeyRequest} req */ Crypto.prototype._processReceivedRoomKeyRequest = /*#__PURE__*/function () { var _ref63 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee49(req) { var userId, deviceId, body, roomId, alg, encryptor, device, decryptor; return _regenerator["default"].wrap(function _callee49$(_context49) { while (1) { switch (_context49.prev = _context49.next) { case 0: userId = req.userId; deviceId = req.deviceId; body = req.requestBody; roomId = body.room_id; alg = body.algorithm; _logger.logger.log("m.room_key_request from ".concat(userId, ":").concat(deviceId) + " for ".concat(roomId, " / ").concat(body.session_id, " (id ").concat(req.requestId, ")")); if (!(userId !== this._userId)) { _context49.next = 24; break; } if (this._roomEncryptors[roomId]) { _context49.next = 10; break; } _logger.logger.debug("room key request for unencrypted room ".concat(roomId)); return _context49.abrupt("return"); case 10: encryptor = this._roomEncryptors[roomId]; device = this._deviceList.getStoredDevice(userId, deviceId); if (device) { _context49.next = 15; break; } _logger.logger.debug("Ignoring keyshare for unknown device ".concat(userId, ":").concat(deviceId)); return _context49.abrupt("return"); case 15: _context49.prev = 15; _context49.next = 18; return encryptor.reshareKeyWithDevice(body.sender_key, body.session_id, userId, device); case 18: _context49.next = 23; break; case 20: _context49.prev = 20; _context49.t0 = _context49["catch"](15); _logger.logger.warn("Failed to re-share keys for session " + body.session_id + " with device " + userId + ":" + device.deviceId, _context49.t0); case 23: return _context49.abrupt("return"); case 24: if (!(deviceId === this._deviceId)) { _context49.next = 27; break; } // We'll always get these because we send room key requests to // '*' (ie. 'all devices') which includes the sending device, // so ignore requests from ourself because apart from it being // very silly, it won't work because an Olm session cannot send // messages to itself. // The log here is probably superfluous since we know this will // always happen, but let's log anyway for now just in case it // causes issues. _logger.logger.log("Ignoring room key request from ourselves"); return _context49.abrupt("return"); case 27: if (this._roomDecryptors[roomId]) { _context49.next = 30; break; } _logger.logger.log("room key request for unencrypted room ".concat(roomId)); return _context49.abrupt("return"); case 30: decryptor = this._roomDecryptors[roomId][alg]; if (decryptor) { _context49.next = 34; break; } _logger.logger.log("room key request for unknown alg ".concat(alg, " in room ").concat(roomId)); return _context49.abrupt("return"); case 34: _context49.next = 36; return decryptor.hasKeysForKeyRequest(req); case 36: if (_context49.sent) { _context49.next = 39; break; } _logger.logger.log("room key request for unknown session ".concat(roomId, " / ") + body.session_id); return _context49.abrupt("return"); case 39: req.share = function () { decryptor.shareKeysWithDevice(req); }; // if the device is verified already, share the keys if (!this.checkDeviceTrust(userId, deviceId).isVerified()) { _context49.next = 44; break; } _logger.logger.log('device is already verified: sharing keys'); req.share(); return _context49.abrupt("return"); case 44: this.emit("crypto.roomKeyRequest", req); case 45: case "end": return _context49.stop(); } } }, _callee49, this, [[15, 20]]); })); return function (_x57) { return _ref63.apply(this, arguments); }; }(); /** * Helper for processReceivedRoomKeyRequests * * @param {IncomingRoomKeyRequestCancellation} cancellation */ Crypto.prototype._processReceivedRoomKeyRequestCancellation = /*#__PURE__*/function () { var _ref64 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee50(cancellation) { return _regenerator["default"].wrap(function _callee50$(_context50) { while (1) { switch (_context50.prev = _context50.next) { case 0: _logger.logger.log("m.room_key_request cancellation for ".concat(cancellation.userId, ":") + "".concat(cancellation.deviceId, " (id ").concat(cancellation.requestId, ")")); // we should probably only notify the app of cancellations we told it // about, but we don't currently have a record of that, so we just pass // everything through. this.emit("crypto.roomKeyRequestCancellation", cancellation); case 2: case "end": return _context50.stop(); } } }, _callee50, this); })); return function (_x58) { return _ref64.apply(this, arguments); }; }(); /** * Get a decryptor for a given room and algorithm. * * If we already have a decryptor for the given room and algorithm, return * it. Otherwise try to instantiate it. * * @private * * @param {string?} roomId room id for decryptor. If undefined, a temporary * decryptor is instantiated. * * @param {string} algorithm crypto algorithm * * @return {module:crypto.algorithms.base.DecryptionAlgorithm} * * @raises {module:crypto.algorithms.DecryptionError} if the algorithm is * unknown */ Crypto.prototype._getRoomDecryptor = function (roomId, algorithm) { var decryptors; var alg; roomId = roomId || null; if (roomId) { decryptors = this._roomDecryptors[roomId]; if (!decryptors) { this._roomDecryptors[roomId] = decryptors = {}; } alg = decryptors[algorithm]; if (alg) { return alg; } } var AlgClass = algorithms.DECRYPTION_CLASSES[algorithm]; if (!AlgClass) { throw new algorithms.DecryptionError('UNKNOWN_ENCRYPTION_ALGORITHM', 'Unknown encryption algorithm "' + algorithm + '".'); } alg = new AlgClass({ userId: this._userId, crypto: this, olmDevice: this._olmDevice, baseApis: this._baseApis, roomId: roomId }); if (decryptors) { decryptors[algorithm] = alg; } return alg; }; /** * Get all the room decryptors for a given encryption algorithm. * * @param {string} algorithm The encryption algorithm * * @return {array} An array of room decryptors */ Crypto.prototype._getRoomDecryptors = function (algorithm) { var decryptors = []; for (var _i5 = 0, _Object$values = Object.values(this._roomDecryptors); _i5 < _Object$values.length; _i5++) { var d = _Object$values[_i5]; if (algorithm in d) { decryptors.push(d[algorithm]); } } return decryptors; }; /** * sign the given object with our ed25519 key * * @param {Object} obj Object to which we will add a 'signatures' property */ Crypto.prototype._signObject = /*#__PURE__*/function () { var _ref65 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee51(obj) { var sigs, unsigned; return _regenerator["default"].wrap(function _callee51$(_context51) { while (1) { switch (_context51.prev = _context51.next) { case 0: sigs = obj.signatures || {}; unsigned = obj.unsigned; delete obj.signatures; delete obj.unsigned; sigs[this._userId] = sigs[this._userId] || {}; _context51.next = 7; return this._olmDevice.sign(_anotherJson["default"].stringify(obj)); case 7: sigs[this._userId]["ed25519:" + this._deviceId] = _context51.sent; obj.signatures = sigs; if (unsigned !== undefined) obj.unsigned = unsigned; case 10: case "end": return _context51.stop(); } } }, _callee51, this); })); return function (_x59) { return _ref65.apply(this, arguments); }; }(); /** * The parameters of a room key request. The details of the request may * vary with the crypto algorithm, but the management and storage layers for * outgoing requests expect it to have 'room_id' and 'session_id' properties. * * @typedef {Object} RoomKeyRequestBody */ /** * Represents a received m.room_key_request event * * @property {string} userId user requesting the key * @property {string} deviceId device requesting the key * @property {string} requestId unique id for the request * @property {module:crypto~RoomKeyRequestBody} requestBody * @property {function()} share callback which, when called, will ask * the relevant crypto algorithm implementation to share the keys for * this request. */ var IncomingRoomKeyRequest = function IncomingRoomKeyRequest(event) { (0, _classCallCheck2["default"])(this, IncomingRoomKeyRequest); var content = event.getContent(); this.userId = event.getSender(); this.deviceId = content.requesting_device_id; this.requestId = content.request_id; this.requestBody = content.body || {}; this.share = function () { throw new Error("don't know how to share keys for this request yet"); }; }; /** * Represents a received m.room_key_request cancellation * * @property {string} userId user requesting the cancellation * @property {string} deviceId device requesting the cancellation * @property {string} requestId unique id for the request to be cancelled */ var IncomingRoomKeyRequestCancellation = function IncomingRoomKeyRequestCancellation(event) { (0, _classCallCheck2["default"])(this, IncomingRoomKeyRequestCancellation); var content = event.getContent(); this.userId = event.getSender(); this.deviceId = content.requesting_device_id; this.requestId = content.request_id; }; /** * The result of a (successful) call to decryptEvent. * * @typedef {Object} EventDecryptionResult * * @property {Object} clearEvent The plaintext payload for the event * (typically containing type and content fields). * * @property {?string} senderCurve25519Key Key owned by the sender of this * event. See {@link module:models/event.MatrixEvent#getSenderKey}. * * @property {?string} claimedEd25519Key ed25519 key claimed by the sender of * this event. See * {@link module:models/event.MatrixEvent#getClaimedEd25519Key}. * * @property {?Array} forwardingCurve25519KeyChain list of curve25519 * keys involved in telling us about the senderCurve25519Key and * claimedEd25519Key. See * {@link module:models/event.MatrixEvent#getForwardingCurve25519KeyChain}. */ /** * Fires when we receive a room key request * * @event module:client~MatrixClient#"crypto.roomKeyRequest" * @param {module:crypto~IncomingRoomKeyRequest} req request details */ /** * Fires when we receive a room key request cancellation * * @event module:client~MatrixClient#"crypto.roomKeyRequestCancellation" * @param {module:crypto~IncomingRoomKeyRequestCancellation} req */ /** * Fires when the app may wish to warn the user about something related * the end-to-end crypto. * * @event module:client~MatrixClient#"crypto.warning" * @param {string} type One of the strings listed above */ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"../ReEmitter":53,"../errors":89,"../logger":95,"../utils":123,"./CrossSigning":60,"./DeviceList":61,"./EncryptionSetup":62,"./OlmDevice":63,"./OutgoingRoomKeyRequestManager":64,"./SecretStorage":66,"./aes":67,"./algorithms":69,"./deviceinfo":72,"./key_passphrase":74,"./olmlib":75,"./recoverykey":76,"./store/indexeddb-crypto-store":78,"./verification/IllegalMethod":83,"./verification/QRCode":84,"./verification/SAS":85,"./verification/request/InRoomChannel":86,"./verification/request/ToDeviceChannel":87,"./verification/request/VerificationRequest":88,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"another-json":28,"buffer":34,"events":36}],74:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.keyFromAuthData = keyFromAuthData; exports.keyFromPassphrase = keyFromPassphrase; exports.deriveKey = deriveKey; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _randomstring = require("../randomstring"); /* Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ var DEFAULT_ITERATIONS = 500000; var DEFAULT_BITSIZE = 256; function keyFromAuthData(_x, _x2) { return _keyFromAuthData.apply(this, arguments); } function _keyFromAuthData() { _keyFromAuthData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(authData, password) { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (global.Olm) { _context.next = 2; break; } throw new Error("Olm is not available"); case 2: if (!(!authData.private_key_salt || !authData.private_key_iterations)) { _context.next = 4; break; } throw new Error("Salt and/or iterations not found: " + "this backup cannot be restored with a passphrase"); case 4: _context.next = 6; return deriveKey(password, authData.private_key_salt, authData.private_key_iterations, authData.private_key_bits || DEFAULT_BITSIZE); case 6: return _context.abrupt("return", _context.sent); case 7: case "end": return _context.stop(); } } }, _callee); })); return _keyFromAuthData.apply(this, arguments); } function keyFromPassphrase(_x3) { return _keyFromPassphrase.apply(this, arguments); } function _keyFromPassphrase() { _keyFromPassphrase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(password) { var salt, key; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (global.Olm) { _context2.next = 2; break; } throw new Error("Olm is not available"); case 2: salt = (0, _randomstring.randomString)(32); _context2.next = 5; return deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE); case 5: key = _context2.sent; return _context2.abrupt("return", { key: key, salt: salt, iterations: DEFAULT_ITERATIONS }); case 7: case "end": return _context2.stop(); } } }, _callee2); })); return _keyFromPassphrase.apply(this, arguments); } function deriveKey(_x4, _x5, _x6) { return _deriveKey.apply(this, arguments); } function _deriveKey() { _deriveKey = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(password, salt, iterations) { var numBits, subtleCrypto, TextEncoder, key, keybits, _args3 = arguments; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: numBits = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : DEFAULT_BITSIZE; subtleCrypto = global.crypto.subtle; TextEncoder = global.TextEncoder; if (!(!subtleCrypto || !TextEncoder)) { _context3.next = 5; break; } throw new Error("Password-based backup is not avaiable on this platform"); case 5: _context3.next = 7; return subtleCrypto.importKey('raw', new TextEncoder().encode(password), { name: 'PBKDF2' }, false, ['deriveBits']); case 7: key = _context3.sent; _context3.next = 10; return subtleCrypto.deriveBits({ name: 'PBKDF2', salt: new TextEncoder().encode(salt), iterations: iterations, hash: 'SHA-512' }, key, numBits); case 10: keybits = _context3.sent; return _context3.abrupt("return", new Uint8Array(keybits)); case 12: case "end": return _context3.stop(); } } }, _callee3); })); return _deriveKey.apply(this, arguments); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../randomstring":110,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/regenerator":27}],75:[function(require,module,exports){ (function (global,Buffer){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.encryptMessageForDevice = encryptMessageForDevice; exports.getExistingOlmSessions = getExistingOlmSessions; exports.ensureOlmSessionsForDevices = ensureOlmSessionsForDevices; exports.verifySignature = verifySignature; exports.pkSign = pkSign; exports.pkVerify = pkVerify; exports.encodeBase64 = encodeBase64; exports.encodeUnpaddedBase64 = encodeUnpaddedBase64; exports.decodeBase64 = decodeBase64; exports.MEGOLM_BACKUP_ALGORITHM = exports.MEGOLM_ALGORITHM = exports.OLM_ALGORITHM = void 0; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _logger = require("../logger"); var utils = _interopRequireWildcard(require("../utils")); var _anotherJson = _interopRequireDefault(require("another-json")); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * matrix algorithm tag for olm */ var OLM_ALGORITHM = "m.olm.v1.curve25519-aes-sha2"; /** * matrix algorithm tag for megolm */ exports.OLM_ALGORITHM = OLM_ALGORITHM; var MEGOLM_ALGORITHM = "m.megolm.v1.aes-sha2"; /** * matrix algorithm tag for megolm backups */ exports.MEGOLM_ALGORITHM = MEGOLM_ALGORITHM; var MEGOLM_BACKUP_ALGORITHM = "m.megolm_backup.v1.curve25519-aes-sha2"; /** * Encrypt an event payload for an Olm device * * @param {Object} 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` */ exports.MEGOLM_BACKUP_ALGORITHM = MEGOLM_BACKUP_ALGORITHM; function encryptMessageForDevice(_x, _x2, _x3, _x4, _x5, _x6, _x7) { return _encryptMessageForDevice.apply(this, arguments); } /** * Get the existing olm sessions for the given devices, and the devices that * don't have olm sessions. * * @param {module:crypto/OlmDevice} olmDevice * * @param {module:base-apis~MatrixBaseApis} baseApis * * @param {object} devicesByUser * map from userid to list of devices to ensure sessions for * * @return {Promise} resolves to an array. The first element of the array is a * a map of user IDs to arrays of deviceInfo, representing the devices that * don't have established olm sessions. The second element of the array is * a map from userId to deviceId to {@link module:crypto~OlmSessionResult} */ function _encryptMessageForDevice() { _encryptMessageForDevice = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(resultsObject, ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice, payloadFields) { var deviceKey, sessionId, payload; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: deviceKey = recipientDevice.getIdentityKey(); _context.next = 3; return olmDevice.getSessionIdForDevice(deviceKey); case 3: sessionId = _context.sent; if (!(sessionId === null)) { _context.next = 6; break; } return _context.abrupt("return"); case 6: _logger.logger.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 olmDevice.encryptMessage(deviceKey, sessionId, JSON.stringify(payload)); case 11: resultsObject[deviceKey] = _context.sent; case 12: case "end": return _context.stop(); } } }, _callee); })); return _encryptMessageForDevice.apply(this, arguments); } function getExistingOlmSessions(_x8, _x9, _x10) { return _getExistingOlmSessions.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} devicesByUser * map from userid to list of devices to ensure sessions for * * @param {boolean} [force=false] If true, establish a new session even if one * already exists. * * @param {Number} [otkTimeout] The timeout in milliseconds when requesting * one-time keys for establishing new olm sessions. * * @param {Array} [failedServers] An array to fill with remote servers that * failed to respond to one-time-key requests. * * @return {Promise} resolves once the sessions are complete, to * an Object mapping from userId to deviceId to * {@link module:crypto~OlmSessionResult} */ function _getExistingOlmSessions() { _getExistingOlmSessions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(olmDevice, baseApis, devicesByUser) { var devicesWithoutSession, sessions, promises, _loop, _i, _Object$entries; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: devicesWithoutSession = {}; sessions = {}; promises = []; _loop = function _loop() { var _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2), userId = _Object$entries$_i[0], devices = _Object$entries$_i[1]; var _iterator = _createForOfIteratorHelper(devices), _step; try { var _loop2 = function _loop2() { var deviceInfo = _step.value; var deviceId = deviceInfo.deviceId; var key = deviceInfo.getIdentityKey(); promises.push((0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var sessionId; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return olmDevice.getSessionIdForDevice(key, true); case 2: sessionId = _context2.sent; if (sessionId === null) { devicesWithoutSession[userId] = devicesWithoutSession[userId] || []; devicesWithoutSession[userId].push(deviceInfo); } else { sessions[userId] = sessions[userId] || {}; sessions[userId][deviceId] = { device: deviceInfo, sessionId: sessionId }; } case 4: case "end": return _context2.stop(); } } }, _callee2); }))()); }; for (_iterator.s(); !(_step = _iterator.n()).done;) { _loop2(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }; for (_i = 0, _Object$entries = Object.entries(devicesByUser); _i < _Object$entries.length; _i++) { _loop(); } _context3.next = 7; return Promise.all(promises); case 7: return _context3.abrupt("return", [devicesWithoutSession, sessions]); case 8: case "end": return _context3.stop(); } } }, _callee3); })); return _getExistingOlmSessions.apply(this, arguments); } function ensureOlmSessionsForDevices(_x11, _x12, _x13, _x14, _x15, _x16) { return _ensureOlmSessionsForDevices.apply(this, arguments); } function _ensureOlmSessionsForDevices() { _ensureOlmSessionsForDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(olmDevice, baseApis, devicesByUser, force, otkTimeout, failedServers) { var devicesWithoutSession, result, resolveSession, _i2, _Object$entries2, _Object$entries2$_i, userId, devices, _iterator2, _step2, _loop3, _ret, oneTimeKeyAlgorithm, res, _i3, _Object$values, resolver, _failedServers, otk_res, promises, _loop4, _i4, _Object$entries3; return _regenerator["default"].wrap(function _callee4$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (typeof force === "number") { failedServers = otkTimeout; otkTimeout = force; force = false; } devicesWithoutSession = [// [userId, deviceId], ... ]; result = {}; resolveSession = {}; _i2 = 0, _Object$entries2 = Object.entries(devicesByUser); case 5: if (!(_i2 < _Object$entries2.length)) { _context5.next = 30; break; } _Object$entries2$_i = (0, _slicedToArray2["default"])(_Object$entries2[_i2], 2), userId = _Object$entries2$_i[0], devices = _Object$entries2$_i[1]; result[userId] = {}; _iterator2 = _createForOfIteratorHelper(devices); _context5.prev = 9; _loop3 = /*#__PURE__*/_regenerator["default"].mark(function _loop3() { var deviceInfo, deviceId, key, sessionId; return _regenerator["default"].wrap(function _loop3$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: deviceInfo = _step2.value; deviceId = deviceInfo.deviceId; key = deviceInfo.getIdentityKey(); if (!(key === olmDevice.deviceCurve25519Key)) { _context4.next = 7; break; } // We should never be trying to start a session with ourself. // Apart from talking to yourself being the first sign of madness, // olm sessions can't do this because they get confused when // they get a message and see that the 'other side' has started a // new chain when this side has an active sender chain. // If you see this message being logged in the wild, we should find // the thing that is trying to send Olm messages to itself and fix it. _logger.logger.info("Attempted to start session with ourself! Ignoring"); // We must fill in the section in the return value though, as callers // expect it to be there. result[userId][deviceId] = { device: deviceInfo, sessionId: null }; return _context4.abrupt("return", "continue"); case 7: 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 Promise(function (_resolve, _reject) { resolveSession[key] = { resolve: function resolve() { delete olmDevice._sessionsInProgress[key]; _resolve.apply(void 0, arguments); }, reject: function reject() { delete olmDevice._sessionsInProgress[key]; _reject.apply(void 0, arguments); } }; }); } _context4.next = 10; return olmDevice.getSessionIdForDevice(key, resolveSession[key]); case 10: sessionId = _context4.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) { if (force) { _logger.logger.info("Forcing new Olm session for " + userId + ":" + deviceId); } else { _logger.logger.info("Making new Olm session for " + userId + ":" + deviceId); } devicesWithoutSession.push([userId, deviceId]); } result[userId][deviceId] = { device: deviceInfo, sessionId: sessionId }; case 14: case "end": return _context4.stop(); } } }, _loop3); }); _iterator2.s(); case 12: if ((_step2 = _iterator2.n()).done) { _context5.next = 19; break; } return _context5.delegateYield(_loop3(), "t0", 14); case 14: _ret = _context5.t0; if (!(_ret === "continue")) { _context5.next = 17; break; } return _context5.abrupt("continue", 17); case 17: _context5.next = 12; break; case 19: _context5.next = 24; break; case 21: _context5.prev = 21; _context5.t1 = _context5["catch"](9); _iterator2.e(_context5.t1); case 24: _context5.prev = 24; _iterator2.f(); return _context5.finish(24); case 27: _i2++; _context5.next = 5; break; case 30: if (!(devicesWithoutSession.length === 0)) { _context5.next = 32; break; } return _context5.abrupt("return", result); case 32: oneTimeKeyAlgorithm = "signed_curve25519"; _context5.prev = 33; _context5.next = 36; return baseApis.claimOneTimeKeys(devicesWithoutSession, oneTimeKeyAlgorithm, otkTimeout); case 36: res = _context5.sent; _context5.next = 44; break; case 39: _context5.prev = 39; _context5.t2 = _context5["catch"](33); for (_i3 = 0, _Object$values = Object.values(resolveSession); _i3 < _Object$values.length; _i3++) { resolver = _Object$values[_i3]; resolver.resolve(); } _logger.logger.log("failed to claim one-time keys", _context5.t2, devicesWithoutSession); throw _context5.t2; case 44: if (failedServers && "failures" in res) { (_failedServers = failedServers).push.apply(_failedServers, (0, _toConsumableArray2["default"])(Object.keys(res.failures))); } otk_res = res.one_time_keys || {}; promises = []; _loop4 = function _loop4() { var _Object$entries3$_i = (0, _slicedToArray2["default"])(_Object$entries3[_i4], 2), userId = _Object$entries3$_i[0], devices = _Object$entries3$_i[1]; var userRes = otk_res[userId] || {}; var _loop5 = function _loop5(j) { var deviceInfo = devices[j]; var deviceId = deviceInfo.deviceId; var key = deviceInfo.getIdentityKey(); if (key === olmDevice.deviceCurve25519Key) { // We've already logged about this above. Skip here too // otherwise we'll log saying there are no one-time keys // which will be confusing. return "continue"; } 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; _logger.logger.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 _ret2 = _loop5(j); if (_ret2 === "continue") continue; } }; for (_i4 = 0, _Object$entries3 = Object.entries(devicesByUser); _i4 < _Object$entries3.length; _i4++) { _loop4(); } _context5.next = 51; return Promise.all(promises); case 51: return _context5.abrupt("return", result); case 52: case "end": return _context5.stop(); } } }, _callee4, null, [[9, 21, 24, 27], [33, 39]]); })); return _ensureOlmSessionsForDevices.apply(this, arguments); } function _verifyKeyAndStartSession(_x17, _x18, _x19, _x20) { return _verifyKeyAndStartSession2.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. * * @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. */ function _verifyKeyAndStartSession2() { _verifyKeyAndStartSession2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(olmDevice, oneTimeKey, userId, deviceInfo) { var deviceId, sid; return _regenerator["default"].wrap(function _callee5$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: deviceId = deviceInfo.deviceId; _context6.prev = 1; _context6.next = 4; return verifySignature(olmDevice, oneTimeKey, userId, deviceId, deviceInfo.getFingerprint()); case 4: _context6.next = 10; break; case 6: _context6.prev = 6; _context6.t0 = _context6["catch"](1); _logger.logger.error("Unable to verify signature on one-time key for device " + userId + ":" + deviceId + ":", _context6.t0); return _context6.abrupt("return", null); case 10: _context6.prev = 10; _context6.next = 13; return olmDevice.createOutboundSession(deviceInfo.getIdentityKey(), oneTimeKey.key); case 13: sid = _context6.sent; _context6.next = 20; break; case 16: _context6.prev = 16; _context6.t1 = _context6["catch"](10); // possibly a bad key _logger.logger.error("Error starting olm session with device " + userId + ":" + deviceId + ": " + _context6.t1); return _context6.abrupt("return", null); case 20: _logger.logger.log("Started new olm sessionid " + sid + " for device " + userId + ":" + deviceId); return _context6.abrupt("return", sid); case 22: case "end": return _context6.stop(); } } }, _callee5, null, [[1, 6], [10, 16]]); })); return _verifyKeyAndStartSession2.apply(this, arguments); } function verifySignature(_x21, _x22, _x23, _x24, _x25) { return _verifySignature.apply(this, arguments); } /** * Sign a JSON object using public key cryptography * @param {Object} obj Object to sign. The object will be modified to include * the new signature * @param {Olm.PkSigning|Uint8Array} key the signing object or the private key * seed * @param {string} userId The user ID who owns the signing key * @param {string} pubkey The public key (ignored if key is a seed) * @returns {string} the signature for the object */ function _verifySignature() { _verifySignature = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(olmDevice, obj, signingUserId, signingDeviceId, signingKey) { var signKeyId, signatures, userSigs, signature, mangledObj, json; return _regenerator["default"].wrap(function _callee6$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: signKeyId = "ed25519:" + signingDeviceId; signatures = obj.signatures || {}; userSigs = signatures[signingUserId] || {}; signature = userSigs[signKeyId]; if (signature) { _context7.next = 6; break; } throw Error("No signature"); case 6: // prepare the canonical json: remove unsigned and signatures, and stringify with // anotherjson mangledObj = Object.assign({}, obj); delete mangledObj.unsigned; delete mangledObj.signatures; json = _anotherJson["default"].stringify(mangledObj); olmDevice.verifySignature(signingKey, json, signature); case 11: case "end": return _context7.stop(); } } }, _callee6); })); return _verifySignature.apply(this, arguments); } function pkSign(obj, key, userId, pubkey) { var createdKey = false; if (key instanceof Uint8Array) { var keyObj = new global.Olm.PkSigning(); pubkey = keyObj.init_with_seed(key); key = keyObj; createdKey = true; } var sigs = obj.signatures || {}; delete obj.signatures; var unsigned = obj.unsigned; if (obj.unsigned) delete obj.unsigned; try { var mysigs = sigs[userId] || {}; sigs[userId] = mysigs; return mysigs['ed25519:' + pubkey] = key.sign(_anotherJson["default"].stringify(obj)); } finally { obj.signatures = sigs; if (unsigned) obj.unsigned = unsigned; if (createdKey) { key.free(); } } } /** * Verify a signed JSON object * @param {Object} obj Object to verify * @param {string} pubkey The public key to use to verify * @param {string} userId The user ID who signed the object */ function pkVerify(obj, pubkey, userId) { var keyId = "ed25519:" + pubkey; if (!(obj.signatures && obj.signatures[userId] && obj.signatures[userId][keyId])) { throw new Error("No signature"); } var signature = obj.signatures[userId][keyId]; var util = new global.Olm.Utility(); var sigs = obj.signatures; delete obj.signatures; var unsigned = obj.unsigned; if (obj.unsigned) delete obj.unsigned; try { util.ed25519_verify(pubkey, _anotherJson["default"].stringify(obj), signature); } finally { obj.signatures = sigs; if (unsigned) obj.unsigned = unsigned; util.free(); } } /** * Encode a typed array of uint8 as base64. * @param {Uint8Array} uint8Array The data to encode. * @return {string} The base64. */ function encodeBase64(uint8Array) { return Buffer.from(uint8Array).toString("base64"); } /** * Encode a typed array of uint8 as unpadded base64. * @param {Uint8Array} uint8Array The data to encode. * @return {string} The unpadded base64. */ function encodeUnpaddedBase64(uint8Array) { return encodeBase64(uint8Array).replace(/=+$/g, ''); } /** * Decode a base64 string to a typed array of uint8. * @param {string} base64 The base64 to decode. * @return {Uint8Array} The decoded data. */ function decodeBase64(base64) { return Buffer.from(base64, "base64"); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"../logger":95,"../utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/toConsumableArray":23,"@babel/runtime/regenerator":27,"another-json":28,"buffer":34}],76:[function(require,module,exports){ (function (global,Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.encodeRecoveryKey = encodeRecoveryKey; exports.decodeRecoveryKey = decodeRecoveryKey; var _bs = _interopRequireDefault(require("bs58")); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } // picked arbitrarily but to try & avoid clashing with any bitcoin ones // (which are also base58 encoded, but bitcoin's involve a lot more hashing) var OLM_RECOVERY_KEY_PREFIX = [0x8B, 0x01]; function encodeRecoveryKey(key) { var buf = new Buffer(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1); buf.set(OLM_RECOVERY_KEY_PREFIX, 0); buf.set(key, OLM_RECOVERY_KEY_PREFIX.length); var parity = 0; for (var i = 0; i < buf.length - 1; ++i) { parity ^= buf[i]; } buf[buf.length - 1] = parity; var base58key = _bs["default"].encode(buf); return base58key.match(/.{1,4}/g).join(" "); } function decodeRecoveryKey(recoverykey) { var result = _bs["default"].decode(recoverykey.replace(/ /g, '')); var parity = 0; var _iterator = _createForOfIteratorHelper(result), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var b = _step.value; parity ^= b; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (parity !== 0) { throw new Error("Incorrect parity"); } for (var i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) { if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) { throw new Error("Incorrect prefix"); } } if (result.length !== OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH + 1) { throw new Error("Incorrect length"); } return Uint8Array.from(result.slice(OLM_RECOVERY_KEY_PREFIX.length, OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH)); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"@babel/runtime/helpers/interopRequireDefault":12,"bs58":33,"buffer":34}],77:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.upgradeDatabase = upgradeDatabase; exports.Backend = exports.VERSION = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _logger = require("../../logger"); var utils = _interopRequireWildcard(require("../../utils")); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var VERSION = 9; /** * Implementation of a CryptoStore which is backed by an existing * IndexedDB connection. Generally you want IndexedDBCryptoStore * which connects to the database and defers to one of these. * * @implements {module:crypto/store/base~CryptoStore} */ exports.VERSION = VERSION; var Backend = /*#__PURE__*/function () { /** * @param {IDBDatabase} db */ function Backend(db) { var _this = this; (0, _classCallCheck2["default"])(this, Backend); this._db = db; // make sure we close the db on `onversionchange` - otherwise // attempts to delete the database will block (and subsequent // attempts to re-create it will also block). db.onversionchange = function (ev) { _logger.logger.log("versionchange for indexeddb ".concat(_this._dbName, ": closing")); db.close(); }; } /** * Look for an existing outgoing room key request, and if none is found, * add a new one * * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request * * @returns {Promise} resolves to * {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the * same instance as passed in, or the existing one. */ (0, _createClass2["default"])(Backend, [{ key: "getOrAddOutgoingRoomKeyRequest", value: function getOrAddOutgoingRoomKeyRequest(request) { var _this2 = this; var requestBody = request.requestBody; return new Promise(function (resolve, reject) { var txn = _this2._db.transaction("outgoingRoomKeyRequests", "readwrite"); txn.onerror = reject; // first see if we already have an entry for this request. _this2._getOutgoingRoomKeyRequest(txn, requestBody, function (existing) { if (existing) { // this entry matches the request - return it. _logger.logger.log("already have key request outstanding for " + "".concat(requestBody.room_id, " / ").concat(requestBody.session_id, ": ") + "not sending another"); resolve(existing); return; } // we got to the end of the list without finding a match // - add the new request. _logger.logger.log("enqueueing key request for ".concat(requestBody.room_id, " / ") + requestBody.session_id); txn.oncomplete = function () { resolve(request); }; var store = txn.objectStore("outgoingRoomKeyRequests"); store.add(request); }); }); } /** * Look for an existing room key request * * @param {module:crypto~RoomKeyRequestBody} requestBody * existing request to look for * * @return {Promise} resolves to the matching * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * not found */ }, { key: "getOutgoingRoomKeyRequest", value: function getOutgoingRoomKeyRequest(requestBody) { var _this3 = this; return new Promise(function (resolve, reject) { var txn = _this3._db.transaction("outgoingRoomKeyRequests", "readonly"); txn.onerror = reject; _this3._getOutgoingRoomKeyRequest(txn, requestBody, function (existing) { resolve(existing); }); }); } /** * look for an existing room key request in the db * * @private * @param {IDBTransaction} txn database transaction * @param {module:crypto~RoomKeyRequestBody} requestBody * existing request to look for * @param {Function} callback function to call with the results of the * search. Either passed a matching * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * not found. */ }, { key: "_getOutgoingRoomKeyRequest", value: function _getOutgoingRoomKeyRequest(txn, requestBody, callback) { var store = txn.objectStore("outgoingRoomKeyRequests"); var idx = store.index("session"); var cursorReq = idx.openCursor([requestBody.room_id, requestBody.session_id]); cursorReq.onsuccess = function (ev) { var cursor = ev.target.result; if (!cursor) { // no match found callback(null); return; } var existing = cursor.value; if (utils.deepCompare(existing.requestBody, requestBody)) { // got a match callback(existing); return; } // look at the next entry in the index cursor["continue"](); }; } /** * Look for room key requests by state * * @param {Array} wantedStates list of acceptable states * * @return {Promise} resolves to the a * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * there are no pending requests in those states. If there are multiple * requests in those states, an arbitrary one is chosen. */ }, { key: "getOutgoingRoomKeyRequestByState", value: function getOutgoingRoomKeyRequestByState(wantedStates) { if (wantedStates.length === 0) { return Promise.resolve(null); } // this is a bit tortuous because we need to make sure we do the lookup // in a single transaction, to avoid having a race with the insertion // code. // index into the wantedStates array var stateIndex = 0; var result; function onsuccess(ev) { var cursor = ev.target.result; if (cursor) { // got a match result = cursor.value; return; } // try the next state in the list stateIndex++; if (stateIndex >= wantedStates.length) { // no matches return; } var wantedState = wantedStates[stateIndex]; var cursorReq = ev.target.source.openCursor(wantedState); cursorReq.onsuccess = onsuccess; } var txn = this._db.transaction("outgoingRoomKeyRequests", "readonly"); var store = txn.objectStore("outgoingRoomKeyRequests"); var wantedState = wantedStates[stateIndex]; var cursorReq = store.index("state").openCursor(wantedState); cursorReq.onsuccess = onsuccess; return promiseifyTxn(txn).then(function () { return result; }); } /** * * @param {Number} wantedState * @return {Promise>} All elements in a given state */ }, { key: "getAllOutgoingRoomKeyRequestsByState", value: function getAllOutgoingRoomKeyRequestsByState(wantedState) { var _this4 = this; return new Promise(function (resolve, reject) { var txn = _this4._db.transaction("outgoingRoomKeyRequests", "readonly"); var store = txn.objectStore("outgoingRoomKeyRequests"); var index = store.index("state"); var request = index.getAll(wantedState); request.onsuccess = function (ev) { return resolve(ev.target.result); }; request.onerror = function (ev) { return reject(ev.target.error); }; }); } }, { key: "getOutgoingRoomKeyRequestsByTarget", value: function getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) { var stateIndex = 0; var results = []; function onsuccess(ev) { var cursor = ev.target.result; if (cursor) { var keyReq = cursor.value; if (keyReq.recipients.includes({ userId: userId, deviceId: deviceId })) { results.push(keyReq); } cursor["continue"](); } else { // try the next state in the list stateIndex++; if (stateIndex >= wantedStates.length) { // no matches return; } var _wantedState = wantedStates[stateIndex]; var _cursorReq = ev.target.source.openCursor(_wantedState); _cursorReq.onsuccess = onsuccess; } } var txn = this._db.transaction("outgoingRoomKeyRequests", "readonly"); var store = txn.objectStore("outgoingRoomKeyRequests"); var wantedState = wantedStates[stateIndex]; var cursorReq = store.index("state").openCursor(wantedState); cursorReq.onsuccess = onsuccess; return promiseifyTxn(txn).then(function () { return results; }); } /** * Look for an existing room key request by id and state, and update it if * found * * @param {string} requestId ID of request to update * @param {number} expectedState state we expect to find the request in * @param {Object} updates name/value map of updates to apply * * @returns {Promise} resolves to * {@link module:crypto/store/base~OutgoingRoomKeyRequest} * updated request, or null if no matching row was found */ }, { key: "updateOutgoingRoomKeyRequest", value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) { var result = null; function onsuccess(ev) { var cursor = ev.target.result; if (!cursor) { return; } var data = cursor.value; if (data.state != expectedState) { _logger.logger.warn("Cannot update room key request from ".concat(expectedState, " ") + "as it was already updated to ".concat(data.state)); return; } Object.assign(data, updates); cursor.update(data); result = data; } var txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite"); var cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId); cursorReq.onsuccess = onsuccess; return promiseifyTxn(txn).then(function () { return result; }); } /** * Look for an existing room key request by id and state, and delete it if * found * * @param {string} requestId ID of request to update * @param {number} expectedState state we expect to find the request in * * @returns {Promise} resolves once the operation is completed */ }, { key: "deleteOutgoingRoomKeyRequest", value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) { var txn = this._db.transaction("outgoingRoomKeyRequests", "readwrite"); var cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId); cursorReq.onsuccess = function (ev) { var cursor = ev.target.result; if (!cursor) { return; } var data = cursor.value; if (data.state != expectedState) { _logger.logger.warn("Cannot delete room key request in state ".concat(data.state, " ") + "(expected ".concat(expectedState, ")")); return; } cursor["delete"](); }; return promiseifyTxn(txn); } // Olm Account }, { key: "getAccount", value: function getAccount(txn, func) { var objectStore = txn.objectStore("account"); var getReq = objectStore.get("-"); getReq.onsuccess = function () { try { func(getReq.result || null); } catch (e) { abortWithException(txn, e); } }; } }, { key: "storeAccount", value: function storeAccount(txn, newData) { var objectStore = txn.objectStore("account"); objectStore.put(newData, "-"); } }, { key: "getCrossSigningKeys", value: function getCrossSigningKeys(txn, func) { var objectStore = txn.objectStore("account"); var getReq = objectStore.get("crossSigningKeys"); getReq.onsuccess = function () { try { func(getReq.result || null); } catch (e) { abortWithException(txn, e); } }; } }, { key: "getSecretStorePrivateKey", value: function getSecretStorePrivateKey(txn, func, type) { var objectStore = txn.objectStore("account"); var getReq = objectStore.get("ssss_cache:".concat(type)); getReq.onsuccess = function () { try { func(getReq.result || null); } catch (e) { abortWithException(txn, e); } }; } }, { key: "storeCrossSigningKeys", value: function storeCrossSigningKeys(txn, keys) { var objectStore = txn.objectStore("account"); objectStore.put(keys, "crossSigningKeys"); } }, { key: "storeSecretStorePrivateKey", value: function storeSecretStorePrivateKey(txn, type, key) { var objectStore = txn.objectStore("account"); objectStore.put(key, "ssss_cache:".concat(type)); } // Olm Sessions }, { key: "countEndToEndSessions", value: function countEndToEndSessions(txn, func) { var objectStore = txn.objectStore("sessions"); var countReq = objectStore.count(); countReq.onsuccess = function () { try { func(countReq.result); } catch (e) { abortWithException(txn, e); } }; } }, { key: "getEndToEndSessions", value: function getEndToEndSessions(deviceKey, txn, func) { var objectStore = txn.objectStore("sessions"); var idx = objectStore.index("deviceKey"); var getReq = idx.openCursor(deviceKey); var results = {}; getReq.onsuccess = function () { var cursor = getReq.result; if (cursor) { results[cursor.value.sessionId] = { session: cursor.value.session, lastReceivedMessageTs: cursor.value.lastReceivedMessageTs }; cursor["continue"](); } else { try { func(results); } catch (e) { abortWithException(txn, e); } } }; } }, { key: "getEndToEndSession", value: function getEndToEndSession(deviceKey, sessionId, txn, func) { var objectStore = txn.objectStore("sessions"); var getReq = objectStore.get([deviceKey, sessionId]); getReq.onsuccess = function () { try { if (getReq.result) { func({ session: getReq.result.session, lastReceivedMessageTs: getReq.result.lastReceivedMessageTs }); } else { func(null); } } catch (e) { abortWithException(txn, e); } }; } }, { key: "getAllEndToEndSessions", value: function getAllEndToEndSessions(txn, func) { var objectStore = txn.objectStore("sessions"); var getReq = objectStore.openCursor(); getReq.onsuccess = function () { try { var cursor = getReq.result; if (cursor) { func(cursor.value); cursor["continue"](); } else { func(null); } } catch (e) { abortWithException(txn, e); } }; } }, { key: "storeEndToEndSession", value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { var objectStore = txn.objectStore("sessions"); objectStore.put({ deviceKey: deviceKey, sessionId: sessionId, session: sessionInfo.session, lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs }); } }, { key: "storeEndToEndSessionProblem", value: function () { var _storeEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(deviceKey, type, fixed) { var txn, objectStore; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: txn = this._db.transaction("session_problems", "readwrite"); objectStore = txn.objectStore("session_problems"); objectStore.put({ deviceKey: deviceKey, type: type, fixed: fixed, time: Date.now() }); return _context.abrupt("return", promiseifyTxn(txn)); case 4: case "end": return _context.stop(); } } }, _callee, this); })); function storeEndToEndSessionProblem(_x, _x2, _x3) { return _storeEndToEndSessionProblem.apply(this, arguments); } return storeEndToEndSessionProblem; }() }, { key: "getEndToEndSessionProblem", value: function () { var _getEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(deviceKey, timestamp) { var result, txn, objectStore, index, req; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: txn = this._db.transaction("session_problems", "readwrite"); objectStore = txn.objectStore("session_problems"); index = objectStore.index("deviceKey"); req = index.getAll(deviceKey); req.onsuccess = function (event) { var problems = req.result; if (!problems.length) { result = null; return; } problems.sort(function (a, b) { return a.time - b.time; }); var lastProblem = problems[problems.length - 1]; var _iterator = _createForOfIteratorHelper(problems), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var problem = _step.value; if (problem.time > timestamp) { result = Object.assign({}, problem, { fixed: lastProblem.fixed }); return; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (lastProblem.fixed) { result = null; } else { result = lastProblem; } }; _context2.next = 7; return promiseifyTxn(txn); case 7: return _context2.abrupt("return", result); case 8: case "end": return _context2.stop(); } } }, _callee2, this); })); function getEndToEndSessionProblem(_x4, _x5) { return _getEndToEndSessionProblem.apply(this, arguments); } return getEndToEndSessionProblem; }() // FIXME: we should probably prune this when devices get deleted }, { key: "filterOutNotifiedErrorDevices", value: function () { var _filterOutNotifiedErrorDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(devices) { var txn, objectStore, ret; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: txn = this._db.transaction("notified_error_devices", "readwrite"); objectStore = txn.objectStore("notified_error_devices"); ret = []; _context3.next = 5; return Promise.all(devices.map(function (device) { return new Promise(function (resolve) { var userId = device.userId, deviceInfo = device.deviceInfo; var getReq = objectStore.get([userId, deviceInfo.deviceId]); getReq.onsuccess = function () { if (!getReq.result) { objectStore.put({ userId: userId, deviceId: deviceInfo.deviceId }); ret.push(device); } resolve(); }; }); })); case 5: return _context3.abrupt("return", ret); case 6: case "end": return _context3.stop(); } } }, _callee3, this); })); function filterOutNotifiedErrorDevices(_x6) { return _filterOutNotifiedErrorDevices.apply(this, arguments); } return filterOutNotifiedErrorDevices; }() // Inbound group sessions }, { key: "getEndToEndInboundGroupSession", value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { var session = false; var withheld = false; var objectStore = txn.objectStore("inbound_group_sessions"); var getReq = objectStore.get([senderCurve25519Key, sessionId]); getReq.onsuccess = function () { try { if (getReq.result) { session = getReq.result.session; } else { session = null; } if (withheld !== false) { func(session, withheld); } } catch (e) { abortWithException(txn, e); } }; var withheldObjectStore = txn.objectStore("inbound_group_sessions_withheld"); var withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]); withheldGetReq.onsuccess = function () { try { if (withheldGetReq.result) { withheld = withheldGetReq.result.session; } else { withheld = null; } if (session !== false) { func(session, withheld); } } catch (e) { abortWithException(txn, e); } }; } }, { key: "getAllEndToEndInboundGroupSessions", value: function getAllEndToEndInboundGroupSessions(txn, func) { var objectStore = txn.objectStore("inbound_group_sessions"); var getReq = objectStore.openCursor(); getReq.onsuccess = function () { var cursor = getReq.result; if (cursor) { try { func({ senderKey: cursor.value.senderCurve25519Key, sessionId: cursor.value.sessionId, sessionData: cursor.value.session }); } catch (e) { abortWithException(txn, e); } cursor["continue"](); } else { try { func(null); } catch (e) { abortWithException(txn, e); } } }; } }, { key: "addEndToEndInboundGroupSession", value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { var objectStore = txn.objectStore("inbound_group_sessions"); var addReq = objectStore.add({ senderCurve25519Key: senderCurve25519Key, sessionId: sessionId, session: sessionData }); addReq.onerror = function (ev) { if (addReq.error.name === 'ConstraintError') { // This stops the error from triggering the txn's onerror ev.stopPropagation(); // ...and this stops it from aborting the transaction ev.preventDefault(); _logger.logger.log("Ignoring duplicate inbound group session: " + senderCurve25519Key + " / " + sessionId); } else { abortWithException(txn, new Error("Failed to add inbound group session: " + addReq.error)); } }; } }, { key: "storeEndToEndInboundGroupSession", value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { var objectStore = txn.objectStore("inbound_group_sessions"); objectStore.put({ senderCurve25519Key: senderCurve25519Key, sessionId: sessionId, session: sessionData }); } }, { key: "storeEndToEndInboundGroupSessionWithheld", value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { var objectStore = txn.objectStore("inbound_group_sessions_withheld"); objectStore.put({ senderCurve25519Key: senderCurve25519Key, sessionId: sessionId, session: sessionData }); } }, { key: "getEndToEndDeviceData", value: function getEndToEndDeviceData(txn, func) { var objectStore = txn.objectStore("device_data"); var getReq = objectStore.get("-"); getReq.onsuccess = function () { try { func(getReq.result || null); } catch (e) { abortWithException(txn, e); } }; } }, { key: "storeEndToEndDeviceData", value: function storeEndToEndDeviceData(deviceData, txn) { var objectStore = txn.objectStore("device_data"); objectStore.put(deviceData, "-"); } }, { key: "storeEndToEndRoom", value: function storeEndToEndRoom(roomId, roomInfo, txn) { var objectStore = txn.objectStore("rooms"); objectStore.put(roomInfo, roomId); } }, { key: "getEndToEndRooms", value: function getEndToEndRooms(txn, func) { var rooms = {}; var objectStore = txn.objectStore("rooms"); var getReq = objectStore.openCursor(); getReq.onsuccess = function () { var cursor = getReq.result; if (cursor) { rooms[cursor.key] = cursor.value; cursor["continue"](); } else { try { func(rooms); } catch (e) { abortWithException(txn, e); } } }; } // session backups }, { key: "getSessionsNeedingBackup", value: function getSessionsNeedingBackup(limit) { var _this5 = this; return new Promise(function (resolve, reject) { var sessions = []; var txn = _this5._db.transaction(["sessions_needing_backup", "inbound_group_sessions"], "readonly"); txn.onerror = reject; txn.oncomplete = function () { resolve(sessions); }; var objectStore = txn.objectStore("sessions_needing_backup"); var sessionStore = txn.objectStore("inbound_group_sessions"); var getReq = objectStore.openCursor(); getReq.onsuccess = function () { var cursor = getReq.result; if (cursor) { var sessionGetReq = sessionStore.get(cursor.key); sessionGetReq.onsuccess = function () { sessions.push({ senderKey: sessionGetReq.result.senderCurve25519Key, sessionId: sessionGetReq.result.sessionId, sessionData: sessionGetReq.result.session }); }; if (!limit || sessions.length < limit) { cursor["continue"](); } } }; }); } }, { key: "countSessionsNeedingBackup", value: function countSessionsNeedingBackup(txn) { if (!txn) { txn = this._db.transaction("sessions_needing_backup", "readonly"); } var objectStore = txn.objectStore("sessions_needing_backup"); return new Promise(function (resolve, reject) { var req = objectStore.count(); req.onerror = reject; req.onsuccess = function () { return resolve(req.result); }; }); } }, { key: "unmarkSessionsNeedingBackup", value: function unmarkSessionsNeedingBackup(sessions, txn) { if (!txn) { txn = this._db.transaction("sessions_needing_backup", "readwrite"); } var objectStore = txn.objectStore("sessions_needing_backup"); return Promise.all(sessions.map(function (session) { return new Promise(function (resolve, reject) { var req = objectStore["delete"]([session.senderKey, session.sessionId]); req.onsuccess = resolve; req.onerror = reject; }); })); } }, { key: "markSessionsNeedingBackup", value: function markSessionsNeedingBackup(sessions, txn) { if (!txn) { txn = this._db.transaction("sessions_needing_backup", "readwrite"); } var objectStore = txn.objectStore("sessions_needing_backup"); return Promise.all(sessions.map(function (session) { return new Promise(function (resolve, reject) { var req = objectStore.put({ senderCurve25519Key: session.senderKey, sessionId: session.sessionId }); req.onsuccess = resolve; req.onerror = reject; }); })); } }, { key: "doTxn", value: function doTxn(mode, stores, func) { var txn = this._db.transaction(stores, mode); var promise = promiseifyTxn(txn); var result = func(txn); return promise.then(function () { return result; }); } }]); return Backend; }(); exports.Backend = Backend; function upgradeDatabase(db, oldVersion) { _logger.logger.log("Upgrading IndexedDBCryptoStore from version ".concat(oldVersion) + " to ".concat(VERSION)); if (oldVersion < 1) { // The database did not previously exist. createDatabase(db); } if (oldVersion < 2) { db.createObjectStore("account"); } if (oldVersion < 3) { var sessionsStore = db.createObjectStore("sessions", { keyPath: ["deviceKey", "sessionId"] }); sessionsStore.createIndex("deviceKey", "deviceKey"); } if (oldVersion < 4) { db.createObjectStore("inbound_group_sessions", { keyPath: ["senderCurve25519Key", "sessionId"] }); } if (oldVersion < 5) { db.createObjectStore("device_data"); } if (oldVersion < 6) { db.createObjectStore("rooms"); } if (oldVersion < 7) { db.createObjectStore("sessions_needing_backup", { keyPath: ["senderCurve25519Key", "sessionId"] }); } if (oldVersion < 8) { db.createObjectStore("inbound_group_sessions_withheld", { keyPath: ["senderCurve25519Key", "sessionId"] }); } if (oldVersion < 9) { var problemsStore = db.createObjectStore("session_problems", { keyPath: ["deviceKey", "time"] }); problemsStore.createIndex("deviceKey", "deviceKey"); db.createObjectStore("notified_error_devices", { keyPath: ["userId", "deviceId"] }); } // Expand as needed. } function createDatabase(db) { var outgoingRoomKeyRequestsStore = db.createObjectStore("outgoingRoomKeyRequests", { keyPath: "requestId" }); // we assume that the RoomKeyRequestBody will have room_id and session_id // properties, to make the index efficient. outgoingRoomKeyRequestsStore.createIndex("session", ["requestBody.room_id", "requestBody.session_id"]); outgoingRoomKeyRequestsStore.createIndex("state", "state"); } /* * Aborts a transaction with a given exception * The transaction promise will be rejected with this exception. */ function abortWithException(txn, e) { // We cheekily stick our exception onto the transaction object here // We could alternatively make the thing we pass back to the app // an object containing the transaction and exception. txn._mx_abortexception = e; try { txn.abort(); } catch (e) {// sometimes we won't be able to abort the transaction // (ie. if it's aborted or completed) } } function promiseifyTxn(txn) { return new Promise(function (resolve, reject) { txn.oncomplete = function () { if (txn._mx_abortexception !== undefined) { reject(txn._mx_abortexception); } resolve(); }; txn.onerror = function (event) { if (txn._mx_abortexception !== undefined) { reject(txn._mx_abortexception); } else { _logger.logger.log("Error performing indexeddb txn", event); reject(event.target.error); } }; txn.onabort = function (event) { if (txn._mx_abortexception !== undefined) { reject(txn._mx_abortexception); } else { _logger.logger.log("Error performing indexeddb txn", event); reject(event.target.error); } }; }); } },{"../../logger":95,"../../utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],78:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.IndexedDBCryptoStore = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _logger = require("../../logger"); var _localStorageCryptoStore = require("./localStorage-crypto-store"); var _memoryCryptoStore = require("./memory-crypto-store"); var IndexedDBCryptoStoreBackend = _interopRequireWildcard(require("./indexeddb-crypto-store-backend")); var _errors = require("../../errors"); var IndexedDBHelpers = _interopRequireWildcard(require("../../indexeddb-helpers")); /* Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Copyright 2020 The Matrix.org Foundation C.I.C. 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. */ /** * Internal module. indexeddb storage for e2e. * * @module */ /** * An implementation of CryptoStore, which is normally backed by an indexeddb, * but with fallback to MemoryCryptoStore. * * @implements {module:crypto/store/base~CryptoStore} */ var IndexedDBCryptoStore = /*#__PURE__*/function () { /** * Create a new IndexedDBCryptoStore * * @param {IDBFactory} indexedDB global indexedDB instance * @param {string} dbName name of db to connect to */ function IndexedDBCryptoStore(indexedDB, dbName) { (0, _classCallCheck2["default"])(this, IndexedDBCryptoStore); this._indexedDB = indexedDB; this._dbName = dbName; this._backendPromise = null; this._backend = null; } (0, _createClass2["default"])(IndexedDBCryptoStore, [{ key: "startup", /** * Ensure the database exists and is up-to-date, or fall back to * a local storage or in-memory store. * * This must be called before the store can be used. * * @return {Promise} resolves to either an IndexedDBCryptoStoreBackend.Backend, * or a MemoryCryptoStore */ value: function startup() { var _this = this; if (this._backendPromise) { return this._backendPromise; } this._backendPromise = new Promise(function (resolve, reject) { if (!_this._indexedDB) { reject(new Error('no indexeddb support available')); return; } _logger.logger.log("connecting to indexeddb ".concat(_this._dbName)); var req = _this._indexedDB.open(_this._dbName, IndexedDBCryptoStoreBackend.VERSION); req.onupgradeneeded = function (ev) { var db = ev.target.result; var oldVersion = ev.oldVersion; IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion); }; req.onblocked = function () { _logger.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere"); }; req.onerror = function (ev) { _logger.logger.log("Error connecting to indexeddb", ev); reject(ev.target.error); }; req.onsuccess = function (r) { var db = r.target.result; _logger.logger.log("connected to indexeddb ".concat(_this._dbName)); resolve(new IndexedDBCryptoStoreBackend.Backend(db)); }; }).then(function (backend) { // Edge has IndexedDB but doesn't support compund keys which we use fairly extensively. // Try a dummy query which will fail if the browser doesn't support compund keys, so // we can fall back to a different backend. return backend.doTxn('readonly', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], function (txn) { backend.getEndToEndInboundGroupSession('', '', txn, function () {}); }).then(function () { return backend; }); })["catch"](function (e) { if (e.name === 'VersionError') { _logger.logger.warn("Crypto DB is too new for us to use!", e); // don't fall back to a different store: the user has crypto data // in this db so we should use it or nothing at all. throw new _errors.InvalidCryptoStoreError(_errors.InvalidCryptoStoreError.TOO_NEW); } _logger.logger.warn("unable to connect to indexeddb ".concat(_this._dbName) + ": falling back to localStorage store: ".concat(e)); try { return new _localStorageCryptoStore.LocalStorageCryptoStore(global.localStorage); } catch (e) { _logger.logger.warn("unable to open localStorage: falling back to in-memory store: ".concat(e)); return new _memoryCryptoStore.MemoryCryptoStore(); } }).then(function (backend) { _this._backend = backend; }); return this._backendPromise; } /** * Delete all data from this store. * * @returns {Promise} resolves when the store has been cleared. */ }, { key: "deleteAllData", value: function deleteAllData() { var _this2 = this; return new Promise(function (resolve, reject) { if (!_this2._indexedDB) { reject(new Error('no indexeddb support available')); return; } _logger.logger.log("Removing indexeddb instance: ".concat(_this2._dbName)); var req = _this2._indexedDB.deleteDatabase(_this2._dbName); req.onblocked = function () { _logger.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere"); }; req.onerror = function (ev) { _logger.logger.log("Error deleting data from indexeddb", ev); reject(ev.target.error); }; req.onsuccess = function () { _logger.logger.log("Removed indexeddb instance: ".concat(_this2._dbName)); resolve(); }; })["catch"](function (e) { // in firefox, with indexedDB disabled, this fails with a // DOMError. We treat this as non-fatal, so that people can // still use the app. _logger.logger.warn("unable to delete IndexedDBCryptoStore: ".concat(e)); }); } /** * Look for an existing outgoing room key request, and if none is found, * add a new one * * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request * * @returns {Promise} resolves to * {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the * same instance as passed in, or the existing one. */ }, { key: "getOrAddOutgoingRoomKeyRequest", value: function getOrAddOutgoingRoomKeyRequest(request) { return this._backend.getOrAddOutgoingRoomKeyRequest(request); } /** * Look for an existing room key request * * @param {module:crypto~RoomKeyRequestBody} requestBody * existing request to look for * * @return {Promise} resolves to the matching * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * not found */ }, { key: "getOutgoingRoomKeyRequest", value: function getOutgoingRoomKeyRequest(requestBody) { return this._backend.getOutgoingRoomKeyRequest(requestBody); } /** * Look for room key requests by state * * @param {Array} wantedStates list of acceptable states * * @return {Promise} resolves to the a * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * there are no pending requests in those states. If there are multiple * requests in those states, an arbitrary one is chosen. */ }, { key: "getOutgoingRoomKeyRequestByState", value: function getOutgoingRoomKeyRequestByState(wantedStates) { return this._backend.getOutgoingRoomKeyRequestByState(wantedStates); } /** * Look for room key requests by state – * unlike above, return a list of all entries in one state. * * @param {Number} wantedState * @return {Promise>} Returns an array of requests in the given state */ }, { key: "getAllOutgoingRoomKeyRequestsByState", value: function getAllOutgoingRoomKeyRequestsByState(wantedState) { return this._backend.getAllOutgoingRoomKeyRequestsByState(wantedState); } /** * Look for room key requests by target device and state * * @param {string} userId Target user ID * @param {string} deviceId Target device ID * @param {Array} wantedStates list of acceptable states * * @return {Promise} resolves to a list of all the * {@link module:crypto/store/base~OutgoingRoomKeyRequest} */ }, { key: "getOutgoingRoomKeyRequestsByTarget", value: function getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) { return this._backend.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates); } /** * Look for an existing room key request by id and state, and update it if * found * * @param {string} requestId ID of request to update * @param {number} expectedState state we expect to find the request in * @param {Object} updates name/value map of updates to apply * * @returns {Promise} resolves to * {@link module:crypto/store/base~OutgoingRoomKeyRequest} * updated request, or null if no matching row was found */ }, { key: "updateOutgoingRoomKeyRequest", value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) { return this._backend.updateOutgoingRoomKeyRequest(requestId, expectedState, updates); } /** * Look for an existing room key request by id and state, and delete it if * found * * @param {string} requestId ID of request to update * @param {number} expectedState state we expect to find the request in * * @returns {Promise} resolves once the operation is completed */ }, { key: "deleteOutgoingRoomKeyRequest", value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) { return this._backend.deleteOutgoingRoomKeyRequest(requestId, expectedState); } // Olm Account /* * Get the account pickle from the store. * This requires an active transaction. See doTxn(). * * @param {*} txn An active transaction. See doTxn(). * @param {function(string)} func Called with the account pickle */ }, { key: "getAccount", value: function getAccount(txn, func) { this._backend.getAccount(txn, func); } /** * Write the account pickle to the store. * This requires an active transaction. See doTxn(). * * @param {*} txn An active transaction. See doTxn(). * @param {string} newData The new account pickle to store. */ }, { key: "storeAccount", value: function storeAccount(txn, newData) { this._backend.storeAccount(txn, newData); } /** * Get the public part of the cross-signing keys (eg. self-signing key, * user signing key). * * @param {*} txn An active transaction. See doTxn(). * @param {function(string)} func Called with the account keys object: * { key_type: base64 encoded seed } where key type = user_signing_key_seed or self_signing_key_seed */ }, { key: "getCrossSigningKeys", value: function getCrossSigningKeys(txn, func) { this._backend.getCrossSigningKeys(txn, func); } /** * @param {*} txn An active transaction. See doTxn(). * @param {function(string)} func Called with the private key * @param {string} type A key type */ }, { key: "getSecretStorePrivateKey", value: function getSecretStorePrivateKey(txn, func, type) { this._backend.getSecretStorePrivateKey(txn, func, type); } /** * Write the cross-signing keys back to the store * * @param {*} txn An active transaction. See doTxn(). * @param {string} keys keys object as getCrossSigningKeys() */ }, { key: "storeCrossSigningKeys", value: function storeCrossSigningKeys(txn, keys) { this._backend.storeCrossSigningKeys(txn, keys); } /** * Write the cross-signing private keys back to the store * * @param {*} txn An active transaction. See doTxn(). * @param {string} type The type of cross-signing private key to store * @param {string} key keys object as getCrossSigningKeys() */ }, { key: "storeSecretStorePrivateKey", value: function storeSecretStorePrivateKey(txn, type, key) { this._backend.storeSecretStorePrivateKey(txn, type, key); } // Olm sessions /** * Returns the number of end-to-end sessions in the store * @param {*} txn An active transaction. See doTxn(). * @param {function(int)} func Called with the count of sessions */ }, { key: "countEndToEndSessions", value: function countEndToEndSessions(txn, func) { this._backend.countEndToEndSessions(txn, func); } /** * Retrieve a specific end-to-end session between the logged-in user * and another device. * @param {string} deviceKey The public key of the other device. * @param {string} sessionId The ID of the session to retrieve * @param {*} txn An active transaction. See doTxn(). * @param {function(object)} func Called with A map from sessionId * to session information object with 'session' key being the * Base64 end-to-end session and lastReceivedMessageTs being the * timestamp in milliseconds at which the session last received * a message. */ }, { key: "getEndToEndSession", value: function getEndToEndSession(deviceKey, sessionId, txn, func) { this._backend.getEndToEndSession(deviceKey, sessionId, txn, func); } /** * Retrieve the end-to-end sessions between the logged-in user and another * device. * @param {string} deviceKey The public key of the other device. * @param {*} txn An active transaction. See doTxn(). * @param {function(object)} func Called with A map from sessionId * to session information object with 'session' key being the * Base64 end-to-end session and lastReceivedMessageTs being the * timestamp in milliseconds at which the session last received * a message. */ }, { key: "getEndToEndSessions", value: function getEndToEndSessions(deviceKey, txn, func) { this._backend.getEndToEndSessions(deviceKey, txn, func); } /** * Retrieve all end-to-end sessions * @param {*} txn An active transaction. See doTxn(). * @param {function(object)} func Called one for each session with * an object with, deviceKey, lastReceivedMessageTs, sessionId * and session keys. */ }, { key: "getAllEndToEndSessions", value: function getAllEndToEndSessions(txn, func) { this._backend.getAllEndToEndSessions(txn, func); } /** * Store a session between the logged-in user and another device * @param {string} deviceKey The public key of the other device. * @param {string} sessionId The ID for this end-to-end session. * @param {string} sessionInfo Session information object * @param {*} txn An active transaction. See doTxn(). */ }, { key: "storeEndToEndSession", value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { this._backend.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn); } }, { key: "storeEndToEndSessionProblem", value: function storeEndToEndSessionProblem(deviceKey, type, fixed) { return this._backend.storeEndToEndSessionProblem(deviceKey, type, fixed); } }, { key: "getEndToEndSessionProblem", value: function getEndToEndSessionProblem(deviceKey, timestamp) { return this._backend.getEndToEndSessionProblem(deviceKey, timestamp); } }, { key: "filterOutNotifiedErrorDevices", value: function filterOutNotifiedErrorDevices(devices) { return this._backend.filterOutNotifiedErrorDevices(devices); } // Inbound group sessions /** * Retrieve the end-to-end inbound group session for a given * server key and session ID * @param {string} senderCurve25519Key The sender's curve 25519 key * @param {string} sessionId The ID of the session * @param {*} txn An active transaction. See doTxn(). * @param {function(object)} func Called with A map from sessionId * to Base64 end-to-end session. */ }, { key: "getEndToEndInboundGroupSession", value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { this._backend.getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func); } /** * Fetches all inbound group sessions in the store * @param {*} txn An active transaction. See doTxn(). * @param {function(object)} func Called once for each group session * in the store with an object having keys {senderKey, sessionId, * sessionData}, then once with null to indicate the end of the list. */ }, { key: "getAllEndToEndInboundGroupSessions", value: function getAllEndToEndInboundGroupSessions(txn, func) { this._backend.getAllEndToEndInboundGroupSessions(txn, func); } /** * Adds an end-to-end inbound group session to the store. * If there already exists an inbound group session with the same * senderCurve25519Key and sessionID, the session will not be added. * @param {string} senderCurve25519Key The sender's curve 25519 key * @param {string} sessionId The ID of the session * @param {object} sessionData The session data structure * @param {*} txn An active transaction. See doTxn(). */ }, { key: "addEndToEndInboundGroupSession", value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { this._backend.addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn); } /** * Writes an end-to-end inbound group session to the store. * If there already exists an inbound group session with the same * senderCurve25519Key and sessionID, it will be overwritten. * @param {string} senderCurve25519Key The sender's curve 25519 key * @param {string} sessionId The ID of the session * @param {object} sessionData The session data structure * @param {*} txn An active transaction. See doTxn(). */ }, { key: "storeEndToEndInboundGroupSession", value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { this._backend.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn); } }, { key: "storeEndToEndInboundGroupSessionWithheld", value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { this._backend.storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn); } // End-to-end device tracking /** * Store the state of all tracked devices * This contains devices for each user, a tracking state for each user * and a sync token matching the point in time the snapshot represents. * These all need to be written out in full each time such that the snapshot * is always consistent, so they are stored in one object. * * @param {Object} deviceData * @param {*} txn An active transaction. See doTxn(). */ }, { key: "storeEndToEndDeviceData", value: function storeEndToEndDeviceData(deviceData, txn) { this._backend.storeEndToEndDeviceData(deviceData, txn); } /** * Get the state of all tracked devices * * @param {*} txn An active transaction. See doTxn(). * @param {function(Object)} func Function called with the * device data */ }, { key: "getEndToEndDeviceData", value: function getEndToEndDeviceData(txn, func) { this._backend.getEndToEndDeviceData(txn, func); } // End to End Rooms /** * Store the end-to-end state for a room. * @param {string} roomId The room's ID. * @param {object} roomInfo The end-to-end info for the room. * @param {*} txn An active transaction. See doTxn(). */ }, { key: "storeEndToEndRoom", value: function storeEndToEndRoom(roomId, roomInfo, txn) { this._backend.storeEndToEndRoom(roomId, roomInfo, txn); } /** * Get an object of roomId->roomInfo for all e2e rooms in the store * @param {*} txn An active transaction. See doTxn(). * @param {function(Object)} func Function called with the end to end encrypted rooms */ }, { key: "getEndToEndRooms", value: function getEndToEndRooms(txn, func) { this._backend.getEndToEndRooms(txn, func); } // session backups /** * Get the inbound group sessions that need to be backed up. * @param {integer} limit The maximum number of sessions to retrieve. 0 * for no limit. * @returns {Promise} resolves to an array of inbound group sessions */ }, { key: "getSessionsNeedingBackup", value: function getSessionsNeedingBackup(limit) { return this._backend.getSessionsNeedingBackup(limit); } /** * Count the inbound group sessions that need to be backed up. * @param {*} txn An active transaction. See doTxn(). (optional) * @returns {Promise} resolves to the number of sessions */ }, { key: "countSessionsNeedingBackup", value: function countSessionsNeedingBackup(txn) { return this._backend.countSessionsNeedingBackup(txn); } /** * Unmark sessions as needing to be backed up. * @param {Array} sessions The sessions that need to be backed up. * @param {*} txn An active transaction. See doTxn(). (optional) * @returns {Promise} resolves when the sessions are unmarked */ }, { key: "unmarkSessionsNeedingBackup", value: function unmarkSessionsNeedingBackup(sessions, txn) { return this._backend.unmarkSessionsNeedingBackup(sessions, txn); } /** * Mark sessions as needing to be backed up. * @param {Array} sessions The sessions that need to be backed up. * @param {*} txn An active transaction. See doTxn(). (optional) * @returns {Promise} resolves when the sessions are marked */ }, { key: "markSessionsNeedingBackup", value: function markSessionsNeedingBackup(sessions, txn) { return this._backend.markSessionsNeedingBackup(sessions, txn); } /** * Perform a transaction on the crypto store. Any store methods * that require a transaction (txn) object to be passed in may * only be called within a callback of either this function or * one of the store functions operating on the same transaction. * * @param {string} mode 'readwrite' if you need to call setter * functions with this transaction. Otherwise, 'readonly'. * @param {string[]} stores List IndexedDBCryptoStore.STORE_* * options representing all types of object that will be * accessed or written to with this transaction. * @param {function(*)} func Function called with the * transaction object: an opaque object that should be passed * to store functions. * @return {Promise} Promise that resolves with the result of the `func` * when the transaction is complete. If the backend is * async (ie. the indexeddb backend) any of the callback * functions throwing an exception will cause this promise to * reject with that exception. On synchronous backends, the * exception will propagate to the caller of the getFoo method. */ }, { key: "doTxn", value: function doTxn(mode, stores, func) { return this._backend.doTxn(mode, stores, func); } }], [{ key: "exists", value: function exists(indexedDB, dbName) { return IndexedDBHelpers.exists(indexedDB, dbName); } }]); return IndexedDBCryptoStore; }(); exports.IndexedDBCryptoStore = IndexedDBCryptoStore; IndexedDBCryptoStore.STORE_ACCOUNT = 'account'; IndexedDBCryptoStore.STORE_SESSIONS = 'sessions'; IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS = 'inbound_group_sessions'; IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD = 'inbound_group_sessions_withheld'; IndexedDBCryptoStore.STORE_DEVICE_DATA = 'device_data'; IndexedDBCryptoStore.STORE_ROOMS = 'rooms'; IndexedDBCryptoStore.STORE_BACKUP = 'sessions_needing_backup'; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../../errors":89,"../../indexeddb-helpers":93,"../../logger":95,"./indexeddb-crypto-store-backend":77,"./localStorage-crypto-store":79,"./memory-crypto-store":80,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13}],79:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.LocalStorageCryptoStore = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _logger = require("../../logger"); var _memoryCryptoStore = require("./memory-crypto-store"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * Internal module. Partial localStorage backed storage for e2e. * This is not a full crypto store, just the in-memory store with * some things backed by localStorage. It exists because indexedDB * is broken in Firefox private mode or set to, "will not remember * history". * * @module */ var E2E_PREFIX = "crypto."; var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account"; var KEY_CROSS_SIGNING_KEYS = E2E_PREFIX + "cross_signing_keys"; var KEY_NOTIFIED_ERROR_DEVICES = E2E_PREFIX + "notified_error_devices"; var KEY_DEVICE_DATA = E2E_PREFIX + "device_data"; var KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + "inboundgroupsessions/"; var KEY_INBOUND_SESSION_WITHHELD_PREFIX = E2E_PREFIX + "inboundgroupsessions.withheld/"; var KEY_ROOMS_PREFIX = E2E_PREFIX + "rooms/"; var KEY_SESSIONS_NEEDING_BACKUP = E2E_PREFIX + "sessionsneedingbackup"; function keyEndToEndSessions(deviceKey) { return E2E_PREFIX + "sessions/" + deviceKey; } function keyEndToEndSessionProblems(deviceKey) { return E2E_PREFIX + "session.problems/" + deviceKey; } function keyEndToEndInboundGroupSession(senderKey, sessionId) { return KEY_INBOUND_SESSION_PREFIX + senderKey + "/" + sessionId; } function keyEndToEndInboundGroupSessionWithheld(senderKey, sessionId) { return KEY_INBOUND_SESSION_WITHHELD_PREFIX + senderKey + "/" + sessionId; } function keyEndToEndRoomsPrefix(roomId) { return KEY_ROOMS_PREFIX + roomId; } /** * @implements {module:crypto/store/base~CryptoStore} */ var LocalStorageCryptoStore = /*#__PURE__*/function (_MemoryCryptoStore) { (0, _inherits2["default"])(LocalStorageCryptoStore, _MemoryCryptoStore); var _super = _createSuper(LocalStorageCryptoStore); function LocalStorageCryptoStore(webStore) { var _this; (0, _classCallCheck2["default"])(this, LocalStorageCryptoStore); _this = _super.call(this); _this.store = webStore; return _this; } (0, _createClass2["default"])(LocalStorageCryptoStore, [{ key: "countEndToEndSessions", // Olm Sessions value: function countEndToEndSessions(txn, func) { var count = 0; for (var i = 0; i < this.store.length; ++i) { if (this.store.key(i).startsWith(keyEndToEndSessions(''))) ++count; } func(count); } }, { key: "_getEndToEndSessions", value: function _getEndToEndSessions(deviceKey, txn, func) { var sessions = getJsonItem(this.store, keyEndToEndSessions(deviceKey)); var fixedSessions = {}; // fix up any old sessions to be objects rather than just the base64 pickle for (var _i = 0, _Object$entries = Object.entries(sessions || {}); _i < _Object$entries.length; _i++) { var _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2), sid = _Object$entries$_i[0], val = _Object$entries$_i[1]; if (typeof val === 'string') { fixedSessions[sid] = { session: val }; } else { fixedSessions[sid] = val; } } return fixedSessions; } }, { key: "getEndToEndSession", value: function getEndToEndSession(deviceKey, sessionId, txn, func) { var sessions = this._getEndToEndSessions(deviceKey); func(sessions[sessionId] || {}); } }, { key: "getEndToEndSessions", value: function getEndToEndSessions(deviceKey, txn, func) { func(this._getEndToEndSessions(deviceKey) || {}); } }, { key: "getAllEndToEndSessions", value: function getAllEndToEndSessions(txn, func) { for (var i = 0; i < this.store.length; ++i) { if (this.store.key(i).startsWith(keyEndToEndSessions(''))) { var deviceKey = this.store.key(i).split('/')[1]; for (var _i2 = 0, _Object$values = Object.values(this._getEndToEndSessions(deviceKey)); _i2 < _Object$values.length; _i2++) { var sess = _Object$values[_i2]; func(sess); } } } } }, { key: "storeEndToEndSession", value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { var sessions = this._getEndToEndSessions(deviceKey) || {}; sessions[sessionId] = sessionInfo; setJsonItem(this.store, keyEndToEndSessions(deviceKey), sessions); } }, { key: "storeEndToEndSessionProblem", value: function () { var _storeEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(deviceKey, type, fixed) { var key, problems; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: key = keyEndToEndSessionProblems(deviceKey); problems = getJsonItem(this.store, key) || []; problems.push({ type: type, fixed: fixed, time: Date.now() }); problems.sort(function (a, b) { return a.time - b.time; }); setJsonItem(this.store, key, problems); case 5: case "end": return _context.stop(); } } }, _callee, this); })); function storeEndToEndSessionProblem(_x, _x2, _x3) { return _storeEndToEndSessionProblem.apply(this, arguments); } return storeEndToEndSessionProblem; }() }, { key: "getEndToEndSessionProblem", value: function () { var _getEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(deviceKey, timestamp) { var key, problems, lastProblem, _iterator, _step, problem; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: key = keyEndToEndSessionProblems(deviceKey); problems = getJsonItem(this.store, key) || []; if (problems.length) { _context2.next = 4; break; } return _context2.abrupt("return", null); case 4: lastProblem = problems[problems.length - 1]; _iterator = _createForOfIteratorHelper(problems); _context2.prev = 6; _iterator.s(); case 8: if ((_step = _iterator.n()).done) { _context2.next = 14; break; } problem = _step.value; if (!(problem.time > timestamp)) { _context2.next = 12; break; } return _context2.abrupt("return", Object.assign({}, problem, { fixed: lastProblem.fixed })); case 12: _context2.next = 8; break; case 14: _context2.next = 19; break; case 16: _context2.prev = 16; _context2.t0 = _context2["catch"](6); _iterator.e(_context2.t0); case 19: _context2.prev = 19; _iterator.f(); return _context2.finish(19); case 22: if (!lastProblem.fixed) { _context2.next = 26; break; } return _context2.abrupt("return", null); case 26: return _context2.abrupt("return", lastProblem); case 27: case "end": return _context2.stop(); } } }, _callee2, this, [[6, 16, 19, 22]]); })); function getEndToEndSessionProblem(_x4, _x5) { return _getEndToEndSessionProblem.apply(this, arguments); } return getEndToEndSessionProblem; }() }, { key: "filterOutNotifiedErrorDevices", value: function () { var _filterOutNotifiedErrorDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(devices) { var notifiedErrorDevices, ret, _iterator2, _step2, device, userId, deviceInfo; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: notifiedErrorDevices = getJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES) || {}; ret = []; _iterator2 = _createForOfIteratorHelper(devices); try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { device = _step2.value; userId = device.userId, deviceInfo = device.deviceInfo; if (userId in notifiedErrorDevices) { if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) { ret.push(device); notifiedErrorDevices[userId][deviceInfo.deviceId] = true; } } else { ret.push(device); notifiedErrorDevices[userId] = (0, _defineProperty2["default"])({}, deviceInfo.deviceId, true); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } setJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES, notifiedErrorDevices); return _context3.abrupt("return", ret); case 6: case "end": return _context3.stop(); } } }, _callee3, this); })); function filterOutNotifiedErrorDevices(_x6) { return _filterOutNotifiedErrorDevices.apply(this, arguments); } return filterOutNotifiedErrorDevices; }() // Inbound Group Sessions }, { key: "getEndToEndInboundGroupSession", value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { func(getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)), getJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId))); } }, { key: "getAllEndToEndInboundGroupSessions", value: function getAllEndToEndInboundGroupSessions(txn, func) { for (var i = 0; i < this.store.length; ++i) { var key = this.store.key(i); if (key.startsWith(KEY_INBOUND_SESSION_PREFIX)) { // we can't use split, as the components we are trying to split out // might themselves contain '/' characters. We rely on the // senderKey being a (32-byte) curve25519 key, base64-encoded // (hence 43 characters long). func({ senderKey: key.substr(KEY_INBOUND_SESSION_PREFIX.length, 43), sessionId: key.substr(KEY_INBOUND_SESSION_PREFIX.length + 44), sessionData: getJsonItem(this.store, key) }); } } func(null); } }, { key: "addEndToEndInboundGroupSession", value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { var existing = getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)); if (!existing) { this.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn); } } }, { key: "storeEndToEndInboundGroupSession", value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { setJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId), sessionData); } }, { key: "storeEndToEndInboundGroupSessionWithheld", value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { setJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId), sessionData); } }, { key: "getEndToEndDeviceData", value: function getEndToEndDeviceData(txn, func) { func(getJsonItem(this.store, KEY_DEVICE_DATA)); } }, { key: "storeEndToEndDeviceData", value: function storeEndToEndDeviceData(deviceData, txn) { setJsonItem(this.store, KEY_DEVICE_DATA, deviceData); } }, { key: "storeEndToEndRoom", value: function storeEndToEndRoom(roomId, roomInfo, txn) { setJsonItem(this.store, keyEndToEndRoomsPrefix(roomId), roomInfo); } }, { key: "getEndToEndRooms", value: function getEndToEndRooms(txn, func) { var result = {}; var prefix = keyEndToEndRoomsPrefix(''); for (var i = 0; i < this.store.length; ++i) { var key = this.store.key(i); if (key.startsWith(prefix)) { var roomId = key.substr(prefix.length); result[roomId] = getJsonItem(this.store, key); } } func(result); } }, { key: "getSessionsNeedingBackup", value: function getSessionsNeedingBackup(limit) { var _this2 = this; var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; var sessions = []; for (var session in sessionsNeedingBackup) { if (Object.prototype.hasOwnProperty.call(sessionsNeedingBackup, session)) { var _ret = function () { // see getAllEndToEndInboundGroupSessions for the magic number explanations var senderKey = session.substr(0, 43); var sessionId = session.substr(44); _this2.getEndToEndInboundGroupSession(senderKey, sessionId, null, function (sessionData) { sessions.push({ senderKey: senderKey, sessionId: sessionId, sessionData: sessionData }); }); if (limit && session.length >= limit) { return "break"; } }(); if (_ret === "break") break; } } return Promise.resolve(sessions); } }, { key: "countSessionsNeedingBackup", value: function countSessionsNeedingBackup() { var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; return Promise.resolve(Object.keys(sessionsNeedingBackup).length); } }, { key: "unmarkSessionsNeedingBackup", value: function unmarkSessionsNeedingBackup(sessions) { var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; var _iterator3 = _createForOfIteratorHelper(sessions), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var session = _step3.value; delete sessionsNeedingBackup[session.senderKey + '/' + session.sessionId]; } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup); return Promise.resolve(); } }, { key: "markSessionsNeedingBackup", value: function markSessionsNeedingBackup(sessions) { var sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; var _iterator4 = _createForOfIteratorHelper(sessions), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var session = _step4.value; sessionsNeedingBackup[session.senderKey + '/' + session.sessionId] = true; } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup); return Promise.resolve(); } /** * Delete all data from this store. * * @returns {Promise} Promise which resolves when the store has been cleared. */ }, { key: "deleteAllData", value: function deleteAllData() { this.store.removeItem(KEY_END_TO_END_ACCOUNT); return Promise.resolve(); } // Olm account }, { key: "getAccount", value: function getAccount(txn, func) { var account = getJsonItem(this.store, KEY_END_TO_END_ACCOUNT); func(account); } }, { key: "storeAccount", value: function storeAccount(txn, newData) { setJsonItem(this.store, KEY_END_TO_END_ACCOUNT, newData); } }, { key: "getCrossSigningKeys", value: function getCrossSigningKeys(txn, func) { var keys = getJsonItem(this.store, KEY_CROSS_SIGNING_KEYS); func(keys); } }, { key: "getSecretStorePrivateKey", value: function getSecretStorePrivateKey(txn, func, type) { var key = getJsonItem(this.store, E2E_PREFIX + "ssss_cache.".concat(type)); func(key); } }, { key: "storeCrossSigningKeys", value: function storeCrossSigningKeys(txn, keys) { setJsonItem(this.store, KEY_CROSS_SIGNING_KEYS, keys); } }, { key: "storeSecretStorePrivateKey", value: function storeSecretStorePrivateKey(txn, type, key) { setJsonItem(this.store, E2E_PREFIX + "ssss_cache.".concat(type), key); } }, { key: "doTxn", value: function doTxn(mode, stores, func) { return Promise.resolve(func(null)); } }], [{ key: "exists", value: function exists(webStore) { var length = webStore.length; for (var i = 0; i < length; i++) { if (webStore.key(i).startsWith(E2E_PREFIX)) { return true; } } return false; } }]); return LocalStorageCryptoStore; }(_memoryCryptoStore.MemoryCryptoStore); exports.LocalStorageCryptoStore = LocalStorageCryptoStore; function getJsonItem(store, key) { try { // if the key is absent, store.getItem() returns null, and // JSON.parse(null) === null, so this returns null. return JSON.parse(store.getItem(key)); } catch (e) { _logger.logger.log("Error: Failed to get key %s: %s", key, e.stack || e); _logger.logger.log(e.stack); } return null; } function setJsonItem(store, key, val) { store.setItem(key, JSON.stringify(val)); } },{"../../logger":95,"./memory-crypto-store":80,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27}],80:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MemoryCryptoStore = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _logger = require("../../logger"); var utils = _interopRequireWildcard(require("../../utils")); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * Internal module. in-memory storage for e2e. * * @module */ /** * @implements {module:crypto/store/base~CryptoStore} */ var MemoryCryptoStore = /*#__PURE__*/function () { function MemoryCryptoStore() { (0, _classCallCheck2["default"])(this, MemoryCryptoStore); this._outgoingRoomKeyRequests = []; this._account = null; this._crossSigningKeys = null; this._privateKeys = {}; this._backupKeys = {}; // Map of {devicekey -> {sessionId -> session pickle}} this._sessions = {}; // Map of {devicekey -> array of problems} this._sessionProblems = {}; // Map of {userId -> deviceId -> true} this._notifiedErrorDevices = {}; // Map of {senderCurve25519Key+'/'+sessionId -> session data object} this._inboundGroupSessions = {}; this._inboundGroupSessionsWithheld = {}; // Opaque device data object this._deviceData = null; // roomId -> Opaque roomInfo object this._rooms = {}; // Set of {senderCurve25519Key+'/'+sessionId} this._sessionsNeedingBackup = {}; } /** * Ensure the database exists and is up-to-date. * * This must be called before the store can be used. * * @return {Promise} resolves to the store. */ (0, _createClass2["default"])(MemoryCryptoStore, [{ key: "startup", value: function () { var _startup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", this); case 1: case "end": return _context.stop(); } } }, _callee, this); })); function startup() { return _startup.apply(this, arguments); } return startup; }() /** * Delete all data from this store. * * @returns {Promise} Promise which resolves when the store has been cleared. */ }, { key: "deleteAllData", value: function deleteAllData() { return Promise.resolve(); } /** * Look for an existing outgoing room key request, and if none is found, * add a new one * * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request * * @returns {Promise} resolves to * {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the * same instance as passed in, or the existing one. */ }, { key: "getOrAddOutgoingRoomKeyRequest", value: function getOrAddOutgoingRoomKeyRequest(request) { var _this = this; var requestBody = request.requestBody; return utils.promiseTry(function () { // first see if we already have an entry for this request. var existing = _this._getOutgoingRoomKeyRequest(requestBody); if (existing) { // this entry matches the request - return it. _logger.logger.log("already have key request outstanding for " + "".concat(requestBody.room_id, " / ").concat(requestBody.session_id, ": ") + "not sending another"); return existing; } // we got to the end of the list without finding a match // - add the new request. _logger.logger.log("enqueueing key request for ".concat(requestBody.room_id, " / ") + requestBody.session_id); _this._outgoingRoomKeyRequests.push(request); return request; }); } /** * Look for an existing room key request * * @param {module:crypto~RoomKeyRequestBody} requestBody * existing request to look for * * @return {Promise} resolves to the matching * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * not found */ }, { key: "getOutgoingRoomKeyRequest", value: function getOutgoingRoomKeyRequest(requestBody) { return Promise.resolve(this._getOutgoingRoomKeyRequest(requestBody)); } /** * Looks for existing room key request, and returns the result synchronously. * * @internal * * @param {module:crypto~RoomKeyRequestBody} requestBody * existing request to look for * * @return {module:crypto/store/base~OutgoingRoomKeyRequest?} * the matching request, or null if not found */ }, { key: "_getOutgoingRoomKeyRequest", value: function _getOutgoingRoomKeyRequest(requestBody) { var _iterator = _createForOfIteratorHelper(this._outgoingRoomKeyRequests), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var existing = _step.value; if (utils.deepCompare(existing.requestBody, requestBody)) { return existing; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return null; } /** * Look for room key requests by state * * @param {Array} wantedStates list of acceptable states * * @return {Promise} resolves to the a * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if * there are no pending requests in those states */ }, { key: "getOutgoingRoomKeyRequestByState", value: function getOutgoingRoomKeyRequestByState(wantedStates) { var _iterator2 = _createForOfIteratorHelper(this._outgoingRoomKeyRequests), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var req = _step2.value; var _iterator3 = _createForOfIteratorHelper(wantedStates), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var state = _step3.value; if (req.state === state) { return Promise.resolve(req); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return Promise.resolve(null); } /** * * @param {Number} wantedState * @return {Promise>} All OutgoingRoomKeyRequests in state */ }, { key: "getAllOutgoingRoomKeyRequestsByState", value: function getAllOutgoingRoomKeyRequestsByState(wantedState) { return Promise.resolve(this._outgoingRoomKeyRequests.filter(function (r) { return r.state == wantedState; })); } }, { key: "getOutgoingRoomKeyRequestsByTarget", value: function getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) { var results = []; var _iterator4 = _createForOfIteratorHelper(this._outgoingRoomKeyRequests), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var req = _step4.value; var _iterator5 = _createForOfIteratorHelper(wantedStates), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var state = _step5.value; if (req.state === state && req.recipients.includes({ userId: userId, deviceId: deviceId })) { results.push(req); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return Promise.resolve(results); } /** * Look for an existing room key request by id and state, and update it if * found * * @param {string} requestId ID of request to update * @param {number} expectedState state we expect to find the request in * @param {Object} updates name/value map of updates to apply * * @returns {Promise} resolves to * {@link module:crypto/store/base~OutgoingRoomKeyRequest} * updated request, or null if no matching row was found */ }, { key: "updateOutgoingRoomKeyRequest", value: function updateOutgoingRoomKeyRequest(requestId, expectedState, updates) { var _iterator6 = _createForOfIteratorHelper(this._outgoingRoomKeyRequests), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var req = _step6.value; if (req.requestId !== requestId) { continue; } if (req.state != expectedState) { _logger.logger.warn("Cannot update room key request from ".concat(expectedState, " ") + "as it was already updated to ".concat(req.state)); return Promise.resolve(null); } Object.assign(req, updates); return Promise.resolve(req); } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return Promise.resolve(null); } /** * Look for an existing room key request by id and state, and delete it if * found * * @param {string} requestId ID of request to update * @param {number} expectedState state we expect to find the request in * * @returns {Promise} resolves once the operation is completed */ }, { key: "deleteOutgoingRoomKeyRequest", value: function deleteOutgoingRoomKeyRequest(requestId, expectedState) { for (var i = 0; i < this._outgoingRoomKeyRequests.length; i++) { var req = this._outgoingRoomKeyRequests[i]; if (req.requestId !== requestId) { continue; } if (req.state != expectedState) { _logger.logger.warn("Cannot delete room key request in state ".concat(req.state, " ") + "(expected ".concat(expectedState, ")")); return Promise.resolve(null); } this._outgoingRoomKeyRequests.splice(i, 1); return Promise.resolve(req); } return Promise.resolve(null); } // Olm Account }, { key: "getAccount", value: function getAccount(txn, func) { func(this._account); } }, { key: "storeAccount", value: function storeAccount(txn, newData) { this._account = newData; } }, { key: "getCrossSigningKeys", value: function getCrossSigningKeys(txn, func) { func(this._crossSigningKeys); } }, { key: "getSecretStorePrivateKey", value: function getSecretStorePrivateKey(txn, func, type) { var result = this._privateKeys[type]; return func(result || null); } }, { key: "storeCrossSigningKeys", value: function storeCrossSigningKeys(txn, keys) { this._crossSigningKeys = keys; } }, { key: "storeSecretStorePrivateKey", value: function storeSecretStorePrivateKey(txn, type, key) { this._privateKeys[type] = key; } // Olm Sessions }, { key: "countEndToEndSessions", value: function countEndToEndSessions(txn, func) { return Object.keys(this._sessions).length; } }, { key: "getEndToEndSession", value: function getEndToEndSession(deviceKey, sessionId, txn, func) { var deviceSessions = this._sessions[deviceKey] || {}; func(deviceSessions[sessionId] || null); } }, { key: "getEndToEndSessions", value: function getEndToEndSessions(deviceKey, txn, func) { func(this._sessions[deviceKey] || {}); } }, { key: "getAllEndToEndSessions", value: function getAllEndToEndSessions(txn, func) { Object.entries(this._sessions).forEach(function (_ref) { var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), deviceKey = _ref2[0], deviceSessions = _ref2[1]; Object.entries(deviceSessions).forEach(function (_ref3) { var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2), sessionId = _ref4[0], session = _ref4[1]; func(_objectSpread(_objectSpread({}, session), {}, { deviceKey: deviceKey, sessionId: sessionId })); }); }); } }, { key: "storeEndToEndSession", value: function storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { var deviceSessions = this._sessions[deviceKey]; if (deviceSessions === undefined) { deviceSessions = {}; this._sessions[deviceKey] = deviceSessions; } deviceSessions[sessionId] = sessionInfo; } }, { key: "storeEndToEndSessionProblem", value: function () { var _storeEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(deviceKey, type, fixed) { var problems; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: problems = this._sessionProblems[deviceKey] = this._sessionProblems[deviceKey] || []; problems.push({ type: type, fixed: fixed, time: Date.now() }); problems.sort(function (a, b) { return a.time - b.time; }); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function storeEndToEndSessionProblem(_x, _x2, _x3) { return _storeEndToEndSessionProblem.apply(this, arguments); } return storeEndToEndSessionProblem; }() }, { key: "getEndToEndSessionProblem", value: function () { var _getEndToEndSessionProblem = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(deviceKey, timestamp) { var problems, lastProblem, _iterator7, _step7, problem; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: problems = this._sessionProblems[deviceKey] || []; if (problems.length) { _context3.next = 3; break; } return _context3.abrupt("return", null); case 3: lastProblem = problems[problems.length - 1]; _iterator7 = _createForOfIteratorHelper(problems); _context3.prev = 5; _iterator7.s(); case 7: if ((_step7 = _iterator7.n()).done) { _context3.next = 13; break; } problem = _step7.value; if (!(problem.time > timestamp)) { _context3.next = 11; break; } return _context3.abrupt("return", Object.assign({}, problem, { fixed: lastProblem.fixed })); case 11: _context3.next = 7; break; case 13: _context3.next = 18; break; case 15: _context3.prev = 15; _context3.t0 = _context3["catch"](5); _iterator7.e(_context3.t0); case 18: _context3.prev = 18; _iterator7.f(); return _context3.finish(18); case 21: if (!lastProblem.fixed) { _context3.next = 25; break; } return _context3.abrupt("return", null); case 25: return _context3.abrupt("return", lastProblem); case 26: case "end": return _context3.stop(); } } }, _callee3, this, [[5, 15, 18, 21]]); })); function getEndToEndSessionProblem(_x4, _x5) { return _getEndToEndSessionProblem.apply(this, arguments); } return getEndToEndSessionProblem; }() }, { key: "filterOutNotifiedErrorDevices", value: function () { var _filterOutNotifiedErrorDevices = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(devices) { var notifiedErrorDevices, ret, _iterator8, _step8, device, userId, deviceInfo; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: notifiedErrorDevices = this._notifiedErrorDevices; ret = []; _iterator8 = _createForOfIteratorHelper(devices); try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { device = _step8.value; userId = device.userId, deviceInfo = device.deviceInfo; if (userId in notifiedErrorDevices) { if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) { ret.push(device); notifiedErrorDevices[userId][deviceInfo.deviceId] = true; } } else { ret.push(device); notifiedErrorDevices[userId] = (0, _defineProperty2["default"])({}, deviceInfo.deviceId, true); } } } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } return _context4.abrupt("return", ret); case 5: case "end": return _context4.stop(); } } }, _callee4, this); })); function filterOutNotifiedErrorDevices(_x6) { return _filterOutNotifiedErrorDevices.apply(this, arguments); } return filterOutNotifiedErrorDevices; }() // Inbound Group Sessions }, { key: "getEndToEndInboundGroupSession", value: function getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { var k = senderCurve25519Key + '/' + sessionId; func(this._inboundGroupSessions[k] || null, this._inboundGroupSessionsWithheld[k] || null); } }, { key: "getAllEndToEndInboundGroupSessions", value: function getAllEndToEndInboundGroupSessions(txn, func) { for (var _i = 0, _Object$keys = Object.keys(this._inboundGroupSessions); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; // we can't use split, as the components we are trying to split out // might themselves contain '/' characters. We rely on the // senderKey being a (32-byte) curve25519 key, base64-encoded // (hence 43 characters long). func({ senderKey: key.substr(0, 43), sessionId: key.substr(44), sessionData: this._inboundGroupSessions[key] }); } func(null); } }, { key: "addEndToEndInboundGroupSession", value: function addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { var k = senderCurve25519Key + '/' + sessionId; if (this._inboundGroupSessions[k] === undefined) { this._inboundGroupSessions[k] = sessionData; } } }, { key: "storeEndToEndInboundGroupSession", value: function storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { this._inboundGroupSessions[senderCurve25519Key + '/' + sessionId] = sessionData; } }, { key: "storeEndToEndInboundGroupSessionWithheld", value: function storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { var k = senderCurve25519Key + '/' + sessionId; this._inboundGroupSessionsWithheld[k] = sessionData; } // Device Data }, { key: "getEndToEndDeviceData", value: function getEndToEndDeviceData(txn, func) { func(this._deviceData); } }, { key: "storeEndToEndDeviceData", value: function storeEndToEndDeviceData(deviceData, txn) { this._deviceData = deviceData; } // E2E rooms }, { key: "storeEndToEndRoom", value: function storeEndToEndRoom(roomId, roomInfo, txn) { this._rooms[roomId] = roomInfo; } }, { key: "getEndToEndRooms", value: function getEndToEndRooms(txn, func) { func(this._rooms); } }, { key: "getSessionsNeedingBackup", value: function getSessionsNeedingBackup(limit) { var sessions = []; for (var session in this._sessionsNeedingBackup) { if (this._inboundGroupSessions[session]) { sessions.push({ senderKey: session.substr(0, 43), sessionId: session.substr(44), sessionData: this._inboundGroupSessions[session] }); if (limit && session.length >= limit) { break; } } } return Promise.resolve(sessions); } }, { key: "countSessionsNeedingBackup", value: function countSessionsNeedingBackup() { return Promise.resolve(Object.keys(this._sessionsNeedingBackup).length); } }, { key: "unmarkSessionsNeedingBackup", value: function unmarkSessionsNeedingBackup(sessions) { var _iterator9 = _createForOfIteratorHelper(sessions), _step9; try { for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { var session = _step9.value; var sessionKey = session.senderKey + '/' + session.sessionId; delete this._sessionsNeedingBackup[sessionKey]; } } catch (err) { _iterator9.e(err); } finally { _iterator9.f(); } return Promise.resolve(); } }, { key: "markSessionsNeedingBackup", value: function markSessionsNeedingBackup(sessions) { var _iterator10 = _createForOfIteratorHelper(sessions), _step10; try { for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) { var session = _step10.value; var sessionKey = session.senderKey + '/' + session.sessionId; this._sessionsNeedingBackup[sessionKey] = true; } } catch (err) { _iterator10.e(err); } finally { _iterator10.f(); } return Promise.resolve(); } // Session key backups }, { key: "doTxn", value: function doTxn(mode, stores, func) { return Promise.resolve(func(null)); } }]); return MemoryCryptoStore; }(); exports.MemoryCryptoStore = MemoryCryptoStore; },{"../../logger":95,"../../utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27}],81:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.VerificationBase = exports.SwitchStartEventError = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); var _event = require("../../models/event"); var _events = require("events"); var _logger = require("../../logger"); var _deviceinfo = require("../deviceinfo"); var _Error2 = require("./Error"); var _CrossSigning = require("../CrossSigning"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var timeoutException = new Error("Verification timed out"); var SwitchStartEventError = /*#__PURE__*/function (_Error) { (0, _inherits2["default"])(SwitchStartEventError, _Error); var _super = _createSuper(SwitchStartEventError); function SwitchStartEventError(startEvent) { var _this; (0, _classCallCheck2["default"])(this, SwitchStartEventError); _this = _super.call(this); _this.startEvent = startEvent; return _this; } return SwitchStartEventError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); exports.SwitchStartEventError = SwitchStartEventError; var VerificationBase = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(VerificationBase, _EventEmitter); var _super2 = _createSuper(VerificationBase); /** * Base class for verification methods. * *

Once a verifier object is created, the verification can be started by * calling the verify() method, which will return a promise that will * resolve when the verification is completed, or reject if it could not * complete.

* *

Subclasses must have a NAME class property.

* * @class * * @param {module:base-apis~Channel} channel the verification channel to send verification messages over. * * @param {module:base-apis~MatrixBaseApis} baseApis base matrix api interface * * @param {string} userId the user ID that is being verified * * @param {string} deviceId the device ID that is being verified * * @param {object} [startEvent] the m.key.verification.start event that * initiated this verification, if any * * @param {object} [request] the key verification request object related to * this verification, if any */ function VerificationBase(channel, baseApis, userId, deviceId, startEvent, request) { var _this2; (0, _classCallCheck2["default"])(this, VerificationBase); _this2 = _super2.call(this); _this2._channel = channel; _this2._baseApis = baseApis; _this2.userId = userId; _this2.deviceId = deviceId; _this2.startEvent = startEvent; _this2.request = request; _this2.cancelled = false; _this2._done = false; _this2._promise = null; _this2._transactionTimeoutTimer = null; return _this2; } (0, _createClass2["default"])(VerificationBase, [{ key: "_resetTimer", value: function _resetTimer() { var _this3 = this; _logger.logger.info("Refreshing/starting the verification transaction timeout timer"); if (this._transactionTimeoutTimer !== null) { clearTimeout(this._transactionTimeoutTimer); } this._transactionTimeoutTimer = setTimeout(function () { if (!_this3._done && !_this3.cancelled) { _logger.logger.info("Triggering verification timeout"); _this3.cancel(timeoutException); } }, 10 * 60 * 1000); // 10 minutes } }, { key: "_endTimer", value: function _endTimer() { if (this._transactionTimeoutTimer !== null) { clearTimeout(this._transactionTimeoutTimer); this._transactionTimeoutTimer = null; } } }, { key: "_send", value: function _send(type, uncompletedContent) { return this._channel.send(type, uncompletedContent); } }, { key: "_waitForEvent", value: function _waitForEvent(type) { var _this4 = this; if (this._done) { return Promise.reject(new Error("Verification is already done")); } var existingEvent = this.request.getEventFromOtherParty(type); if (existingEvent) { return Promise.resolve(existingEvent); } this._expectedEvent = type; return new Promise(function (resolve, reject) { _this4._resolveEvent = resolve; _this4._rejectEvent = reject; }); } }, { key: "canSwitchStartEvent", value: function canSwitchStartEvent() { return false; } }, { key: "switchStartEvent", value: function switchStartEvent(event) { if (this.canSwitchStartEvent(event)) { _logger.logger.log("Verification Base: switching verification start event", { restartingFlow: !!this._rejectEvent }); if (this._rejectEvent) { var reject = this._rejectEvent; this._rejectEvent = undefined; reject(new SwitchStartEventError(event)); } else { this.startEvent = event; } } } }, { key: "handleEvent", value: function handleEvent(e) { if (this._done) { return; } else if (e.getType() === this._expectedEvent) { // if we receive an expected m.key.verification.done, then just // ignore it, since we don't need to do anything about it if (this._expectedEvent !== "m.key.verification.done") { this._expectedEvent = undefined; this._rejectEvent = undefined; this._resetTimer(); this._resolveEvent(e); } } else if (e.getType() === "m.key.verification.cancel") { var reject = this._reject; this._reject = undefined; // there is only promise to reject if verify has been called if (reject) { var content = e.getContent(); var reason = content.reason, code = content.code; reject(new Error("Other side cancelled verification " + "because ".concat(reason, " (").concat(code, ")"))); } } else if (this._expectedEvent) { // only cancel if there is an event expected. // if there is no event expected, it means verify() wasn't called // and we're just replaying the timeline events when syncing // after a refresh when the events haven't been stored in the cache yet. var exception = new Error("Unexpected message: expecting " + this._expectedEvent + " but got " + e.getType()); this._expectedEvent = undefined; if (this._rejectEvent) { var _reject = this._rejectEvent; this._rejectEvent = undefined; _reject(exception); } this.cancel(exception); } } }, { key: "done", value: function done() { this._endTimer(); // always kill the activity timer if (!this._done) { this.request.onVerifierFinished(); this._resolve(); return (0, _CrossSigning.requestKeysDuringVerification)(this._baseApis, this.userId, this.deviceId); } } }, { key: "cancel", value: function cancel(e) { this._endTimer(); // always kill the activity timer if (!this._done) { this.cancelled = true; this.request.onVerifierCancelled(); if (this.userId && this.deviceId) { // send a cancellation to the other user (if it wasn't // cancelled by the other user) if (e === timeoutException) { var timeoutEvent = (0, _Error2.newTimeoutError)(); this._send(timeoutEvent.getType(), timeoutEvent.getContent()); } else if (e instanceof _event.MatrixEvent) { var sender = e.getSender(); if (sender !== this.userId) { var content = e.getContent(); if (e.getType() === "m.key.verification.cancel") { content.code = content.code || "m.unknown"; content.reason = content.reason || content.body || "Unknown reason"; this._send("m.key.verification.cancel", content); } else { this._send("m.key.verification.cancel", { code: "m.unknown", reason: content.body || "Unknown reason" }); } } } else { this._send("m.key.verification.cancel", { code: "m.unknown", reason: e.toString() }); } } if (this._promise !== null) { // when we cancel without a promise, we end up with a promise // but no reject function. If cancel is called again, we'd error. if (this._reject) this._reject(e); } else { // FIXME: this causes an "Uncaught promise" console message // if nothing ends up chaining this promise. this._promise = Promise.reject(e); } // Also emit a 'cancel' event that the app can listen for to detect cancellation // before calling verify() this.emit('cancel', e); } } /** * Begin the key verification * * @returns {Promise} Promise which resolves when the verification has * completed. */ }, { key: "verify", value: function verify() { var _this5 = this; if (this._promise) return this._promise; this._promise = new Promise(function (resolve, reject) { _this5._resolve = function () { _this5._done = true; _this5._endTimer(); resolve.apply(void 0, arguments); }; _this5._reject = function () { _this5._done = true; _this5._endTimer(); reject.apply(void 0, arguments); }; }); if (this._doVerification && !this._started) { this._started = true; this._resetTimer(); // restart the timeout Promise.resolve(this._doVerification()).then(this.done.bind(this), this.cancel.bind(this)); } return this._promise; } }, { key: "_verifyKeys", value: function () { var _verifyKeys2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(userId, keys, verifier) { var verifiedDevices, _i, _Object$entries, _Object$entries$_i, keyId, keyInfo, deviceId, device, crossSigningInfo, _i2, _verifiedDevices, _deviceId; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // we try to verify all the keys that we're told about, but we might // not know about all of them, so keep track of the keys that we know // about, and ignore the rest verifiedDevices = []; _i = 0, _Object$entries = Object.entries(keys); case 2: if (!(_i < _Object$entries.length)) { _context.next = 23; break; } _Object$entries$_i = (0, _slicedToArray2["default"])(_Object$entries[_i], 2), keyId = _Object$entries$_i[0], keyInfo = _Object$entries$_i[1]; deviceId = keyId.split(':', 2)[1]; device = this._baseApis.getStoredDevice(userId, deviceId); if (!device) { _context.next = 12; break; } _context.next = 9; return verifier(keyId, device, keyInfo); case 9: verifiedDevices.push(deviceId); _context.next = 20; break; case 12: crossSigningInfo = this._baseApis._crypto._deviceList.getStoredCrossSigningForUser(userId); if (!(crossSigningInfo && crossSigningInfo.getId() === deviceId)) { _context.next = 19; break; } _context.next = 16; return verifier(keyId, _deviceinfo.DeviceInfo.fromStorage({ keys: (0, _defineProperty2["default"])({}, keyId, deviceId) }, deviceId), keyInfo); case 16: verifiedDevices.push(deviceId); _context.next = 20; break; case 19: _logger.logger.warn("verification: Could not find device ".concat(deviceId, " to verify")); case 20: _i++; _context.next = 2; break; case 23: if (verifiedDevices.length) { _context.next = 25; break; } throw new Error("No devices could be verified"); case 25: _logger.logger.info("Verification completed! Marking devices verified: ", verifiedDevices); // TODO: There should probably be a batch version of this, otherwise it's going // to upload each signature in a separate API call which is silly because the // API supports as many signatures as you like. _i2 = 0, _verifiedDevices = verifiedDevices; case 27: if (!(_i2 < _verifiedDevices.length)) { _context.next = 34; break; } _deviceId = _verifiedDevices[_i2]; _context.next = 31; return this._baseApis.setDeviceVerified(userId, _deviceId); case 31: _i2++; _context.next = 27; break; case 34: case "end": return _context.stop(); } } }, _callee, this); })); function _verifyKeys(_x, _x2, _x3) { return _verifyKeys2.apply(this, arguments); } return _verifyKeys; }() }, { key: "initiatedByMe", get: function get() { // if there is no start event yet, // we probably want to send it, // which happens if we initiate if (!this.startEvent) { return true; } var sender = this.startEvent.getSender(); var content = this.startEvent.getContent(); return sender === this._baseApis.getUserId() && content.from_device === this._baseApis.getDeviceId(); } }]); return VerificationBase; }(_events.EventEmitter); exports.VerificationBase = VerificationBase; },{"../../logger":95,"../../models/event":100,"../CrossSigning":60,"../deviceinfo":72,"./Error":82,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/wrapNativeSuper":26,"@babel/runtime/regenerator":27,"events":36}],82:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.newVerificationError = newVerificationError; exports.errorFactory = errorFactory; exports.errorFromEvent = errorFromEvent; exports.newInvalidMessageError = exports.newUserMismatchError = exports.newKeyMismatchError = exports.newUnexpectedMessageError = exports.newUnknownMethodError = exports.newUnknownTransactionError = exports.newTimeoutError = exports.newUserCancelledError = void 0; var _event = require("../../models/event"); /* Copyright 2018 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. */ /** * Error messages. * * @module crypto/verification/Error */ function newVerificationError(code, reason, extradata) { var content = Object.assign({}, { code: code, reason: reason }, extradata); return new _event.MatrixEvent({ type: "m.key.verification.cancel", content: content }); } function errorFactory(code, reason) { return function (extradata) { return newVerificationError(code, reason, extradata); }; } /** * The verification was cancelled by the user. */ var newUserCancelledError = errorFactory("m.user", "Cancelled by user"); /** * The verification timed out. */ exports.newUserCancelledError = newUserCancelledError; var newTimeoutError = errorFactory("m.timeout", "Timed out"); /** * The transaction is unknown. */ exports.newTimeoutError = newTimeoutError; var newUnknownTransactionError = errorFactory("m.unknown_transaction", "Unknown transaction"); /** * An unknown method was selected. */ exports.newUnknownTransactionError = newUnknownTransactionError; var newUnknownMethodError = errorFactory("m.unknown_method", "Unknown method"); /** * An unexpected message was sent. */ exports.newUnknownMethodError = newUnknownMethodError; var newUnexpectedMessageError = errorFactory("m.unexpected_message", "Unexpected message"); /** * The key does not match. */ exports.newUnexpectedMessageError = newUnexpectedMessageError; var newKeyMismatchError = errorFactory("m.key_mismatch", "Key mismatch"); /** * The user does not match. */ exports.newKeyMismatchError = newKeyMismatchError; var newUserMismatchError = errorFactory("m.user_error", "User mismatch"); /** * An invalid message was sent. */ exports.newUserMismatchError = newUserMismatchError; var newInvalidMessageError = errorFactory("m.invalid_message", "Invalid message"); exports.newInvalidMessageError = newInvalidMessageError; function errorFromEvent(event) { var content = event.getContent(); if (content) { var code = content.code, reason = content.reason; return { code: code, reason: reason }; } else { return { code: "Unknown error", reason: "m.unknown" }; } } },{"../../models/event":100}],83:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.IllegalMethod = void 0; var _construct2 = _interopRequireDefault(require("@babel/runtime/helpers/construct")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _Base2 = require("./Base"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * @class crypto/verification/IllegalMethod/IllegalMethod * @extends {module:crypto/verification/Base} */ var IllegalMethod = /*#__PURE__*/function (_Base) { (0, _inherits2["default"])(IllegalMethod, _Base); var _super = _createSuper(IllegalMethod); function IllegalMethod() { (0, _classCallCheck2["default"])(this, IllegalMethod); return _super.apply(this, arguments); } (0, _createClass2["default"])(IllegalMethod, [{ key: "_doVerification", value: function () { var _doVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: throw new Error("Verification is not possible with this method"); case 1: case "end": return _context.stop(); } } }, _callee); })); function _doVerification() { return _doVerification2.apply(this, arguments); } return _doVerification; }() }], [{ key: "factory", value: function factory() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (0, _construct2["default"])(IllegalMethod, args); } }, { key: "NAME", get: function get() { // Typically the name will be something else, but to complete // the contract we offer a default one here. return "org.matrix.illegal_method"; } }]); return IllegalMethod; }(_Base2.VerificationBase); exports.IllegalMethod = IllegalMethod; },{"./Base":81,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/construct":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/regenerator":27}],84:[function(require,module,exports){ (function (global,Buffer){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.QRCodeData = exports.ReciprocateQRCode = exports.SCAN_QR_CODE_METHOD = exports.SHOW_QR_CODE_METHOD = void 0; var _construct2 = _interopRequireDefault(require("@babel/runtime/helpers/construct")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _Base2 = require("./Base"); var _Error = require("./Error"); var _olmlib = require("../olmlib"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var SHOW_QR_CODE_METHOD = "m.qr_code.show.v1"; exports.SHOW_QR_CODE_METHOD = SHOW_QR_CODE_METHOD; var SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1"; /** * @class crypto/verification/QRCode/ReciprocateQRCode * @extends {module:crypto/verification/Base} */ exports.SCAN_QR_CODE_METHOD = SCAN_QR_CODE_METHOD; var ReciprocateQRCode = /*#__PURE__*/function (_Base) { (0, _inherits2["default"])(ReciprocateQRCode, _Base); var _super = _createSuper(ReciprocateQRCode); function ReciprocateQRCode() { (0, _classCallCheck2["default"])(this, ReciprocateQRCode); return _super.apply(this, arguments); } (0, _createClass2["default"])(ReciprocateQRCode, [{ key: "_doVerification", value: function () { var _doVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var _this = this; var qrCodeData, keys, masterKey, deviceId, _masterKey; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (this.startEvent) { _context.next = 2; break; } throw new Error("It is not currently possible to start verification" + "with this method yet."); case 2: qrCodeData = this.request.qrCodeData; // 1. check the secret if (!(this.startEvent.getContent()['secret'] !== qrCodeData.encodedSharedSecret)) { _context.next = 5; break; } throw (0, _Error.newKeyMismatchError)(); case 5: _context.next = 7; return new Promise(function (resolve, reject) { _this.reciprocateQREvent = { confirm: resolve, cancel: function cancel() { return reject((0, _Error.newUserCancelledError)()); } }; _this.emit("show_reciprocate_qr", _this.reciprocateQREvent); }); case 7: // 3. determine key to sign / mark as trusted keys = {}; _context.t0 = qrCodeData.mode; _context.next = _context.t0 === MODE_VERIFY_OTHER_USER ? 11 : _context.t0 === MODE_VERIFY_SELF_TRUSTED ? 14 : _context.t0 === MODE_VERIFY_SELF_UNTRUSTED ? 17 : 20; break; case 11: // add master key to keys to be signed, only if we're not doing self-verification masterKey = qrCodeData.otherUserMasterKey; keys["ed25519:".concat(masterKey)] = masterKey; return _context.abrupt("break", 20); case 14: deviceId = this.request.targetDevice.deviceId; keys["ed25519:".concat(deviceId)] = qrCodeData.otherDeviceKey; return _context.abrupt("break", 20); case 17: _masterKey = qrCodeData.myMasterKey; keys["ed25519:".concat(_masterKey)] = _masterKey; return _context.abrupt("break", 20); case 20: _context.next = 22; return this._verifyKeys(this.userId, keys, function (keyId, device, keyInfo) { // make sure the device has the expected keys var targetKey = keys[keyId]; if (!targetKey) throw (0, _Error.newKeyMismatchError)(); if (keyInfo !== targetKey) { console.error("key ID from key info does not match"); throw (0, _Error.newKeyMismatchError)(); } for (var deviceKeyId in device.keys) { if (!deviceKeyId.startsWith("ed25519")) continue; var deviceTargetKey = keys[deviceKeyId]; if (!deviceTargetKey) throw (0, _Error.newKeyMismatchError)(); if (device.keys[deviceKeyId] !== deviceTargetKey) { console.error("master key does not match"); throw (0, _Error.newKeyMismatchError)(); } } }); case 22: case "end": return _context.stop(); } } }, _callee, this); })); function _doVerification() { return _doVerification2.apply(this, arguments); } return _doVerification; }() }], [{ key: "factory", value: function factory() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (0, _construct2["default"])(ReciprocateQRCode, args); } }, { key: "NAME", get: function get() { return "m.reciprocate.v1"; } }]); return ReciprocateQRCode; }(_Base2.VerificationBase); exports.ReciprocateQRCode = ReciprocateQRCode; var CODE_VERSION = 0x02; // the version of binary QR codes we support var BINARY_PREFIX = "MATRIX"; // ASCII, used to prefix the binary format var MODE_VERIFY_OTHER_USER = 0x00; // Verifying someone who isn't us var MODE_VERIFY_SELF_TRUSTED = 0x01; // We trust the master key var MODE_VERIFY_SELF_UNTRUSTED = 0x02; // We do not trust the master key var QRCodeData = /*#__PURE__*/function () { function QRCodeData(mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey, buffer) { (0, _classCallCheck2["default"])(this, QRCodeData); this._sharedSecret = sharedSecret; this._mode = mode; this._otherUserMasterKey = otherUserMasterKey; this._otherDeviceKey = otherDeviceKey; this._myMasterKey = myMasterKey; this._buffer = buffer; } (0, _createClass2["default"])(QRCodeData, [{ key: "buffer", get: function get() { return this._buffer; } }, { key: "mode", get: function get() { return this._mode; } /** * only set when mode is MODE_VERIFY_SELF_TRUSTED * @return {string} device key of other party at time of generating QR code */ }, { key: "otherDeviceKey", get: function get() { return this._otherDeviceKey; } /** * only set when mode is MODE_VERIFY_OTHER_USER * @return {string} master key of other party at time of generating QR code */ }, { key: "otherUserMasterKey", get: function get() { return this._otherUserMasterKey; } /** * only set when mode is MODE_VERIFY_SELF_UNTRUSTED * @return {string} own master key at time of generating QR code */ }, { key: "myMasterKey", get: function get() { return this._myMasterKey; } /** * The unpadded base64 encoded shared secret. */ }, { key: "encodedSharedSecret", get: function get() { return this._sharedSecret; } }], [{ key: "create", value: function () { var _create = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(request, client) { var sharedSecret, mode, otherUserMasterKey, otherDeviceKey, myMasterKey, otherUserCrossSigningInfo, myUserId, myCrossSigningInfo, qrData, buffer; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: sharedSecret = QRCodeData._generateSharedSecret(); mode = QRCodeData._determineMode(request, client); otherUserMasterKey = null; otherDeviceKey = null; myMasterKey = null; if (!(mode === MODE_VERIFY_OTHER_USER)) { _context2.next = 10; break; } otherUserCrossSigningInfo = client.getStoredCrossSigningForUser(request.otherUserId); otherUserMasterKey = otherUserCrossSigningInfo.getId("master"); _context2.next = 17; break; case 10: if (!(mode === MODE_VERIFY_SELF_TRUSTED)) { _context2.next = 16; break; } _context2.next = 13; return QRCodeData._getOtherDeviceKey(request, client); case 13: otherDeviceKey = _context2.sent; _context2.next = 17; break; case 16: if (mode === MODE_VERIFY_SELF_UNTRUSTED) { myUserId = client.getUserId(); myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId); myMasterKey = myCrossSigningInfo.getId("master"); } case 17: qrData = QRCodeData._generateQrData(request, client, mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey); buffer = QRCodeData._generateBuffer(qrData); return _context2.abrupt("return", new QRCodeData(mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey, buffer)); case 20: case "end": return _context2.stop(); } } }, _callee2); })); function create(_x, _x2) { return _create.apply(this, arguments); } return create; }() }, { key: "_generateSharedSecret", value: function _generateSharedSecret() { var secretBytes = new Uint8Array(11); global.crypto.getRandomValues(secretBytes); return (0, _olmlib.encodeUnpaddedBase64)(secretBytes); } }, { key: "_getOtherDeviceKey", value: function () { var _getOtherDeviceKey2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(request, client) { var myUserId, otherDevice, otherDeviceId, device, key; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: myUserId = client.getUserId(); otherDevice = request.targetDevice; otherDeviceId = otherDevice ? otherDevice.deviceId : null; device = client.getStoredDevice(myUserId, otherDeviceId); if (device) { _context3.next = 6; break; } throw new Error("could not find device " + otherDeviceId); case 6: key = device.getFingerprint(); return _context3.abrupt("return", key); case 8: case "end": return _context3.stop(); } } }, _callee3); })); function _getOtherDeviceKey(_x3, _x4) { return _getOtherDeviceKey2.apply(this, arguments); } return _getOtherDeviceKey; }() }, { key: "_determineMode", value: function _determineMode(request, client) { var myUserId = client.getUserId(); var otherUserId = request.otherUserId; var mode = MODE_VERIFY_OTHER_USER; if (myUserId === otherUserId) { // Mode changes depending on whether or not we trust the master cross signing key var myTrust = client.checkUserTrust(myUserId); if (myTrust.isCrossSigningVerified()) { mode = MODE_VERIFY_SELF_TRUSTED; } else { mode = MODE_VERIFY_SELF_UNTRUSTED; } } return mode; } }, { key: "_generateQrData", value: function _generateQrData(request, client, mode, encodedSharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey) { var myUserId = client.getUserId(); var transactionId = request.channel.transactionId; var qrData = { prefix: BINARY_PREFIX, version: CODE_VERSION, mode: mode, transactionId: transactionId, firstKeyB64: '', // worked out shortly secondKeyB64: '', // worked out shortly secretB64: encodedSharedSecret }; var myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId); if (mode === MODE_VERIFY_OTHER_USER) { // First key is our master cross signing key qrData.firstKeyB64 = myCrossSigningInfo.getId("master"); // Second key is the other user's master cross signing key qrData.secondKeyB64 = otherUserMasterKey; } else if (mode === MODE_VERIFY_SELF_TRUSTED) { // First key is our master cross signing key qrData.firstKeyB64 = myCrossSigningInfo.getId("master"); qrData.secondKeyB64 = otherDeviceKey; } else if (mode === MODE_VERIFY_SELF_UNTRUSTED) { // First key is our device's key qrData.firstKeyB64 = client.getDeviceEd25519Key(); // Second key is what we think our master cross signing key is qrData.secondKeyB64 = myMasterKey; } return qrData; } }, { key: "_generateBuffer", value: function _generateBuffer(qrData) { var buf = Buffer.alloc(0); // we'll concat our way through life var appendByte = function appendByte(b) { var tmpBuf = Buffer.from([b]); buf = Buffer.concat([buf, tmpBuf]); }; var appendInt = function appendInt(i) { var tmpBuf = Buffer.alloc(2); tmpBuf.writeInt16BE(i, 0); buf = Buffer.concat([buf, tmpBuf]); }; var appendStr = function appendStr(s, enc) { var withLengthPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var tmpBuf = Buffer.from(s, enc); if (withLengthPrefix) appendInt(tmpBuf.byteLength); buf = Buffer.concat([buf, tmpBuf]); }; var appendEncBase64 = function appendEncBase64(b64) { var b = (0, _olmlib.decodeBase64)(b64); var tmpBuf = Buffer.from(b); buf = Buffer.concat([buf, tmpBuf]); }; // Actually build the buffer for the QR code appendStr(qrData.prefix, "ascii", false); appendByte(qrData.version); appendByte(qrData.mode); appendStr(qrData.transactionId, "utf-8"); appendEncBase64(qrData.firstKeyB64); appendEncBase64(qrData.secondKeyB64); appendEncBase64(qrData.secretB64); return buf; } }]); return QRCodeData; }(); exports.QRCodeData = QRCodeData; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"../olmlib":75,"./Base":81,"./Error":82,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/construct":7,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/regenerator":27,"buffer":34}],85:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SAS = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _Base2 = require("./Base"); var _anotherJson = _interopRequireDefault(require("another-json")); var _Error = require("./Error"); var _logger = require("../../logger"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var START_TYPE = "m.key.verification.start"; var EVENTS = ["m.key.verification.accept", "m.key.verification.key", "m.key.verification.mac"]; var olmutil; var newMismatchedSASError = (0, _Error.errorFactory)("m.mismatched_sas", "Mismatched short authentication string"); var newMismatchedCommitmentError = (0, _Error.errorFactory)("m.mismatched_commitment", "Mismatched commitment"); function generateDecimalSas(sasBytes) { /** * +--------+--------+--------+--------+--------+ * | Byte 0 | Byte 1 | Byte 2 | Byte 3 | Byte 4 | * +--------+--------+--------+--------+--------+ * bits: 87654321 87654321 87654321 87654321 87654321 * \____________/\_____________/\____________/ * 1st number 2nd number 3rd number */ return [(sasBytes[0] << 5 | sasBytes[1] >> 3) + 1000, ((sasBytes[1] & 0x7) << 10 | sasBytes[2] << 2 | sasBytes[3] >> 6) + 1000, ((sasBytes[3] & 0x3f) << 7 | sasBytes[4] >> 1) + 1000]; } var emojiMapping = [["🐶", "dog"], // 0 ["🐱", "cat"], // 1 ["🦁", "lion"], // 2 ["🐎", "horse"], // 3 ["🦄", "unicorn"], // 4 ["🐷", "pig"], // 5 ["🐘", "elephant"], // 6 ["🐰", "rabbit"], // 7 ["🐼", "panda"], // 8 ["🐓", "rooster"], // 9 ["🐧", "penguin"], // 10 ["🐢", "turtle"], // 11 ["🐟", "fish"], // 12 ["🐙", "octopus"], // 13 ["🦋", "butterfly"], // 14 ["🌷", "flower"], // 15 ["🌳", "tree"], // 16 ["🌵", "cactus"], // 17 ["🍄", "mushroom"], // 18 ["🌏", "globe"], // 19 ["🌙", "moon"], // 20 ["☁️", "cloud"], // 21 ["🔥", "fire"], // 22 ["🍌", "banana"], // 23 ["🍎", "apple"], // 24 ["🍓", "strawberry"], // 25 ["🌽", "corn"], // 26 ["🍕", "pizza"], // 27 ["🎂", "cake"], // 28 ["❤️", "heart"], // 29 ["🙂", "smiley"], // 30 ["🤖", "robot"], // 31 ["🎩", "hat"], // 32 ["👓", "glasses"], // 33 ["🔧", "spanner"], // 34 ["🎅", "santa"], // 35 ["👍", "thumbs up"], // 36 ["☂️", "umbrella"], // 37 ["⌛", "hourglass"], // 38 ["⏰", "clock"], // 39 ["🎁", "gift"], // 40 ["💡", "light bulb"], // 41 ["📕", "book"], // 42 ["✏️", "pencil"], // 43 ["📎", "paperclip"], // 44 ["✂️", "scissors"], // 45 ["🔒", "lock"], // 46 ["🔑", "key"], // 47 ["🔨", "hammer"], // 48 ["☎️", "telephone"], // 49 ["🏁", "flag"], // 50 ["🚂", "train"], // 51 ["🚲", "bicycle"], // 52 ["✈️", "aeroplane"], // 53 ["🚀", "rocket"], // 54 ["🏆", "trophy"], // 55 ["⚽", "ball"], // 56 ["🎸", "guitar"], // 57 ["🎺", "trumpet"], // 58 ["🔔", "bell"], // 59 ["⚓️", "anchor"], // 60 ["🎧", "headphones"], // 61 ["📁", "folder"], // 62 ["📌", "pin"] // 63 ]; function generateEmojiSas(sasBytes) { var emojis = [// just like base64 encoding sasBytes[0] >> 2, (sasBytes[0] & 0x3) << 4 | sasBytes[1] >> 4, (sasBytes[1] & 0xf) << 2 | sasBytes[2] >> 6, sasBytes[2] & 0x3f, sasBytes[3] >> 2, (sasBytes[3] & 0x3) << 4 | sasBytes[4] >> 4, (sasBytes[4] & 0xf) << 2 | sasBytes[5] >> 6]; return emojis.map(function (num) { return emojiMapping[num]; }); } var sasGenerators = { decimal: generateDecimalSas, emoji: generateEmojiSas }; function generateSas(sasBytes, methods) { var sas = {}; var _iterator = _createForOfIteratorHelper(methods), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var method = _step.value; if (method in sasGenerators) { sas[method] = sasGenerators[method](sasBytes); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return sas; } var macMethods = { "hkdf-hmac-sha256": "calculate_mac", "hmac-sha256": "calculate_mac_long_kdf" }; function calculateMAC(olmSAS, method) { return function () { var macFunction = olmSAS[macMethods[method]]; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var mac = macFunction.apply(olmSAS, args); _logger.logger.log("SAS calculateMAC:", method, args, mac); return mac; }; } var calculateKeyAgreement = { "curve25519-hkdf-sha256": function curve25519HkdfSha256(sas, olmSAS, bytes) { var ourInfo = "".concat(sas._baseApis.getUserId(), "|").concat(sas._baseApis.deviceId, "|") + "".concat(sas.ourSASPubKey, "|"); var theirInfo = "".concat(sas.userId, "|").concat(sas.deviceId, "|").concat(sas.theirSASPubKey, "|"); var sasInfo = "MATRIX_KEY_VERIFICATION_SAS|" + (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) + sas._channel.transactionId; return olmSAS.generate_bytes(sasInfo, bytes); }, "curve25519": function curve25519(sas, olmSAS, bytes) { var ourInfo = "".concat(sas._baseApis.getUserId()).concat(sas._baseApis.deviceId); var theirInfo = "".concat(sas.userId).concat(sas.deviceId); var sasInfo = "MATRIX_KEY_VERIFICATION_SAS" + (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) + sas._channel.transactionId; return olmSAS.generate_bytes(sasInfo, bytes); } }; /* lists of algorithms/methods that are supported. The key agreement, hashes, * and MAC lists should be sorted in order of preference (most preferred * first). */ var KEY_AGREEMENT_LIST = ["curve25519-hkdf-sha256", "curve25519"]; var HASHES_LIST = ["sha256"]; var MAC_LIST = ["hkdf-hmac-sha256", "hmac-sha256"]; var SAS_LIST = Object.keys(sasGenerators); var KEY_AGREEMENT_SET = new Set(KEY_AGREEMENT_LIST); var HASHES_SET = new Set(HASHES_LIST); var MAC_SET = new Set(MAC_LIST); var SAS_SET = new Set(SAS_LIST); function intersection(anArray, aSet) { return anArray instanceof Array ? anArray.filter(function (x) { return aSet.has(x); }) : []; } /** * @alias module:crypto/verification/SAS * @extends {module:crypto/verification/Base} */ var SAS = /*#__PURE__*/function (_Base) { (0, _inherits2["default"])(SAS, _Base); var _super = _createSuper(SAS); function SAS() { (0, _classCallCheck2["default"])(this, SAS); return _super.apply(this, arguments); } (0, _createClass2["default"])(SAS, [{ key: "_doVerification", value: function () { var _doVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var retry; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return global.Olm.init(); case 2: olmutil = olmutil || new global.Olm.Utility(); // make sure user's keys are downloaded _context.next = 5; return this._baseApis.downloadKeys([this.userId]); case 5: retry = false; case 6: _context.prev = 6; if (!this.initiatedByMe) { _context.next = 13; break; } _context.next = 10; return this._doSendVerification(); case 10: return _context.abrupt("return", _context.sent); case 13: _context.next = 15; return this._doRespondVerification(); case 15: return _context.abrupt("return", _context.sent); case 16: _context.next = 26; break; case 18: _context.prev = 18; _context.t0 = _context["catch"](6); if (!(_context.t0 instanceof _Base2.SwitchStartEventError)) { _context.next = 25; break; } // this changes what initiatedByMe returns this.startEvent = _context.t0.startEvent; retry = true; _context.next = 26; break; case 25: throw _context.t0; case 26: if (retry) { _context.next = 6; break; } case 27: case "end": return _context.stop(); } } }, _callee, this, [[6, 18]]); })); function _doVerification() { return _doVerification2.apply(this, arguments); } return _doVerification; }() }, { key: "canSwitchStartEvent", value: function canSwitchStartEvent(event) { if (event.getType() !== START_TYPE) { return false; } var content = event.getContent(); return content && content.method === SAS.NAME && this._waitingForAccept; } }, { key: "_sendStart", value: function () { var _sendStart2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var startContent; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: startContent = this._channel.completeContent(START_TYPE, { method: SAS.NAME, from_device: this._baseApis.deviceId, key_agreement_protocols: KEY_AGREEMENT_LIST, hashes: HASHES_LIST, message_authentication_codes: MAC_LIST, // FIXME: allow app to specify what SAS methods can be used short_authentication_string: SAS_LIST }); _context2.next = 3; return this._channel.sendCompleted(START_TYPE, startContent); case 3: return _context2.abrupt("return", startContent); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); function _sendStart() { return _sendStart2.apply(this, arguments); } return _sendStart; }() }, { key: "_doSendVerification", value: function () { var _doSendVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var _this = this; var startContent, e, content, sasMethods, keyAgreement, macMethod, hashCommitment, olmSAS, commitmentStr, sasBytes, verifySAS, _yield$Promise$all, _yield$Promise$all2; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: this._waitingForAccept = true; if (!this.startEvent) { _context4.next = 5; break; } startContent = this._channel.completedContentFromEvent(this.startEvent); _context4.next = 8; break; case 5: _context4.next = 7; return this._sendStart(); case 7: startContent = _context4.sent; case 8: if (this.initiatedByMe) { _context4.next = 10; break; } throw new _Base2.SwitchStartEventError(this.startEvent); case 10: _context4.prev = 10; _context4.next = 13; return this._waitForEvent("m.key.verification.accept"); case 13: e = _context4.sent; case 14: _context4.prev = 14; this._waitingForAccept = false; return _context4.finish(14); case 17: content = e.getContent(); sasMethods = intersection(content.short_authentication_string, SAS_SET); if (KEY_AGREEMENT_SET.has(content.key_agreement_protocol) && HASHES_SET.has(content.hash) && MAC_SET.has(content.message_authentication_code) && sasMethods.length) { _context4.next = 21; break; } throw (0, _Error.newUnknownMethodError)(); case 21: if (!(typeof content.commitment !== "string")) { _context4.next = 23; break; } throw (0, _Error.newInvalidMessageError)(); case 23: keyAgreement = content.key_agreement_protocol; macMethod = content.message_authentication_code; hashCommitment = content.commitment; olmSAS = new global.Olm.SAS(); _context4.prev = 27; this.ourSASPubKey = olmSAS.get_pubkey(); _context4.next = 31; return this._send("m.key.verification.key", { key: this.ourSASPubKey }); case 31: _context4.next = 33; return this._waitForEvent("m.key.verification.key"); case 33: e = _context4.sent; // FIXME: make sure event is properly formed content = e.getContent(); commitmentStr = content.key + _anotherJson["default"].stringify(startContent); // TODO: use selected hash function (when we support multiple) if (!(olmutil.sha256(commitmentStr) !== hashCommitment)) { _context4.next = 38; break; } throw newMismatchedCommitmentError(); case 38: this.theirSASPubKey = content.key; olmSAS.set_their_key(content.key); sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6); verifySAS = new Promise(function (resolve, reject) { _this.sasEvent = { sas: generateSas(sasBytes, sasMethods), confirm: function () { var _confirm = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.prev = 0; _context3.next = 3; return _this._sendMAC(olmSAS, macMethod); case 3: resolve(); _context3.next = 9; break; case 6: _context3.prev = 6; _context3.t0 = _context3["catch"](0); reject(_context3.t0); case 9: case "end": return _context3.stop(); } } }, _callee3, null, [[0, 6]]); })); function confirm() { return _confirm.apply(this, arguments); } return confirm; }(), cancel: function cancel() { return reject((0, _Error.newUserCancelledError)()); }, mismatch: function mismatch() { return reject(newMismatchedSASError()); } }; _this.emit("show_sas", _this.sasEvent); }); _context4.next = 44; return Promise.all([this._waitForEvent("m.key.verification.mac").then(function (e) { // we don't expect any more messages from the other // party, and they may send a m.key.verification.done // when they're done on their end _this._expectedEvent = "m.key.verification.done"; return e; }), verifySAS]); case 44: _yield$Promise$all = _context4.sent; _yield$Promise$all2 = (0, _slicedToArray2["default"])(_yield$Promise$all, 1); e = _yield$Promise$all2[0]; content = e.getContent(); _context4.next = 50; return this._checkMAC(olmSAS, content, macMethod); case 50: _context4.prev = 50; olmSAS.free(); return _context4.finish(50); case 53: case "end": return _context4.stop(); } } }, _callee4, this, [[10,, 14, 17], [27,, 50, 53]]); })); function _doSendVerification() { return _doSendVerification2.apply(this, arguments); } return _doSendVerification; }() }, { key: "_doRespondVerification", value: function () { var _doRespondVerification2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { var _this2 = this; var content, keyAgreement, hashMethod, macMethod, sasMethods, olmSAS, commitmentStr, e, sasBytes, verifySAS, _yield$Promise$all3, _yield$Promise$all4; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: // as m.related_to is not included in the encrypted content in e2e rooms, // we need to make sure it is added content = this._channel.completedContentFromEvent(this.startEvent); // Note: we intersect using our pre-made lists, rather than the sets, // so that the result will be in our order of preference. Then // fetching the first element from the array will give our preferred // method out of the ones offered by the other party. keyAgreement = intersection(KEY_AGREEMENT_LIST, new Set(content.key_agreement_protocols))[0]; hashMethod = intersection(HASHES_LIST, new Set(content.hashes))[0]; macMethod = intersection(MAC_LIST, new Set(content.message_authentication_codes))[0]; // FIXME: allow app to specify what SAS methods can be used sasMethods = intersection(content.short_authentication_string, SAS_SET); if (keyAgreement !== undefined && hashMethod !== undefined && macMethod !== undefined && sasMethods.length) { _context6.next = 7; break; } throw (0, _Error.newUnknownMethodError)(); case 7: olmSAS = new global.Olm.SAS(); _context6.prev = 8; commitmentStr = olmSAS.get_pubkey() + _anotherJson["default"].stringify(content); _context6.next = 12; return this._send("m.key.verification.accept", { key_agreement_protocol: keyAgreement, hash: hashMethod, message_authentication_code: macMethod, short_authentication_string: sasMethods, // TODO: use selected hash function (when we support multiple) commitment: olmutil.sha256(commitmentStr) }); case 12: _context6.next = 14; return this._waitForEvent("m.key.verification.key"); case 14: e = _context6.sent; // FIXME: make sure event is properly formed content = e.getContent(); this.theirSASPubKey = content.key; olmSAS.set_their_key(content.key); this.ourSASPubKey = olmSAS.get_pubkey(); _context6.next = 21; return this._send("m.key.verification.key", { key: this.ourSASPubKey }); case 21: sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6); verifySAS = new Promise(function (resolve, reject) { _this2.sasEvent = { sas: generateSas(sasBytes, sasMethods), confirm: function () { var _confirm2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.prev = 0; _context5.next = 3; return _this2._sendMAC(olmSAS, macMethod); case 3: resolve(); _context5.next = 9; break; case 6: _context5.prev = 6; _context5.t0 = _context5["catch"](0); reject(_context5.t0); case 9: case "end": return _context5.stop(); } } }, _callee5, null, [[0, 6]]); })); function confirm() { return _confirm2.apply(this, arguments); } return confirm; }(), cancel: function cancel() { return reject((0, _Error.newUserCancelledError)()); }, mismatch: function mismatch() { return reject(newMismatchedSASError()); } }; _this2.emit("show_sas", _this2.sasEvent); }); _context6.next = 25; return Promise.all([this._waitForEvent("m.key.verification.mac").then(function (e) { // we don't expect any more messages from the other // party, and they may send a m.key.verification.done // when they're done on their end _this2._expectedEvent = "m.key.verification.done"; return e; }), verifySAS]); case 25: _yield$Promise$all3 = _context6.sent; _yield$Promise$all4 = (0, _slicedToArray2["default"])(_yield$Promise$all3, 1); e = _yield$Promise$all4[0]; content = e.getContent(); _context6.next = 31; return this._checkMAC(olmSAS, content, macMethod); case 31: _context6.prev = 31; olmSAS.free(); return _context6.finish(31); case 34: case "end": return _context6.stop(); } } }, _callee6, this, [[8,, 31, 34]]); })); function _doRespondVerification() { return _doRespondVerification2.apply(this, arguments); } return _doRespondVerification; }() }, { key: "_sendMAC", value: function _sendMAC(olmSAS, method) { var mac = {}; var keyList = []; var baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + this._baseApis.getUserId() + this._baseApis.deviceId + this.userId + this.deviceId + this._channel.transactionId; var deviceKeyId = "ed25519:".concat(this._baseApis.deviceId); mac[deviceKeyId] = calculateMAC(olmSAS, method)(this._baseApis.getDeviceEd25519Key(), baseInfo + deviceKeyId); keyList.push(deviceKeyId); var crossSigningId = this._baseApis.getCrossSigningId(); if (crossSigningId) { var crossSigningKeyId = "ed25519:".concat(crossSigningId); mac[crossSigningKeyId] = calculateMAC(olmSAS, method)(crossSigningId, baseInfo + crossSigningKeyId); keyList.push(crossSigningKeyId); } var keys = calculateMAC(olmSAS, method)(keyList.sort().join(","), baseInfo + "KEY_IDS"); return this._send("m.key.verification.mac", { mac: mac, keys: keys }); } }, { key: "_checkMAC", value: function () { var _checkMAC2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(olmSAS, content, method) { var baseInfo; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + this.userId + this.deviceId + this._baseApis.getUserId() + this._baseApis.deviceId + this._channel.transactionId; if (!(content.keys !== calculateMAC(olmSAS, method)(Object.keys(content.mac).sort().join(","), baseInfo + "KEY_IDS"))) { _context7.next = 3; break; } throw (0, _Error.newKeyMismatchError)(); case 3: _context7.next = 5; return this._verifyKeys(this.userId, content.mac, function (keyId, device, keyInfo) { if (keyInfo !== calculateMAC(olmSAS, method)(device.keys[keyId], baseInfo + keyId)) { throw (0, _Error.newKeyMismatchError)(); } }); case 5: case "end": return _context7.stop(); } } }, _callee7, this); })); function _checkMAC(_x, _x2, _x3) { return _checkMAC2.apply(this, arguments); } return _checkMAC; }() }, { key: "events", get: function get() { return EVENTS; } }], [{ key: "NAME", get: function get() { return "m.sas.v1"; } }]); return SAS; }(_Base2.VerificationBase); exports.SAS = SAS; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../../logger":95,"./Base":81,"./Error":82,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"another-json":28}],86:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.InRoomRequests = exports.InRoomChannel = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _VerificationRequest = require("./VerificationRequest"); var _logger = require("../../../logger"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var MESSAGE_TYPE = "m.room.message"; var M_REFERENCE = "m.reference"; var M_RELATES_TO = "m.relates_to"; /** * A key verification channel that sends verification events in the timeline of a room. * Uses the event id of the initial m.key.verification.request event as a transaction id. */ var InRoomChannel = /*#__PURE__*/function () { /** * @param {MatrixClient} client the matrix client, to send messages with and get current user & device from. * @param {string} roomId id of the room where verification events should be posted in, should be a DM with the given user. * @param {string} userId id of user that the verification request is directed at, should be present in the room. */ function InRoomChannel(client, roomId) { var userId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; (0, _classCallCheck2["default"])(this, InRoomChannel); this._client = client; this._roomId = roomId; this.userId = userId; this._requestEventId = null; } (0, _createClass2["default"])(InRoomChannel, [{ key: "getTimestamp", /** * @param {MatrixEvent} event the event to get the timestamp of * @return {number} the timestamp when the event was sent */ value: function getTimestamp(event) { return event.getTs(); } /** * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel * @param {string} type the event type to check * @returns {bool} boolean flag */ }, { key: "handleEvent", /** * Changes the state of the channel, request, and verifier in response to a key verification event. * @param {MatrixEvent} event to handle * @param {VerificationRequest} request the request to forward handling to * @param {bool} isLiveEvent whether this is an even received through sync or not * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent. */ value: function () { var _handleEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(event, request, isLiveEvent) { var type, userId, ownUserId, sender, isRemoteEcho, isSentByUs; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!request.hasEventId(event.getId())) { _context.next = 2; break; } return _context.abrupt("return"); case 2: type = InRoomChannel.getEventType(event); // do validations that need state (roomId, userId), // ignore if invalid if (!(event.getRoomId() !== this._roomId)) { _context.next = 5; break; } return _context.abrupt("return"); case 5: // set userId if not set already if (this.userId === null) { userId = InRoomChannel.getOtherPartyUserId(event, this._client); if (userId) { this.userId = userId; } } // ignore events not sent by us or the other party ownUserId = this._client.getUserId(); sender = event.getSender(); if (!(this.userId !== null)) { _context.next = 12; break; } if (!(sender !== ownUserId && sender !== this.userId)) { _context.next = 12; break; } _logger.logger.log("InRoomChannel: ignoring verification event from " + "non-participating sender ".concat(sender)); return _context.abrupt("return"); case 12: if (this._requestEventId === null) { this._requestEventId = InRoomChannel.getTransactionId(event); } isRemoteEcho = !!event.getUnsigned().transaction_id; isSentByUs = event.getSender() === this._client.getUserId(); _context.next = 17; return request.handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs); case 17: return _context.abrupt("return", _context.sent); case 18: case "end": return _context.stop(); } } }, _callee, this); })); function handleEvent(_x, _x2, _x3) { return _handleEvent.apply(this, arguments); } return handleEvent; }() /** * Adds the transaction id (relation) back to a received event * so it has the same format as returned by `completeContent` before sending. * The relation can not appear on the event content because of encryption, * relations are excluded from encryption. * @param {MatrixEvent} event the received event * @returns {Object} the content object with the relation added again */ }, { key: "completedContentFromEvent", value: function completedContentFromEvent(event) { // ensure m.related_to is included in e2ee rooms // as the field is excluded from encryption var content = Object.assign({}, event.getContent()); content[M_RELATES_TO] = event.getRelation(); return content; } /** * Add all the fields to content needed for sending it over this channel. * This is public so verification methods (SAS uses this) can get the exact * content that will be sent independent of the used channel, * as they need to calculate the hash of it. * @param {string} type the event type * @param {object} content the (incomplete) content * @returns {object} the complete content, as it will be sent. */ }, { key: "completeContent", value: function completeContent(type, content) { content = Object.assign({}, content); if (type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.READY_TYPE || type === _VerificationRequest.START_TYPE) { content.from_device = this._client.getDeviceId(); } if (type === _VerificationRequest.REQUEST_TYPE) { // type is mapped to m.room.message in the send method content = { body: this._client.getUserId() + " is requesting to verify " + "your key, but your client does not support in-chat key " + "verification. You will need to use legacy key " + "verification to verify keys.", msgtype: _VerificationRequest.REQUEST_TYPE, to: this.userId, from_device: content.from_device, methods: content.methods }; } else { content[M_RELATES_TO] = { rel_type: M_REFERENCE, event_id: this.transactionId }; } return content; } /** * Send an event over the channel with the content not having gone through `completeContent`. * @param {string} type the event type * @param {object} uncompletedContent the (incomplete) content * @returns {Promise} the promise of the request */ }, { key: "send", value: function send(type, uncompletedContent) { var content = this.completeContent(type, uncompletedContent); return this.sendCompleted(type, content); } /** * Send an event over the channel with the content having gone through `completeContent` already. * @param {string} type the event type * @param {object} content * @returns {Promise} the promise of the request */ }, { key: "sendCompleted", value: function () { var _sendCompleted = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(type, content) { var sendType, response; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: sendType = type; if (type === _VerificationRequest.REQUEST_TYPE) { sendType = MESSAGE_TYPE; } _context2.next = 4; return this._client.sendEvent(this._roomId, sendType, content); case 4: response = _context2.sent; if (type === _VerificationRequest.REQUEST_TYPE) { this._requestEventId = response.event_id; } case 6: case "end": return _context2.stop(); } } }, _callee2, this); })); function sendCompleted(_x4, _x5) { return _sendCompleted.apply(this, arguments); } return sendCompleted; }() }, { key: "receiveStartFromOtherDevices", get: function get() { return true; } }, { key: "roomId", get: function get() { return this._roomId; } /** The transaction id generated/used by this verification channel */ }, { key: "transactionId", get: function get() { return this._requestEventId; } }], [{ key: "getOtherPartyUserId", value: function getOtherPartyUserId(event, client) { var type = InRoomChannel.getEventType(event); if (type !== _VerificationRequest.REQUEST_TYPE) { return; } var ownUserId = client.getUserId(); var sender = event.getSender(); var content = event.getContent(); var receiver = content.to; if (sender === ownUserId) { return receiver; } else if (receiver === ownUserId) { return sender; } } }, { key: "canCreateRequest", value: function canCreateRequest(type) { return type === _VerificationRequest.REQUEST_TYPE; } /** * Extract the transaction id used by a given key verification event, if any * @param {MatrixEvent} event the event * @returns {string} the transaction id */ }, { key: "getTransactionId", value: function getTransactionId(event) { if (InRoomChannel.getEventType(event) === _VerificationRequest.REQUEST_TYPE) { return event.getId(); } else { var relation = event.getRelation(); if (relation && relation.rel_type === M_REFERENCE) { return relation.event_id; } } } /** * Checks whether this event is a well-formed key verification event. * This only does checks that don't rely on the current state of a potentially already channel * so we can prevent channels being created by invalid events. * `handleEvent` can do more checks and choose to ignore invalid events. * @param {MatrixEvent} event the event to validate * @param {MatrixClient} client the client to get the current user and device id from * @returns {bool} whether the event is valid and should be passed to handleEvent */ }, { key: "validateEvent", value: function validateEvent(event, client) { var txnId = InRoomChannel.getTransactionId(event); if (typeof txnId !== "string" || txnId.length === 0) { return false; } var type = InRoomChannel.getEventType(event); var content = event.getContent(); // from here on we're fairly sure that this is supposed to be // part of a verification request, so be noisy when rejecting something if (type === _VerificationRequest.REQUEST_TYPE) { if (!content || typeof content.to !== "string" || !content.to.length) { _logger.logger.log("InRoomChannel: validateEvent: " + "no valid to " + (content && content.to)); return false; } // ignore requests that are not direct to or sent by the syncing user if (!InRoomChannel.getOtherPartyUserId(event, client)) { _logger.logger.log("InRoomChannel: validateEvent: " + "not directed to or sent by me: ".concat(event.getSender()) + ", ".concat(content && content.to)); return false; } } return _VerificationRequest.VerificationRequest.validateEvent(type, event, client); } /** * As m.key.verification.request events are as m.room.message events with the InRoomChannel * to have a fallback message in non-supporting clients, we map the real event type * to the symbolic one to keep things in unison with ToDeviceChannel * @param {MatrixEvent} event the event to get the type of * @returns {string} the "symbolic" event type */ }, { key: "getEventType", value: function getEventType(event) { var type = event.getType(); if (type === MESSAGE_TYPE) { var content = event.getContent(); if (content) { var msgtype = content.msgtype; if (msgtype === _VerificationRequest.REQUEST_TYPE) { return _VerificationRequest.REQUEST_TYPE; } } } if (type && type !== _VerificationRequest.REQUEST_TYPE) { return type; } else { return ""; } } }]); return InRoomChannel; }(); exports.InRoomChannel = InRoomChannel; var InRoomRequests = /*#__PURE__*/function () { function InRoomRequests() { (0, _classCallCheck2["default"])(this, InRoomRequests); this._requestsByRoomId = new Map(); } (0, _createClass2["default"])(InRoomRequests, [{ key: "getRequest", value: function getRequest(event) { var roomId = event.getRoomId(); var txnId = InRoomChannel.getTransactionId(event); return this._getRequestByTxnId(roomId, txnId); } }, { key: "getRequestByChannel", value: function getRequestByChannel(channel) { return this._getRequestByTxnId(channel.roomId, channel.transactionId); } }, { key: "_getRequestByTxnId", value: function _getRequestByTxnId(roomId, txnId) { var requestsByTxnId = this._requestsByRoomId.get(roomId); if (requestsByTxnId) { return requestsByTxnId.get(txnId); } } }, { key: "setRequest", value: function setRequest(event, request) { this._setRequest(event.getRoomId(), InRoomChannel.getTransactionId(event), request); } }, { key: "setRequestByChannel", value: function setRequestByChannel(channel, request) { this._setRequest(channel.roomId, channel.transactionId, request); } }, { key: "_setRequest", value: function _setRequest(roomId, txnId, request) { var requestsByTxnId = this._requestsByRoomId.get(roomId); if (!requestsByTxnId) { requestsByTxnId = new Map(); this._requestsByRoomId.set(roomId, requestsByTxnId); } requestsByTxnId.set(txnId, request); } }, { key: "removeRequest", value: function removeRequest(event) { var roomId = event.getRoomId(); var requestsByTxnId = this._requestsByRoomId.get(roomId); if (requestsByTxnId) { requestsByTxnId["delete"](InRoomChannel.getTransactionId(event)); if (requestsByTxnId.size === 0) { this._requestsByRoomId["delete"](roomId); } } } }, { key: "findRequestInProgress", value: function findRequestInProgress(roomId) { var requestsByTxnId = this._requestsByRoomId.get(roomId); if (requestsByTxnId) { var _iterator = _createForOfIteratorHelper(requestsByTxnId.values()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var request = _step.value; if (request.pending) { return request; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } } }]); return InRoomRequests; }(); exports.InRoomRequests = InRoomRequests; },{"../../../logger":95,"./VerificationRequest":88,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/regenerator":27}],87:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.ToDeviceRequests = exports.ToDeviceChannel = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _randomstring = require("../../../randomstring"); var _logger = require("../../../logger"); var _VerificationRequest = require("./VerificationRequest"); var _Error = require("../Error"); var _event = require("../../../models/event"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * A key verification channel that sends verification events over to_device messages. * Generates its own transaction ids. */ var ToDeviceChannel = /*#__PURE__*/function () { // userId and devices of user we're about to verify function ToDeviceChannel(client, userId, devices) { var transactionId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var deviceId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; (0, _classCallCheck2["default"])(this, ToDeviceChannel); this._client = client; this.userId = userId; this._devices = devices; this.transactionId = transactionId; this._deviceId = deviceId; } (0, _createClass2["default"])(ToDeviceChannel, [{ key: "isToDevices", value: function isToDevices(devices) { var _this = this; if (devices.length === this._devices.length) { var _iterator = _createForOfIteratorHelper(devices), _step; try { var _loop = function _loop() { var device = _step.value; var d = _this._devices.find(function (d) { return d.deviceId === device.deviceId; }); if (!d) { return { v: false }; } }; for (_iterator.s(); !(_step = _iterator.n()).done;) { var _ret = _loop(); if ((0, _typeof2["default"])(_ret) === "object") return _ret.v; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return true; } else { return false; } } }, { key: "getTimestamp", /** * @param {MatrixEvent} event the event to get the timestamp of * @return {number} the timestamp when the event was sent */ value: function getTimestamp(event) { var content = event.getContent(); return content && content.timestamp; } /** * Changes the state of the channel, request, and verifier in response to a key verification event. * @param {MatrixEvent} event to handle * @param {VerificationRequest} request the request to forward handling to * @param {bool} isLiveEvent whether this is an even received through sync or not * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent. */ }, { key: "handleEvent", value: function () { var _handleEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(event, request, isLiveEvent) { var _this2 = this; var type, content, deviceId, cancelContent, wasStarted, isStarted, isAcceptingEvent, nonChosenDevices, message; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: type = event.getType(); content = event.getContent(); if (!(type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.READY_TYPE || type === _VerificationRequest.START_TYPE)) { _context.next = 9; break; } if (!this.transactionId) { this.transactionId = content.transaction_id; } deviceId = content.from_device; // adopt deviceId if not set before and valid if (!this._deviceId && this._devices.includes(deviceId)) { this._deviceId = deviceId; } // if no device id or different from addopted one, cancel with sender if (!(!this._deviceId || this._deviceId !== deviceId)) { _context.next = 9; break; } // also check that message came from the device we sent the request to earlier on // and do send a cancel message to that device // (but don't cancel the request for the device we should be talking to) cancelContent = this.completeContent((0, _Error.errorFromEvent)((0, _Error.newUnexpectedMessageError)())); return _context.abrupt("return", this._sendToDevices(_VerificationRequest.CANCEL_TYPE, cancelContent, [deviceId])); case 9: wasStarted = request.phase === _VerificationRequest.PHASE_STARTED || request.phase === _VerificationRequest.PHASE_READY; _context.next = 12; return request.handleEvent(event.getType(), event, isLiveEvent, false, false); case 12: isStarted = request.phase === _VerificationRequest.PHASE_STARTED || request.phase === _VerificationRequest.PHASE_READY; isAcceptingEvent = type === _VerificationRequest.START_TYPE || type === _VerificationRequest.READY_TYPE; // the request has picked a ready or start event, tell the other devices about it if (!(isAcceptingEvent && !wasStarted && isStarted && this._deviceId)) { _context.next = 20; break; } nonChosenDevices = this._devices.filter(function (d) { return d !== _this2._deviceId; }); if (!nonChosenDevices.length) { _context.next = 20; break; } message = this.completeContent({ code: "m.accepted", reason: "Verification request accepted by another device" }); _context.next = 20; return this._sendToDevices(_VerificationRequest.CANCEL_TYPE, message, nonChosenDevices); case 20: case "end": return _context.stop(); } } }, _callee, this); })); function handleEvent(_x, _x2, _x3) { return _handleEvent.apply(this, arguments); } return handleEvent; }() /** * See {InRoomChannel.completedContentFromEvent} why this is needed. * @param {MatrixEvent} event the received event * @returns {Object} the content object */ }, { key: "completedContentFromEvent", value: function completedContentFromEvent(event) { return event.getContent(); } /** * Add all the fields to content needed for sending it over this channel. * This is public so verification methods (SAS uses this) can get the exact * content that will be sent independent of the used channel, * as they need to calculate the hash of it. * @param {string} type the event type * @param {object} content the (incomplete) content * @returns {object} the complete content, as it will be sent. */ }, { key: "completeContent", value: function completeContent(type, content) { // make a copy content = Object.assign({}, content); if (this.transactionId) { content.transaction_id = this.transactionId; } if (type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.READY_TYPE || type === _VerificationRequest.START_TYPE) { content.from_device = this._client.getDeviceId(); } if (type === _VerificationRequest.REQUEST_TYPE) { content.timestamp = Date.now(); } return content; } /** * Send an event over the channel with the content not having gone through `completeContent`. * @param {string} type the event type * @param {object} uncompletedContent the (incomplete) content * @returns {Promise} the promise of the request */ }, { key: "send", value: function send(type) { var uncompletedContent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // create transaction id when sending request if ((type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.START_TYPE) && !this.transactionId) { this.transactionId = ToDeviceChannel.makeTransactionId(); } var content = this.completeContent(type, uncompletedContent); return this.sendCompleted(type, content); } /** * Send an event over the channel with the content having gone through `completeContent` already. * @param {string} type the event type * @param {object} content * @returns {Promise} the promise of the request */ }, { key: "sendCompleted", value: function () { var _sendCompleted = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(type, content) { var result, remoteEchoEvent; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(type === _VerificationRequest.REQUEST_TYPE)) { _context2.next = 6; break; } _context2.next = 3; return this._sendToDevices(type, content, this._devices); case 3: result = _context2.sent; _context2.next = 9; break; case 6: _context2.next = 8; return this._sendToDevices(type, content, [this._deviceId]); case 8: result = _context2.sent; case 9: // the VerificationRequest state machine requires remote echos of the event // the client sends itself, so we fake this for to_device messages remoteEchoEvent = new _event.MatrixEvent({ sender: this._client.getUserId(), content: content, type: type }); _context2.next = 12; return this._request.handleEvent(type, remoteEchoEvent, /*isLiveEvent=*/ true, /*isRemoteEcho=*/ true, /*isSentByUs=*/ true); case 12: return _context2.abrupt("return", result); case 13: case "end": return _context2.stop(); } } }, _callee2, this); })); function sendCompleted(_x4, _x5) { return _sendCompleted.apply(this, arguments); } return sendCompleted; }() }, { key: "_sendToDevices", value: function _sendToDevices(type, content, devices) { if (devices.length) { var msgMap = {}; var _iterator2 = _createForOfIteratorHelper(devices), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var deviceId = _step2.value; msgMap[deviceId] = content; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return this._client.sendToDevice(type, (0, _defineProperty2["default"])({}, this.userId, msgMap)); } else { return Promise.resolve(); } } /** * Allow Crypto module to create and know the transaction id before the .start event gets sent. * @returns {string} the transaction id */ }, { key: "deviceId", get: function get() { return this._deviceId; } }], [{ key: "getEventType", value: function getEventType(event) { return event.getType(); } /** * Extract the transaction id used by a given key verification event, if any * @param {MatrixEvent} event the event * @returns {string} the transaction id */ }, { key: "getTransactionId", value: function getTransactionId(event) { var content = event.getContent(); return content && content.transaction_id; } /** * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel * @param {string} type the event type to check * @returns {bool} boolean flag */ }, { key: "canCreateRequest", value: function canCreateRequest(type) { return type === _VerificationRequest.REQUEST_TYPE || type === _VerificationRequest.START_TYPE; } /** * Checks whether this event is a well-formed key verification event. * This only does checks that don't rely on the current state of a potentially already channel * so we can prevent channels being created by invalid events. * `handleEvent` can do more checks and choose to ignore invalid events. * @param {MatrixEvent} event the event to validate * @param {MatrixClient} client the client to get the current user and device id from * @returns {bool} whether the event is valid and should be passed to handleEvent */ }, { key: "validateEvent", value: function validateEvent(event, client) { if (event.isCancelled()) { _logger.logger.warn("Ignoring flagged verification request from " + event.getSender()); return false; } var content = event.getContent(); if (!content) { _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"); return false; } if (!content.transaction_id) { _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"); return false; } var type = event.getType(); if (type === _VerificationRequest.REQUEST_TYPE) { if (!Number.isFinite(content.timestamp)) { _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"); return false; } if (event.getSender() === client.getUserId() && content.from_device == client.getDeviceId()) { // ignore requests from ourselves, because it doesn't make sense for a // device to verify itself _logger.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"); return false; } } return _VerificationRequest.VerificationRequest.validateEvent(type, event, client); } }, { key: "makeTransactionId", value: function makeTransactionId() { return (0, _randomstring.randomString)(32); } }]); return ToDeviceChannel; }(); exports.ToDeviceChannel = ToDeviceChannel; var ToDeviceRequests = /*#__PURE__*/function () { function ToDeviceRequests() { (0, _classCallCheck2["default"])(this, ToDeviceRequests); this._requestsByUserId = new Map(); } (0, _createClass2["default"])(ToDeviceRequests, [{ key: "getRequest", value: function getRequest(event) { return this.getRequestBySenderAndTxnId(event.getSender(), ToDeviceChannel.getTransactionId(event)); } }, { key: "getRequestByChannel", value: function getRequestByChannel(channel) { return this.getRequestBySenderAndTxnId(channel.userId, channel.transactionId); } }, { key: "getRequestBySenderAndTxnId", value: function getRequestBySenderAndTxnId(sender, txnId) { var requestsByTxnId = this._requestsByUserId.get(sender); if (requestsByTxnId) { return requestsByTxnId.get(txnId); } } }, { key: "setRequest", value: function setRequest(event, request) { this.setRequestBySenderAndTxnId(event.getSender(), ToDeviceChannel.getTransactionId(event), request); } }, { key: "setRequestByChannel", value: function setRequestByChannel(channel, request) { this.setRequestBySenderAndTxnId(channel.userId, channel.transactionId, request); } }, { key: "setRequestBySenderAndTxnId", value: function setRequestBySenderAndTxnId(sender, txnId, request) { var requestsByTxnId = this._requestsByUserId.get(sender); if (!requestsByTxnId) { requestsByTxnId = new Map(); this._requestsByUserId.set(sender, requestsByTxnId); } requestsByTxnId.set(txnId, request); } }, { key: "removeRequest", value: function removeRequest(event) { var userId = event.getSender(); var requestsByTxnId = this._requestsByUserId.get(userId); if (requestsByTxnId) { requestsByTxnId["delete"](ToDeviceChannel.getTransactionId(event)); if (requestsByTxnId.size === 0) { this._requestsByUserId["delete"](userId); } } } }, { key: "findRequestInProgress", value: function findRequestInProgress(userId, devices) { var requestsByTxnId = this._requestsByUserId.get(userId); if (requestsByTxnId) { var _iterator3 = _createForOfIteratorHelper(requestsByTxnId.values()), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var request = _step3.value; if (request.pending && request.channel.isToDevices(devices)) { return request; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } } }, { key: "getRequestsInProgress", value: function getRequestsInProgress(userId) { var requestsByTxnId = this._requestsByUserId.get(userId); if (requestsByTxnId) { return Array.from(requestsByTxnId.values()).filter(function (r) { return r.pending; }); } return []; } }]); return ToDeviceRequests; }(); exports.ToDeviceRequests = ToDeviceRequests; },{"../../../logger":95,"../../../models/event":100,"../../../randomstring":110,"../Error":82,"./VerificationRequest":88,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/typeof":24,"@babel/runtime/regenerator":27}],88:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.VerificationRequest = exports.PHASE_DONE = exports.PHASE_CANCELLED = exports.PHASE_STARTED = exports.PHASE_READY = exports.PHASE_REQUESTED = exports.PHASE_UNSENT = exports.READY_TYPE = exports.DONE_TYPE = exports.CANCEL_TYPE = exports.START_TYPE = exports.REQUEST_TYPE = exports.EVENT_PREFIX = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _logger = require("../../../logger"); var _events = require("events"); var _Error = require("../Error"); var _QRCode = require("../QRCode"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } // How long after the event's timestamp that the request times out var TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes // How long after we receive the event that the request times out var TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes // to avoid almost expired verification notifications // from showing a notification and almost immediately // disappearing, also ignore verification requests that // are this amount of time away from expiring. var VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds var EVENT_PREFIX = "m.key.verification."; exports.EVENT_PREFIX = EVENT_PREFIX; var REQUEST_TYPE = EVENT_PREFIX + "request"; exports.REQUEST_TYPE = REQUEST_TYPE; var START_TYPE = EVENT_PREFIX + "start"; exports.START_TYPE = START_TYPE; var CANCEL_TYPE = EVENT_PREFIX + "cancel"; exports.CANCEL_TYPE = CANCEL_TYPE; var DONE_TYPE = EVENT_PREFIX + "done"; exports.DONE_TYPE = DONE_TYPE; var READY_TYPE = EVENT_PREFIX + "ready"; exports.READY_TYPE = READY_TYPE; var PHASE_UNSENT = 1; exports.PHASE_UNSENT = PHASE_UNSENT; var PHASE_REQUESTED = 2; exports.PHASE_REQUESTED = PHASE_REQUESTED; var PHASE_READY = 3; exports.PHASE_READY = PHASE_READY; var PHASE_STARTED = 4; exports.PHASE_STARTED = PHASE_STARTED; var PHASE_CANCELLED = 5; exports.PHASE_CANCELLED = PHASE_CANCELLED; var PHASE_DONE = 6; /** * State machine for verification requests. * Things that differ based on what channel is used to * send and receive verification events are put in `InRoomChannel` or `ToDeviceChannel`. * @event "change" whenever the state of the request object has changed. */ exports.PHASE_DONE = PHASE_DONE; var VerificationRequest = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(VerificationRequest, _EventEmitter); var _super = _createSuper(VerificationRequest); function VerificationRequest(channel, verificationMethods, client) { var _this; (0, _classCallCheck2["default"])(this, VerificationRequest); _this = _super.call(this); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_cancelOnTimeout", function () { try { if (_this.initiatedByMe) { _this.cancel({ reason: "Other party didn't accept in time", code: "m.timeout" }); } else { _this.cancel({ reason: "User didn't accept in time", code: "m.timeout" }); } } catch (err) { _logger.logger.error("Error while cancelling verification request", err); } }); _this.channel = channel; _this.channel._request = (0, _assertThisInitialized2["default"])(_this); _this._verificationMethods = verificationMethods; _this._client = client; _this._commonMethods = []; _this._setPhase(PHASE_UNSENT, false); _this._eventsByUs = new Map(); _this._eventsByThem = new Map(); _this._observeOnly = false; _this._timeoutTimer = null; _this._accepting = false; _this._declining = false; _this._verifierHasFinished = false; _this._cancelled = false; _this._chosenMethod = null; // we keep a copy of the QR Code data (including other user master key) around // for QR reciprocate verification, to protect against // cross-signing identity reset between the .ready and .start event // and signing the wrong key after .start _this._qrCodeData = null; // The timestamp when we received the request event from the other side _this._requestReceivedAt = null; return _this; } /** * Stateless validation logic not specific to the channel. * Invoked by the same static method in either channel. * @param {string} type the "symbolic" event type, as returned by the `getEventType` function on the channel. * @param {MatrixEvent} event the event to validate. Don't call getType() on it but use the `type` parameter instead. * @param {MatrixClient} client the client to get the current user and device id from * @returns {bool} whether the event is valid and should be passed to handleEvent */ (0, _createClass2["default"])(VerificationRequest, [{ key: "calculateEventTimeout", value: function calculateEventTimeout(event) { var effectiveExpiresAt = this.channel.getTimestamp(event) + TIMEOUT_FROM_EVENT_TS; if (this._requestReceivedAt && !this.initiatedByMe && this.phase <= PHASE_REQUESTED) { var expiresAtByReceipt = this._requestReceivedAt + TIMEOUT_FROM_EVENT_RECEIPT; effectiveExpiresAt = Math.min(effectiveExpiresAt, expiresAtByReceipt); } return Math.max(0, effectiveExpiresAt - Date.now()); } /** The current remaining amount of ms before the request should be automatically cancelled */ }, { key: "otherPartySupportsMethod", /** Checks whether the other party supports a given verification method. * This is useful when setting up the QR code UI, as it is somewhat asymmetrical: * if the other party supports SCAN_QR, we should show a QR code in the UI, and vice versa. * For methods that need to be supported by both ends, use the `methods` property. * @param {string} method the method to check * @param {boolean} force to check even if the phase is not ready or started yet, internal usage * @return {bool} whether or not the other party said the supported the method */ value: function otherPartySupportsMethod(method) { var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!force && !this.ready && !this.started) { return false; } var theirMethodEvent = this._eventsByThem.get(REQUEST_TYPE) || this._eventsByThem.get(READY_TYPE); if (!theirMethodEvent) { // if we started straight away with .start event, // we are assuming that the other side will support the // chosen method, so return true for that. if (this.started && this.initiatedByMe) { var myStartEvent = this._eventsByUs.get(START_TYPE); var _content = myStartEvent && myStartEvent.getContent(); var myStartMethod = _content && _content.method; return method == myStartMethod; } return false; } var content = theirMethodEvent.getContent(); if (!content) { return false; } var methods = content.methods; if (!Array.isArray(methods)) { return false; } return methods.includes(method); } /** Whether this request was initiated by the syncing user. * For InRoomChannel, this is who sent the .request event. * For ToDeviceChannel, this is who sent the .start event */ }, { key: "beginKeyVerification", /* Start the key verification, creating a verifier and sending a .start event. * If no previous events have been sent, pass in `targetDevice` to set who to direct this request to. * @param {string} method the name of the verification method to use. * @param {string?} targetDevice.userId the id of the user to direct this request to * @param {string?} targetDevice.deviceId the id of the device to direct this request to * @returns {VerifierBase} the verifier of the given method */ value: function beginKeyVerification(method) { var targetDevice = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; // need to allow also when unsent in case of to_device if (!this.observeOnly && !this._verifier) { var validStartPhase = this.phase === PHASE_REQUESTED || this.phase === PHASE_READY || this.phase === PHASE_UNSENT && this.channel.constructor.canCreateRequest(START_TYPE); if (validStartPhase) { // when called on a request that was initiated with .request event // check the method is supported by both sides if (this._commonMethods.length && !this._commonMethods.includes(method)) { throw (0, _Error.newUnknownMethodError)(); } this._verifier = this._createVerifier(method, null, targetDevice); if (!this._verifier) { throw (0, _Error.newUnknownMethodError)(); } this._chosenMethod = method; } } return this._verifier; } /** * sends the initial .request event. * @returns {Promise} resolves when the event has been sent. */ }, { key: "sendRequest", value: function () { var _sendRequest = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var methods; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(!this.observeOnly && this._phase === PHASE_UNSENT)) { _context.next = 4; break; } methods = (0, _toConsumableArray2["default"])(this._verificationMethods.keys()); _context.next = 4; return this.channel.send(REQUEST_TYPE, { methods: methods }); case 4: case "end": return _context.stop(); } } }, _callee, this); })); function sendRequest() { return _sendRequest.apply(this, arguments); } return sendRequest; }() /** * Cancels the request, sending a cancellation to the other party * @param {string?} error.reason the error reason to send the cancellation with * @param {string?} error.code the error code to send the cancellation with * @returns {Promise} resolves when the event has been sent. */ }, { key: "cancel", value: function () { var _cancel = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var _ref, _ref$reason, reason, _ref$code, code, _args2 = arguments; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref$reason = _ref.reason, reason = _ref$reason === void 0 ? "User declined" : _ref$reason, _ref$code = _ref.code, code = _ref$code === void 0 ? "m.user" : _ref$code; if (!(!this.observeOnly && this._phase !== PHASE_CANCELLED)) { _context2.next = 11; break; } this._declining = true; this.emit("change"); if (!this._verifier) { _context2.next = 8; break; } return _context2.abrupt("return", this._verifier.cancel((0, _Error.errorFactory)(code, reason)())); case 8: this._cancellingUserId = this._client.getUserId(); _context2.next = 11; return this.channel.send(CANCEL_TYPE, { code: code, reason: reason }); case 11: case "end": return _context2.stop(); } } }, _callee2, this); })); function cancel() { return _cancel.apply(this, arguments); } return cancel; }() /** * Accepts the request, sending a .ready event to the other party * @returns {Promise} resolves when the event has been sent. */ }, { key: "accept", value: function () { var _accept = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { var methods; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(!this.observeOnly && this.phase === PHASE_REQUESTED && !this.initiatedByMe)) { _context3.next = 6; break; } methods = (0, _toConsumableArray2["default"])(this._verificationMethods.keys()); this._accepting = true; this.emit("change"); _context3.next = 6; return this.channel.send(READY_TYPE, { methods: methods }); case 6: case "end": return _context3.stop(); } } }, _callee3, this); })); function accept() { return _accept.apply(this, arguments); } return accept; }() /** * Can be used to listen for state changes until the callback returns true. * @param {Function} fn callback to evaluate whether the request is in the desired state. * Takes the request as an argument. * @returns {Promise} that resolves once the callback returns true * @throws {Error} when the request is cancelled */ }, { key: "waitFor", value: function waitFor(fn) { var _this2 = this; return new Promise(function (resolve, reject) { var check = function check() { var handled = false; if (fn(_this2)) { resolve(_this2); handled = true; } else if (_this2.cancelled) { reject(new Error("cancelled")); handled = true; } if (handled) { _this2.off("change", check); } return handled; }; if (!check()) { _this2.on("change", check); } }); } }, { key: "_setPhase", value: function _setPhase(phase) { var notify = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; this._phase = phase; if (notify) { this.emit("change"); } } }, { key: "_getEventByEither", value: function _getEventByEither(type) { return this._eventsByThem.get(type) || this._eventsByUs.get(type); } }, { key: "_getEventBy", value: function _getEventBy(type, byThem) { if (byThem) { return this._eventsByThem.get(type); } else { return this._eventsByUs.get(type); } } }, { key: "_calculatePhaseTransitions", value: function _calculatePhaseTransitions() { var transitions = [{ phase: PHASE_UNSENT }]; var phase = function phase() { return transitions[transitions.length - 1].phase; }; // always pass by .request first to be sure channel.userId has been set var hasRequestByThem = this._eventsByThem.has(REQUEST_TYPE); var requestEvent = this._getEventBy(REQUEST_TYPE, hasRequestByThem); if (requestEvent) { transitions.push({ phase: PHASE_REQUESTED, event: requestEvent }); } var readyEvent = requestEvent && this._getEventBy(READY_TYPE, !hasRequestByThem); if (readyEvent && phase() === PHASE_REQUESTED) { transitions.push({ phase: PHASE_READY, event: readyEvent }); } var startEvent; if (readyEvent || !requestEvent) { var theirStartEvent = this._eventsByThem.get(START_TYPE); var ourStartEvent = this._eventsByUs.get(START_TYPE); // any party can send .start after a .ready or unsent if (theirStartEvent && ourStartEvent) { startEvent = theirStartEvent.getSender() < ourStartEvent.getSender() ? theirStartEvent : ourStartEvent; } else { startEvent = theirStartEvent ? theirStartEvent : ourStartEvent; } } else { startEvent = this._getEventBy(START_TYPE, !hasRequestByThem); } if (startEvent) { var fromRequestPhase = phase() === PHASE_REQUESTED && requestEvent.getSender() !== startEvent.getSender(); var fromUnsentPhase = phase() === PHASE_UNSENT && this.channel.constructor.canCreateRequest(START_TYPE); if (fromRequestPhase || phase() === PHASE_READY || fromUnsentPhase) { transitions.push({ phase: PHASE_STARTED, event: startEvent }); } } var ourDoneEvent = this._eventsByUs.get(DONE_TYPE); if (this._verifierHasFinished || ourDoneEvent && phase() === PHASE_STARTED) { transitions.push({ phase: PHASE_DONE }); } var cancelEvent = this._getEventByEither(CANCEL_TYPE); if ((this._cancelled || cancelEvent) && phase() !== PHASE_DONE) { transitions.push({ phase: PHASE_CANCELLED, event: cancelEvent }); return transitions; } return transitions; } }, { key: "_transitionToPhase", value: function _transitionToPhase(transition) { var _this3 = this; var phase = transition.phase, event = transition.event; // get common methods if (phase === PHASE_REQUESTED || phase === PHASE_READY) { if (!this._wasSentByOwnDevice(event)) { var content = event.getContent(); this._commonMethods = content.methods.filter(function (m) { return _this3._verificationMethods.has(m); }); } } // detect if we're not a party in the request, and we should just observe if (!this.observeOnly) { // if requested or accepted by one of my other devices if (phase === PHASE_REQUESTED || phase === PHASE_STARTED || phase === PHASE_READY) { if (this.channel.receiveStartFromOtherDevices && this._wasSentByOwnUser(event) && !this._wasSentByOwnDevice(event)) { this._observeOnly = true; } } } // create verifier if (phase === PHASE_STARTED) { var _event$getContent = event.getContent(), method = _event$getContent.method; if (!this._verifier && !this.observeOnly) { this._verifier = this._createVerifier(method, event); if (!this._verifier) { this.cancel({ code: "m.unknown_method", reason: "Unknown method: ".concat(method) }); } else { this._chosenMethod = method; } } } } }, { key: "_applyPhaseTransitions", value: function _applyPhaseTransitions() { var _this4 = this; var transitions = this._calculatePhaseTransitions(); var existingIdx = transitions.findIndex(function (t) { return t.phase === _this4.phase; }); // trim off phases we already went through, if any var newTransitions = transitions.slice(existingIdx + 1); // transition to all new phases var _iterator = _createForOfIteratorHelper(newTransitions), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var transition = _step.value; this._transitionToPhase(transition); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return newTransitions; } }, { key: "_isWinningStartRace", value: function _isWinningStartRace(newEvent) { if (newEvent.getType() !== START_TYPE) { return false; } var oldEvent = this._verifier.startEvent; var oldRaceIdentifier; if (this.isSelfVerification) { // if the verifier does not have a startEvent, // it is because it's still sending and we are on the initator side // we know we are sending a .start event because we already // have a verifier (checked in calling method) if (oldEvent) { var oldContent = oldEvent.getContent(); oldRaceIdentifier = oldContent && oldContent.from_device; } else { oldRaceIdentifier = this._client.getDeviceId(); } } else { if (oldEvent) { oldRaceIdentifier = oldEvent.getSender(); } else { oldRaceIdentifier = this._client.getUserId(); } } var newRaceIdentifier; if (this.isSelfVerification) { var newContent = newEvent.getContent(); newRaceIdentifier = newContent && newContent.from_device; } else { newRaceIdentifier = newEvent.getSender(); } return newRaceIdentifier < oldRaceIdentifier; } }, { key: "hasEventId", value: function hasEventId(eventId) { var _iterator2 = _createForOfIteratorHelper(this._eventsByUs.values()), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var event = _step2.value; if (event.getId() === eventId) { return true; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } var _iterator3 = _createForOfIteratorHelper(this._eventsByThem.values()), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var _event = _step3.value; if (_event.getId() === eventId) { return true; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return false; } /** * Changes the state of the request and verifier in response to a key verification event. * @param {string} type the "symbolic" event type, as returned by the `getEventType` function on the channel. * @param {MatrixEvent} event the event to handle. Don't call getType() on it but use the `type` parameter instead. * @param {bool} isLiveEvent whether this is an even received through sync or not * @param {bool} isRemoteEcho whether this is the remote echo of an event sent by the same device * @param {bool} isSentByUs whether this event is sent by a party that can accept and/or observe the request like one of our peers. * For InRoomChannel this means any device for the syncing user. For ToDeviceChannel, just the syncing device. * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent. */ }, { key: "handleEvent", value: function () { var _handleEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(type, event, isLiveEvent, isRemoteEcho, isSentByUs) { var wasObserveOnly, isDuplicateEvent, oldPhase, newTransitions, newEventWinsRace, shouldGenerateQrCode, lastTransition, phase; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (!(this.done || this.cancelled)) { _context4.next = 2; break; } return _context4.abrupt("return"); case 2: wasObserveOnly = this._observeOnly; this._adjustObserveOnly(event, isLiveEvent); if (!(!this.observeOnly && !isRemoteEcho)) { _context4.next = 9; break; } _context4.next = 7; return this._cancelOnError(type, event); case 7: if (!_context4.sent) { _context4.next = 9; break; } return _context4.abrupt("return"); case 9: // This assumes verification won't need to send an event with // the same type for the same party twice. // This is true for QR and SAS verification, and was // added here to prevent verification getting cancelled // when the server duplicates an event (https://github.com/matrix-org/synapse/issues/3365) isDuplicateEvent = isSentByUs ? this._eventsByUs.has(type) : this._eventsByThem.has(type); if (!isDuplicateEvent) { _context4.next = 12; break; } return _context4.abrupt("return"); case 12: oldPhase = this.phase; this._addEvent(type, event, isSentByUs); // this will create if needed the verifier so needs to happen before calling it newTransitions = this._applyPhaseTransitions(); _context4.prev = 15; // only pass events from the other side to the verifier, // no remote echos of our own events if (this._verifier && !this.observeOnly) { newEventWinsRace = this._isWinningStartRace(event); if (this._verifier.canSwitchStartEvent(event) && newEventWinsRace) { this._verifier.switchStartEvent(event); } else if (!isRemoteEcho) { if (type === CANCEL_TYPE || this._verifier.events && this._verifier.events.includes(type)) { this._verifier.handleEvent(event); } } } if (!newTransitions.length) { _context4.next = 30; break; } if (!(isLiveEvent && newTransitions.some(function (t) { return t.phase === PHASE_READY; }))) { _context4.next = 24; break; } shouldGenerateQrCode = this.otherPartySupportsMethod(_QRCode.SCAN_QR_CODE_METHOD, true); if (!shouldGenerateQrCode) { _context4.next = 24; break; } _context4.next = 23; return _QRCode.QRCodeData.create(this, this._client); case 23: this._qrCodeData = _context4.sent; case 24: lastTransition = newTransitions[newTransitions.length - 1]; phase = lastTransition.phase; this._setupTimeout(phase); // set phase as last thing as this emits the "change" event this._setPhase(phase); _context4.next = 31; break; case 30: if (this._observeOnly !== wasObserveOnly) { this.emit("change"); } case 31: _context4.prev = 31; // log events we processed so we can see from rageshakes what events were added to a request _logger.logger.log("Verification request ".concat(this.channel.transactionId, ": ") + "".concat(type, " event with id:").concat(event.getId(), ", ") + "content:".concat(JSON.stringify(event.getContent()), " ") + "deviceId:".concat(this.channel.deviceId, ", ") + "sender:".concat(event.getSender(), ", isSentByUs:").concat(isSentByUs, ", ") + "isLiveEvent:".concat(isLiveEvent, ", isRemoteEcho:").concat(isRemoteEcho, ", ") + "phase:".concat(oldPhase, "=>").concat(this.phase, ", ") + "observeOnly:".concat(wasObserveOnly, "=>").concat(this._observeOnly)); return _context4.finish(31); case 34: case "end": return _context4.stop(); } } }, _callee4, this, [[15,, 31, 34]]); })); function handleEvent(_x, _x2, _x3, _x4, _x5) { return _handleEvent.apply(this, arguments); } return handleEvent; }() }, { key: "_setupTimeout", value: function _setupTimeout(phase) { var shouldTimeout = !this._timeoutTimer && !this.observeOnly && phase === PHASE_REQUESTED; if (shouldTimeout) { this._timeoutTimer = setTimeout(this._cancelOnTimeout, this.timeout); } if (this._timeoutTimer) { var shouldClear = phase === PHASE_STARTED || phase === PHASE_READY || phase === PHASE_DONE || phase === PHASE_CANCELLED; if (shouldClear) { clearTimeout(this._timeoutTimer); this._timeoutTimer = null; } } } }, { key: "_cancelOnError", value: function () { var _cancelOnError2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(type, event) { var method, isUnexpectedRequest, isUnexpectedReady, reason; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (!(type === START_TYPE)) { _context5.next = 6; break; } method = event.getContent().method; if (this._verificationMethods.has(method)) { _context5.next = 6; break; } _context5.next = 5; return this.cancel((0, _Error.errorFromEvent)((0, _Error.newUnknownMethodError)())); case 5: return _context5.abrupt("return", true); case 6: isUnexpectedRequest = type === REQUEST_TYPE && this.phase !== PHASE_UNSENT; isUnexpectedReady = type === READY_TYPE && this.phase !== PHASE_REQUESTED; // only if phase has passed from PHASE_UNSENT should we cancel, because events // are allowed to come in in any order (at least with InRoomChannel). So we only know // we're dealing with a valid request we should participate in once we've moved to PHASE_REQUESTED // before that, we could be looking at somebody elses verification request and we just // happen to be in the room if (!(this.phase !== PHASE_UNSENT && (isUnexpectedRequest || isUnexpectedReady))) { _context5.next = 14; break; } _logger.logger.warn("Cancelling, unexpected ".concat(type, " verification ") + "event from ".concat(event.getSender())); reason = "Unexpected ".concat(type, " event in phase ").concat(this.phase); _context5.next = 13; return this.cancel((0, _Error.errorFromEvent)((0, _Error.newUnexpectedMessageError)({ reason: reason }))); case 13: return _context5.abrupt("return", true); case 14: return _context5.abrupt("return", false); case 15: case "end": return _context5.stop(); } } }, _callee5, this); })); function _cancelOnError(_x6, _x7) { return _cancelOnError2.apply(this, arguments); } return _cancelOnError; }() }, { key: "_adjustObserveOnly", value: function _adjustObserveOnly(event, isLiveEvent) { // don't send out events for historical requests if (!isLiveEvent) { this._observeOnly = true; } if (this.calculateEventTimeout(event) < VERIFICATION_REQUEST_MARGIN) { this._observeOnly = true; } } }, { key: "_addEvent", value: function _addEvent(type, event, isSentByUs) { if (isSentByUs) { this._eventsByUs.set(type, event); } else { this._eventsByThem.set(type, event); } // once we know the userId of the other party (from the .request event) // see if any event by anyone else crept into this._eventsByThem if (type === REQUEST_TYPE) { var _iterator4 = _createForOfIteratorHelper(this._eventsByThem.entries()), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var _step4$value = (0, _slicedToArray2["default"])(_step4.value, 2), _type = _step4$value[0], _event2 = _step4$value[1]; if (_event2.getSender() !== this.otherUserId) { this._eventsByThem["delete"](_type); } } // also remember when we received the request event } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } this._requestReceivedAt = Date.now(); } } }, { key: "_createVerifier", value: function _createVerifier(method) { var startEvent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var targetDevice = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (!targetDevice) { targetDevice = this.targetDevice; } var _targetDevice = targetDevice, userId = _targetDevice.userId, deviceId = _targetDevice.deviceId; var VerifierCtor = this._verificationMethods.get(method); if (!VerifierCtor) { _logger.logger.warn("could not find verifier constructor for method", method); return; } return new VerifierCtor(this.channel, this._client, userId, deviceId, startEvent, this); } }, { key: "_wasSentByOwnUser", value: function _wasSentByOwnUser(event) { return event.getSender() === this._client.getUserId(); } // only for .request, .ready or .start }, { key: "_wasSentByOwnDevice", value: function _wasSentByOwnDevice(event) { if (!this._wasSentByOwnUser(event)) { return false; } var content = event.getContent(); if (!content || content.from_device !== this._client.getDeviceId()) { return false; } return true; } }, { key: "onVerifierCancelled", value: function onVerifierCancelled() { this._cancelled = true; // move to cancelled phase var newTransitions = this._applyPhaseTransitions(); if (newTransitions.length) { this._setPhase(newTransitions[newTransitions.length - 1].phase); } } }, { key: "onVerifierFinished", value: function onVerifierFinished() { this.channel.send("m.key.verification.done", {}); this._verifierHasFinished = true; // move to .done phase var newTransitions = this._applyPhaseTransitions(); if (newTransitions.length) { this._setPhase(newTransitions[newTransitions.length - 1].phase); } } }, { key: "getEventFromOtherParty", value: function getEventFromOtherParty(type) { return this._eventsByThem.get(type); } }, { key: "invalid", get: function get() { return this.phase === PHASE_UNSENT; } /** returns whether the phase is PHASE_REQUESTED */ }, { key: "requested", get: function get() { return this.phase === PHASE_REQUESTED; } /** returns whether the phase is PHASE_CANCELLED */ }, { key: "cancelled", get: function get() { return this.phase === PHASE_CANCELLED; } /** returns whether the phase is PHASE_READY */ }, { key: "ready", get: function get() { return this.phase === PHASE_READY; } /** returns whether the phase is PHASE_STARTED */ }, { key: "started", get: function get() { return this.phase === PHASE_STARTED; } /** returns whether the phase is PHASE_DONE */ }, { key: "done", get: function get() { return this.phase === PHASE_DONE; } /** once the phase is PHASE_STARTED (and !initiatedByMe) or PHASE_READY: common methods supported by both sides */ }, { key: "methods", get: function get() { return this._commonMethods; } /** the method picked in the .start event */ }, { key: "chosenMethod", get: function get() { return this._chosenMethod; } }, { key: "timeout", get: function get() { var requestEvent = this._getEventByEither(REQUEST_TYPE); if (requestEvent) { return this.calculateEventTimeout(requestEvent); } return 0; } /** * The key verification request event. * @returns {MatrixEvent} The request event, or falsey if not found. */ }, { key: "requestEvent", get: function get() { return this._getEventByEither(REQUEST_TYPE); } /** current phase of the request. Some properties might only be defined in a current phase. */ }, { key: "phase", get: function get() { return this._phase; } /** The verifier to do the actual verification, once the method has been established. Only defined when the `phase` is PHASE_STARTED. */ }, { key: "verifier", get: function get() { return this._verifier; } }, { key: "canAccept", get: function get() { return this.phase < PHASE_READY && !this._accepting && !this._declining; } }, { key: "accepting", get: function get() { return this._accepting; } }, { key: "declining", get: function get() { return this._declining; } /** whether this request has sent it's initial event and needs more events to complete */ }, { key: "pending", get: function get() { return !this.observeOnly && this._phase !== PHASE_DONE && this._phase !== PHASE_CANCELLED; } /** Only set after a .ready if the other party can scan a QR code */ }, { key: "qrCodeData", get: function get() { return this._qrCodeData; } }, { key: "initiatedByMe", get: function get() { // event created by us but no remote echo has been received yet var noEventsYet = this._eventsByUs.size + this._eventsByThem.size === 0; if (this._phase === PHASE_UNSENT && noEventsYet) { return true; } var hasMyRequest = this._eventsByUs.has(REQUEST_TYPE); var hasTheirRequest = this._eventsByThem.has(REQUEST_TYPE); if (hasMyRequest && !hasTheirRequest) { return true; } if (!hasMyRequest && hasTheirRequest) { return false; } var hasMyStart = this._eventsByUs.has(START_TYPE); var hasTheirStart = this._eventsByThem.has(START_TYPE); if (hasMyStart && !hasTheirStart) { return true; } return false; } /** The id of the user that initiated the request */ }, { key: "requestingUserId", get: function get() { if (this.initiatedByMe) { return this._client.getUserId(); } else { return this.otherUserId; } } /** The id of the user that (will) receive(d) the request */ }, { key: "receivingUserId", get: function get() { if (this.initiatedByMe) { return this.otherUserId; } else { return this._client.getUserId(); } } /** The user id of the other party in this request */ }, { key: "otherUserId", get: function get() { return this.channel.userId; } }, { key: "isSelfVerification", get: function get() { return this._client.getUserId() === this.otherUserId; } /** * The id of the user that cancelled the request, * only defined when phase is PHASE_CANCELLED */ }, { key: "cancellingUserId", get: function get() { var myCancel = this._eventsByUs.get(CANCEL_TYPE); var theirCancel = this._eventsByThem.get(CANCEL_TYPE); if (myCancel && (!theirCancel || myCancel.getId() < theirCancel.getId())) { return myCancel.getSender(); } if (theirCancel) { return theirCancel.getSender(); } return undefined; } /** * The cancellation code e.g m.user which is responsible for cancelling this verification */ }, { key: "cancellationCode", get: function get() { var ev = this._getEventByEither(CANCEL_TYPE); return ev ? ev.getContent().code : null; } }, { key: "observeOnly", get: function get() { return this._observeOnly; } /** * Gets which device the verification should be started with * given the events sent so far in the verification. This is the * same algorithm used to determine which device to send the * verification to when no specific device is specified. * @returns {{userId: *, deviceId: *}} The device information */ }, { key: "targetDevice", get: function get() { var theirFirstEvent = this._eventsByThem.get(REQUEST_TYPE) || this._eventsByThem.get(READY_TYPE) || this._eventsByThem.get(START_TYPE); var theirFirstContent = theirFirstEvent.getContent(); var fromDevice = theirFirstContent.from_device; return { userId: this.otherUserId, deviceId: fromDevice }; } }], [{ key: "validateEvent", value: function validateEvent(type, event, client) { var content = event.getContent(); if (!type || !type.startsWith(EVENT_PREFIX)) { return false; } // from here on we're fairly sure that this is supposed to be // part of a verification request, so be noisy when rejecting something if (!content) { _logger.logger.log("VerificationRequest: validateEvent: no content"); return false; } if (type === REQUEST_TYPE || type === READY_TYPE) { if (!Array.isArray(content.methods)) { _logger.logger.log("VerificationRequest: validateEvent: " + "fail because methods"); return false; } } if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) { if (typeof content.from_device !== "string" || content.from_device.length === 0) { _logger.logger.log("VerificationRequest: validateEvent: " + "fail because from_device"); return false; } } return true; } }]); return VerificationRequest; }(_events.EventEmitter); exports.VerificationRequest = VerificationRequest; },{"../../../logger":95,"../Error":82,"../QRCode":84,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/helpers/toConsumableArray":23,"@babel/runtime/regenerator":27,"events":36}],89:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.InvalidStoreError = InvalidStoreError; exports.InvalidCryptoStoreError = InvalidCryptoStoreError; exports.KeySignatureUploadError = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } // can't just do InvalidStoreError extends Error // because of http://babeljs.io/docs/usage/caveats/#classes function InvalidStoreError(reason, value) { var message = "Store is invalid because ".concat(reason, ", ") + "please stop the client, delete all data and start the client again"; var instance = Reflect.construct(Error, [message]); Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this)); instance.reason = reason; instance.value = value; return instance; } InvalidStoreError.TOGGLED_LAZY_LOADING = "TOGGLED_LAZY_LOADING"; InvalidStoreError.prototype = Object.create(Error.prototype, { constructor: { value: Error, enumerable: false, writable: true, configurable: true } }); Reflect.setPrototypeOf(InvalidStoreError, Error); function InvalidCryptoStoreError(reason) { var message = "Crypto store is invalid because ".concat(reason, ", ") + "please stop the client, delete all data and start the client again"; var instance = Reflect.construct(Error, [message]); Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this)); instance.reason = reason; instance.name = 'InvalidCryptoStoreError'; return instance; } InvalidCryptoStoreError.TOO_NEW = "TOO_NEW"; InvalidCryptoStoreError.prototype = Object.create(Error.prototype, { constructor: { value: Error, enumerable: false, writable: true, configurable: true } }); Reflect.setPrototypeOf(InvalidCryptoStoreError, Error); var KeySignatureUploadError = /*#__PURE__*/function (_Error) { (0, _inherits2["default"])(KeySignatureUploadError, _Error); var _super = _createSuper(KeySignatureUploadError); function KeySignatureUploadError(message, value) { var _this; (0, _classCallCheck2["default"])(this, KeySignatureUploadError); _this = _super.call(this, message); _this.value = value; return _this; } return KeySignatureUploadError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); exports.KeySignatureUploadError = KeySignatureUploadError; },{"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/wrapNativeSuper":26}],90:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FilterComponent = FilterComponent; /* Copyright 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 filter-component */ /** * Checks if a value matches a given field value, which may be a * terminated * wildcard pattern. * @param {String} actual_value The value to be compared * @param {String} filter_value The filter pattern to be compared * @return {bool} true if the actual_value matches the filter_value */ function _matches_wildcard(actual_value, filter_value) { if (filter_value.endsWith("*")) { var type_prefix = filter_value.slice(0, -1); return actual_value.substr(0, type_prefix.length) === type_prefix; } else { return actual_value === filter_value; } } /** * FilterComponent is a section of a Filter definition which defines the * types, rooms, senders filters etc to be applied to a particular type of resource. * This is all ported over from synapse's Filter object. * * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as * 'Filters' are referred to as 'FilterCollections'. * * @constructor * @param {Object} filter_json the definition of this filter JSON, e.g. { 'contains_url': true } */ function FilterComponent(filter_json) { this.filter_json = filter_json; this.types = filter_json.types || null; this.not_types = filter_json.not_types || []; this.rooms = filter_json.rooms || null; this.not_rooms = filter_json.not_rooms || []; this.senders = filter_json.senders || null; this.not_senders = filter_json.not_senders || []; this.contains_url = filter_json.contains_url || null; } /** * Checks with the filter component matches the given event * @param {MatrixEvent} event event to be checked against the filter * @return {bool} true if the event matches the filter */ FilterComponent.prototype.check = function (event) { return this._checkFields(event.getRoomId(), event.getSender(), event.getType(), event.getContent() ? event.getContent().url !== undefined : false); }; /** * Checks whether the filter component matches the given event fields. * @param {String} room_id the room_id for the event being checked * @param {String} sender the sender of the event being checked * @param {String} event_type the type of the event being checked * @param {String} contains_url whether the event contains a content.url field * @return {bool} true if the event fields match the filter */ FilterComponent.prototype._checkFields = function (room_id, sender, event_type, contains_url) { var literal_keys = { "rooms": function rooms(v) { return room_id === v; }, "senders": function senders(v) { return sender === v; }, "types": function types(v) { return _matches_wildcard(event_type, v); } }; var self = this; for (var n = 0; n < Object.keys(literal_keys).length; n++) { var name = Object.keys(literal_keys)[n]; var match_func = literal_keys[name]; var not_name = "not_" + name; var disallowed_values = self[not_name]; if (disallowed_values.filter(match_func).length > 0) { return false; } var allowed_values = self[name]; if (allowed_values && allowed_values.length > 0) { var anyMatch = allowed_values.some(match_func); if (!anyMatch) { return false; } } } var contains_url_filter = this.filter_json.contains_url; if (contains_url_filter !== undefined) { if (contains_url_filter !== contains_url) { return false; } } return true; }; /** * Filters a list of events down to those which match this filter component * @param {MatrixEvent[]} events Events to be checked againt the filter component * @return {MatrixEvent[]} events which matched the filter component */ FilterComponent.prototype.filter = function (events) { return events.filter(this.check, this); }; /** * Returns the limit field for a given filter component, providing a default of * 10 if none is otherwise specified. Cargo-culted from Synapse. * @return {Number} the limit for this filter component. */ FilterComponent.prototype.limit = function () { return this.filter_json.limit !== undefined ? this.filter_json.limit : 10; }; },{}],91:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Filter = Filter; var _filterComponent = require("./filter-component"); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 filter */ /** * @param {Object} obj * @param {string} keyNesting * @param {*} val */ function setProp(obj, keyNesting, val) { var nestedKeys = keyNesting.split("."); var currentObj = obj; for (var i = 0; i < nestedKeys.length - 1; i++) { if (!currentObj[nestedKeys[i]]) { currentObj[nestedKeys[i]] = {}; } currentObj = currentObj[nestedKeys[i]]; } currentObj[nestedKeys[nestedKeys.length - 1]] = val; } /** * Construct a new Filter. * @constructor * @param {string} userId The user ID for this filter. * @param {string=} filterId The filter ID if known. * @prop {string} userId The user ID of the filter * @prop {?string} filterId The filter ID */ function Filter(userId, filterId) { this.userId = userId; this.filterId = filterId; this.definition = {}; } Filter.LAZY_LOADING_MESSAGES_FILTER = { lazy_load_members: true }; /** * Get the ID of this filter on your homeserver (if known) * @return {?Number} The filter ID */ Filter.prototype.getFilterId = function () { return this.filterId; }; /** * Get the JSON body of the filter. * @return {Object} The filter definition */ Filter.prototype.getDefinition = function () { return this.definition; }; /** * Set the JSON body of the filter * @param {Object} definition The filter definition */ Filter.prototype.setDefinition = function (definition) { this.definition = definition; // This is all ported from synapse's FilterCollection() // definitions look something like: // { // "room": { // "rooms": ["!abcde:example.com"], // "not_rooms": ["!123456:example.com"], // "state": { // "types": ["m.room.*"], // "not_rooms": ["!726s6s6q:example.com"], // "lazy_load_members": true, // }, // "timeline": { // "limit": 10, // "types": ["m.room.message"], // "not_rooms": ["!726s6s6q:example.com"], // "not_senders": ["@spam:example.com"] // "contains_url": true // }, // "ephemeral": { // "types": ["m.receipt", "m.typing"], // "not_rooms": ["!726s6s6q:example.com"], // "not_senders": ["@spam:example.com"] // } // }, // "presence": { // "types": ["m.presence"], // "not_senders": ["@alice:example.com"] // }, // "event_format": "client", // "event_fields": ["type", "content", "sender"] // } var room_filter_json = definition.room; // consider the top level rooms/not_rooms filter var room_filter_fields = {}; if (room_filter_json) { if (room_filter_json.rooms) { room_filter_fields.rooms = room_filter_json.rooms; } if (room_filter_json.rooms) { room_filter_fields.not_rooms = room_filter_json.not_rooms; } this._include_leave = room_filter_json.include_leave || false; } this._room_filter = new _filterComponent.FilterComponent(room_filter_fields); this._room_timeline_filter = new _filterComponent.FilterComponent(room_filter_json ? room_filter_json.timeline || {} : {}); // don't bother porting this from synapse yet: // this._room_state_filter = // new FilterComponent(room_filter_json.state || {}); // this._room_ephemeral_filter = // new FilterComponent(room_filter_json.ephemeral || {}); // this._room_account_data_filter = // new FilterComponent(room_filter_json.account_data || {}); // this._presence_filter = // new FilterComponent(definition.presence || {}); // this._account_data_filter = // new FilterComponent(definition.account_data || {}); }; /** * Get the room.timeline filter component of the filter * @return {FilterComponent} room timeline filter component */ Filter.prototype.getRoomTimelineFilterComponent = function () { return this._room_timeline_filter; }; /** * Filter the list of events based on whether they are allowed in a timeline * based on this filter * @param {MatrixEvent[]} events the list of events being filtered * @return {MatrixEvent[]} the list of events which match the filter */ Filter.prototype.filterRoomTimeline = function (events) { return this._room_timeline_filter.filter(this._room_filter.filter(events)); }; /** * Set the max number of events to return for each room's timeline. * @param {Number} limit The max number of events to return for each room. */ Filter.prototype.setTimelineLimit = function (limit) { setProp(this.definition, "room.timeline.limit", limit); }; Filter.prototype.setLazyLoadMembers = function (enabled) { setProp(this.definition, "room.state.lazy_load_members", !!enabled); }; /** * Control whether left rooms should be included in responses. * @param {boolean} includeLeave True to make rooms the user has left appear * in responses. */ Filter.prototype.setIncludeLeaveRooms = function (includeLeave) { setProp(this.definition, "room.include_leave", includeLeave); }; /** * Create a filter from existing data. * @static * @param {string} userId * @param {string} filterId * @param {Object} jsonObj * @return {Filter} */ Filter.fromJson = function (userId, filterId, jsonObj) { var filter = new Filter(userId, filterId); filter.setDefinition(jsonObj); return filter; }; },{"./filter-component":90}],92:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixHttpApi = MatrixHttpApi; exports.retryNetworkOperation = retryNetworkOperation; exports.AbortError = exports.ConnectionError = exports.MatrixError = exports.PREFIX_MEDIA_R0 = exports.PREFIX_IDENTITY_V2 = exports.PREFIX_IDENTITY_V1 = exports.PREFIX_UNSTABLE = exports.PREFIX_R0 = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var _contentType = require("content-type"); var utils = _interopRequireWildcard(require("./utils")); var _logger = require("./logger"); var callbacks = _interopRequireWildcard(require("./realtime-callbacks")); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } /* TODO: - CS: complete register function (doing stages) - Identity server: linkEmail, authEmail, bindEmail, lookup3pid */ /** * A constant representing the URI path for release 0 of the Client-Server HTTP API. */ var PREFIX_R0 = "/_matrix/client/r0"; /** * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs. */ exports.PREFIX_R0 = PREFIX_R0; var PREFIX_UNSTABLE = "/_matrix/client/unstable"; /** * URI path for v1 of the the identity API * @deprecated Use v2. */ exports.PREFIX_UNSTABLE = PREFIX_UNSTABLE; var PREFIX_IDENTITY_V1 = "/_matrix/identity/api/v1"; /** * URI path for the v2 identity API */ exports.PREFIX_IDENTITY_V1 = PREFIX_IDENTITY_V1; var PREFIX_IDENTITY_V2 = "/_matrix/identity/v2"; /** * URI path for the media repo API */ exports.PREFIX_IDENTITY_V2 = PREFIX_IDENTITY_V2; var PREFIX_MEDIA_R0 = "/_matrix/media/r0"; /** * Construct a MatrixHttpApi. * @constructor * @param {EventEmitter} event_emitter The event emitter to use for emitting events * @param {Object} opts The options to use for this HTTP API. * @param {string} opts.baseUrl Required. The base client-server URL e.g. * 'http://localhost:8008'. * @param {Function} opts.request Required. The function to call for HTTP * requests. This function must look like function(opts, callback){ ... }. * @param {string} opts.prefix Required. The matrix client prefix to use, e.g. * '/_matrix/client/r0'. See PREFIX_R0 and PREFIX_UNSTABLE for constants. * * @param {boolean} opts.onlyData True to return only the 'data' component of the * response (e.g. the parsed HTTP body). If false, requests will return an * object with the properties code, headers and data. * * @param {string} opts.accessToken The access_token to send with requests. Can be * null to not send an access token. * @param {Object=} opts.extraParams Optional. Extra query parameters to send on * requests. * @param {Number=} opts.localTimeoutMs The default maximum amount of time to wait * before timing out the request. If not specified, there is no timeout. * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use * Authorization header instead of query param to send the access token to the server. */ exports.PREFIX_MEDIA_R0 = PREFIX_MEDIA_R0; function MatrixHttpApi(event_emitter, opts) { utils.checkObjectHasKeys(opts, ["baseUrl", "request", "prefix"]); opts.onlyData = opts.onlyData || false; this.event_emitter = event_emitter; this.opts = opts; this.useAuthorizationHeader = Boolean(opts.useAuthorizationHeader); this.uploads = []; } MatrixHttpApi.prototype = { /** * Sets the baase URL for the identity server * @param {string} url The new base url */ setIdBaseUrl: function setIdBaseUrl(url) { this.opts.idBaseUrl = url; }, /** * Get the content repository url with query parameters. * @return {Object} An object with a 'base', 'path' and 'params' for base URL, * path and query parameters respectively. */ getContentUri: function getContentUri() { var params = { access_token: this.opts.accessToken }; return { base: this.opts.baseUrl, path: "/_matrix/media/r0/upload", params: params }; }, /** * Upload content to the Home Server * * @param {object} file The object to upload. On a browser, something that * can be sent to XMLHttpRequest.send (typically a File). Under node.js, * a Buffer, String or ReadStream. * * @param {object} opts options object * * @param {string=} opts.name Name to give the file on the server. Defaults * to file.name. * * @param {boolean=} opts.includeFilename if false will not send the filename, * e.g for encrypted file uploads where filename leaks are undesirable. * Defaults to true. * * @param {string=} opts.type Content-type for the upload. Defaults to * file.type, or applicaton/octet-stream. * * @param {boolean=} opts.rawResponse Return the raw body, rather than * parsing the JSON. Defaults to false (except on node.js, where it * defaults to true for backwards compatibility). * * @param {boolean=} opts.onlyContentUri Just return the content URI, * rather than the whole body. Defaults to false (except on browsers, * where it defaults to true for backwards compatibility). Ignored if * opts.rawResponse is true. * * @param {Function=} opts.callback Deprecated. Optional. The callback to * invoke on success/failure. See the promise return values for more * information. * * @param {Function=} opts.progressHandler Optional. Called when a chunk of * data has been uploaded, with an object containing the fields `loaded` * (number of bytes transferred) and `total` (total size, if known). * * @return {Promise} Resolves to response object, as * determined by this.opts.onlyData, opts.rawResponse, and * opts.onlyContentUri. Rejects with an error (usually a MatrixError). */ uploadContent: function uploadContent(file, opts) { if (utils.isFunction(opts)) { // opts used to be callback opts = { callback: opts }; } else if (opts === undefined) { opts = {}; } // default opts.includeFilename to true (ignoring falsey values) var includeFilename = opts.includeFilename !== false; // if the file doesn't have a mime type, use a default since // the HS errors if we don't supply one. var contentType = opts.type || file.type || 'application/octet-stream'; var fileName = opts.name || file.name; // We used to recommend setting file.stream to the thing to upload on // Node.js. As of 2019-06-11, this is still in widespread use in various // clients, so we should preserve this for simple objects used in // Node.js. File API objects (via either the File or Blob interfaces) in // the browser now define a `stream` method, which leads to trouble // here, so we also check the type of `stream`. var body = file; if (body.stream && typeof body.stream !== "function") { _logger.logger.warn("Using `file.stream` as the content to upload. Future " + "versions of the js-sdk will change this to expect `file` to " + "be the content directly."); body = body.stream; } // backwards-compatibility hacks where we used to do different things // between browser and node. var rawResponse = opts.rawResponse; if (rawResponse === undefined) { if (global.XMLHttpRequest) { rawResponse = false; } else { _logger.logger.warn("Returning the raw JSON from uploadContent(). Future " + "versions of the js-sdk will change this default, to " + "return the parsed object. Set opts.rawResponse=false " + "to change this behaviour now."); rawResponse = true; } } var onlyContentUri = opts.onlyContentUri; if (!rawResponse && onlyContentUri === undefined) { if (global.XMLHttpRequest) { _logger.logger.warn("Returning only the content-uri from uploadContent(). " + "Future versions of the js-sdk will change this " + "default, to return the whole response object. Set " + "opts.onlyContentUri=false to change this behaviour now."); onlyContentUri = true; } else { onlyContentUri = false; } } // browser-request doesn't support File objects because it deep-copies // the options using JSON.parse(JSON.stringify(options)). Instead of // loading the whole file into memory as a string and letting // browser-request base64 encode and then decode it again, we just // use XMLHttpRequest directly. // (browser-request doesn't support progress either, which is also kind // of important here) var upload = { loaded: 0, total: 0 }; var promise; // XMLHttpRequest doesn't parse JSON for us. request normally does, but // we're setting opts.json=false so that it doesn't JSON-encode the // request, which also means it doesn't JSON-decode the response. Either // way, we have to JSON-parse the response ourselves. var bodyParser = null; if (!rawResponse) { bodyParser = function bodyParser(rawBody) { var body = JSON.parse(rawBody); if (onlyContentUri) { body = body.content_uri; if (body === undefined) { throw Error('Bad response'); } } return body; }; } if (global.XMLHttpRequest) { var defer = utils.defer(); var xhr = new global.XMLHttpRequest(); upload.xhr = xhr; var cb = requestCallback(defer, opts.callback, this.opts.onlyData); var timeout_fn = function timeout_fn() { xhr.abort(); cb(new Error('Timeout')); }; // set an initial timeout of 30s; we'll advance it each time we get // a progress notification xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000); xhr.onreadystatechange = function () { switch (xhr.readyState) { case global.XMLHttpRequest.DONE: callbacks.clearTimeout(xhr.timeout_timer); var resp; try { if (xhr.status === 0) { throw new AbortError(); } if (!xhr.responseText) { throw new Error('No response body.'); } resp = xhr.responseText; if (bodyParser) { resp = bodyParser(resp); } } catch (err) { err.http_status = xhr.status; cb(err); return; } cb(undefined, xhr, resp); break; } }; xhr.upload.addEventListener("progress", function (ev) { callbacks.clearTimeout(xhr.timeout_timer); upload.loaded = ev.loaded; upload.total = ev.total; xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000); if (opts.progressHandler) { opts.progressHandler({ loaded: ev.loaded, total: ev.total }); } }); var url = this.opts.baseUrl + "/_matrix/media/r0/upload"; var queryArgs = []; if (includeFilename && fileName) { queryArgs.push("filename=" + encodeURIComponent(fileName)); } if (!this.useAuthorizationHeader) { queryArgs.push("access_token=" + encodeURIComponent(this.opts.accessToken)); } if (queryArgs.length > 0) { url += "?" + queryArgs.join("&"); } xhr.open("POST", url); if (this.useAuthorizationHeader) { xhr.setRequestHeader("Authorization", "Bearer " + this.opts.accessToken); } xhr.setRequestHeader("Content-Type", contentType); xhr.send(body); promise = defer.promise; // dirty hack (as per _request) to allow the upload to be cancelled. promise.abort = xhr.abort.bind(xhr); } else { var queryParams = {}; if (includeFilename && fileName) { queryParams.filename = fileName; } promise = this.authedRequest(opts.callback, "POST", "/upload", queryParams, body, { prefix: "/_matrix/media/r0", headers: { "Content-Type": contentType }, json: false, bodyParser: bodyParser }); } var self = this; // remove the upload from the list on completion var promise0 = promise["finally"](function () { for (var i = 0; i < self.uploads.length; ++i) { if (self.uploads[i] === upload) { self.uploads.splice(i, 1); return; } } }); // copy our dirty abort() method to the new promise promise0.abort = promise.abort; upload.promise = promise0; this.uploads.push(upload); return promise0; }, cancelUpload: function cancelUpload(promise) { if (promise.abort) { promise.abort(); return true; } return false; }, getCurrentUploads: function getCurrentUploads() { return this.uploads; }, idServerRequest: function idServerRequest(callback, method, path, params, prefix, accessToken) { if (!this.opts.idBaseUrl) { throw new Error("No Identity Server base URL set"); } var fullUri = this.opts.idBaseUrl + prefix + path; if (callback !== undefined && !utils.isFunction(callback)) { throw Error("Expected callback to be a function but got " + (0, _typeof2["default"])(callback)); } var opts = { uri: fullUri, method: method, withCredentials: false, json: true, // we want a JSON response if we can _matrix_opts: this.opts, headers: {} }; if (method === 'GET') { opts.qs = params; } else if ((0, _typeof2["default"])(params) === "object") { opts.json = params; } if (accessToken) { opts.headers['Authorization'] = "Bearer ".concat(accessToken); } var defer = utils.defer(); this.opts.request(opts, requestCallback(defer, callback, this.opts.onlyData)); return defer.promise; }, /** * Perform an authorised request to the homeserver. * @param {Function} callback Optional. The callback to invoke on * success/failure. See the promise return values for more information. * @param {string} method The HTTP method e.g. "GET". * @param {string} path The HTTP path after the supplied prefix e.g. * "/createRoom". * * @param {Object=} queryParams A dict of query params (these will NOT be * urlencoded). If unspecified, there will be no query params. * * @param {Object} [data] The HTTP JSON body. * * @param {Object|Number=} opts additional options. If a number is specified, * this is treated as `opts.localTimeoutMs`. * * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before * timing out the request. If not specified, there is no timeout. * * @param {sting=} opts.prefix The full prefix to use e.g. * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix. * * @param {Object=} opts.headers map of additional request headers * * @return {Promise} Resolves to {data: {Object}, * headers: {Object}, code: {Number}}. * If onlyData is set, this will resolve to the data * object only. * @return {module:http-api.MatrixError} Rejects with an error if a problem * occurred. This includes network problems and Matrix-specific error JSON. */ authedRequest: function authedRequest(callback, method, path, queryParams, data, opts) { if (!queryParams) { queryParams = {}; } if (this.useAuthorizationHeader) { if (isFinite(opts)) { // opts used to be localTimeoutMs opts = { localTimeoutMs: opts }; } if (!opts) { opts = {}; } if (!opts.headers) { opts.headers = {}; } if (!opts.headers.Authorization) { opts.headers.Authorization = "Bearer " + this.opts.accessToken; } if (queryParams.access_token) { delete queryParams.access_token; } } else { if (!queryParams.access_token) { queryParams.access_token = this.opts.accessToken; } } var requestPromise = this.request(callback, method, path, queryParams, data, opts); var self = this; requestPromise["catch"](function (err) { if (err.errcode == 'M_UNKNOWN_TOKEN') { self.event_emitter.emit("Session.logged_out", err); } else if (err.errcode == 'M_CONSENT_NOT_GIVEN') { self.event_emitter.emit("no_consent", err.message, err.data.consent_uri); } }); // return the original promise, otherwise tests break due to it having to // go around the event loop one more time to process the result of the request return requestPromise; }, /** * Perform a request to the homeserver without any credentials. * @param {Function} callback Optional. The callback to invoke on * success/failure. See the promise return values for more information. * @param {string} method The HTTP method e.g. "GET". * @param {string} path The HTTP path after the supplied prefix e.g. * "/createRoom". * * @param {Object=} queryParams A dict of query params (these will NOT be * urlencoded). If unspecified, there will be no query params. * * @param {Object} [data] The HTTP JSON body. * * @param {Object=} opts additional options * * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before * timing out the request. If not specified, there is no timeout. * * @param {sting=} opts.prefix The full prefix to use e.g. * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix. * * @param {Object=} opts.headers map of additional request headers * * @return {Promise} Resolves to {data: {Object}, * headers: {Object}, code: {Number}}. * If onlyData is set, this will resolve to the data * object only. * @return {module:http-api.MatrixError} Rejects with an error if a problem * occurred. This includes network problems and Matrix-specific error JSON. */ request: function request(callback, method, path, queryParams, data, opts) { opts = opts || {}; var prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix; var fullUri = this.opts.baseUrl + prefix + path; return this.requestOtherUrl(callback, method, fullUri, queryParams, data, opts); }, /** * Perform a request to an arbitrary URL. * @param {Function} callback Optional. The callback to invoke on * success/failure. See the promise return values for more information. * @param {string} method The HTTP method e.g. "GET". * @param {string} uri The HTTP URI * * @param {Object=} queryParams A dict of query params (these will NOT be * urlencoded). If unspecified, there will be no query params. * * @param {Object} [data] The HTTP JSON body. * * @param {Object=} opts additional options * * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before * timing out the request. If not specified, there is no timeout. * * @param {sting=} opts.prefix The full prefix to use e.g. * "/_matrix/client/v2_alpha". If not specified, uses this.opts.prefix. * * @param {Object=} opts.headers map of additional request headers * * @return {Promise} Resolves to {data: {Object}, * headers: {Object}, code: {Number}}. * If onlyData is set, this will resolve to the data * object only. * @return {module:http-api.MatrixError} Rejects with an error if a problem * occurred. This includes network problems and Matrix-specific error JSON. */ requestOtherUrl: function requestOtherUrl(callback, method, uri, queryParams, data, opts) { if (opts === undefined || opts === null) { opts = {}; } else if (isFinite(opts)) { // opts used to be localTimeoutMs opts = { localTimeoutMs: opts }; } return this._request(callback, method, uri, queryParams, data, opts); }, /** * Form and return a homeserver request URL based on the given path * params and prefix. * @param {string} path The HTTP path after the supplied prefix e.g. * "/createRoom". * @param {Object} queryParams A dict of query params (these will NOT be * urlencoded). * @param {string} prefix The full prefix to use e.g. * "/_matrix/client/v2_alpha". * @return {string} URL */ getUrl: function getUrl(path, queryParams, prefix) { var queryString = ""; if (queryParams) { queryString = "?" + utils.encodeParams(queryParams); } return this.opts.baseUrl + prefix + path + queryString; }, /** * @private * * @param {function} callback * @param {string} method * @param {string} uri * @param {object} queryParams * @param {object|string} data * @param {object=} opts * * @param {boolean} [opts.json =true] Json-encode data before sending, and * decode response on receipt. (We will still json-decode error * responses, even if this is false.) * * @param {object=} opts.headers extra request headers * * @param {number=} opts.localTimeoutMs client-side timeout for the * request. Default timeout if falsy. * * @param {function=} opts.bodyParser function to parse the body of the * response before passing it to the promise and callback. * * @return {Promise} a promise which resolves to either the * response object (if this.opts.onlyData is truthy), or the parsed * body. Rejects */ _request: function _request(callback, method, uri, queryParams, data, opts) { if (callback !== undefined && !utils.isFunction(callback)) { throw Error("Expected callback to be a function but got " + (0, _typeof2["default"])(callback)); } opts = opts || {}; var self = this; if (this.opts.extraParams) { queryParams = _objectSpread(_objectSpread({}, queryParams), this.opts.extraParams); } var headers = utils.extend({}, opts.headers || {}); var json = opts.json === undefined ? true : opts.json; var bodyParser = opts.bodyParser; // we handle the json encoding/decoding here, because request and // browser-request make a mess of it. Specifically, they attempt to // json-decode plain-text error responses, which in turn means that the // actual error gets swallowed by a SyntaxError. if (json) { if (data) { data = JSON.stringify(data); headers['content-type'] = 'application/json'; } if (!headers['accept']) { headers['accept'] = 'application/json'; } if (bodyParser === undefined) { bodyParser = function bodyParser(rawBody) { return JSON.parse(rawBody); }; } } var defer = utils.defer(); var timeoutId; var timedOut = false; var req; var localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs; var resetTimeout = function resetTimeout() { if (localTimeoutMs) { if (timeoutId) { callbacks.clearTimeout(timeoutId); } timeoutId = callbacks.setTimeout(function () { timedOut = true; if (req && req.abort) { req.abort(); } defer.reject(new MatrixError({ error: "Locally timed out waiting for a response", errcode: "ORG.MATRIX.JSSDK_TIMEOUT", timeout: localTimeoutMs })); }, localTimeoutMs); } }; resetTimeout(); var reqPromise = defer.promise; try { req = this.opts.request({ uri: uri, method: method, withCredentials: false, qs: queryParams, qsStringifyOptions: opts.qsStringifyOptions, useQuerystring: true, body: data, json: false, timeout: localTimeoutMs, headers: headers || {}, _matrix_opts: this.opts }, function (err, response, body) { if (localTimeoutMs) { callbacks.clearTimeout(timeoutId); if (timedOut) { return; // already rejected promise } } var handlerFn = requestCallback(defer, callback, self.opts.onlyData, bodyParser); handlerFn(err, response, body); }); if (req) { // This will only work in a browser, where opts.request is the // `browser-request` import. Currently `request` does not support progress // updates - see https://github.com/request/request/pull/2346. // `browser-request` returns an XHRHttpRequest which exposes `onprogress` if ('onprogress' in req) { req.onprogress = function (e) { // Prevent the timeout from rejecting the deferred promise if progress is // seen with the request resetTimeout(); }; } // FIXME: This is EVIL, but I can't think of a better way to expose // abort() operations on underlying HTTP requests :( if (req.abort) reqPromise.abort = req.abort.bind(req); } } catch (ex) { defer.reject(ex); if (callback) { callback(ex); } } return reqPromise; } }; /* * Returns a callback that can be invoked by an HTTP request on completion, * that will either resolve or reject the given defer as well as invoke the * given userDefinedCallback (if any). * * HTTP errors are transformed into javascript errors and the deferred is rejected. * * If bodyParser is given, it is used to transform the body of the successful * responses before passing to the defer/callback. * * If onlyData is true, the defer/callback is invoked with the body of the * response, otherwise the result object (with `code` and `data` fields) * */ var requestCallback = function requestCallback(defer, userDefinedCallback, onlyData, bodyParser) { userDefinedCallback = userDefinedCallback || function () {}; return function (err, response, body) { if (err) { // the unit tests use matrix-mock-request, which throw the string "aborted" when aborting a request. // See https://github.com/matrix-org/matrix-mock-request/blob/3276d0263a561b5b8326b47bae720578a2c7473a/src/index.js#L48 var aborted = err.name === "AbortError" || err === "aborted"; if (!aborted && !(err instanceof MatrixError)) { // browser-request just throws normal Error objects, // not `TypeError`s like fetch does. So just assume any // error is due to the connection. err = new ConnectionError("request failed", err); } } if (!err) { try { if (response.statusCode >= 400) { err = parseErrorResponse(response, body); } else if (bodyParser) { body = bodyParser(body); } } catch (e) { err = new Error("Error parsing server response: ".concat(e)); } } if (err) { defer.reject(err); userDefinedCallback(err); } else { var res = { code: response.statusCode, // XXX: why do we bother with this? it doesn't work for // XMLHttpRequest, so clearly we don't use it. headers: response.headers, data: body }; defer.resolve(onlyData ? body : res); userDefinedCallback(null, onlyData ? body : res); } }; }; /** * Attempt to turn an HTTP error response into a Javascript Error. * * If it is a JSON response, we will parse it into a MatrixError. Otherwise * we return a generic Error. * * @param {XMLHttpRequest|http.IncomingMessage} response response object * @param {String} body raw body of the response * @returns {Error} */ function parseErrorResponse(response, body) { var httpStatus = response.statusCode; var contentType = getResponseContentType(response); var err; if (contentType) { if (contentType.type === 'application/json') { var jsonBody = (0, _typeof2["default"])(body) === 'object' ? body : JSON.parse(body); err = new MatrixError(jsonBody); } else if (contentType.type === 'text/plain') { err = new Error("Server returned ".concat(httpStatus, " error: ").concat(body)); } } if (!err) { err = new Error("Server returned ".concat(httpStatus, " error")); } err.httpStatus = httpStatus; return err; } /** * extract the Content-Type header from the response object, and * parse it to a `{type, parameters}` object. * * returns null if no content-type header could be found. * * @param {XMLHttpRequest|http.IncomingMessage} response response object * @returns {{type: String, parameters: Object}?} parsed content-type header, or null if not found */ function getResponseContentType(response) { var contentType; if (response.getResponseHeader) { // XMLHttpRequest provides getResponseHeader contentType = response.getResponseHeader("Content-Type"); } else if (response.headers) { // request provides http.IncomingMessage which has a message.headers map contentType = response.headers['content-type'] || null; } if (!contentType) { return null; } try { return (0, _contentType.parse)(contentType); } catch (e) { throw new Error("Error parsing Content-Type '".concat(contentType, "': ").concat(e)); } } /** * Construct a Matrix error. This is a JavaScript Error with additional * information specific to the standard Matrix error response. * @constructor * @param {Object} errorJson The Matrix error JSON returned from the homeserver. * @prop {string} errcode The Matrix 'errcode' value, e.g. "M_FORBIDDEN". * @prop {string} name Same as MatrixError.errcode but with a default unknown string. * @prop {string} message The Matrix 'error' value, e.g. "Missing token." * @prop {Object} data The raw Matrix error JSON used to construct this object. * @prop {integer} httpStatus The numeric HTTP status code given */ var MatrixError = /*#__PURE__*/function (_Error) { (0, _inherits2["default"])(MatrixError, _Error); var _super = _createSuper(MatrixError); function MatrixError(errorJson) { var _this; (0, _classCallCheck2["default"])(this, MatrixError); errorJson = errorJson || {}; _this = _super.call(this, "MatrixError: ".concat(errorJson.errcode)); _this.errcode = errorJson.errcode; _this.name = errorJson.errcode || "Unknown error code"; _this.message = errorJson.error || "Unknown message"; _this.data = errorJson; return _this; } return MatrixError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); /** * Construct a ConnectionError. This is a JavaScript Error indicating * that a request failed because of some error with the connection, either * CORS was not correctly configured on the server, the server didn't response, * the request timed out, or the internet connection on the client side went down. * @constructor */ exports.MatrixError = MatrixError; var ConnectionError = /*#__PURE__*/function (_Error2) { (0, _inherits2["default"])(ConnectionError, _Error2); var _super2 = _createSuper(ConnectionError); function ConnectionError(message) { var _this2; var cause = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; (0, _classCallCheck2["default"])(this, ConnectionError); _this2 = _super2.call(this, message + (cause ? ": ".concat(cause.message) : "")); _this2._cause = cause; return _this2; } (0, _createClass2["default"])(ConnectionError, [{ key: "name", get: function get() { return "ConnectionError"; } }, { key: "cause", get: function get() { return this._cause; } }]); return ConnectionError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); exports.ConnectionError = ConnectionError; var AbortError = /*#__PURE__*/function (_Error3) { (0, _inherits2["default"])(AbortError, _Error3); var _super3 = _createSuper(AbortError); function AbortError() { (0, _classCallCheck2["default"])(this, AbortError); return _super3.call(this, "Operation aborted"); } (0, _createClass2["default"])(AbortError, [{ key: "name", get: function get() { return "AbortError"; } }]); return AbortError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); /** * Retries a network operation run in a callback. * @param {number} maxAttempts maximum attempts to try * @param {Function} callback callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again. * @return {any} the result of the network operation * @throws {ConnectionError} If after maxAttempts the callback still throws ConnectionError */ exports.AbortError = AbortError; function retryNetworkOperation(_x, _x2) { return _retryNetworkOperation.apply(this, arguments); } function _retryNetworkOperation() { _retryNetworkOperation = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(maxAttempts, callback) { var attempts, lastConnectionError; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: attempts = 0; lastConnectionError = null; case 2: if (!(attempts < maxAttempts)) { _context2.next = 21; break; } _context2.prev = 3; if (!(attempts > 0)) { _context2.next = 6; break; } return _context2.delegateYield( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var timeout; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: timeout = 1000 * Math.pow(2, attempts); console.log("network operation failed ".concat(attempts, " times,") + " retrying in ".concat(timeout, "ms...")); _context.next = 4; return new Promise(function (r) { return setTimeout(r, timeout); }); case 4: case "end": return _context.stop(); } } }, _callee); })(), "t0", 6); case 6: _context2.next = 8; return callback(); case 8: return _context2.abrupt("return", _context2.sent); case 11: _context2.prev = 11; _context2.t1 = _context2["catch"](3); if (!(_context2.t1 instanceof ConnectionError)) { _context2.next = 18; break; } attempts += 1; lastConnectionError = _context2.t1; _context2.next = 19; break; case 18: throw _context2.t1; case 19: _context2.next = 2; break; case 21: throw lastConnectionError; case 22: case "end": return _context2.stop(); } } }, _callee2, null, [[3, 11]]); })); return _retryNetworkOperation.apply(this, arguments); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./logger":95,"./realtime-callbacks":111,"./utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/typeof":24,"@babel/runtime/helpers/wrapNativeSuper":26,"@babel/runtime/regenerator":27,"content-type":35}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.exists = exists; /* 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. */ /** * Check if an IndexedDB database exists. The only way to do so is to try opening it, so * we do that and then delete it did not exist before. * * @param {Object} indexedDB The `indexedDB` interface * @param {string} dbName The database name to test for * @returns {boolean} Whether the database exists */ function exists(indexedDB, dbName) { return new Promise(function (resolve, reject) { var exists = true; var req = indexedDB.open(dbName); req.onupgradeneeded = function () { // Since we did not provide an explicit version when opening, this event // should only fire if the DB did not exist before at any version. exists = false; }; req.onblocked = function () { return reject(); }; req.onsuccess = function () { var db = req.result; db.close(); if (!exists) { // The DB did not exist before, but has been created as part of this // existence check. Delete it now to restore previous state. Delete can // actually take a while to complete in some browsers, so don't wait for // it. This won't block future open calls that a store might issue next to // properly set up the DB. indexedDB.deleteDatabase(dbName); } resolve(exists); }; req.onerror = function (ev) { return reject(ev.target.error); }; }); } },{}],94:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.InteractiveAuth = InteractiveAuth; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _url = _interopRequireDefault(require("url")); var utils = _interopRequireWildcard(require("./utils")); var _logger = require("./logger"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var EMAIL_STAGE_TYPE = "m.login.email.identity"; var MSISDN_STAGE_TYPE = "m.login.msisdn"; /** * Abstracts the logic used to drive the interactive auth process. * *

Components implementing an interactive auth flow should instantiate one of * these, passing in the necessary callbacks to the constructor. They should * then call attemptAuth, which will return a promise which will resolve or * reject when the interactive-auth process completes. * *

Meanwhile, calls will be made to the startAuthStage and doRequest * callbacks, and information gathered from the user can be submitted with * submitAuthDict. * * @constructor * @alias module:interactive-auth * * @param {object} opts options object * * @param {object} opts.matrixClient A matrix client to use for the auth process * * @param {object?} opts.authData error response from the last request. If * null, a request will be made with no auth before starting. * * @param {function(object?): Promise} opts.doRequest * called with the new auth dict to submit the request. Also passes a * second deprecated arg which is a flag set to true if this request * is a background request. The busyChanged callback should be used * instead of the backfround flag. Should return a promise which resolves * to the successful response or rejects with a MatrixError. * * @param {function(bool): Promise} opts.busyChanged * called whenever the interactive auth logic becomes busy submitting * information provided by the user or finsihes. After this has been * called with true the UI should indicate that a request is in progress * until it is called again with false. * * @param {function(string, object?)} opts.stateUpdated * called when the status of the UI auth changes, ie. when the state of * an auth stage changes of when the auth flow moves to a new stage. * The arguments are: the login type (eg m.login.password); and an object * which is either an error or an informational object specific to the * login type. If the 'errcode' key is defined, the object is an error, * and has keys: * errcode: string, the textual error code, eg. M_UNKNOWN * error: string, human readable string describing the error * * The login type specific objects are as follows: * m.login.email.identity: * * emailSid: string, the sid of the active email auth session * * @param {object?} opts.inputs Inputs provided by the user and used by different * stages of the auto process. The inputs provided will affect what flow is chosen. * * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow * using email verification will be chosen. * * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives * the country that opts.phoneNumber should be resolved relative to. * * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow * using phone number validation will be chosen. * * @param {string?} opts.sessionId If resuming an existing interactive auth session, * the sessionId of that session. * * @param {string?} opts.clientSecret If resuming an existing interactive auth session, * the client secret for that session * * @param {string?} opts.emailSid If returning from having completed m.login.email.identity * auth, the sid for the email verification session. * * @param {function?} opts.requestEmailToken A function that takes the email address (string), * clientSecret (string), attempt number (int) and sessionId (string) and calls the * relevant requestToken function and returns the promise returned by that function. * If the resulting promise rejects, the rejection will propagate through to the * attemptAuth promise. * */ function InteractiveAuth(opts) { this._matrixClient = opts.matrixClient; this._data = opts.authData || {}; this._requestCallback = opts.doRequest; this._busyChangedCallback = opts.busyChanged; // startAuthStage included for backwards compat this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage; this._resolveFunc = null; this._rejectFunc = null; this._inputs = opts.inputs || {}; this._requestEmailTokenCallback = opts.requestEmailToken; if (opts.sessionId) this._data.session = opts.sessionId; this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret(); this._emailSid = opts.emailSid; if (this._emailSid === undefined) this._emailSid = null; this._requestingEmailToken = false; this._chosenFlow = null; this._currentStage = null; // if we are currently trying to submit an auth dict (which includes polling) // the promise the will resolve/reject when it completes this._submitPromise = null; } InteractiveAuth.prototype = { /** * begin the authentication process. * * @return {Promise} which resolves to the response on success, * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if * no suitable authentication flow can be found */ attemptAuth: function attemptAuth() { var _this = this; // This promise will be quite long-lived and will resolve when the // request is authenticated and completes successfully. return new Promise(function (resolve, reject) { _this._resolveFunc = resolve; _this._rejectFunc = reject; var hasFlows = _this._data && _this._data.flows; // if we have no flows, try a request to acquire the flows if (!hasFlows) { if (_this._busyChangedCallback) _this._busyChangedCallback(true); // use the existing sessionid, if one is present. var auth = null; if (_this._data.session) { auth = { session: _this._data.session }; } _this._doRequest(auth)["finally"](function () { if (_this._busyChangedCallback) _this._busyChangedCallback(false); }); } else { _this._startNextAuthStage(); } }); }, /** * Poll to check if the auth session or current stage has been * completed out-of-band. If so, the attemptAuth promise will * be resolved. */ poll: function () { var _poll = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var authDict, creds, idServerParsedUrl; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (this._data.session) { _context.next = 2; break; } return _context.abrupt("return"); case 2: if (this._resolveFunc) { _context.next = 4; break; } return _context.abrupt("return"); case 4: if (!this._submitPromise) { _context.next = 6; break; } return _context.abrupt("return"); case 6: authDict = {}; if (!(this._currentStage == EMAIL_STAGE_TYPE)) { _context.next = 16; break; } if (!this._emailSid) { _context.next = 16; break; } creds = { sid: this._emailSid, client_secret: this._clientSecret }; _context.next = 12; return this._matrixClient.doesServerRequireIdServerParam(); case 12: if (!_context.sent) { _context.next = 15; break; } idServerParsedUrl = _url["default"].parse(this._matrixClient.getIdentityServerUrl()); creds.id_server = idServerParsedUrl.host; case 15: authDict = { type: EMAIL_STAGE_TYPE, // TODO: Remove `threepid_creds` once servers support proper UIA // See https://github.com/matrix-org/synapse/issues/5665 // See https://github.com/matrix-org/matrix-doc/issues/2220 threepid_creds: creds, threepidCreds: creds }; case 16: this.submitAuthDict(authDict, true); case 17: case "end": return _context.stop(); } } }, _callee, this); })); function poll() { return _poll.apply(this, arguments); } return poll; }(), /** * get the auth session ID * * @return {string} session id */ getSessionId: function getSessionId() { return this._data ? this._data.session : undefined; }, /** * get the client secret used for validation sessions * with the ID server. * * @return {string} client secret */ getClientSecret: function getClientSecret() { return this._clientSecret; }, /** * get the server params for a given stage * * @param {string} loginType login type for the stage * @return {object?} any parameters from the server for this stage */ getStageParams: function getStageParams(loginType) { var params = {}; if (this._data && this._data.params) { params = this._data.params; } return params[loginType]; }, getChosenFlow: function getChosenFlow() { return this._chosenFlow; }, /** * submit a new auth dict and fire off the request. This will either * make attemptAuth resolve/reject, or cause the startAuthStage callback * to be called for a new stage. * * @param {object} authData new auth dict to send to the server. Should * include a `type` propterty denoting the login type, as well as any * other params for that stage. * @param {bool} background If true, this request failing will not result * in the attemptAuth promise being rejected. This can be set to true * for requests that just poll to see if auth has been completed elsewhere. */ submitAuthDict: function () { var _submitAuthDict = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(authData, background) { var auth; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (this._resolveFunc) { _context2.next = 2; break; } throw new Error("submitAuthDict() called before attemptAuth()"); case 2: if (!background && this._busyChangedCallback) { this._busyChangedCallback(true); } // if we're currently trying a request, wait for it to finish // as otherwise we can get multiple 200 responses which can mean // things like multiple logins for register requests. // (but discard any expections as we only care when its done, // not whether it worked or not) case 3: if (!this._submitPromise) { _context2.next = 13; break; } _context2.prev = 4; _context2.next = 7; return this._submitPromise; case 7: _context2.next = 11; break; case 9: _context2.prev = 9; _context2.t0 = _context2["catch"](4); case 11: _context2.next = 3; break; case 13: if (this._data.session) { auth = { session: this._data.session }; utils.extend(auth, authData); } else { auth = authData; } _context2.prev = 14; // NB. the 'background' flag is deprecated by the busyChanged // callback and is here for backwards compat this._submitPromise = this._doRequest(auth, background); _context2.next = 18; return this._submitPromise; case 18: _context2.prev = 18; this._submitPromise = null; if (!background && this._busyChangedCallback) { this._busyChangedCallback(false); } return _context2.finish(18); case 22: case "end": return _context2.stop(); } } }, _callee2, this, [[4, 9], [14,, 18, 22]]); })); function submitAuthDict(_x, _x2) { return _submitAuthDict.apply(this, arguments); } return submitAuthDict; }(), /** * Gets the sid for the email validation session * Specific to m.login.email.identity * * @returns {string} The sid of the email auth session */ getEmailSid: function getEmailSid() { return this._emailSid; }, /** * Sets the sid for the email validation session * This must be set in order to successfully poll for completion * of the email validation. * Specific to m.login.email.identity * * @param {string} sid The sid for the email validation session */ setEmailSid: function setEmailSid(sid) { this._emailSid = sid; }, /** * Fire off a request, and either resolve the promise, or call * startAuthStage. * * @private * @param {object?} auth new auth dict, including session id * @param {bool?} background If true, this request is a background poll, so it * failing will not result in the attemptAuth promise being rejected. * This can be set to true for requests that just poll to see if auth has * been completed elsewhere. */ _doRequest: function () { var _doRequest2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(auth, background) { var result, errorFlows, haveFlows, requestTokenResult; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.prev = 0; _context3.next = 3; return this._requestCallback(auth, background); case 3: result = _context3.sent; this._resolveFunc(result); this._resolveFunc = null; this._rejectFunc = null; _context3.next = 34; break; case 9: _context3.prev = 9; _context3.t0 = _context3["catch"](0); // sometimes UI auth errors don't come with flows errorFlows = _context3.t0.data ? _context3.t0.data.flows : null; haveFlows = this._data.flows || Boolean(errorFlows); if (_context3.t0.httpStatus !== 401 || !_context3.t0.data || !haveFlows) { // doesn't look like an interactive-auth failure. if (!background) { this._rejectFunc(_context3.t0); } else { // We ignore all failures here (even non-UI auth related ones) // since we don't want to suddenly fail if the internet connection // had a blip whilst we were polling _logger.logger.log("Background poll request failed doing UI auth: ignoring", _context3.t0); } } // if the error didn't come with flows, completed flows or session ID, // copy over the ones we have. Synapse sometimes sends responses without // any UI auth data (eg. when polling for email validation, if the email // has not yet been validated). This appears to be a Synapse bug, which // we workaround here. if (!_context3.t0.data.flows && !_context3.t0.data.completed && !_context3.t0.data.session) { _context3.t0.data.flows = this._data.flows; _context3.t0.data.completed = this._data.completed; _context3.t0.data.session = this._data.session; } this._data = _context3.t0.data; try { this._startNextAuthStage(); } catch (e) { this._rejectFunc(e); this._resolveFunc = null; this._rejectFunc = null; } if (!(!this._emailSid && !this._requestingEmailToken && this._chosenFlow.stages.includes('m.login.email.identity'))) { _context3.next = 34; break; } // If we've picked a flow with email auth, we send the email // now because we want the request to fail as soon as possible // if the email address is not valid (ie. already taken or not // registered, depending on what the operation is). this._requestingEmailToken = true; _context3.prev = 19; _context3.next = 22; return this._requestEmailTokenCallback(this._inputs.emailAddress, this._clientSecret, 1, // TODO: Multiple send attempts? this._data.session); case 22: requestTokenResult = _context3.sent; this._emailSid = requestTokenResult.sid; // NB. promise is not resolved here - at some point, doRequest // will be called again and if the user has jumped through all // the hoops correctly, auth will be complete and the request // will succeed. // Also, we should expose the fact that this request has compledted // so clients can know that the email has actually been sent. _context3.next = 31; break; case 26: _context3.prev = 26; _context3.t1 = _context3["catch"](19); // we failed to request an email token, so fail the request. // This could be due to the email already beeing registered // (or not being registered, depending on what we're trying // to do) or it could be a network failure. Either way, pass // the failure up as the user can't complete auth if we can't // send the email, for whatever reason. this._rejectFunc(_context3.t1); this._resolveFunc = null; this._rejectFunc = null; case 31: _context3.prev = 31; this._requestingEmailToken = false; return _context3.finish(31); case 34: case "end": return _context3.stop(); } } }, _callee3, this, [[0, 9], [19, 26, 31, 34]]); })); function _doRequest(_x3, _x4) { return _doRequest2.apply(this, arguments); } return _doRequest; }(), /** * Pick the next stage and call the callback * * @private * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found */ _startNextAuthStage: function _startNextAuthStage() { var nextStage = this._chooseStage(); if (!nextStage) { throw new Error("No incomplete flows from the server"); } this._currentStage = nextStage; if (nextStage === 'm.login.dummy') { this.submitAuthDict({ type: 'm.login.dummy' }); return; } if (this._data && this._data.errcode || this._data.error) { this._stateUpdatedCallback(nextStage, { errcode: this._data.errcode || "", error: this._data.error || "" }); return; } var stageStatus = {}; if (nextStage == EMAIL_STAGE_TYPE) { stageStatus.emailSid = this._emailSid; } this._stateUpdatedCallback(nextStage, stageStatus); }, /** * Pick the next auth stage * * @private * @return {string?} login type * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found */ _chooseStage: function _chooseStage() { if (this._chosenFlow === null) { this._chosenFlow = this._chooseFlow(); } _logger.logger.log("Active flow => %s", JSON.stringify(this._chosenFlow)); var nextStage = this._firstUncompletedStage(this._chosenFlow); _logger.logger.log("Next stage: %s", nextStage); return nextStage; }, /** * Pick one of the flows from the returned list * If a flow using all of the inputs is found, it will * be returned, otherwise, null will be returned. * * Only flows using all given inputs are chosen because it * is likley to be surprising if the user provides a * credential and it is not used. For example, for registration, * this could result in the email not being used which would leave * the account with no means to reset a password. * * @private * @return {object} flow * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found */ _chooseFlow: function _chooseFlow() { var flows = this._data.flows || []; // we've been given an email or we've already done an email part var haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid); var haveMsisdn = Boolean(this._inputs.phoneCountry) && Boolean(this._inputs.phoneNumber); var _iterator = _createForOfIteratorHelper(flows), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var flow = _step.value; var flowHasEmail = false; var flowHasMsisdn = false; var _iterator2 = _createForOfIteratorHelper(flow.stages), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var stage = _step2.value; if (stage === EMAIL_STAGE_TYPE) { flowHasEmail = true; } else if (stage == MSISDN_STAGE_TYPE) { flowHasMsisdn = true; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) { return flow; } } // Throw an error with a fairly generic description, but with more // information such that the app can give a better one if so desired. } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var err = new Error("No appropriate authentication flow found"); err.name = 'NoAuthFlowFoundError'; err.required_stages = []; if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE); if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE); err.available_flows = flows; throw err; }, /** * Get the first uncompleted stage in the given flow * * @private * @param {object} flow * @return {string} login type */ _firstUncompletedStage: function _firstUncompletedStage(flow) { var completed = (this._data || {}).completed || []; for (var i = 0; i < flow.stages.length; ++i) { var stageType = flow.stages[i]; if (completed.indexOf(stageType) === -1) { return stageType; } } } }; },{"./logger":95,"./utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27,"url":51}],95:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.logger = void 0; var _loglevel = _interopRequireDefault(require("loglevel")); /* Copyright 2018 André Jaenisch Copyright 2019 The Matrix.org Foundation C.I.C. 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 logger */ // This is to demonstrate, that you can use any namespace you want. // Namespaces allow you to turn on/off the logging for specific parts of the // application. // An idea would be to control this via an environment variable (on Node.js). // See https://www.npmjs.com/package/debug to see how this could be implemented // Part of #332 is introducing a logging library in the first place. var DEFAULT_NAMESPACE = "matrix"; // because rageshakes in react-sdk hijack the console log, also at module load time, // initializing the logger here races with the initialization of rageshakes. // to avoid the issue, we override the methodFactory of loglevel that binds to the // console methods at initialization time by a factory that looks up the console methods // when logging so we always get the current value of console methods. _loglevel["default"].methodFactory = function (methodName, logLevel, loggerName) { return function () { var supportedByConsole = methodName === "error" || methodName === "warn" || methodName === "trace" || methodName === "info"; if (supportedByConsole) { var _console; return (_console = console)[methodName].apply(_console, arguments); } else { var _console2; return (_console2 = console).log.apply(_console2, arguments); } }; }; /** * Drop-in replacement for console using {@link https://www.npmjs.com/package/loglevel|loglevel}. * Can be tailored down to specific use cases if needed. */ var logger = _loglevel["default"].getLogger(DEFAULT_NAMESPACE); exports.logger = logger; logger.setLevel(_loglevel["default"].levels.DEBUG); },{"@babel/runtime/helpers/interopRequireDefault":12,"loglevel":38}],96:[function(require,module,exports){ (function (global){ "use strict"; /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createClient = exports.setCryptoStoreFactory = exports.wrapRequest = exports.getRequest = exports.request = exports.ContentHelpers = void 0; const memory_crypto_store_1 = require("./crypto/store/memory-crypto-store"); const memory_1 = require("./store/memory"); const scheduler_1 = require("./scheduler"); const client_1 = require("./client"); __exportStar(require("./client"), exports); __exportStar(require("./http-api"), exports); __exportStar(require("./autodiscovery"), exports); __exportStar(require("./sync-accumulator"), exports); __exportStar(require("./errors"), exports); __exportStar(require("./models/event"), exports); __exportStar(require("./models/room"), exports); __exportStar(require("./models/group"), exports); __exportStar(require("./models/event-timeline"), exports); __exportStar(require("./models/event-timeline-set"), exports); __exportStar(require("./models/room-member"), exports); __exportStar(require("./models/room-state"), exports); __exportStar(require("./models/user"), exports); __exportStar(require("./scheduler"), exports); __exportStar(require("./filter"), exports); __exportStar(require("./timeline-window"), exports); __exportStar(require("./interactive-auth"), exports); __exportStar(require("./service-types"), exports); __exportStar(require("./store/memory"), exports); __exportStar(require("./store/indexeddb"), exports); __exportStar(require("./store/session/webstorage"), exports); __exportStar(require("./crypto/store/memory-crypto-store"), exports); __exportStar(require("./crypto/store/indexeddb-crypto-store"), exports); __exportStar(require("./content-repo"), exports); exports.ContentHelpers = Promise.resolve().then(() => __importStar(require("./content-helpers"))); var call_1 = require("./webrtc/call"); Object.defineProperty(exports, "createNewMatrixCall", { enumerable: true, get: function () { return call_1.createNewMatrixCall; } }); Object.defineProperty(exports, "setMatrixCallAudioOutput", { enumerable: true, get: function () { return call_1.setAudioOutput; } }); Object.defineProperty(exports, "setMatrixCallAudioInput", { enumerable: true, get: function () { return call_1.setAudioInput; } }); Object.defineProperty(exports, "setMatrixCallVideoInput", { enumerable: true, get: function () { return call_1.setVideoInput; } }); // expose the underlying request object so different environments can use // different request libs (e.g. request or browser-request) let requestInstance; /** * The function used to perform HTTP requests. Only use this if you want to * use a different HTTP library, e.g. Angular's $http. This should * be set prior to calling {@link createClient}. * @param {requestFunction} r The request function to use. */ function request(r) { requestInstance = r; } exports.request = request; /** * Return the currently-set request function. * @return {requestFunction} The current request function. */ function getRequest() { return requestInstance; } exports.getRequest = getRequest; /** * Apply wrapping code around the request function. The wrapper function is * installed as the new request handler, and when invoked it is passed the * previous value, along with the options and callback arguments. * @param {requestWrapperFunction} wrapper The wrapping function. */ function wrapRequest(wrapper) { const origRequest = requestInstance; requestInstance = function (options, callback) { return wrapper(origRequest, options, callback); }; } exports.wrapRequest = wrapRequest; let cryptoStoreFactory = () => new memory_crypto_store_1.MemoryCryptoStore; /** * Configure a different factory to be used for creating crypto stores * * @param {Function} fac a function which will return a new * {@link module:crypto.store.base~CryptoStore}. */ function setCryptoStoreFactory(fac) { cryptoStoreFactory = fac; } exports.setCryptoStoreFactory = setCryptoStoreFactory; /** * Construct a Matrix Client. Similar to {@link module:client.MatrixClient} * except that the 'request', 'store' and 'scheduler' dependencies are satisfied. * @param {(Object|string)} opts The configuration options for this client. If * this is a string, it is assumed to be the base URL. These configuration * options will be passed directly to {@link module:client.MatrixClient}. * @param {Object} opts.store If not set, defaults to * {@link module:store/memory.MemoryStore}. * @param {Object} opts.scheduler If not set, defaults to * {@link module:scheduler~MatrixScheduler}. * @param {requestFunction} opts.request If not set, defaults to the function * supplied to {@link request} which defaults to the request module from NPM. * * @param {module:crypto.store.base~CryptoStore=} opts.cryptoStore * crypto store implementation. Calls the factory supplied to * {@link setCryptoStoreFactory} if unspecified; or if no factory has been * specified, uses a default implementation (indexeddb in the browser, * in-memory otherwise). * * @return {MatrixClient} A new matrix client. * @see {@link module:client.MatrixClient} for the full list of options for * opts. */ function createClient(opts) { if (typeof opts === "string") { opts = { "baseUrl": opts, }; } opts.request = opts.request || requestInstance; opts.store = opts.store || new memory_1.MemoryStore({ localStorage: global.localStorage, }); opts.scheduler = opts.scheduler || new scheduler_1.MatrixScheduler(); opts.cryptoStore = opts.cryptoStore || cryptoStoreFactory(); return new client_1.MatrixClient(opts); } exports.createClient = createClient; /** * The request function interface for performing HTTP requests. This matches the * API for the {@link https://github.com/request/request#requestoptions-callback| * request NPM module}. The SDK will attempt to call this function in order to * perform an HTTP request. * @callback requestFunction * @param {Object} opts The options for this HTTP request. * @param {string} opts.uri The complete URI. * @param {string} opts.method The HTTP method. * @param {Object} opts.qs The query parameters to append to the URI. * @param {Object} opts.body The JSON-serializable object. * @param {boolean} opts.json True if this is a JSON request. * @param {Object} opts._matrix_opts The underlying options set for * {@link MatrixHttpApi}. * @param {requestCallback} callback The request callback. */ /** * A wrapper for the request function interface. * @callback requestWrapperFunction * @param {requestFunction} origRequest The underlying request function being * wrapped * @param {Object} opts The options for this HTTP request, given in the same * form as {@link requestFunction}. * @param {requestCallback} callback The request callback. */ /** * The request callback interface for performing HTTP requests. This matches the * API for the {@link https://github.com/request/request#requestoptions-callback| * request NPM module}. The SDK will implement a callback which meets this * interface in order to handle the HTTP response. * @callback requestCallback * @param {Error} err The error if one occurred, else falsey. * @param {Object} response The HTTP response which consists of * {statusCode: {Number}, headers: {Object}} * @param {Object} body The parsed HTTP response body. */ }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./autodiscovery":54,"./client":57,"./content-helpers":58,"./content-repo":59,"./crypto/store/indexeddb-crypto-store":78,"./crypto/store/memory-crypto-store":80,"./errors":89,"./filter":91,"./http-api":92,"./interactive-auth":94,"./models/event":100,"./models/event-timeline":99,"./models/event-timeline-set":98,"./models/group":101,"./models/room":106,"./models/room-member":103,"./models/room-state":104,"./models/user":108,"./scheduler":112,"./service-types":113,"./store/indexeddb":116,"./store/memory":117,"./store/session/webstorage":118,"./sync-accumulator":120,"./timeline-window":122,"./webrtc/call":124}],97:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventContext = EventContext; /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/event-context */ /** * Construct a new EventContext * * An eventcontext is used for circumstances such as search results, when we * have a particular event of interest, and a bunch of events before and after * it. * * It also stores pagination tokens for going backwards and forwards in the * timeline. * * @param {MatrixEvent} ourEvent the event at the centre of this context * * @constructor */ function EventContext(ourEvent) { this._timeline = [ourEvent]; this._ourEventIndex = 0; this._paginateTokens = { b: null, f: null }; // this is used by MatrixClient to keep track of active requests this._paginateRequests = { b: null, f: null }; } /** * Get the main event of interest * * This is a convenience function for getTimeline()[getOurEventIndex()]. * * @return {MatrixEvent} The event at the centre of this context. */ EventContext.prototype.getEvent = function () { return this._timeline[this._ourEventIndex]; }; /** * Get the list of events in this context * * @return {Array} An array of MatrixEvents */ EventContext.prototype.getTimeline = function () { return this._timeline; }; /** * Get the index in the timeline of our event * * @return {Number} */ EventContext.prototype.getOurEventIndex = function () { return this._ourEventIndex; }; /** * Get a pagination token. * * @param {boolean} backwards true to get the pagination token for going * backwards in time * @return {string} */ EventContext.prototype.getPaginateToken = function (backwards) { return this._paginateTokens[backwards ? 'b' : 'f']; }; /** * Set a pagination token. * * Generally this will be used only by the matrix js sdk. * * @param {string} token pagination token * @param {boolean} backwards true to set the pagination token for going * backwards in time */ EventContext.prototype.setPaginateToken = function (token, backwards) { this._paginateTokens[backwards ? 'b' : 'f'] = token; }; /** * Add more events to the timeline * * @param {Array} events new events, in timeline order * @param {boolean} atStart true to insert new events at the start */ EventContext.prototype.addEvents = function (events, atStart) { // TODO: should we share logic with Room.addEventsToTimeline? // Should Room even use EventContext? if (atStart) { this._timeline = events.concat(this._timeline); this._ourEventIndex += events.length; } else { this._timeline = this._timeline.concat(events); } }; },{}],98:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.EventTimelineSet = EventTimelineSet; var _events = require("events"); var _eventTimeline = require("./event-timeline"); var _event = require("./event"); var utils = _interopRequireWildcard(require("../utils")); var _logger = require("../logger"); var _relations = require("./relations"); /* Copyright 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/event-timeline-set */ // var DEBUG = false; var DEBUG = true; var debuglog; if (DEBUG) { // using bind means that we get to keep useful line numbers in the console debuglog = _logger.logger.log.bind(_logger.logger); } else { debuglog = function debuglog() {}; } /** * Construct a set of EventTimeline objects, typically on behalf of a given * room. A room may have multiple EventTimelineSets for different levels * of filtering. The global notification list is also an EventTimelineSet, but * lacks a room. * *

This is an ordered sequence of timelines, which may or may not * be continuous. Each timeline lists a series of events, as well as tracking * the room state at the start and the end of the timeline (if appropriate). * It also tracks forward and backward pagination tokens, as well as containing * links to the next timeline in the sequence. * *

There is one special timeline - the 'live' timeline, which represents the * timeline to which events are being added in real-time as they are received * from the /sync API. Note that you should not retain references to this * timeline - even if it is the current timeline right now, it may not remain * so if the server gives us a timeline gap in /sync. * *

In order that we can find events from their ids later, we also maintain a * map from event_id to timeline and index. * * @constructor * @param {?Room} room * Room for this timelineSet. May be null for non-room cases, such as the * notification timeline. * @param {Object} opts Options inherited from Room. * * @param {boolean} [opts.timelineSupport = false] * Set to true to enable improved timeline support. * @param {Object} [opts.filter = null] * The filter object, if any, for this timelineSet. * @param {boolean} [opts.unstableClientRelationAggregation = false] * Optional. Set to true to enable client-side aggregation of event relations * via `getRelationsForEvent`. * This feature is currently unstable and the API may change without notice. */ function EventTimelineSet(room, opts) { this.room = room; this._timelineSupport = Boolean(opts.timelineSupport); this._liveTimeline = new _eventTimeline.EventTimeline(this); this._unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation; // just a list - *not* ordered. this._timelines = [this._liveTimeline]; this._eventIdToTimeline = {}; this._filter = opts.filter || null; if (this._unstableClientRelationAggregation) { // A tree of objects to access a set of relations for an event, as in: // this._relations[relatesToEventId][relationType][relationEventType] this._relations = {}; } } utils.inherits(EventTimelineSet, _events.EventEmitter); /** * Get all the timelines in this set * @return {module:models/event-timeline~EventTimeline[]} the timelines in this set */ EventTimelineSet.prototype.getTimelines = function () { return this._timelines; }; /** * Get the filter object this timeline set is filtered on, if any * @return {?Filter} the optional filter for this timelineSet */ EventTimelineSet.prototype.getFilter = function () { return this._filter; }; /** * Set the filter object this timeline set is filtered on * (passed to the server when paginating via /messages). * @param {Filter} filter the filter for this timelineSet */ EventTimelineSet.prototype.setFilter = function (filter) { this._filter = filter; }; /** * Get the list of pending sent events for this timelineSet's room, filtered * by the timelineSet's filter if appropriate. * * @return {module:models/event.MatrixEvent[]} A list of the sent events * waiting for remote echo. * * @throws If opts.pendingEventOrdering was not 'detached' */ EventTimelineSet.prototype.getPendingEvents = function () { if (!this.room) { return []; } if (this._filter) { return this._filter.filterRoomTimeline(this.room.getPendingEvents()); } else { return this.room.getPendingEvents(); } }; /** * Get the live timeline for this room. * * @return {module:models/event-timeline~EventTimeline} live timeline */ EventTimelineSet.prototype.getLiveTimeline = function () { return this._liveTimeline; }; /** * Return the timeline (if any) this event is in. * @param {String} eventId the eventId being sought * @return {module:models/event-timeline~EventTimeline} timeline */ EventTimelineSet.prototype.eventIdToTimeline = function (eventId) { return this._eventIdToTimeline[eventId]; }; /** * Track a new event as if it were in the same timeline as an old event, * replacing it. * @param {String} oldEventId event ID of the original event * @param {String} newEventId event ID of the replacement event */ EventTimelineSet.prototype.replaceEventId = function (oldEventId, newEventId) { var existingTimeline = this._eventIdToTimeline[oldEventId]; if (existingTimeline) { delete this._eventIdToTimeline[oldEventId]; this._eventIdToTimeline[newEventId] = existingTimeline; } }; /** * Reset the live timeline, and start a new one. * *

This is used when /sync returns a 'limited' timeline. * * @param {string=} backPaginationToken token for back-paginating the new timeline * @param {string=} forwardPaginationToken token for forward-paginating the old live timeline, * if absent or null, all timelines are reset. * * @fires module:client~MatrixClient#event:"Room.timelineReset" */ EventTimelineSet.prototype.resetLiveTimeline = function (backPaginationToken, forwardPaginationToken) { // Each EventTimeline has RoomState objects tracking the state at the start // and end of that timeline. The copies at the end of the live timeline are // special because they will have listeners attached to monitor changes to // the current room state, so we move this RoomState from the end of the // current live timeline to the end of the new one and, if necessary, // replace it with a newly created one. We also make a copy for the start // of the new timeline. // if timeline support is disabled, forget about the old timelines var resetAllTimelines = !this._timelineSupport || !forwardPaginationToken; var oldTimeline = this._liveTimeline; var newTimeline = resetAllTimelines ? oldTimeline.forkLive(_eventTimeline.EventTimeline.FORWARDS) : oldTimeline.fork(_eventTimeline.EventTimeline.FORWARDS); if (resetAllTimelines) { this._timelines = [newTimeline]; this._eventIdToTimeline = {}; } else { this._timelines.push(newTimeline); } if (forwardPaginationToken) { // Now set the forward pagination token on the old live timeline // so it can be forward-paginated. oldTimeline.setPaginationToken(forwardPaginationToken, _eventTimeline.EventTimeline.FORWARDS); } // make sure we set the pagination token before firing timelineReset, // otherwise clients which start back-paginating will fail, and then get // stuck without realising that they *can* back-paginate. newTimeline.setPaginationToken(backPaginationToken, _eventTimeline.EventTimeline.BACKWARDS); // Now we can swap the live timeline to the new one. this._liveTimeline = newTimeline; this.emit("Room.timelineReset", this.room, this, resetAllTimelines); }; /** * Get the timeline which contains the given event, if any * * @param {string} eventId event ID to look for * @return {?module:models/event-timeline~EventTimeline} timeline containing * the given event, or null if unknown */ EventTimelineSet.prototype.getTimelineForEvent = function (eventId) { var res = this._eventIdToTimeline[eventId]; return res === undefined ? null : res; }; /** * Get an event which is stored in our timelines * * @param {string} eventId event ID to look for * @return {?module:models/event~MatrixEvent} the given event, or undefined if unknown */ EventTimelineSet.prototype.findEventById = function (eventId) { var tl = this.getTimelineForEvent(eventId); if (!tl) { return undefined; } return utils.findElement(tl.getEvents(), function (ev) { return ev.getId() == eventId; }); }; /** * Add a new timeline to this timeline list * * @return {module:models/event-timeline~EventTimeline} newly-created timeline */ EventTimelineSet.prototype.addTimeline = function () { if (!this._timelineSupport) { throw new Error("timeline support is disabled. Set the 'timelineSupport'" + " parameter to true when creating MatrixClient to enable" + " it."); } var timeline = new _eventTimeline.EventTimeline(this); this._timelines.push(timeline); return timeline; }; /** * Add events to a timeline * *

Will fire "Room.timeline" for each event added. * * @param {MatrixEvent[]} events A list of events to add. * * @param {boolean} toStartOfTimeline True to add these events to the start * (oldest) instead of the end (newest) of the timeline. If true, the oldest * event will be the last element of 'events'. * * @param {module:models/event-timeline~EventTimeline} timeline timeline to * add events to. * * @param {string=} paginationToken token for the next batch of events * * @fires module:client~MatrixClient#event:"Room.timeline" * */ EventTimelineSet.prototype.addEventsToTimeline = function (events, toStartOfTimeline, timeline, paginationToken) { if (!timeline) { throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline"); } if (!toStartOfTimeline && timeline == this._liveTimeline) { throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to " + "the live timeline - use Room.addLiveEvents instead"); } if (this._filter) { events = this._filter.filterRoomTimeline(events); if (!events.length) { return; } } var direction = toStartOfTimeline ? _eventTimeline.EventTimeline.BACKWARDS : _eventTimeline.EventTimeline.FORWARDS; var inverseDirection = toStartOfTimeline ? _eventTimeline.EventTimeline.FORWARDS : _eventTimeline.EventTimeline.BACKWARDS; // Adding events to timelines can be quite complicated. The following // illustrates some of the corner-cases. // // Let's say we start by knowing about four timelines. timeline3 and // timeline4 are neighbours: // // timeline1 timeline2 timeline3 timeline4 // [M] [P] [S] <------> [T] // // Now we paginate timeline1, and get the following events from the server: // [M, N, P, R, S, T, U]. // // 1. First, we ignore event M, since we already know about it. // // 2. Next, we append N to timeline 1. // // 3. Next, we don't add event P, since we already know about it, // but we do link together the timelines. We now have: // // timeline1 timeline2 timeline3 timeline4 // [M, N] <---> [P] [S] <------> [T] // // 4. Now we add event R to timeline2: // // timeline1 timeline2 timeline3 timeline4 // [M, N] <---> [P, R] [S] <------> [T] // // Note that we have switched the timeline we are working on from // timeline1 to timeline2. // // 5. We ignore event S, but again join the timelines: // // timeline1 timeline2 timeline3 timeline4 // [M, N] <---> [P, R] <---> [S] <------> [T] // // 6. We ignore event T, and the timelines are already joined, so there // is nothing to do. // // 7. Finally, we add event U to timeline4: // // timeline1 timeline2 timeline3 timeline4 // [M, N] <---> [P, R] <---> [S] <------> [T, U] // // The important thing to note in the above is what happened when we // already knew about a given event: // // - if it was appropriate, we joined up the timelines (steps 3, 5). // - in any case, we started adding further events to the timeline which // contained the event we knew about (steps 3, 5, 6). // // // So much for adding events to the timeline. But what do we want to do // with the pagination token? // // In the case above, we will be given a pagination token which tells us how to // get events beyond 'U' - in this case, it makes sense to store this // against timeline4. But what if timeline4 already had 'U' and beyond? in // that case, our best bet is to throw away the pagination token we were // given and stick with whatever token timeline4 had previously. In short, // we want to only store the pagination token if the last event we receive // is one we didn't previously know about. // // We make an exception for this if it turns out that we already knew about // *all* of the events, and we weren't able to join up any timelines. When // that happens, it means our existing pagination token is faulty, since it // is only telling us what we already know. Rather than repeatedly // paginating with the same token, we might as well use the new pagination // token in the hope that we eventually work our way out of the mess. var didUpdate = false; var lastEventWasNew = false; for (var i = 0; i < events.length; i++) { var event = events[i]; var eventId = event.getId(); var existingTimeline = this._eventIdToTimeline[eventId]; if (!existingTimeline) { // we don't know about this event yet. Just add it to the timeline. this.addEventToTimeline(event, timeline, toStartOfTimeline); lastEventWasNew = true; didUpdate = true; continue; } lastEventWasNew = false; if (existingTimeline == timeline) { debuglog("Event " + eventId + " already in timeline " + timeline); continue; } var neighbour = timeline.getNeighbouringTimeline(direction); if (neighbour) { // this timeline already has a neighbour in the relevant direction; // let's assume the timelines are already correctly linked up, and // skip over to it. // // there's probably some edge-case here where we end up with an // event which is in a timeline a way down the chain, and there is // a break in the chain somewhere. But I can't really imagine how // that would happen, so I'm going to ignore it for now. // if (existingTimeline == neighbour) { debuglog("Event " + eventId + " in neighbouring timeline - " + "switching to " + existingTimeline); } else { debuglog("Event " + eventId + " already in a different " + "timeline " + existingTimeline); } timeline = existingTimeline; continue; } // time to join the timelines. _logger.logger.info("Already have timeline for " + eventId + " - joining timeline " + timeline + " to " + existingTimeline); // Variables to keep the line length limited below. var existingIsLive = existingTimeline === this._liveTimeline; var timelineIsLive = timeline === this._liveTimeline; var backwardsIsLive = direction === _eventTimeline.EventTimeline.BACKWARDS && existingIsLive; var forwardsIsLive = direction === _eventTimeline.EventTimeline.FORWARDS && timelineIsLive; if (backwardsIsLive || forwardsIsLive) { // The live timeline should never be spliced into a non-live position. // We use independent logging to better discover the problem at a glance. if (backwardsIsLive) { _logger.logger.warn("Refusing to set a preceding existingTimeLine on our " + "timeline as the existingTimeLine is live (" + existingTimeline + ")"); } if (forwardsIsLive) { _logger.logger.warn("Refusing to set our preceding timeline on a existingTimeLine " + "as our timeline is live (" + timeline + ")"); } continue; // abort splicing - try next event } timeline.setNeighbouringTimeline(existingTimeline, direction); existingTimeline.setNeighbouringTimeline(timeline, inverseDirection); timeline = existingTimeline; didUpdate = true; } // see above - if the last event was new to us, or if we didn't find any // new information, we update the pagination token for whatever // timeline we ended up on. if (lastEventWasNew || !didUpdate) { if (direction === _eventTimeline.EventTimeline.FORWARDS && timeline === this._liveTimeline) { _logger.logger.warn({ lastEventWasNew: lastEventWasNew, didUpdate: didUpdate }); // for debugging _logger.logger.warn("Refusing to set forwards pagination token of live timeline " + "".concat(timeline, " to ").concat(paginationToken)); return; } timeline.setPaginationToken(paginationToken, direction); } }; /** * Add an event to the end of this live timeline. * * @param {MatrixEvent} event Event to be added * @param {string?} duplicateStrategy 'ignore' or 'replace' * @param {boolean} fromCache whether the sync response came from cache */ EventTimelineSet.prototype.addLiveEvent = function (event, duplicateStrategy, fromCache) { if (this._filter) { var events = this._filter.filterRoomTimeline([event]); if (!events.length) { return; } } var timeline = this._eventIdToTimeline[event.getId()]; if (timeline) { if (duplicateStrategy === "replace") { debuglog("EventTimelineSet.addLiveEvent: replacing duplicate event " + event.getId()); var tlEvents = timeline.getEvents(); for (var j = 0; j < tlEvents.length; j++) { if (tlEvents[j].getId() === event.getId()) { // still need to set the right metadata on this event _eventTimeline.EventTimeline.setEventMetadata(event, timeline.getState(_eventTimeline.EventTimeline.FORWARDS), false); if (!tlEvents[j].encryptedType) { tlEvents[j] = event; } // XXX: we need to fire an event when this happens. break; } } } else { debuglog("EventTimelineSet.addLiveEvent: ignoring duplicate event " + event.getId()); } return; } this.addEventToTimeline(event, this._liveTimeline, false, fromCache); }; /** * Add event to the given timeline, and emit Room.timeline. Assumes * we have already checked we don't know about this event. * * Will fire "Room.timeline" for each event added. * * @param {MatrixEvent} event * @param {EventTimeline} timeline * @param {boolean} toStartOfTimeline * @param {boolean} fromCache whether the sync response came from cache * * @fires module:client~MatrixClient#event:"Room.timeline" */ EventTimelineSet.prototype.addEventToTimeline = function (event, timeline, toStartOfTimeline, fromCache) { var eventId = event.getId(); timeline.addEvent(event, toStartOfTimeline); this._eventIdToTimeline[eventId] = timeline; this.setRelationsTarget(event); this.aggregateRelations(event); var data = { timeline: timeline, liveEvent: !toStartOfTimeline && timeline == this._liveTimeline && !fromCache }; this.emit("Room.timeline", event, this.room, Boolean(toStartOfTimeline), false, data); }; /** * Replaces event with ID oldEventId with one with newEventId, if oldEventId is * recognised. Otherwise, add to the live timeline. Used to handle remote echos. * * @param {MatrixEvent} localEvent the new event to be added to the timeline * @param {String} oldEventId the ID of the original event * @param {boolean} newEventId the ID of the replacement event * * @fires module:client~MatrixClient#event:"Room.timeline" */ EventTimelineSet.prototype.handleRemoteEcho = function (localEvent, oldEventId, newEventId) { // XXX: why don't we infer newEventId from localEvent? var existingTimeline = this._eventIdToTimeline[oldEventId]; if (existingTimeline) { delete this._eventIdToTimeline[oldEventId]; this._eventIdToTimeline[newEventId] = existingTimeline; } else { if (this._filter) { if (this._filter.filterRoomTimeline([localEvent]).length) { this.addEventToTimeline(localEvent, this._liveTimeline, false); } } else { this.addEventToTimeline(localEvent, this._liveTimeline, false); } } }; /** * Removes a single event from this room. * * @param {String} eventId The id of the event to remove * * @return {?MatrixEvent} the removed event, or null if the event was not found * in this room. */ EventTimelineSet.prototype.removeEvent = function (eventId) { var timeline = this._eventIdToTimeline[eventId]; if (!timeline) { return null; } var removed = timeline.removeEvent(eventId); if (removed) { delete this._eventIdToTimeline[eventId]; var data = { timeline: timeline }; this.emit("Room.timeline", removed, this.room, undefined, true, data); } return removed; }; /** * Determine where two events appear in the timeline relative to one another * * @param {string} eventId1 The id of the first event * @param {string} eventId2 The id of the second event * @return {?number} a number less than zero if eventId1 precedes eventId2, and * greater than zero if eventId1 succeeds eventId2. zero if they are the * same event; null if we can't tell (either because we don't know about one * of the events, or because they are in separate timelines which don't join * up). */ EventTimelineSet.prototype.compareEventOrdering = function (eventId1, eventId2) { if (eventId1 == eventId2) { // optimise this case return 0; } var timeline1 = this._eventIdToTimeline[eventId1]; var timeline2 = this._eventIdToTimeline[eventId2]; if (timeline1 === undefined) { return null; } if (timeline2 === undefined) { return null; } if (timeline1 === timeline2) { // both events are in the same timeline - figure out their // relative indices var idx1; var idx2; var events = timeline1.getEvents(); for (var idx = 0; idx < events.length && (idx1 === undefined || idx2 === undefined); idx++) { var evId = events[idx].getId(); if (evId == eventId1) { idx1 = idx; } if (evId == eventId2) { idx2 = idx; } } return idx1 - idx2; } // the events are in different timelines. Iterate through the // linkedlist to see which comes first. // first work forwards from timeline1 var tl = timeline1; while (tl) { if (tl === timeline2) { // timeline1 is before timeline2 return -1; } tl = tl.getNeighbouringTimeline(_eventTimeline.EventTimeline.FORWARDS); } // now try backwards from timeline1 tl = timeline1; while (tl) { if (tl === timeline2) { // timeline2 is before timeline1 return 1; } tl = tl.getNeighbouringTimeline(_eventTimeline.EventTimeline.BACKWARDS); } // the timelines are not contiguous. return null; }; /** * Get a collection of relations to a given event in this timeline set. * * @param {String} eventId * The ID of the event that you'd like to access relation events for. * For example, with annotations, this would be the ID of the event being annotated. * @param {String} relationType * The type of relation involved, such as "m.annotation", "m.reference", "m.replace", etc. * @param {String} eventType * The relation event's type, such as "m.reaction", etc. * @throws If eventId, relationType or eventType * are not valid. * * @returns {?Relations} * A container for relation events or undefined if there are no relation events for * the relationType. */ EventTimelineSet.prototype.getRelationsForEvent = function (eventId, relationType, eventType) { if (!this._unstableClientRelationAggregation) { throw new Error("Client-side relation aggregation is disabled"); } if (!eventId || !relationType || !eventType) { throw new Error("Invalid arguments for `getRelationsForEvent`"); } // debuglog("Getting relations for: ", eventId, relationType, eventType); var relationsForEvent = this._relations[eventId] || {}; var relationsWithRelType = relationsForEvent[relationType] || {}; return relationsWithRelType[eventType]; }; /** * Set an event as the target event if any Relations exist for it already * * @param {MatrixEvent} event * The event to check as relation target. */ EventTimelineSet.prototype.setRelationsTarget = function (event) { if (!this._unstableClientRelationAggregation) { return; } var relationsForEvent = this._relations[event.getId()]; if (!relationsForEvent) { return; } // don't need it for non m.replace relations for now var relationsWithRelType = relationsForEvent["m.replace"]; if (!relationsWithRelType) { return; } // only doing replacements for messages for now (e.g. edits) var relationsWithEventType = relationsWithRelType["m.room.message"]; if (relationsWithEventType) { relationsWithEventType.setTargetEvent(event); } }; /** * Add relation events to the relevant relation collection. * * @param {MatrixEvent} event * The new relation event to be aggregated. */ EventTimelineSet.prototype.aggregateRelations = function (event) { var _this = this; if (!this._unstableClientRelationAggregation) { return; } if (event.isRedacted() || event.status === _event.EventStatus.CANCELLED) { return; } // If the event is currently encrypted, wait until it has been decrypted. if (event.isBeingDecrypted()) { event.once("Event.decrypted", function () { _this.aggregateRelations(event); }); return; } var relation = event.getRelation(); if (!relation) { return; } var relatesToEventId = relation.event_id; var relationType = relation.rel_type; var eventType = event.getType(); // debuglog("Aggregating relation: ", event.getId(), eventType, relation); var relationsForEvent = this._relations[relatesToEventId]; if (!relationsForEvent) { relationsForEvent = this._relations[relatesToEventId] = {}; } var relationsWithRelType = relationsForEvent[relationType]; if (!relationsWithRelType) { relationsWithRelType = relationsForEvent[relationType] = {}; } var relationsWithEventType = relationsWithRelType[eventType]; var isNewRelations = false; var relatesToEvent; if (!relationsWithEventType) { relationsWithEventType = relationsWithRelType[eventType] = new _relations.Relations(relationType, eventType, this.room); isNewRelations = true; relatesToEvent = this.findEventById(relatesToEventId); if (relatesToEvent) { relationsWithEventType.setTargetEvent(relatesToEvent); } } relationsWithEventType.addEvent(event); // only emit once event has been added to relations if (isNewRelations && relatesToEvent) { relatesToEvent.emit("Event.relationsCreated", relationType, eventType); } }; /** * Fires whenever the timeline in a room is updated. * @event module:client~MatrixClient#"Room.timeline" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {?Room} room The room, if any, whose timeline was updated. * @param {boolean} toStartOfTimeline True if this event was added to the start * @param {boolean} removed True if this event has just been removed from the timeline * (beginning; oldest) of the timeline e.g. due to pagination. * * @param {object} data more data about the event * * @param {module:models/event-timeline.EventTimeline} data.timeline the timeline the * event was added to/removed from * * @param {boolean} data.liveEvent true if the event was a real-time event * added to the end of the live timeline * * @example * matrixClient.on("Room.timeline", * function(event, room, toStartOfTimeline, removed, data) { * if (!toStartOfTimeline && data.liveEvent) { * var messageToAppend = room.timeline.[room.timeline.length - 1]; * } * }); */ /** * Fires whenever the live timeline in a room is reset. * * When we get a 'limited' sync (for example, after a network outage), we reset * the live timeline to be empty before adding the recent events to the new * timeline. This event is fired after the timeline is reset, and before the * new events are added. * * @event module:client~MatrixClient#"Room.timelineReset" * @param {Room} room The room whose live timeline was reset, if any * @param {EventTimelineSet} timelineSet timelineSet room whose live timeline was reset * @param {boolean} resetAllTimelines True if all timelines were reset. */ },{"../logger":95,"../utils":123,"./event":100,"./event-timeline":99,"./relations":102,"@babel/runtime/helpers/interopRequireWildcard":13,"events":36}],99:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventTimeline = EventTimeline; var _roomState = require("./room-state"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * Construct a new EventTimeline * *

An EventTimeline represents a contiguous sequence of events in a room. * *

As well as keeping track of the events themselves, it stores the state of * the room at the beginning and end of the timeline, and pagination tokens for * going backwards and forwards in the timeline. * *

In order that clients can meaningfully maintain an index into a timeline, * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is * incremented when events are prepended to the timeline. The index of an event * relative to baseIndex therefore remains constant. * *

Once a timeline joins up with its neighbour, they are linked together into a * doubly-linked list. * * @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of * @constructor */ function EventTimeline(eventTimelineSet) { this._eventTimelineSet = eventTimelineSet; this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null; this._events = []; this._baseIndex = 0; this._startState = new _roomState.RoomState(this._roomId); this._startState.paginationToken = null; this._endState = new _roomState.RoomState(this._roomId); this._endState.paginationToken = null; this._prevTimeline = null; this._nextTimeline = null; // this is used by client.js this._paginationRequests = { 'b': null, 'f': null }; this._name = this._roomId + ":" + new Date().toISOString(); } /** * Symbolic constant for methods which take a 'direction' argument: * refers to the start of the timeline, or backwards in time. */ EventTimeline.BACKWARDS = "b"; /** * Symbolic constant for methods which take a 'direction' argument: * refers to the end of the timeline, or forwards in time. */ EventTimeline.FORWARDS = "f"; /** * Initialise the start and end state with the given events * *

This can only be called before any events are added. * * @param {MatrixEvent[]} stateEvents list of state events to initialise the * state with. * @throws {Error} if an attempt is made to call this after addEvent is called. */ EventTimeline.prototype.initialiseState = function (stateEvents) { if (this._events.length > 0) { throw new Error("Cannot initialise state after events are added"); } // We previously deep copied events here and used different copies in // the oldState and state events: this decision seems to date back // quite a way and was apparently made to fix a bug where modifications // made to the start state leaked through to the end state. // This really shouldn't be possible though: the events themselves should // not change. Duplicating the events uses a lot of extra memory, // so we now no longer do it. To assert that they really do never change, // freeze them! Note that we can't do this for events in general: // although it looks like the only things preventing us are the // 'status' flag, forwardLooking (which is only set once when adding to the // timeline) and possibly the sender (which seems like it should never be // reset but in practice causes a lot of the tests to break). var _iterator = _createForOfIteratorHelper(stateEvents), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var e = _step.value; Object.freeze(e); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this._startState.setStateEvents(stateEvents); this._endState.setStateEvents(stateEvents); }; /** * Forks the (live) timeline, taking ownership of the existing directional state of this timeline. * All attached listeners will keep receiving state updates from the new live timeline state. * The end state of this timeline gets replaced with an independent copy of the current RoomState, * and will need a new pagination token if it ever needs to paginate forwards. * @param {string} direction EventTimeline.BACKWARDS to get the state at the * start of the timeline; EventTimeline.FORWARDS to get the state at the end * of the timeline. * * @return {EventTimeline} the new timeline */ EventTimeline.prototype.forkLive = function (direction) { var forkState = this.getState(direction); var timeline = new EventTimeline(this._eventTimelineSet); timeline._startState = forkState.clone(); // Now clobber the end state of the new live timeline with that from the // previous live timeline. It will be identical except that we'll keep // using the same RoomMember objects for the 'live' set of members with any // listeners still attached timeline._endState = forkState; // Firstly, we just stole the current timeline's end state, so it needs a new one. // Make an immutable copy of the state so back pagination will get the correct sentinels. this._endState = forkState.clone(); return timeline; }; /** * Creates an independent timeline, inheriting the directional state from this timeline. * * @param {string} direction EventTimeline.BACKWARDS to get the state at the * start of the timeline; EventTimeline.FORWARDS to get the state at the end * of the timeline. * * @return {EventTimeline} the new timeline */ EventTimeline.prototype.fork = function (direction) { var forkState = this.getState(direction); var timeline = new EventTimeline(this._eventTimelineSet); timeline._startState = forkState.clone(); timeline._endState = forkState.clone(); return timeline; }; /** * Get the ID of the room for this timeline * @return {string} room ID */ EventTimeline.prototype.getRoomId = function () { return this._roomId; }; /** * Get the filter for this timeline's timelineSet (if any) * @return {Filter} filter */ EventTimeline.prototype.getFilter = function () { return this._eventTimelineSet.getFilter(); }; /** * Get the timelineSet for this timeline * @return {EventTimelineSet} timelineSet */ EventTimeline.prototype.getTimelineSet = function () { return this._eventTimelineSet; }; /** * Get the base index. * *

This is an index which is incremented when events are prepended to the * timeline. An individual event therefore stays at the same index in the array * relative to the base index (although note that a given event's index may * well be less than the base index, thus giving that event a negative relative * index). * * @return {number} */ EventTimeline.prototype.getBaseIndex = function () { return this._baseIndex; }; /** * Get the list of events in this context * * @return {MatrixEvent[]} An array of MatrixEvents */ EventTimeline.prototype.getEvents = function () { return this._events; }; /** * Get the room state at the start/end of the timeline * * @param {string} direction EventTimeline.BACKWARDS to get the state at the * start of the timeline; EventTimeline.FORWARDS to get the state at the end * of the timeline. * * @return {RoomState} state at the start/end of the timeline */ EventTimeline.prototype.getState = function (direction) { if (direction == EventTimeline.BACKWARDS) { return this._startState; } else if (direction == EventTimeline.FORWARDS) { return this._endState; } else { throw new Error("Invalid direction '" + direction + "'"); } }; /** * Get a pagination token * * @param {string} direction EventTimeline.BACKWARDS to get the pagination * token for going backwards in time; EventTimeline.FORWARDS to get the * pagination token for going forwards in time. * * @return {?string} pagination token */ EventTimeline.prototype.getPaginationToken = function (direction) { return this.getState(direction).paginationToken; }; /** * Set a pagination token * * @param {?string} token pagination token * * @param {string} direction EventTimeline.BACKWARDS to set the pagination * token for going backwards in time; EventTimeline.FORWARDS to set the * pagination token for going forwards in time. */ EventTimeline.prototype.setPaginationToken = function (token, direction) { this.getState(direction).paginationToken = token; }; /** * Get the next timeline in the series * * @param {string} direction EventTimeline.BACKWARDS to get the previous * timeline; EventTimeline.FORWARDS to get the next timeline. * * @return {?EventTimeline} previous or following timeline, if they have been * joined up. */ EventTimeline.prototype.getNeighbouringTimeline = function (direction) { if (direction == EventTimeline.BACKWARDS) { return this._prevTimeline; } else if (direction == EventTimeline.FORWARDS) { return this._nextTimeline; } else { throw new Error("Invalid direction '" + direction + "'"); } }; /** * Set the next timeline in the series * * @param {EventTimeline} neighbour previous/following timeline * * @param {string} direction EventTimeline.BACKWARDS to set the previous * timeline; EventTimeline.FORWARDS to set the next timeline. * * @throws {Error} if an attempt is made to set the neighbouring timeline when * it is already set. */ EventTimeline.prototype.setNeighbouringTimeline = function (neighbour, direction) { if (this.getNeighbouringTimeline(direction)) { throw new Error("timeline already has a neighbouring timeline - " + "cannot reset neighbour (direction: " + direction + ")"); } if (direction == EventTimeline.BACKWARDS) { this._prevTimeline = neighbour; } else if (direction == EventTimeline.FORWARDS) { this._nextTimeline = neighbour; } else { throw new Error("Invalid direction '" + direction + "'"); } // make sure we don't try to paginate this timeline this.setPaginationToken(null, direction); }; /** * Add a new event to the timeline, and update the state * * @param {MatrixEvent} event new event * @param {boolean} atStart true to insert new event at the start */ EventTimeline.prototype.addEvent = function (event, atStart) { var stateContext = atStart ? this._startState : this._endState; // only call setEventMetadata on the unfiltered timelineSets var timelineSet = this.getTimelineSet(); if (timelineSet.room && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) { EventTimeline.setEventMetadata(event, stateContext, atStart); // modify state if (event.isState()) { stateContext.setStateEvents([event]); // it is possible that the act of setting the state event means we // can set more metadata (specifically sender/target props), so try // it again if the prop wasn't previously set. It may also mean that // the sender/target is updated (if the event set was a room member event) // so we want to use the *updated* member (new avatar/name) instead. // // However, we do NOT want to do this on member events if we're going // back in time, else we'll set the .sender value for BEFORE the given // member event, whereas we want to set the .sender value for the ACTUAL // member event itself. if (!event.sender || event.getType() === "m.room.member" && !atStart) { EventTimeline.setEventMetadata(event, stateContext, atStart); } } } var insertIndex; if (atStart) { insertIndex = 0; } else { insertIndex = this._events.length; } this._events.splice(insertIndex, 0, event); // insert element if (atStart) { this._baseIndex++; } }; /** * Static helper method to set sender and target properties * * @param {MatrixEvent} event the event whose metadata is to be set * @param {RoomState} stateContext the room state to be queried * @param {bool} toStartOfTimeline if true the event's forwardLooking flag is set false */ EventTimeline.setEventMetadata = function (event, stateContext, toStartOfTimeline) { // set sender and target properties event.sender = stateContext.getSentinelMember(event.getSender()); if (event.getType() === "m.room.member") { event.target = stateContext.getSentinelMember(event.getStateKey()); } if (event.isState()) { // room state has no concept of 'old' or 'current', but we want the // room state to regress back to previous values if toStartOfTimeline // is set, which means inspecting prev_content if it exists. This // is done by toggling the forwardLooking flag. if (toStartOfTimeline) { event.forwardLooking = false; } } }; /** * Remove an event from the timeline * * @param {string} eventId ID of event to be removed * @return {?MatrixEvent} removed event, or null if not found */ EventTimeline.prototype.removeEvent = function (eventId) { for (var i = this._events.length - 1; i >= 0; i--) { var ev = this._events[i]; if (ev.getId() == eventId) { this._events.splice(i, 1); if (i < this._baseIndex) { this._baseIndex--; } return ev; } } return null; }; /** * Return a string to identify this timeline, for debugging * * @return {string} name for this timeline */ EventTimeline.prototype.toString = function () { return this._name; }; },{"./room-state":104}],100:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixEvent = exports.EventStatus = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _events = require("events"); var utils = _interopRequireWildcard(require("../utils")); var _logger = require("../logger"); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for * the public classes. * @module models/event */ /** * Enum for event statuses. * @readonly * @enum {string} */ var EventStatus = { /** The event was not sent and will no longer be retried. */ NOT_SENT: "not_sent", /** The message is being encrypted */ ENCRYPTING: "encrypting", /** The event is in the process of being sent. */ SENDING: "sending", /** The event is in a queue waiting to be sent. */ QUEUED: "queued", /** The event has been sent to the server, but we have not yet received the * echo. */ SENT: "sent", /** The event was cancelled before it was successfully sent. */ CANCELLED: "cancelled" }; exports.EventStatus = EventStatus; var interns = {}; function intern(str) { if (!interns[str]) { interns[str] = str; } return interns[str]; } /** * Construct a Matrix Event object * @constructor * * @param {Object} event The raw event to be wrapped in this DAO * * @prop {Object} event The raw (possibly encrypted) event. Do not access * this property directly unless you absolutely have to. Prefer the getter * methods defined on this class. Using the getter methods shields your app * from changes to event JSON between Matrix versions. * * @prop {RoomMember} sender The room member who sent this event, or null e.g. * this is a presence event. This is only guaranteed to be set for events that * appear in a timeline, ie. do not guarantee that it will be set on state * events. * @prop {RoomMember} target The room member who is the target of this event, e.g. * the invitee, the person being banned, etc. * @prop {EventStatus} status The sending status of the event. * @prop {Error} error most recent error associated with sending the event, if any * @prop {boolean} forwardLooking True if this event is 'forward looking', meaning * that getDirectionalContent() will return event.content and not event.prev_content. * Default: true. This property is experimental and may change. */ var MatrixEvent = function MatrixEvent(event) { // intern the values of matrix events to force share strings and reduce the // amount of needless string duplication. This can save moderate amounts of // memory (~10% on a 350MB heap). // 'membership' at the event level (rather than the content level) is a legacy // field that Element never otherwise looks at, but it will still take up a lot // of space if we don't intern it. ["state_key", "type", "sender", "room_id", "membership"].forEach(function (prop) { if (!event[prop]) { return; } event[prop] = intern(event[prop]); }); ["membership", "avatar_url", "displayname"].forEach(function (prop) { if (!event.content || !event.content[prop]) { return; } event.content[prop] = intern(event.content[prop]); }); ["rel_type"].forEach(function (prop) { if (!event.content || !event.content["m.relates_to"] || !event.content["m.relates_to"][prop]) { return; } event.content["m.relates_to"][prop] = intern(event.content["m.relates_to"][prop]); }); this.event = event || {}; this.sender = null; this.target = null; this.status = null; this.error = null; this.forwardLooking = true; this._pushActions = null; this._replacingEvent = null; this._localRedactionEvent = null; this._isCancelled = false; this._clearEvent = {}; /* curve25519 key which we believe belongs to the sender of the event. See * getSenderKey() */ this._senderCurve25519Key = null; /* ed25519 key which the sender of this event (for olm) or the creator of * the megolm session (for megolm) claims to own. See getClaimedEd25519Key() */ this._claimedEd25519Key = null; /* curve25519 keys of devices involved in telling us about the * _senderCurve25519Key and _claimedEd25519Key. * See getForwardingCurve25519KeyChain(). */ this._forwardingCurve25519KeyChain = []; /* where the decryption key is untrusted */ this._untrusted = null; /* if we have a process decrypting this event, a Promise which resolves * when it is finished. Normally null. */ this._decryptionPromise = null; /* flag to indicate if we should retry decrypting this event after the * first attempt (eg, we have received new data which means that a second * attempt may succeed) */ this._retryDecryption = false; /* If the event is a `m.key.verification.request` (or to_device `m.key.verification.start`) event, * `Crypto` will set this the `VerificationRequest` for the event * so it can be easily accessed from the timeline. */ this.verificationRequest = null; /* The txnId with which this event was sent if it was during this session, allows for a unique ID which does not change when the event comes back down sync. */ this._txnId = null; }; exports.MatrixEvent = MatrixEvent; utils.inherits(MatrixEvent, _events.EventEmitter); utils.extend(MatrixEvent.prototype, { /** * Get the event_id for this event. * @return {string} The event ID, e.g. $143350589368169JsLZx:localhost * */ getId: function getId() { return this.event.event_id; }, /** * Get the user_id for this event. * @return {string} The user ID, e.g. @alice:matrix.org */ getSender: function getSender() { return this.event.sender || this.event.user_id; // v2 / v1 }, /** * Get the (decrypted, if necessary) type of event. * * @return {string} The event type, e.g. m.room.message */ getType: function getType() { return this._clearEvent.type || this.event.type; }, /** * Get the (possibly encrypted) type of the event that will be sent to the * homeserver. * * @return {string} The event type. */ getWireType: function getWireType() { return this.event.type; }, /** * Get the room_id for this event. This will return undefined * for m.presence events. * @return {string} The room ID, e.g. !cURbafjkfsMDVwdRDQ:matrix.org * */ getRoomId: function getRoomId() { return this.event.room_id; }, /** * Get the timestamp of this event. * @return {Number} The event timestamp, e.g. 1433502692297 */ getTs: function getTs() { return this.event.origin_server_ts; }, /** * Get the timestamp of this event, as a Date object. * @return {Date} The event date, e.g. new Date(1433502692297) */ getDate: function getDate() { return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null; }, /** * Get the (decrypted, if necessary) event content JSON, even if the event * was replaced by another event. * * @return {Object} The event content JSON, or an empty object. */ getOriginalContent: function getOriginalContent() { if (this._localRedactionEvent) { return {}; } return this._clearEvent.content || this.event.content || {}; }, /** * Get the (decrypted, if necessary) event content JSON, * or the content from the replacing event, if any. * See `makeReplaced`. * * @return {Object} The event content JSON, or an empty object. */ getContent: function getContent() { if (this._localRedactionEvent) { return {}; } else if (this._replacingEvent) { return this._replacingEvent.getContent()["m.new_content"] || {}; } else { return this.getOriginalContent(); } }, /** * Get the (possibly encrypted) event content JSON that will be sent to the * homeserver. * * @return {Object} The event content JSON, or an empty object. */ getWireContent: function getWireContent() { return this.event.content || {}; }, /** * Get the previous event content JSON. This will only return something for * state events which exist in the timeline. * @return {Object} The previous event content JSON, or an empty object. */ getPrevContent: function getPrevContent() { // v2 then v1 then default return this.getUnsigned().prev_content || this.event.prev_content || {}; }, /** * Get either 'content' or 'prev_content' depending on if this event is * 'forward-looking' or not. This can be modified via event.forwardLooking. * In practice, this means we get the chronologically earlier content value * for this event (this method should surely be called getEarlierContent) * This method is experimental and may change. * @return {Object} event.content if this event is forward-looking, else * event.prev_content. */ getDirectionalContent: function getDirectionalContent() { return this.forwardLooking ? this.getContent() : this.getPrevContent(); }, /** * Get the age of this event. This represents the age of the event when the * event arrived at the device, and not the age of the event when this * function was called. * @return {Number} The age of this event in milliseconds. */ getAge: function getAge() { return this.getUnsigned().age || this.event.age; // v2 / v1 }, /** * Get the age of the event when this function was called. * Relies on the local clock being in sync with the clock of the original homeserver. * @return {Number} The age of this event in milliseconds. */ getLocalAge: function getLocalAge() { return Date.now() - this.getTs(); }, /** * Get the event state_key if it has one. This will return undefined * for message events. * @return {string} The event's state_key. */ getStateKey: function getStateKey() { return this.event.state_key; }, /** * Check if this event is a state event. * @return {boolean} True if this is a state event. */ isState: function isState() { return this.event.state_key !== undefined; }, /** * Replace the content of this event with encrypted versions. * (This is used when sending an event; it should not be used by applications). * * @internal * * @param {string} crypto_type type of the encrypted event - typically * "m.room.encrypted" * * @param {object} crypto_content raw 'content' for the encrypted event. * * @param {string} senderCurve25519Key curve25519 key to record for the * sender of this event. * See {@link module:models/event.MatrixEvent#getSenderKey}. * * @param {string} claimedEd25519Key claimed ed25519 key to record for the * sender if this event. * See {@link module:models/event.MatrixEvent#getClaimedEd25519Key} */ makeEncrypted: function makeEncrypted(crypto_type, crypto_content, senderCurve25519Key, claimedEd25519Key) { // keep the plain-text data for 'view source' this._clearEvent = { type: this.event.type, content: this.event.content }; this.event.type = crypto_type; this.event.content = crypto_content; this._senderCurve25519Key = senderCurve25519Key; this._claimedEd25519Key = claimedEd25519Key; }, /** * Check if this event is currently being decrypted. * * @return {boolean} True if this event is currently being decrypted, else false. */ isBeingDecrypted: function isBeingDecrypted() { return this._decryptionPromise != null; }, /** * Check if this event is an encrypted event which we failed to decrypt * * (This implies that we might retry decryption at some point in the future) * * @return {boolean} True if this event is an encrypted event which we * couldn't decrypt. */ isDecryptionFailure: function isDecryptionFailure() { return this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype === "m.bad.encrypted"; }, /** * Start the process of trying to decrypt this event. * * (This is used within the SDK: it isn't intended for use by applications) * * @internal * * @param {module:crypto} crypto crypto module * @param {bool} isRetry True if this is a retry (enables more logging) * * @returns {Promise} promise which resolves (to undefined) when the decryption * attempt is completed. */ attemptDecryption: function () { var _attemptDecryption = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(crypto, isRetry) { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (this.isEncrypted()) { _context.next = 2; break; } throw new Error("Attempt to decrypt event which isn't encrypted"); case 2: if (!(this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype !== "m.bad.encrypted")) { _context.next = 4; break; } throw new Error("Attempt to decrypt event which has already been decrypted"); case 4: if (!this._decryptionPromise) { _context.next = 8; break; } _logger.logger.log("Event ".concat(this.getId(), " already being decrypted; queueing a retry")); this._retryDecryption = true; return _context.abrupt("return", this._decryptionPromise); case 8: this._decryptionPromise = this._decryptionLoop(crypto, isRetry); return _context.abrupt("return", this._decryptionPromise); case 10: case "end": return _context.stop(); } } }, _callee, this); })); function attemptDecryption(_x, _x2) { return _attemptDecryption.apply(this, arguments); } return attemptDecryption; }(), /** * Cancel any room key request for this event and resend another. * * @param {module:crypto} crypto crypto module * @param {string} userId the user who received this event * * @returns {Promise} a promise that resolves when the request is queued */ cancelAndResendKeyRequest: function cancelAndResendKeyRequest(crypto, userId) { var wireContent = this.getWireContent(); return crypto.requestRoomKey({ algorithm: wireContent.algorithm, room_id: this.getRoomId(), session_id: wireContent.session_id, sender_key: wireContent.sender_key }, this.getKeyRequestRecipients(userId), true); }, /** * Calculate the recipients for keyshare requests. * * @param {string} userId the user who received this event. * * @returns {Array} array of recipients */ getKeyRequestRecipients: function getKeyRequestRecipients(userId) { // send the request to all of our own devices, and the // original sending device if it wasn't us. var wireContent = this.getWireContent(); var recipients = [{ userId: userId, deviceId: '*' }]; var sender = this.getSender(); if (sender !== userId) { recipients.push({ userId: sender, deviceId: wireContent.device_id }); } return recipients; }, _decryptionLoop: function () { var _decryptionLoop2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(crypto, isRetry) { var res, err, re; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return Promise.resolve(); case 2: if (!true) { _context2.next = 39; break; } this._retryDecryption = false; res = void 0; err = void 0; _context2.prev = 6; if (crypto) { _context2.next = 11; break; } res = this._badEncryptedMessage("Encryption not enabled"); _context2.next = 15; break; case 11: _context2.next = 13; return crypto.decryptEvent(this); case 13: res = _context2.sent; if (isRetry) { _logger.logger.info("Decrypted event on retry (id=".concat(this.getId(), ")")); } case 15: _context2.next = 31; break; case 17: _context2.prev = 17; _context2.t0 = _context2["catch"](6); if (!(_context2.t0.name !== "DecryptionError")) { _context2.next = 25; break; } // not a decryption error: log the whole exception as an error // (and don't bother with a retry) re = isRetry ? 're' : ''; _logger.logger.error("Error ".concat(re, "decrypting event ") + "(id=".concat(this.getId(), "): ").concat(_context2.t0.stack || _context2.t0)); this._decryptionPromise = null; this._retryDecryption = false; return _context2.abrupt("return"); case 25: err = _context2.t0; // see if we have a retry queued. // // NB: make sure to keep this check in the same tick of the // event loop as `_decryptionPromise = null` below - otherwise we // risk a race: // // * A: we check _retryDecryption here and see that it is // false // * B: we get a second call to attemptDecryption, which sees // that _decryptionPromise is set so sets // _retryDecryption // * A: we continue below, clear _decryptionPromise, and // never do the retry. // if (!this._retryDecryption) { _context2.next = 29; break; } // decryption error, but we have a retry queued. _logger.logger.log("Got error decrypting event (id=".concat(this.getId(), ": ") + "".concat(_context2.t0, "), but retrying")); return _context2.abrupt("continue", 2); case 29: // decryption error, no retries queued. Warn about the error and // set it to m.bad.encrypted. _logger.logger.warn("Error decrypting event (id=".concat(this.getId(), "): ").concat(_context2.t0.detailedString)); res = this._badEncryptedMessage(_context2.t0.message); case 31: // at this point, we've either successfully decrypted the event, or have given up // (and set res to a 'badEncryptedMessage'). Either way, we can now set the // cleartext of the event and raise Event.decrypted. // // make sure we clear '_decryptionPromise' before sending the 'Event.decrypted' event, // otherwise the app will be confused to see `isBeingDecrypted` still set when // there isn't an `Event.decrypted` on the way. // // see also notes on _retryDecryption above. // this._decryptionPromise = null; this._retryDecryption = false; this._setClearData(res); // Before we emit the event, clear the push actions so that they can be recalculated // by relevant code. We do this because the clear event has now changed, making it // so that existing rules can be re-run over the applicable properties. Stuff like // highlighting when the user's name is mentioned rely on this happening. We also want // to set the push actions before emitting so that any notification listeners don't // pick up the wrong contents. this.setPushActions(null); this.emit("Event.decrypted", this, err); return _context2.abrupt("return"); case 39: case "end": return _context2.stop(); } } }, _callee2, this, [[6, 17]]); })); function _decryptionLoop(_x3, _x4) { return _decryptionLoop2.apply(this, arguments); } return _decryptionLoop; }(), _badEncryptedMessage: function _badEncryptedMessage(reason) { return { clearEvent: { type: "m.room.message", content: { msgtype: "m.bad.encrypted", body: "** Unable to decrypt: " + reason + " **" } } }; }, /** * Update the cleartext data on this event. * * (This is used after decrypting an event; it should not be used by applications). * * @internal * * @fires module:models/event.MatrixEvent#"Event.decrypted" * * @param {module:crypto~EventDecryptionResult} decryptionResult * the decryption result, including the plaintext and some key info */ _setClearData: function _setClearData(decryptionResult) { this._clearEvent = decryptionResult.clearEvent; this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null; this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null; this._forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || []; this._untrusted = decryptionResult.untrusted || false; }, /** * Gets the cleartext content for this event. If the event is not encrypted, * or encryption has not been completed, this will return null. * * @returns {Object} The cleartext (decrypted) content for the event */ getClearContent: function getClearContent() { var ev = this._clearEvent; return ev && ev.content ? ev.content : null; }, /** * Check if the event is encrypted. * @return {boolean} True if this event is encrypted. */ isEncrypted: function isEncrypted() { return !this.isState() && this.event.type === "m.room.encrypted"; }, /** * The curve25519 key for the device that we think sent this event * * For an Olm-encrypted event, this is inferred directly from the DH * exchange at the start of the session: the curve25519 key is involved in * the DH exchange, so only a device which holds the private part of that * key can establish such a session. * * For a megolm-encrypted event, it is inferred from the Olm message which * established the megolm session * * @return {string} */ getSenderKey: function getSenderKey() { return this._senderCurve25519Key; }, /** * The additional keys the sender of this encrypted event claims to possess. * * Just a wrapper for #getClaimedEd25519Key (q.v.) * * @return {Object} */ getKeysClaimed: function getKeysClaimed() { return { ed25519: this._claimedEd25519Key }; }, /** * Get the ed25519 the sender of this event claims to own. * * For Olm messages, this claim is encoded directly in the plaintext of the * event itself. For megolm messages, it is implied by the m.room_key event * which established the megolm session. * * Until we download the device list of the sender, it's just a claim: the * device list gives a proof that the owner of the curve25519 key used for * this event (and returned by #getSenderKey) also owns the ed25519 key by * signing the public curve25519 key with the ed25519 key. * * In general, applications should not use this method directly, but should * instead use MatrixClient.getEventSenderDeviceInfo. * * @return {string} */ getClaimedEd25519Key: function getClaimedEd25519Key() { return this._claimedEd25519Key; }, /** * Get the curve25519 keys of the devices which were involved in telling us * about the claimedEd25519Key and sender curve25519 key. * * Normally this will be empty, but in the case of a forwarded megolm * session, the sender keys are sent to us by another device (the forwarding * device), which we need to trust to do this. In that case, the result will * be a list consisting of one entry. * * If the device that sent us the key (A) got it from another device which * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on. * * @return {string[]} base64-encoded curve25519 keys, from oldest to newest. */ getForwardingCurve25519KeyChain: function getForwardingCurve25519KeyChain() { return this._forwardingCurve25519KeyChain; }, /** * Whether the decryption key was obtained from an untrusted source. If so, * we cannot verify the authenticity of the message. * * @return {boolean} */ isKeySourceUntrusted: function isKeySourceUntrusted() { return this._untrusted; }, getUnsigned: function getUnsigned() { return this.event.unsigned || {}; }, unmarkLocallyRedacted: function unmarkLocallyRedacted() { var value = this._localRedactionEvent; this._localRedactionEvent = null; if (this.event.unsigned) { this.event.unsigned.redacted_because = null; } return !!value; }, markLocallyRedacted: function markLocallyRedacted(redactionEvent) { if (this._localRedactionEvent) { return; } this.emit("Event.beforeRedaction", this, redactionEvent); this._localRedactionEvent = redactionEvent; if (!this.event.unsigned) { this.event.unsigned = {}; } this.event.unsigned.redacted_because = redactionEvent.event; }, /** * Update the content of an event in the same way it would be by the server * if it were redacted before it was sent to us * * @param {module:models/event.MatrixEvent} redaction_event * event causing the redaction */ makeRedacted: function makeRedacted(redaction_event) { // quick sanity-check if (!redaction_event.event) { throw new Error("invalid redaction_event in makeRedacted"); } this._localRedactionEvent = null; this.emit("Event.beforeRedaction", this, redaction_event); this._replacingEvent = null; // we attempt to replicate what we would see from the server if // the event had been redacted before we saw it. // // The server removes (most of) the content of the event, and adds a // "redacted_because" key to the unsigned section containing the // redacted event. if (!this.event.unsigned) { this.event.unsigned = {}; } this.event.unsigned.redacted_because = redaction_event.event; var key; for (key in this.event) { if (!this.event.hasOwnProperty(key)) { continue; } if (!_REDACT_KEEP_KEY_MAP[key]) { delete this.event[key]; } } var keeps = _REDACT_KEEP_CONTENT_MAP[this.getType()] || {}; var content = this.getContent(); for (key in content) { if (!content.hasOwnProperty(key)) { continue; } if (!keeps[key]) { delete content[key]; } } }, /** * Check if this event has been redacted * * @return {boolean} True if this event has been redacted */ isRedacted: function isRedacted() { return Boolean(this.getUnsigned().redacted_because); }, /** * Check if this event is a redaction of another event * * @return {boolean} True if this event is a redaction */ isRedaction: function isRedaction() { return this.getType() === "m.room.redaction"; }, /** * Get the push actions, if known, for this event * * @return {?Object} push actions */ getPushActions: function getPushActions() { return this._pushActions; }, /** * Set the push actions for this event. * * @param {Object} pushActions push actions */ setPushActions: function setPushActions(pushActions) { this._pushActions = pushActions; }, /** * Replace the `event` property and recalculate any properties based on it. * @param {Object} event the object to assign to the `event` property */ handleRemoteEcho: function handleRemoteEcho(event) { var oldUnsigned = this.getUnsigned(); var oldId = this.getId(); this.event = event; // if this event was redacted before it was sent, it's locally marked as redacted. // At this point, we've received the remote echo for the event, but not yet for // the redaction that we are sending ourselves. Preserve the locally redacted // state by copying over redacted_because so we don't get a flash of // redacted, not-redacted, redacted as remote echos come in if (oldUnsigned.redacted_because) { if (!this.event.unsigned) { this.event.unsigned = {}; } this.event.unsigned.redacted_because = oldUnsigned.redacted_because; } // successfully sent. this.setStatus(null); if (this.getId() !== oldId) { // emit the event if it changed this.emit("Event.localEventIdReplaced", this); } }, /** * Whether the event is in any phase of sending, send failure, waiting for * remote echo, etc. * * @return {boolean} */ isSending: function isSending() { return !!this.status; }, /** * Update the event's sending status and emit an event as well. * * @param {String} status The new status */ setStatus: function setStatus(status) { this.status = status; this.emit("Event.status", this, status); }, replaceLocalEventId: function replaceLocalEventId(eventId) { this.event.event_id = eventId; this.emit("Event.localEventIdReplaced", this); }, /** * Get whether the event is a relation event, and of a given type if * `relType` is passed in. * * @param {string?} relType if given, checks that the relation is of the * given type * @return {boolean} */ isRelation: function isRelation() { var relType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; // Relation info is lifted out of the encrypted content when sent to // encrypted rooms, so we have to check `getWireContent` for this. var content = this.getWireContent(); var relation = content && content["m.relates_to"]; return relation && relation.rel_type && relation.event_id && (relType && relation.rel_type === relType || !relType); }, /** * Get relation info for the event, if any. * * @return {Object} */ getRelation: function getRelation() { if (!this.isRelation()) { return null; } return this.getWireContent()["m.relates_to"]; }, /** * Set an event that replaces the content of this event, through an m.replace relation. * * @param {MatrixEvent?} newEvent the event with the replacing content, if any. */ makeReplaced: function makeReplaced(newEvent) { // don't allow redacted events to be replaced. // if newEvent is null we allow to go through though, // as with local redaction, the replacing event might get // cancelled, which should be reflected on the target event. if (this.isRedacted() && newEvent) { return; } if (this._replacingEvent !== newEvent) { this._replacingEvent = newEvent; this.emit("Event.replaced", this); } }, /** * Returns the status of any associated edit or redaction * (not for reactions/annotations as their local echo doesn't affect the orignal event), * or else the status of the event. * * @return {EventStatus} */ getAssociatedStatus: function getAssociatedStatus() { if (this._replacingEvent) { return this._replacingEvent.status; } else if (this._localRedactionEvent) { return this._localRedactionEvent.status; } return this.status; }, getServerAggregatedRelation: function getServerAggregatedRelation(relType) { var relations = this.getUnsigned()["m.relations"]; if (relations) { return relations[relType]; } }, /** * Returns the event ID of the event replacing the content of this event, if any. * * @return {string?} */ replacingEventId: function replacingEventId() { var replaceRelation = this.getServerAggregatedRelation("m.replace"); if (replaceRelation) { return replaceRelation.event_id; } else if (this._replacingEvent) { return this._replacingEvent.getId(); } }, /** * Returns the event replacing the content of this event, if any. * Replacements are aggregated on the server, so this would only * return an event in case it came down the sync, or for local echo of edits. * * @return {MatrixEvent?} */ replacingEvent: function replacingEvent() { return this._replacingEvent; }, /** * Returns the origin_server_ts of the event replacing the content of this event, if any. * * @return {Date?} */ replacingEventDate: function replacingEventDate() { var replaceRelation = this.getServerAggregatedRelation("m.replace"); if (replaceRelation) { var ts = replaceRelation.origin_server_ts; if (Number.isFinite(ts)) { return new Date(ts); } } else if (this._replacingEvent) { return this._replacingEvent.getDate(); } }, /** * Returns the event that wants to redact this event, but hasn't been sent yet. * @return {MatrixEvent} the event */ localRedactionEvent: function localRedactionEvent() { return this._localRedactionEvent; }, /** * For relations and redactions, returns the event_id this event is referring to. * * @return {string?} */ getAssociatedId: function getAssociatedId() { var relation = this.getRelation(); if (relation) { return relation.event_id; } else if (this.isRedaction()) { return this.event.redacts; } }, /** * Checks if this event is associated with another event. See `getAssociatedId`. * * @return {bool} */ hasAssocation: function hasAssocation() { return !!this.getAssociatedId(); }, /** * Update the related id with a new one. * * Used to replace a local id with remote one before sending * an event with a related id. * * @param {string} eventId the new event id */ updateAssociatedId: function updateAssociatedId(eventId) { var relation = this.getRelation(); if (relation) { relation.event_id = eventId; } else if (this.isRedaction()) { this.event.redacts = eventId; } }, /** * Flags an event as cancelled due to future conditions. For example, a verification * request event in the same sync transaction may be flagged as cancelled to warn * listeners that a cancellation event is coming down the same pipe shortly. * @param {boolean} cancelled Whether the event is to be cancelled or not. */ flagCancelled: function flagCancelled() { var cancelled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; this._isCancelled = cancelled; }, /** * Gets whether or not the event is flagged as cancelled. See flagCancelled() for * more information. * @returns {boolean} True if the event is cancelled, false otherwise. */ isCancelled: function isCancelled() { return this._isCancelled; }, /** * Summarise the event as JSON for debugging. If encrypted, include both the * decrypted and encrypted view of the event. This is named `toJSON` for use * with `JSON.stringify` which checks objects for functions named `toJSON` * and will call them to customise the output if they are defined. * * @return {Object} */ toJSON: function toJSON() { var event = { type: this.getType(), sender: this.getSender(), content: this.getContent(), event_id: this.getId(), origin_server_ts: this.getTs(), unsigned: this.getUnsigned(), room_id: this.getRoomId() }; // if this is a redaction then attach the redacts key if (this.isRedaction()) { event.redacts = this.event.redacts; } if (!this.isEncrypted()) { return event; } return { decrypted: event, encrypted: this.event }; }, setVerificationRequest: function setVerificationRequest(request) { this.verificationRequest = request; }, setTxnId: function setTxnId(txnId) { this._txnId = txnId; }, getTxnId: function getTxnId() { return this._txnId; } }); /* _REDACT_KEEP_KEY_MAP gives the keys we keep when an event is redacted * * This is specified here: * http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions * * Also: * - We keep 'unsigned' since that is created by the local server * - We keep user_id for backwards-compat with v1 */ var _REDACT_KEEP_KEY_MAP = ['event_id', 'type', 'room_id', 'user_id', 'sender', 'state_key', 'prev_state', 'content', 'unsigned', 'origin_server_ts'].reduce(function (ret, val) { ret[val] = 1; return ret; }, {}); // a map from event type to the .content keys we keep when an event is redacted var _REDACT_KEEP_CONTENT_MAP = { 'm.room.member': { 'membership': 1 }, 'm.room.create': { 'creator': 1 }, 'm.room.join_rules': { 'join_rule': 1 }, 'm.room.power_levels': { 'ban': 1, 'events': 1, 'events_default': 1, 'kick': 1, 'redact': 1, 'state_default': 1, 'users': 1, 'users_default': 1 }, 'm.room.aliases': { 'aliases': 1 } }; /** * Fires when an event is decrypted * * @event module:models/event.MatrixEvent#"Event.decrypted" * * @param {module:models/event.MatrixEvent} event * The matrix event which has been decrypted * @param {module:crypto/algorithms/base.DecryptionError?} err * The error that occured during decryption, or `undefined` if no * error occured. */ },{"../logger":95,"../utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27,"events":36}],101:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.Group = Group; var utils = _interopRequireWildcard(require("../utils")); var _events = require("events"); /* Copyright 2017 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/group */ /** * Construct a new Group. * * @param {string} groupId The ID of this group. * * @prop {string} groupId The ID of this group. * @prop {string} name The human-readable display name for this group. * @prop {string} avatarUrl The mxc URL for this group's avatar. * @prop {string} myMembership The logged in user's membership of this group * @prop {Object} inviter Infomation about the user who invited the logged in user * to the group, if myMembership is 'invite'. * @prop {string} inviter.userId The user ID of the inviter */ function Group(groupId) { this.groupId = groupId; this.name = null; this.avatarUrl = null; this.myMembership = null; this.inviter = null; } utils.inherits(Group, _events.EventEmitter); Group.prototype.setProfile = function (name, avatarUrl) { if (this.name === name && this.avatarUrl === avatarUrl) return; this.name = name || this.groupId; this.avatarUrl = avatarUrl; this.emit("Group.profile", this); }; Group.prototype.setMyMembership = function (membership) { if (this.myMembership === membership) return; this.myMembership = membership; this.emit("Group.myMembership", this); }; /** * Sets the 'inviter' property. This does not emit an event (the inviter * will only change when the user is revited / reinvited to a room), * so set this before setting myMembership. * @param {Object} inviter Infomation about who invited us to the room */ Group.prototype.setInviter = function (inviter) { this.inviter = inviter; }; /** * Fires whenever a group's profile information is updated. * This means the 'name' and 'avatarUrl' properties. * @event module:client~MatrixClient#"Group.profile" * @param {Group} group The group whose profile was updated. * @example * matrixClient.on("Group.profile", function(group){ * var name = group.name; * }); */ /** * Fires whenever the logged in user's membership status of * the group is updated. * @event module:client~MatrixClient#"Group.myMembership" * @param {Group} group The group in which the user's membership changed * @example * matrixClient.on("Group.myMembership", function(group){ * var myMembership = group.myMembership; * }); */ },{"../utils":123,"@babel/runtime/helpers/interopRequireWildcard":13,"events":36}],102:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.Relations = void 0; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _events = require("events"); var _event = require("../models/event"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * A container for relation events that supports easy access to common ways of * aggregating such events. Each instance holds events that of a single relation * type and event type. All of the events also relate to the same original event. * * The typical way to get one of these containers is via * EventTimelineSet#getRelationsForEvent. */ var Relations = /*#__PURE__*/function (_EventEmitter) { (0, _inherits2["default"])(Relations, _EventEmitter); var _super = _createSuper(Relations); /** * @param {String} relationType * The type of relation involved, such as "m.annotation", "m.reference", * "m.replace", etc. * @param {String} eventType * The relation event's type, such as "m.reaction", etc. * @param {?Room} room * Room for this container. May be null for non-room cases, such as the * notification timeline. */ function Relations(relationType, eventType, room) { var _this; (0, _classCallCheck2["default"])(this, Relations); _this = _super.call(this); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_onEventStatus", function (event, status) { if (!event.isSending()) { // Sending is done, so we don't need to listen anymore event.removeListener("Event.status", _this._onEventStatus); return; } if (status !== _event.EventStatus.CANCELLED) { return; } // Event was cancelled, remove from the collection event.removeListener("Event.status", _this._onEventStatus); _this._removeEvent(event); }); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_onBeforeRedaction", function (redactedEvent) { if (!_this._relations.has(redactedEvent)) { return; } _this._relations["delete"](redactedEvent); if (_this.relationType === "m.annotation") { // Remove the redacted annotation from aggregation by key _this._removeAnnotationFromAggregation(redactedEvent); } else if (_this.relationType === "m.replace" && _this._targetEvent) { _this._targetEvent.makeReplaced(_this.getLastReplacement()); } redactedEvent.removeListener("Event.beforeRedaction", _this._onBeforeRedaction); _this.emit("Relations.redaction", redactedEvent); }); _this.relationType = relationType; _this.eventType = eventType; _this._relations = new Set(); _this._annotationsByKey = {}; _this._annotationsBySender = {}; _this._sortedAnnotationsByKey = []; _this._targetEvent = null; return _this; } /** * Add relation events to this collection. * * @param {MatrixEvent} event * The new relation event to be added. */ (0, _createClass2["default"])(Relations, [{ key: "addEvent", value: function addEvent(event) { if (this._relations.has(event)) { return; } var relation = event.getRelation(); if (!relation) { console.error("Event must have relation info"); return; } var relationType = relation.rel_type; var eventType = event.getType(); if (this.relationType !== relationType || this.eventType !== eventType) { console.error("Event relation info doesn't match this container"); return; } // If the event is in the process of being sent, listen for cancellation // so we can remove the event from the collection. if (event.isSending()) { event.on("Event.status", this._onEventStatus); } this._relations.add(event); if (this.relationType === "m.annotation") { this._addAnnotationToAggregation(event); } else if (this.relationType === "m.replace" && this._targetEvent) { this._targetEvent.makeReplaced(this.getLastReplacement()); } event.on("Event.beforeRedaction", this._onBeforeRedaction); this.emit("Relations.add", event); } /** * Remove relation event from this collection. * * @param {MatrixEvent} event * The relation event to remove. */ }, { key: "_removeEvent", value: function _removeEvent(event) { if (!this._relations.has(event)) { return; } var relation = event.getRelation(); if (!relation) { console.error("Event must have relation info"); return; } var relationType = relation.rel_type; var eventType = event.getType(); if (this.relationType !== relationType || this.eventType !== eventType) { console.error("Event relation info doesn't match this container"); return; } this._relations["delete"](event); if (this.relationType === "m.annotation") { this._removeAnnotationFromAggregation(event); } else if (this.relationType === "m.replace" && this._targetEvent) { this._targetEvent.makeReplaced(this.getLastReplacement()); } this.emit("Relations.remove", event); } /** * Listens for event status changes to remove cancelled events. * * @param {MatrixEvent} event The event whose status has changed * @param {EventStatus} status The new status */ }, { key: "getRelations", /** * Get all relation events in this collection. * * These are currently in the order of insertion to this collection, which * won't match timeline order in the case of scrollback. * TODO: Tweak `addEvent` to insert correctly for scrollback. * * @return {Array} * Relation events in insertion order. */ value: function getRelations() { return (0, _toConsumableArray2["default"])(this._relations); } }, { key: "_addAnnotationToAggregation", value: function _addAnnotationToAggregation(event) { var _event$getRelation = event.getRelation(), key = _event$getRelation.key; if (!key) { return; } var eventsForKey = this._annotationsByKey[key]; if (!eventsForKey) { eventsForKey = this._annotationsByKey[key] = new Set(); this._sortedAnnotationsByKey.push([key, eventsForKey]); } // Add the new event to the set for this key eventsForKey.add(event); // Re-sort the [key, events] pairs in descending order of event count this._sortedAnnotationsByKey.sort(function (a, b) { var aEvents = a[1]; var bEvents = b[1]; return bEvents.size - aEvents.size; }); var sender = event.getSender(); var eventsFromSender = this._annotationsBySender[sender]; if (!eventsFromSender) { eventsFromSender = this._annotationsBySender[sender] = new Set(); } // Add the new event to the set for this sender eventsFromSender.add(event); } }, { key: "_removeAnnotationFromAggregation", value: function _removeAnnotationFromAggregation(event) { var _event$getRelation2 = event.getRelation(), key = _event$getRelation2.key; if (!key) { return; } var eventsForKey = this._annotationsByKey[key]; if (eventsForKey) { eventsForKey["delete"](event); // Re-sort the [key, events] pairs in descending order of event count this._sortedAnnotationsByKey.sort(function (a, b) { var aEvents = a[1]; var bEvents = b[1]; return bEvents.size - aEvents.size; }); } var sender = event.getSender(); var eventsFromSender = this._annotationsBySender[sender]; if (eventsFromSender) { eventsFromSender["delete"](event); } } /** * For relations that have been redacted, we want to remove them from * aggregation data sets and emit an update event. * * To do so, we listen for `Event.beforeRedaction`, which happens: * - after the server accepted the redaction and remote echoed back to us * - before the original event has been marked redacted in the client * * @param {MatrixEvent} redactedEvent * The original relation event that is about to be redacted. */ }, { key: "getSortedAnnotationsByKey", /** * Get all events in this collection grouped by key and sorted by descending * event count in each group. * * This is currently only supported for the annotation relation type. * * @return {Array} * An array of [key, events] pairs sorted by descending event count. * The events are stored in a Set (which preserves insertion order). */ value: function getSortedAnnotationsByKey() { if (this.relationType !== "m.annotation") { // Other relation types are not grouped currently. return null; } return this._sortedAnnotationsByKey; } /** * Get all events in this collection grouped by sender. * * This is currently only supported for the annotation relation type. * * @return {Object} * An object with each relation sender as a key and the matching Set of * events for that sender as a value. */ }, { key: "getAnnotationsBySender", value: function getAnnotationsBySender() { if (this.relationType !== "m.annotation") { // Other relation types are not grouped currently. return null; } return this._annotationsBySender; } /** * Returns the most recent (and allowed) m.replace relation, if any. * * This is currently only supported for the m.replace relation type, * once the target event is known, see `addEvent`. * * @return {MatrixEvent?} */ }, { key: "getLastReplacement", value: function getLastReplacement() { var _this2 = this; if (this.relationType !== "m.replace") { // Aggregating on last only makes sense for this relation type return null; } if (!this._targetEvent) { // Don't know which replacements to accept yet. // This method shouldn't be called before the original // event is known anyway. return null; } // the all-knowning server tells us that the event at some point had // this timestamp for its replacement, so any following replacement should definitely not be less var replaceRelation = this._targetEvent.getServerAggregatedRelation("m.replace"); var minTs = replaceRelation && replaceRelation.origin_server_ts; return this.getRelations().reduce(function (last, event) { if (event.getSender() !== _this2._targetEvent.getSender()) { return last; } if (minTs && minTs > event.getTs()) { return last; } if (last && last.getTs() > event.getTs()) { return last; } return event; }, null); } /* * @param {MatrixEvent} targetEvent the event the relations are related to. */ }, { key: "setTargetEvent", value: function setTargetEvent(event) { if (this._targetEvent) { return; } this._targetEvent = event; if (this.relationType === "m.replace") { var replacement = this.getLastReplacement(); // this is the initial update, so only call it if we already have something // to not emit Event.replaced needlessly if (replacement) { this._targetEvent.makeReplaced(replacement); } } } }]); return Relations; }(_events.EventEmitter); exports.Relations = Relations; },{"../models/event":100,"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/defineProperty":9,"@babel/runtime/helpers/getPrototypeOf":10,"@babel/runtime/helpers/inherits":11,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/possibleConstructorReturn":20,"@babel/runtime/helpers/toConsumableArray":23,"events":36}],103:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RoomMember = RoomMember; var _events = require("events"); var _contentRepo = require("../content-repo"); var utils = _interopRequireWildcard(require("../utils")); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/room-member */ /** * Construct a new room member. * * @constructor * @alias module:models/room-member * * @param {string} roomId The room ID of the member. * @param {string} userId The user ID of the member. * @prop {string} roomId The room ID for this member. * @prop {string} userId The user ID of this member. * @prop {boolean} typing True if the room member is currently typing. * @prop {string} name The human-readable name for this room member. This will be * disambiguated with a suffix of " (@user_id:matrix.org)" if another member shares the * same displayname. * @prop {string} rawDisplayName The ambiguous displayname of this room member. * @prop {Number} powerLevel The power level for this room member. * @prop {Number} powerLevelNorm The normalised power level (0-100) for this * room member. * @prop {User} user The User object for this room member, if one exists. * @prop {string} membership The membership state for this room member e.g. 'join'. * @prop {Object} events The events describing this RoomMember. * @prop {MatrixEvent} events.member The m.room.member event for this RoomMember. */ function RoomMember(roomId, userId) { this.roomId = roomId; this.userId = userId; this.typing = false; this.name = userId; this.rawDisplayName = userId; this.powerLevel = 0; this.powerLevelNorm = 0; this.user = null; this.membership = null; this.events = { member: null }; this._isOutOfBand = false; this._updateModifiedTime(); } utils.inherits(RoomMember, _events.EventEmitter); /** * Mark the member as coming from a channel that is not sync */ RoomMember.prototype.markOutOfBand = function () { this._isOutOfBand = true; }; /** * @return {bool} does the member come from a channel that is not sync? * This is used to store the member seperately * from the sync state so it available across browser sessions. */ RoomMember.prototype.isOutOfBand = function () { return this._isOutOfBand; }; /** * Update this room member's membership event. May fire "RoomMember.name" if * this event updates this member's name. * @param {MatrixEvent} event The m.room.member event * @param {RoomState} roomState Optional. The room state to take into account * when calculating (e.g. for disambiguating users with the same name). * @fires module:client~MatrixClient#event:"RoomMember.name" * @fires module:client~MatrixClient#event:"RoomMember.membership" */ RoomMember.prototype.setMembershipEvent = function (event, roomState) { if (event.getType() !== "m.room.member") { return; } this._isOutOfBand = false; this.events.member = event; var oldMembership = this.membership; this.membership = event.getDirectionalContent().membership; var oldName = this.name; this.name = calculateDisplayName(this.userId, event.getDirectionalContent().displayname, roomState); this.rawDisplayName = event.getDirectionalContent().displayname || this.userId; if (oldMembership !== this.membership) { this._updateModifiedTime(); this.emit("RoomMember.membership", event, this, oldMembership); } if (oldName !== this.name) { this._updateModifiedTime(); this.emit("RoomMember.name", event, this, oldName); } }; /** * Update this room member's power level event. May fire * "RoomMember.powerLevel" if this event updates this member's power levels. * @param {MatrixEvent} powerLevelEvent The m.room.power_levels * event * @fires module:client~MatrixClient#event:"RoomMember.powerLevel" */ RoomMember.prototype.setPowerLevelEvent = function (powerLevelEvent) { if (powerLevelEvent.getType() !== "m.room.power_levels") { return; } var evContent = powerLevelEvent.getDirectionalContent(); var maxLevel = evContent.users_default || 0; utils.forEach(utils.values(evContent.users), function (lvl) { maxLevel = Math.max(maxLevel, lvl); }); var oldPowerLevel = this.powerLevel; var oldPowerLevelNorm = this.powerLevelNorm; if (evContent.users && evContent.users[this.userId] !== undefined) { this.powerLevel = evContent.users[this.userId]; } else if (evContent.users_default !== undefined) { this.powerLevel = evContent.users_default; } else { this.powerLevel = 0; } this.powerLevelNorm = 0; if (maxLevel > 0) { this.powerLevelNorm = this.powerLevel * 100 / maxLevel; } // emit for changes in powerLevelNorm as well (since the app will need to // redraw everyone's level if the max has changed) if (oldPowerLevel !== this.powerLevel || oldPowerLevelNorm !== this.powerLevelNorm) { this._updateModifiedTime(); this.emit("RoomMember.powerLevel", powerLevelEvent, this); } }; /** * Update this room member's typing event. May fire "RoomMember.typing" if * this event changes this member's typing state. * @param {MatrixEvent} event The typing event * @fires module:client~MatrixClient#event:"RoomMember.typing" */ RoomMember.prototype.setTypingEvent = function (event) { if (event.getType() !== "m.typing") { return; } var oldTyping = this.typing; this.typing = false; var typingList = event.getContent().user_ids; if (!utils.isArray(typingList)) { // malformed event :/ bail early. TODO: whine? return; } if (typingList.indexOf(this.userId) !== -1) { this.typing = true; } if (oldTyping !== this.typing) { this._updateModifiedTime(); this.emit("RoomMember.typing", event, this); } }; /** * Update the last modified time to the current time. */ RoomMember.prototype._updateModifiedTime = function () { this._modified = Date.now(); }; /** * Get the timestamp when this RoomMember was last updated. This timestamp is * updated when properties on this RoomMember are updated. * It is updated before firing events. * @return {number} The timestamp */ RoomMember.prototype.getLastModifiedTime = function () { return this._modified; }; RoomMember.prototype.isKicked = function () { return this.membership === "leave" && this.events.member.getSender() !== this.events.member.getStateKey(); }; /** * If this member was invited with the is_direct flag set, return * the user that invited this member * @return {string} user id of the inviter */ RoomMember.prototype.getDMInviter = function () { // when not available because that room state hasn't been loaded in, // we don't really know, but more likely to not be a direct chat if (this.events.member) { // TODO: persist the is_direct flag on the member as more member events // come in caused by displayName changes. // the is_direct flag is set on the invite member event. // This is copied on the prev_content section of the join member event // when the invite is accepted. var memberEvent = this.events.member; var memberContent = memberEvent.getContent(); var inviteSender = memberEvent.getSender(); if (memberContent.membership === "join") { memberContent = memberEvent.getPrevContent(); inviteSender = memberEvent.getUnsigned().prev_sender; } if (memberContent.membership === "invite" && memberContent.is_direct) { return inviteSender; } } }; /** * Get the avatar URL for a room member. * @param {string} baseUrl The base homeserver URL See * {@link module:client~MatrixClient#getHomeserverUrl}. * @param {Number} width The desired width of the thumbnail. * @param {Number} height The desired height of the thumbnail. * @param {string} resizeMethod The thumbnail resize method to use, either * "crop" or "scale". * @param {Boolean} allowDefault (optional) Passing false causes this method to * return null if the user has no avatar image. Otherwise, a default image URL * will be returned. Default: true. (Deprecated) * @param {Boolean} allowDirectLinks (optional) If true, the avatar URL will be * returned even if it is a direct hyperlink rather than a matrix content URL. * If false, any non-matrix content URLs will be ignored. Setting this option to * true will expose URLs that, if fetched, will leak information about the user * to anyone who they share a room with. * @return {?string} the avatar URL or null. */ RoomMember.prototype.getAvatarUrl = function (baseUrl, width, height, resizeMethod, allowDefault, allowDirectLinks) { if (allowDefault === undefined) { allowDefault = true; } var rawUrl = this.getMxcAvatarUrl(); if (!rawUrl && !allowDefault) { return null; } var httpUrl = (0, _contentRepo.getHttpUriForMxc)(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks); if (httpUrl) { return httpUrl; } return null; }; /** * get the mxc avatar url, either from a state event, or from a lazily loaded member * @return {string} the mxc avatar url */ RoomMember.prototype.getMxcAvatarUrl = function () { if (this.events.member) { return this.events.member.getDirectionalContent().avatar_url; } else if (this.user) { return this.user.avatarUrl; } return null; }; function calculateDisplayName(selfUserId, displayName, roomState) { if (!displayName || displayName === selfUserId) { return selfUserId; } // First check if the displayname is something we consider truthy // after stripping it of zero width characters and padding spaces if (!utils.removeHiddenChars(displayName)) { return selfUserId; } if (!roomState) { return displayName; } // Next check if the name contains something that look like a mxid // If it does, it may be someone trying to impersonate someone else // Show full mxid in this case var disambiguate = /@.+:.+/.test(displayName); if (!disambiguate) { // Also show mxid if the display name contains any LTR/RTL characters as these // make it very difficult for us to find similar *looking* display names // E.g "Mark" could be cloned by writing "kraM" but in RTL. disambiguate = /[\u200E\u200F\u202A-\u202F]/.test(displayName); } if (!disambiguate) { // Also show mxid if there are other people with the same or similar // displayname, after hidden character removal. var userIds = roomState.getUserIdsWithDisplayName(displayName); disambiguate = userIds.some(function (u) { return u !== selfUserId; }); } if (disambiguate) { return displayName + " (" + selfUserId + ")"; } return displayName; } /** * Fires whenever any room member's name changes. * @event module:client~MatrixClient#"RoomMember.name" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomMember} member The member whose RoomMember.name changed. * @param {string?} oldName The previous name. Null if the member didn't have a * name previously. * @example * matrixClient.on("RoomMember.name", function(event, member){ * var newName = member.name; * }); */ /** * Fires whenever any room member's membership state changes. * @event module:client~MatrixClient#"RoomMember.membership" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomMember} member The member whose RoomMember.membership changed. * @param {string?} oldMembership The previous membership state. Null if it's a * new member. * @example * matrixClient.on("RoomMember.membership", function(event, member, oldMembership){ * var newState = member.membership; * }); */ /** * Fires whenever any room member's typing state changes. * @event module:client~MatrixClient#"RoomMember.typing" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomMember} member The member whose RoomMember.typing changed. * @example * matrixClient.on("RoomMember.typing", function(event, member){ * var isTyping = member.typing; * }); */ /** * Fires whenever any room member's power level changes. * @event module:client~MatrixClient#"RoomMember.powerLevel" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomMember} member The member whose RoomMember.powerLevel changed. * @example * matrixClient.on("RoomMember.powerLevel", function(event, member){ * var newPowerLevel = member.powerLevel; * var newNormPowerLevel = member.powerLevelNorm; * }); */ },{"../content-repo":59,"../utils":123,"@babel/runtime/helpers/interopRequireWildcard":13,"events":36}],104:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RoomState = RoomState; var _events = require("events"); var _roomMember = require("./room-member"); var _logger = require("../logger"); var utils = _interopRequireWildcard(require("../utils")); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/room-state */ // possible statuses for out-of-band member loading var OOB_STATUS_NOTSTARTED = 1; var OOB_STATUS_INPROGRESS = 2; var OOB_STATUS_FINISHED = 3; /** * Construct room state. * * Room State represents the state of the room at a given point. * It can be mutated by adding state events to it. * There are two types of room member associated with a state event: * normal member objects (accessed via getMember/getMembers) which mutate * with the state to represent the current state of that room/user, eg. * the object returned by getMember('@bob:example.com') will mutate to * get a different display name if Bob later changes his display name * in the room. * There are also 'sentinel' members (accessed via getSentinelMember). * These also represent the state of room members at the point in time * represented by the RoomState object, but unlike objects from getMember, * sentinel objects will always represent the room state as at the time * getSentinelMember was called, so if Bob subsequently changes his display * name, a room member object previously acquired with getSentinelMember * will still have his old display name. Calling getSentinelMember again * after the display name change will return a new RoomMember object * with Bob's new display name. * * @constructor * @param {?string} roomId Optional. The ID of the room which has this state. * If none is specified it just tracks paginationTokens, useful for notifTimelineSet * @param {?object} oobMemberFlags Optional. The state of loading out of bound members. * As the timeline might get reset while they are loading, this state needs to be inherited * and shared when the room state is cloned for the new timeline. * This should only be passed from clone. * @prop {Object.} members The room member dictionary, keyed * on the user's ID. * @prop {Object.>} events The state * events dictionary, keyed on the event type and then the state_key value. * @prop {string} paginationToken The pagination token for this state. */ function RoomState(roomId) { var oobMemberFlags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; this.roomId = roomId; this.members = {// userId: RoomMember }; this.events = new Map(); // Map> this.paginationToken = null; this._sentinels = {// userId: RoomMember }; this._updateModifiedTime(); // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys) this._displayNameToUserIds = {}; this._userIdsToDisplayNames = {}; this._tokenToInvite = {}; // 3pid invite state_key to m.room.member invite this._joinedMemberCount = null; // cache of the number of joined members // joined members count from summary api // once set, we know the server supports the summary api // and we should only trust that // we could also only trust that before OOB members // are loaded but doesn't seem worth the hassle atm this._summaryJoinedMemberCount = null; // same for invited member count this._invitedMemberCount = null; this._summaryInvitedMemberCount = null; if (!oobMemberFlags) { oobMemberFlags = { status: OOB_STATUS_NOTSTARTED }; } this._oobMemberFlags = oobMemberFlags; } utils.inherits(RoomState, _events.EventEmitter); /** * Returns the number of joined members in this room * This method caches the result. * @return {integer} The number of members in this room whose membership is 'join' */ RoomState.prototype.getJoinedMemberCount = function () { if (this._summaryJoinedMemberCount !== null) { return this._summaryJoinedMemberCount; } if (this._joinedMemberCount === null) { this._joinedMemberCount = this.getMembers().reduce(function (count, m) { return m.membership === 'join' ? count + 1 : count; }, 0); } return this._joinedMemberCount; }; /** * Set the joined member count explicitly (like from summary part of the sync response) * @param {number} count the amount of joined members */ RoomState.prototype.setJoinedMemberCount = function (count) { this._summaryJoinedMemberCount = count; }; /** * Returns the number of invited members in this room * @return {integer} The number of members in this room whose membership is 'invite' */ RoomState.prototype.getInvitedMemberCount = function () { if (this._summaryInvitedMemberCount !== null) { return this._summaryInvitedMemberCount; } if (this._invitedMemberCount === null) { this._invitedMemberCount = this.getMembers().reduce(function (count, m) { return m.membership === 'invite' ? count + 1 : count; }, 0); } return this._invitedMemberCount; }; /** * Set the amount of invited members in this room * @param {number} count the amount of invited members */ RoomState.prototype.setInvitedMemberCount = function (count) { this._summaryInvitedMemberCount = count; }; /** * Get all RoomMembers in this room. * @return {Array} A list of RoomMembers. */ RoomState.prototype.getMembers = function () { return utils.values(this.members); }; /** * Get all RoomMembers in this room, excluding the user IDs provided. * @param {Array} excludedIds The user IDs to exclude. * @return {Array} A list of RoomMembers. */ RoomState.prototype.getMembersExcept = function (excludedIds) { return utils.values(this.members).filter(function (m) { return !excludedIds.includes(m.userId); }); }; /** * Get a room member by their user ID. * @param {string} userId The room member's user ID. * @return {RoomMember} The member or null if they do not exist. */ RoomState.prototype.getMember = function (userId) { return this.members[userId] || null; }; /** * Get a room member whose properties will not change with this room state. You * typically want this if you want to attach a RoomMember to a MatrixEvent which * may no longer be represented correctly by Room.currentState or Room.oldState. * The term 'sentinel' refers to the fact that this RoomMember is an unchanging * guardian for state at this particular point in time. * @param {string} userId The room member's user ID. * @return {RoomMember} The member or null if they do not exist. */ RoomState.prototype.getSentinelMember = function (userId) { if (!userId) return null; var sentinel = this._sentinels[userId]; if (sentinel === undefined) { sentinel = new _roomMember.RoomMember(this.roomId, userId); var member = this.members[userId]; if (member) { sentinel.setMembershipEvent(member.events.member, this); } this._sentinels[userId] = sentinel; } return sentinel; }; /** * Get state events from the state of the room. * @param {string} eventType The event type of the state event. * @param {string} stateKey Optional. The state_key of the state event. If * this is undefined then all matching state events will be * returned. * @return {MatrixEvent[]|MatrixEvent} A list of events if state_key was * undefined, else a single event (or null if no match found). */ RoomState.prototype.getStateEvents = function (eventType, stateKey) { if (!this.events.has(eventType)) { // no match return stateKey === undefined ? [] : null; } if (stateKey === undefined) { // return all values return Array.from(this.events.get(eventType).values()); } var event = this.events.get(eventType).get(stateKey); return event ? event : null; }; /** * Creates a copy of this room state so that mutations to either won't affect the other. * @return {RoomState} the copy of the room state */ RoomState.prototype.clone = function () { var copy = new RoomState(this.roomId, this._oobMemberFlags); // Ugly hack: because setStateEvents will mark // members as susperseding future out of bound members // if loading is in progress (through _oobMemberFlags) // since these are not new members, we're merely copying them // set the status to not started // after copying, we set back the status var status = this._oobMemberFlags.status; this._oobMemberFlags.status = OOB_STATUS_NOTSTARTED; Array.from(this.events.values()).forEach(function (eventsByStateKey) { copy.setStateEvents(Array.from(eventsByStateKey.values())); }); // Ugly hack: see above this._oobMemberFlags.status = status; if (this._summaryInvitedMemberCount !== null) { copy.setInvitedMemberCount(this.getInvitedMemberCount()); } if (this._summaryJoinedMemberCount !== null) { copy.setJoinedMemberCount(this.getJoinedMemberCount()); } // copy out of band flags if needed if (this._oobMemberFlags.status == OOB_STATUS_FINISHED) { // copy markOutOfBand flags this.getMembers().forEach(function (member) { if (member.isOutOfBand()) { var copyMember = copy.getMember(member.userId); copyMember.markOutOfBand(); } }); } return copy; }; /** * Add previously unknown state events. * When lazy loading members while back-paginating, * the relevant room state for the timeline chunk at the end * of the chunk can be set with this method. * @param {MatrixEvent[]} events state events to prepend */ RoomState.prototype.setUnknownStateEvents = function (events) { var _this = this; var unknownStateEvents = events.filter(function (event) { return !_this.events.has(event.getType()) || !_this.events.get(event.getType()).has(event.getStateKey()); }); this.setStateEvents(unknownStateEvents); }; /** * Add an array of one or more state MatrixEvents, overwriting * any existing state with the same {type, stateKey} tuple. Will fire * "RoomState.events" for every event added. May fire "RoomState.members" * if there are m.room.member events. * @param {MatrixEvent[]} stateEvents a list of state events for this room. * @fires module:client~MatrixClient#event:"RoomState.members" * @fires module:client~MatrixClient#event:"RoomState.newMember" * @fires module:client~MatrixClient#event:"RoomState.events" */ RoomState.prototype.setStateEvents = function (stateEvents) { var self = this; this._updateModifiedTime(); // update the core event dict utils.forEach(stateEvents, function (event) { if (event.getRoomId() !== self.roomId) { return; } if (!event.isState()) { return; } var lastStateEvent = self._getStateEventMatching(event); self._setStateEvent(event); if (event.getType() === "m.room.member") { _updateDisplayNameCache(self, event.getStateKey(), event.getContent().displayname); _updateThirdPartyTokenCache(self, event); } self.emit("RoomState.events", event, self, lastStateEvent); }); // update higher level data structures. This needs to be done AFTER the // core event dict as these structures may depend on other state events in // the given array (e.g. disambiguating display names in one go to do both // clashing names rather than progressively which only catches 1 of them). utils.forEach(stateEvents, function (event) { if (event.getRoomId() !== self.roomId) { return; } if (!event.isState()) { return; } if (event.getType() === "m.room.member") { var userId = event.getStateKey(); // leave events apparently elide the displayname or avatar_url, // so let's fake one up so that we don't leak user ids // into the timeline if (event.getContent().membership === "leave" || event.getContent().membership === "ban") { event.getContent().avatar_url = event.getContent().avatar_url || event.getPrevContent().avatar_url; event.getContent().displayname = event.getContent().displayname || event.getPrevContent().displayname; } var member = self._getOrCreateMember(userId, event); member.setMembershipEvent(event, self); self._updateMember(member); self.emit("RoomState.members", event, self, member); } else if (event.getType() === "m.room.power_levels") { var members = utils.values(self.members); utils.forEach(members, function (member) { member.setPowerLevelEvent(event); self.emit("RoomState.members", event, self, member); }); // assume all our sentinels are now out-of-date self._sentinels = {}; } }); }; /** * Looks up a member by the given userId, and if it doesn't exist, * create it and emit the `RoomState.newMember` event. * This method makes sure the member is added to the members dictionary * before emitting, as this is done from setStateEvents and _setOutOfBandMember. * @param {string} userId the id of the user to look up * @param {MatrixEvent} event the membership event for the (new) member. Used to emit. * @fires module:client~MatrixClient#event:"RoomState.newMember" * @returns {RoomMember} the member, existing or newly created. */ RoomState.prototype._getOrCreateMember = function (userId, event) { var member = this.members[userId]; if (!member) { member = new _roomMember.RoomMember(this.roomId, userId); // add member to members before emitting any events, // as event handlers often lookup the member this.members[userId] = member; this.emit("RoomState.newMember", event, this, member); } return member; }; RoomState.prototype._setStateEvent = function (event) { if (!this.events.has(event.getType())) { this.events.set(event.getType(), new Map()); } this.events.get(event.getType()).set(event.getStateKey(), event); }; RoomState.prototype._getStateEventMatching = function (event) { if (!this.events.has(event.getType())) return null; return this.events.get(event.getType()).get(event.getStateKey()); }; RoomState.prototype._updateMember = function (member) { // this member may have a power level already, so set it. var pwrLvlEvent = this.getStateEvents("m.room.power_levels", ""); if (pwrLvlEvent) { member.setPowerLevelEvent(pwrLvlEvent); } // blow away the sentinel which is now outdated delete this._sentinels[member.userId]; this.members[member.userId] = member; this._joinedMemberCount = null; this._invitedMemberCount = null; }; /** * Get the out-of-band members loading state, whether loading is needed or not. * Note that loading might be in progress and hence isn't needed. * @return {bool} whether or not the members of this room need to be loaded */ RoomState.prototype.needsOutOfBandMembers = function () { return this._oobMemberFlags.status === OOB_STATUS_NOTSTARTED; }; /** * Mark this room state as waiting for out-of-band members, * ensuring it doesn't ask for them to be requested again * through needsOutOfBandMembers */ RoomState.prototype.markOutOfBandMembersStarted = function () { if (this._oobMemberFlags.status !== OOB_STATUS_NOTSTARTED) { return; } this._oobMemberFlags.status = OOB_STATUS_INPROGRESS; }; /** * Mark this room state as having failed to fetch out-of-band members */ RoomState.prototype.markOutOfBandMembersFailed = function () { if (this._oobMemberFlags.status !== OOB_STATUS_INPROGRESS) { return; } this._oobMemberFlags.status = OOB_STATUS_NOTSTARTED; }; /** * Clears the loaded out-of-band members */ RoomState.prototype.clearOutOfBandMembers = function () { var _this2 = this; var count = 0; Object.keys(this.members).forEach(function (userId) { var member = _this2.members[userId]; if (member.isOutOfBand()) { ++count; delete _this2.members[userId]; } }); _logger.logger.log("LL: RoomState removed ".concat(count, " members...")); this._oobMemberFlags.status = OOB_STATUS_NOTSTARTED; }; /** * Sets the loaded out-of-band members. * @param {MatrixEvent[]} stateEvents array of membership state events */ RoomState.prototype.setOutOfBandMembers = function (stateEvents) { var _this3 = this; _logger.logger.log("LL: RoomState about to set ".concat(stateEvents.length, " OOB members ...")); if (this._oobMemberFlags.status !== OOB_STATUS_INPROGRESS) { return; } _logger.logger.log("LL: RoomState put in OOB_STATUS_FINISHED state ..."); this._oobMemberFlags.status = OOB_STATUS_FINISHED; stateEvents.forEach(function (e) { return _this3._setOutOfBandMember(e); }); }; /** * Sets a single out of band member, used by both setOutOfBandMembers and clone * @param {MatrixEvent} stateEvent membership state event */ RoomState.prototype._setOutOfBandMember = function (stateEvent) { if (stateEvent.getType() !== 'm.room.member') { return; } var userId = stateEvent.getStateKey(); var existingMember = this.getMember(userId); // never replace members received as part of the sync if (existingMember && !existingMember.isOutOfBand()) { return; } var member = this._getOrCreateMember(userId, stateEvent); member.setMembershipEvent(stateEvent, this); // needed to know which members need to be stored seperately // as they are not part of the sync accumulator // this is cleared by setMembershipEvent so when it's updated through /sync member.markOutOfBand(); _updateDisplayNameCache(this, member.userId, member.name); this._setStateEvent(stateEvent); this._updateMember(member); this.emit("RoomState.members", stateEvent, this, member); }; /** * Set the current typing event for this room. * @param {MatrixEvent} event The typing event */ RoomState.prototype.setTypingEvent = function (event) { utils.forEach(utils.values(this.members), function (member) { member.setTypingEvent(event); }); }; /** * Get the m.room.member event which has the given third party invite token. * * @param {string} token The token * @return {?MatrixEvent} The m.room.member event or null */ RoomState.prototype.getInviteForThreePidToken = function (token) { return this._tokenToInvite[token] || null; }; /** * Update the last modified time to the current time. */ RoomState.prototype._updateModifiedTime = function () { this._modified = Date.now(); }; /** * Get the timestamp when this room state was last updated. This timestamp is * updated when this object has received new state events. * @return {number} The timestamp */ RoomState.prototype.getLastModifiedTime = function () { return this._modified; }; /** * Get user IDs with the specified or similar display names. * @param {string} displayName The display name to get user IDs from. * @return {string[]} An array of user IDs or an empty array. */ RoomState.prototype.getUserIdsWithDisplayName = function (displayName) { return this._displayNameToUserIds[utils.removeHiddenChars(displayName)] || []; }; /** * Returns true if userId is in room, event is not redacted and either sender of * mxEvent or has power level sufficient to redact events other than their own. * @param {MatrixEvent} mxEvent The event to test permission for * @param {string} userId The user ID of the user to test permission for * @return {boolean} true if the given used ID can redact given event */ RoomState.prototype.maySendRedactionForEvent = function (mxEvent, userId) { var member = this.getMember(userId); if (!member || member.membership === 'leave') return false; if (mxEvent.status || mxEvent.isRedacted()) return false; // The user may have been the sender, but they can't redact their own message // if redactions are blocked. var canRedact = this.maySendEvent("m.room.redaction", userId); if (mxEvent.getSender() === userId) return canRedact; return this._hasSufficientPowerLevelFor('redact', member.powerLevel); }; /** * Returns true if the given power level is sufficient for action * @param {string} action The type of power level to check * @param {number} powerLevel The power level of the member * @return {boolean} true if the given power level is sufficient */ RoomState.prototype._hasSufficientPowerLevelFor = function (action, powerLevel) { var powerLevelsEvent = this.getStateEvents('m.room.power_levels', ''); var powerLevels = {}; if (powerLevelsEvent) { powerLevels = powerLevelsEvent.getContent(); } var requiredLevel = 50; if (utils.isNumber(powerLevels[action])) { requiredLevel = powerLevels[action]; } return powerLevel >= requiredLevel; }; /** * Short-form for maySendEvent('m.room.message', userId) * @param {string} userId The user ID of the user to test permission for * @return {boolean} true if the given user ID should be permitted to send * message events into the given room. */ RoomState.prototype.maySendMessage = function (userId) { return this._maySendEventOfType('m.room.message', userId, false); }; /** * Returns true if the given user ID has permission to send a normal * event of type `eventType` into this room. * @param {string} eventType The type of event to test * @param {string} userId The user ID of the user to test permission for * @return {boolean} true if the given user ID should be permitted to send * the given type of event into this room, * according to the room's state. */ RoomState.prototype.maySendEvent = function (eventType, userId) { return this._maySendEventOfType(eventType, userId, false); }; /** * Returns true if the given MatrixClient has permission to send a state * event of type `stateEventType` into this room. * @param {string} stateEventType The type of state events to test * @param {MatrixClient} cli The client to test permission for * @return {boolean} true if the given client should be permitted to send * the given type of state event into this room, * according to the room's state. */ RoomState.prototype.mayClientSendStateEvent = function (stateEventType, cli) { if (cli.isGuest()) { return false; } return this.maySendStateEvent(stateEventType, cli.credentials.userId); }; /** * Returns true if the given user ID has permission to send a state * event of type `stateEventType` into this room. * @param {string} stateEventType The type of state events to test * @param {string} userId The user ID of the user to test permission for * @return {boolean} true if the given user ID should be permitted to send * the given type of state event into this room, * according to the room's state. */ RoomState.prototype.maySendStateEvent = function (stateEventType, userId) { return this._maySendEventOfType(stateEventType, userId, true); }; /** * Returns true if the given user ID has permission to send a normal or state * event of type `eventType` into this room. * @param {string} eventType The type of event to test * @param {string} userId The user ID of the user to test permission for * @param {boolean} state If true, tests if the user may send a state event of this type. Otherwise tests whether they may send a regular event. * @return {boolean} true if the given user ID should be permitted to send * the given type of event into this room, * according to the room's state. */ RoomState.prototype._maySendEventOfType = function (eventType, userId, state) { var power_levels_event = this.getStateEvents('m.room.power_levels', ''); var power_levels; var events_levels = {}; var state_default = 0; var events_default = 0; var powerLevel = 0; if (power_levels_event) { power_levels = power_levels_event.getContent(); events_levels = power_levels.events || {}; if (Number.isFinite(power_levels.state_default)) { state_default = power_levels.state_default; } else { state_default = 50; } var userPowerLevel = power_levels.users && power_levels.users[userId]; if (Number.isFinite(userPowerLevel)) { powerLevel = userPowerLevel; } else if (Number.isFinite(power_levels.users_default)) { powerLevel = power_levels.users_default; } if (Number.isFinite(power_levels.events_default)) { events_default = power_levels.events_default; } } var required_level = state ? state_default : events_default; if (Number.isFinite(events_levels[eventType])) { required_level = events_levels[eventType]; } return powerLevel >= required_level; }; /** * Returns true if the given user ID has permission to trigger notification * of type `notifLevelKey` * @param {string} notifLevelKey The level of notification to test (eg. 'room') * @param {string} userId The user ID of the user to test permission for * @return {boolean} true if the given user ID has permission to trigger a * notification of this type. */ RoomState.prototype.mayTriggerNotifOfType = function (notifLevelKey, userId) { var member = this.getMember(userId); if (!member) { return false; } var powerLevelsEvent = this.getStateEvents('m.room.power_levels', ''); var notifLevel = 50; if (powerLevelsEvent && powerLevelsEvent.getContent() && powerLevelsEvent.getContent().notifications && utils.isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])) { notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey]; } return member.powerLevel >= notifLevel; }; function _updateThirdPartyTokenCache(roomState, memberEvent) { if (!memberEvent.getContent().third_party_invite) { return; } var token = (memberEvent.getContent().third_party_invite.signed || {}).token; if (!token) { return; } var threePidInvite = roomState.getStateEvents("m.room.third_party_invite", token); if (!threePidInvite) { return; } roomState._tokenToInvite[token] = memberEvent; } function _updateDisplayNameCache(roomState, userId, displayName) { var oldName = roomState._userIdsToDisplayNames[userId]; delete roomState._userIdsToDisplayNames[userId]; if (oldName) { // Remove the old name from the cache. // We clobber the user_id > name lookup but the name -> [user_id] lookup // means we need to remove that user ID from that array rather than nuking // the lot. var strippedOldName = utils.removeHiddenChars(oldName); var existingUserIds = roomState._displayNameToUserIds[strippedOldName]; if (existingUserIds) { // remove this user ID from this array var filteredUserIDs = existingUserIds.filter(function (id) { return id !== userId; }); roomState._displayNameToUserIds[strippedOldName] = filteredUserIDs; } } roomState._userIdsToDisplayNames[userId] = displayName; var strippedDisplayname = displayName && utils.removeHiddenChars(displayName); // an empty stripped displayname (undefined/'') will be set to MXID in room-member.js if (strippedDisplayname) { if (!roomState._displayNameToUserIds[strippedDisplayname]) { roomState._displayNameToUserIds[strippedDisplayname] = []; } roomState._displayNameToUserIds[strippedDisplayname].push(userId); } } /** * Fires whenever the event dictionary in room state is updated. * @event module:client~MatrixClient#"RoomState.events" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomState} state The room state whose RoomState.events dictionary * was updated. * @param {MatrixEvent} prevEvent The event being replaced by the new state, if * known. Note that this can differ from `getPrevContent()` on the new state event * as this is the store's view of the last state, not the previous state provided * by the server. * @example * matrixClient.on("RoomState.events", function(event, state, prevEvent){ * var newStateEvent = event; * }); */ /** * Fires whenever a member in the members dictionary is updated in any way. * @event module:client~MatrixClient#"RoomState.members" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomState} state The room state whose RoomState.members dictionary * was updated. * @param {RoomMember} member The room member that was updated. * @example * matrixClient.on("RoomState.members", function(event, state, member){ * var newMembershipState = member.membership; * }); */ /** * Fires whenever a member is added to the members dictionary. The RoomMember * will not be fully populated yet (e.g. no membership state) but will already * be available in the members dictionary. * @event module:client~MatrixClient#"RoomState.newMember" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {RoomState} state The room state whose RoomState.members dictionary * was updated with a new entry. * @param {RoomMember} member The room member that was added. * @example * matrixClient.on("RoomState.newMember", function(event, state, member){ * // add event listeners on 'member' * }); */ },{"../logger":95,"../utils":123,"./room-member":103,"@babel/runtime/helpers/interopRequireWildcard":13,"events":36}],105:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RoomSummary = RoomSummary; /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/room-summary */ /** * Construct a new Room Summary. A summary can be used for display on a recent * list, without having to load the entire room list into memory. * @constructor * @param {string} roomId Required. The ID of this room. * @param {Object} info Optional. The summary info. Additional keys are supported. * @param {string} info.title The title of the room (e.g. m.room.name) * @param {string} info.desc The description of the room (e.g. * m.room.topic) * @param {Number} info.numMembers The number of joined users. * @param {string[]} info.aliases The list of aliases for this room. * @param {Number} info.timestamp The timestamp for this room. */ function RoomSummary(roomId, info) { this.roomId = roomId; this.info = info; } },{}],106:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.Room = Room; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _events = require("events"); var _eventTimelineSet = require("./event-timeline-set"); var _eventTimeline = require("./event-timeline"); var _contentRepo = require("../content-repo"); var utils = _interopRequireWildcard(require("../utils")); var _event = require("./event"); var _roomMember = require("./room-member"); var _roomSummary = require("./room-summary"); var _logger = require("../logger"); var _ReEmitter = require("../ReEmitter"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } // These constants are used as sane defaults when the homeserver doesn't support // the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be // the same as the common default room version whereas SAFE_ROOM_VERSIONS are the // room versions which are considered okay for people to run without being asked // to upgrade (ie: "stable"). Eventually, we should remove these when all homeservers // return an m.room_versions capability. var KNOWN_SAFE_ROOM_VERSION = '5'; var SAFE_ROOM_VERSIONS = ['1', '2', '3', '4', '5']; function synthesizeReceipt(userId, event, receiptType) { // console.log("synthesizing receipt for "+event.getId()); // This is really ugly because JS has no way to express an object literal // where the name of a key comes from an expression var fakeReceipt = { content: {}, type: "m.receipt", room_id: event.getRoomId() }; fakeReceipt.content[event.getId()] = {}; fakeReceipt.content[event.getId()][receiptType] = {}; fakeReceipt.content[event.getId()][receiptType][userId] = { ts: event.getTs() }; return new _event.MatrixEvent(fakeReceipt); } /** * Construct a new Room. * *

For a room, we store an ordered sequence of timelines, which may or may not * be continuous. Each timeline lists a series of events, as well as tracking * the room state at the start and the end of the timeline. It also tracks * forward and backward pagination tokens, as well as containing links to the * next timeline in the sequence. * *

There is one special timeline - the 'live' timeline, which represents the * timeline to which events are being added in real-time as they are received * from the /sync API. Note that you should not retain references to this * timeline - even if it is the current timeline right now, it may not remain * so if the server gives us a timeline gap in /sync. * *

In order that we can find events from their ids later, we also maintain a * map from event_id to timeline and index. * * @constructor * @alias module:models/room * @param {string} roomId Required. The ID of this room. * @param {MatrixClient} client Required. The client, used to lazy load members. * @param {string} myUserId Required. The ID of the syncing user. * @param {Object=} opts Configuration options * @param {*} opts.storageToken Optional. The token which a data store can use * to remember the state of the room. What this means is dependent on the store * implementation. * * @param {String=} opts.pendingEventOrdering Controls where pending messages * appear in a room's timeline. If "chronological", messages will appear * in the timeline when the call to sendEvent was made. If * "detached", pending messages will appear in a separate list, * accessbile via {@link module:models/room#getPendingEvents}. Default: * "chronological". * @param {boolean} [opts.timelineSupport = false] Set to true to enable improved * timeline support. * @param {boolean} [opts.unstableClientRelationAggregation = false] * Optional. Set to true to enable client-side aggregation of event relations * via `EventTimelineSet#getRelationsForEvent`. * This feature is currently unstable and the API may change without notice. * * @prop {string} roomId The ID of this room. * @prop {string} name The human-readable display name for this room. * @prop {Array} timeline The live event timeline for this room, * with the oldest event at index 0. Present for backwards compatibility - * prefer getLiveTimeline().getEvents(). * @prop {object} tags Dict of room tags; the keys are the tag name and the values * are any metadata associated with the tag - e.g. { "fav" : { order: 1 } } * @prop {object} accountData Dict of per-room account_data events; the keys are the * event type and the values are the events. * @prop {RoomState} oldState The state of the room at the time of the oldest * event in the live timeline. Present for backwards compatibility - * prefer getLiveTimeline().getState(EventTimeline.BACKWARDS). * @prop {RoomState} currentState The state of the room at the time of the * newest event in the timeline. Present for backwards compatibility - * prefer getLiveTimeline().getState(EventTimeline.FORWARDS). * @prop {RoomSummary} summary The room summary. * @prop {*} storageToken A token which a data store can use to remember * the state of the room. */ function Room(roomId, client, myUserId, opts) { opts = opts || {}; opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological"; // In some cases, we add listeners for every displayed Matrix event, so it's // common to have quite a few more than the default limit. this.setMaxListeners(100); this.reEmitter = new _ReEmitter.ReEmitter(this); if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) { throw new Error("opts.pendingEventOrdering MUST be either 'chronological' or " + "'detached'. Got: '" + opts.pendingEventOrdering + "'"); } this.myUserId = myUserId; this.roomId = roomId; this.name = roomId; this.tags = {// $tagName: { $metadata: $value }, // $tagName: { $metadata: $value }, }; this.accountData = {// $eventType: $event }; this.summary = null; this.storageToken = opts.storageToken; this._opts = opts; this._txnToEvent = {}; // Pending in-flight requests { string: MatrixEvent } // receipts should clobber based on receipt_type and user_id pairs hence // the form of this structure. This is sub-optimal for the exposed APIs // which pass in an event ID and get back some receipts, so we also store // a pre-cached list for this purpose. this._receipts = {// receipt_type: { // user_id: { // eventId: , // data: // } // } }; this._receiptCacheByEventId = {// $event_id: [{ // type: $type, // userId: $user_id, // data: // }] }; // only receipts that came from the server, not synthesized ones this._realReceipts = {}; this._notificationCounts = {}; // all our per-room timeline sets. the first one is the unfiltered ones; // the subsequent ones are the filtered ones in no particular order. this._timelineSets = [new _eventTimelineSet.EventTimelineSet(this, opts)]; this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), ["Room.timeline", "Room.timelineReset"]); this._fixUpLegacyTimelineFields(); // any filtered timeline sets we're maintaining for this room this._filteredTimelineSets = {// filter_id: timelineSet }; if (this._opts.pendingEventOrdering == "detached") { this._pendingEventList = []; } // read by megolm; boolean value - null indicates "use global value" this._blacklistUnverifiedDevices = null; this._selfMembership = null; this._summaryHeroes = null; // awaited by getEncryptionTargetMembers while room members are loading this._client = client; if (!this._opts.lazyLoadMembers) { this._membersPromise = Promise.resolve(); } else { this._membersPromise = null; } } utils.inherits(Room, _events.EventEmitter); /** * Gets the version of the room * @returns {string} The version of the room, or null if it could not be determined */ Room.prototype.getVersion = function () { var createEvent = this.currentState.getStateEvents("m.room.create", ""); if (!createEvent) { _logger.logger.warn("Room " + this.roomId + " does not have an m.room.create event"); return '1'; } var ver = createEvent.getContent()['room_version']; if (ver === undefined) return '1'; return ver; }; /** * Determines whether this room needs to be upgraded to a new version * @returns {string?} What version the room should be upgraded to, or null if * the room does not require upgrading at this time. * @deprecated Use #getRecommendedVersion() instead */ Room.prototype.shouldUpgradeToVersion = function () { // TODO: Remove this function. // This makes assumptions about which versions are safe, and can easily // be wrong. Instead, people are encouraged to use getRecommendedVersion // which determines a safer value. This function doesn't use that function // because this is not async-capable, and to avoid breaking the contract // we're deprecating this. if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) { return KNOWN_SAFE_ROOM_VERSION; } return null; }; /** * Determines the recommended room version for the room. This returns an * object with 3 properties: version as the new version the * room should be upgraded to (may be the same as the current version); * needsUpgrade to indicate if the room actually can be * upgraded (ie: does the current version not match?); and urgent * to indicate if the new version patches a vulnerability in a previous * version. * @returns {Promise<{version: string, needsUpgrade: bool, urgent: bool}>} * Resolves to the version the room should be upgraded to. */ Room.prototype.getRecommendedVersion = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var capabilities, versionCap, _iterator, _step, safeVer, result, caps; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this._client.getCapabilities(); case 2: capabilities = _context.sent; versionCap = capabilities["m.room_versions"]; if (!versionCap) { versionCap = { "default": KNOWN_SAFE_ROOM_VERSION, available: {} }; _iterator = _createForOfIteratorHelper(SAFE_ROOM_VERSIONS); try { for (_iterator.s(); !(_step = _iterator.n()).done;) { safeVer = _step.value; versionCap.available[safeVer] = "stable"; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } result = this._checkVersionAgainstCapability(versionCap); if (!(result.urgent && result.needsUpgrade)) { _context.next = 18; break; } // Something doesn't feel right: we shouldn't need to update // because the version we're on should be in the protocol's // namespace. This usually means that the server was updated // before the client was, making us think the newest possible // room version is not stable. As a solution, we'll refresh // the capability we're using to determine this. _logger.logger.warn("Refreshing room version capability because the server looks " + "to be supporting a newer room version we don't know about."); _context.next = 10; return this._client.getCapabilities(true); case 10: caps = _context.sent; versionCap = caps["m.room_versions"]; if (versionCap) { _context.next = 17; break; } _logger.logger.warn("No room version capability - assuming upgrade required."); return _context.abrupt("return", result); case 17: result = this._checkVersionAgainstCapability(versionCap); case 18: return _context.abrupt("return", result); case 19: case "end": return _context.stop(); } } }, _callee, this); })); Room.prototype._checkVersionAgainstCapability = function (versionCap) { var currentVersion = this.getVersion(); _logger.logger.log("[".concat(this.roomId, "] Current version: ").concat(currentVersion)); _logger.logger.log("[".concat(this.roomId, "] Version capability: "), versionCap); var result = { version: currentVersion, needsUpgrade: false, urgent: false }; // If the room is on the default version then nothing needs to change if (currentVersion === versionCap["default"]) return result; var stableVersions = Object.keys(versionCap.available).filter(function (v) { return versionCap.available[v] === 'stable'; }); // Check if the room is on an unstable version. We determine urgency based // off the version being in the Matrix spec namespace or not (if the version // is in the current namespace and unstable, the room is probably vulnerable). if (!stableVersions.includes(currentVersion)) { result.version = versionCap["default"]; result.needsUpgrade = true; result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g); if (result.urgent) { _logger.logger.warn("URGENT upgrade required on ".concat(this.roomId)); } else { _logger.logger.warn("Non-urgent upgrade required on ".concat(this.roomId)); } return result; } // The room is on a stable, but non-default, version by this point. // No upgrade needed. return result; }; /** * Determines whether the given user is permitted to perform a room upgrade * @param {String} userId The ID of the user to test against * @returns {bool} True if the given user is permitted to upgrade the room */ Room.prototype.userMayUpgradeRoom = function (userId) { return this.currentState.maySendStateEvent("m.room.tombstone", userId); }; /** * Get the list of pending sent events for this room * * @return {module:models/event.MatrixEvent[]} A list of the sent events * waiting for remote echo. * * @throws If opts.pendingEventOrdering was not 'detached' */ Room.prototype.getPendingEvents = function () { if (this._opts.pendingEventOrdering !== "detached") { throw new Error("Cannot call getPendingEvents with pendingEventOrdering == " + this._opts.pendingEventOrdering); } return this._pendingEventList; }; /** * Check whether the pending event list contains a given event by ID. * * @param {string} eventId The event ID to check for. * @return {boolean} * @throws If opts.pendingEventOrdering was not 'detached' */ Room.prototype.hasPendingEvent = function (eventId) { if (this._opts.pendingEventOrdering !== "detached") { throw new Error("Cannot call hasPendingEvent with pendingEventOrdering == " + this._opts.pendingEventOrdering); } return this._pendingEventList.some(function (event) { return event.getId() === eventId; }); }; /** * Get the live unfiltered timeline for this room. * * @return {module:models/event-timeline~EventTimeline} live timeline */ Room.prototype.getLiveTimeline = function () { return this.getUnfilteredTimelineSet().getLiveTimeline(); }; /** * Get the timestamp of the last message in the room * * @return {number} the timestamp of the last message in the room */ Room.prototype.getLastActiveTimestamp = function () { var timeline = this.getLiveTimeline(); var events = timeline.getEvents(); if (events.length) { var lastEvent = events[events.length - 1]; return lastEvent.getTs(); } else { return Number.MIN_SAFE_INTEGER; } }; /** * @param {string} myUserId the user id for the logged in member * @return {string} the membership type (join | leave | invite) for the logged in user */ Room.prototype.getMyMembership = function () { return this._selfMembership; }; /** * If this room is a DM we're invited to, * try to find out who invited us * @return {string} user id of the inviter */ Room.prototype.getDMInviter = function () { if (this.myUserId) { var me = this.getMember(this.myUserId); if (me) { return me.getDMInviter(); } } if (this._selfMembership === "invite") { // fall back to summary information var memberCount = this.getInvitedAndJoinedMemberCount(); if (memberCount == 2 && this._summaryHeroes.length) { return this._summaryHeroes[0]; } } }; /** * Assuming this room is a DM room, tries to guess with which user. * @return {string} user id of the other member (could be syncing user) */ Room.prototype.guessDMUserId = function () { var _this = this; var me = this.getMember(this.myUserId); if (me) { var inviterId = me.getDMInviter(); if (inviterId) { return inviterId; } } // remember, we're assuming this room is a DM, // so returning the first member we find should be fine var hasHeroes = Array.isArray(this._summaryHeroes) && this._summaryHeroes.length; if (hasHeroes) { return this._summaryHeroes[0]; } var members = this.currentState.getMembers(); var anyMember = members.find(function (m) { return m.userId !== _this.myUserId; }); if (anyMember) { return anyMember.userId; } // it really seems like I'm the only user in the room // so I probably created a room with just me in it // and marked it as a DM. Ok then return this.myUserId; }; Room.prototype.getAvatarFallbackMember = function () { var _this2 = this; var memberCount = this.getInvitedAndJoinedMemberCount(); if (memberCount > 2) { return; } var hasHeroes = Array.isArray(this._summaryHeroes) && this._summaryHeroes.length; if (hasHeroes) { var availableMember = this._summaryHeroes.map(function (userId) { return _this2.getMember(userId); }).find(function (member) { return !!member; }); if (availableMember) { return availableMember; } } var members = this.currentState.getMembers(); // could be different than memberCount // as this includes left members if (members.length <= 2) { var _availableMember = members.find(function (m) { return m.userId !== _this2.myUserId; }); if (_availableMember) { return _availableMember; } } // if all else fails, try falling back to a user, // and create a one-off member for it if (hasHeroes) { var availableUser = this._summaryHeroes.map(function (userId) { return _this2._client.getUser(userId); }).find(function (user) { return !!user; }); if (availableUser) { var member = new _roomMember.RoomMember(this.roomId, availableUser.userId); member.user = availableUser; return member; } } }; /** * Sets the membership this room was received as during sync * @param {string} membership join | leave | invite */ Room.prototype.updateMyMembership = function (membership) { var prevMembership = this._selfMembership; this._selfMembership = membership; if (prevMembership !== membership) { if (membership === "leave") { this._cleanupAfterLeaving(); } this.emit("Room.myMembership", this, membership, prevMembership); } }; Room.prototype._loadMembersFromServer = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { var lastSyncToken, queryString, path, http, response; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: lastSyncToken = this._client.store.getSyncToken(); queryString = utils.encodeParams({ not_membership: "leave", at: lastSyncToken }); path = utils.encodeUri("/rooms/$roomId/members?" + queryString, { $roomId: this.roomId }); http = this._client._http; _context2.next = 6; return http.authedRequest(undefined, "GET", path); case 6: response = _context2.sent; return _context2.abrupt("return", response.chunk); case 8: case "end": return _context2.stop(); } } }, _callee2, this); })); Room.prototype._loadMembers = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { var fromServer, rawMembersEvents, memberEvents; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: // were the members loaded from the server? fromServer = false; _context3.next = 3; return this._client.store.getOutOfBandMembers(this.roomId); case 3: rawMembersEvents = _context3.sent; if (!(rawMembersEvents === null)) { _context3.next = 10; break; } fromServer = true; _context3.next = 8; return this._loadMembersFromServer(); case 8: rawMembersEvents = _context3.sent; _logger.logger.log("LL: got ".concat(rawMembersEvents.length, " ") + "members from server for room ".concat(this.roomId)); case 10: memberEvents = rawMembersEvents.map(this._client.getEventMapper()); return _context3.abrupt("return", { memberEvents: memberEvents, fromServer: fromServer }); case 12: case "end": return _context3.stop(); } } }, _callee3, this); })); /** * Preloads the member list in case lazy loading * of memberships is in use. Can be called multiple times, * it will only preload once. * @return {Promise} when preloading is done and * accessing the members on the room will take * all members in the room into account */ Room.prototype.loadMembersIfNeeded = function () { var _this3 = this; if (this._membersPromise) { return this._membersPromise; } // mark the state so that incoming messages while // the request is in flight get marked as superseding // the OOB members this.currentState.markOutOfBandMembersStarted(); var inMemoryUpdate = this._loadMembers().then(function (result) { _this3.currentState.setOutOfBandMembers(result.memberEvents); // now the members are loaded, start to track the e2e devices if needed if (_this3._client.isCryptoEnabled() && _this3._client.isRoomEncrypted(_this3.roomId)) { _this3._client._crypto.trackRoomDevices(_this3.roomId); } return result.fromServer; })["catch"](function (err) { // allow retries on fail _this3._membersPromise = null; _this3.currentState.markOutOfBandMembersFailed(); throw err; }); // update members in storage, but don't wait for it inMemoryUpdate.then(function (fromServer) { if (fromServer) { var oobMembers = _this3.currentState.getMembers().filter(function (m) { return m.isOutOfBand(); }).map(function (m) { return m.events.member.event; }); _logger.logger.log("LL: telling store to write ".concat(oobMembers.length) + " members for room ".concat(_this3.roomId)); var store = _this3._client.store; return store.setOutOfBandMembers(_this3.roomId, oobMembers) // swallow any IDB error as we don't want to fail // because of this ["catch"](function (err) { _logger.logger.log("LL: storing OOB room members failed, oh well", err); }); } })["catch"](function (err) { // as this is not awaited anywhere, // at least show the error in the console _logger.logger.error(err); }); this._membersPromise = inMemoryUpdate; return this._membersPromise; }; /** * Removes the lazily loaded members from storage if needed */ Room.prototype.clearLoadedMembersIfNeeded = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (!(this._opts.lazyLoadMembers && this._membersPromise)) { _context4.next = 7; break; } _context4.next = 3; return this.loadMembersIfNeeded(); case 3: _context4.next = 5; return this._client.store.clearOutOfBandMembers(this.roomId); case 5: this.currentState.clearOutOfBandMembers(); this._membersPromise = null; case 7: case "end": return _context4.stop(); } } }, _callee4, this); })); /** * called when sync receives this room in the leave section * to do cleanup after leaving a room. Possibly called multiple times. */ Room.prototype._cleanupAfterLeaving = function () { var _this4 = this; this.clearLoadedMembersIfNeeded()["catch"](function (err) { _logger.logger.error("error after clearing loaded members from " + "room ".concat(_this4.roomId, " after leaving")); _logger.logger.log(err); }); }; /** * Reset the live timeline of all timelineSets, and start new ones. * *

This is used when /sync returns a 'limited' timeline. * * @param {string=} backPaginationToken token for back-paginating the new timeline * @param {string=} forwardPaginationToken token for forward-paginating the old live timeline, * if absent or null, all timelines are reset, removing old ones (including the previous live * timeline which would otherwise be unable to paginate forwards without this token). * Removing just the old live timeline whilst preserving previous ones is not supported. */ Room.prototype.resetLiveTimeline = function (backPaginationToken, forwardPaginationToken) { for (var i = 0; i < this._timelineSets.length; i++) { this._timelineSets[i].resetLiveTimeline(backPaginationToken, forwardPaginationToken); } this._fixUpLegacyTimelineFields(); }; /** * Fix up this.timeline, this.oldState and this.currentState * * @private */ Room.prototype._fixUpLegacyTimelineFields = function () { // maintain this.timeline as a reference to the live timeline, // and this.oldState and this.currentState as references to the // state at the start and end of that timeline. These are more // for backwards-compatibility than anything else. this.timeline = this.getLiveTimeline().getEvents(); this.oldState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.BACKWARDS); this.currentState = this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS); }; /** * Returns whether there are any devices in the room that are unverified * * Note: Callers should first check if crypto is enabled on this device. If it is * disabled, then we aren't tracking room devices at all, so we can't answer this, and an * error will be thrown. * * @return {bool} the result */ Room.prototype.hasUnverifiedDevices = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { var e2eMembers, _iterator2, _step2, member, devices; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (this._client.isRoomEncrypted(this.roomId)) { _context5.next = 2; break; } return _context5.abrupt("return", false); case 2: _context5.next = 4; return this.getEncryptionTargetMembers(); case 4: e2eMembers = _context5.sent; _iterator2 = _createForOfIteratorHelper(e2eMembers); _context5.prev = 6; _iterator2.s(); case 8: if ((_step2 = _iterator2.n()).done) { _context5.next = 15; break; } member = _step2.value; devices = this._client.getStoredDevicesForUser(member.userId); if (!devices.some(function (device) { return device.isUnverified(); })) { _context5.next = 13; break; } return _context5.abrupt("return", true); case 13: _context5.next = 8; break; case 15: _context5.next = 20; break; case 17: _context5.prev = 17; _context5.t0 = _context5["catch"](6); _iterator2.e(_context5.t0); case 20: _context5.prev = 20; _iterator2.f(); return _context5.finish(20); case 23: return _context5.abrupt("return", false); case 24: case "end": return _context5.stop(); } } }, _callee5, this, [[6, 17, 20, 23]]); })); /** * Return the timeline sets for this room. * @return {EventTimelineSet[]} array of timeline sets for this room */ Room.prototype.getTimelineSets = function () { return this._timelineSets; }; /** * Helper to return the main unfiltered timeline set for this room * @return {EventTimelineSet} room's unfiltered timeline set */ Room.prototype.getUnfilteredTimelineSet = function () { return this._timelineSets[0]; }; /** * Get the timeline which contains the given event from the unfiltered set, if any * * @param {string} eventId event ID to look for * @return {?module:models/event-timeline~EventTimeline} timeline containing * the given event, or null if unknown */ Room.prototype.getTimelineForEvent = function (eventId) { return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId); }; /** * Add a new timeline to this room's unfiltered timeline set * * @return {module:models/event-timeline~EventTimeline} newly-created timeline */ Room.prototype.addTimeline = function () { return this.getUnfilteredTimelineSet().addTimeline(); }; /** * Get an event which is stored in our unfiltered timeline set * * @param {string} eventId event ID to look for * @return {?module:models/event.MatrixEvent} the given event, or undefined if unknown */ Room.prototype.findEventById = function (eventId) { return this.getUnfilteredTimelineSet().findEventById(eventId); }; /** * Get one of the notification counts for this room * @param {String} type The type of notification count to get. default: 'total' * @return {Number} The notification count, or undefined if there is no count * for this type. */ Room.prototype.getUnreadNotificationCount = function (type) { type = type || 'total'; return this._notificationCounts[type]; }; /** * Set one of the notification counts for this room * @param {String} type The type of notification count to set. * @param {Number} count The new count */ Room.prototype.setUnreadNotificationCount = function (type, count) { this._notificationCounts[type] = count; }; Room.prototype.setSummary = function (summary) { var _this5 = this; var heroes = summary["m.heroes"]; var joinedCount = summary["m.joined_member_count"]; var invitedCount = summary["m.invited_member_count"]; if (Number.isInteger(joinedCount)) { this.currentState.setJoinedMemberCount(joinedCount); } if (Number.isInteger(invitedCount)) { this.currentState.setInvitedMemberCount(invitedCount); } if (Array.isArray(heroes)) { // be cautious about trusting server values, // and make sure heroes doesn't contain our own id // just to be sure this._summaryHeroes = heroes.filter(function (userId) { return userId !== _this5.myUserId; }); } }; /** * Whether to send encrypted messages to devices within this room. * @param {Boolean} value true to blacklist unverified devices, null * to use the global value for this room. */ Room.prototype.setBlacklistUnverifiedDevices = function (value) { this._blacklistUnverifiedDevices = value; }; /** * Whether to send encrypted messages to devices within this room. * @return {Boolean} true if blacklisting unverified devices, null * if the global value should be used for this room. */ Room.prototype.getBlacklistUnverifiedDevices = function () { return this._blacklistUnverifiedDevices; }; /** * Get the avatar URL for a room if one was set. * @param {String} baseUrl The homeserver base URL. See * {@link module:client~MatrixClient#getHomeserverUrl}. * @param {Number} width The desired width of the thumbnail. * @param {Number} height The desired height of the thumbnail. * @param {string} resizeMethod The thumbnail resize method to use, either * "crop" or "scale". * @param {boolean} allowDefault True to allow an identicon for this room if an * avatar URL wasn't explicitly set. Default: true. (Deprecated) * @return {?string} the avatar URL or null. */ Room.prototype.getAvatarUrl = function (baseUrl, width, height, resizeMethod, allowDefault) { var roomAvatarEvent = this.currentState.getStateEvents("m.room.avatar", ""); if (allowDefault === undefined) { allowDefault = true; } if (!roomAvatarEvent && !allowDefault) { return null; } var mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null; if (mainUrl) { return (0, _contentRepo.getHttpUriForMxc)(baseUrl, mainUrl, width, height, resizeMethod); } return null; }; /** * Get the aliases this room has according to the room's state * The aliases returned by this function may not necessarily * still point to this room. * @return {array} The room's alias as an array of strings */ Room.prototype.getAliases = function () { var aliasStrings = []; var aliasEvents = this.currentState.getStateEvents("m.room.aliases"); if (aliasEvents) { var _loop = function _loop(i) { var aliasEvent = aliasEvents[i]; if (utils.isArray(aliasEvent.getContent().aliases)) { var filteredAliases = aliasEvent.getContent().aliases.filter(function (a) { if (typeof a !== "string") return false; if (a[0] !== '#') return false; if (!a.endsWith(":".concat(aliasEvent.getStateKey()))) return false; // It's probably valid by here. return true; }); Array.prototype.push.apply(aliasStrings, filteredAliases); } }; for (var i = 0; i < aliasEvents.length; ++i) { _loop(i); } } return aliasStrings; }; /** * Get this room's canonical alias * The alias returned by this function may not necessarily * still point to this room. * @return {?string} The room's canonical alias, or null if there is none */ Room.prototype.getCanonicalAlias = function () { var canonicalAlias = this.currentState.getStateEvents("m.room.canonical_alias", ""); if (canonicalAlias) { return canonicalAlias.getContent().alias || null; } return null; }; /** * Get this room's alternative aliases * @return {array} The room's alternative aliases, or an empty array */ Room.prototype.getAltAliases = function () { var canonicalAlias = this.currentState.getStateEvents("m.room.canonical_alias", ""); if (canonicalAlias) { return canonicalAlias.getContent().alt_aliases || []; } return []; }; /** * Add events to a timeline * *

Will fire "Room.timeline" for each event added. * * @param {MatrixEvent[]} events A list of events to add. * * @param {boolean} toStartOfTimeline True to add these events to the start * (oldest) instead of the end (newest) of the timeline. If true, the oldest * event will be the last element of 'events'. * * @param {module:models/event-timeline~EventTimeline} timeline timeline to * add events to. * * @param {string=} paginationToken token for the next batch of events * * @fires module:client~MatrixClient#event:"Room.timeline" * */ Room.prototype.addEventsToTimeline = function (events, toStartOfTimeline, timeline, paginationToken) { timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken); }; /** * Get a member from the current room state. * @param {string} userId The user ID of the member. * @return {RoomMember} The member or null. */ Room.prototype.getMember = function (userId) { return this.currentState.getMember(userId); }; /** * Get a list of members whose membership state is "join". * @return {RoomMember[]} A list of currently joined members. */ Room.prototype.getJoinedMembers = function () { return this.getMembersWithMembership("join"); }; /** * Returns the number of joined members in this room * This method caches the result. * This is a wrapper around the method of the same name in roomState, returning * its result for the room's current state. * @return {integer} The number of members in this room whose membership is 'join' */ Room.prototype.getJoinedMemberCount = function () { return this.currentState.getJoinedMemberCount(); }; /** * Returns the number of invited members in this room * @return {integer} The number of members in this room whose membership is 'invite' */ Room.prototype.getInvitedMemberCount = function () { return this.currentState.getInvitedMemberCount(); }; /** * Returns the number of invited + joined members in this room * @return {integer} The number of members in this room whose membership is 'invite' or 'join' */ Room.prototype.getInvitedAndJoinedMemberCount = function () { return this.getInvitedMemberCount() + this.getJoinedMemberCount(); }; /** * Get a list of members with given membership state. * @param {string} membership The membership state. * @return {RoomMember[]} A list of members with the given membership state. */ Room.prototype.getMembersWithMembership = function (membership) { return utils.filter(this.currentState.getMembers(), function (m) { return m.membership === membership; }); }; /** * Get a list of members we should be encrypting for in this room * @return {Promise} A list of members who * we should encrypt messages for in this room. */ Room.prototype.getEncryptionTargetMembers = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { var members; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return this.loadMembersIfNeeded(); case 2: members = this.getMembersWithMembership("join"); if (this.shouldEncryptForInvitedMembers()) { members = members.concat(this.getMembersWithMembership("invite")); } return _context6.abrupt("return", members); case 5: case "end": return _context6.stop(); } } }, _callee6, this); })); /** * Determine whether we should encrypt messages for invited users in this room * @return {boolean} if we should encrypt messages for invited users */ Room.prototype.shouldEncryptForInvitedMembers = function () { var ev = this.currentState.getStateEvents("m.room.history_visibility", ""); return ev && ev.getContent() && ev.getContent().history_visibility !== "joined"; }; /** * Get the default room name (i.e. what a given user would see if the * room had no m.room.name) * @param {string} userId The userId from whose perspective we want * to calculate the default name * @return {string} The default room name */ Room.prototype.getDefaultRoomName = function (userId) { return calculateRoomName(this, userId, true); }; /** * Check if the given user_id has the given membership state. * @param {string} userId The user ID to check. * @param {string} membership The membership e.g. 'join' * @return {boolean} True if this user_id has the given membership state. */ Room.prototype.hasMembershipState = function (userId, membership) { var member = this.getMember(userId); if (!member) { return false; } return member.membership === membership; }; /** * Add a timelineSet for this room with the given filter * @param {Filter} filter The filter to be applied to this timelineSet * @return {EventTimelineSet} The timelineSet */ Room.prototype.getOrCreateFilteredTimelineSet = function (filter) { if (this._filteredTimelineSets[filter.filterId]) { return this._filteredTimelineSets[filter.filterId]; } var opts = Object.assign({ filter: filter }, this._opts); var timelineSet = new _eventTimelineSet.EventTimelineSet(this, opts); this.reEmitter.reEmit(timelineSet, ["Room.timeline", "Room.timelineReset"]); this._filteredTimelineSets[filter.filterId] = timelineSet; this._timelineSets.push(timelineSet); // populate up the new timelineSet with filtered events from our live // unfiltered timeline. // // XXX: This is risky as our timeline // may have grown huge and so take a long time to filter. // see https://github.com/vector-im/vector-web/issues/2109 var unfilteredLiveTimeline = this.getLiveTimeline(); unfilteredLiveTimeline.getEvents().forEach(function (event) { timelineSet.addLiveEvent(event); }); // find the earliest unfiltered timeline var timeline = unfilteredLiveTimeline; while (timeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.BACKWARDS)) { timeline = timeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.BACKWARDS); } timelineSet.getLiveTimeline().setPaginationToken(timeline.getPaginationToken(_eventTimeline.EventTimeline.BACKWARDS), _eventTimeline.EventTimeline.BACKWARDS); // alternatively, we could try to do something like this to try and re-paginate // in the filtered events from nothing, but Mark says it's an abuse of the API // to do so: // // timelineSet.resetLiveTimeline( // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS) // ); return timelineSet; }; /** * Forget the timelineSet for this room with the given filter * * @param {Filter} filter the filter whose timelineSet is to be forgotten */ Room.prototype.removeFilteredTimelineSet = function (filter) { var timelineSet = this._filteredTimelineSets[filter.filterId]; delete this._filteredTimelineSets[filter.filterId]; var i = this._timelineSets.indexOf(timelineSet); if (i > -1) { this._timelineSets.splice(i, 1); } }; /** * Add an event to the end of this room's live timelines. Will fire * "Room.timeline". * * @param {MatrixEvent} event Event to be added * @param {string?} duplicateStrategy 'ignore' or 'replace' * @param {boolean} fromCache whether the sync response came from cache * @fires module:client~MatrixClient#event:"Room.timeline" * @private */ Room.prototype._addLiveEvent = function (event, duplicateStrategy, fromCache) { if (event.isRedaction()) { var redactId = event.event.redacts; // if we know about this event, redact its contents now. var redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId); if (redactedEvent) { redactedEvent.makeRedacted(event); // If this is in the current state, replace it with the redacted version if (redactedEvent.getStateKey()) { var currentStateEvent = this.currentState.getStateEvents(redactedEvent.getType(), redactedEvent.getStateKey()); if (currentStateEvent.getId() === redactedEvent.getId()) { this.currentState.setStateEvents([redactedEvent]); } } this.emit("Room.redaction", event, this); // TODO: we stash user displaynames (among other things) in // RoomMember objects which are then attached to other events // (in the sender and target fields). We should get those // RoomMember objects to update themselves when the events that // they are based on are changed. } // FIXME: apply redactions to notification list // NB: We continue to add the redaction event to the timeline so // clients can say "so and so redacted an event" if they wish to. Also // this may be needed to trigger an update. } if (event.getUnsigned().transaction_id) { var existingEvent = this._txnToEvent[event.getUnsigned().transaction_id]; if (existingEvent) { // remote echo of an event we sent earlier this._handleRemoteEcho(event, existingEvent); return; } } // add to our timeline sets for (var i = 0; i < this._timelineSets.length; i++) { this._timelineSets[i].addLiveEvent(event, duplicateStrategy, fromCache); } // synthesize and inject implicit read receipts // Done after adding the event because otherwise the app would get a read receipt // pointing to an event that wasn't yet in the timeline // Don't synthesize RR for m.room.redaction as this causes the RR to go missing. if (event.sender && event.getType() !== "m.room.redaction") { this.addReceipt(synthesizeReceipt(event.sender.userId, event, "m.read"), true); // Any live events from a user could be taken as implicit // presence information: evidence that they are currently active. // ...except in a world where we use 'user.currentlyActive' to reduce // presence spam, this isn't very useful - we'll get a transition when // they are no longer currently active anyway. So don't bother to // reset the lastActiveAgo and lastPresenceTs from the RoomState's user. } }; /** * Add a pending outgoing event to this room. * *

The event is added to either the pendingEventList, or the live timeline, * depending on the setting of opts.pendingEventOrdering. * *

This is an internal method, intended for use by MatrixClient. * * @param {module:models/event.MatrixEvent} event The event to add. * * @param {string} txnId Transaction id for this outgoing event * * @fires module:client~MatrixClient#event:"Room.localEchoUpdated" * * @throws if the event doesn't have status SENDING, or we aren't given a * unique transaction id. */ Room.prototype.addPendingEvent = function (event, txnId) { if (event.status !== _event.EventStatus.SENDING) { throw new Error("addPendingEvent called on an event with status " + event.status); } if (this._txnToEvent[txnId]) { throw new Error("addPendingEvent called on an event with known txnId " + txnId); } // call setEventMetadata to set up event.sender etc // as event is shared over all timelineSets, we set up its metadata based // on the unfiltered timelineSet. _eventTimeline.EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(_eventTimeline.EventTimeline.FORWARDS), false); this._txnToEvent[txnId] = event; if (this._opts.pendingEventOrdering == "detached") { if (this._pendingEventList.some(function (e) { return e.status === _event.EventStatus.NOT_SENT; })) { _logger.logger.warn("Setting event as NOT_SENT due to messages in the same state"); event.setStatus(_event.EventStatus.NOT_SENT); } this._pendingEventList.push(event); if (event.isRelation()) { // For pending events, add them to the relations collection immediately. // (The alternate case below already covers this as part of adding to // the timeline set.) this._aggregateNonLiveRelation(event); } if (event.isRedaction()) { var redactId = event.event.redacts; var redactedEvent = this._pendingEventList && this._pendingEventList.find(function (e) { return e.getId() === redactId; }); if (!redactedEvent) { redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId); } if (redactedEvent) { redactedEvent.markLocallyRedacted(event); this.emit("Room.redaction", event, this); } } } else { for (var i = 0; i < this._timelineSets.length; i++) { var timelineSet = this._timelineSets[i]; if (timelineSet.getFilter()) { if (timelineSet.getFilter().filterRoomTimeline([event]).length) { timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), false); } } else { timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), false); } } } this.emit("Room.localEchoUpdated", event, this, null, null); }; /** * Used to aggregate the local echo for a relation, and also * for re-applying a relation after it's redaction has been cancelled, * as the local echo for the redaction of the relation would have * un-aggregated the relation. Note that this is different from regular messages, * which are just kept detached for their local echo. * * Also note that live events are aggregated in the live EventTimelineSet. * @param {module:models/event.MatrixEvent} event the relation event that needs to be aggregated. */ Room.prototype._aggregateNonLiveRelation = function (event) { // TODO: We should consider whether this means it would be a better // design to lift the relations handling up to the room instead. for (var i = 0; i < this._timelineSets.length; i++) { var timelineSet = this._timelineSets[i]; if (timelineSet.getFilter()) { if (timelineSet.getFilter().filterRoomTimeline([event]).length) { timelineSet.aggregateRelations(event); } } else { timelineSet.aggregateRelations(event); } } }; /** * Deal with the echo of a message we sent. * *

We move the event to the live timeline if it isn't there already, and * update it. * * @param {module:models/event.MatrixEvent} remoteEvent The event received from * /sync * @param {module:models/event.MatrixEvent} localEvent The local echo, which * should be either in the _pendingEventList or the timeline. * * @fires module:client~MatrixClient#event:"Room.localEchoUpdated" * @private */ Room.prototype._handleRemoteEcho = function (remoteEvent, localEvent) { var oldEventId = localEvent.getId(); var newEventId = remoteEvent.getId(); var oldStatus = localEvent.status; _logger.logger.debug("Got remote echo for event ".concat(oldEventId, " -> ").concat(newEventId, " ") + "old status ".concat(oldStatus)); // no longer pending delete this._txnToEvent[remoteEvent.getUnsigned().transaction_id]; // if it's in the pending list, remove it if (this._pendingEventList) { utils.removeElement(this._pendingEventList, function (ev) { return ev.getId() == oldEventId; }, false); } // replace the event source (this will preserve the plaintext payload if // any, which is good, because we don't want to try decoding it again). localEvent.handleRemoteEcho(remoteEvent.event); for (var i = 0; i < this._timelineSets.length; i++) { var timelineSet = this._timelineSets[i]; // if it's already in the timeline, update the timeline map. If it's not, add it. timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId); } this.emit("Room.localEchoUpdated", localEvent, this, oldEventId, oldStatus); }; /* a map from current event status to a list of allowed next statuses */ var ALLOWED_TRANSITIONS = {}; ALLOWED_TRANSITIONS[_event.EventStatus.ENCRYPTING] = [_event.EventStatus.SENDING, _event.EventStatus.NOT_SENT]; ALLOWED_TRANSITIONS[_event.EventStatus.SENDING] = [_event.EventStatus.ENCRYPTING, _event.EventStatus.QUEUED, _event.EventStatus.NOT_SENT, _event.EventStatus.SENT]; ALLOWED_TRANSITIONS[_event.EventStatus.QUEUED] = [_event.EventStatus.SENDING, _event.EventStatus.CANCELLED]; ALLOWED_TRANSITIONS[_event.EventStatus.SENT] = []; ALLOWED_TRANSITIONS[_event.EventStatus.NOT_SENT] = [_event.EventStatus.SENDING, _event.EventStatus.QUEUED, _event.EventStatus.CANCELLED]; ALLOWED_TRANSITIONS[_event.EventStatus.CANCELLED] = []; /** * Update the status / event id on a pending event, to reflect its transmission * progress. * *

This is an internal method. * * @param {MatrixEvent} event local echo event * @param {EventStatus} newStatus status to assign * @param {string} newEventId new event id to assign. Ignored unless * newStatus == EventStatus.SENT. * @fires module:client~MatrixClient#event:"Room.localEchoUpdated" */ Room.prototype.updatePendingEvent = function (event, newStatus, newEventId) { _logger.logger.log("setting pendingEvent status to ".concat(newStatus, " in ").concat(event.getRoomId(), " ") + "event ID ".concat(event.getId(), " -> ").concat(newEventId)); // if the message was sent, we expect an event id if (newStatus == _event.EventStatus.SENT && !newEventId) { throw new Error("updatePendingEvent called with status=SENT, " + "but no new event id"); } // SENT races against /sync, so we have to special-case it. if (newStatus == _event.EventStatus.SENT) { var timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId); if (timeline) { // we've already received the event via the event stream. // nothing more to do here. return; } } var oldStatus = event.status; var oldEventId = event.getId(); if (!oldStatus) { throw new Error("updatePendingEventStatus called on an event which is " + "not a local echo."); } var allowed = ALLOWED_TRANSITIONS[oldStatus]; if (!allowed || allowed.indexOf(newStatus) < 0) { throw new Error("Invalid EventStatus transition " + oldStatus + "->" + newStatus); } event.setStatus(newStatus); if (newStatus == _event.EventStatus.SENT) { // update the event id event.replaceLocalEventId(newEventId); // if the event was already in the timeline (which will be the case if // opts.pendingEventOrdering==chronological), we need to update the // timeline map. for (var i = 0; i < this._timelineSets.length; i++) { this._timelineSets[i].replaceEventId(oldEventId, newEventId); } } else if (newStatus == _event.EventStatus.CANCELLED) { // remove it from the pending event list, or the timeline. if (this._pendingEventList) { var idx = this._pendingEventList.findIndex(function (ev) { return ev.getId() === oldEventId; }); if (idx !== -1) { var _this$_pendingEventLi = this._pendingEventList.splice(idx, 1), _this$_pendingEventLi2 = (0, _slicedToArray2["default"])(_this$_pendingEventLi, 1), removedEvent = _this$_pendingEventLi2[0]; if (removedEvent.isRedaction()) { this._revertRedactionLocalEcho(removedEvent); } } } this.removeEvent(oldEventId); } this.emit("Room.localEchoUpdated", event, this, oldEventId, oldStatus); }; Room.prototype._revertRedactionLocalEcho = function (redactionEvent) { var redactId = redactionEvent.event.redacts; if (!redactId) { return; } var redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId); if (redactedEvent) { redactedEvent.unmarkLocallyRedacted(); // re-render after undoing redaction this.emit("Room.redactionCancelled", redactionEvent, this); // reapply relation now redaction failed if (redactedEvent.isRelation()) { this._aggregateNonLiveRelation(redactedEvent); } } }; /** * Add some events to this room. This can include state events, message * events and typing notifications. These events are treated as "live" so * they will go to the end of the timeline. * * @param {MatrixEvent[]} events A list of events to add. * * @param {string} duplicateStrategy Optional. Applies to events in the * timeline only. If this is 'replace' then if a duplicate is encountered, the * event passed to this function will replace the existing event in the * timeline. If this is not specified, or is 'ignore', then the event passed to * this function will be ignored entirely, preserving the existing event in the * timeline. Events are identical based on their event ID only. * * @param {boolean} fromCache whether the sync response came from cache * @throws If duplicateStrategy is not falsey, 'replace' or 'ignore'. */ Room.prototype.addLiveEvents = function (events, duplicateStrategy, fromCache) { var i; if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) { throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'"); } // sanity check that the live timeline is still live for (i = 0; i < this._timelineSets.length; i++) { var liveTimeline = this._timelineSets[i].getLiveTimeline(); if (liveTimeline.getPaginationToken(_eventTimeline.EventTimeline.FORWARDS)) { throw new Error("live timeline " + i + " is no longer live - it has a pagination token " + "(" + liveTimeline.getPaginationToken(_eventTimeline.EventTimeline.FORWARDS) + ")"); } if (liveTimeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.FORWARDS)) { throw new Error("live timeline " + i + " is no longer live - " + "it has a neighbouring timeline"); } } for (i = 0; i < events.length; i++) { // TODO: We should have a filter to say "only add state event // types X Y Z to the timeline". this._addLiveEvent(events[i], duplicateStrategy, fromCache); } }; /** * Adds/handles ephemeral events such as typing notifications and read receipts. * @param {MatrixEvent[]} events A list of events to process */ Room.prototype.addEphemeralEvents = function (events) { var _iterator3 = _createForOfIteratorHelper(events), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var event = _step3.value; if (event.getType() === 'm.typing') { this.currentState.setTypingEvent(event); } else if (event.getType() === 'm.receipt') { this.addReceipt(event); } // else ignore - life is too short for us to care about these events } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } }; /** * Removes events from this room. * @param {String[]} eventIds A list of eventIds to remove. */ Room.prototype.removeEvents = function (eventIds) { for (var i = 0; i < eventIds.length; ++i) { this.removeEvent(eventIds[i]); } }; /** * Removes a single event from this room. * * @param {String} eventId The id of the event to remove * * @return {bool} true if the event was removed from any of the room's timeline sets */ Room.prototype.removeEvent = function (eventId) { var removedAny = false; for (var i = 0; i < this._timelineSets.length; i++) { var removed = this._timelineSets[i].removeEvent(eventId); if (removed) { if (removed.isRedaction()) { this._revertRedactionLocalEcho(removed); } removedAny = true; } } return removedAny; }; /** * Recalculate various aspects of the room, including the room name and * room summary. Call this any time the room's current state is modified. * May fire "Room.name" if the room name is updated. * @fires module:client~MatrixClient#event:"Room.name" */ Room.prototype.recalculate = function () { // set fake stripped state events if this is an invite room so logic remains // consistent elsewhere. var self = this; var membershipEvent = this.currentState.getStateEvents("m.room.member", this.myUserId); if (membershipEvent && membershipEvent.getContent().membership === "invite") { var strippedStateEvents = membershipEvent.event.invite_room_state || []; utils.forEach(strippedStateEvents, function (strippedEvent) { var existingEvent = self.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key); if (!existingEvent) { // set the fake stripped event instead self.currentState.setStateEvents([new _event.MatrixEvent({ type: strippedEvent.type, state_key: strippedEvent.state_key, content: strippedEvent.content, event_id: "$fake" + Date.now(), room_id: self.roomId, user_id: self.myUserId // technically a lie })]); } }); } var oldName = this.name; this.name = calculateRoomName(this, this.myUserId); this.summary = new _roomSummary.RoomSummary(this.roomId, { title: this.name }); if (oldName !== this.name) { this.emit("Room.name", this); } }; /** * Get a list of user IDs who have read up to the given event. * @param {MatrixEvent} event the event to get read receipts for. * @return {String[]} A list of user IDs. */ Room.prototype.getUsersReadUpTo = function (event) { return this.getReceiptsForEvent(event).filter(function (receipt) { return receipt.type === "m.read"; }).map(function (receipt) { return receipt.userId; }); }; /** * Get the ID of the event that a given user has read up to, or null if we * have received no read receipts from them. * @param {String} userId The user ID to get read receipt event ID for * @param {Boolean} ignoreSynthesized If true, return only receipts that have been * sent by the server, not implicit ones generated * by the JS SDK. * @return {String} ID of the latest event that the given user has read, or null. */ Room.prototype.getEventReadUpTo = function (userId, ignoreSynthesized) { var receipts = this._receipts; if (ignoreSynthesized) { receipts = this._realReceipts; } if (receipts["m.read"] === undefined || receipts["m.read"][userId] === undefined) { return null; } return receipts["m.read"][userId].eventId; }; /** * Determines if the given user has read a particular event ID with the known * history of the room. This is not a definitive check as it relies only on * what is available to the room at the time of execution. * @param {String} userId The user ID to check the read state of. * @param {String} eventId The event ID to check if the user read. * @returns {Boolean} True if the user has read the event, false otherwise. */ Room.prototype.hasUserReadEvent = function (userId, eventId) { var readUpToId = this.getEventReadUpTo(userId, false); if (readUpToId === eventId) return true; if (this.timeline.length && this.timeline[this.timeline.length - 1].getSender() && this.timeline[this.timeline.length - 1].getSender() === userId) { // It doesn't matter where the event is in the timeline, the user has read // it because they've sent the latest event. return true; } for (var i = this.timeline.length - 1; i >= 0; --i) { var ev = this.timeline[i]; // If we encounter the target event first, the user hasn't read it // however if we encounter the readUpToId first then the user has read // it. These rules apply because we're iterating bottom-up. if (ev.getId() === eventId) return false; if (ev.getId() === readUpToId) return true; } // We don't know if the user has read it, so assume not. return false; }; /** * Get a list of receipts for the given event. * @param {MatrixEvent} event the event to get receipts for * @return {Object[]} A list of receipts with a userId, type and data keys or * an empty list. */ Room.prototype.getReceiptsForEvent = function (event) { return this._receiptCacheByEventId[event.getId()] || []; }; /** * Add a receipt event to the room. * @param {MatrixEvent} event The m.receipt event. * @param {Boolean} fake True if this event is implicit */ Room.prototype.addReceipt = function (event, fake) { // event content looks like: // content: { // $event_id: { // $receipt_type: { // $user_id: { // ts: $timestamp // } // } // } // } if (fake === undefined) { fake = false; } if (!fake) { this._addReceiptsToStructure(event, this._realReceipts); // we don't bother caching real receipts by event ID // as there's nothing that would read it. } this._addReceiptsToStructure(event, this._receipts); this._receiptCacheByEventId = this._buildReceiptCache(this._receipts); // send events after we've regenerated the cache, otherwise things that // listened for the event would read from a stale cache this.emit("Room.receipt", event, this); }; /** * Add a receipt event to the room. * @param {MatrixEvent} event The m.receipt event. * @param {Object} receipts The object to add receipts to */ Room.prototype._addReceiptsToStructure = function (event, receipts) { var self = this; utils.keys(event.getContent()).forEach(function (eventId) { utils.keys(event.getContent()[eventId]).forEach(function (receiptType) { utils.keys(event.getContent()[eventId][receiptType]).forEach(function (userId) { var receipt = event.getContent()[eventId][receiptType][userId]; if (!receipts[receiptType]) { receipts[receiptType] = {}; } var existingReceipt = receipts[receiptType][userId]; if (!existingReceipt) { receipts[receiptType][userId] = {}; } else { // we only want to add this receipt if we think it is later // than the one we already have. (This is managed // server-side, but because we synthesize RRs locally we // have to do it here too.) var ordering = self.getUnfilteredTimelineSet().compareEventOrdering(existingReceipt.eventId, eventId); if (ordering !== null && ordering >= 0) { return; } } receipts[receiptType][userId] = { eventId: eventId, data: receipt }; }); }); }); }; /** * Build and return a map of receipts by event ID * @param {Object} receipts A map of receipts * @return {Object} Map of receipts by event ID */ Room.prototype._buildReceiptCache = function (receipts) { var receiptCacheByEventId = {}; utils.keys(receipts).forEach(function (receiptType) { utils.keys(receipts[receiptType]).forEach(function (userId) { var receipt = receipts[receiptType][userId]; if (!receiptCacheByEventId[receipt.eventId]) { receiptCacheByEventId[receipt.eventId] = []; } receiptCacheByEventId[receipt.eventId].push({ userId: userId, type: receiptType, data: receipt.data }); }); }); return receiptCacheByEventId; }; /** * Add a temporary local-echo receipt to the room to reflect in the * client the fact that we've sent one. * @param {string} userId The user ID if the receipt sender * @param {MatrixEvent} e The event that is to be acknowledged * @param {string} receiptType The type of receipt */ Room.prototype._addLocalEchoReceipt = function (userId, e, receiptType) { this.addReceipt(synthesizeReceipt(userId, e, receiptType), true); }; /** * Update the room-tag event for the room. The previous one is overwritten. * @param {MatrixEvent} event the m.tag event */ Room.prototype.addTags = function (event) { // event content looks like: // content: { // tags: { // $tagName: { $metadata: $value }, // $tagName: { $metadata: $value }, // } // } // XXX: do we need to deep copy here? this.tags = event.getContent().tags || {}; // XXX: we could do a deep-comparison to see if the tags have really // changed - but do we want to bother? this.emit("Room.tags", event, this); }; /** * Update the account_data events for this room, overwriting events of the same type. * @param {Array} events an array of account_data events to add */ Room.prototype.addAccountData = function (events) { for (var i = 0; i < events.length; i++) { var event = events[i]; if (event.getType() === "m.tag") { this.addTags(event); } var lastEvent = this.accountData[event.getType()]; this.accountData[event.getType()] = event; this.emit("Room.accountData", event, this, lastEvent); } }; /** * Access account_data event of given event type for this room * @param {string} type the type of account_data event to be accessed * @return {?MatrixEvent} the account_data event in question */ Room.prototype.getAccountData = function (type) { return this.accountData[type]; }; /** * Returns wheter the syncing user has permission to send a message in the room * @return {boolean} true if the user should be permitted to send * message events into the room. */ Room.prototype.maySendMessage = function () { return this.getMyMembership() === 'join' && this.currentState.maySendEvent('m.room.message', this.myUserId); }; /** * This is an internal method. Calculates the name of the room from the current * room state. * @param {Room} room The matrix room. * @param {string} userId The client's user ID. Used to filter room members * correctly. * @param {bool} ignoreRoomNameEvent Return the implicit room name that we'd see if there * was no m.room.name event. * @return {string} The calculated room name. */ function calculateRoomName(room, userId, ignoreRoomNameEvent) { if (!ignoreRoomNameEvent) { // check for an alias, if any. for now, assume first alias is the // official one. var mRoomName = room.currentState.getStateEvents("m.room.name", ""); if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) { return mRoomName.getContent().name; } } var alias = room.getCanonicalAlias(); if (!alias) { var aliases = room.getAltAliases(); if (aliases.length) { alias = aliases[0]; } } if (alias) { return alias; } var joinedMemberCount = room.currentState.getJoinedMemberCount(); var invitedMemberCount = room.currentState.getInvitedMemberCount(); // -1 because these numbers include the syncing user var inviteJoinCount = joinedMemberCount + invitedMemberCount - 1; // get members that are NOT ourselves and are actually in the room. var otherNames = null; if (room._summaryHeroes) { // if we have a summary, the member state events // should be in the room state otherNames = room._summaryHeroes.map(function (userId) { var member = room.getMember(userId); return member ? member.name : userId; }); } else { var otherMembers = room.currentState.getMembers().filter(function (m) { return m.userId !== userId && (m.membership === "invite" || m.membership === "join"); }); // make sure members have stable order otherMembers.sort(function (a, b) { return a.userId.localeCompare(b.userId); }); // only 5 first members, immitate _summaryHeroes otherMembers = otherMembers.slice(0, 5); otherNames = otherMembers.map(function (m) { return m.name; }); } if (inviteJoinCount) { return memberNamesToRoomName(otherNames, inviteJoinCount); } var myMembership = room.getMyMembership(); // if I have created a room and invited people throuh // 3rd party invites if (myMembership == 'join') { var thirdPartyInvites = room.currentState.getStateEvents("m.room.third_party_invite"); if (thirdPartyInvites && thirdPartyInvites.length) { var thirdPartyNames = thirdPartyInvites.map(function (i) { return i.getContent().display_name; }); return "Inviting ".concat(memberNamesToRoomName(thirdPartyNames)); } } // let's try to figure out who was here before var leftNames = otherNames; // if we didn't have heroes, try finding them in the room state if (!leftNames.length) { leftNames = room.currentState.getMembers().filter(function (m) { return m.userId !== userId && m.membership !== "invite" && m.membership !== "join"; }).map(function (m) { return m.name; }); } if (leftNames.length) { return "Empty room (was ".concat(memberNamesToRoomName(leftNames), ")"); } else { return "Empty room"; } } function memberNamesToRoomName(names) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : names.length + 1; var countWithoutMe = count - 1; if (!names.length) { return "Empty room"; } else if (names.length === 1 && countWithoutMe <= 1) { return names[0]; } else if (names.length === 2 && countWithoutMe <= 2) { return "".concat(names[0], " and ").concat(names[1]); } else { var plural = countWithoutMe > 1; if (plural) { return "".concat(names[0], " and ").concat(countWithoutMe, " others"); } else { return "".concat(names[0], " and 1 other"); } } } /** * Fires when an event we had previously received is redacted. * * (Note this is *not* fired when the redaction happens before we receive the * event). * * @event module:client~MatrixClient#"Room.redaction" * @param {MatrixEvent} event The matrix redaction event * @param {Room} room The room containing the redacted event */ /** * Fires when an event that was previously redacted isn't anymore. * This happens when the redaction couldn't be sent and * was subsequently cancelled by the user. Redactions have a local echo * which is undone in this scenario. * * @event module:client~MatrixClient#"Room.redactionCancelled" * @param {MatrixEvent} event The matrix redaction event that was cancelled. * @param {Room} room The room containing the unredacted event */ /** * Fires whenever the name of a room is updated. * @event module:client~MatrixClient#"Room.name" * @param {Room} room The room whose Room.name was updated. * @example * matrixClient.on("Room.name", function(room){ * var newName = room.name; * }); */ /** * Fires whenever a receipt is received for a room * @event module:client~MatrixClient#"Room.receipt" * @param {event} event The receipt event * @param {Room} room The room whose receipts was updated. * @example * matrixClient.on("Room.receipt", function(event, room){ * var receiptContent = event.getContent(); * }); */ /** * Fires whenever a room's tags are updated. * @event module:client~MatrixClient#"Room.tags" * @param {event} event The tags event * @param {Room} room The room whose Room.tags was updated. * @example * matrixClient.on("Room.tags", function(event, room){ * var newTags = event.getContent().tags; * if (newTags["favourite"]) showStar(room); * }); */ /** * Fires whenever a room's account_data is updated. * @event module:client~MatrixClient#"Room.accountData" * @param {event} event The account_data event * @param {Room} room The room whose account_data was updated. * @param {MatrixEvent} prevEvent The event being replaced by * the new account data, if known. * @example * matrixClient.on("Room.accountData", function(event, room, oldEvent){ * if (event.getType() === "m.room.colorscheme") { * applyColorScheme(event.getContents()); * } * }); */ /** * Fires when the status of a transmitted event is updated. * *

When an event is first transmitted, a temporary copy of the event is * inserted into the timeline, with a temporary event id, and a status of * 'SENDING'. * *

Once the echo comes back from the server, the content of the event * (MatrixEvent.event) is replaced by the complete event from the homeserver, * thus updating its event id, as well as server-generated fields such as the * timestamp. Its status is set to null. * *

Once the /send request completes, if the remote echo has not already * arrived, the event is updated with a new event id and the status is set to * 'SENT'. The server-generated fields are of course not updated yet. * *

If the /send fails, In this case, the event's status is set to * 'NOT_SENT'. If it is later resent, the process starts again, setting the * status to 'SENDING'. Alternatively, the message may be cancelled, which * removes the event from the room, and sets the status to 'CANCELLED'. * *

This event is raised to reflect each of the transitions above. * * @event module:client~MatrixClient#"Room.localEchoUpdated" * * @param {MatrixEvent} event The matrix event which has been updated * * @param {Room} room The room containing the redacted event * * @param {string} oldEventId The previous event id (the temporary event id, * except when updating a successfully-sent event when its echo arrives) * * @param {EventStatus} oldStatus The previous event status. */ },{"../ReEmitter":53,"../content-repo":59,"../logger":95,"../utils":123,"./event":100,"./event-timeline":99,"./event-timeline-set":98,"./room-member":103,"./room-summary":105,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"events":36}],107:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SearchResult = SearchResult; var utils = _interopRequireWildcard(require("../utils")); var _eventContext = require("./event-context"); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/search-result */ /** * Construct a new SearchResult * * @param {number} rank where this SearchResult ranks in the results * @param {event-context.EventContext} eventContext the matching event and its * context * * @constructor */ function SearchResult(rank, eventContext) { this.rank = rank; this.context = eventContext; } /** * Create a SearchResponse from the response to /search * @static * @param {Object} jsonObj * @param {function} eventMapper * @return {SearchResult} */ SearchResult.fromJson = function (jsonObj, eventMapper) { var jsonContext = jsonObj.context || {}; var events_before = jsonContext.events_before || []; var events_after = jsonContext.events_after || []; var context = new _eventContext.EventContext(eventMapper(jsonObj.result)); context.setPaginateToken(jsonContext.start, true); context.addEvents(utils.map(events_before, eventMapper), true); context.addEvents(utils.map(events_after, eventMapper), false); context.setPaginateToken(jsonContext.end, false); return new SearchResult(jsonObj.rank, context); }; },{"../utils":123,"./event-context":97,"@babel/runtime/helpers/interopRequireWildcard":13}],108:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.User = User; var utils = _interopRequireWildcard(require("../utils")); var _events = require("events"); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 models/user */ /** * Construct a new User. A User must have an ID and can optionally have extra * information associated with it. * @constructor * @param {string} userId Required. The ID of this user. * @prop {string} userId The ID of the user. * @prop {Object} info The info object supplied in the constructor. * @prop {string} displayName The 'displayname' of the user if known. * @prop {string} avatarUrl The 'avatar_url' of the user if known. * @prop {string} presence The presence enum if known. * @prop {string} presenceStatusMsg The presence status message if known. * @prop {Number} lastActiveAgo The time elapsed in ms since the user interacted * proactively with the server, or we saw a message from the user * @prop {Number} lastPresenceTs Timestamp (ms since the epoch) for when we last * received presence data for this user. We can subtract * lastActiveAgo from this to approximate an absolute value for * when a user was last active. * @prop {Boolean} currentlyActive Whether we should consider lastActiveAgo to be * an approximation and that the user should be seen as active 'now' * @prop {string} _unstable_statusMessage The status message for the user, if known. This is * different from the presenceStatusMsg in that this is not tied to * the user's presence, and should be represented differently. * @prop {Object} events The events describing this user. * @prop {MatrixEvent} events.presence The m.presence event for this user. */ function User(userId) { this.userId = userId; this.presence = "offline"; this.presenceStatusMsg = null; this._unstable_statusMessage = ""; this.displayName = userId; this.rawDisplayName = userId; this.avatarUrl = null; this.lastActiveAgo = 0; this.lastPresenceTs = 0; this.currentlyActive = false; this.events = { presence: null, profile: null }; this._updateModifiedTime(); } utils.inherits(User, _events.EventEmitter); /** * Update this User with the given presence event. May fire "User.presence", * "User.avatarUrl" and/or "User.displayName" if this event updates this user's * properties. * @param {MatrixEvent} event The m.presence event. * @fires module:client~MatrixClient#event:"User.presence" * @fires module:client~MatrixClient#event:"User.displayName" * @fires module:client~MatrixClient#event:"User.avatarUrl" */ User.prototype.setPresenceEvent = function (event) { if (event.getType() !== "m.presence") { return; } var firstFire = this.events.presence === null; this.events.presence = event; var eventsToFire = []; if (event.getContent().presence !== this.presence || firstFire) { eventsToFire.push("User.presence"); } if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) { eventsToFire.push("User.avatarUrl"); } if (event.getContent().displayname && event.getContent().displayname !== this.displayName) { eventsToFire.push("User.displayName"); } if (event.getContent().currently_active !== undefined && event.getContent().currently_active !== this.currentlyActive) { eventsToFire.push("User.currentlyActive"); } this.presence = event.getContent().presence; eventsToFire.push("User.lastPresenceTs"); if (event.getContent().status_msg) { this.presenceStatusMsg = event.getContent().status_msg; } if (event.getContent().displayname) { this.displayName = event.getContent().displayname; } if (event.getContent().avatar_url) { this.avatarUrl = event.getContent().avatar_url; } this.lastActiveAgo = event.getContent().last_active_ago; this.lastPresenceTs = Date.now(); this.currentlyActive = event.getContent().currently_active; this._updateModifiedTime(); for (var i = 0; i < eventsToFire.length; i++) { this.emit(eventsToFire[i], event, this); } }; /** * Manually set this user's display name. No event is emitted in response to this * as there is no underlying MatrixEvent to emit with. * @param {string} name The new display name. */ User.prototype.setDisplayName = function (name) { var oldName = this.displayName; if (typeof name === "string") { this.displayName = name; } else { this.displayName = undefined; } if (name !== oldName) { this._updateModifiedTime(); } }; /** * Manually set this user's non-disambiguated display name. No event is emitted * in response to this as there is no underlying MatrixEvent to emit with. * @param {string} name The new display name. */ User.prototype.setRawDisplayName = function (name) { if (typeof name === "string") { this.rawDisplayName = name; } else { this.rawDisplayName = undefined; } }; /** * Manually set this user's avatar URL. No event is emitted in response to this * as there is no underlying MatrixEvent to emit with. * @param {string} url The new avatar URL. */ User.prototype.setAvatarUrl = function (url) { var oldUrl = this.avatarUrl; this.avatarUrl = url; if (url !== oldUrl) { this._updateModifiedTime(); } }; /** * Update the last modified time to the current time. */ User.prototype._updateModifiedTime = function () { this._modified = Date.now(); }; /** * Get the timestamp when this User was last updated. This timestamp is * updated when this User receives a new Presence event which has updated a * property on this object. It is updated before firing events. * @return {number} The timestamp */ User.prototype.getLastModifiedTime = function () { return this._modified; }; /** * Get the absolute timestamp when this User was last known active on the server. * It is *NOT* accurate if this.currentlyActive is true. * @return {number} The timestamp */ User.prototype.getLastActiveTs = function () { return this.lastPresenceTs - this.lastActiveAgo; }; /** * Manually set the user's status message. * @param {MatrixEvent} event The im.vector.user_status event. * @fires module:client~MatrixClient#event:"User._unstable_statusMessage" */ User.prototype._unstable_updateStatusMessage = function (event) { if (!event.getContent()) this._unstable_statusMessage = "";else this._unstable_statusMessage = event.getContent()["status"]; this._updateModifiedTime(); this.emit("User._unstable_statusMessage", this); }; /** * Fires whenever any user's lastPresenceTs changes, * ie. whenever any presence event is received for a user. * @event module:client~MatrixClient#"User.lastPresenceTs" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {User} user The user whose User.lastPresenceTs changed. * @example * matrixClient.on("User.lastPresenceTs", function(event, user){ * var newlastPresenceTs = user.lastPresenceTs; * }); */ /** * Fires whenever any user's presence changes. * @event module:client~MatrixClient#"User.presence" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {User} user The user whose User.presence changed. * @example * matrixClient.on("User.presence", function(event, user){ * var newPresence = user.presence; * }); */ /** * Fires whenever any user's currentlyActive changes. * @event module:client~MatrixClient#"User.currentlyActive" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {User} user The user whose User.currentlyActive changed. * @example * matrixClient.on("User.currentlyActive", function(event, user){ * var newCurrentlyActive = user.currentlyActive; * }); */ /** * Fires whenever any user's display name changes. * @event module:client~MatrixClient#"User.displayName" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {User} user The user whose User.displayName changed. * @example * matrixClient.on("User.displayName", function(event, user){ * var newName = user.displayName; * }); */ /** * Fires whenever any user's avatar URL changes. * @event module:client~MatrixClient#"User.avatarUrl" * @param {MatrixEvent} event The matrix event which caused this event to fire. * @param {User} user The user whose User.avatarUrl changed. * @example * matrixClient.on("User.avatarUrl", function(event, user){ * var newUrl = user.avatarUrl; * }); */ },{"../utils":123,"@babel/runtime/helpers/interopRequireWildcard":13,"events":36}],109:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.PushProcessor = PushProcessor; var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var _utils = require("./utils"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * @module pushprocessor */ var RULEKINDS_IN_ORDER = ['override', 'content', 'room', 'sender', 'underride']; // The default override rules to apply to the push rules that arrive from the server. // We do this for two reasons: // 1. Synapse is unlikely to send us the push rule in an incremental sync - see // https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for // more details. // 2. We often want to start using push rules ahead of the server supporting them, // and so we can put them here. var DEFAULT_OVERRIDE_RULES = [{ // For homeservers which don't support MSC1930 yet rule_id: ".m.rule.tombstone", "default": true, enabled: true, conditions: [{ kind: "event_match", key: "type", pattern: "m.room.tombstone" }, { kind: "event_match", key: "state_key", pattern: "" }], actions: ["notify", { set_tweak: "highlight", value: true }] }, { // For homeservers which don't support MSC2153 yet rule_id: ".m.rule.reaction", "default": true, enabled: true, conditions: [{ kind: "event_match", key: "type", pattern: "m.reaction" }], actions: ["dont_notify"] }]; /** * Construct a Push Processor. * @constructor * @param {Object} client The Matrix client object to use */ function PushProcessor(client) { var _this = this; var cachedGlobToRegex = {// $glob: RegExp, }; var matchingRuleFromKindSet = function matchingRuleFromKindSet(ev, kindset) { for (var ruleKindIndex = 0; ruleKindIndex < RULEKINDS_IN_ORDER.length; ++ruleKindIndex) { var kind = RULEKINDS_IN_ORDER[ruleKindIndex]; var ruleset = kindset[kind]; if (!ruleset) { continue; } for (var ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) { var rule = ruleset[ruleIndex]; if (!rule.enabled) { continue; } var rawrule = templateRuleToRaw(kind, rule); if (!rawrule) { continue; } if (_this.ruleMatchesEvent(rawrule, ev)) { rule.kind = kind; return rule; } } } return null; }; var templateRuleToRaw = function templateRuleToRaw(kind, tprule) { var rawrule = { 'rule_id': tprule.rule_id, 'actions': tprule.actions, 'conditions': [] }; switch (kind) { case 'underride': case 'override': rawrule.conditions = tprule.conditions; break; case 'room': if (!tprule.rule_id) { return null; } rawrule.conditions.push({ 'kind': 'event_match', 'key': 'room_id', 'value': tprule.rule_id }); break; case 'sender': if (!tprule.rule_id) { return null; } rawrule.conditions.push({ 'kind': 'event_match', 'key': 'user_id', 'value': tprule.rule_id }); break; case 'content': if (!tprule.pattern) { return null; } rawrule.conditions.push({ 'kind': 'event_match', 'key': 'content.body', 'pattern': tprule.pattern }); break; } return rawrule; }; var eventFulfillsCondition = function eventFulfillsCondition(cond, ev) { var condition_functions = { "event_match": eventFulfillsEventMatchCondition, "contains_display_name": eventFulfillsDisplayNameCondition, "room_member_count": eventFulfillsRoomMemberCountCondition, "sender_notification_permission": eventFulfillsSenderNotifPermCondition }; if (condition_functions[cond.kind]) { return condition_functions[cond.kind](cond, ev); } // unknown conditions: we previously matched all unknown conditions, // but given that rules can be added to the base rules on a server, // it's probably better to not match unknown conditions. return false; }; var eventFulfillsSenderNotifPermCondition = function eventFulfillsSenderNotifPermCondition(cond, ev) { var notifLevelKey = cond['key']; if (!notifLevelKey) { return false; } var room = client.getRoom(ev.getRoomId()); if (!room || !room.currentState) { return false; } // Note that this should not be the current state of the room but the state at // the point the event is in the DAG. Unfortunately the js-sdk does not store // this. return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()); }; var eventFulfillsRoomMemberCountCondition = function eventFulfillsRoomMemberCountCondition(cond, ev) { if (!cond.is) { return false; } var room = client.getRoom(ev.getRoomId()); if (!room || !room.currentState || !room.currentState.members) { return false; } var memberCount = room.currentState.getJoinedMemberCount(); var m = cond.is.match(/^([=<>]*)([0-9]*)$/); if (!m) { return false; } var ineq = m[1]; var rhs = parseInt(m[2]); if (isNaN(rhs)) { return false; } switch (ineq) { case '': case '==': return memberCount == rhs; case '<': return memberCount < rhs; case '>': return memberCount > rhs; case '<=': return memberCount <= rhs; case '>=': return memberCount >= rhs; default: return false; } }; var eventFulfillsDisplayNameCondition = function eventFulfillsDisplayNameCondition(cond, ev) { var content = ev.getContent(); if (ev.isEncrypted() && ev.getClearContent()) { content = ev.getClearContent(); } if (!content || !content.body || typeof content.body != 'string') { return false; } var room = client.getRoom(ev.getRoomId()); if (!room || !room.currentState || !room.currentState.members || !room.currentState.getMember(client.credentials.userId)) { return false; } var displayName = room.currentState.getMember(client.credentials.userId).name; // N.B. we can't use \b as it chokes on unicode. however \W seems to be okay // as shorthand for [^0-9A-Za-z_]. var pat = new RegExp("(^|\\W)" + (0, _utils.escapeRegExp)(displayName) + "(\\W|$)", 'i'); return content.body.search(pat) > -1; }; var eventFulfillsEventMatchCondition = function eventFulfillsEventMatchCondition(cond, ev) { if (!cond.key) { return false; } var val = valueForDottedKey(cond.key, ev); if (typeof val !== 'string') { return false; } if (cond.value) { return cond.value === val; } var regex; if (cond.key == 'content.body') { regex = createCachedRegex('(^|\\W)', cond.pattern, '(\\W|$)'); } else { regex = createCachedRegex('^', cond.pattern, '$'); } return !!val.match(regex); }; var createCachedRegex = function createCachedRegex(prefix, glob, suffix) { if (cachedGlobToRegex[glob]) { return cachedGlobToRegex[glob]; } cachedGlobToRegex[glob] = new RegExp(prefix + (0, _utils.globToRegexp)(glob) + suffix, 'i'); return cachedGlobToRegex[glob]; }; var valueForDottedKey = function valueForDottedKey(key, ev) { var parts = key.split('.'); var val; // special-case the first component to deal with encrypted messages var firstPart = parts[0]; if (firstPart === 'content') { val = ev.getContent(); parts.shift(); } else if (firstPart === 'type') { val = ev.getType(); parts.shift(); } else { // use the raw event for any other fields val = ev.event; } while (parts.length > 0) { var thisPart = parts.shift(); if ((0, _utils.isNullOrUndefined)(val[thisPart])) { return null; } val = val[thisPart]; } return val; }; var matchingRuleForEventWithRulesets = function matchingRuleForEventWithRulesets(ev, rulesets) { if (!rulesets) { return null; } if (ev.getSender() === client.credentials.userId) { return null; } return matchingRuleFromKindSet(ev, rulesets.global); }; var pushActionsForEventAndRulesets = function pushActionsForEventAndRulesets(ev, rulesets) { var rule = matchingRuleForEventWithRulesets(ev, rulesets); if (!rule) { return {}; } var actionObj = PushProcessor.actionListToActionsObject(rule.actions); // Some actions are implicit in some situations: we add those here if (actionObj.tweaks.highlight === undefined) { // if it isn't specified, highlight if it's a content // rule but otherwise not actionObj.tweaks.highlight = rule.kind == 'content'; } return actionObj; }; this.ruleMatchesEvent = function (rule, ev) { var ret = true; for (var i = 0; i < rule.conditions.length; ++i) { var cond = rule.conditions[i]; ret &= eventFulfillsCondition(cond, ev); } //console.log("Rule "+rule.rule_id+(ret ? " matches" : " doesn't match")); return ret; }; /** * Get the user's push actions for the given event * * @param {module:models/event.MatrixEvent} ev * * @return {PushAction} */ this.actionsForEvent = function (ev) { return pushActionsForEventAndRulesets(ev, client.pushRules); }; /** * Get one of the users push rules by its ID * * @param {string} ruleId The ID of the rule to search for * @return {object} The push rule, or null if no such rule was found */ this.getPushRuleById = function (ruleId) { for (var _i = 0, _arr = ['global']; _i < _arr.length; _i++) { var scope = _arr[_i]; if (client.pushRules[scope] === undefined) continue; var _iterator = _createForOfIteratorHelper(RULEKINDS_IN_ORDER), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var kind = _step.value; if (client.pushRules[scope][kind] === undefined) continue; var _iterator2 = _createForOfIteratorHelper(client.pushRules[scope][kind]), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var rule = _step2.value; if (rule.rule_id === ruleId) return rule; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return null; }; } /** * Convert a list of actions into a object with the actions as keys and their values * eg. [ 'notify', { set_tweak: 'sound', value: 'default' } ] * becomes { notify: true, tweaks: { sound: 'default' } } * @param {array} actionlist The actions list * * @return {object} A object with key 'notify' (true or false) and an object of actions */ PushProcessor.actionListToActionsObject = function (actionlist) { var actionobj = { 'notify': false, 'tweaks': {} }; for (var i = 0; i < actionlist.length; ++i) { var action = actionlist[i]; if (action === 'notify') { actionobj.notify = true; } else if ((0, _typeof2["default"])(action) === 'object') { if (action.value === undefined) { action.value = true; } actionobj.tweaks[action.set_tweak] = action.value; } } return actionobj; }; /** * Rewrites conditions on a client's push rules to match the defaults * where applicable. Useful for upgrading push rules to more strict * conditions when the server is falling behind on defaults. * @param {object} incomingRules The client's existing push rules * @returns {object} The rewritten rules */ PushProcessor.rewriteDefaultRules = function (incomingRules) { var newRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone // These lines are mostly to make the tests happy. We shouldn't run into these // properties missing in practice. if (!newRules) newRules = {}; if (!newRules.global) newRules.global = {}; if (!newRules.global.override) newRules.global.override = []; // Merge the client-level defaults with the ones from the server var globalOverrides = newRules.global.override; var _iterator3 = _createForOfIteratorHelper(DEFAULT_OVERRIDE_RULES), _step3; try { var _loop = function _loop() { var override = _step3.value; var existingRule = globalOverrides.find(function (r) { return r.rule_id === override.rule_id; }); if (existingRule) { // Copy over the actions, default, and conditions. Don't touch the user's // preference. existingRule["default"] = override["default"]; existingRule.conditions = override.conditions; existingRule.actions = override.actions; } else { // Add the rule var ruleId = override.rule_id; console.warn("Adding default global override for ".concat(ruleId)); globalOverrides.push(override); } }; for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { _loop(); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return newRules; }; /** * @typedef {Object} PushAction * @type {Object} * @property {boolean} notify Whether this event should notify the user or not. * @property {Object} tweaks How this event should be notified. * @property {boolean} tweaks.highlight Whether this event should be highlighted * on the UI. * @property {boolean} tweaks.sound Whether this notification should produce a * noise. */ },{"./utils":123,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/typeof":24}],110:[function(require,module,exports){ "use strict"; /* Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.randomString = void 0; function randomString(len) { let ret = ""; const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (let i = 0; i < len; ++i) { ret += chars.charAt(Math.floor(Math.random() * chars.length)); } return ret; } exports.randomString = randomString; },{}],111:[function(require,module,exports){ (function (global){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setNow = setNow; exports.setTimeout = setTimeout; exports.clearTimeout = clearTimeout; var _logger = require("./logger"); /* Copyright 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /* A re-implementation of the javascript callback functions (setTimeout, * clearTimeout; setInterval and clearInterval are not yet implemented) which * try to improve handling of large clock jumps (as seen when * suspending/resuming the system). * * In particular, if a timeout would have fired while the system was suspended, * it will instead fire as soon as possible after resume. */ // we schedule a callback at least this often, to check if we've missed out on // some wall-clock time due to being suspended. var TIMER_CHECK_PERIOD_MS = 1000; // counter, for making up ids to return from setTimeout var _count = 0; // the key for our callback with the real global.setTimeout var _realCallbackKey; // a sorted list of the callbacks to be run. // each is an object with keys [runAt, func, params, key]. var _callbackList = []; // var debuglog = logger.log.bind(logger); var debuglog = function debuglog() {}; /** * Replace the function used by this module to get the current time. * * Intended for use by the unit tests. * * @param {function} [f] function which should return a millisecond counter * * @internal */ function setNow(f) { _now = f || Date.now; } var _now = Date.now; /** * reimplementation of window.setTimeout, which will call the callback if * the wallclock time goes past the deadline. * * @param {function} func callback to be called after a delay * @param {Number} delayMs number of milliseconds to delay by * * @return {Number} an identifier for this callback, which may be passed into * clearTimeout later. */ function setTimeout(func, delayMs) { delayMs = delayMs || 0; if (delayMs < 0) { delayMs = 0; } var params = Array.prototype.slice.call(arguments, 2); var runAt = _now() + delayMs; var key = _count++; debuglog("setTimeout: scheduling cb", key, "at", runAt, "(delay", delayMs, ")"); var data = { runAt: runAt, func: func, params: params, key: key }; // figure out where it goes in the list var idx = binarySearch(_callbackList, function (el) { return el.runAt - runAt; }); _callbackList.splice(idx, 0, data); _scheduleRealCallback(); return key; } /** * reimplementation of window.clearTimeout, which mirrors setTimeout * * @param {Number} key result from an earlier setTimeout call */ function clearTimeout(key) { if (_callbackList.length === 0) { return; } // remove the element from the list var i; for (i = 0; i < _callbackList.length; i++) { var cb = _callbackList[i]; if (cb.key == key) { _callbackList.splice(i, 1); break; } } // iff it was the first one in the list, reschedule our callback. if (i === 0) { _scheduleRealCallback(); } } // use the real global.setTimeout to schedule a callback to _runCallbacks. function _scheduleRealCallback() { if (_realCallbackKey) { global.clearTimeout(_realCallbackKey); } var first = _callbackList[0]; if (!first) { debuglog("_scheduleRealCallback: no more callbacks, not rescheduling"); return; } var now = _now(); var delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS); debuglog("_scheduleRealCallback: now:", now, "delay:", delayMs); _realCallbackKey = global.setTimeout(_runCallbacks, delayMs); } function _runCallbacks() { var cb; var now = _now(); debuglog("_runCallbacks: now:", now); // get the list of things to call var callbacksToRun = []; while (true) { var first = _callbackList[0]; if (!first || first.runAt > now) { break; } cb = _callbackList.shift(); debuglog("_runCallbacks: popping", cb.key); callbacksToRun.push(cb); } // reschedule the real callback before running our functions, to // keep the codepaths the same whether or not our functions // register their own setTimeouts. _scheduleRealCallback(); for (var i = 0; i < callbacksToRun.length; i++) { cb = callbacksToRun[i]; try { cb.func.apply(global, cb.params); } catch (e) { _logger.logger.error("Uncaught exception in callback function", e.stack || e); } } } /* search in a sorted array. * * returns the index of the last element for which func returns * greater than zero, or array.length if no such element exists. */ function binarySearch(array, func) { // min is inclusive, max exclusive. var min = 0; var max = array.length; while (min < max) { var mid = min + max >> 1; var res = func(array[mid]); if (res > 0) { // the element at 'mid' is too big; set it as the new max. max = mid; } else { // the element at 'mid' is too small. 'min' is inclusive, so +1. min = mid + 1; } } // presumably, min==max now. return min; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./logger":95}],112:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixScheduler = MatrixScheduler; var utils = _interopRequireWildcard(require("./utils")); var _logger = require("./logger"); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * This is an internal module which manages queuing, scheduling and retrying * of requests. * @module scheduler */ var DEBUG = false; // set true to enable console logging. /** * Construct a scheduler for Matrix. Requires * {@link module:scheduler~MatrixScheduler#setProcessFunction} to be provided * with a way of processing events. * @constructor * @param {module:scheduler~retryAlgorithm} retryAlgorithm Optional. The retry * algorithm to apply when determining when to try to send an event again. * Defaults to {@link module:scheduler~MatrixScheduler.RETRY_BACKOFF_RATELIMIT}. * @param {module:scheduler~queueAlgorithm} queueAlgorithm Optional. The queuing * algorithm to apply when determining which events should be sent before the * given event. Defaults to {@link module:scheduler~MatrixScheduler.QUEUE_MESSAGES}. */ function MatrixScheduler(retryAlgorithm, queueAlgorithm) { this.retryAlgorithm = retryAlgorithm || MatrixScheduler.RETRY_BACKOFF_RATELIMIT; this.queueAlgorithm = queueAlgorithm || MatrixScheduler.QUEUE_MESSAGES; this._queues = {// queueName: [{ // event: MatrixEvent, // event to send // defer: Deferred, // defer to resolve/reject at the END of the retries // attempts: Number // number of times we've called processFn // }, ...] }; this._activeQueues = []; this._procFn = null; } /** * Retrieve a queue based on an event. The event provided does not need to be in * the queue. * @param {MatrixEvent} event An event to get the queue for. * @return {?Array} A shallow copy of events in the queue or null. * Modifying this array will not modify the list itself. Modifying events in * this array will modify the underlying event in the queue. * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue. */ MatrixScheduler.prototype.getQueueForEvent = function (event) { var name = this.queueAlgorithm(event); if (!name || !this._queues[name]) { return null; } return utils.map(this._queues[name], function (obj) { return obj.event; }); }; /** * Remove this event from the queue. The event is equal to another event if they * have the same ID returned from event.getId(). * @param {MatrixEvent} event The event to remove. * @return {boolean} True if this event was removed. */ MatrixScheduler.prototype.removeEventFromQueue = function (event) { var name = this.queueAlgorithm(event); if (!name || !this._queues[name]) { return false; } var removed = false; utils.removeElement(this._queues[name], function (element) { if (element.event.getId() === event.getId()) { // XXX we should probably reject the promise? // https://github.com/matrix-org/matrix-js-sdk/issues/496 removed = true; return true; } }); return removed; }; /** * Set the process function. Required for events in the queue to be processed. * If set after events have been added to the queue, this will immediately start * processing them. * @param {module:scheduler~processFn} fn The function that can process events * in the queue. */ MatrixScheduler.prototype.setProcessFunction = function (fn) { this._procFn = fn; _startProcessingQueues(this); }; /** * Queue an event if it is required and start processing queues. * @param {MatrixEvent} event The event that may be queued. * @return {?Promise} A promise if the event was queued, which will be * resolved or rejected in due time, else null. */ MatrixScheduler.prototype.queueEvent = function (event) { var queueName = this.queueAlgorithm(event); if (!queueName) { return null; } // add the event to the queue and make a deferred for it. if (!this._queues[queueName]) { this._queues[queueName] = []; } var defer = utils.defer(); this._queues[queueName].push({ event: event, defer: defer, attempts: 0 }); debuglog("Queue algorithm dumped event %s into queue '%s'", event.getId(), queueName); _startProcessingQueues(this); return defer.promise; }; /** * Retries events up to 4 times using exponential backoff. This produces wait * times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the * failure was due to a rate limited request, the time specified in the error is * waited before being retried. * @param {MatrixEvent} event * @param {Number} attempts * @param {MatrixError} err * @return {Number} * @see module:scheduler~retryAlgorithm */ MatrixScheduler.RETRY_BACKOFF_RATELIMIT = function (event, attempts, err) { if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) { // client error; no amount of retrying with save you now. return -1; } // we ship with browser-request which returns { cors: rejected } when trying // with no connection, so if we match that, give up since they have no conn. if (err.cors === "rejected") { return -1; } // if event that we are trying to send is too large in any way then retrying won't help if (err.name === "M_TOO_LARGE") { return -1; } if (err.name === "M_LIMIT_EXCEEDED") { var waitTime = err.data.retry_after_ms; if (waitTime) { return waitTime; } } if (attempts > 4) { return -1; // give up } return 1000 * Math.pow(2, attempts); }; /** * Queues m.room.message events and lets other events continue * concurrently. * @param {MatrixEvent} event * @return {string} * @see module:scheduler~queueAlgorithm */ MatrixScheduler.QUEUE_MESSAGES = function (event) { // enqueue messages or events that associate with another event (redactions and relations) if (event.getType() === "m.room.message" || event.hasAssocation()) { // put these events in the 'message' queue. return "message"; } // allow all other events continue concurrently. return null; }; function _startProcessingQueues(scheduler) { if (!scheduler._procFn) { return; } // for each inactive queue with events in them utils.forEach(utils.filter(utils.keys(scheduler._queues), function (queueName) { return scheduler._activeQueues.indexOf(queueName) === -1 && scheduler._queues[queueName].length > 0; }), function (queueName) { // mark the queue as active scheduler._activeQueues.push(queueName); // begin processing the head of the queue debuglog("Spinning up queue: '%s'", queueName); _processQueue(scheduler, queueName); }); } function _processQueue(scheduler, queueName) { // get head of queue var obj = _peekNextEvent(scheduler, queueName); if (!obj) { // queue is empty. Mark as inactive and stop recursing. var index = scheduler._activeQueues.indexOf(queueName); if (index >= 0) { scheduler._activeQueues.splice(index, 1); } debuglog("Stopping queue '%s' as it is now empty", queueName); return; } debuglog("Queue '%s' has %s pending events", queueName, scheduler._queues[queueName].length); // fire the process function and if it resolves, resolve the deferred. Else // invoke the retry algorithm. // First wait for a resolved promise, so the resolve handlers for // the deferred of the previously sent event can run. // This way enqueued relations/redactions to enqueued events can receive // the remove id of their target before being sent. Promise.resolve().then(function () { return scheduler._procFn(obj.event); }).then(function (res) { // remove this from the queue _removeNextEvent(scheduler, queueName); debuglog("Queue '%s' sent event %s", queueName, obj.event.getId()); obj.defer.resolve(res); // keep processing _processQueue(scheduler, queueName); }, function (err) { obj.attempts += 1; // ask the retry algorithm when/if we should try again var waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err); debuglog("retry(%s) err=%s event_id=%s waitTime=%s", obj.attempts, err, obj.event.getId(), waitTimeMs); if (waitTimeMs === -1) { // give up (you quitter!) debuglog("Queue '%s' giving up on event %s", queueName, obj.event.getId()); // remove this from the queue _removeNextEvent(scheduler, queueName); obj.defer.reject(err); // process next event _processQueue(scheduler, queueName); } else { setTimeout(function () { _processQueue(scheduler, queueName); }, waitTimeMs); } }); } function _peekNextEvent(scheduler, queueName) { var queue = scheduler._queues[queueName]; if (!utils.isArray(queue)) { return null; } return queue[0]; } function _removeNextEvent(scheduler, queueName) { var queue = scheduler._queues[queueName]; if (!utils.isArray(queue)) { return null; } return queue.shift(); } function debuglog() { if (DEBUG) { _logger.logger.log.apply(_logger.logger, arguments); } } /** * The retry algorithm to apply when retrying events. To stop retrying, return * -1. If this event was part of a queue, it will be removed from * the queue. * @callback retryAlgorithm * @param {MatrixEvent} event The event being retried. * @param {Number} attempts The number of failed attempts. This will always be * >= 1. * @param {MatrixError} err The most recent error message received when trying * to send this event. * @return {Number} The number of milliseconds to wait before trying again. If * this is 0, the request will be immediately retried. If this is * -1, the event will be marked as * {@link module:models/event.EventStatus.NOT_SENT} and will not be retried. */ /** * The queuing algorithm to apply to events. This function must be idempotent as * it may be called multiple times with the same event. All queues created are * serviced in a FIFO manner. To send the event ASAP, return null * which will not put this event in a queue. Events that fail to send that form * part of a queue will be removed from the queue and the next event in the * queue will be sent. * @callback queueAlgorithm * @param {MatrixEvent} event The event to be sent. * @return {string} The name of the queue to put the event into. If a queue with * this name does not exist, it will be created. If this is null, * the event is not put into a queue and will be sent concurrently. */ /** * The function to invoke to process (send) events in the queue. * @callback processFn * @param {MatrixEvent} event The event to send. * @return {Promise} Resolved/rejected depending on the outcome of the request. */ },{"./logger":95,"./utils":123,"@babel/runtime/helpers/interopRequireWildcard":13}],113:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SERVICE_TYPES = void 0; /* Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ var SERVICE_TYPES = Object.freeze({ IS: 'SERVICE_TYPE_IS', // An Identity Service IM: 'SERVICE_TYPE_IM' // An Integration Manager }); exports.SERVICE_TYPES = SERVICE_TYPES; },{}],114:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.LocalIndexedDBStoreBackend = LocalIndexedDBStoreBackend; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _syncAccumulator = require("../sync-accumulator"); var utils = _interopRequireWildcard(require("../utils")); var IndexedDBHelpers = _interopRequireWildcard(require("../indexeddb-helpers")); var _logger = require("../logger"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var VERSION = 3; function createDatabase(db) { // Make user store, clobber based on user ID. (userId property of User objects) db.createObjectStore("users", { keyPath: ["userId"] }); // Make account data store, clobber based on event type. // (event.type property of MatrixEvent objects) db.createObjectStore("accountData", { keyPath: ["type"] }); // Make /sync store (sync tokens, room data, etc), always clobber (const key). db.createObjectStore("sync", { keyPath: ["clobber"] }); } function upgradeSchemaV2(db) { var oobMembersStore = db.createObjectStore("oob_membership_events", { keyPath: ["room_id", "state_key"] }); oobMembersStore.createIndex("room", "room_id"); } function upgradeSchemaV3(db) { db.createObjectStore("client_options", { keyPath: ["clobber"] }); } /** * Helper method to collect results from a Cursor and promiseify it. * @param {ObjectStore|Index} store The store to perform openCursor on. * @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor. * @param {Function} resultMapper A function which is repeatedly called with a * Cursor. * Return the data you want to keep. * @return {Promise} Resolves to an array of whatever you returned from * resultMapper. */ function selectQuery(store, keyRange, resultMapper) { var query = store.openCursor(keyRange); return new Promise(function (resolve, reject) { var results = []; query.onerror = function (event) { reject(new Error("Query failed: " + event.target.errorCode)); }; // collect results query.onsuccess = function (event) { var cursor = event.target.result; if (!cursor) { resolve(results); return; // end of results } results.push(resultMapper(cursor)); cursor["continue"](); }; }); } function txnAsPromise(txn) { return new Promise(function (resolve, reject) { txn.oncomplete = function (event) { resolve(event); }; txn.onerror = function (event) { reject(event.target.error); }; }); } function reqAsEventPromise(req) { return new Promise(function (resolve, reject) { req.onsuccess = function (event) { resolve(event); }; req.onerror = function (event) { reject(event.target.error); }; }); } function reqAsPromise(req) { return new Promise(function (resolve, reject) { req.onsuccess = function () { return resolve(req); }; req.onerror = function (err) { return reject(err); }; }); } function reqAsCursorPromise(req) { return reqAsEventPromise(req).then(function (event) { return event.target.result; }); } /** * Does the actual reading from and writing to the indexeddb * * Construct a new Indexed Database store backend. This requires a call to * connect() before this store can be used. * @constructor * @param {Object} indexedDBInterface The Indexed DB interface e.g * window.indexedDB * @param {string=} dbName Optional database name. The same name must be used * to open the same database. */ function LocalIndexedDBStoreBackend(indexedDBInterface, dbName) { this.indexedDB = indexedDBInterface; this._dbName = "matrix-js-sdk:" + (dbName || "default"); this.db = null; this._disconnected = true; this._syncAccumulator = new _syncAccumulator.SyncAccumulator(); this._isNewlyCreated = false; } LocalIndexedDBStoreBackend.exists = function (indexedDB, dbName) { dbName = "matrix-js-sdk:" + (dbName || "default"); return IndexedDBHelpers.exists(indexedDB, dbName); }; LocalIndexedDBStoreBackend.prototype = { /** * Attempt to connect to the database. This can fail if the user does not * grant permission. * @return {Promise} Resolves if successfully connected. */ connect: function connect() { var _this = this; if (!this._disconnected) { _logger.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"); return Promise.resolve(); } this._disconnected = false; _logger.logger.log("LocalIndexedDBStoreBackend.connect: connecting..."); var req = this.indexedDB.open(this._dbName, VERSION); req.onupgradeneeded = function (ev) { var db = ev.target.result; var oldVersion = ev.oldVersion; _logger.logger.log("LocalIndexedDBStoreBackend.connect: upgrading from ".concat(oldVersion)); if (oldVersion < 1) { // The database did not previously exist. _this._isNewlyCreated = true; createDatabase(db); } if (oldVersion < 2) { upgradeSchemaV2(db); } if (oldVersion < 3) { upgradeSchemaV3(db); } // Expand as needed. }; req.onblocked = function () { _logger.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere"); }; _logger.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."); return reqAsEventPromise(req).then(function (ev) { _logger.logger.log("LocalIndexedDBStoreBackend.connect: connected"); _this.db = ev.target.result; // add a poorly-named listener for when deleteDatabase is called // so we can close our db connections. _this.db.onversionchange = function () { _this.db.close(); }; return _this._init(); }); }, /** @return {bool} whether or not the database was newly created in this session. */ isNewlyCreated: function isNewlyCreated() { return Promise.resolve(this._isNewlyCreated); }, /** * Having connected, load initial data from the database and prepare for use * @return {Promise} Resolves on success */ _init: function _init() { var _this2 = this; return Promise.all([this._loadAccountData(), this._loadSyncData()]).then(function (_ref) { var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), accountData = _ref2[0], syncData = _ref2[1]; _logger.logger.log("LocalIndexedDBStoreBackend: loaded initial data"); _this2._syncAccumulator.accumulate({ next_batch: syncData.nextBatch, rooms: syncData.roomsData, groups: syncData.groupsData, account_data: { events: accountData } }); }); }, /** * Returns the out-of-band membership events for this room that * were previously loaded. * @param {string} roomId * @returns {Promise} the events, potentially an empty array if OOB loading didn't yield any new members * @returns {null} in case the members for this room haven't been stored yet */ getOutOfBandMembers: function getOutOfBandMembers(roomId) { var _this3 = this; return new Promise(function (resolve, reject) { var tx = _this3.db.transaction(["oob_membership_events"], "readonly"); var store = tx.objectStore("oob_membership_events"); var roomIndex = store.index("room"); var range = IDBKeyRange.only(roomId); var request = roomIndex.openCursor(range); var membershipEvents = []; // did we encounter the oob_written marker object // amongst the results? That means OOB member // loading already happened for this room // but there were no members to persist as they // were all known already var oobWritten = false; request.onsuccess = function (event) { var cursor = event.target.result; if (!cursor) { // Unknown room if (!membershipEvents.length && !oobWritten) { return resolve(null); } return resolve(membershipEvents); } var record = cursor.value; if (record.oob_written) { oobWritten = true; } else { membershipEvents.push(record); } cursor["continue"](); }; request.onerror = function (err) { reject(err); }; }).then(function (events) { _logger.logger.log("LL: got ".concat(events && events.length) + " membershipEvents from storage for room ".concat(roomId, " ...")); return events; }); }, /** * Stores the out-of-band membership events for this room. Note that * it still makes sense to store an empty array as the OOB status for the room is * marked as fetched, and getOutOfBandMembers will return an empty array instead of null * @param {string} roomId * @param {event[]} membershipEvents the membership events to store */ setOutOfBandMembers: function () { var _setOutOfBandMembers = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(roomId, membershipEvents) { var tx, store, markerObject; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _logger.logger.log("LL: backend about to store ".concat(membershipEvents.length) + " members for ".concat(roomId)); tx = this.db.transaction(["oob_membership_events"], "readwrite"); store = tx.objectStore("oob_membership_events"); membershipEvents.forEach(function (e) { store.put(e); }); // aside from all the events, we also write a marker object to the store // to mark the fact that OOB members have been written for this room. // It's possible that 0 members need to be written as all where previously know // but we still need to know whether to return null or [] from getOutOfBandMembers // where null means out of band members haven't been stored yet for this room markerObject = { room_id: roomId, oob_written: true, state_key: 0 }; store.put(markerObject); _context.next = 8; return txnAsPromise(tx); case 8: _logger.logger.log("LL: backend done storing for ".concat(roomId, "!")); case 9: case "end": return _context.stop(); } } }, _callee, this); })); function setOutOfBandMembers(_x, _x2) { return _setOutOfBandMembers.apply(this, arguments); } return setOutOfBandMembers; }(), clearOutOfBandMembers: function () { var _clearOutOfBandMembers = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(roomId) { var readTx, store, roomIndex, roomRange, minStateKeyProm, maxStateKeyProm, _yield$Promise$all, _yield$Promise$all2, minStateKey, maxStateKey, writeTx, writeStore, membersKeyRange; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // the approach to delete all members for a room // is to get the min and max state key from the index // for that room, and then delete between those // keys in the store. // this should be way faster than deleting every member // individually for a large room. readTx = this.db.transaction(["oob_membership_events"], "readonly"); store = readTx.objectStore("oob_membership_events"); roomIndex = store.index("room"); roomRange = IDBKeyRange.only(roomId); minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, "next")).then(function (cursor) { return cursor && cursor.primaryKey[1]; }); maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, "prev")).then(function (cursor) { return cursor && cursor.primaryKey[1]; }); _context2.next = 8; return Promise.all([minStateKeyProm, maxStateKeyProm]); case 8: _yield$Promise$all = _context2.sent; _yield$Promise$all2 = (0, _slicedToArray2["default"])(_yield$Promise$all, 2); minStateKey = _yield$Promise$all2[0]; maxStateKey = _yield$Promise$all2[1]; writeTx = this.db.transaction(["oob_membership_events"], "readwrite"); writeStore = writeTx.objectStore("oob_membership_events"); membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]); _logger.logger.log("LL: Deleting all users + marker in storage for " + "room ".concat(roomId, ", with key range:"), [roomId, minStateKey], [roomId, maxStateKey]); _context2.next = 18; return reqAsPromise(writeStore["delete"](membersKeyRange)); case 18: case "end": return _context2.stop(); } } }, _callee2, this); })); function clearOutOfBandMembers(_x3) { return _clearOutOfBandMembers.apply(this, arguments); } return clearOutOfBandMembers; }(), /** * Clear the entire database. This should be used when logging out of a client * to prevent mixing data between accounts. * @return {Promise} Resolved when the database is cleared. */ clearDatabase: function clearDatabase() { var _this4 = this; return new Promise(function (resolve, reject) { _logger.logger.log("Removing indexeddb instance: ".concat(_this4._dbName)); var req = _this4.indexedDB.deleteDatabase(_this4._dbName); req.onblocked = function () { _logger.logger.log("can't yet delete indexeddb ".concat(_this4._dbName) + " because it is open elsewhere"); }; req.onerror = function (ev) { // in firefox, with indexedDB disabled, this fails with a // DOMError. We treat this as non-fatal, so that we can still // use the app. _logger.logger.warn("unable to delete js-sdk store indexeddb: ".concat(ev.target.error)); resolve(); }; req.onsuccess = function () { _logger.logger.log("Removed indexeddb instance: ".concat(_this4._dbName)); resolve(); }; }); }, /** * @param {boolean=} copy If false, the data returned is from internal * buffers and must not be mutated. Otherwise, a copy is made before * returning such that the data can be safely mutated. Default: true. * * @return {Promise} Resolves with a sync response to restore the * client state to where it was at the last save, or null if there * is no saved sync data. */ getSavedSync: function getSavedSync(copy) { if (copy === undefined) copy = true; var data = this._syncAccumulator.getJSON(); if (!data.nextBatch) return Promise.resolve(null); if (copy) { // We must deep copy the stored data so that the /sync processing code doesn't // corrupt the internal state of the sync accumulator (it adds non-clonable keys) return Promise.resolve(utils.deepCopy(data)); } else { return Promise.resolve(data); } }, getNextBatchToken: function getNextBatchToken() { return Promise.resolve(this._syncAccumulator.getNextBatchToken()); }, setSyncData: function setSyncData(syncData) { var _this5 = this; return Promise.resolve().then(function () { _this5._syncAccumulator.accumulate(syncData); }); }, syncToDatabase: function syncToDatabase(userTuples) { var syncData = this._syncAccumulator.getJSON(); return Promise.all([this._persistUserPresenceEvents(userTuples), this._persistAccountData(syncData.accountData), this._persistSyncData(syncData.nextBatch, syncData.roomsData, syncData.groupsData)]); }, /** * Persist rooms /sync data along with the next batch token. * @param {string} nextBatch The next_batch /sync value. * @param {Object} roomsData The 'rooms' /sync data from a SyncAccumulator * @param {Object} groupsData The 'groups' /sync data from a SyncAccumulator * @return {Promise} Resolves if the data was persisted. */ _persistSyncData: function _persistSyncData(nextBatch, roomsData, groupsData) { var _this6 = this; _logger.logger.log("Persisting sync data up to ", nextBatch); return utils.promiseTry(function () { var txn = _this6.db.transaction(["sync"], "readwrite"); var store = txn.objectStore("sync"); store.put({ clobber: "-", // constant key so will always clobber nextBatch: nextBatch, roomsData: roomsData, groupsData: groupsData }); // put == UPSERT return txnAsPromise(txn); }); }, /** * Persist a list of account data events. Events with the same 'type' will * be replaced. * @param {Object[]} accountData An array of raw user-scoped account data events * @return {Promise} Resolves if the events were persisted. */ _persistAccountData: function _persistAccountData(accountData) { var _this7 = this; return utils.promiseTry(function () { var txn = _this7.db.transaction(["accountData"], "readwrite"); var store = txn.objectStore("accountData"); for (var i = 0; i < accountData.length; i++) { store.put(accountData[i]); // put == UPSERT } return txnAsPromise(txn); }); }, /** * Persist a list of [user id, presence event] they are for. * Users with the same 'userId' will be replaced. * Presence events should be the event in its raw form (not the Event * object) * @param {Object[]} tuples An array of [userid, event] tuples * @return {Promise} Resolves if the users were persisted. */ _persistUserPresenceEvents: function _persistUserPresenceEvents(tuples) { var _this8 = this; return utils.promiseTry(function () { var txn = _this8.db.transaction(["users"], "readwrite"); var store = txn.objectStore("users"); var _iterator = _createForOfIteratorHelper(tuples), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var tuple = _step.value; store.put({ userId: tuple[0], event: tuple[1] }); // put == UPSERT } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return txnAsPromise(txn); }); }, /** * Load all user presence events from the database. This is not cached. * FIXME: It would probably be more sensible to store the events in the * sync. * @return {Promise} A list of presence events in their raw form. */ getUserPresenceEvents: function getUserPresenceEvents() { var _this9 = this; return utils.promiseTry(function () { var txn = _this9.db.transaction(["users"], "readonly"); var store = txn.objectStore("users"); return selectQuery(store, undefined, function (cursor) { return [cursor.value.userId, cursor.value.event]; }); }); }, /** * Load all the account data events from the database. This is not cached. * @return {Promise} A list of raw global account events. */ _loadAccountData: function _loadAccountData() { var _this10 = this; _logger.logger.log("LocalIndexedDBStoreBackend: loading account data..."); return utils.promiseTry(function () { var txn = _this10.db.transaction(["accountData"], "readonly"); var store = txn.objectStore("accountData"); return selectQuery(store, undefined, function (cursor) { return cursor.value; }).then(function (result) { _logger.logger.log("LocalIndexedDBStoreBackend: loaded account data"); return result; }); }); }, /** * Load the sync data from the database. * @return {Promise} An object with "roomsData" and "nextBatch" keys. */ _loadSyncData: function _loadSyncData() { var _this11 = this; _logger.logger.log("LocalIndexedDBStoreBackend: loading sync data..."); return utils.promiseTry(function () { var txn = _this11.db.transaction(["sync"], "readonly"); var store = txn.objectStore("sync"); return selectQuery(store, undefined, function (cursor) { return cursor.value; }).then(function (results) { _logger.logger.log("LocalIndexedDBStoreBackend: loaded sync data"); if (results.length > 1) { _logger.logger.warn("loadSyncData: More than 1 sync row found."); } return results.length > 0 ? results[0] : {}; }); }); }, getClientOptions: function getClientOptions() { var _this12 = this; return Promise.resolve().then(function () { var txn = _this12.db.transaction(["client_options"], "readonly"); var store = txn.objectStore("client_options"); return selectQuery(store, undefined, function (cursor) { if (cursor.value && cursor.value && cursor.value.options) { return cursor.value.options; } }).then(function (results) { return results[0]; }); }); }, storeClientOptions: function () { var _storeClientOptions = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(options) { var txn, store; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: txn = this.db.transaction(["client_options"], "readwrite"); store = txn.objectStore("client_options"); store.put({ clobber: "-", // constant key so will always clobber options: options }); // put == UPSERT _context3.next = 5; return txnAsPromise(txn); case 5: case "end": return _context3.stop(); } } }, _callee3, this); })); function storeClientOptions(_x4) { return _storeClientOptions.apply(this, arguments); } return storeClientOptions; }() }; },{"../indexeddb-helpers":93,"../logger":95,"../sync-accumulator":120,"../utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27}],115:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RemoteIndexedDBStoreBackend = RemoteIndexedDBStoreBackend; var _logger = require("../logger"); var _utils = require("../utils"); /* Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * An IndexedDB store backend where the actual backend sits in a web * worker. * * Construct a new Indexed Database store backend. This requires a call to * connect() before this store can be used. * @constructor * @param {string} workerScript URL to the worker script * @param {string=} dbName Optional database name. The same name must be used * to open the same database. * @param {Object} workerApi The web worker compatible interface object */ function RemoteIndexedDBStoreBackend(workerScript, dbName, workerApi) { this._workerScript = workerScript; this._dbName = dbName; this._workerApi = workerApi; this._worker = null; this._nextSeq = 0; // The currently in-flight requests to the actual backend this._inFlight = {// seq: promise, }; // Once we start connecting, we keep the promise and re-use it // if we try to connect again this._startPromise = null; } RemoteIndexedDBStoreBackend.prototype = { /** * Attempt to connect to the database. This can fail if the user does not * grant permission. * @return {Promise} Resolves if successfully connected. */ connect: function connect() { var _this = this; return this._ensureStarted().then(function () { return _this._doCmd('connect'); }); }, /** * Clear the entire database. This should be used when logging out of a client * to prevent mixing data between accounts. * @return {Promise} Resolved when the database is cleared. */ clearDatabase: function clearDatabase() { var _this2 = this; return this._ensureStarted().then(function () { return _this2._doCmd('clearDatabase'); }); }, /** @return {Promise} whether or not the database was newly created in this session. */ isNewlyCreated: function isNewlyCreated() { return this._doCmd('isNewlyCreated'); }, /** * @return {Promise} Resolves with a sync response to restore the * client state to where it was at the last save, or null if there * is no saved sync data. */ getSavedSync: function getSavedSync() { return this._doCmd('getSavedSync'); }, getNextBatchToken: function getNextBatchToken() { return this._doCmd('getNextBatchToken'); }, setSyncData: function setSyncData(syncData) { return this._doCmd('setSyncData', [syncData]); }, syncToDatabase: function syncToDatabase(users) { return this._doCmd('syncToDatabase', [users]); }, /** * Returns the out-of-band membership events for this room that * were previously loaded. * @param {string} roomId * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members * @returns {null} in case the members for this room haven't been stored yet */ getOutOfBandMembers: function getOutOfBandMembers(roomId) { return this._doCmd('getOutOfBandMembers', [roomId]); }, /** * Stores the out-of-band membership events for this room. Note that * it still makes sense to store an empty array as the OOB status for the room is * marked as fetched, and getOutOfBandMembers will return an empty array instead of null * @param {string} roomId * @param {event[]} membershipEvents the membership events to store * @returns {Promise} when all members have been stored */ setOutOfBandMembers: function setOutOfBandMembers(roomId, membershipEvents) { return this._doCmd('setOutOfBandMembers', [roomId, membershipEvents]); }, clearOutOfBandMembers: function clearOutOfBandMembers(roomId) { return this._doCmd('clearOutOfBandMembers', [roomId]); }, getClientOptions: function getClientOptions() { return this._doCmd('getClientOptions'); }, storeClientOptions: function storeClientOptions(options) { return this._doCmd('storeClientOptions', [options]); }, /** * Load all user presence events from the database. This is not cached. * @return {Promise} A list of presence events in their raw form. */ getUserPresenceEvents: function getUserPresenceEvents() { return this._doCmd('getUserPresenceEvents'); }, _ensureStarted: function _ensureStarted() { if (this._startPromise === null) { this._worker = new this._workerApi(this._workerScript); this._worker.onmessage = this._onWorkerMessage.bind(this); // tell the worker the db name. this._startPromise = this._doCmd('_setupWorker', [this._dbName]).then(function () { _logger.logger.log("IndexedDB worker is ready"); }); } return this._startPromise; }, _doCmd: function _doCmd(cmd, args) { var _this3 = this; // wrap in a q so if the postMessage throws, // the promise automatically gets rejected return Promise.resolve().then(function () { var seq = _this3._nextSeq++; var def = (0, _utils.defer)(); _this3._inFlight[seq] = def; _this3._worker.postMessage({ command: cmd, seq: seq, args: args }); return def.promise; }); }, _onWorkerMessage: function _onWorkerMessage(ev) { var msg = ev.data; if (msg.command == 'cmd_success' || msg.command == 'cmd_fail') { if (msg.seq === undefined) { _logger.logger.error("Got reply from worker with no seq"); return; } var def = this._inFlight[msg.seq]; if (def === undefined) { _logger.logger.error("Got reply for unknown seq " + msg.seq); return; } delete this._inFlight[msg.seq]; if (msg.command == 'cmd_success') { def.resolve(msg.result); } else { var error = new Error(msg.error.message); error.name = msg.error.name; def.reject(error); } } else { _logger.logger.warn("Unrecognised message from worker: " + msg); } } }; },{"../logger":95,"../utils":123}],116:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.IndexedDBStore = IndexedDBStore; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _memory = require("./memory"); var utils = _interopRequireWildcard(require("../utils")); var _events = require("events"); var _indexeddbLocalBackend = require("./indexeddb-local-backend.js"); var _indexeddbRemoteBackend = require("./indexeddb-remote-backend.js"); var _user = require("../models/user"); var _event = require("../models/event"); var _logger = require("../logger"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * This is an internal module. See {@link IndexedDBStore} for the public class. * @module store/indexeddb */ // If this value is too small we'll be writing very often which will cause // noticable stop-the-world pauses. If this value is too big we'll be writing // so infrequently that the /sync size gets bigger on reload. Writing more // often does not affect the length of the pause since the entire /sync // response is persisted each time. var WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes /** * Construct a new Indexed Database store, which extends MemoryStore. * * This store functions like a MemoryStore except it periodically persists * the contents of the store to an IndexedDB backend. * * All data is still kept in-memory but can be loaded from disk by calling * startup(). This can make startup times quicker as a complete * sync from the server is not required. This does not reduce memory usage as all * the data is eagerly fetched when startup() is called. *
 * let opts = { localStorage: window.localStorage };
 * let store = new IndexedDBStore();
 * await store.startup(); // load from indexed db
 * let client = sdk.createClient({
 *     store: store,
 * });
 * client.startClient();
 * client.on("sync", function(state, prevState, data) {
 *     if (state === "PREPARED") {
 *         console.log("Started up, now with go faster stripes!");
 *     }
 * });
 * 
* * @constructor * @extends MemoryStore * @param {Object} opts Options object. * @param {Object} opts.indexedDB The Indexed DB interface e.g. * window.indexedDB * @param {string=} opts.dbName Optional database name. The same name must be used * to open the same database. * @param {string=} opts.workerScript Optional URL to a script to invoke a web * worker with to run IndexedDB queries on the web worker. The IndexedDbStoreWorker * class is provided for this purpose and requires the application to provide a * trivial wrapper script around it. * @param {Object=} opts.workerApi The webWorker API object. If omitted, the global Worker * object will be used if it exists. * @prop {IndexedDBStoreBackend} backend The backend instance. Call through to * this API if you need to perform specific indexeddb actions like deleting the * database. */ function IndexedDBStore(opts) { _memory.MemoryStore.call(this, opts); if (!opts.indexedDB) { throw new Error('Missing required option: indexedDB'); } if (opts.workerScript) { // try & find a webworker-compatible API var workerApi = opts.workerApi; if (!workerApi) { // default to the global Worker object (which is where it in a browser) workerApi = global.Worker; } this.backend = new _indexeddbRemoteBackend.RemoteIndexedDBStoreBackend(opts.workerScript, opts.dbName, workerApi); } else { this.backend = new _indexeddbLocalBackend.LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName); } this.startedUp = false; this._syncTs = 0; // Records the last-modified-time of each user at the last point we saved // the database, such that we can derive the set if users that have been // modified since we last saved. this._userModifiedMap = {// user_id : timestamp }; } utils.inherits(IndexedDBStore, _memory.MemoryStore); utils.extend(IndexedDBStore.prototype, _events.EventEmitter.prototype); IndexedDBStore.exists = function (indexedDB, dbName) { return _indexeddbLocalBackend.LocalIndexedDBStoreBackend.exists(indexedDB, dbName); }; /** * @return {Promise} Resolved when loaded from indexed db. */ IndexedDBStore.prototype.startup = function () { var _this = this; if (this.startedUp) { _logger.logger.log("IndexedDBStore.startup: already started"); return Promise.resolve(); } _logger.logger.log("IndexedDBStore.startup: connecting to backend"); return this.backend.connect().then(function () { _logger.logger.log("IndexedDBStore.startup: loading presence events"); return _this.backend.getUserPresenceEvents(); }).then(function (userPresenceEvents) { _logger.logger.log("IndexedDBStore.startup: processing presence events"); userPresenceEvents.forEach(function (_ref) { var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), userId = _ref2[0], rawEvent = _ref2[1]; var u = new _user.User(userId); if (rawEvent) { u.setPresenceEvent(new _event.MatrixEvent(rawEvent)); } _this._userModifiedMap[u.userId] = u.getLastModifiedTime(); _this.storeUser(u); }); }); }; /** * @return {Promise} Resolves with a sync response to restore the * client state to where it was at the last save, or null if there * is no saved sync data. */ IndexedDBStore.prototype.getSavedSync = degradable(function () { return this.backend.getSavedSync(); }, "getSavedSync"); /** @return {Promise} whether or not the database was newly created in this session. */ IndexedDBStore.prototype.isNewlyCreated = degradable(function () { return this.backend.isNewlyCreated(); }, "isNewlyCreated"); /** * @return {Promise} If there is a saved sync, the nextBatch token * for this sync, otherwise null. */ IndexedDBStore.prototype.getSavedSyncToken = degradable(function () { return this.backend.getNextBatchToken(); }, "getSavedSyncToken"), /** * Delete all data from this store. * @return {Promise} Resolves if the data was deleted from the database. */ IndexedDBStore.prototype.deleteAllData = degradable(function () { _memory.MemoryStore.prototype.deleteAllData.call(this); return this.backend.clearDatabase().then(function () { _logger.logger.log("Deleted indexeddb data."); }, function (err) { _logger.logger.error("Failed to delete indexeddb data: ".concat(err)); throw err; }); }); /** * Whether this store would like to save its data * Note that obviously whether the store wants to save or * not could change between calling this function and calling * save(). * * @return {boolean} True if calling save() will actually save * (at the time this function is called). */ IndexedDBStore.prototype.wantsSave = function () { var now = Date.now(); return now - this._syncTs > WRITE_DELAY_MS; }; /** * Possibly write data to the database. * * @param {bool} force True to force a save to happen * @return {Promise} Promise resolves after the write completes * (or immediately if no write is performed) */ IndexedDBStore.prototype.save = function (force) { if (force || this.wantsSave()) { return this._reallySave(); } return Promise.resolve(); }; IndexedDBStore.prototype._reallySave = degradable(function () { this._syncTs = Date.now(); // set now to guard against multi-writes // work out changed users (this doesn't handle deletions but you // can't 'delete' users as they are just presence events). var userTuples = []; var _iterator = _createForOfIteratorHelper(this.getUsers()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var u = _step.value; if (this._userModifiedMap[u.userId] === u.getLastModifiedTime()) continue; if (!u.events.presence) continue; userTuples.push([u.userId, u.events.presence.event]); // note that we've saved this version of the user this._userModifiedMap[u.userId] = u.getLastModifiedTime(); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return this.backend.syncToDatabase(userTuples); }); IndexedDBStore.prototype.setSyncData = degradable(function (syncData) { return this.backend.setSyncData(syncData); }, "setSyncData"); /** * Returns the out-of-band membership events for this room that * were previously loaded. * @param {string} roomId * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members * @returns {null} in case the members for this room haven't been stored yet */ IndexedDBStore.prototype.getOutOfBandMembers = degradable(function (roomId) { return this.backend.getOutOfBandMembers(roomId); }, "getOutOfBandMembers"); /** * Stores the out-of-band membership events for this room. Note that * it still makes sense to store an empty array as the OOB status for the room is * marked as fetched, and getOutOfBandMembers will return an empty array instead of null * @param {string} roomId * @param {event[]} membershipEvents the membership events to store * @returns {Promise} when all members have been stored */ IndexedDBStore.prototype.setOutOfBandMembers = degradable(function (roomId, membershipEvents) { _memory.MemoryStore.prototype.setOutOfBandMembers.call(this, roomId, membershipEvents); return this.backend.setOutOfBandMembers(roomId, membershipEvents); }, "setOutOfBandMembers"); IndexedDBStore.prototype.clearOutOfBandMembers = degradable(function (roomId) { _memory.MemoryStore.prototype.clearOutOfBandMembers.call(this); return this.backend.clearOutOfBandMembers(roomId); }, "clearOutOfBandMembers"); IndexedDBStore.prototype.getClientOptions = degradable(function () { return this.backend.getClientOptions(); }, "getClientOptions"); IndexedDBStore.prototype.storeClientOptions = degradable(function (options) { _memory.MemoryStore.prototype.storeClientOptions.call(this, options); return this.backend.storeClientOptions(options); }, "storeClientOptions"); /** * All member functions of `IndexedDBStore` that access the backend use this wrapper to * watch for failures after initial store startup, including `QuotaExceededError` as * free disk space changes, etc. * * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore` * in place so that the current operation and all future ones are in-memory only. * * @param {Function} func The degradable work to do. * @param {String} fallback The method name for fallback. * @returns {Function} A wrapped member function. */ function degradable(func, fallback) { return /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var _len, args, _key, _MemoryStore$prototyp, _args = arguments; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = _args[_key]; } _context.prev = 1; _context.next = 4; return func.call.apply(func, [this].concat(args)); case 4: return _context.abrupt("return", _context.sent); case 7: _context.prev = 7; _context.t0 = _context["catch"](1); _logger.logger.error("IndexedDBStore failure, degrading to MemoryStore", _context.t0); this.emit("degraded", _context.t0); _context.prev = 11; // We try to delete IndexedDB after degrading since this store is only a // cache (the app will still function correctly without the data). // It's possible that deleting repair IndexedDB for the next app load, // potenially by making a little more space available. _logger.logger.log("IndexedDBStore trying to delete degraded data"); _context.next = 15; return this.backend.clearDatabase(); case 15: _logger.logger.log("IndexedDBStore delete after degrading succeeeded"); _context.next = 21; break; case 18: _context.prev = 18; _context.t1 = _context["catch"](11); _logger.logger.warn("IndexedDBStore delete after degrading failed", _context.t1); case 21: // Degrade the store from being an instance of `IndexedDBStore` to instead be // an instance of `MemoryStore` so that future API calls use the memory path // directly and skip IndexedDB entirely. This should be safe as // `IndexedDBStore` already extends from `MemoryStore`, so we are making the // store become its parent type in a way. The mutator methods of // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are // not overridden at all). Object.setPrototypeOf(this, _memory.MemoryStore.prototype); if (!fallback) { _context.next = 26; break; } _context.next = 25; return (_MemoryStore$prototyp = _memory.MemoryStore.prototype[fallback]).call.apply(_MemoryStore$prototyp, [this].concat(args)); case 25: return _context.abrupt("return", _context.sent); case 26: case "end": return _context.stop(); } } }, _callee, this, [[1, 7], [11, 18]]); })); } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../logger":95,"../models/event":100,"../models/user":108,"../utils":123,"./indexeddb-local-backend.js":114,"./indexeddb-remote-backend.js":115,"./memory":117,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/helpers/slicedToArray":22,"@babel/runtime/regenerator":27,"events":36}],117:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MemoryStore = MemoryStore; var _user = require("../models/user"); var utils = _interopRequireWildcard(require("../utils")); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * This is an internal module. See {@link MemoryStore} for the public class. * @module store/memory */ function isValidFilterId(filterId) { var isValidStr = typeof filterId === "string" && !!filterId && filterId !== "undefined" && // exclude these as we've serialized undefined in localStorage before filterId !== "null"; return isValidStr || typeof filterId === "number"; } /** * Construct a new in-memory data store for the Matrix Client. * @constructor * @param {Object=} opts Config options * @param {LocalStorage} opts.localStorage The local storage instance to persist * some forms of data such as tokens. Rooms will NOT be stored. */ function MemoryStore(opts) { opts = opts || {}; this.rooms = {// roomId: Room }; this.groups = {// groupId: Group }; this.users = {// userId: User }; this.syncToken = null; this.filters = {// userId: { // filterId: Filter // } }; this.accountData = {// type : content }; this.localStorage = opts.localStorage; this._oobMembers = {// roomId: [member events] }; this._clientOptions = {}; } MemoryStore.prototype = { /** * Retrieve the token to stream from. * @return {string} The token or null. */ getSyncToken: function getSyncToken() { return this.syncToken; }, /** @return {Promise} whether or not the database was newly created in this session. */ isNewlyCreated: function isNewlyCreated() { return Promise.resolve(true); }, /** * Set the token to stream from. * @param {string} token The token to stream from. */ setSyncToken: function setSyncToken(token) { this.syncToken = token; }, /** * Store the given room. * @param {Group} group The group to be stored */ storeGroup: function storeGroup(group) { this.groups[group.groupId] = group; }, /** * Retrieve a group by its group ID. * @param {string} groupId The group ID. * @return {Group} The group or null. */ getGroup: function getGroup(groupId) { return this.groups[groupId] || null; }, /** * Retrieve all known groups. * @return {Group[]} A list of groups, which may be empty. */ getGroups: function getGroups() { return utils.values(this.groups); }, /** * Store the given room. * @param {Room} room The room to be stored. All properties must be stored. */ storeRoom: function storeRoom(room) { this.rooms[room.roomId] = room; // add listeners for room member changes so we can keep the room member // map up-to-date. room.currentState.on("RoomState.members", this._onRoomMember.bind(this)); // add existing members var self = this; room.currentState.getMembers().forEach(function (m) { self._onRoomMember(null, room.currentState, m); }); }, /** * Called when a room member in a room being tracked by this store has been * updated. * @param {MatrixEvent} event * @param {RoomState} state * @param {RoomMember} member */ _onRoomMember: function _onRoomMember(event, state, member) { if (member.membership === "invite") { // We do NOT add invited members because people love to typo user IDs // which would then show up in these lists (!) return; } var user = this.users[member.userId] || new _user.User(member.userId); if (member.name) { user.setDisplayName(member.name); if (member.events.member) { user.setRawDisplayName(member.events.member.getDirectionalContent().displayname); } } if (member.events.member && member.events.member.getContent().avatar_url) { user.setAvatarUrl(member.events.member.getContent().avatar_url); } this.users[user.userId] = user; }, /** * Retrieve a room by its' room ID. * @param {string} roomId The room ID. * @return {Room} The room or null. */ getRoom: function getRoom(roomId) { return this.rooms[roomId] || null; }, /** * Retrieve all known rooms. * @return {Room[]} A list of rooms, which may be empty. */ getRooms: function getRooms() { return utils.values(this.rooms); }, /** * Permanently delete a room. * @param {string} roomId */ removeRoom: function removeRoom(roomId) { if (this.rooms[roomId]) { this.rooms[roomId].removeListener("RoomState.members", this._onRoomMember); } delete this.rooms[roomId]; }, /** * Retrieve a summary of all the rooms. * @return {RoomSummary[]} A summary of each room. */ getRoomSummaries: function getRoomSummaries() { return utils.map(utils.values(this.rooms), function (room) { return room.summary; }); }, /** * Store a User. * @param {User} user The user to store. */ storeUser: function storeUser(user) { this.users[user.userId] = user; }, /** * Retrieve a User by its' user ID. * @param {string} userId The user ID. * @return {User} The user or null. */ getUser: function getUser(userId) { return this.users[userId] || null; }, /** * Retrieve all known users. * @return {User[]} A list of users, which may be empty. */ getUsers: function getUsers() { return utils.values(this.users); }, /** * Retrieve scrollback for this room. * @param {Room} room The matrix room * @param {integer} limit The max number of old events to retrieve. * @return {Array} An array of objects which will be at most 'limit' * length and at least 0. The objects are the raw event JSON. */ scrollback: function scrollback(room, limit) { return []; }, /** * Store events for a room. The events have already been added to the timeline * @param {Room} room The room to store events for. * @param {Array} events The events to store. * @param {string} token The token associated with these events. * @param {boolean} toStart True if these are paginated results. */ storeEvents: function storeEvents(room, events, token, toStart) {// no-op because they've already been added to the room instance. }, /** * Store a filter. * @param {Filter} filter */ storeFilter: function storeFilter(filter) { if (!filter) { return; } if (!this.filters[filter.userId]) { this.filters[filter.userId] = {}; } this.filters[filter.userId][filter.filterId] = filter; }, /** * Retrieve a filter. * @param {string} userId * @param {string} filterId * @return {?Filter} A filter or null. */ getFilter: function getFilter(userId, filterId) { if (!this.filters[userId] || !this.filters[userId][filterId]) { return null; } return this.filters[userId][filterId]; }, /** * Retrieve a filter ID with the given name. * @param {string} filterName The filter name. * @return {?string} The filter ID or null. */ getFilterIdByName: function getFilterIdByName(filterName) { if (!this.localStorage) { return null; } var key = "mxjssdk_memory_filter_" + filterName; // XXX Storage.getItem doesn't throw ... // or are we using something different // than window.localStorage in some cases // that does throw? // that would be very naughty try { var value = this.localStorage.getItem(key); if (isValidFilterId(value)) { return value; } } catch (e) {} return null; }, /** * Set a filter name to ID mapping. * @param {string} filterName * @param {string} filterId */ setFilterIdByName: function setFilterIdByName(filterName, filterId) { if (!this.localStorage) { return; } var key = "mxjssdk_memory_filter_" + filterName; try { if (isValidFilterId(filterId)) { this.localStorage.setItem(key, filterId); } else { this.localStorage.removeItem(key); } } catch (e) {} }, /** * Store user-scoped account data events. * N.B. that account data only allows a single event per type, so multiple * events with the same type will replace each other. * @param {Array} events The events to store. */ storeAccountDataEvents: function storeAccountDataEvents(events) { var self = this; events.forEach(function (event) { self.accountData[event.getType()] = event; }); }, /** * Get account data event by event type * @param {string} eventType The event type being queried * @return {?MatrixEvent} the user account_data event of given type, if any */ getAccountData: function getAccountData(eventType) { return this.accountData[eventType]; }, /** * setSyncData does nothing as there is no backing data store. * * @param {Object} syncData The sync data * @return {Promise} An immediately resolved promise. */ setSyncData: function setSyncData(syncData) { return Promise.resolve(); }, /** * We never want to save becase we have nothing to save to. * * @return {boolean} If the store wants to save */ wantsSave: function wantsSave() { return false; }, /** * Save does nothing as there is no backing data store. * @param {bool} force True to force a save (but the memory * store still can't save anything) */ save: function save(force) {}, /** * Startup does nothing as this store doesn't require starting up. * @return {Promise} An immediately resolved promise. */ startup: function startup() { return Promise.resolve(); }, /** * @return {Promise} Resolves with a sync response to restore the * client state to where it was at the last save, or null if there * is no saved sync data. */ getSavedSync: function getSavedSync() { return Promise.resolve(null); }, /** * @return {Promise} If there is a saved sync, the nextBatch token * for this sync, otherwise null. */ getSavedSyncToken: function getSavedSyncToken() { return Promise.resolve(null); }, /** * Delete all data from this store. * @return {Promise} An immediately resolved promise. */ deleteAllData: function deleteAllData() { this.rooms = {// roomId: Room }; this.users = {// userId: User }; this.syncToken = null; this.filters = {// userId: { // filterId: Filter // } }; this.accountData = {// type : content }; return Promise.resolve(); }, /** * Returns the out-of-band membership events for this room that * were previously loaded. * @param {string} roomId * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members * @returns {null} in case the members for this room haven't been stored yet */ getOutOfBandMembers: function getOutOfBandMembers(roomId) { return Promise.resolve(this._oobMembers[roomId] || null); }, /** * Stores the out-of-band membership events for this room. Note that * it still makes sense to store an empty array as the OOB status for the room is * marked as fetched, and getOutOfBandMembers will return an empty array instead of null * @param {string} roomId * @param {event[]} membershipEvents the membership events to store * @returns {Promise} when all members have been stored */ setOutOfBandMembers: function setOutOfBandMembers(roomId, membershipEvents) { this._oobMembers[roomId] = membershipEvents; return Promise.resolve(); }, clearOutOfBandMembers: function clearOutOfBandMembers() { this._oobMembers = {}; return Promise.resolve(); }, getClientOptions: function getClientOptions() { return Promise.resolve(this._clientOptions); }, storeClientOptions: function storeClientOptions(options) { this._clientOptions = Object.assign({}, options); return Promise.resolve(); } }; },{"../models/user":108,"../utils":123,"@babel/runtime/helpers/interopRequireWildcard":13}],118:[function(require,module,exports){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.WebStorageSessionStore = WebStorageSessionStore; var utils = _interopRequireWildcard(require("../../utils")); var _logger = require("../../logger"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var DEBUG = false; // set true to enable console logging. var E2E_PREFIX = "session.e2e."; /** * Construct a web storage session store, capable of storing account keys, * session keys and access tokens. * @constructor * @param {WebStorage} webStore A web storage implementation, e.g. * 'window.localStorage' or 'window.sessionStorage' or a custom implementation. * @throws if the supplied 'store' does not meet the Storage interface of the * WebStorage API. */ function WebStorageSessionStore(webStore) { this.store = webStore; if (!utils.isFunction(webStore.getItem) || !utils.isFunction(webStore.setItem) || !utils.isFunction(webStore.removeItem) || !utils.isFunction(webStore.key) || typeof webStore.length !== 'number') { throw new Error("Supplied webStore does not meet the WebStorage API interface"); } } WebStorageSessionStore.prototype = { /** * Remove the stored end to end account for the logged-in user. */ removeEndToEndAccount: function removeEndToEndAccount() { this.store.removeItem(KEY_END_TO_END_ACCOUNT); }, /** * Load the end to end account for the logged-in user. * Note that the end-to-end account is now stored in the * crypto store rather than here: this remains here so * old sessions can be migrated out of the session store. * @return {?string} Base64 encoded account. */ getEndToEndAccount: function getEndToEndAccount() { return this.store.getItem(KEY_END_TO_END_ACCOUNT); }, /** * Retrieves the known devices for all users. * @return {object} A map from user ID to map of device ID to keys for the device. */ getAllEndToEndDevices: function getAllEndToEndDevices() { var prefix = keyEndToEndDevicesForUser(''); var devices = {}; for (var i = 0; i < this.store.length; ++i) { var key = this.store.key(i); var userId = key.substr(prefix.length); if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key); } return devices; }, getEndToEndDeviceTrackingStatus: function getEndToEndDeviceTrackingStatus() { return getJsonItem(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS); }, /** * Get the sync token corresponding to the device list. * * @return {String?} token */ getEndToEndDeviceSyncToken: function getEndToEndDeviceSyncToken() { return getJsonItem(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN); }, /** * Removes all end to end device data from the store */ removeEndToEndDeviceData: function removeEndToEndDeviceData() { removeByPrefix(this.store, keyEndToEndDevicesForUser('')); removeByPrefix(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS); removeByPrefix(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN); }, /** * Retrieve the end-to-end sessions between the logged-in user and another * device. * @param {string} deviceKey The public key of the other device. * @return {object} A map from sessionId to Base64 end-to-end session. */ getEndToEndSessions: function getEndToEndSessions(deviceKey) { return getJsonItem(this.store, keyEndToEndSessions(deviceKey)); }, /** * Retrieve all end-to-end sessions between the logged-in user and other * devices. * @return {object} A map of {deviceKey -> {sessionId -> session pickle}} */ getAllEndToEndSessions: function getAllEndToEndSessions() { var deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions('')); var results = {}; var _iterator = _createForOfIteratorHelper(deviceKeys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var k = _step.value; var unprefixedKey = k.substr(keyEndToEndSessions('').length); results[unprefixedKey] = getJsonItem(this.store, k); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return results; }, /** * Remove all end-to-end sessions from the store * This is used after migrating sessions awat from the sessions store. */ removeAllEndToEndSessions: function removeAllEndToEndSessions() { removeByPrefix(this.store, keyEndToEndSessions('')); }, /** * Retrieve a list of all known inbound group sessions * * @return {{senderKey: string, sessionId: string}} */ getAllEndToEndInboundGroupSessionKeys: function getAllEndToEndInboundGroupSessionKeys() { var prefix = E2E_PREFIX + 'inboundgroupsessions/'; var result = []; for (var i = 0; i < this.store.length; i++) { var key = this.store.key(i); if (!key.startsWith(prefix)) { continue; } // we can't use split, as the components we are trying to split out // might themselves contain '/' characters. We rely on the // senderKey being a (32-byte) curve25519 key, base64-encoded // (hence 43 characters long). result.push({ senderKey: key.substr(prefix.length, 43), sessionId: key.substr(prefix.length + 44) }); } return result; }, getEndToEndInboundGroupSession: function getEndToEndInboundGroupSession(senderKey, sessionId) { var key = keyEndToEndInboundGroupSession(senderKey, sessionId); return this.store.getItem(key); }, removeAllEndToEndInboundGroupSessions: function removeAllEndToEndInboundGroupSessions() { removeByPrefix(this.store, E2E_PREFIX + 'inboundgroupsessions/'); }, /** * Get the end-to-end state for all rooms * @return {object} roomId -> object with the end-to-end info for the room. */ getAllEndToEndRooms: function getAllEndToEndRooms() { var roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom('')); var results = {}; var _iterator2 = _createForOfIteratorHelper(roomKeys), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var k = _step2.value; var unprefixedKey = k.substr(keyEndToEndRoom('').length); results[unprefixedKey] = getJsonItem(this.store, k); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return results; }, removeAllEndToEndRooms: function removeAllEndToEndRooms() { removeByPrefix(this.store, keyEndToEndRoom('')); }, setLocalTrustedBackupPubKey: function setLocalTrustedBackupPubKey(pubkey) { this.store.setItem(KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY, pubkey); }, // XXX: This store is deprecated really, but added this as a temporary // thing until cross-signing lands. getLocalTrustedBackupPubKey: function getLocalTrustedBackupPubKey() { return this.store.getItem(KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY); } }; var KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account"; var KEY_END_TO_END_DEVICE_SYNC_TOKEN = E2E_PREFIX + "device_sync_token"; var KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS = E2E_PREFIX + "device_tracking"; var KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY = E2E_PREFIX + "trusted_backup_pubkey"; function keyEndToEndDevicesForUser(userId) { return E2E_PREFIX + "devices/" + userId; } function keyEndToEndSessions(deviceKey) { return E2E_PREFIX + "sessions/" + deviceKey; } function keyEndToEndInboundGroupSession(senderKey, sessionId) { return E2E_PREFIX + "inboundgroupsessions/" + senderKey + "/" + sessionId; } function keyEndToEndRoom(roomId) { return E2E_PREFIX + "rooms/" + roomId; } function getJsonItem(store, key) { try { // if the key is absent, store.getItem() returns null, and // JSON.parse(null) === null, so this returns null. return JSON.parse(store.getItem(key)); } catch (e) { debuglog("Failed to get key %s: %s", key, e); debuglog(e.stack); } return null; } function getKeysWithPrefix(store, prefix) { var results = []; for (var i = 0; i < store.length; ++i) { var key = store.key(i); if (key.startsWith(prefix)) results.push(key); } return results; } function removeByPrefix(store, prefix) { var toRemove = []; for (var i = 0; i < store.length; ++i) { var key = store.key(i); if (key.startsWith(prefix)) toRemove.push(key); } for (var _i = 0, _toRemove = toRemove; _i < _toRemove.length; _i++) { var _key = _toRemove[_i]; store.removeItem(_key); } } function debuglog() { if (DEBUG) { _logger.logger.log.apply(_logger.logger, arguments); } } },{"../../logger":95,"../../utils":123,"@babel/runtime/helpers/interopRequireWildcard":13}],119:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.StubStore = StubStore; /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * This is an internal module. * @module store/stub */ /** * Construct a stub store. This does no-ops on most store methods. * @constructor */ function StubStore() { this.fromToken = null; } StubStore.prototype = { /** @return {Promise} whether or not the database was newly created in this session. */ isNewlyCreated: function isNewlyCreated() { return Promise.resolve(true); }, /** * Get the sync token. * @return {string} */ getSyncToken: function getSyncToken() { return this.fromToken; }, /** * Set the sync token. * @param {string} token */ setSyncToken: function setSyncToken(token) { this.fromToken = token; }, /** * No-op. * @param {Group} group */ storeGroup: function storeGroup(group) {}, /** * No-op. * @param {string} groupId * @return {null} */ getGroup: function getGroup(groupId) { return null; }, /** * No-op. * @return {Array} An empty array. */ getGroups: function getGroups() { return []; }, /** * No-op. * @param {Room} room */ storeRoom: function storeRoom(room) {}, /** * No-op. * @param {string} roomId * @return {null} */ getRoom: function getRoom(roomId) { return null; }, /** * No-op. * @return {Array} An empty array. */ getRooms: function getRooms() { return []; }, /** * Permanently delete a room. * @param {string} roomId */ removeRoom: function removeRoom(roomId) { return; }, /** * No-op. * @return {Array} An empty array. */ getRoomSummaries: function getRoomSummaries() { return []; }, /** * No-op. * @param {User} user */ storeUser: function storeUser(user) {}, /** * No-op. * @param {string} userId * @return {null} */ getUser: function getUser(userId) { return null; }, /** * No-op. * @return {User[]} */ getUsers: function getUsers() { return []; }, /** * No-op. * @param {Room} room * @param {integer} limit * @return {Array} */ scrollback: function scrollback(room, limit) { return []; }, /** * Store events for a room. * @param {Room} room The room to store events for. * @param {Array} events The events to store. * @param {string} token The token associated with these events. * @param {boolean} toStart True if these are paginated results. */ storeEvents: function storeEvents(room, events, token, toStart) {}, /** * Store a filter. * @param {Filter} filter */ storeFilter: function storeFilter(filter) {}, /** * Retrieve a filter. * @param {string} userId * @param {string} filterId * @return {?Filter} A filter or null. */ getFilter: function getFilter(userId, filterId) { return null; }, /** * Retrieve a filter ID with the given name. * @param {string} filterName The filter name. * @return {?string} The filter ID or null. */ getFilterIdByName: function getFilterIdByName(filterName) { return null; }, /** * Set a filter name to ID mapping. * @param {string} filterName * @param {string} filterId */ setFilterIdByName: function setFilterIdByName(filterName, filterId) {}, /** * Store user-scoped account data events * @param {Array} events The events to store. */ storeAccountDataEvents: function storeAccountDataEvents(events) {}, /** * Get account data event by event type * @param {string} eventType The event type being queried */ getAccountData: function getAccountData(eventType) {}, /** * setSyncData does nothing as there is no backing data store. * * @param {Object} syncData The sync data * @return {Promise} An immediately resolved promise. */ setSyncData: function setSyncData(syncData) { return Promise.resolve(); }, /** * We never want to save becase we have nothing to save to. * * @return {boolean} If the store wants to save */ wantsSave: function wantsSave() { return false; }, /** * Save does nothing as there is no backing data store. */ save: function save() {}, /** * Startup does nothing. * @return {Promise} An immediately resolved promise. */ startup: function startup() { return Promise.resolve(); }, /** * @return {Promise} Resolves with a sync response to restore the * client state to where it was at the last save, or null if there * is no saved sync data. */ getSavedSync: function getSavedSync() { return Promise.resolve(null); }, /** * @return {Promise} If there is a saved sync, the nextBatch token * for this sync, otherwise null. */ getSavedSyncToken: function getSavedSyncToken() { return Promise.resolve(null); }, /** * Delete all data from this store. Does nothing since this store * doesn't store anything. * @return {Promise} An immediately resolved promise. */ deleteAllData: function deleteAllData() { return Promise.resolve(); }, getOutOfBandMembers: function getOutOfBandMembers() { return Promise.resolve(null); }, setOutOfBandMembers: function setOutOfBandMembers() { return Promise.resolve(); }, clearOutOfBandMembers: function clearOutOfBandMembers() { return Promise.resolve(); }, getClientOptions: function getClientOptions() { return Promise.resolve(); }, storeClientOptions: function storeClientOptions() { return Promise.resolve(); } }; },{}],120:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SyncAccumulator = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _logger = require("./logger"); var _utils = require("./utils"); /* Copyright 2017 Vector Creations Ltd Copyright 2018 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * This is an internal module. See {@link SyncAccumulator} for the public class. * @module sync-accumulator */ /** * The purpose of this class is to accumulate /sync responses such that a * complete "initial" JSON response can be returned which accurately represents * the sum total of the /sync responses accumulated to date. It only handles * room data: that is, everything under the "rooms" top-level key. * * This class is used when persisting room data so a complete /sync response can * be loaded from disk and incremental syncs can be performed on the server, * rather than asking the server to do an initial sync on startup. */ var SyncAccumulator = /*#__PURE__*/function () { /** * @param {Object} opts * @param {Number=} opts.maxTimelineEntries The ideal maximum number of * timeline entries to keep in the sync response. This is best-effort, as * clients do not always have a back-pagination token for each event, so * it's possible there may be slightly *less* than this value. There will * never be more. This cannot be 0 or else it makes it impossible to scroll * back in a room. Default: 50. */ function SyncAccumulator(opts) { (0, _classCallCheck2["default"])(this, SyncAccumulator); opts = opts || {}; opts.maxTimelineEntries = opts.maxTimelineEntries || 50; this.opts = opts; this.accountData = {//$event_type: Object }; this.inviteRooms = {//$roomId: { ... sync 'invite' json data ... } }; this.joinRooms = {//$roomId: { // _currentState: { $event_type: { $state_key: json } }, // _timeline: [ // { event: $event, token: null|token }, // { event: $event, token: null|token }, // { event: $event, token: null|token }, // ... // ], // _summary: { // m.heroes: [ $user_id ], // m.joined_member_count: $count, // m.invited_member_count: $count // }, // _accountData: { $event_type: json }, // _unreadNotifications: { ... unread_notifications JSON ... }, // _readReceipts: { $user_id: { data: $json, eventId: $event_id }} //} }; // the /sync token which corresponds to the last time rooms were // accumulated. We remember this so that any caller can obtain a // coherent /sync response and know at what point they should be // streaming from without losing events. this.nextBatch = null; // { ('invite'|'join'|'leave'): $groupId: { ... sync 'group' data } } this.groups = { invite: {}, join: {}, leave: {} }; } (0, _createClass2["default"])(SyncAccumulator, [{ key: "accumulate", value: function accumulate(syncResponse) { this._accumulateRooms(syncResponse); this._accumulateGroups(syncResponse); this._accumulateAccountData(syncResponse); this.nextBatch = syncResponse.next_batch; } }, { key: "_accumulateAccountData", value: function _accumulateAccountData(syncResponse) { var _this = this; if (!syncResponse.account_data || !syncResponse.account_data.events) { return; } // Clobbers based on event type. syncResponse.account_data.events.forEach(function (e) { _this.accountData[e.type] = e; }); } /** * Accumulate incremental /sync room data. * @param {Object} syncResponse the complete /sync JSON */ }, { key: "_accumulateRooms", value: function _accumulateRooms(syncResponse) { var _this2 = this; if (!syncResponse.rooms) { return; } if (syncResponse.rooms.invite) { Object.keys(syncResponse.rooms.invite).forEach(function (roomId) { _this2._accumulateRoom(roomId, "invite", syncResponse.rooms.invite[roomId]); }); } if (syncResponse.rooms.join) { Object.keys(syncResponse.rooms.join).forEach(function (roomId) { _this2._accumulateRoom(roomId, "join", syncResponse.rooms.join[roomId]); }); } if (syncResponse.rooms.leave) { Object.keys(syncResponse.rooms.leave).forEach(function (roomId) { _this2._accumulateRoom(roomId, "leave", syncResponse.rooms.leave[roomId]); }); } } }, { key: "_accumulateRoom", value: function _accumulateRoom(roomId, category, data) { // Valid /sync state transitions // +--------+ <======+ 1: Accept an invite // +== | INVITE | | (5) 2: Leave a room // | +--------+ =====+ | 3: Join a public room previously // |(1) (4) | | left (handle as if new room) // V (2) V | 4: Reject an invite // +------+ ========> +--------+ 5: Invite to a room previously // | JOIN | (3) | LEAVE* | left (handle as if new room) // +------+ <======== +--------+ // // * equivalent to "no state" switch (category) { case "invite": // (5) this._accumulateInviteState(roomId, data); break; case "join": if (this.inviteRooms[roomId]) { // (1) // was previously invite, now join. We expect /sync to give // the entire state and timeline on 'join', so delete previous // invite state delete this.inviteRooms[roomId]; } // (3) this._accumulateJoinState(roomId, data); break; case "leave": if (this.inviteRooms[roomId]) { // (4) delete this.inviteRooms[roomId]; } else { // (2) delete this.joinRooms[roomId]; } break; default: _logger.logger.error("Unknown cateogory: ", category); } } }, { key: "_accumulateInviteState", value: function _accumulateInviteState(roomId, data) { if (!data.invite_state || !data.invite_state.events) { // no new data return; } if (!this.inviteRooms[roomId]) { this.inviteRooms[roomId] = { invite_state: data.invite_state }; return; } // accumulate extra keys for invite->invite transitions // clobber based on event type / state key // We expect invite_state to be small, so just loop over the events var currentData = this.inviteRooms[roomId]; data.invite_state.events.forEach(function (e) { var hasAdded = false; for (var i = 0; i < currentData.invite_state.events.length; i++) { var current = currentData.invite_state.events[i]; if (current.type === e.type && current.state_key == e.state_key) { currentData.invite_state.events[i] = e; // update hasAdded = true; } } if (!hasAdded) { currentData.invite_state.events.push(e); } }); } // Accumulate timeline and state events in a room. }, { key: "_accumulateJoinState", value: function _accumulateJoinState(roomId, data) { // We expect this function to be called a lot (every /sync) so we want // this to be fast. /sync stores events in an array but we often want // to clobber based on type/state_key. Rather than convert arrays to // maps all the time, just keep private maps which contain // the actual current accumulated sync state, and array-ify it when // getJSON() is called. // State resolution: // The 'state' key is the delta from the previous sync (or start of time // if no token was supplied), to the START of the timeline. To obtain // the current state, we need to "roll forward" state by reading the // timeline. We want to store the current state so we can drop events // out the end of the timeline based on opts.maxTimelineEntries. // // 'state' 'timeline' current state // |-------x<======================>x // T I M E // // When getJSON() is called, we 'roll back' the current state by the // number of entries in the timeline to work out what 'state' should be. // Back-pagination: // On an initial /sync, the server provides a back-pagination token for // the start of the timeline. When /sync deltas come down, they also // include back-pagination tokens for the start of the timeline. This // means not all events in the timeline have back-pagination tokens, as // it is only the ones at the START of the timeline which have them. // In order for us to have a valid timeline (and back-pagination token // to match), we need to make sure that when we remove old timeline // events, that we roll forward to an event which has a back-pagination // token. This means we can't keep a strict sliding-window based on // opts.maxTimelineEntries, and we may have a few less. We should never // have more though, provided that the /sync limit is less than or equal // to opts.maxTimelineEntries. if (!this.joinRooms[roomId]) { // Create truly empty objects so event types of 'hasOwnProperty' and co // don't cause this code to break. this.joinRooms[roomId] = { _currentState: Object.create(null), _timeline: [], _accountData: Object.create(null), _unreadNotifications: {}, _summary: {}, _readReceipts: {} }; } var currentData = this.joinRooms[roomId]; if (data.account_data && data.account_data.events) { // clobber based on type data.account_data.events.forEach(function (e) { currentData._accountData[e.type] = e; }); } // these probably clobber, spec is unclear. if (data.unread_notifications) { currentData._unreadNotifications = data.unread_notifications; } if (data.summary) { var HEROES_KEY = "m.heroes"; var INVITED_COUNT_KEY = "m.invited_member_count"; var JOINED_COUNT_KEY = "m.joined_member_count"; var acc = currentData._summary; var sum = data.summary; acc[HEROES_KEY] = sum[HEROES_KEY] || acc[HEROES_KEY]; acc[JOINED_COUNT_KEY] = sum[JOINED_COUNT_KEY] || acc[JOINED_COUNT_KEY]; acc[INVITED_COUNT_KEY] = sum[INVITED_COUNT_KEY] || acc[INVITED_COUNT_KEY]; } if (data.ephemeral && data.ephemeral.events) { data.ephemeral.events.forEach(function (e) { // We purposefully do not persist m.typing events. // Technically you could refresh a browser before the timer on a // typing event is up, so it'll look like you aren't typing when // you really still are. However, the alternative is worse. If // we do persist typing events, it will look like people are // typing forever until someone really does start typing (which // will prompt Synapse to send down an actual m.typing event to // clobber the one we persisted). if (e.type !== "m.receipt" || !e.content) { // This means we'll drop unknown ephemeral events but that // seems okay. return; } // Handle m.receipt events. They clobber based on: // (user_id, receipt_type) // but they are keyed in the event as: // content:{ $event_id: { $receipt_type: { $user_id: {json} }}} // so store them in the former so we can accumulate receipt deltas // quickly and efficiently (we expect a lot of them). Fold the // receipt type into the key name since we only have 1 at the // moment (m.read) and nested JSON objects are slower and more // of a hassle to work with. We'll inflate this back out when // getJSON() is called. Object.keys(e.content).forEach(function (eventId) { if (!e.content[eventId]["m.read"]) { return; } Object.keys(e.content[eventId]["m.read"]).forEach(function (userId) { // clobber on user ID currentData._readReceipts[userId] = { data: e.content[eventId]["m.read"][userId], eventId: eventId }; }); }); }); } // if we got a limited sync, we need to remove all timeline entries or else // we will have gaps in the timeline. if (data.timeline && data.timeline.limited) { currentData._timeline = []; } // Work out the current state. The deltas need to be applied in the order: // - existing state which didn't come down /sync. // - State events under the 'state' key. // - State events in the 'timeline'. if (data.state && data.state.events) { data.state.events.forEach(function (e) { setState(currentData._currentState, e); }); } if (data.timeline && data.timeline.events) { data.timeline.events.forEach(function (e, index) { // this nops if 'e' isn't a state event setState(currentData._currentState, e); // append the event to the timeline. The back-pagination token // corresponds to the first event in the timeline currentData._timeline.push({ event: e, token: index === 0 ? data.timeline.prev_batch : null }); }); } // attempt to prune the timeline by jumping between events which have // pagination tokens. if (currentData._timeline.length > this.opts.maxTimelineEntries) { var startIndex = currentData._timeline.length - this.opts.maxTimelineEntries; for (var i = startIndex; i < currentData._timeline.length; i++) { if (currentData._timeline[i].token) { // keep all events after this, including this one currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length); break; } } } } /** * Accumulate incremental /sync group data. * @param {Object} syncResponse the complete /sync JSON */ }, { key: "_accumulateGroups", value: function _accumulateGroups(syncResponse) { var _this3 = this; if (!syncResponse.groups) { return; } if (syncResponse.groups.invite) { Object.keys(syncResponse.groups.invite).forEach(function (groupId) { _this3._accumulateGroup(groupId, "invite", syncResponse.groups.invite[groupId]); }); } if (syncResponse.groups.join) { Object.keys(syncResponse.groups.join).forEach(function (groupId) { _this3._accumulateGroup(groupId, "join", syncResponse.groups.join[groupId]); }); } if (syncResponse.groups.leave) { Object.keys(syncResponse.groups.leave).forEach(function (groupId) { _this3._accumulateGroup(groupId, "leave", syncResponse.groups.leave[groupId]); }); } } }, { key: "_accumulateGroup", value: function _accumulateGroup(groupId, category, data) { for (var _i = 0, _arr = ['invite', 'join', 'leave']; _i < _arr.length; _i++) { var cat = _arr[_i]; delete this.groups[cat][groupId]; } this.groups[category][groupId] = data; } /** * Return everything under the 'rooms' key from a /sync response which * represents all room data that should be stored. This should be paired * with the sync token which represents the most recent /sync response * provided to accumulate(). * @return {Object} An object with a "nextBatch", "roomsData" and "accountData" * keys. * The "nextBatch" key is a string which represents at what point in the * /sync stream the accumulator reached. This token should be used when * restarting a /sync stream at startup. Failure to do so can lead to missing * events. The "roomsData" key is an Object which represents the entire * /sync response from the 'rooms' key onwards. The "accountData" key is * a list of raw events which represent global account data. */ }, { key: "getJSON", value: function getJSON() { var _this4 = this; var data = { join: {}, invite: {}, // always empty. This is set by /sync when a room was previously // in 'invite' or 'join'. On fresh startup, the client won't know // about any previous room being in 'invite' or 'join' so we can // just omit mentioning it at all, even if it has previously come // down /sync. // The notable exception is when a client is kicked or banned: // we may want to hold onto that room so the client can clearly see // why their room has disappeared. We don't persist it though because // it is unclear *when* we can safely remove the room from the DB. // Instead, we assume that if you're loading from the DB, you've // refreshed the page, which means you've seen the kick/ban already. leave: {} }; Object.keys(this.inviteRooms).forEach(function (roomId) { data.invite[roomId] = _this4.inviteRooms[roomId]; }); Object.keys(this.joinRooms).forEach(function (roomId) { var roomData = _this4.joinRooms[roomId]; var roomJson = { ephemeral: { events: [] }, account_data: { events: [] }, state: { events: [] }, timeline: { events: [], prev_batch: null }, unread_notifications: roomData._unreadNotifications, summary: roomData._summary }; // Add account data Object.keys(roomData._accountData).forEach(function (evType) { roomJson.account_data.events.push(roomData._accountData[evType]); }); // Add receipt data var receiptEvent = { type: "m.receipt", room_id: roomId, content: {// $event_id: { "m.read": { $user_id: $json } } } }; Object.keys(roomData._readReceipts).forEach(function (userId) { var receiptData = roomData._readReceipts[userId]; if (!receiptEvent.content[receiptData.eventId]) { receiptEvent.content[receiptData.eventId] = { "m.read": {} }; } receiptEvent.content[receiptData.eventId]["m.read"][userId] = receiptData.data; }); // add only if we have some receipt data if (Object.keys(receiptEvent.content).length > 0) { roomJson.ephemeral.events.push(receiptEvent); } // Add timeline data roomData._timeline.forEach(function (msgData) { if (!roomJson.timeline.prev_batch) { // the first event we add to the timeline MUST match up to // the prev_batch token. if (!msgData.token) { return; // this shouldn't happen as we prune constantly. } roomJson.timeline.prev_batch = msgData.token; } roomJson.timeline.events.push(msgData.event); }); // Add state data: roll back current state to the start of timeline, // by "reverse clobbering" from the end of the timeline to the start. // Convert maps back into arrays. var rollBackState = Object.create(null); for (var i = roomJson.timeline.events.length - 1; i >= 0; i--) { var timelineEvent = roomJson.timeline.events[i]; if (timelineEvent.state_key === null || timelineEvent.state_key === undefined) { continue; // not a state event } // since we're going back in time, we need to use the previous // state value else we'll break causality. We don't have the // complete previous state event, so we need to create one. var prevStateEvent = (0, _utils.deepCopy)(timelineEvent); if (prevStateEvent.unsigned) { if (prevStateEvent.unsigned.prev_content) { prevStateEvent.content = prevStateEvent.unsigned.prev_content; } if (prevStateEvent.unsigned.prev_sender) { prevStateEvent.sender = prevStateEvent.unsigned.prev_sender; } } setState(rollBackState, prevStateEvent); } Object.keys(roomData._currentState).forEach(function (evType) { Object.keys(roomData._currentState[evType]).forEach(function (stateKey) { var ev = roomData._currentState[evType][stateKey]; if (rollBackState[evType] && rollBackState[evType][stateKey]) { // use the reverse clobbered event instead. ev = rollBackState[evType][stateKey]; } roomJson.state.events.push(ev); }); }); data.join[roomId] = roomJson; }); // Add account data var accData = []; Object.keys(this.accountData).forEach(function (evType) { accData.push(_this4.accountData[evType]); }); return { nextBatch: this.nextBatch, roomsData: data, groupsData: this.groups, accountData: accData }; } }, { key: "getNextBatchToken", value: function getNextBatchToken() { return this.nextBatch; } }]); return SyncAccumulator; }(); exports.SyncAccumulator = SyncAccumulator; function setState(eventMap, event) { if (event.state_key === null || event.state_key === undefined || !event.type) { return; } if (!eventMap[event.type]) { eventMap[event.type] = Object.create(null); } eventMap[event.type][event.state_key] = event; } },{"./logger":95,"./utils":123,"@babel/runtime/helpers/classCallCheck":6,"@babel/runtime/helpers/createClass":8,"@babel/runtime/helpers/interopRequireDefault":12}],121:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SyncApi = SyncApi; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _user = require("./models/user"); var _room = require("./models/room"); var _group = require("./models/group"); var utils = _interopRequireWildcard(require("./utils")); var _filter = require("./filter"); var _eventTimeline = require("./models/event-timeline"); var _pushprocessor = require("./pushprocessor"); var _logger = require("./logger"); var _errors = require("./errors"); function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var DEBUG = true; // /sync requests allow you to set a timeout= but the request may continue // beyond that and wedge forever, so we need to track how long we are willing // to keep open the connection. This constant is *ADDED* to the timeout= value // to determine the max time we're willing to wait. var BUFFER_PERIOD_MS = 80 * 1000; // Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed // to RECONNECTING. This is needed to inform the client of server issues when the // keepAlive is successful but the server /sync fails. var FAILED_SYNC_ERROR_THRESHOLD = 3; function getFilterName(userId, suffix) { // scope this on the user ID because people may login on many accounts // and they all need to be stored! return "FILTER_SYNC_" + userId + (suffix ? "_" + suffix : ""); } function debuglog() { if (!DEBUG) { return; } _logger.logger.log.apply(_logger.logger, arguments); } /** * Internal class - unstable. * Construct an entity which is able to sync with a homeserver. * @constructor * @param {MatrixClient} client The matrix client instance to use. * @param {Object} opts Config options * @param {module:crypto=} opts.crypto Crypto manager * @param {Function=} opts.canResetEntireTimeline A function which is called * with a room ID and returns a boolean. It should return 'true' if the SDK can * SAFELY remove events from this room. It may not be safe to remove events if * there are other references to the timelines for this room. * Default: returns false. * @param {Boolean=} opts.disablePresence True to perform syncing without automatically * updating presence. */ function SyncApi(client, opts) { this.client = client; opts = opts || {}; opts.initialSyncLimit = opts.initialSyncLimit === undefined ? 8 : opts.initialSyncLimit; opts.resolveInvitesToProfiles = opts.resolveInvitesToProfiles || false; opts.pollTimeout = opts.pollTimeout || 30 * 1000; opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological"; if (!opts.canResetEntireTimeline) { opts.canResetEntireTimeline = function (roomId) { return false; }; } this.opts = opts; this._peekRoomId = null; this._currentSyncRequest = null; this._syncState = null; this._syncStateData = null; // additional data (eg. error object for failed sync) this._catchingUp = false; this._running = false; this._keepAliveTimer = null; this._connectionReturnedDefer = null; this._notifEvents = []; // accumulator of sync events in the current sync response this._failedSyncCount = 0; // Number of consecutive failed /sync requests this._storeIsInvalid = false; // flag set if the store needs to be cleared before we can start if (client.getNotifTimelineSet()) { client.reEmitter.reEmit(client.getNotifTimelineSet(), ["Room.timeline", "Room.timelineReset"]); } } /** * @param {string} roomId * @return {Room} */ SyncApi.prototype.createRoom = function (roomId) { var client = this.client; var timelineSupport = client.timelineSupport, unstableClientRelationAggregation = client.unstableClientRelationAggregation; var room = new _room.Room(roomId, client, client.getUserId(), { lazyLoadMembers: this.opts.lazyLoadMembers, pendingEventOrdering: this.opts.pendingEventOrdering, timelineSupport: timelineSupport, unstableClientRelationAggregation: unstableClientRelationAggregation }); client.reEmitter.reEmit(room, ["Room.name", "Room.timeline", "Room.redaction", "Room.redactionCancelled", "Room.receipt", "Room.tags", "Room.timelineReset", "Room.localEchoUpdated", "Room.accountData", "Room.myMembership", "Room.replaceEvent"]); this._registerStateListeners(room); return room; }; /** * @param {string} groupId * @return {Group} */ SyncApi.prototype.createGroup = function (groupId) { var client = this.client; var group = new _group.Group(groupId); client.reEmitter.reEmit(group, ["Group.profile", "Group.myMembership"]); client.store.storeGroup(group); return group; }; /** * @param {Room} room * @private */ SyncApi.prototype._registerStateListeners = function (room) { var client = this.client; // we need to also re-emit room state and room member events, so hook it up // to the client now. We need to add a listener for RoomState.members in // order to hook them correctly. (TODO: find a better way?) client.reEmitter.reEmit(room.currentState, ["RoomState.events", "RoomState.members", "RoomState.newMember"]); room.currentState.on("RoomState.newMember", function (event, state, member) { member.user = client.getUser(member.userId); client.reEmitter.reEmit(member, ["RoomMember.name", "RoomMember.typing", "RoomMember.powerLevel", "RoomMember.membership"]); }); }; /** * @param {Room} room * @private */ SyncApi.prototype._deregisterStateListeners = function (room) { // could do with a better way of achieving this. room.currentState.removeAllListeners("RoomState.events"); room.currentState.removeAllListeners("RoomState.members"); room.currentState.removeAllListeners("RoomState.newMember"); }; /** * Sync rooms the user has left. * @return {Promise} Resolved when they've been added to the store. */ SyncApi.prototype.syncLeftRooms = function () { var client = this.client; var self = this; // grab a filter with limit=1 and include_leave=true var filter = new _filter.Filter(this.client.credentials.userId); filter.setTimelineLimit(1); filter.setIncludeLeaveRooms(true); var localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; var qps = { timeout: 0 // don't want to block since this is a single isolated req }; return client.getOrCreateFilter(getFilterName(client.credentials.userId, "LEFT_ROOMS"), filter).then(function (filterId) { qps.filter = filterId; return client._http.authedRequest(undefined, "GET", "/sync", qps, undefined, localTimeoutMs); }).then(function (data) { var leaveRooms = []; if (data.rooms && data.rooms.leave) { leaveRooms = self._mapSyncResponseToRoomArray(data.rooms.leave); } var rooms = []; leaveRooms.forEach(function (leaveObj) { var room = leaveObj.room; rooms.push(room); if (!leaveObj.isBrandNewRoom) { // the intention behind syncLeftRooms is to add in rooms which were // *omitted* from the initial /sync. Rooms the user were joined to // but then left whilst the app is running will appear in this list // and we do not want to bother with them since they will have the // current state already (and may get dupe messages if we add // yet more timeline events!), so skip them. // NB: When we persist rooms to localStorage this will be more // complicated... return; } leaveObj.timeline = leaveObj.timeline || {}; var timelineEvents = self._mapSyncEventsFormat(leaveObj.timeline, room); var stateEvents = self._mapSyncEventsFormat(leaveObj.state, room); // set the back-pagination token. Do this *before* adding any // events so that clients can start back-paginating. room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, _eventTimeline.EventTimeline.BACKWARDS); self._processRoomEvents(room, stateEvents, timelineEvents); room.recalculate(); client.store.storeRoom(room); client.emit("Room", room); self._processEventsForNotifs(room, timelineEvents); }); return rooms; }); }; /** * Peek into a room. This will result in the room in question being synced so it * is accessible via getRooms(). Live updates for the room will be provided. * @param {string} roomId The room ID to peek into. * @return {Promise} A promise which resolves once the room has been added to the * store. */ SyncApi.prototype.peek = function (roomId) { var self = this; var client = this.client; this._peekRoomId = roomId; return this.client.roomInitialSync(roomId, 20).then(function (response) { // make sure things are init'd response.messages = response.messages || {}; response.messages.chunk = response.messages.chunk || []; response.state = response.state || []; var peekRoom = self.createRoom(roomId); // FIXME: Mostly duplicated from _processRoomEvents but not entirely // because "state" in this API is at the BEGINNING of the chunk var oldStateEvents = utils.map(utils.deepCopy(response.state), client.getEventMapper()); var stateEvents = utils.map(response.state, client.getEventMapper()); var messages = utils.map(response.messages.chunk, client.getEventMapper()); // XXX: copypasted from /sync until we kill off this // minging v1 API stuff) // handle presence events (User objects) if (response.presence && utils.isArray(response.presence)) { response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) { var user = client.store.getUser(presenceEvent.getContent().user_id); if (user) { user.setPresenceEvent(presenceEvent); } else { user = createNewUser(client, presenceEvent.getContent().user_id); user.setPresenceEvent(presenceEvent); client.store.storeUser(user); } client.emit("event", presenceEvent); }); } // set the pagination token before adding the events in case people // fire off pagination requests in response to the Room.timeline // events. if (response.messages.start) { peekRoom.oldState.paginationToken = response.messages.start; } // set the state of the room to as it was after the timeline executes peekRoom.oldState.setStateEvents(oldStateEvents); peekRoom.currentState.setStateEvents(stateEvents); self._resolveInvites(peekRoom); peekRoom.recalculate(); // roll backwards to diverge old state. addEventsToTimeline // will overwrite the pagination token, so make sure it overwrites // it with the right thing. peekRoom.addEventsToTimeline(messages.reverse(), true, peekRoom.getLiveTimeline(), response.messages.start); client.store.storeRoom(peekRoom); client.emit("Room", peekRoom); self._peekPoll(peekRoom); return peekRoom; }); }; /** * Stop polling for updates in the peeked room. NOPs if there is no room being * peeked. */ SyncApi.prototype.stopPeeking = function () { this._peekRoomId = null; }; /** * Do a peek room poll. * @param {Room} peekRoom * @param {string} token from= token */ SyncApi.prototype._peekPoll = function (peekRoom, token) { if (this._peekRoomId !== peekRoom.roomId) { debuglog("Stopped peeking in room %s", peekRoom.roomId); return; } var self = this; // FIXME: gut wrenching; hard-coded timeout values this.client._http.authedRequest(undefined, "GET", "/events", { room_id: peekRoom.roomId, timeout: 30 * 1000, from: token }, undefined, 50 * 1000).then(function (res) { if (self._peekRoomId !== peekRoom.roomId) { debuglog("Stopped peeking in room %s", peekRoom.roomId); return; } // We have a problem that we get presence both from /events and /sync // however, /sync only returns presence for users in rooms // you're actually joined to. // in order to be sure to get presence for all of the users in the // peeked room, we handle presence explicitly here. This may result // in duplicate presence events firing for some users, which is a // performance drain, but such is life. // XXX: copypasted from /sync until we can kill this minging v1 stuff. res.chunk.filter(function (e) { return e.type === "m.presence"; }).map(self.client.getEventMapper()).forEach(function (presenceEvent) { var user = self.client.store.getUser(presenceEvent.getContent().user_id); if (user) { user.setPresenceEvent(presenceEvent); } else { user = createNewUser(self.client, presenceEvent.getContent().user_id); user.setPresenceEvent(presenceEvent); self.client.store.storeUser(user); } self.client.emit("event", presenceEvent); }); // strip out events which aren't for the given room_id (e.g presence) // and also ephemeral events (which we're assuming is anything without // and event ID because the /events API doesn't separate them). var events = res.chunk.filter(function (e) { return e.room_id === peekRoom.roomId && e.event_id; }).map(self.client.getEventMapper()); peekRoom.addLiveEvents(events); self._peekPoll(peekRoom, res.end); }, function (err) { _logger.logger.error("[%s] Peek poll failed: %s", peekRoom.roomId, err); setTimeout(function () { self._peekPoll(peekRoom, token); }, 30 * 1000); }); }; /** * Returns the current state of this sync object * @see module:client~MatrixClient#event:"sync" * @return {?String} */ SyncApi.prototype.getSyncState = function () { return this._syncState; }; /** * Returns the additional data object associated with * the current sync state, or null if there is no * such data. * Sync errors, if available, are put in the 'error' key of * this object. * @return {?Object} */ SyncApi.prototype.getSyncStateData = function () { return this._syncStateData; }; SyncApi.prototype.recoverFromSyncStartupError = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(savedSyncPromise, err) { var keepaliveProm; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return savedSyncPromise; case 2: keepaliveProm = this._startKeepAlives(); this._updateSyncState("ERROR", { error: err }); _context.next = 6; return keepaliveProm; case 6: case "end": return _context.stop(); } } }, _callee, this); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(); /** * Is the lazy loading option different than in previous session? * @param {bool} lazyLoadMembers current options for lazy loading * @return {bool} whether or not the option has changed compared to the previous session */ SyncApi.prototype._wasLazyLoadingToggled = /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(lazyLoadMembers) { var lazyLoadMembersBefore, isStoreNewlyCreated, prevClientOptions; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: lazyLoadMembers = !!lazyLoadMembers; // assume it was turned off before // if we don't know any better lazyLoadMembersBefore = false; _context2.next = 4; return this.client.store.isNewlyCreated(); case 4: isStoreNewlyCreated = _context2.sent; if (isStoreNewlyCreated) { _context2.next = 11; break; } _context2.next = 8; return this.client.store.getClientOptions(); case 8: prevClientOptions = _context2.sent; if (prevClientOptions) { lazyLoadMembersBefore = !!prevClientOptions.lazyLoadMembers; } return _context2.abrupt("return", lazyLoadMembersBefore !== lazyLoadMembers); case 11: return _context2.abrupt("return", false); case 12: case "end": return _context2.stop(); } } }, _callee2, this); })); return function (_x3) { return _ref2.apply(this, arguments); }; }(); SyncApi.prototype._shouldAbortSync = function (error) { if (error.errcode === "M_UNKNOWN_TOKEN") { // The logout already happened, we just need to stop. _logger.logger.warn("Token no longer valid - assuming logout"); this.stop(); return true; } return false; }; /** * Main entry point */ SyncApi.prototype.sync = function () { var _this = this; var client = this.client; var self = this; this._running = true; if (global.document) { this._onOnlineBound = this._onOnline.bind(this); global.document.addEventListener("online", this._onOnlineBound, false); } var savedSyncPromise = Promise.resolve(); var savedSyncToken = null; // We need to do one-off checks before we can begin the /sync loop. // These are: // 1) We need to get push rules so we can check if events should bing as we get // them from /sync. // 2) We need to get/create a filter which we can use for /sync. // 3) We need to check the lazy loading option matches what was used in the // stored sync. If it doesn't, we can't use the stored sync. function getPushRules() { return _getPushRules.apply(this, arguments); } function _getPushRules() { _getPushRules = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var result; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.prev = 0; debuglog("Getting push rules..."); _context4.next = 4; return client.getPushRules(); case 4: result = _context4.sent; debuglog("Got push rules"); client.pushRules = result; _context4.next = 19; break; case 9: _context4.prev = 9; _context4.t0 = _context4["catch"](0); _logger.logger.error("Getting push rules failed", _context4.t0); if (!self._shouldAbortSync(_context4.t0)) { _context4.next = 14; break; } return _context4.abrupt("return"); case 14: // wait for saved sync to complete before doing anything else, // otherwise the sync state will end up being incorrect debuglog("Waiting for saved sync before retrying push rules..."); _context4.next = 17; return self.recoverFromSyncStartupError(savedSyncPromise, _context4.t0); case 17: getPushRules(); return _context4.abrupt("return"); case 19: checkLazyLoadStatus(); // advance to the next stage case 20: case "end": return _context4.stop(); } } }, _callee4, null, [[0, 9]]); })); return _getPushRules.apply(this, arguments); } function buildDefaultFilter() { var filter = new _filter.Filter(client.credentials.userId); filter.setTimelineLimit(self.opts.initialSyncLimit); return filter; } var checkLazyLoadStatus = /*#__PURE__*/function () { var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { var supported, shouldClear, reason, error; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: debuglog("Checking lazy load status..."); if (_this.opts.lazyLoadMembers && client.isGuest()) { _this.opts.lazyLoadMembers = false; } if (!_this.opts.lazyLoadMembers) { _context3.next = 8; break; } debuglog("Checking server lazy load support..."); _context3.next = 6; return client.doesServerSupportLazyLoading(); case 6: supported = _context3.sent; if (supported) { debuglog("Enabling lazy load on sync filter..."); if (!_this.opts.filter) { _this.opts.filter = buildDefaultFilter(); } _this.opts.filter.setLazyLoadMembers(true); } else { debuglog("LL: lazy loading requested but not supported " + "by server, so disabling"); _this.opts.lazyLoadMembers = false; } case 8: // need to vape the store when enabling LL and wasn't enabled before debuglog("Checking whether lazy loading has changed in store..."); _context3.next = 11; return _this._wasLazyLoadingToggled(_this.opts.lazyLoadMembers); case 11: shouldClear = _context3.sent; if (!shouldClear) { _context3.next = 19; break; } _this._storeIsInvalid = true; reason = _errors.InvalidStoreError.TOGGLED_LAZY_LOADING; error = new _errors.InvalidStoreError(reason, !!_this.opts.lazyLoadMembers); _this._updateSyncState("ERROR", { error: error }); // bail out of the sync loop now: the app needs to respond to this error. // we leave the state as 'ERROR' which isn't great since this normally means // we're retrying. The client must be stopped before clearing the stores anyway // so the app should stop the client, clear the store and start it again. _logger.logger.warn("InvalidStoreError: store is not usable: stopping sync."); return _context3.abrupt("return"); case 19: if (_this.opts.lazyLoadMembers && _this.opts.crypto) { _this.opts.crypto.enableLazyLoading(); } _context3.prev = 20; debuglog("Storing client options..."); _context3.next = 24; return _this.client._storeClientOptions(); case 24: debuglog("Stored client options"); _context3.next = 31; break; case 27: _context3.prev = 27; _context3.t0 = _context3["catch"](20); _logger.logger.error("Storing client options failed", _context3.t0); throw _context3.t0; case 31: getFilter(); // Now get the filter and start syncing case 32: case "end": return _context3.stop(); } } }, _callee3, null, [[20, 27]]); })); return function checkLazyLoadStatus() { return _ref3.apply(this, arguments); }; }(); function getFilter() { return _getFilter.apply(this, arguments); } function _getFilter() { _getFilter = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { var filter, filterId; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: debuglog("Getting filter..."); if (self.opts.filter) { filter = self.opts.filter; } else { filter = buildDefaultFilter(); } _context5.prev = 2; _context5.next = 5; return client.getOrCreateFilter(getFilterName(client.credentials.userId), filter); case 5: filterId = _context5.sent; _context5.next = 18; break; case 8: _context5.prev = 8; _context5.t0 = _context5["catch"](2); _logger.logger.error("Getting filter failed", _context5.t0); if (!self._shouldAbortSync(_context5.t0)) { _context5.next = 13; break; } return _context5.abrupt("return"); case 13: // wait for saved sync to complete before doing anything else, // otherwise the sync state will end up being incorrect debuglog("Waiting for saved sync before retrying filter..."); _context5.next = 16; return self.recoverFromSyncStartupError(savedSyncPromise, _context5.t0); case 16: getFilter(); return _context5.abrupt("return"); case 18: // reset the notifications timeline to prepare it to paginate from // the current point in time. // The right solution would be to tie /sync pagination tokens into // /notifications API somehow. client.resetNotifTimelineSet(); if (self._currentSyncRequest === null) { // Send this first sync request here so we can then wait for the saved // sync data to finish processing before we process the results of this one. debuglog("Sending first sync request..."); self._currentSyncRequest = self._doSyncRequest({ filterId: filterId }, savedSyncToken); } // Now wait for the saved sync to finish... debuglog("Waiting for saved sync before starting sync processing..."); _context5.next = 23; return savedSyncPromise; case 23: self._sync({ filterId: filterId }); case 24: case "end": return _context5.stop(); } } }, _callee5, null, [[2, 8]]); })); return _getFilter.apply(this, arguments); } if (client.isGuest()) { // no push rules for guests, no access to POST filter for guests. self._sync({}); } else { // Pull the saved sync token out first, before the worker starts sending // all the sync data which could take a while. This will let us send our // first incremental sync request before we've processed our saved data. debuglog("Getting saved sync token..."); savedSyncPromise = client.store.getSavedSyncToken().then(function (tok) { debuglog("Got saved sync token"); savedSyncToken = tok; debuglog("Getting saved sync..."); return client.store.getSavedSync(); }).then(function (savedSync) { debuglog("Got reply from saved sync, exists? ".concat(!!savedSync)); if (savedSync) { return self._syncFromCache(savedSync); } })["catch"](function (err) { _logger.logger.error("Getting saved sync failed", err); }); // Now start the first incremental sync request: this can also // take a while so if we set it going now, we can wait for it // to finish while we process our saved sync data. getPushRules(); } }; /** * Stops the sync object from syncing. */ SyncApi.prototype.stop = function () { debuglog("SyncApi.stop"); if (global.document) { global.document.removeEventListener("online", this._onOnlineBound, false); this._onOnlineBound = undefined; } this._running = false; if (this._currentSyncRequest) { this._currentSyncRequest.abort(); } if (this._keepAliveTimer) { clearTimeout(this._keepAliveTimer); this._keepAliveTimer = null; } }; /** * Retry a backed off syncing request immediately. This should only be used when * the user explicitly attempts to retry their lost connection. * @return {boolean} True if this resulted in a request being retried. */ SyncApi.prototype.retryImmediately = function () { if (!this._connectionReturnedDefer) { return false; } this._startKeepAlives(0); return true; }; /** * Process a single set of cached sync data. * @param {Object} savedSync a saved sync that was persisted by a store. This * should have been acquired via client.store.getSavedSync(). */ SyncApi.prototype._syncFromCache = /*#__PURE__*/function () { var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(savedSync) { var nextSyncToken, syncEventData, data; return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: debuglog("sync(): not doing HTTP hit, instead returning stored /sync data"); nextSyncToken = savedSync.nextBatch; // Set sync token for future incremental syncing this.client.store.setSyncToken(nextSyncToken); // No previous sync, set old token to null syncEventData = { oldSyncToken: null, nextSyncToken: nextSyncToken, catchingUp: false, fromCache: true }; data = { next_batch: nextSyncToken, rooms: savedSync.roomsData, groups: savedSync.groupsData, account_data: { events: savedSync.accountData } }; _context6.prev = 5; _context6.next = 8; return this._processSyncResponse(syncEventData, data); case 8: _context6.next = 13; break; case 10: _context6.prev = 10; _context6.t0 = _context6["catch"](5); _logger.logger.error("Error processing cached sync", _context6.t0.stack || _context6.t0); case 13: // Don't emit a prepared if we've bailed because the store is invalid: // in this case the client will not be usable until stopped & restarted // so this would be useless and misleading. if (!this._storeIsInvalid) { this._updateSyncState("PREPARED", syncEventData); } case 14: case "end": return _context6.stop(); } } }, _callee6, this, [[5, 10]]); })); return function (_x4) { return _ref4.apply(this, arguments); }; }(); /** * Invoke me to do /sync calls * @param {Object} syncOptions * @param {string} syncOptions.filterId * @param {boolean} syncOptions.hasSyncedBefore */ SyncApi.prototype._sync = /*#__PURE__*/function () { var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(syncOptions) { var client, syncToken, data, syncEventData; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: client = this.client; if (this._running) { _context7.next = 6; break; } debuglog("Sync no longer running: exiting."); if (this._connectionReturnedDefer) { this._connectionReturnedDefer.reject(); this._connectionReturnedDefer = null; } this._updateSyncState("STOPPED"); return _context7.abrupt("return"); case 6: syncToken = client.store.getSyncToken(); _context7.prev = 7; //debuglog('Starting sync since=' + syncToken); if (this._currentSyncRequest === null) { this._currentSyncRequest = this._doSyncRequest(syncOptions, syncToken); } _context7.next = 11; return this._currentSyncRequest; case 11: data = _context7.sent; _context7.next = 18; break; case 14: _context7.prev = 14; _context7.t0 = _context7["catch"](7); this._onSyncError(_context7.t0, syncOptions); return _context7.abrupt("return"); case 18: _context7.prev = 18; this._currentSyncRequest = null; return _context7.finish(18); case 21: //debuglog('Completed sync, next_batch=' + data.next_batch); // set the sync token NOW *before* processing the events. We do this so // if something barfs on an event we can skip it rather than constantly // polling with the same token. client.store.setSyncToken(data.next_batch); // Reset after a successful sync this._failedSyncCount = 0; _context7.next = 25; return client.store.setSyncData(data); case 25: syncEventData = { oldSyncToken: syncToken, nextSyncToken: data.next_batch, catchingUp: this._catchingUp }; if (!this.opts.crypto) { _context7.next = 29; break; } _context7.next = 29; return this.opts.crypto.onSyncWillProcess(syncEventData); case 29: _context7.prev = 29; _context7.next = 32; return this._processSyncResponse(syncEventData, data); case 32: _context7.next = 38; break; case 34: _context7.prev = 34; _context7.t1 = _context7["catch"](29); // log the exception with stack if we have it, else fall back // to the plain description _logger.logger.error("Caught /sync error", _context7.t1.stack || _context7.t1); // Emit the exception for client handling this.client.emit("sync.unexpectedError", _context7.t1); case 38: // update this as it may have changed syncEventData.catchingUp = this._catchingUp; // emit synced events if (!syncOptions.hasSyncedBefore) { this._updateSyncState("PREPARED", syncEventData); syncOptions.hasSyncedBefore = true; } // tell the crypto module to do its processing. It may block (to do a // /keys/changes request). if (!this.opts.crypto) { _context7.next = 43; break; } _context7.next = 43; return this.opts.crypto.onSyncCompleted(syncEventData); case 43: // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates this._updateSyncState("SYNCING", syncEventData); if (!client.store.wantsSave()) { _context7.next = 49; break; } if (!this.opts.crypto) { _context7.next = 48; break; } _context7.next = 48; return this.opts.crypto.saveDeviceList(0); case 48: // tell databases that everything is now in a consistent state and can be saved. client.store.save(); case 49: // Begin next sync this._sync(syncOptions); case 50: case "end": return _context7.stop(); } } }, _callee7, this, [[7, 14, 18, 21], [29, 34]]); })); return function (_x5) { return _ref5.apply(this, arguments); }; }(); SyncApi.prototype._doSyncRequest = function (syncOptions, syncToken) { var qps = this._getSyncParams(syncOptions, syncToken); return this.client._http.authedRequest(undefined, "GET", "/sync", qps, undefined, qps.timeout + BUFFER_PERIOD_MS); }; SyncApi.prototype._getSyncParams = function (syncOptions, syncToken) { var pollTimeout = this.opts.pollTimeout; if (this.getSyncState() !== 'SYNCING' || this._catchingUp) { // unless we are happily syncing already, we want the server to return // as quickly as possible, even if there are no events queued. This // serves two purposes: // // * When the connection dies, we want to know asap when it comes back, // so that we can hide the error from the user. (We don't want to // have to wait for an event or a timeout). // // * We want to know if the server has any to_device messages queued up // for us. We do that by calling it with a zero timeout until it // doesn't give us any more to_device messages. this._catchingUp = true; pollTimeout = 0; } var filterId = syncOptions.filterId; if (this.client.isGuest() && !filterId) { filterId = this._getGuestFilter(); } var qps = { filter: filterId, timeout: pollTimeout }; if (this.opts.disablePresence) { qps.set_presence = "offline"; } if (syncToken) { qps.since = syncToken; } else { // use a cachebuster for initialsyncs, to make sure that // we don't get a stale sync // (https://github.com/vector-im/vector-web/issues/1354) qps._cacheBuster = Date.now(); } if (this.getSyncState() == 'ERROR' || this.getSyncState() == 'RECONNECTING') { // we think the connection is dead. If it comes back up, we won't know // about it till /sync returns. If the timeout= is high, this could // be a long time. Set it to 0 when doing retries so we don't have to wait // for an event or a timeout before emiting the SYNCING event. qps.timeout = 0; } return qps; }; SyncApi.prototype._onSyncError = function (err, syncOptions) { var _this2 = this; if (!this._running) { debuglog("Sync no longer running: exiting"); if (this._connectionReturnedDefer) { this._connectionReturnedDefer.reject(); this._connectionReturnedDefer = null; } this._updateSyncState("STOPPED"); return; } _logger.logger.error("/sync error %s", err); _logger.logger.error(err); if (this._shouldAbortSync(err)) { return; } this._failedSyncCount++; _logger.logger.log('Number of consecutive failed sync requests:', this._failedSyncCount); debuglog("Starting keep-alive"); // Note that we do *not* mark the sync connection as // lost yet: we only do this if a keepalive poke // fails, since long lived HTTP connections will // go away sometimes and we shouldn't treat this as // erroneous. We set the state to 'reconnecting' // instead, so that clients can observe this state // if they wish. this._startKeepAlives().then(function (connDidFail) { // Only emit CATCHUP if we detected a connectivity error: if we didn't, // it's quite likely the sync will fail again for the same reason and we // want to stay in ERROR rather than keep flip-flopping between ERROR // and CATCHUP. if (connDidFail && _this2.getSyncState() === 'ERROR') { _this2._updateSyncState("CATCHUP", { oldSyncToken: null, nextSyncToken: null, catchingUp: true }); } _this2._sync(syncOptions); }); this._currentSyncRequest = null; // Transition from RECONNECTING to ERROR after a given number of failed syncs this._updateSyncState(this._failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ? "ERROR" : "RECONNECTING", { error: err }); }; /** * Process data returned from a sync response and propagate it * into the model objects * * @param {Object} syncEventData Object containing sync tokens associated with this sync * @param {Object} data The response from /sync */ SyncApi.prototype._processSyncResponse = /*#__PURE__*/function () { var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(syncEventData, data) { var client, self, events, prevEventsMap, cancelledKeyVerificationTxns, inviteRooms, joinRooms, leaveRooms, currentCount; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: client = this.client; self = this; // data looks like: // { // next_batch: $token, // presence: { events: [] }, // account_data: { events: [] }, // device_lists: { changed: ["@user:server", ... ]}, // to_device: { events: [] }, // device_one_time_keys_count: { signed_curve25519: 42 }, // rooms: { // invite: { // $roomid: { // invite_state: { events: [] } // } // }, // join: { // $roomid: { // state: { events: [] }, // timeline: { events: [], prev_batch: $token, limited: true }, // ephemeral: { events: [] }, // summary: { // m.heroes: [ $user_id ], // m.joined_member_count: $count, // m.invited_member_count: $count // }, // account_data: { events: [] }, // unread_notifications: { // highlight_count: 0, // notification_count: 0, // } // } // }, // leave: { // $roomid: { // state: { events: [] }, // timeline: { events: [], prev_batch: $token } // } // } // }, // groups: { // invite: { // $groupId: { // inviter: $inviter, // profile: { // avatar_url: $avatarUrl, // name: $groupName, // }, // }, // }, // join: {}, // leave: {}, // }, // } // TODO-arch: // - Each event we pass through needs to be emitted via 'event', can we // do this in one place? // - The isBrandNewRoom boilerplate is boilerplatey. // handle presence events (User objects) if (data.presence && utils.isArray(data.presence.events)) { data.presence.events.map(client.getEventMapper()).forEach(function (presenceEvent) { var user = client.store.getUser(presenceEvent.getSender()); if (user) { user.setPresenceEvent(presenceEvent); } else { user = createNewUser(client, presenceEvent.getSender()); user.setPresenceEvent(presenceEvent); client.store.storeUser(user); } client.emit("event", presenceEvent); }); } // handle non-room account_data if (data.account_data && utils.isArray(data.account_data.events)) { events = data.account_data.events.map(client.getEventMapper()); prevEventsMap = events.reduce(function (m, c) { m[c.getId()] = client.store.getAccountData(c.getType()); return m; }, {}); client.store.storeAccountDataEvents(events); events.forEach(function (accountDataEvent) { // Honour push rules that come down the sync stream but also // honour push rules that were previously cached. Base rules // will be updated when we receive push rules via getPushRules // (see SyncApi.prototype.sync) before syncing over the network. if (accountDataEvent.getType() === 'm.push_rules') { var rules = accountDataEvent.getContent(); client.pushRules = _pushprocessor.PushProcessor.rewriteDefaultRules(rules); } var prevEvent = prevEventsMap[accountDataEvent.getId()]; client.emit("accountData", accountDataEvent, prevEvent); return accountDataEvent; }); } // handle to-device events if (data.to_device && utils.isArray(data.to_device.events) && data.to_device.events.length > 0) { cancelledKeyVerificationTxns = []; data.to_device.events.map(client.getEventMapper()).map(function (toDeviceEvent) { // map is a cheap inline forEach // We want to flag m.key.verification.start events as cancelled // if there's an accompanying m.key.verification.cancel event, so // we pull out the transaction IDs from the cancellation events // so we can flag the verification events as cancelled in the loop // below. if (toDeviceEvent.getType() === "m.key.verification.cancel") { var txnId = toDeviceEvent.getContent()['transaction_id']; if (txnId) { cancelledKeyVerificationTxns.push(txnId); } } // as mentioned above, .map is a cheap inline forEach, so return // the unmodified event. return toDeviceEvent; }).forEach(function (toDeviceEvent) { var content = toDeviceEvent.getContent(); if (toDeviceEvent.getType() == "m.room.message" && content.msgtype == "m.bad.encrypted") { // the mapper already logged a warning. _logger.logger.log('Ignoring undecryptable to-device event from ' + toDeviceEvent.getSender()); return; } if (toDeviceEvent.getType() === "m.key.verification.start" || toDeviceEvent.getType() === "m.key.verification.request") { var txnId = content['transaction_id']; if (cancelledKeyVerificationTxns.includes(txnId)) { toDeviceEvent.flagCancelled(); } } client.emit("toDeviceEvent", toDeviceEvent); }); } else { // no more to-device events: we can stop polling with a short timeout. this._catchingUp = false; } if (data.groups) { if (data.groups.invite) { this._processGroupSyncEntry(data.groups.invite, 'invite'); } if (data.groups.join) { this._processGroupSyncEntry(data.groups.join, 'join'); } if (data.groups.leave) { this._processGroupSyncEntry(data.groups.leave, 'leave'); } } // the returned json structure is a bit crap, so make it into a // nicer form (array) after applying sanity to make sure we don't fail // on missing keys (on the off chance) inviteRooms = []; joinRooms = []; leaveRooms = []; if (data.rooms) { if (data.rooms.invite) { inviteRooms = this._mapSyncResponseToRoomArray(data.rooms.invite); } if (data.rooms.join) { joinRooms = this._mapSyncResponseToRoomArray(data.rooms.join); } if (data.rooms.leave) { leaveRooms = this._mapSyncResponseToRoomArray(data.rooms.leave); } } this._notifEvents = []; // Handle invites inviteRooms.forEach(function (inviteObj) { var room = inviteObj.room; var stateEvents = self._mapSyncEventsFormat(inviteObj.invite_state, room); self._processRoomEvents(room, stateEvents); if (inviteObj.isBrandNewRoom) { room.recalculate(); client.store.storeRoom(room); client.emit("Room", room); } stateEvents.forEach(function (e) { client.emit("event", e); }); room.updateMyMembership("invite"); }); // Handle joins _context10.next = 14; return utils.promiseMapSeries(joinRooms, /*#__PURE__*/function () { var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(joinObj) { var room, stateEvents, timelineEvents, ephemeralEvents, accountDataEvents, encrypted, limited, i, eventId, processRoomEvent, _processRoomEvent; return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _processRoomEvent = function _processRoomEvent3() { _processRoomEvent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(e) { var user; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: client.emit("event", e); if (!(e.isState() && e.getType() == "m.room.encryption" && self.opts.crypto)) { _context8.next = 4; break; } _context8.next = 4; return self.opts.crypto.onCryptoEvent(e); case 4: if (e.isState() && e.getType() === "im.vector.user_status") { user = client.store.getUser(e.getStateKey()); if (user) { user._unstable_updateStatusMessage(e); } else { user = createNewUser(client, e.getStateKey()); user._unstable_updateStatusMessage(e); client.store.storeUser(user); } } case 5: case "end": return _context8.stop(); } } }, _callee8); })); return _processRoomEvent.apply(this, arguments); }; processRoomEvent = function _processRoomEvent2(_x9) { return _processRoomEvent.apply(this, arguments); }; room = joinObj.room; stateEvents = self._mapSyncEventsFormat(joinObj.state, room); timelineEvents = self._mapSyncEventsFormat(joinObj.timeline, room); ephemeralEvents = self._mapSyncEventsFormat(joinObj.ephemeral); accountDataEvents = self._mapSyncEventsFormat(joinObj.account_data); // we do this first so it's correct when any of the events fire if (joinObj.unread_notifications) { room.setUnreadNotificationCount('total', joinObj.unread_notifications.notification_count); // We track unread notifications ourselves in encrypted rooms, so don't // bother setting it here. We trust our calculations better than the // server's for this case, and therefore will assume that our non-zero // count is accurate. encrypted = client.isRoomEncrypted(room.roomId); if (!encrypted || encrypted && room.getUnreadNotificationCount('highlight') <= 0) { room.setUnreadNotificationCount('highlight', joinObj.unread_notifications.highlight_count); } } joinObj.timeline = joinObj.timeline || {}; if (!joinObj.isBrandNewRoom) { _context9.next = 13; break; } // set the back-pagination token. Do this *before* adding any // events so that clients can start back-paginating. room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, _eventTimeline.EventTimeline.BACKWARDS); _context9.next = 27; break; case 13: if (!joinObj.timeline.limited) { _context9.next = 27; break; } limited = true; // we've got a limited sync, so we *probably* have a gap in the // timeline, so should reset. But we might have been peeking or // paginating and already have some of the events, in which // case we just want to append any subsequent events to the end // of the existing timeline. // // This is particularly important in the case that we already have // *all* of the events in the timeline - in that case, if we reset // the timeline, we'll end up with an entirely empty timeline, // which we'll try to paginate but not get any new events (which // will stop us linking the empty timeline into the chain). // i = timelineEvents.length - 1; case 16: if (!(i >= 0)) { _context9.next = 26; break; } eventId = timelineEvents[i].getId(); if (!room.getTimelineForEvent(eventId)) { _context9.next = 23; break; } debuglog("Already have event " + eventId + " in limited " + "sync - not resetting"); limited = false; // we might still be missing some of the events before i; // we don't want to be adding them to the end of the // timeline because that would put them out of order. timelineEvents.splice(0, i); // XXX: there's a problem here if the skipped part of the // timeline modifies the state set in stateEvents, because // we'll end up using the state from stateEvents rather // than the later state from timelineEvents. We probably // need to wind stateEvents forward over the events we're // skipping. return _context9.abrupt("break", 26); case 23: i--; _context9.next = 16; break; case 26: if (limited) { self._deregisterStateListeners(room); room.resetLiveTimeline(joinObj.timeline.prev_batch, self.opts.canResetEntireTimeline(room.roomId) ? null : syncEventData.oldSyncToken); // We have to assume any gap in any timeline is // reason to stop incrementally tracking notifications and // reset the timeline. client.resetNotifTimelineSet(); self._registerStateListeners(room); } case 27: self._processRoomEvents(room, stateEvents, timelineEvents, syncEventData.fromCache); // set summary after processing events, // because it will trigger a name calculation // which needs the room state to be up to date if (joinObj.summary) { room.setSummary(joinObj.summary); } // we deliberately don't add ephemeral events to the timeline room.addEphemeralEvents(ephemeralEvents); // we deliberately don't add accountData to the timeline room.addAccountData(accountDataEvents); room.recalculate(); if (joinObj.isBrandNewRoom) { client.store.storeRoom(room); client.emit("Room", room); } self._processEventsForNotifs(room, timelineEvents); _context9.next = 36; return utils.promiseMapSeries(stateEvents, processRoomEvent); case 36: _context9.next = 38; return utils.promiseMapSeries(timelineEvents, processRoomEvent); case 38: ephemeralEvents.forEach(function (e) { client.emit("event", e); }); accountDataEvents.forEach(function (e) { client.emit("event", e); }); room.updateMyMembership("join"); case 41: case "end": return _context9.stop(); } } }, _callee9); })); return function (_x8) { return _ref7.apply(this, arguments); }; }()); case 14: // Handle leaves (e.g. kicked rooms) leaveRooms.forEach(function (leaveObj) { var room = leaveObj.room; var stateEvents = self._mapSyncEventsFormat(leaveObj.state, room); var timelineEvents = self._mapSyncEventsFormat(leaveObj.timeline, room); var accountDataEvents = self._mapSyncEventsFormat(leaveObj.account_data); self._processRoomEvents(room, stateEvents, timelineEvents); room.addAccountData(accountDataEvents); room.recalculate(); if (leaveObj.isBrandNewRoom) { client.store.storeRoom(room); client.emit("Room", room); } self._processEventsForNotifs(room, timelineEvents); stateEvents.forEach(function (e) { client.emit("event", e); }); timelineEvents.forEach(function (e) { client.emit("event", e); }); accountDataEvents.forEach(function (e) { client.emit("event", e); }); room.updateMyMembership("leave"); }); // update the notification timeline, if appropriate. // we only do this for live events, as otherwise we can't order them sanely // in the timeline relative to ones paginated in by /notifications. // XXX: we could fix this by making EventTimeline support chronological // ordering... but it doesn't, right now. if (syncEventData.oldSyncToken && this._notifEvents.length) { this._notifEvents.sort(function (a, b) { return a.getTs() - b.getTs(); }); this._notifEvents.forEach(function (event) { client.getNotifTimelineSet().addLiveEvent(event); }); } // Handle device list updates if (!data.device_lists) { _context10.next = 22; break; } if (!this.opts.crypto) { _context10.next = 22; break; } _context10.next = 20; return this.opts.crypto.handleDeviceListChanges(syncEventData, data.device_lists); case 20: _context10.next = 22; break; case 22: // Handle one_time_keys_count if (this.opts.crypto && data.device_one_time_keys_count) { currentCount = data.device_one_time_keys_count.signed_curve25519 || 0; this.opts.crypto.updateOneTimeKeyCount(currentCount); } case 23: case "end": return _context10.stop(); } } }, _callee10, this); })); return function (_x6, _x7) { return _ref6.apply(this, arguments); }; }(); /** * Starts polling the connectivity check endpoint * @param {number} delay How long to delay until the first poll. * defaults to a short, randomised interval (to prevent * tightlooping if /versions succeeds but /sync etc. fail). * @return {promise} which resolves once the connection returns */ SyncApi.prototype._startKeepAlives = function (delay) { if (delay === undefined) { delay = 2000 + Math.floor(Math.random() * 5000); } if (this._keepAliveTimer !== null) { clearTimeout(this._keepAliveTimer); } var self = this; if (delay > 0) { self._keepAliveTimer = setTimeout(self._pokeKeepAlive.bind(self), delay); } else { self._pokeKeepAlive(); } if (!this._connectionReturnedDefer) { this._connectionReturnedDefer = utils.defer(); } return this._connectionReturnedDefer.promise; }; /** * Make a dummy call to /_matrix/client/versions, to see if the HS is * reachable. * * On failure, schedules a call back to itself. On success, resolves * this._connectionReturnedDefer. * * @param {bool} connDidFail True if a connectivity failure has been detected. Optional. */ SyncApi.prototype._pokeKeepAlive = function (connDidFail) { if (connDidFail === undefined) connDidFail = false; var self = this; function success() { clearTimeout(self._keepAliveTimer); if (self._connectionReturnedDefer) { self._connectionReturnedDefer.resolve(connDidFail); self._connectionReturnedDefer = null; } } this.client._http.request(undefined, // callback "GET", "/_matrix/client/versions", undefined, // queryParams undefined, // data { prefix: '', localTimeoutMs: 15 * 1000 }).then(function () { success(); }, function (err) { if (err.httpStatus == 400 || err.httpStatus == 404) { // treat this as a success because the server probably just doesn't // support /versions: point is, we're getting a response. // We wait a short time though, just in case somehow the server // is in a mode where it 400s /versions responses and sync etc. // responses fail, this will mean we don't hammer in a loop. self._keepAliveTimer = setTimeout(success, 2000); } else { connDidFail = true; self._keepAliveTimer = setTimeout(self._pokeKeepAlive.bind(self, connDidFail), 5000 + Math.floor(Math.random() * 5000)); // A keepalive has failed, so we emit the // error state (whether or not this is the // first failure). // Note we do this after setting the timer: // this lets the unit tests advance the mock // clock when they get the error. self._updateSyncState("ERROR", { error: err }); } }); }; /** * @param {Object} groupsSection Groups section object, eg. response.groups.invite * @param {string} sectionName Which section this is ('invite', 'join' or 'leave') */ SyncApi.prototype._processGroupSyncEntry = function (groupsSection, sectionName) { // Processes entries from 'groups' section of the sync stream for (var _i = 0, _Object$keys = Object.keys(groupsSection); _i < _Object$keys.length; _i++) { var groupId = _Object$keys[_i]; var groupInfo = groupsSection[groupId]; var group = this.client.store.getGroup(groupId); var isBrandNew = group === null; if (group === null) { group = this.createGroup(groupId); } if (groupInfo.profile) { group.setProfile(groupInfo.profile.name, groupInfo.profile.avatar_url); } if (groupInfo.inviter) { group.setInviter({ userId: groupInfo.inviter }); } group.setMyMembership(sectionName); if (isBrandNew) { // Now we've filled in all the fields, emit the Group event this.client.emit("Group", group); } } }; /** * @param {Object} obj * @return {Object[]} */ SyncApi.prototype._mapSyncResponseToRoomArray = function (obj) { // Maps { roomid: {stuff}, roomid: {stuff} } // to // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}] var client = this.client; var self = this; return utils.keys(obj).map(function (roomId) { var arrObj = obj[roomId]; var room = client.store.getRoom(roomId); var isBrandNewRoom = false; if (!room) { room = self.createRoom(roomId); isBrandNewRoom = true; } arrObj.room = room; arrObj.isBrandNewRoom = isBrandNewRoom; return arrObj; }); }; /** * @param {Object} obj * @param {Room} room * @return {MatrixEvent[]} */ SyncApi.prototype._mapSyncEventsFormat = function (obj, room) { if (!obj || !utils.isArray(obj.events)) { return []; } var mapper = this.client.getEventMapper(); return obj.events.map(function (e) { if (room) { e.room_id = room.roomId; } return mapper(e); }); }; /** * @param {Room} room */ SyncApi.prototype._resolveInvites = function (room) { if (!room || !this.opts.resolveInvitesToProfiles) { return; } var client = this.client; // For each invited room member we want to give them a displayname/avatar url // if they have one (the m.room.member invites don't contain this). room.getMembersWithMembership("invite").forEach(function (member) { if (member._requestedProfileInfo) { return; } member._requestedProfileInfo = true; // try to get a cached copy first. var user = client.getUser(member.userId); var promise; if (user) { promise = Promise.resolve({ avatar_url: user.avatarUrl, displayname: user.displayName }); } else { promise = client.getProfileInfo(member.userId); } promise.then(function (info) { // slightly naughty by doctoring the invite event but this means all // the code paths remain the same between invite/join display name stuff // which is a worthy trade-off for some minor pollution. var inviteEvent = member.events.member; if (inviteEvent.getContent().membership !== "invite") { // between resolving and now they have since joined, so don't clobber return; } inviteEvent.getContent().avatar_url = info.avatar_url; inviteEvent.getContent().displayname = info.displayname; // fire listeners member.setMembershipEvent(inviteEvent, room.currentState); }, function (err) {// OH WELL. }); }); }; /** * @param {Room} room * @param {MatrixEvent[]} stateEventList A list of state events. This is the state * at the *START* of the timeline list if it is supplied. * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index * @param {boolean} fromCache whether the sync response came from cache * is earlier in time. Higher index is later. */ SyncApi.prototype._processRoomEvents = function (room, stateEventList, timelineEventList, fromCache) { // If there are no events in the timeline yet, initialise it with // the given state events var liveTimeline = room.getLiveTimeline(); var timelineWasEmpty = liveTimeline.getEvents().length == 0; if (timelineWasEmpty) { // Passing these events into initialiseState will freeze them, so we need // to compute and cache the push actions for them now, otherwise sync dies // with an attempt to assign to read only property. // XXX: This is pretty horrible and is assuming all sorts of behaviour from // these functions that it shouldn't be. We should probably either store the // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise // find some solution where MatrixEvents are immutable but allow for a cache // field. var _iterator = _createForOfIteratorHelper(stateEventList), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var ev = _step.value; this.client.getPushActionsForEvent(ev); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } liveTimeline.initialiseState(stateEventList); } this._resolveInvites(room); // recalculate the room name at this point as adding events to the timeline // may make notifications appear which should have the right name. // XXX: This looks suspect: we'll end up recalculating the room once here // and then again after adding events (_processSyncResponse calls it after // calling us) even if no state events were added. It also means that if // one of the room events in timelineEventList is something that needs // a recalculation (like m.room.name) we won't recalculate until we've // finished adding all the events, which will cause the notification to have // the old room name rather than the new one. room.recalculate(); // If the timeline wasn't empty, we process the state events here: they're // defined as updates to the state before the start of the timeline, so this // starts to roll the state forward. // XXX: That's what we *should* do, but this can happen if we were previously // peeking in a room, in which case we obviously do *not* want to add the // state events here onto the end of the timeline. Historically, the js-sdk // has just set these new state events on the old and new state. This seems // very wrong because there could be events in the timeline that diverge the // state, in which case this is going to leave things out of sync. However, // for now I think it;s best to behave the same as the code has done previously. if (!timelineWasEmpty) { // XXX: As above, don't do this... //room.addLiveEvents(stateEventList || []); // Do this instead... room.oldState.setStateEvents(stateEventList || []); room.currentState.setStateEvents(stateEventList || []); } // execute the timeline events. This will continue to diverge the current state // if the timeline has any state events in it. // This also needs to be done before running push rules on the events as they need // to be decorated with sender etc. room.addLiveEvents(timelineEventList || [], null, fromCache); }; /** * Takes a list of timelineEvents and adds and adds to _notifEvents * as appropriate. * This must be called after the room the events belong to has been stored. * * @param {Room} room * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index * is earlier in time. Higher index is later. */ SyncApi.prototype._processEventsForNotifs = function (room, timelineEventList) { // gather our notifications into this._notifEvents if (this.client.getNotifTimelineSet()) { for (var i = 0; i < timelineEventList.length; i++) { var pushActions = this.client.getPushActionsForEvent(timelineEventList[i]); if (pushActions && pushActions.notify && pushActions.tweaks && pushActions.tweaks.highlight) { this._notifEvents.push(timelineEventList[i]); } } } }; /** * @return {string} */ SyncApi.prototype._getGuestFilter = function () { var guestRooms = this.client._guestRooms; // FIXME: horrible gut-wrenching if (!guestRooms) { return "{}"; } // we just need to specify the filter inline if we're a guest because guests // can't create filters. return JSON.stringify({ room: { timeline: { limit: 20 } } }); }; /** * Sets the sync state and emits an event to say so * @param {String} newState The new state string * @param {Object} data Object of additional data to emit in the event */ SyncApi.prototype._updateSyncState = function (newState, data) { var old = this._syncState; this._syncState = newState; this._syncStateData = data; this.client.emit("sync", this._syncState, old, data); }; /** * Event handler for the 'online' event * This event is generally unreliable and precise behaviour * varies between browsers, so we poll for connectivity too, * but this might help us reconnect a little faster. */ SyncApi.prototype._onOnline = function () { debuglog("Browser thinks we are back online"); this._startKeepAlives(0); }; function createNewUser(client, userId) { var user = new _user.User(userId); client.reEmitter.reEmit(user, ["User.avatarUrl", "User.displayName", "User.presence", "User.currentlyActive", "User.lastPresenceTs"]); return user; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./errors":89,"./filter":91,"./logger":95,"./models/event-timeline":99,"./models/group":101,"./models/room":106,"./models/user":108,"./pushprocessor":109,"./utils":123,"@babel/runtime/helpers/asyncToGenerator":5,"@babel/runtime/helpers/interopRequireDefault":12,"@babel/runtime/helpers/interopRequireWildcard":13,"@babel/runtime/regenerator":27}],122:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimelineWindow = TimelineWindow; exports.TimelineIndex = TimelineIndex; var _eventTimeline = require("./models/event-timeline"); var _logger = require("./logger"); /* Copyright 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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 timeline-window */ /** * @private */ var DEBUG = false; /** * @private */ var debuglog = DEBUG ? _logger.logger.log.bind(_logger.logger) : function () {}; /** * the number of times we ask the server for more events before giving up * * @private */ var DEFAULT_PAGINATE_LOOP_LIMIT = 5; /** * Construct a TimelineWindow. * *

This abstracts the separate timelines in a Matrix {@link * module:models/room|Room} into a single iterable thing. It keeps track of * the start and endpoints of the window, which can be advanced with the help * of pagination requests. * *

Before the window is useful, it must be initialised by calling {@link * module:timeline-window~TimelineWindow#load|load}. * *

Note that the window will not automatically extend itself when new events * are received from /sync; you should arrange to call {@link * module:timeline-window~TimelineWindow#paginate|paginate} on {@link * module:client~MatrixClient.event:"Room.timeline"|Room.timeline} events. * * @param {MatrixClient} client MatrixClient to be used for context/pagination * requests. * * @param {EventTimelineSet} timelineSet The timelineSet to track * * @param {Object} [opts] Configuration options for this window * * @param {number} [opts.windowLimit = 1000] maximum number of events to keep * in the window. If more events are retrieved via pagination requests, * excess events will be dropped from the other end of the window. * * @constructor */ function TimelineWindow(client, timelineSet, opts) { opts = opts || {}; this._client = client; this._timelineSet = timelineSet; // these will be TimelineIndex objects; they delineate the 'start' and // 'end' of the window. // // _start.index is inclusive; _end.index is exclusive. this._start = null; this._end = null; this._eventCount = 0; this._windowLimit = opts.windowLimit || 1000; } /** * Initialise the window to point at a given event, or the live timeline * * @param {string} [initialEventId] If given, the window will contain the * given event * @param {number} [initialWindowSize = 20] Size of the initial window * * @return {Promise} */ TimelineWindow.prototype.load = function (initialEventId, initialWindowSize) { var self = this; initialWindowSize = initialWindowSize || 20; // given an EventTimeline, find the event we were looking for, and initialise our // fields so that the event in question is in the middle of the window. var initFields = function initFields(timeline) { var eventIndex; var events = timeline.getEvents(); if (!initialEventId) { // we were looking for the live timeline: initialise to the end eventIndex = events.length; } else { for (var i = 0; i < events.length; i++) { if (events[i].getId() == initialEventId) { eventIndex = i; break; } } if (eventIndex === undefined) { throw new Error("getEventTimeline result didn't include requested event"); } } var endIndex = Math.min(events.length, eventIndex + Math.ceil(initialWindowSize / 2)); var startIndex = Math.max(0, endIndex - initialWindowSize); self._start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex()); self._end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex()); self._eventCount = endIndex - startIndex; }; // We avoid delaying the resolution of the promise by a reactor tick if // we already have the data we need, which is important to keep room-switching // feeling snappy. // if (initialEventId) { var timeline = this._timelineSet.getTimelineForEvent(initialEventId); if (timeline) { // hot-path optimization to save a reactor tick by replicating the sync check getTimelineForEvent does. initFields(timeline); return Promise.resolve(timeline); } var prom = this._client.getEventTimeline(this._timelineSet, initialEventId); return prom.then(initFields); } else { var tl = this._timelineSet.getLiveTimeline(); initFields(tl); return Promise.resolve(); } }; /** * Get the TimelineIndex of the window in the given direction. * * @param {string} direction EventTimeline.BACKWARDS to get the TimelineIndex * at the start of the window; EventTimeline.FORWARDS to get the TimelineIndex at * the end. * * @return {TimelineIndex} The requested timeline index if one exists, null * otherwise. */ TimelineWindow.prototype.getTimelineIndex = function (direction) { if (direction == _eventTimeline.EventTimeline.BACKWARDS) { return this._start; } else if (direction == _eventTimeline.EventTimeline.FORWARDS) { return this._end; } else { throw new Error("Invalid direction '" + direction + "'"); } }; /** * Try to extend the window using events that are already in the underlying * TimelineIndex. * * @param {string} direction EventTimeline.BACKWARDS to try extending it * backwards; EventTimeline.FORWARDS to try extending it forwards. * @param {number} size number of events to try to extend by. * * @return {boolean} true if the window was extended, false otherwise. */ TimelineWindow.prototype.extend = function (direction, size) { var tl = this.getTimelineIndex(direction); if (!tl) { debuglog("TimelineWindow: no timeline yet"); return false; } var count = direction == _eventTimeline.EventTimeline.BACKWARDS ? tl.retreat(size) : tl.advance(size); if (count) { this._eventCount += count; debuglog("TimelineWindow: increased cap by " + count + " (now " + this._eventCount + ")"); // remove some events from the other end, if necessary var excess = this._eventCount - this._windowLimit; if (excess > 0) { this.unpaginate(excess, direction != _eventTimeline.EventTimeline.BACKWARDS); } return true; } return false; }; /** * Check if this window can be extended * *

This returns true if we either have more events, or if we have a * pagination token which means we can paginate in that direction. It does not * necessarily mean that there are more events available in that direction at * this time. * * @param {string} direction EventTimeline.BACKWARDS to check if we can * paginate backwards; EventTimeline.FORWARDS to check if we can go forwards * * @return {boolean} true if we can paginate in the given direction */ TimelineWindow.prototype.canPaginate = function (direction) { var tl = this.getTimelineIndex(direction); if (!tl) { debuglog("TimelineWindow: no timeline yet"); return false; } if (direction == _eventTimeline.EventTimeline.BACKWARDS) { if (tl.index > tl.minIndex()) { return true; } } else { if (tl.index < tl.maxIndex()) { return true; } } return Boolean(tl.timeline.getNeighbouringTimeline(direction) || tl.timeline.getPaginationToken(direction)); }; /** * Attempt to extend the window * * @param {string} direction EventTimeline.BACKWARDS to extend the window * backwards (towards older events); EventTimeline.FORWARDS to go forwards. * * @param {number} size number of events to try to extend by. If fewer than this * number are immediately available, then we return immediately rather than * making an API call. * * @param {boolean} [makeRequest = true] whether we should make API calls to * fetch further events if we don't have any at all. (This has no effect if * the room already knows about additional events in the relevant direction, * even if there are fewer than 'size' of them, as we will just return those * we already know about.) * * @param {number} [requestLimit = 5] limit for the number of API requests we * should make. * * @return {Promise} Resolves to a boolean which is true if more events * were successfully retrieved. */ TimelineWindow.prototype.paginate = function (direction, size, makeRequest, requestLimit) { // Either wind back the message cap (if there are enough events in the // timeline to do so), or fire off a pagination request. if (makeRequest === undefined) { makeRequest = true; } if (requestLimit === undefined) { requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT; } var tl = this.getTimelineIndex(direction); if (!tl) { debuglog("TimelineWindow: no timeline yet"); return Promise.resolve(false); } if (tl.pendingPaginate) { return tl.pendingPaginate; } // try moving the cap if (this.extend(direction, size)) { return Promise.resolve(true); } if (!makeRequest || requestLimit === 0) { // todo: should we return something different to indicate that there // might be more events out there, but we haven't found them yet? return Promise.resolve(false); } // try making a pagination request var token = tl.timeline.getPaginationToken(direction); if (!token) { debuglog("TimelineWindow: no token"); return Promise.resolve(false); } debuglog("TimelineWindow: starting request"); var self = this; var prom = this._client.paginateEventTimeline(tl.timeline, { backwards: direction == _eventTimeline.EventTimeline.BACKWARDS, limit: size })["finally"](function () { tl.pendingPaginate = null; }).then(function (r) { debuglog("TimelineWindow: request completed with result " + r); if (!r) { // end of timeline return false; } // recurse to advance the index into the results. // // If we don't get any new events, we want to make sure we keep asking // the server for events for as long as we have a valid pagination // token. In particular, we want to know if we've actually hit the // start of the timeline, or if we just happened to know about all of // the events thanks to https://matrix.org/jira/browse/SYN-645. // // On the other hand, we necessarily want to wait forever for the // server to make its mind up about whether there are other events, // because it gives a bad user experience // (https://github.com/vector-im/vector-web/issues/1204). return self.paginate(direction, size, true, requestLimit - 1); }); tl.pendingPaginate = prom; return prom; }; /** * Remove `delta` events from the start or end of the timeline. * * @param {number} delta number of events to remove from the timeline * @param {boolean} startOfTimeline if events should be removed from the start * of the timeline. */ TimelineWindow.prototype.unpaginate = function (delta, startOfTimeline) { var tl = startOfTimeline ? this._start : this._end; // sanity-check the delta if (delta > this._eventCount || delta < 0) { throw new Error("Attemting to unpaginate " + delta + " events, but " + "only have " + this._eventCount + " in the timeline"); } while (delta > 0) { var count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta); if (count <= 0) { // sadness. This shouldn't be possible. throw new Error("Unable to unpaginate any further, but still have " + this._eventCount + " events"); } delta -= count; this._eventCount -= count; debuglog("TimelineWindow.unpaginate: dropped " + count + " (now " + this._eventCount + ")"); } }; /** * Get a list of the events currently in the window * * @return {MatrixEvent[]} the events in the window */ TimelineWindow.prototype.getEvents = function () { if (!this._start) { // not yet loaded return []; } var result = []; // iterate through each timeline between this._start and this._end // (inclusive). var timeline = this._start.timeline; while (true) { var events = timeline.getEvents(); // For the first timeline in the chain, we want to start at // this._start.index. For the last timeline in the chain, we want to // stop before this._end.index. Otherwise, we want to copy all of the // events in the timeline. // // (Note that both this._start.index and this._end.index are relative // to their respective timelines' BaseIndex). // var startIndex = 0; var endIndex = events.length; if (timeline === this._start.timeline) { startIndex = this._start.index + timeline.getBaseIndex(); } if (timeline === this._end.timeline) { endIndex = this._end.index + timeline.getBaseIndex(); } for (var i = startIndex; i < endIndex; i++) { result.push(events[i]); } // if we're not done, iterate to the next timeline. if (timeline === this._end.timeline) { break; } else { timeline = timeline.getNeighbouringTimeline(_eventTimeline.EventTimeline.FORWARDS); } } return result; }; /** * a thing which contains a timeline reference, and an index into it. * * @constructor * @param {EventTimeline} timeline * @param {number} index * @private */ function TimelineIndex(timeline, index) { this.timeline = timeline; // the indexes are relative to BaseIndex, so could well be negative. this.index = index; } /** * @return {number} the minimum possible value for the index in the current * timeline */ TimelineIndex.prototype.minIndex = function () { return this.timeline.getBaseIndex() * -1; }; /** * @return {number} the maximum possible value for the index in the current * timeline (exclusive - ie, it actually returns one more than the index * of the last element). */ TimelineIndex.prototype.maxIndex = function () { return this.timeline.getEvents().length - this.timeline.getBaseIndex(); }; /** * Try move the index forward, or into the neighbouring timeline * * @param {number} delta number of events to advance by * @return {number} number of events successfully advanced by */ TimelineIndex.prototype.advance = function (delta) { if (!delta) { return 0; } // first try moving the index in the current timeline. See if there is room // to do so. var cappedDelta; if (delta < 0) { // we want to wind the index backwards. // // (this.minIndex() - this.index) is a negative number whose magnitude // is the amount of room we have to wind back the index in the current // timeline. We cap delta to this quantity. cappedDelta = Math.max(delta, this.minIndex() - this.index); if (cappedDelta < 0) { this.index += cappedDelta; return cappedDelta; } } else { // we want to wind the index forwards. // // (this.maxIndex() - this.index) is a (positive) number whose magnitude // is the amount of room we have to wind forward the index in the current // timeline. We cap delta to this quantity. cappedDelta = Math.min(delta, this.maxIndex() - this.index); if (cappedDelta > 0) { this.index += cappedDelta; return cappedDelta; } } // the index is already at the start/end of the current timeline. // // next see if there is a neighbouring timeline to switch to. var neighbour = this.timeline.getNeighbouringTimeline(delta < 0 ? _eventTimeline.EventTimeline.BACKWARDS : _eventTimeline.EventTimeline.FORWARDS); if (neighbour) { this.timeline = neighbour; if (delta < 0) { this.index = this.maxIndex(); } else { this.index = this.minIndex(); } debuglog("paginate: switched to new neighbour"); // recurse, using the next timeline return this.advance(delta); } return 0; }; /** * Try move the index backwards, or into the neighbouring timeline * * @param {number} delta number of events to retreat by * @return {number} number of events successfully retreated by */ TimelineIndex.prototype.retreat = function (delta) { return this.advance(delta * -1) * -1; }; },{"./logger":95,"./models/event-timeline":99}],123:[function(require,module,exports){ "use strict"; /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCrypto = exports.setCrypto = exports.promiseTry = exports.promiseMapSeries = exports.defer = exports.isNullOrUndefined = exports.sleep = exports.ensureNoTrailingSlash = exports.globToRegexp = exports.escapeRegExp = exports.removeHiddenChars = exports.isNumber = exports.polyfillSuper = exports.inherits = exports.runPolyfills = exports.extend = exports.deepCompare = exports.deepCopy = exports.checkObjectHasNoAdditionalKeys = exports.checkObjectHasKeys = exports.isArray = exports.isFunction = exports.removeElement = exports.findElement = exports.forEach = exports.values = exports.keys = exports.filter = exports.map = exports.encodeUri = exports.encodeParams = void 0; /** * This is an internal module. * @module utils */ const unhomoglyph_1 = __importDefault(require("unhomoglyph")); /** * Encode a dictionary of query parameters. * @param {Object} params A dict of key/values to encode e.g. * {"foo": "bar", "baz": "taz"} * @return {string} The encoded string e.g. foo=bar&baz=taz */ function encodeParams(params) { let qs = ""; for (const key in params) { if (!params.hasOwnProperty(key)) { continue; } qs += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); } return qs.substring(1); } exports.encodeParams = encodeParams; /** * Encodes a URI according to a set of template variables. Variables will be * passed through encodeURIComponent. * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'. * @param {Object} variables The key/value pairs to replace the template * variables with. E.g. { "$bar": "baz" }. * @return {string} The result of replacing all template variables e.g. '/foo/baz'. */ function encodeUri(pathTemplate, variables) { for (const key in variables) { if (!variables.hasOwnProperty(key)) { continue; } pathTemplate = pathTemplate.replace(key, encodeURIComponent(variables[key])); } return pathTemplate; } exports.encodeUri = encodeUri; /** * Applies a map function to the given array. * @param {Array} array The array to apply the function to. * @param {Function} fn The function that will be invoked for each element in * the array with the signature fn(element){...} * @return {Array} A new array with the results of the function. */ function map(array, fn) { const results = new Array(array.length); for (let i = 0; i < array.length; i++) { results[i] = fn(array[i]); } return results; } exports.map = map; /** * Applies a filter function to the given array. * @param {Array} array The array to apply the function to. * @param {Function} fn The function that will be invoked for each element in * the array. It should return true to keep the element. The function signature * looks like fn(element, index, array){...}. * @return {Array} A new array with the results of the function. */ function filter(array, fn) { const results = []; for (let i = 0; i < array.length; i++) { if (fn(array[i], i, array)) { results.push(array[i]); } } return results; } exports.filter = filter; /** * Get the keys for an object. Same as Object.keys(). * @param {Object} obj The object to get the keys for. * @return {string[]} The keys of the object. */ function keys(obj) { const result = []; for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } result.push(key); } return result; } exports.keys = keys; /** * Get the values for an object. * @param {Object} obj The object to get the values for. * @return {Array<*>} The values of the object. */ function values(obj) { const result = []; for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } result.push(obj[key]); } return result; } exports.values = values; /** * Invoke a function for each item in the array. * @param {Array} array The array. * @param {Function} fn The function to invoke for each element. Has the * function signature fn(element, index). */ function forEach(array, fn) { for (let i = 0; i < array.length; i++) { fn(array[i], i); } } exports.forEach = forEach; /** * The findElement() method returns a value in the array, if an element in the array * satisfies (returns true) the provided testing function. Otherwise undefined * is returned. * @param {Array} array The array. * @param {Function} fn Function to execute on each value in the array, with the * function signature fn(element, index, array) * @param {boolean} reverse True to search in reverse order. * @return {*} The first value in the array which returns true for * the given function. */ function findElement(array, fn, reverse) { let i; if (reverse) { for (i = array.length - 1; i >= 0; i--) { if (fn(array[i], i, array)) { return array[i]; } } } else { for (i = 0; i < array.length; i++) { if (fn(array[i], i, array)) { return array[i]; } } } } exports.findElement = findElement; /** * The removeElement() method removes the first element in the array that * satisfies (returns true) the provided testing function. * @param {Array} array The array. * @param {Function} fn Function to execute on each value in the array, with the * function signature fn(element, index, array). Return true to * remove this element and break. * @param {boolean} reverse True to search in reverse order. * @return {boolean} True if an element was removed. */ function removeElement(array, fn, reverse) { let i; let removed; if (reverse) { for (i = array.length - 1; i >= 0; i--) { if (fn(array[i], i, array)) { removed = array[i]; array.splice(i, 1); return removed; } } } else { for (i = 0; i < array.length; i++) { if (fn(array[i], i, array)) { removed = array[i]; array.splice(i, 1); return removed; } } } return false; } exports.removeElement = removeElement; /** * Checks if the given thing is a function. * @param {*} value The thing to check. * @return {boolean} True if it is a function. */ function isFunction(value) { return Object.prototype.toString.call(value) === "[object Function]"; } exports.isFunction = isFunction; /** * Checks if the given thing is an array. * @param {*} value The thing to check. * @return {boolean} True if it is an array. */ function isArray(value) { return Array.isArray ? Array.isArray(value) : Boolean(value && value.constructor === Array); } exports.isArray = isArray; /** * Checks that the given object has the specified keys. * @param {Object} obj The object to check. * @param {string[]} keys The list of keys that 'obj' must have. * @throws If the object is missing keys. */ // note using 'keys' here would shadow the 'keys' function defined above function checkObjectHasKeys(obj, keys_) { for (let i = 0; i < keys_.length; i++) { if (!obj.hasOwnProperty(keys_[i])) { throw new Error("Missing required key: " + keys_[i]); } } } exports.checkObjectHasKeys = checkObjectHasKeys; /** * Checks that the given object has no extra keys other than the specified ones. * @param {Object} obj The object to check. * @param {string[]} allowedKeys The list of allowed key names. * @throws If there are extra keys. */ function checkObjectHasNoAdditionalKeys(obj, allowedKeys) { for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } if (allowedKeys.indexOf(key) === -1) { throw new Error("Unknown key: " + key); } } } exports.checkObjectHasNoAdditionalKeys = checkObjectHasNoAdditionalKeys; /** * Deep copy the given object. The object MUST NOT have circular references and * MUST NOT have functions. * @param {Object} obj The object to deep copy. * @return {Object} A copy of the object without any references to the original. */ function deepCopy(obj) { return JSON.parse(JSON.stringify(obj)); } exports.deepCopy = deepCopy; /** * Compare two objects for equality. The objects MUST NOT have circular references. * * @param {Object} x The first object to compare. * @param {Object} y The second object to compare. * * @return {boolean} true if the two objects are equal */ function deepCompare(x, y) { // Inspired by // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249 // Compare primitives and functions. // Also check if both arguments link to the same object. if (x === y) { return true; } if (typeof x !== typeof y) { return false; } // special-case NaN (since NaN !== NaN) if (typeof x === 'number' && isNaN(x) && isNaN(y)) { return true; } // special-case null (since typeof null == 'object', but null.constructor // throws) if (x === null || y === null) { return x === y; } // everything else is either an unequal primitive, or an object if (!(x instanceof Object)) { return false; } // check they are the same type of object if (x.constructor !== y.constructor || x.prototype !== y.prototype) { return false; } // special-casing for some special types of object if (x instanceof RegExp || x instanceof Date) { return x.toString() === y.toString(); } // the object algorithm works for Array, but it's sub-optimal. if (x instanceof Array) { if (x.length !== y.length) { return false; } for (let i = 0; i < x.length; i++) { if (!deepCompare(x[i], y[i])) { return false; } } } else { // disable jshint "The body of a for in should be wrapped in an if // statement" /* jshint -W089 */ // check that all of y's direct keys are in x let p; for (p in y) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } } // finally, compare each of x's keys with y for (p in y) { // eslint-disable-line guard-for-in if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } if (!deepCompare(x[p], y[p])) { return false; } } } /* jshint +W089 */ return true; } exports.deepCompare = deepCompare; /** * Copy properties from one object to another. * * All enumerable properties, included inherited ones, are copied. * * This is approximately equivalent to ES6's Object.assign, except * that the latter doesn't copy inherited properties. * * @param {Object} target The object that will receive new properties * @param {...Object} source Objects from which to copy properties * * @return {Object} target */ function extend(...restParams) { const target = restParams[0] || {}; for (let i = 1; i < restParams.length; i++) { const source = restParams[i]; if (!source) continue; for (const propName in source) { // eslint-disable-line guard-for-in target[propName] = source[propName]; } } return target; } exports.extend = extend; /** * Run polyfills to add Array.map and Array.filter if they are missing. */ function runPolyfills() { // Array.prototype.filter // ======================================================== // SOURCE: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter if (!Array.prototype.filter) { // eslint-disable-next-line no-extend-native Array.prototype.filter = function (fun /*, thisArg*/, ...restProps) { if (this === void 0 || this === null) { throw new TypeError(); } const t = Object(this); const len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } const res = []; const thisArg = restProps ? restProps[0] : void 0; for (let i = 0; i < len; i++) { if (i in t) { const val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } // Array.prototype.map // ======================================================== // SOURCE: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map // Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.io/#x15.4.4.19 if (!Array.prototype.map) { // eslint-disable-next-line no-extend-native Array.prototype.map = function (callback, thisArg) { let T; let k; if (this === null || this === undefined) { throw new TypeError(' this is null or not defined'); } // 1. Let O be the result of calling ToObject passing the |this| // value as the argument. const O = Object(this); // 2. Let lenValue be the result of calling the Get internal // method of O with the argument "length". // 3. Let len be ToUint32(lenValue). const len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. const A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { let kValue; let mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor // { Value: mappedValue, // Writable: true, // Enumerable: true, // Configurable: true }, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, k, { // value: mappedValue, // writable: true, // enumerable: true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; } // Array.prototype.forEach // ======================================================== // SOURCE: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.io/#x15.4.4.18 if (!Array.prototype.forEach) { // eslint-disable-next-line no-extend-native Array.prototype.forEach = function (callback, thisArg) { let T; let k; if (this === null || this === undefined) { throw new TypeError(' this is null or not defined'); } // 1. Let O be the result of calling ToObject passing the |this| value as the // argument. const O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the // argument "length". // 3. Let len be ToUint32(lenValue). const len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0 k = 0; // 7. Repeat, while k < len while (k < len) { let kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with // argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with // argument Pk kValue = O[k]; // ii. Call the Call internal method of callback with T as the this value and // argument list containing kValue, k, and O. callback.call(T, kValue, k, O); } // d. Increase k by 1. k++; } // 8. return undefined }; } } exports.runPolyfills = runPolyfills; /** * Inherit the prototype methods from one constructor into another. This is a * port of the Node.js implementation with an Object.create polyfill. * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ function inherits(ctor, superCtor) { // Add util.inherits from Node.js // Source: // https://github.com/joyent/node/blob/master/lib/util.js // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true, }, }); } exports.inherits = inherits; /** * Polyfills inheritance for prototypes by allowing different kinds of * super types. Typically prototypes would use `SuperType.call(this, params)` * though this doesn't always work in some environments - this function * falls back to using `Object.assign()` to clone a constructed copy * of the super type onto `thisArg`. * @param {any} thisArg The child instance. Modified in place. * @param {any} SuperType The type to act as a super instance * @param {any} params Arguments to supply to the super type's constructor */ function polyfillSuper(thisArg, SuperType, ...params) { try { SuperType.call(thisArg, ...params); } catch (e) { // fall back to Object.assign to just clone the thing const fakeSuper = new SuperType(...params); Object.assign(thisArg, fakeSuper); } } exports.polyfillSuper = polyfillSuper; /** * Returns whether the given value is a finite number without type-coercion * * @param {*} value the value to test * @return {boolean} whether or not value is a finite number without type-coercion */ function isNumber(value) { return typeof value === 'number' && isFinite(value); } exports.isNumber = isNumber; /** * Removes zero width chars, diacritics and whitespace from the string * Also applies an unhomoglyph on the string, to prevent similar looking chars * @param {string} str the string to remove hidden characters from * @return {string} a string with the hidden characters removed */ function removeHiddenChars(str) { if (typeof str === "string") { return unhomoglyph_1.default(str.normalize('NFD').replace(removeHiddenCharsRegex, '')); } return ""; } exports.removeHiddenChars = removeHiddenChars; // Regex matching bunch of unicode control characters and otherwise misleading/invisible characters. // Includes: // various width spaces U+2000 - U+200D // LTR and RTL marks U+200E and U+200F // LTR/RTL and other directional formatting marks U+202A - U+202F // Combining characters U+0300 - U+036F // Zero width no-break space (BOM) U+FEFF // eslint-disable-next-line no-misleading-character-class const removeHiddenCharsRegex = /[\u2000-\u200F\u202A-\u202F\u0300-\u036f\uFEFF\s]/g; function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } exports.escapeRegExp = escapeRegExp; function globToRegexp(glob, extended) { extended = typeof (extended) === 'boolean' ? extended : true; // From // https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132 // Because micromatch is about 130KB with dependencies, // and minimatch is not much better. let pat = escapeRegExp(glob); pat = pat.replace(/\\\*/g, '.*'); pat = pat.replace(/\?/g, '.'); if (extended) { pat = pat.replace(/\\\[(!|)(.*)\\]/g, function (match, p1, p2, offset, string) { const first = p1 && '^' || ''; const second = p2.replace(/\\-/, '-'); return '[' + first + second + ']'; }); } return pat; } exports.globToRegexp = globToRegexp; function ensureNoTrailingSlash(url) { if (url && url.endsWith("/")) { return url.substr(0, url.length - 1); } else { return url; } } exports.ensureNoTrailingSlash = ensureNoTrailingSlash; // Returns a promise which resolves with a given value after the given number of ms function sleep(ms, value) { return new Promise((resolve => { setTimeout(resolve, ms, value); })); } exports.sleep = sleep; function isNullOrUndefined(val) { return val === null || val === undefined; } exports.isNullOrUndefined = isNullOrUndefined; // Returns a Deferred function defer() { let resolve; let reject; const promise = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); return { resolve, reject, promise }; } exports.defer = defer; function promiseMapSeries(promises, fn) { return __awaiter(this, void 0, void 0, function* () { for (const o of yield promises) { yield fn(yield o); } }); } exports.promiseMapSeries = promiseMapSeries; function promiseTry(fn) { return new Promise((resolve) => resolve(fn())); } exports.promiseTry = promiseTry; // We need to be able to access the Node.js crypto library from within the // Matrix SDK without needing to `require("crypto")`, which will fail in // browsers. So `index.ts` will call `setCrypto` to store it, and when we need // it, we can call `getCrypto`. let crypto; function setCrypto(c) { crypto = c; } exports.setCrypto = setCrypto; function getCrypto() { return crypto; } exports.getCrypto = getCrypto; },{"unhomoglyph":50}],124:[function(require,module,exports){ (function (global){ "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.MatrixCall = MatrixCall; exports.setAudioOutput = setAudioOutput; exports.setAudioInput = setAudioInput; exports.setVideoInput = setVideoInput; exports.createNewMatrixCall = createNewMatrixCall; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _logger = require("../logger"); var _events = require("events"); var utils = _interopRequireWildcard(require("../utils")); /* Copyright 2015, 2016 OpenMarket Ltd Copyright 2017 New Vector Ltd Copyright 2019 The Matrix.org Foundation C.I.C. 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. */ /** * This is an internal module. See {@link createNewMatrixCall} for the public API. * @module webrtc/call */ var DEBUG = true; // set true to enable console logging. // events: hangup, error(err), replaced(call), state(state, oldState) /** * Fires whenever an error occurs when call.js encounters an issue with setting up the call. *

* The error given will have a code equal to either `MatrixCall.ERR_LOCAL_OFFER_FAILED` or * `MatrixCall.ERR_NO_USER_MEDIA`. `ERR_LOCAL_OFFER_FAILED` is emitted when the local client * fails to create an offer. `ERR_NO_USER_MEDIA` is emitted when the user has denied access * to their audio/video hardware. * * @event module:webrtc/call~MatrixCall#"error" * @param {Error} err The error raised by MatrixCall. * @example * matrixCall.on("error", function(err){ * console.error(err.code, err); * }); */ /** * Construct a new Matrix Call. * @constructor * @param {Object} opts Config options. * @param {string} opts.roomId The room ID for this call. * @param {Object} opts.webRtc The WebRTC globals from the browser. * @param {boolean} opts.forceTURN whether relay through TURN should be forced. * @param {Object} opts.URL The URL global. * @param {Array} opts.turnServers Optional. A list of TURN servers. * @param {MatrixClient} opts.client The Matrix Client instance to send events to. */ function MatrixCall(opts) { this.roomId = opts.roomId; this.client = opts.client; this.webRtc = opts.webRtc; this.forceTURN = opts.forceTURN; this.URL = opts.URL; // Array of Objects with urls, username, credential keys this.turnServers = opts.turnServers || []; if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) { this.turnServers.push({ urls: [MatrixCall.FALLBACK_ICE_SERVER] }); } utils.forEach(this.turnServers, function (server) { utils.checkObjectHasKeys(server, ["urls"]); }); this.callId = "c" + new Date().getTime() + Math.random(); this.state = 'fledgling'; this.didConnect = false; // A queue for candidates waiting to go out. // We try to amalgamate candidates into a single candidate message where // possible this.candidateSendQueue = []; this.candidateSendTries = 0; // Lookup from opaque queue ID to a promise for media element operations that // need to be serialised into a given queue. Store this per-MatrixCall on the // assumption that multiple matrix calls will never compete for control of the // same DOM elements. this.mediaPromises = Object.create(null); this.screenSharingStream = null; this._answerContent = null; this._sentEndOfCandidates = false; } /** The length of time a call can be ringing for. */ MatrixCall.CALL_TIMEOUT_MS = 60000; /** The fallback ICE server to use for STUN or TURN protocols. */ MatrixCall.FALLBACK_ICE_SERVER = 'stun:turn.matrix.org'; /** An error code when the local client failed to create an offer. */ MatrixCall.ERR_LOCAL_OFFER_FAILED = "local_offer_failed"; /** * An error code when there is no local mic/camera to use. This may be because * the hardware isn't plugged in, or the user has explicitly denied access. */ MatrixCall.ERR_NO_USER_MEDIA = "no_user_media"; /* * Error code used when a call event failed to send * because unknown devices were present in the room */ MatrixCall.ERR_UNKNOWN_DEVICES = "unknown_devices"; /* * Error code usewd when we fail to send the invite * for some reason other than there being unknown devices */ MatrixCall.ERR_SEND_INVITE = "send_invite"; /* * Error code usewd when we fail to send the answer * for some reason other than there being unknown devices */ MatrixCall.ERR_SEND_ANSWER = "send_answer"; utils.inherits(MatrixCall, _events.EventEmitter); /** * Place a voice call to this room. * @throws If you have not specified a listener for 'error' events. */ MatrixCall.prototype.placeVoiceCall = function () { debuglog("placeVoiceCall"); checkForErrorListener(this); _placeCallWithConstraints(this, _getUserMediaVideoContraints('voice')); this.type = 'voice'; }; /** * Place a video call to this room. * @param {Element} remoteVideoElement a <video> DOM element * to render video to. * @param {Element} localVideoElement a <video> DOM element * to render the local camera preview. * @throws If you have not specified a listener for 'error' events. */ MatrixCall.prototype.placeVideoCall = function (remoteVideoElement, localVideoElement) { debuglog("placeVideoCall"); checkForErrorListener(this); this.localVideoElement = localVideoElement; this.remoteVideoElement = remoteVideoElement; _placeCallWithConstraints(this, _getUserMediaVideoContraints('video')); this.type = 'video'; _tryPlayRemoteStream(this); }; /** * Place a screen-sharing call to this room. This includes audio. * This method is EXPERIMENTAL and subject to change without warning. It * only works in Google Chrome and Firefox >= 44. * @param {Element} remoteVideoElement a <video> DOM element * to render video to. * @param {Element} localVideoElement a <video> DOM element * to render the local camera preview. * @throws If you have not specified a listener for 'error' events. */ MatrixCall.prototype.placeScreenSharingCall = /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(remoteVideoElement, localVideoElement) { var self, audioConstraints; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: debuglog("placeScreenSharingCall"); checkForErrorListener(this); this.localVideoElement = localVideoElement; this.remoteVideoElement = remoteVideoElement; self = this; _context.prev = 5; _context.next = 8; return this.webRtc.getDisplayMedia({ 'audio': false }); case 8: self.screenSharingStream = _context.sent; debuglog("Got screen stream, requesting audio stream..."); audioConstraints = _getUserMediaVideoContraints('voice'); _placeCallWithConstraints(self, audioConstraints); _context.next = 17; break; case 14: _context.prev = 14; _context.t0 = _context["catch"](5); self.emit("error", callError(MatrixCall.ERR_NO_USER_MEDIA, "Failed to get screen-sharing stream: " + _context.t0)); case 17: this.type = 'video'; _tryPlayRemoteStream(this); case 19: case "end": return _context.stop(); } } }, _callee, this, [[5, 14]]); })); return function (_x, _x2) { return _ref.apply(this, arguments); }; }(); /** * Play the given HTMLMediaElement, serialising the operation into a chain * of promises to avoid racing access to the element * @param {Element} element HTMLMediaElement element to play * @param {string} queueId Arbitrary ID to track the chain of promises to be used */ MatrixCall.prototype.playElement = function (element, queueId) { _logger.logger.log("queuing play on " + queueId + " and element " + element); // XXX: FIXME: Does this leak elements, given the old promises // may hang around and retain a reference to them? if (this.mediaPromises[queueId]) { // XXX: these promises can fail (e.g. by