element-call-Github/public/browser-matrix.js.map
2021-08-09 11:03:31 -07:00

295 lines
3.0 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"version": 3,
"sources": [
"node_modules/browser-pack/_prelude.js",
"node_modules/@babel/runtime/helpers/arrayLikeToArray.js",
"node_modules/@babel/runtime/helpers/arrayWithHoles.js",
"node_modules/@babel/runtime/helpers/arrayWithoutHoles.js",
"node_modules/@babel/runtime/helpers/assertThisInitialized.js",
"node_modules/@babel/runtime/helpers/asyncToGenerator.js",
"node_modules/@babel/runtime/helpers/classCallCheck.js",
"node_modules/@babel/runtime/helpers/construct.js",
"node_modules/@babel/runtime/helpers/createClass.js",
"node_modules/@babel/runtime/helpers/defineProperty.js",
"node_modules/@babel/runtime/helpers/getPrototypeOf.js",
"node_modules/@babel/runtime/helpers/inherits.js",
"node_modules/@babel/runtime/helpers/interopRequireDefault.js",
"node_modules/@babel/runtime/helpers/interopRequireWildcard.js",
"node_modules/@babel/runtime/helpers/isNativeFunction.js",
"node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js",
"node_modules/@babel/runtime/helpers/iterableToArray.js",
"node_modules/@babel/runtime/helpers/iterableToArrayLimit.js",
"node_modules/@babel/runtime/helpers/nonIterableRest.js",
"node_modules/@babel/runtime/helpers/nonIterableSpread.js",
"node_modules/@babel/runtime/helpers/possibleConstructorReturn.js",
"node_modules/@babel/runtime/helpers/setPrototypeOf.js",
"node_modules/@babel/runtime/helpers/slicedToArray.js",
"node_modules/@babel/runtime/helpers/toConsumableArray.js",
"node_modules/@babel/runtime/helpers/typeof.js",
"node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js",
"node_modules/@babel/runtime/helpers/wrapNativeSuper.js",
"node_modules/@babel/runtime/regenerator/index.js",
"node_modules/another-json/another-json.js",
"node_modules/base-x/src/index.js",
"node_modules/base64-js/index.js",
"node_modules/browser-request/index.js",
"node_modules/browserify/node_modules/punycode/punycode.js",
"node_modules/bs58/index.js",
"node_modules/buffer/index.js",
"node_modules/content-type/index.js",
"node_modules/events/events.js",
"node_modules/ieee754/index.js",
"node_modules/loglevel/lib/loglevel.js",
"node_modules/p-retry/index.js",
"node_modules/process/browser.js",
"node_modules/qs/lib/formats.js",
"node_modules/qs/lib/index.js",
"node_modules/qs/lib/parse.js",
"node_modules/qs/lib/stringify.js",
"node_modules/qs/lib/utils.js",
"node_modules/querystring-es3/decode.js",
"node_modules/querystring-es3/encode.js",
"node_modules/querystring-es3/index.js",
"node_modules/regenerator-runtime/runtime.js",
"node_modules/retry/index.js",
"node_modules/retry/lib/retry.js",
"node_modules/retry/lib/retry_operation.js",
"node_modules/safe-buffer/index.js",
"node_modules/unhomoglyph/data.json",
"node_modules/unhomoglyph/index.js",
"node_modules/url/url.js",
"node_modules/url/util.js",
"src/@types/event.ts",
"src/@types/partials.ts",
"src/NamespacedValue.ts",
"src/ReEmitter.ts",
"src/autodiscovery.js",
"src/browser-index.js",
"src/client.ts",
"src/content-helpers.ts",
"src/content-repo.ts",
"src/crypto/CrossSigning.ts",
"src/crypto/DeviceList.ts",
"src/crypto/EncryptionSetup.ts",
"src/crypto/OlmDevice.js",
"src/crypto/OutgoingRoomKeyRequestManager.ts",
"src/crypto/RoomList.ts",
"src/crypto/SecretStorage.ts",
"src/crypto/aes.ts",
"src/crypto/algorithms/base.ts",
"src/crypto/algorithms/index.ts",
"src/crypto/algorithms/megolm.ts",
"src/crypto/algorithms/olm.ts",
"src/crypto/api.ts",
"src/crypto/backup.ts",
"src/crypto/dehydration.ts",
"src/crypto/deviceinfo.ts",
"src/crypto/index.ts",
"src/crypto/key_passphrase.ts",
"src/crypto/olmlib.ts",
"src/crypto/recoverykey.ts",
"src/crypto/store/indexeddb-crypto-store-backend.js",
"src/crypto/store/indexeddb-crypto-store.js",
"src/crypto/store/localStorage-crypto-store.js",
"src/crypto/store/memory-crypto-store.js",
"src/crypto/verification/Base.js",
"src/crypto/verification/Error.js",
"src/crypto/verification/IllegalMethod.js",
"src/crypto/verification/QRCode.js",
"src/crypto/verification/SAS.js",
"src/crypto/verification/request/InRoomChannel.js",
"src/crypto/verification/request/ToDeviceChannel.js",
"src/crypto/verification/request/VerificationRequest.js",
"src/errors.js",
"src/event-mapper.ts",
"src/filter-component.ts",
"src/filter.ts",
"src/http-api.js",
"src/indexeddb-helpers.js",
"src/interactive-auth.js",
"src/logger.ts",
"src/matrix.ts",
"src/models/MSC3089Branch.ts",
"src/models/MSC3089TreeSpace.ts",
"src/models/event-context.ts",
"src/models/event-timeline-set.ts",
"src/models/event-timeline.ts",
"src/models/event.ts",
"src/models/group.js",
"src/models/relations.ts",
"src/models/room-member.ts",
"src/models/room-state.ts",
"src/models/room-summary.ts",
"src/models/room.ts",
"src/models/search-result.js",
"src/models/user.ts",
"src/pushprocessor.js",
"src/randomstring.ts",
"src/realtime-callbacks.js",
"src/scheduler.js",
"src/service-types.ts",
"src/store/indexeddb-local-backend.js",
"src/store/indexeddb-remote-backend.js",
"src/store/indexeddb.ts",
"src/store/memory.ts",
"src/store/session/webstorage.js",
"src/store/stub.ts",
"src/sync-accumulator.ts",
"src/sync.api.ts",
"src/sync.ts",
"src/timeline-window.ts",
"src/utils.ts",
"src/webrtc/call.ts",
"src/webrtc/callEventHandler.ts",
"src/webrtc/callEventTypes.ts",
"src/webrtc/callFeed.ts"
],
"names": [],
"mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtDA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC9eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACrhBA;AACA;AACA;AACA;AACA;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACjvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5dA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5uBA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxqMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5tBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChBA;;;;;;;;;;;;;;EAcE;;;AAEF,wDAAmD;AAEnD,IAAY,SAqEX;AArED,WAAY,SAAS;IACj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AAC;QAClD,OAAO,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,CAAC;IAED;;;OAGG;IACI,OAAO;QACV,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IACnD,CAAC;IAED,2DAA2D;IAC3D,2DAA2D;IAC3D;;;;OAIG;IACI,YAAY;QACf,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC,MAAM,KAAK,CAAC,CAAC;IACrD,CAAC;IAED;;;;OAIG;IACI,YAAY;QACf,iCAAiC;QACjC,OAAO,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC,MAAM,KAAK,CAAC,CAAC;IACrD,CAAC;IAED;;;;OAIG;IACI,YAAY,CAAC,SAAsB;QACtC,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,CAAC;CACJ;AA1DD,4BA0DC",
"file": "generated.js",
"sourceRoot": "",
"sourcesContent": [
"(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<t.length;i++)o(t[i]);return o}return r})()",
"function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}\n\nmodule.exports = _arrayLikeToArray;",
"function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;",
"var arrayLikeToArray = require(\"./arrayLikeToArray\");\n\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}\n\nmodule.exports = _arrayWithoutHoles;",
"function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nmodule.exports = _assertThisInitialized;",
"function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nfunction _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n}\n\nmodule.exports = _asyncToGenerator;",
"function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;",
"var setPrototypeOf = require(\"./setPrototypeOf\");\n\nvar isNativeReflectConstruct = require(\"./isNativeReflectConstruct\");\n\nfunction _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n module.exports = _construct = Reflect.construct;\n } else {\n module.exports = _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}\n\nmodule.exports = _construct;",
"function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nmodule.exports = _createClass;",
"function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;",
"function _getPrototypeOf(o) {\n module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}\n\nmodule.exports = _getPrototypeOf;",
"var setPrototypeOf = require(\"./setPrototypeOf\");\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}\n\nmodule.exports = _inherits;",
"function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault;",
"var _typeof = require(\"@babel/runtime/helpers/typeof\");\n\nfunction _getRequireWildcardCache() {\n if (typeof WeakMap !== \"function\") return null;\n var cache = new WeakMap();\n\n _getRequireWildcardCache = function _getRequireWildcardCache() {\n return cache;\n };\n\n return cache;\n}\n\nfunction _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n }\n\n if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") {\n return {\n \"default\": obj\n };\n }\n\n var cache = _getRequireWildcardCache();\n\n if (cache && cache.has(obj)) {\n return cache.get(obj);\n }\n\n var newObj = {};\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;\n\n if (desc && (desc.get || desc.set)) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n\n newObj[\"default\"] = obj;\n\n if (cache) {\n cache.set(obj, newObj);\n }\n\n return newObj;\n}\n\nmodule.exports = _interopRequireWildcard;",
"function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n}\n\nmodule.exports = _isNativeFunction;",
"function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}\n\nmodule.exports = _isNativeReflectConstruct;",
"function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n}\n\nmodule.exports = _iterableToArray;",
"function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;",
"function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableRest;",
"function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nmodule.exports = _nonIterableSpread;",
"var _typeof = require(\"@babel/runtime/helpers/typeof\");\n\nvar assertThisInitialized = require(\"./assertThisInitialized\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn;",
"function _setPrototypeOf(o, p) {\n module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}\n\nmodule.exports = _setPrototypeOf;",
"var arrayWithHoles = require(\"./arrayWithHoles\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray\");\n\nvar nonIterableRest = require(\"./nonIterableRest\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;",
"var arrayWithoutHoles = require(\"./arrayWithoutHoles\");\n\nvar iterableToArray = require(\"./iterableToArray\");\n\nvar unsupportedIterableToArray = require(\"./unsupportedIterableToArray\");\n\nvar nonIterableSpread = require(\"./nonIterableSpread\");\n\nfunction _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}\n\nmodule.exports = _toConsumableArray;",
"function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n module.exports = _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n module.exports = _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\nmodule.exports = _typeof;",
"var arrayLikeToArray = require(\"./arrayLikeToArray\");\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}\n\nmodule.exports = _unsupportedIterableToArray;",
"var getPrototypeOf = require(\"./getPrototypeOf\");\n\nvar setPrototypeOf = require(\"./setPrototypeOf\");\n\nvar isNativeFunction = require(\"./isNativeFunction\");\n\nvar construct = require(\"./construct\");\n\nfunction _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}\n\nmodule.exports = _wrapNativeSuper;",
"module.exports = require(\"regenerator-runtime\");\n",
"/* Copyright 2015 Mark Haines\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use strict';\n\nvar escaped = /[\\\\\\\"\\x00-\\x1F]/g;\nvar escapes = {};\nfor (var i = 0; i < 0x20; ++i) {\n escapes[String.fromCharCode(i)] = (\n '\\\\U' + ('0000' + i.toString(16)).slice(-4).toUpperCase()\n );\n}\nescapes['\\b'] = '\\\\b';\nescapes['\\t'] = '\\\\t';\nescapes['\\n'] = '\\\\n';\nescapes['\\f'] = '\\\\f';\nescapes['\\r'] = '\\\\r';\nescapes['\\\"'] = '\\\\\\\"';\nescapes['\\\\'] = '\\\\\\\\';\n\nfunction escapeString(value) {\n escaped.lastIndex = 0;\n return value.replace(escaped, function(c) { return escapes[c]; });\n}\n\nfunction stringify(value) {\n switch (typeof value) {\n case 'string':\n return '\"' + escapeString(value) + '\"';\n case 'number':\n return isFinite(value) ? value : 'null';\n case 'boolean':\n return value;\n case 'object':\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return stringifyArray(value);\n }\n return stringifyObject(value);\n default:\n throw new Error('Cannot stringify: ' + typeof value);\n }\n}\n\nfunction stringifyArray(array) {\n var sep = '[';\n var result = '';\n for (var i = 0; i < array.length; ++i) {\n result += sep;\n sep = ',';\n result += stringify(array[i]);\n }\n if (sep != ',') {\n return '[]';\n } else {\n return result + ']';\n }\n}\n\nfunction stringifyObject(object) {\n var sep = '{';\n var result = '';\n var keys = Object.keys(object);\n keys.sort();\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n result += sep + '\"' + escapeString(key) + '\":';\n sep = ',';\n result += stringify(object[key]);\n }\n if (sep != ',') {\n return '{}';\n } else {\n return result + '}';\n }\n}\n\n/** */\nmodule.exports = {stringify: stringify};\n",
"'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n// @ts-ignore\nvar _Buffer = require('safe-buffer').Buffer\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }\n if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return _Buffer.alloc(0) }\n var psz = 0\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = _Buffer.allocUnsafe(zeroes + (size - it4))\n vch.fill(0x00, 0, zeroes)\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n",
"'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n",
"// Browser Request\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// UMD HEADER START \n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define([], factory);\n } else if (typeof exports === 'object') {\n // Node. Does not work with strict CommonJS, but\n // only CommonJS-like enviroments that support module.exports,\n // like Node.\n module.exports = factory();\n } else {\n // Browser globals (root is window)\n root.returnExports = factory();\n }\n}(this, function () {\n// UMD HEADER END\n\nvar XHR = XMLHttpRequest\nif (!XHR) throw new Error('missing XMLHttpRequest')\nrequest.log = {\n 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop\n}\n\nvar DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes\n\n//\n// request\n//\n\nfunction request(options, callback) {\n // The entry-point to the API: prep the options object and pass the real work to run_xhr.\n if(typeof callback !== 'function')\n throw new Error('Bad callback given: ' + callback)\n\n if(!options)\n throw new Error('No options given')\n\n var options_onResponse = options.onResponse; // Save this for later.\n\n if(typeof options === 'string')\n options = {'uri':options};\n else\n options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.\n\n options.onResponse = options_onResponse // And put it back.\n\n if (options.verbose) request.log = getLogger();\n\n if(options.url) {\n options.uri = options.url;\n delete options.url;\n }\n\n if(!options.uri && options.uri !== \"\")\n throw new Error(\"options.uri is a required argument\");\n\n if(typeof options.uri != \"string\")\n throw new Error(\"options.uri must be a string\");\n\n var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']\n for (var i = 0; i < unsupported_options.length; i++)\n if(options[ unsupported_options[i] ])\n throw new Error(\"options.\" + unsupported_options[i] + \" is not supported\")\n\n options.callback = callback\n options.method = options.method || 'GET';\n options.headers = options.headers || {};\n options.body = options.body || null\n options.timeout = options.timeout || request.DEFAULT_TIMEOUT\n\n if(options.headers.host)\n throw new Error(\"Options.headers.host is not supported\");\n\n if(options.json) {\n options.headers.accept = options.headers.accept || 'application/json'\n if(options.method !== 'GET')\n options.headers['content-type'] = 'application/json'\n\n if(typeof options.json !== 'boolean')\n options.body = JSON.stringify(options.json)\n else if(typeof options.body !== 'string')\n options.body = JSON.stringify(options.body)\n }\n \n //BEGIN QS Hack\n var serialize = function(obj) {\n var str = [];\n for(var p in obj)\n if (obj.hasOwnProperty(p)) {\n str.push(encodeURIComponent(p) + \"=\" + encodeURIComponent(obj[p]));\n }\n return str.join(\"&\");\n }\n \n if(options.qs){\n var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);\n if(options.uri.indexOf('?') !== -1){ //no get params\n options.uri = options.uri+'&'+qs;\n }else{ //existing get params\n options.uri = options.uri+'?'+qs;\n }\n }\n //END QS Hack\n \n //BEGIN FORM Hack\n var multipart = function(obj) {\n //todo: support file type (useful?)\n var result = {};\n result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);\n var lines = [];\n for(var p in obj){\n if (obj.hasOwnProperty(p)) {\n lines.push(\n '--'+result.boundry+\"\\n\"+\n 'Content-Disposition: form-data; name=\"'+p+'\"'+\"\\n\"+\n \"\\n\"+\n obj[p]+\"\\n\"\n );\n }\n }\n lines.push( '--'+result.boundry+'--' );\n result.body = lines.join('');\n result.length = result.body.length;\n result.type = 'multipart/form-data; boundary='+result.boundry;\n return result;\n }\n \n if(options.form){\n if(typeof options.form == 'string') throw('form name unsupported');\n if(options.method === 'POST'){\n var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();\n options.headers['content-type'] = encoding;\n switch(encoding){\n case 'application/x-www-form-urlencoded':\n options.body = serialize(options.form).replace(/%20/g, \"+\");\n break;\n case 'multipart/form-data':\n var multi = multipart(options.form);\n //options.headers['content-length'] = multi.length;\n options.body = multi.body;\n options.headers['content-type'] = multi.type;\n break;\n default : throw new Error('unsupported encoding:'+encoding);\n }\n }\n }\n //END FORM Hack\n\n // If onResponse is boolean true, call back immediately when the response is known,\n // not when the full request is complete.\n options.onResponse = options.onResponse || noop\n if(options.onResponse === true) {\n options.onResponse = callback\n options.callback = noop\n }\n\n // XXX Browsers do not like this.\n //if(options.body)\n // options.headers['content-length'] = options.body.length;\n\n // HTTP basic authentication\n if(!options.headers.authorization && options.auth)\n options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);\n\n return run_xhr(options)\n}\n\nvar req_seq = 0\nfunction run_xhr(options) {\n var xhr = new XHR\n , timed_out = false\n , is_cors = is_crossDomain(options.uri)\n , supports_cors = ('withCredentials' in xhr)\n\n req_seq += 1\n xhr.seq_id = req_seq\n xhr.id = req_seq + ': ' + options.method + ' ' + options.uri\n xhr._id = xhr.id // I know I will type \"_id\" from habit all the time.\n\n if(is_cors && !supports_cors) {\n var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)\n cors_err.cors = 'unsupported'\n return options.callback(cors_err, xhr)\n }\n\n xhr.timeoutTimer = setTimeout(too_late, options.timeout)\n function too_late() {\n timed_out = true\n var er = new Error('ETIMEDOUT')\n er.code = 'ETIMEDOUT'\n er.duration = options.timeout\n\n request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })\n return options.callback(er, xhr)\n }\n\n // Some states can be skipped over, so remember what is still incomplete.\n var did = {'response':false, 'loading':false, 'end':false}\n\n xhr.onreadystatechange = on_state_change\n xhr.open(options.method, options.uri, true) // asynchronous\n if(is_cors)\n xhr.withCredentials = !! options.withCredentials\n xhr.send(options.body)\n return xhr\n\n function on_state_change(event) {\n if(timed_out)\n return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})\n\n request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})\n\n if(xhr.readyState === XHR.OPENED) {\n request.log.debug('Request started', {'id':xhr.id})\n for (var key in options.headers)\n xhr.setRequestHeader(key, options.headers[key])\n }\n\n else if(xhr.readyState === XHR.HEADERS_RECEIVED)\n on_response()\n\n else if(xhr.readyState === XHR.LOADING) {\n on_response()\n on_loading()\n }\n\n else if(xhr.readyState === XHR.DONE) {\n on_response()\n on_loading()\n on_end()\n }\n }\n\n function on_response() {\n if(did.response)\n return\n\n did.response = true\n request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})\n clearTimeout(xhr.timeoutTimer)\n xhr.statusCode = xhr.status // Node request compatibility\n\n // Detect failed CORS requests.\n if(is_cors && xhr.statusCode == 0) {\n var cors_err = new Error('CORS request rejected: ' + options.uri)\n cors_err.cors = 'rejected'\n\n // Do not process this request further.\n did.loading = true\n did.end = true\n\n return options.callback(cors_err, xhr)\n }\n\n options.onResponse(null, xhr)\n }\n\n function on_loading() {\n if(did.loading)\n return\n\n did.loading = true\n request.log.debug('Response body loading', {'id':xhr.id})\n // TODO: Maybe simulate \"data\" events by watching xhr.responseText\n }\n\n function on_end() {\n if(did.end)\n return\n\n did.end = true\n request.log.debug('Request done', {'id':xhr.id})\n\n xhr.body = xhr.responseText\n if(options.json) {\n try { xhr.body = JSON.parse(xhr.responseText) }\n catch (er) { return options.callback(er, xhr) }\n }\n\n options.callback(null, xhr, xhr.body)\n }\n\n} // request\n\nrequest.withCredentials = false;\nrequest.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;\n\n//\n// defaults\n//\n\nrequest.defaults = function(options, requester) {\n var def = function (method) {\n var d = function (params, callback) {\n if(typeof params === 'string')\n params = {'uri': params};\n else {\n params = JSON.parse(JSON.stringify(params));\n }\n for (var i in options) {\n if (params[i] === undefined) params[i] = options[i]\n }\n return method(params, callback)\n }\n return d\n }\n var de = def(request)\n de.get = def(request.get)\n de.post = def(request.post)\n de.put = def(request.put)\n de.head = def(request.head)\n return de\n}\n\n//\n// HTTP method shortcuts\n//\n\nvar shortcuts = [ 'get', 'put', 'post', 'head' ];\nshortcuts.forEach(function(shortcut) {\n var method = shortcut.toUpperCase();\n var func = shortcut.toLowerCase();\n\n request[func] = function(opts) {\n if(typeof opts === 'string')\n opts = {'method':method, 'uri':opts};\n else {\n opts = JSON.parse(JSON.stringify(opts));\n opts.method = method;\n }\n\n var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));\n return request.apply(this, args);\n }\n})\n\n//\n// CouchDB shortcut\n//\n\nrequest.couch = function(options, callback) {\n if(typeof options === 'string')\n options = {'uri':options}\n\n // Just use the request API to do JSON.\n options.json = true\n if(options.body)\n options.json = options.body\n delete options.body\n\n callback = callback || noop\n\n var xhr = request(options, couch_handler)\n return xhr\n\n function couch_handler(er, resp, body) {\n if(er)\n return callback(er, resp, body)\n\n if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {\n // The body is a Couch JSON object indicating the error.\n er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))\n for (var key in body)\n er[key] = body[key]\n return callback(er, resp, body);\n }\n\n return callback(er, resp, body);\n }\n}\n\n//\n// Utility\n//\n\nfunction noop() {}\n\nfunction getLogger() {\n var logger = {}\n , levels = ['trace', 'debug', 'info', 'warn', 'error']\n , level, i\n\n for(i = 0; i < levels.length; i++) {\n level = levels[i]\n\n logger[level] = noop\n if(typeof console !== 'undefined' && console && console[level])\n logger[level] = formatted(console, level)\n }\n\n return logger\n}\n\nfunction formatted(obj, method) {\n return formatted_logger\n\n function formatted_logger(str, context) {\n if(typeof context === 'object')\n str += ' ' + JSON.stringify(context)\n\n return obj[method].call(obj, str)\n }\n}\n\n// Return whether a URL is a cross-domain request.\nfunction is_crossDomain(url) {\n var rurl = /^([\\w\\+\\.\\-]+:)(?:\\/\\/([^\\/?#:]*)(?::(\\d+))?)?/\n\n // jQuery #8138, IE may throw an exception when accessing\n // a field from window.location if document.domain has been set\n var ajaxLocation\n try { ajaxLocation = location.href }\n catch (e) {\n // Use the href attribute of an A element since IE will modify it given document.location\n ajaxLocation = document.createElement( \"a\" );\n ajaxLocation.href = \"\";\n ajaxLocation = ajaxLocation.href;\n }\n\n var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []\n , parts = rurl.exec(url.toLowerCase() )\n\n var result = !!(\n parts &&\n ( parts[1] != ajaxLocParts[1]\n || parts[2] != ajaxLocParts[2]\n || (parts[3] || (parts[1] === \"http:\" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === \"http:\" ? 80 : 443))\n )\n )\n\n //console.debug('is_crossDomain('+url+') -> ' + result)\n return result\n}\n\n// MIT License from http://phpjs.org/functions/base64_encode:358\nfunction b64_enc (data) {\n // Encodes string using MIME base64 algorithm\n var b64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc=\"\", tmp_arr = [];\n\n if (!data) {\n return data;\n }\n\n // assume utf8 data\n // data = this.utf8_encode(data+'');\n\n do { // pack three octets into four hexets\n o1 = data.charCodeAt(i++);\n o2 = data.charCodeAt(i++);\n o3 = data.charCodeAt(i++);\n\n bits = o1<<16 | o2<<8 | o3;\n\n h1 = bits>>18 & 0x3f;\n h2 = bits>>12 & 0x3f;\n h3 = bits>>6 & 0x3f;\n h4 = bits & 0x3f;\n\n // use hexets to index into b64, and append result to encoded string\n tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);\n } while (i < data.length);\n\n enc = tmp_arr.join('');\n\n switch (data.length % 3) {\n case 1:\n enc = enc.slice(0, -2) + '==';\n break;\n case 2:\n enc = enc.slice(0, -1) + '=';\n break;\n }\n\n return enc;\n}\n return request;\n//UMD FOOTER START\n}));\n//UMD FOOTER END\n",
"/*! https://mths.be/punycode v1.4.1 by @mathias */\n;(function(root) {\n\n\t/** Detect free variables */\n\tvar freeExports = typeof exports == 'object' && exports &&\n\t\t!exports.nodeType && exports;\n\tvar freeModule = typeof module == 'object' && module &&\n\t\t!module.nodeType && module;\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (\n\t\tfreeGlobal.global === freeGlobal ||\n\t\tfreeGlobal.window === freeGlobal ||\n\t\tfreeGlobal.self === freeGlobal\n\t) {\n\t\troot = freeGlobal;\n\t}\n\n\t/**\n\t * The `punycode` object.\n\t * @name punycode\n\t * @type Object\n\t */\n\tvar punycode,\n\n\t/** Highest positive signed 32-bit float value */\n\tmaxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1\n\n\t/** Bootstring parameters */\n\tbase = 36,\n\ttMin = 1,\n\ttMax = 26,\n\tskew = 38,\n\tdamp = 700,\n\tinitialBias = 72,\n\tinitialN = 128, // 0x80\n\tdelimiter = '-', // '\\x2D'\n\n\t/** Regular expressions */\n\tregexPunycode = /^xn--/,\n\tregexNonASCII = /[^\\x20-\\x7E]/, // unprintable ASCII chars + non-ASCII chars\n\tregexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g, // RFC 3490 separators\n\n\t/** Error messages */\n\terrors = {\n\t\t'overflow': 'Overflow: input needs wider integers to process',\n\t\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t\t'invalid-input': 'Invalid input'\n\t},\n\n\t/** Convenience shortcuts */\n\tbaseMinusTMin = base - tMin,\n\tfloor = Math.floor,\n\tstringFromCharCode = String.fromCharCode,\n\n\t/** Temporary variable */\n\tkey;\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/**\n\t * A generic error utility function.\n\t * @private\n\t * @param {String} type The error type.\n\t * @returns {Error} Throws a `RangeError` with the applicable error message.\n\t */\n\tfunction error(type) {\n\t\tthrow new RangeError(errors[type]);\n\t}\n\n\t/**\n\t * A generic `Array#map` utility function.\n\t * @private\n\t * @param {Array} array The array to iterate over.\n\t * @param {Function} callback The function that gets called for every array\n\t * item.\n\t * @returns {Array} A new array of values returned by the callback function.\n\t */\n\tfunction map(array, fn) {\n\t\tvar length = array.length;\n\t\tvar result = [];\n\t\twhile (length--) {\n\t\t\tresult[length] = fn(array[length]);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * A simple `Array#map`-like wrapper to work with domain name strings or email\n\t * addresses.\n\t * @private\n\t * @param {String} domain The domain name or email address.\n\t * @param {Function} callback The function that gets called for every\n\t * character.\n\t * @returns {Array} A new string of characters returned by the callback\n\t * function.\n\t */\n\tfunction mapDomain(string, fn) {\n\t\tvar parts = string.split('@');\n\t\tvar result = '';\n\t\tif (parts.length > 1) {\n\t\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t\t// the local part (i.e. everything up to `@`) intact.\n\t\t\tresult = parts[0] + '@';\n\t\t\tstring = parts[1];\n\t\t}\n\t\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\t\tstring = string.replace(regexSeparators, '\\x2E');\n\t\tvar labels = string.split('.');\n\t\tvar encoded = map(labels, fn).join('.');\n\t\treturn result + encoded;\n\t}\n\n\t/**\n\t * Creates an array containing the numeric code points of each Unicode\n\t * character in the string. While JavaScript uses UCS-2 internally,\n\t * this function will convert a pair of surrogate halves (each of which\n\t * UCS-2 exposes as separate characters) into a single code point,\n\t * matching UTF-16.\n\t * @see `punycode.ucs2.encode`\n\t * @see <https://mathiasbynens.be/notes/javascript-encoding>\n\t * @memberOf punycode.ucs2\n\t * @name decode\n\t * @param {String} string The Unicode input string (UCS-2).\n\t * @returns {Array} The new array of code points.\n\t */\n\tfunction ucs2decode(string) {\n\t\tvar output = [],\n\t\t counter = 0,\n\t\t length = string.length,\n\t\t value,\n\t\t extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t/**\n\t * Creates a string based on an array of numeric code points.\n\t * @see `punycode.ucs2.decode`\n\t * @memberOf punycode.ucs2\n\t * @name encode\n\t * @param {Array} codePoints The array of numeric code points.\n\t * @returns {String} The new Unicode string (UCS-2).\n\t */\n\tfunction ucs2encode(array) {\n\t\treturn map(array, function(value) {\n\t\t\tvar output = '';\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t\treturn output;\n\t\t}).join('');\n\t}\n\n\t/**\n\t * Converts a basic code point into a digit/integer.\n\t * @see `digitToBasic()`\n\t * @private\n\t * @param {Number} codePoint The basic numeric code point value.\n\t * @returns {Number} The numeric value of a basic code point (for use in\n\t * representing integers) in the range `0` to `base - 1`, or `base` if\n\t * the code point does not represent a value.\n\t */\n\tfunction basicToDigit(codePoint) {\n\t\tif (codePoint - 48 < 10) {\n\t\t\treturn codePoint - 22;\n\t\t}\n\t\tif (codePoint - 65 < 26) {\n\t\t\treturn codePoint - 65;\n\t\t}\n\t\tif (codePoint - 97 < 26) {\n\t\t\treturn codePoint - 97;\n\t\t}\n\t\treturn base;\n\t}\n\n\t/**\n\t * Converts a digit/integer into a basic code point.\n\t * @see `basicToDigit()`\n\t * @private\n\t * @param {Number} digit The numeric value of a basic code point.\n\t * @returns {Number} The basic code point whose value (when used for\n\t * representing integers) is `digit`, which needs to be in the range\n\t * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n\t * used; else, the lowercase form is used. The behavior is undefined\n\t * if `flag` is non-zero and `digit` has no uppercase form.\n\t */\n\tfunction digitToBasic(digit, flag) {\n\t\t// 0..25 map to ASCII a..z or A..Z\n\t\t// 26..35 map to ASCII 0..9\n\t\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n\t}\n\n\t/**\n\t * Bias adaptation function as per section 3.4 of RFC 3492.\n\t * https://tools.ietf.org/html/rfc3492#section-3.4\n\t * @private\n\t */\n\tfunction adapt(delta, numPoints, firstTime) {\n\t\tvar k = 0;\n\t\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\t\tdelta += floor(delta / numPoints);\n\t\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\t\tdelta = floor(delta / baseMinusTMin);\n\t\t}\n\t\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n\t}\n\n\t/**\n\t * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n\t * symbols.\n\t * @memberOf punycode\n\t * @param {String} input The Punycode string of ASCII-only symbols.\n\t * @returns {String} The resulting string of Unicode symbols.\n\t */\n\tfunction decode(input) {\n\t\t// Don't use UCS-2\n\t\tvar output = [],\n\t\t inputLength = input.length,\n\t\t out,\n\t\t i = 0,\n\t\t n = initialN,\n\t\t bias = initialBias,\n\t\t basic,\n\t\t j,\n\t\t index,\n\t\t oldi,\n\t\t w,\n\t\t k,\n\t\t digit,\n\t\t t,\n\t\t /** Cached calculation results */\n\t\t baseMinusT;\n\n\t\t// Handle the basic code points: let `basic` be the number of input code\n\t\t// points before the last delimiter, or `0` if there is none, then copy\n\t\t// the first basic code points to the output.\n\n\t\tbasic = input.lastIndexOf(delimiter);\n\t\tif (basic < 0) {\n\t\t\tbasic = 0;\n\t\t}\n\n\t\tfor (j = 0; j < basic; ++j) {\n\t\t\t// if it's not a basic code point\n\t\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\t\terror('not-basic');\n\t\t\t}\n\t\t\toutput.push(input.charCodeAt(j));\n\t\t}\n\n\t\t// Main decoding loop: start just after the last delimiter if any basic code\n\t\t// points were copied; start at the beginning otherwise.\n\n\t\tfor (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t\t// `index` is the index of the next character to be consumed.\n\t\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t\t// which gets added to `i`. The overflow checking is easier\n\t\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t\t// value at the end to obtain `delta`.\n\t\t\tfor (oldi = i, w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\t\tif (index >= inputLength) {\n\t\t\t\t\terror('invalid-input');\n\t\t\t\t}\n\n\t\t\t\tdigit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\ti += digit * w;\n\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\t\tif (digit < t) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbaseMinusT = base - t;\n\t\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tw *= baseMinusT;\n\n\t\t\t}\n\n\t\t\tout = output.length + 1;\n\t\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t\t// incrementing `n` each time, so we'll fix that now:\n\t\t\tif (floor(i / out) > maxInt - n) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tn += floor(i / out);\n\t\t\ti %= out;\n\n\t\t\t// Insert `n` at position `i` of the output\n\t\t\toutput.splice(i++, 0, n);\n\n\t\t}\n\n\t\treturn ucs2encode(output);\n\t}\n\n\t/**\n\t * Converts a string of Unicode symbols (e.g. a domain name label) to a\n\t * Punycode string of ASCII-only symbols.\n\t * @memberOf punycode\n\t * @param {String} input The string of Unicode symbols.\n\t * @returns {String} The resulting Punycode string of ASCII-only symbols.\n\t */\n\tfunction encode(input) {\n\t\tvar n,\n\t\t delta,\n\t\t handledCPCount,\n\t\t basicLength,\n\t\t bias,\n\t\t j,\n\t\t m,\n\t\t q,\n\t\t k,\n\t\t t,\n\t\t currentValue,\n\t\t output = [],\n\t\t /** `inputLength` will hold the number of code points in `input`. */\n\t\t inputLength,\n\t\t /** Cached calculation results */\n\t\t handledCPCountPlusOne,\n\t\t baseMinusT,\n\t\t qMinusT;\n\n\t\t// Convert the input in UCS-2 to Unicode\n\t\tinput = ucs2decode(input);\n\n\t\t// Cache the length\n\t\tinputLength = input.length;\n\n\t\t// Initialize the state\n\t\tn = initialN;\n\t\tdelta = 0;\n\t\tbias = initialBias;\n\n\t\t// Handle the basic code points\n\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\tcurrentValue = input[j];\n\t\t\tif (currentValue < 0x80) {\n\t\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t\t}\n\t\t}\n\n\t\thandledCPCount = basicLength = output.length;\n\n\t\t// `handledCPCount` is the number of code points that have been handled;\n\t\t// `basicLength` is the number of basic code points.\n\n\t\t// Finish the basic string - if it is not empty - with a delimiter\n\t\tif (basicLength) {\n\t\t\toutput.push(delimiter);\n\t\t}\n\n\t\t// Main encoding loop:\n\t\twhile (handledCPCount < inputLength) {\n\n\t\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t\t// larger one:\n\t\t\tfor (m = maxInt, j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\t\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\t\tm = currentValue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,\n\t\t\t// but guard against overflow\n\t\t\thandledCPCountPlusOne = handledCPCount + 1;\n\t\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\t\tn = m;\n\n\t\t\tfor (j = 0; j < inputLength; ++j) {\n\t\t\t\tcurrentValue = input[j];\n\n\t\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\t\terror('overflow');\n\t\t\t\t}\n\n\t\t\t\tif (currentValue == n) {\n\t\t\t\t\t// Represent delta as a generalized variable-length integer\n\t\t\t\t\tfor (q = delta, k = base; /* no condition */; k += base) {\n\t\t\t\t\t\tt = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tqMinusT = q - t;\n\t\t\t\t\t\tbaseMinusT = base - t;\n\t\t\t\t\t\toutput.push(\n\t\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t\t);\n\t\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\t\tdelta = 0;\n\t\t\t\t\t++handledCPCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t++delta;\n\t\t\t++n;\n\n\t\t}\n\t\treturn output.join('');\n\t}\n\n\t/**\n\t * Converts a Punycode string representing a domain name or an email address\n\t * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n\t * it doesn't matter if you call it on a string that has already been\n\t * converted to Unicode.\n\t * @memberOf punycode\n\t * @param {String} input The Punycoded domain name or email address to\n\t * convert to Unicode.\n\t * @returns {String} The Unicode representation of the given Punycode\n\t * string.\n\t */\n\tfunction toUnicode(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexPunycode.test(string)\n\t\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/**\n\t * Converts a Unicode string representing a domain name or an email address to\n\t * Punycode. Only the non-ASCII parts of the domain name will be converted,\n\t * i.e. it doesn't matter if you call it with a domain that's already in\n\t * ASCII.\n\t * @memberOf punycode\n\t * @param {String} input The domain name or email address to convert, as a\n\t * Unicode string.\n\t * @returns {String} The Punycode representation of the given domain name or\n\t * email address.\n\t */\n\tfunction toASCII(input) {\n\t\treturn mapDomain(input, function(string) {\n\t\t\treturn regexNonASCII.test(string)\n\t\t\t\t? 'xn--' + encode(string)\n\t\t\t\t: string;\n\t\t});\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t/** Define the public API */\n\tpunycode = {\n\t\t/**\n\t\t * A string representing the current Punycode.js version number.\n\t\t * @memberOf punycode\n\t\t * @type String\n\t\t */\n\t\t'version': '1.4.1',\n\t\t/**\n\t\t * An object of methods to convert from JavaScript's internal character\n\t\t * representation (UCS-2) to Unicode code points, and back.\n\t\t * @see <https://mathiasbynens.be/notes/javascript-encoding>\n\t\t * @memberOf punycode\n\t\t * @type Object\n\t\t */\n\t\t'ucs2': {\n\t\t\t'decode': ucs2decode,\n\t\t\t'encode': ucs2encode\n\t\t},\n\t\t'decode': decode,\n\t\t'encode': encode,\n\t\t'toASCII': toASCII,\n\t\t'toUnicode': toUnicode\n\t};\n\n\t/** Expose `punycode` */\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine('punycode', function() {\n\t\t\treturn punycode;\n\t\t});\n\t} else if (freeExports && freeModule) {\n\t\tif (module.exports == freeExports) {\n\t\t\t// in Node.js, io.js, or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = punycode;\n\t\t} else {\n\t\t\t// in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (key in punycode) {\n\t\t\t\tpunycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// in Rhino or a web browser\n\t\troot.punycode = punycode;\n\t}\n\n}(this));\n",
"var basex = require('base-x')\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n",
"/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species != null &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayLike(value)\n }\n\n if (value == null) {\n throw TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n buf = Buffer.from(buf)\n }\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return '<Buffer ' + str + '>'\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (var i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n",
"/*!\n * content-type\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter = token \"=\" ( token / quoted-string )\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text = %x80-FF\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nvar PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *(\"(?:[\\u000b\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\u000b\\u0020-\\u00ff])*\"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g\nvar TEXT_REGEXP = /^[\\u000b\\u0020-\\u007e\\u0080-\\u00ff]+$/\nvar TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text = %x80-FF\n */\nvar QESC_REGEXP = /\\\\([\\u000b\\u0020-\\u00ff])/g\n\n/**\n * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6\n */\nvar QUOTE_REGEXP = /([\\\\\"])/g\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nvar TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * Module exports.\n * @public\n */\n\nexports.format = format\nexports.parse = parse\n\n/**\n * Format object to media type.\n *\n * @param {object} obj\n * @return {string}\n * @public\n */\n\nfunction format (obj) {\n if (!obj || typeof obj !== 'object') {\n throw new TypeError('argument obj is required')\n }\n\n var parameters = obj.parameters\n var type = obj.type\n\n if (!type || !TYPE_REGEXP.test(type)) {\n throw new TypeError('invalid type')\n }\n\n var string = type\n\n // append parameters\n if (parameters && typeof parameters === 'object') {\n var param\n var params = Object.keys(parameters).sort()\n\n for (var i = 0; i < params.length; i++) {\n param = params[i]\n\n if (!TOKEN_REGEXP.test(param)) {\n throw new TypeError('invalid parameter name')\n }\n\n string += '; ' + param + '=' + qstring(parameters[param])\n }\n }\n\n return string\n}\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} string\n * @return {Object}\n * @public\n */\n\nfunction parse (string) {\n if (!string) {\n throw new TypeError('argument string is required')\n }\n\n // support req/res-like objects as argument\n var header = typeof string === 'object'\n ? getcontenttype(string)\n : string\n\n if (typeof header !== 'string') {\n throw new TypeError('argument string is required to be a string')\n }\n\n var index = header.indexOf(';')\n var type = index !== -1\n ? header.substr(0, index).trim()\n : header.trim()\n\n if (!TYPE_REGEXP.test(type)) {\n throw new TypeError('invalid media type')\n }\n\n var obj = new ContentType(type.toLowerCase())\n\n // parse parameters\n if (index !== -1) {\n var key\n var match\n var value\n\n PARAM_REGEXP.lastIndex = index\n\n while ((match = PARAM_REGEXP.exec(header))) {\n if (match.index !== index) {\n throw new TypeError('invalid parameter format')\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value\n .substr(1, value.length - 2)\n .replace(QESC_REGEXP, '$1')\n }\n\n obj.parameters[key] = value\n }\n\n if (index !== header.length) {\n throw new TypeError('invalid parameter format')\n }\n }\n\n return obj\n}\n\n/**\n * Get content-type from req/res objects.\n *\n * @param {object}\n * @return {Object}\n * @private\n */\n\nfunction getcontenttype (obj) {\n var header\n\n if (typeof obj.getHeader === 'function') {\n // res-like\n header = obj.getHeader('content-type')\n } else if (typeof obj.headers === 'object') {\n // req-like\n header = obj.headers && obj.headers['content-type']\n }\n\n if (typeof header !== 'string') {\n throw new TypeError('content-type header is missing from object')\n }\n\n return header\n}\n\n/**\n * Quote a string if necessary.\n *\n * @param {string} val\n * @return {string}\n * @private\n */\n\nfunction qstring (val) {\n var str = String(val)\n\n // no need to quote tokens\n if (TOKEN_REGEXP.test(str)) {\n return str\n }\n\n if (str.length > 0 && !TEXT_REGEXP.test(str)) {\n throw new TypeError('invalid parameter value')\n }\n\n return '\"' + str.replace(QUOTE_REGEXP, '\\\\$1') + '\"'\n}\n\n/**\n * Class to represent a content type.\n * @private\n */\nfunction ContentType (type) {\n this.parameters = Object.create(null)\n this.type = type\n}\n",
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function eventListener() {\n if (errorListener !== undefined) {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n var errorListener;\n\n // Adding an error listener is not optional because\n // if an error is thrown on an event emitter we cannot\n // guarantee that the actual event we are waiting will\n // be fired. The result could be a silent way to create\n // memory or file descriptor leaks, which is something\n // we should avoid.\n if (name !== 'error') {\n errorListener = function errorListener(err) {\n emitter.removeListener(name, eventListener);\n reject(err);\n };\n\n emitter.once('error', errorListener);\n }\n\n emitter.once(name, eventListener);\n });\n}\n",
"/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n",
"/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods(level, loggerName) {\n /*jshint validthis:true */\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, loggerName);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this, level, loggerName);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, level, loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, defaultLevel, factory) {\n var self = this;\n var currentLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var location = cookie.indexOf(\n encodeURIComponent(storageKey) + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n return currentLevel;\n };\n\n self.setLevel = function (level, persist) {\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n currentLevel = level;\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(level);\n }\n replaceLoggingMethods.call(self, level, name);\n if (typeof console === undefinedType && level < self.levels.SILENT) {\n return \"No console available for logging\";\n }\n } else {\n throw \"log.setLevel() called with invalid level: \" + level;\n }\n };\n\n self.setDefaultLevel = function (level) {\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n // Initialize with the right level\n var initialLevel = getPersistedLevel();\n if (initialLevel == null) {\n initialLevel = defaultLevel == null ? \"WARN\" : defaultLevel;\n }\n self.setLevel(initialLevel, false);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n var defaultLogger = new Logger();\n\n var _loggersByName = {};\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name, defaultLogger.getLevel(), defaultLogger.methodFactory);\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n",
"'use strict';\nconst retry = require('retry');\n\nconst networkErrorMsgs = [\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource', // Firefox\n\t'The Internet connection appears to be offline', // Safari\n\t'Network request failed' // `cross-fetch`\n];\n\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nconst isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);\n\nconst pRetry = (input, options) => new Promise((resolve, reject) => {\n\toptions = {\n\t\tonFailedAttempt: () => {},\n\t\tretries: 10,\n\t\t...options\n\t};\n\n\tconst operation = retry.operation(options);\n\n\toperation.attempt(async attemptNumber => {\n\t\ttry {\n\t\t\tresolve(await input(attemptNumber));\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\treject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (error instanceof AbortError) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error.originalError);\n\t\t\t} else if (error instanceof TypeError && !isNetworkError(error.message)) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error);\n\t\t\t} else {\n\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\treject(operation.mainError());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n});\n\nmodule.exports = pRetry;\n// TODO: remove this in the next major version\nmodule.exports.default = pRetry;\n\nmodule.exports.AbortError = AbortError;\n",
"// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n",
"'use strict';\n\nvar replace = String.prototype.replace;\nvar percentTwenties = /%20/g;\n\nvar Format = {\n RFC1738: 'RFC1738',\n RFC3986: 'RFC3986'\n};\n\nmodule.exports = {\n 'default': Format.RFC3986,\n formatters: {\n RFC1738: function (value) {\n return replace.call(value, percentTwenties, '+');\n },\n RFC3986: function (value) {\n return String(value);\n }\n },\n RFC1738: Format.RFC1738,\n RFC3986: Format.RFC3986\n};\n",
"'use strict';\n\nvar stringify = require('./stringify');\nvar parse = require('./parse');\nvar formats = require('./formats');\n\nmodule.exports = {\n formats: formats,\n parse: parse,\n stringify: stringify\n};\n",
"'use strict';\n\nvar utils = require('./utils');\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar defaults = {\n allowDots: false,\n allowPrototypes: false,\n arrayLimit: 20,\n charset: 'utf-8',\n charsetSentinel: false,\n comma: false,\n decoder: utils.decode,\n delimiter: '&',\n depth: 5,\n ignoreQueryPrefix: false,\n interpretNumericEntities: false,\n parameterLimit: 1000,\n parseArrays: true,\n plainObjects: false,\n strictNullHandling: false\n};\n\nvar interpretNumericEntities = function (str) {\n return str.replace(/&#(\\d+);/g, function ($0, numberStr) {\n return String.fromCharCode(parseInt(numberStr, 10));\n });\n};\n\nvar parseArrayValue = function (val, options) {\n if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {\n return val.split(',');\n }\n\n return val;\n};\n\n// This is what browsers will submit when the ✓ character occurs in an\n// application/x-www-form-urlencoded body and the encoding of the page containing\n// the form is iso-8859-1, or when the submitted form has an accept-charset\n// attribute of iso-8859-1. Presumably also with other charsets that do not contain\n// the ✓ character, such as us-ascii.\nvar isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')\n\n// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.\nvar charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')\n\nvar parseValues = function parseQueryStringValues(str, options) {\n var obj = {};\n var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\\?/, '') : str;\n var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;\n var parts = cleanStr.split(options.delimiter, limit);\n var skipIndex = -1; // Keep track of where the utf8 sentinel was found\n var i;\n\n var charset = options.charset;\n if (options.charsetSentinel) {\n for (i = 0; i < parts.length; ++i) {\n if (parts[i].indexOf('utf8=') === 0) {\n if (parts[i] === charsetSentinel) {\n charset = 'utf-8';\n } else if (parts[i] === isoSentinel) {\n charset = 'iso-8859-1';\n }\n skipIndex = i;\n i = parts.length; // The eslint settings do not allow break;\n }\n }\n }\n\n for (i = 0; i < parts.length; ++i) {\n if (i === skipIndex) {\n continue;\n }\n var part = parts[i];\n\n var bracketEqualsPos = part.indexOf(']=');\n var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;\n\n var key, val;\n if (pos === -1) {\n key = options.decoder(part, defaults.decoder, charset, 'key');\n val = options.strictNullHandling ? null : '';\n } else {\n key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');\n val = utils.maybeMap(\n parseArrayValue(part.slice(pos + 1), options),\n function (encodedVal) {\n return options.decoder(encodedVal, defaults.decoder, charset, 'value');\n }\n );\n }\n\n if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {\n val = interpretNumericEntities(val);\n }\n\n if (part.indexOf('[]=') > -1) {\n val = isArray(val) ? [val] : val;\n }\n\n if (has.call(obj, key)) {\n obj[key] = utils.combine(obj[key], val);\n } else {\n obj[key] = val;\n }\n }\n\n return obj;\n};\n\nvar parseObject = function (chain, val, options, valuesParsed) {\n var leaf = valuesParsed ? val : parseArrayValue(val, options);\n\n for (var i = chain.length - 1; i >= 0; --i) {\n var obj;\n var root = chain[i];\n\n if (root === '[]' && options.parseArrays) {\n obj = [].concat(leaf);\n } else {\n obj = options.plainObjects ? Object.create(null) : {};\n var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;\n var index = parseInt(cleanRoot, 10);\n if (!options.parseArrays && cleanRoot === '') {\n obj = { 0: leaf };\n } else if (\n !isNaN(index)\n && root !== cleanRoot\n && String(index) === cleanRoot\n && index >= 0\n && (options.parseArrays && index <= options.arrayLimit)\n ) {\n obj = [];\n obj[index] = leaf;\n } else {\n obj[cleanRoot] = leaf;\n }\n }\n\n leaf = obj;\n }\n\n return leaf;\n};\n\nvar parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {\n if (!givenKey) {\n return;\n }\n\n // Transform dot notation to bracket notation\n var key = options.allowDots ? givenKey.replace(/\\.([^.[]+)/g, '[$1]') : givenKey;\n\n // The regex chunks\n\n var brackets = /(\\[[^[\\]]*])/;\n var child = /(\\[[^[\\]]*])/g;\n\n // Get the parent\n\n var segment = options.depth > 0 && brackets.exec(key);\n var parent = segment ? key.slice(0, segment.index) : key;\n\n // Stash the parent if it exists\n\n var keys = [];\n if (parent) {\n // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties\n if (!options.plainObjects && has.call(Object.prototype, parent)) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n\n keys.push(parent);\n }\n\n // Loop through children appending to the array until we hit depth\n\n var i = 0;\n while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {\n i += 1;\n if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n keys.push(segment[1]);\n }\n\n // If there's a remainder, just add whatever is left\n\n if (segment) {\n keys.push('[' + key.slice(segment.index) + ']');\n }\n\n return parseObject(keys, val, options, valuesParsed);\n};\n\nvar normalizeParseOptions = function normalizeParseOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {\n throw new TypeError('Decoder has to be a function.');\n }\n\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;\n\n return {\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,\n arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,\n decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,\n delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,\n // eslint-disable-next-line no-implicit-coercion, no-extra-parens\n depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,\n ignoreQueryPrefix: opts.ignoreQueryPrefix === true,\n interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,\n parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,\n parseArrays: opts.parseArrays !== false,\n plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (str, opts) {\n var options = normalizeParseOptions(opts);\n\n if (str === '' || str === null || typeof str === 'undefined') {\n return options.plainObjects ? Object.create(null) : {};\n }\n\n var tempObj = typeof str === 'string' ? parseValues(str, options) : str;\n var obj = options.plainObjects ? Object.create(null) : {};\n\n // Iterate over the keys and setup the new object\n\n var keys = Object.keys(tempObj);\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');\n obj = utils.merge(obj, newObj, options);\n }\n\n return utils.compact(obj);\n};\n",
"'use strict';\n\nvar utils = require('./utils');\nvar formats = require('./formats');\nvar has = Object.prototype.hasOwnProperty;\n\nvar arrayPrefixGenerators = {\n brackets: function brackets(prefix) {\n return prefix + '[]';\n },\n comma: 'comma',\n indices: function indices(prefix, key) {\n return prefix + '[' + key + ']';\n },\n repeat: function repeat(prefix) {\n return prefix;\n }\n};\n\nvar isArray = Array.isArray;\nvar push = Array.prototype.push;\nvar pushToArray = function (arr, valueOrArray) {\n push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);\n};\n\nvar toISO = Date.prototype.toISOString;\n\nvar defaultFormat = formats['default'];\nvar defaults = {\n addQueryPrefix: false,\n allowDots: false,\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encoder: utils.encode,\n encodeValuesOnly: false,\n format: defaultFormat,\n formatter: formats.formatters[defaultFormat],\n // deprecated\n indices: false,\n serializeDate: function serializeDate(date) {\n return toISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false\n};\n\nvar isNonNullishPrimitive = function isNonNullishPrimitive(v) {\n return typeof v === 'string'\n || typeof v === 'number'\n || typeof v === 'boolean'\n || typeof v === 'symbol'\n || typeof v === 'bigint';\n};\n\nvar stringify = function stringify(\n object,\n prefix,\n generateArrayPrefix,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset\n) {\n var obj = object;\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n } else if (obj instanceof Date) {\n obj = serializeDate(obj);\n } else if (generateArrayPrefix === 'comma' && isArray(obj)) {\n obj = utils.maybeMap(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate(value);\n }\n return value;\n });\n }\n\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;\n }\n\n obj = '';\n }\n\n if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {\n if (encoder) {\n var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];\n }\n return [formatter(prefix) + '=' + formatter(String(obj))];\n }\n\n var values = [];\n\n if (typeof obj === 'undefined') {\n return values;\n }\n\n var objKeys;\n if (generateArrayPrefix === 'comma' && isArray(obj)) {\n // we need to join elements in\n objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : undefined }];\n } else if (isArray(filter)) {\n objKeys = filter;\n } else {\n var keys = Object.keys(obj);\n objKeys = sort ? keys.sort(sort) : keys;\n }\n\n for (var i = 0; i < objKeys.length; ++i) {\n var key = objKeys[i];\n var value = typeof key === 'object' && key.value !== undefined ? key.value : obj[key];\n\n if (skipNulls && value === null) {\n continue;\n }\n\n var keyPrefix = isArray(obj)\n ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix\n : prefix + (allowDots ? '.' + key : '[' + key + ']');\n\n pushToArray(values, stringify(\n value,\n keyPrefix,\n generateArrayPrefix,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset\n ));\n }\n\n return values;\n};\n\nvar normalizeStringifyOptions = function normalizeStringifyOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n\n var charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n\n var format = formats['default'];\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formats.formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n var formatter = formats.formatters[format];\n\n var filter = defaults.filter;\n if (typeof opts.filter === 'function' || isArray(opts.filter)) {\n filter = opts.filter;\n }\n\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (object, opts) {\n var obj = object;\n var options = normalizeStringifyOptions(opts);\n\n var objKeys;\n var filter;\n\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n } else if (isArray(options.filter)) {\n filter = options.filter;\n objKeys = filter;\n }\n\n var keys = [];\n\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n\n var arrayFormat;\n if (opts && opts.arrayFormat in arrayPrefixGenerators) {\n arrayFormat = opts.arrayFormat;\n } else if (opts && 'indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n } else {\n arrayFormat = 'indices';\n }\n\n var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];\n\n if (!objKeys) {\n objKeys = Object.keys(obj);\n }\n\n if (options.sort) {\n objKeys.sort(options.sort);\n }\n\n for (var i = 0; i < objKeys.length; ++i) {\n var key = objKeys[i];\n\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n pushToArray(keys, stringify(\n obj[key],\n key,\n generateArrayPrefix,\n options.strictNullHandling,\n options.skipNulls,\n options.encode ? options.encoder : null,\n options.filter,\n options.sort,\n options.allowDots,\n options.serializeDate,\n options.format,\n options.formatter,\n options.encodeValuesOnly,\n options.charset\n ));\n }\n\n var joined = keys.join(options.delimiter);\n var prefix = options.addQueryPrefix === true ? '?' : '';\n\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('&#10003;'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n } else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n\n return joined.length > 0 ? prefix + joined : '';\n};\n",
"'use strict';\n\nvar formats = require('./formats');\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar hexTable = (function () {\n var array = [];\n for (var i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n\n return array;\n}());\n\nvar compactQueue = function compactQueue(queue) {\n while (queue.length > 1) {\n var item = queue.pop();\n var obj = item.obj[item.prop];\n\n if (isArray(obj)) {\n var compacted = [];\n\n for (var j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n\n item.obj[item.prop] = compacted;\n }\n }\n};\n\nvar arrayToObject = function arrayToObject(source, options) {\n var obj = options && options.plainObjects ? Object.create(null) : {};\n for (var i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n\n return obj;\n};\n\nvar merge = function merge(target, source, options) {\n /* eslint no-param-reassign: 0 */\n if (!source) {\n return target;\n }\n\n if (typeof source !== 'object') {\n if (isArray(target)) {\n target.push(source);\n } else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {\n target[source] = true;\n }\n } else {\n return [target, source];\n }\n\n return target;\n }\n\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n\n var mergeTarget = target;\n if (isArray(target) && !isArray(source)) {\n mergeTarget = arrayToObject(target, options);\n }\n\n if (isArray(target) && isArray(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n var targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n } else {\n target.push(item);\n }\n } else {\n target[i] = item;\n }\n });\n return target;\n }\n\n return Object.keys(source).reduce(function (acc, key) {\n var value = source[key];\n\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n } else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n};\n\nvar assign = function assignSingleSource(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n};\n\nvar decode = function (str, decoder, charset) {\n var strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n } catch (e) {\n return strWithoutPlus;\n }\n};\n\nvar encode = function encode(str, defaultEncoder, charset, kind, format) {\n // This code was originally written by Brian White (mscdex) for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n\n var string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n } else if (typeof str !== 'string') {\n string = String(str);\n }\n\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n\n var out = '';\n for (var i = 0; i < string.length; ++i) {\n var c = string.charCodeAt(i);\n\n if (\n c === 0x2D // -\n || c === 0x2E // .\n || c === 0x5F // _\n || c === 0x7E // ~\n || (c >= 0x30 && c <= 0x39) // 0-9\n || (c >= 0x41 && c <= 0x5A) // a-z\n || (c >= 0x61 && c <= 0x7A) // A-Z\n || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n out += string.charAt(i);\n continue;\n }\n\n if (c < 0x80) {\n out = out + hexTable[c];\n continue;\n }\n\n if (c < 0x800) {\n out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n if (c < 0xD800 || c >= 0xE000) {\n out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n i += 1;\n c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));\n out += hexTable[0xF0 | (c >> 18)]\n + hexTable[0x80 | ((c >> 12) & 0x3F)]\n + hexTable[0x80 | ((c >> 6) & 0x3F)]\n + hexTable[0x80 | (c & 0x3F)];\n }\n\n return out;\n};\n\nvar compact = function compact(value) {\n var queue = [{ obj: { o: value }, prop: 'o' }];\n var refs = [];\n\n for (var i = 0; i < queue.length; ++i) {\n var item = queue[i];\n var obj = item.obj[item.prop];\n\n var keys = Object.keys(obj);\n for (var j = 0; j < keys.length; ++j) {\n var key = keys[j];\n var val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n\n compactQueue(queue);\n\n return value;\n};\n\nvar isRegExp = function isRegExp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n};\n\nvar isBuffer = function isBuffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n};\n\nvar combine = function combine(a, b) {\n return [].concat(a, b);\n};\n\nvar maybeMap = function maybeMap(val, fn) {\n if (isArray(val)) {\n var mapped = [];\n for (var i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]));\n }\n return mapped;\n }\n return fn(val);\n};\n\nmodule.exports = {\n arrayToObject: arrayToObject,\n assign: assign,\n combine: combine,\n compact: compact,\n decode: decode,\n encode: encode,\n isBuffer: isBuffer,\n isRegExp: isRegExp,\n maybeMap: maybeMap,\n merge: merge\n};\n",
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nmodule.exports = function(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n",
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar stringifyPrimitive = function(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n};\n\nmodule.exports = function(obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return map(objectKeys(obj), function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (isArray(obj[k])) {\n return map(obj[k], function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n\nfunction map (xs, f) {\n if (xs.map) return xs.map(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n res.push(f(xs[i], i));\n }\n return res;\n}\n\nvar objectKeys = Object.keys || function (obj) {\n var res = [];\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);\n }\n return res;\n};\n",
"'use strict';\n\nexports.decode = exports.parse = require('./decode');\nexports.encode = exports.stringify = require('./encode');\n",
"/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n",
"module.exports = require('./lib/retry');",
"var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && options.forever,\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n",
"function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts;\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(this._errors.length - 1, this._errors.length);\n this._timeouts = this._cachedTimeouts.slice(0);\n timeout = this._timeouts.shift();\n } else {\n return false;\n }\n }\n\n var self = this;\n var timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n",
"/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n",
"module.exports={\n \"0\": \"O\",\n \"1\": \"l\",\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 \"𑌀\": \"̊\",\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 \"̶\": \"̵\",\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 \"𑓁\": \"ঃ\",\n \"់\": \"่\",\n \"່\": \"่\",\n \"້\": \"้\",\n \"໊\": \"๊\",\n \"໋\": \"๋\",\n \"꙯\": \"⃩\",\n \"\\u2028\": \" \",\n \"\\u2029\": \" \",\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 \"։\": \":\",\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 \"‧\": \"·\",\n \"∙\": \"·\",\n \"⋅\": \"·\",\n \"ꞏ\": \"·\",\n \"ᐧ\": \"·\",\n \"⋯\": \"···\",\n \"ⵈ\": \"···\",\n \"ᑄ\": \"·<\",\n \"⋗\": \"·>\",\n \"ᐷ\": \"·>\",\n \"ᑀ\": \"·>\",\n \"ᔯ\": \"·4\",\n \"ᑾ\": \"·b\",\n \"ᒀ\": \"·ḃ\",\n \"ᑺ\": \"·d\",\n \"ᒘ\": \"·J\",\n \"ᒶ\": \"·L\",\n \"ᑶ\": \"·P\",\n \"ᑗ\": \"·U\",\n \"ᐺ\": \"·V\",\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 \"ᓺ\": \"·ᓰ\",\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 \"՚\": \"'\",\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 \"Ɓ\": \"'B\",\n \"Ɗ\": \"'D\",\n \"ʼn\": \"'n\",\n \"Ƥ\": \"'P\",\n \"Ƭ\": \"'T\",\n \"Ƴ\": \"'Y\",\n \"\": \"(\",\n \"\": \"(\",\n \"\": \"(\",\n \"\": \"(\",\n \"\": \"(\",\n \"⸨\": \"((\",\n \"㈠\": \"(ー)\",\n \"⑵\": \"(2)\",\n \"⒇\": \"(2O)\",\n \"⑶\": \"(3)\",\n \"⑷\": \"(4)\",\n \"⑸\": \"(5)\",\n \"⑹\": \"(6)\",\n \"⑺\": \"(7)\",\n \"⑻\": \"(8)\",\n \"⑼\": \"(9)\",\n \"⒜\": \"(a)\",\n \"🄐\": \"(A)\",\n \"⒝\": \"(b)\",\n \"🄑\": \"(B)\",\n \"⒞\": \"(c)\",\n \"🄒\": \"(C)\",\n \"⒟\": \"(d)\",\n \"🄓\": \"(D)\",\n \"⒠\": \"(e)\",\n \"🄔\": \"(E)\",\n \"⒡\": \"(f)\",\n \"🄕\": \"(F)\",\n \"⒢\": \"(g)\",\n \"🄖\": \"(G)\",\n \"⒣\": \"(h)\",\n \"🄗\": \"(H)\",\n \"⒤\": \"(i)\",\n \"⒥\": \"(j)\",\n \"🄙\": \"(J)\",\n \"⒦\": \"(k)\",\n \"🄚\": \"(K)\",\n \"⑴\": \"(l)\",\n \"🄘\": \"(l)\",\n \"⒧\": \"(l)\",\n \"🄛\": \"(L)\",\n \"⑿\": \"(l2)\",\n \"⒀\": \"(l3)\",\n \"⒁\": \"(l4)\",\n \"⒂\": \"(l5)\",\n \"⒃\": \"(l6)\",\n \"⒄\": \"(l7)\",\n \"⒅\": \"(l8)\",\n \"⒆\": \"(l9)\",\n \"⑾\": \"(ll)\",\n \"⑽\": \"(lO)\",\n \"🄜\": \"(M)\",\n \"⒩\": \"(n)\",\n \"🄝\": \"(N)\",\n \"⒪\": \"(o)\",\n \"🄞\": \"(O)\",\n \"⒫\": \"(p)\",\n \"🄟\": \"(P)\",\n \"⒬\": \"(q)\",\n \"🄠\": \"(Q)\",\n \"⒭\": \"(r)\",\n \"🄡\": \"(R)\",\n \"⒨\": \"(rn)\",\n \"⒮\": \"(s)\",\n \"🄢\": \"(S)\",\n \"🄪\": \"(S)\",\n \"⒯\": \"(t)\",\n \"🄣\": \"(T)\",\n \"⒰\": \"(u)\",\n \"🄤\": \"(U)\",\n \"⒱\": \"(v)\",\n \"🄥\": \"(V)\",\n \"⒲\": \"(w)\",\n \"🄦\": \"(W)\",\n \"⒳\": \"(x)\",\n \"🄧\": \"(X)\",\n \"⒴\": \"(y)\",\n \"🄨\": \"(Y)\",\n \"⒵\": \"(z)\",\n \"🄩\": \"(Z)\",\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 \"㈣\": \"(四)\",\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 \"\": \"*\",\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 \"﹊\": \"ˉ\",\n \"﹋\": \"ˉ\",\n \"﹌\": \"ˉ\",\n \"¯\": \"ˉ\",\n \" ̄\": \"ˉ\",\n \"▔\": \"ˉ\",\n \"ъ\": \"ˉb\",\n \"ꙑ\": \"ˉbi\",\n \"͵\": \"ˏ\",\n \"˻\": \"˪\",\n \"꜖\": \"˪\",\n \"꜔\": \"˫\",\n \"。\": \"˳\",\n \"⸰\": \"°\",\n \"˚\": \"°\",\n \"∘\": \"°\",\n \"○\": \"°\",\n \"◦\": \"°\",\n \"⍜\": \"°̲\",\n \"⍤\": \"°̈\",\n \"℃\": \"°C\",\n \"℉\": \"°F\",\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 \"˂\": \"<\",\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 \"🝞\": \"≏\",\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 \"🜊\": \"☩\",\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 \"𝟐\": \"2\",\n \"𝟚\": \"2\",\n \"𝟤\": \"2\",\n \"𝟮\": \"2\",\n \"𝟸\": \"2\",\n \"🯲\": \"2\",\n \"\": \"2\",\n \"Ƨ\": \"2\",\n \"Ϩ\": \"2\",\n \"\": \"2\",\n \"\": \"2\",\n \"\": \"2\",\n \"ꧏ\": \"٢\",\n \"۲\": \"٢\",\n \"૨\": \"२\",\n \"𑓒\": \"২\",\n \"೨\": \"౨\",\n \"②\": \"➁\",\n \"ƻ\": \"2̵\",\n \"🄃\": \"2,\",\n \"⒉\": \"2.\",\n \"㏵\": \"22日\",\n \"㍮\": \"22点\",\n \"㏶\": \"23日\",\n \"㍯\": \"23点\",\n \"㏷\": \"24日\",\n \"㍰\": \"24点\",\n \"㏸\": \"25日\",\n \"㏹\": \"26日\",\n \"㏺\": \"27日\",\n \"㏻\": \"28日\",\n \"㏼\": \"29日\",\n \"㏴\": \"2l日\",\n \"㍭\": \"2l点\",\n \"⒛\": \"2O.\",\n \"㏳\": \"2O日\",\n \"㍬\": \"2O点\",\n \"෩\": \"෨ා\",\n \"෯\": \"෨ී\",\n \"㏡\": \"2日\",\n \"㋁\": \"2月\",\n \"㍚\": \"2点\",\n \"𝈆\": \"3\",\n \"𝟑\": \"3\",\n \"𝟛\": \"3\",\n \"𝟥\": \"3\",\n \"𝟯\": \"3\",\n \"𝟹\": \"3\",\n \"🯳\": \"3\",\n \"\": \"3\",\n \"Ȝ\": \"3\",\n \"Ʒ\": \"3\",\n \"\": \"3\",\n \"\": \"3\",\n \"З\": \"3\",\n \"Ӡ\": \"3\",\n \"𖼻\": \"3\",\n \"𑣊\": \"3\",\n \"۳\": \"٣\",\n \"𞣉\": \"٣\",\n \"૩\": \"३\",\n \"③\": \"➂\",\n \"Ҙ\": \"3̦\",\n \"🄄\": \"3,\",\n \"⒊\": \"3.\",\n \"㏾\": \"3l日\",\n \"㏽\": \"3O日\",\n \"㏢\": \"3日\",\n \"㋂\": \"3月\",\n \"㍛\": \"3点\",\n \"𝟒\": \"4\",\n \"𝟜\": \"4\",\n \"𝟦\": \"4\",\n \"𝟰\": \"4\",\n \"𝟺\": \"4\",\n \"🯴\": \"4\",\n \"\": \"4\",\n \"𑢯\": \"4\",\n \"۴\": \"٤\",\n \"૪\": \"४\",\n \"④\": \"➃\",\n \"🄅\": \"4,\",\n \"⒋\": \"4.\",\n \"ᔰ\": \"4·\",\n \"㏣\": \"4日\",\n \"㋃\": \"4月\",\n \"㍜\": \"4点\",\n \"𝟓\": \"5\",\n \"𝟝\": \"5\",\n \"𝟧\": \"5\",\n \"𝟱\": \"5\",\n \"𝟻\": \"5\",\n \"🯵\": \"5\",\n \"Ƽ\": \"5\",\n \"𑢻\": \"5\",\n \"⑤\": \"➄\",\n \"🄆\": \"5,\",\n \"⒌\": \"5.\",\n \"㏤\": \"5日\",\n \"㋄\": \"5月\",\n \"㍝\": \"5点\",\n \"𝟔\": \"6\",\n \"𝟞\": \"6\",\n \"𝟨\": \"6\",\n \"𝟲\": \"6\",\n \"𝟼\": \"6\",\n \"🯶\": \"6\",\n \"\": \"6\",\n \"б\": \"6\",\n \"\": \"6\",\n \"𑣕\": \"6\",\n \"۶\": \"٦\",\n \"𑓖\": \"৬\",\n \"⑥\": \"➅\",\n \"🄇\": \"6,\",\n \"⒍\": \"6.\",\n \"㏥\": \"6日\",\n \"㋅\": \"6月\",\n \"㍞\": \"6点\",\n \"𝈒\": \"7\",\n \"𝟕\": \"7\",\n \"𝟟\": \"7\",\n \"𝟩\": \"7\",\n \"𝟳\": \"7\",\n \"𝟽\": \"7\",\n \"🯷\": \"7\",\n \"𐓒\": \"7\",\n \"𑣆\": \"7\",\n \"⑦\": \"➆\",\n \"🄈\": \"7,\",\n \"⒎\": \"7.\",\n \"㏦\": \"7日\",\n \"㋆\": \"7月\",\n \"㍟\": \"7点\",\n \"\": \"8\",\n \"\": \"8\",\n \"\": \"8\",\n \"𞣋\": \"8\",\n \"𝟖\": \"8\",\n \"𝟠\": \"8\",\n \"𝟪\": \"8\",\n \"𝟴\": \"8\",\n \"𝟾\": \"8\",\n \"🯸\": \"8\",\n \"ȣ\": \"8\",\n \"Ȣ\": \"8\",\n \"𐌚\": \"8\",\n \"૮\": \"८\",\n \"⑧\": \"➇\",\n \"🄉\": \"8,\",\n \"⒏\": \"8.\",\n \"㏧\": \"8日\",\n \"㋇\": \"8月\",\n \"㍠\": \"8点\",\n \"\": \"9\",\n \"\": \"9\",\n \"\": \"9\",\n \"\": \"9\",\n \"𝟗\": \"9\",\n \"𝟡\": \"9\",\n \"𝟫\": \"9\",\n \"𝟵\": \"9\",\n \"𝟿\": \"9\",\n \"🯹\": \"9\",\n \"\": \"9\",\n \"\": \"9\",\n \"𑣌\": \"9\",\n \"𑢬\": \"9\",\n \"𑣖\": \"9\",\n \"१\": \"٩\",\n \"𑣤\": \"٩\",\n \"۹\": \"٩\",\n \"೯\": \"౯\",\n \"⑨\": \"➈\",\n \"🄊\": \"9,\",\n \"⒐\": \"9.\",\n \"㏨\": \"9日\",\n \"㋈\": \"9月\",\n \"㍡\": \"9点\",\n \"\": \"a\",\n \"\": \"a\",\n \"𝐚\": \"a\",\n \"𝑎\": \"a\",\n \"𝒂\": \"a\",\n \"𝒶\": \"a\",\n \"𝓪\": \"a\",\n \"𝔞\": \"a\",\n \"𝕒\": \"a\",\n \"𝖆\": \"a\",\n \"𝖺\": \"a\",\n \"𝗮\": \"a\",\n \"𝘢\": \"a\",\n \"𝙖\": \"a\",\n \"𝚊\": \"a\",\n \"ɑ\": \"a\",\n \"α\": \"a\",\n \"𝛂\": \"a\",\n \"𝛼\": \"a\",\n \"𝜶\": \"a\",\n \"𝝰\": \"a\",\n \"𝞪\": \"a\",\n \"а\": \"a\",\n \"ⷶ\": \"ͣ\",\n \"\": \"A\",\n \"𝐀\": \"A\",\n \"𝐴\": \"A\",\n \"𝑨\": \"A\",\n \"𝒜\": \"A\",\n \"𝓐\": \"A\",\n \"𝔄\": \"A\",\n \"𝔸\": \"A\",\n \"𝕬\": \"A\",\n \"𝖠\": \"A\",\n \"𝗔\": \"A\",\n \"𝘈\": \"A\",\n \"𝘼\": \"A\",\n \"𝙰\": \"A\",\n \"Α\": \"A\",\n \"𝚨\": \"A\",\n \"𝛢\": \"A\",\n \"𝜜\": \"A\",\n \"𝝖\": \"A\",\n \"𝞐\": \"A\",\n \"А\": \"A\",\n \"\": \"A\",\n \"\": \"A\",\n \"\": \"A\",\n \"𖽀\": \"A\",\n \"𐊠\": \"A\",\n \"⍶\": \"a̲\",\n \"ǎ\": \"ă\",\n \"Ǎ\": \"Ă\",\n \"ȧ\": \"å\",\n \"Ȧ\": \"Å\",\n \"ẚ\": \"ả\",\n \"℀\": \"a/c\",\n \"℁\": \"a/s\",\n \"ꜳ\": \"aa\",\n \"Ꜳ\": \"AA\",\n \"æ\": \"ae\",\n \"ӕ\": \"ae\",\n \"Æ\": \"AE\",\n \"Ӕ\": \"AE\",\n \"ꜵ\": \"ao\",\n \"Ꜵ\": \"AO\",\n \"🜇\": \"AR\",\n \"ꜷ\": \"au\",\n \"Ꜷ\": \"AU\",\n \"ꜹ\": \"av\",\n \"ꜻ\": \"av\",\n \"Ꜹ\": \"AV\",\n \"Ꜻ\": \"AV\",\n \"ꜽ\": \"ay\",\n \"Ꜽ\": \"AY\",\n \"ꭺ\": \"ᴀ\",\n \"∀\": \"Ɐ\",\n \"𝈗\": \"Ɐ\",\n \"ᗄ\": \"Ɐ\",\n \"ꓯ\": \"Ɐ\",\n \"𐐟\": \"Ɒ\",\n \"𝐛\": \"b\",\n \"𝑏\": \"b\",\n \"𝒃\": \"b\",\n \"𝒷\": \"b\",\n \"𝓫\": \"b\",\n \"𝔟\": \"b\",\n \"𝕓\": \"b\",\n \"𝖇\": \"b\",\n \"𝖻\": \"b\",\n \"𝗯\": \"b\",\n \"𝘣\": \"b\",\n \"𝙗\": \"b\",\n \"𝚋\": \"b\",\n \"Ƅ\": \"b\",\n \"Ь\": \"b\",\n \"\": \"b\",\n \"\": \"b\",\n \"\": \"b\",\n \"\": \"B\",\n \"\": \"B\",\n \"𝐁\": \"B\",\n \"𝐵\": \"B\",\n \"𝑩\": \"B\",\n \"𝓑\": \"B\",\n \"𝔅\": \"B\",\n \"𝔹\": \"B\",\n \"𝕭\": \"B\",\n \"𝖡\": \"B\",\n \"𝗕\": \"B\",\n \"𝘉\": \"B\",\n \"𝘽\": \"B\",\n \"𝙱\": \"B\",\n \"\": \"B\",\n \"Β\": \"B\",\n \"𝚩\": \"B\",\n \"𝛣\": \"B\",\n \"𝜝\": \"B\",\n \"𝝗\": \"B\",\n \"𝞑\": \"B\",\n \"В\": \"B\",\n \"\": \"B\",\n \"\": \"B\",\n \"\": \"B\",\n \"𐊂\": \"B\",\n \"𐊡\": \"B\",\n \"𐌁\": \"B\",\n \"ɓ\": \"b̔\",\n \"ᑳ\": \"ḃ\",\n \"ƃ\": \"b̄\",\n \"Ƃ\": \"b̄\",\n \"Б\": \"b̄\",\n \"ƀ\": \"b̵\",\n \"ҍ\": \"b̵\",\n \"Ҍ\": \"b̵\",\n \"ѣ\": \"b̵\",\n \"Ѣ\": \"b̵\",\n \"ᑿ\": \"b·\",\n \"ᒁ\": \"ḃ·\",\n \"ᒈ\": \"b'\",\n \"Ы\": \"bl\",\n \"в\": \"ʙ\",\n \"ᏼ\": \"ʙ\",\n \"\": \"c\",\n \"\": \"c\",\n \"𝐜\": \"c\",\n \"𝑐\": \"c\",\n \"𝒄\": \"c\",\n \"𝒸\": \"c\",\n \"𝓬\": \"c\",\n \"𝔠\": \"c\",\n \"𝕔\": \"c\",\n \"𝖈\": \"c\",\n \"𝖼\": \"c\",\n \"𝗰\": \"c\",\n \"𝘤\": \"c\",\n \"𝙘\": \"c\",\n \"𝚌\": \"c\",\n \"\": \"c\",\n \"ϲ\": \"c\",\n \"\": \"c\",\n \"с\": \"c\",\n \"\": \"c\",\n \"𐐽\": \"c\",\n \"ⷭ\": \"ͨ\",\n \"🝌\": \"C\",\n \"𑣲\": \"C\",\n \"𑣩\": \"C\",\n \"\": \"C\",\n \"\": \"C\",\n \"\": \"C\",\n \"\": \"C\",\n \"𝐂\": \"C\",\n \"𝐶\": \"C\",\n \"𝑪\": \"C\",\n \"𝒞\": \"C\",\n \"𝓒\": \"C\",\n \"𝕮\": \"C\",\n \"𝖢\": \"C\",\n \"𝗖\": \"C\",\n \"𝘊\": \"C\",\n \"𝘾\": \"C\",\n \"𝙲\": \"C\",\n \"Ϲ\": \"C\",\n \"\": \"C\",\n \"С\": \"C\",\n \"\": \"C\",\n \"\": \"C\",\n \"𐊢\": \"C\",\n \"𐌂\": \"C\",\n \"𐐕\": \"C\",\n \"𐔜\": \"C\",\n \"¢\": \"c̸\",\n \"ȼ\": \"c̸\",\n \"₡\": \"C⃫\",\n \"🅮\": \"C⃠\",\n \"ç\": \"c̦\",\n \"ҫ\": \"c̦\",\n \"Ç\": \"C̦\",\n \"Ҫ\": \"C̦\",\n \"Ƈ\": \"C'\",\n \"℅\": \"c/o\",\n \"℆\": \"c/u\",\n \"🅭\": \"㏄\\t⃝\",\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 \"\": \"d\",\n \"\": \"d\",\n \"𝐝\": \"d\",\n \"𝑑\": \"d\",\n \"𝒅\": \"d\",\n \"𝒹\": \"d\",\n \"𝓭\": \"d\",\n \"𝔡\": \"d\",\n \"𝕕\": \"d\",\n \"𝖉\": \"d\",\n \"𝖽\": \"d\",\n \"𝗱\": \"d\",\n \"𝘥\": \"d\",\n \"𝙙\": \"d\",\n \"𝚍\": \"d\",\n \"ԁ\": \"d\",\n \"\": \"d\",\n \"\": \"d\",\n \"\": \"d\",\n \"\": \"D\",\n \"\": \"D\",\n \"𝐃\": \"D\",\n \"𝐷\": \"D\",\n \"𝑫\": \"D\",\n \"𝒟\": \"D\",\n \"𝓓\": \"D\",\n \"𝔇\": \"D\",\n \"𝔻\": \"D\",\n \"𝕯\": \"D\",\n \"𝖣\": \"D\",\n \"𝗗\": \"D\",\n \"𝘋\": \"D\",\n \"𝘿\": \"D\",\n \"𝙳\": \"D\",\n \"\": \"D\",\n \"\": \"D\",\n \"\": \"D\",\n \"\": \"D\",\n \"ɗ\": \"d̔\",\n \"ɖ\": \"d̨\",\n \"ƌ\": \"d̄\",\n \"đ\": \"d̵\",\n \"Đ\": \"D̵\",\n \"Ð\": \"D̵\",\n \"Ɖ\": \"D̵\",\n \"₫\": \"ḏ̵\",\n \"ꝺ\": \"Ꝺ\",\n \"ᑻ\": \"d·\",\n \"ᒇ\": \"d'\",\n \"ʤ\": \"dȝ\",\n \"dz\": \"dz\",\n \"ʣ\": \"dz\",\n \"Dz\": \"Dz\",\n \"DZ\": \"DZ\",\n \"dž\": \"dž\",\n \"Dž\": \"Dž\",\n \"DŽ\": \"DŽ\",\n \"ʥ\": \"dʑ\",\n \"ꭰ\": \"ᴅ\",\n \"⸹\": \"ẟ\",\n \"δ\": \"ẟ\",\n \"𝛅\": \"ẟ\",\n \"𝛿\": \"ẟ\",\n \"𝜹\": \"ẟ\",\n \"𝝳\": \"ẟ\",\n \"𝞭\": \"ẟ\",\n \"ծ\": \"ẟ\",\n \"ᕷ\": \"ẟ\",\n \"\": \"e\",\n \"\": \"e\",\n \"\": \"e\",\n \"\": \"e\",\n \"𝐞\": \"e\",\n \"𝑒\": \"e\",\n \"𝒆\": \"e\",\n \"𝓮\": \"e\",\n \"𝔢\": \"e\",\n \"𝕖\": \"e\",\n \"𝖊\": \"e\",\n \"𝖾\": \"e\",\n \"𝗲\": \"e\",\n \"𝘦\": \"e\",\n \"𝙚\": \"e\",\n \"𝚎\": \"e\",\n \"\": \"e\",\n \"е\": \"e\",\n \"ҽ\": \"e\",\n \"ⷷ\": \"ͤ\",\n \"\": \"E\",\n \"\": \"E\",\n \"\": \"E\",\n \"𝐄\": \"E\",\n \"𝐸\": \"E\",\n \"𝑬\": \"E\",\n \"𝓔\": \"E\",\n \"𝔈\": \"E\",\n \"𝔼\": \"E\",\n \"𝕰\": \"E\",\n \"𝖤\": \"E\",\n \"𝗘\": \"E\",\n \"𝘌\": \"E\",\n \"𝙀\": \"E\",\n \"𝙴\": \"E\",\n \"Ε\": \"E\",\n \"𝚬\": \"E\",\n \"𝛦\": \"E\",\n \"𝜠\": \"E\",\n \"𝝚\": \"E\",\n \"𝞔\": \"E\",\n \"Е\": \"E\",\n \"\": \"E\",\n \"\": \"E\",\n \"\": \"E\",\n \"𑢦\": \"E\",\n \"𑢮\": \"E\",\n \"𐊆\": \"E\",\n \"ě\": \"ĕ\",\n \"Ě\": \"Ĕ\",\n \"ɇ\": \"e̸\",\n \"Ɇ\": \"E̸\",\n \"ҿ\": \"ę\",\n \"ꭼ\": \"ᴇ\",\n \"ə\": \"ǝ\",\n \"ә\": \"ǝ\",\n \"∃\": \"Ǝ\",\n \"ⴺ\": \"Ǝ\",\n \"ꓱ\": \"Ǝ\",\n \"ɚ\": \"ǝ˞\",\n \"ᴔ\": \"ǝo\",\n \"ꭁ\": \"ǝo̸\",\n \"ꭂ\": \"ǝo̵\",\n \"Ә\": \"Ə\",\n \"𝈡\": \"Ɛ\",\n \"ℇ\": \"Ɛ\",\n \"Ԑ\": \"Ɛ\",\n \"Ꮛ\": \"Ɛ\",\n \"𖼭\": \"Ɛ\",\n \"𐐁\": \"Ɛ\",\n \"ᶟ\": \"ᵋ\",\n \"ᴈ\": \"ɜ\",\n \"з\": \"ɜ\",\n \"ҙ\": \"ɜ̦\",\n \"𐑂\": \"ɞ\",\n \"ꞝ\": \"ʚ\",\n \"𐐪\": \"ʚ\",\n \"𝐟\": \"f\",\n \"𝑓\": \"f\",\n \"𝒇\": \"f\",\n \"𝒻\": \"f\",\n \"𝓯\": \"f\",\n \"𝔣\": \"f\",\n \"𝕗\": \"f\",\n \"𝖋\": \"f\",\n \"𝖿\": \"f\",\n \"𝗳\": \"f\",\n \"𝘧\": \"f\",\n \"𝙛\": \"f\",\n \"𝚏\": \"f\",\n \"\": \"f\",\n \"\": \"f\",\n \"ſ\": \"f\",\n \"\": \"f\",\n \"ք\": \"f\",\n \"𝈓\": \"F\",\n \"\": \"F\",\n \"𝐅\": \"F\",\n \"𝐹\": \"F\",\n \"𝑭\": \"F\",\n \"𝓕\": \"F\",\n \"𝔉\": \"F\",\n \"𝔽\": \"F\",\n \"𝕱\": \"F\",\n \"𝖥\": \"F\",\n \"𝗙\": \"F\",\n \"𝘍\": \"F\",\n \"𝙁\": \"F\",\n \"𝙵\": \"F\",\n \"\": \"F\",\n \"Ϝ\": \"F\",\n \"𝟊\": \"F\",\n \"\": \"F\",\n \"\": \"F\",\n \"𑣂\": \"F\",\n \"𑢢\": \"F\",\n \"𐊇\": \"F\",\n \"𐊥\": \"F\",\n \"𐔥\": \"F\",\n \"ƒ\": \"f̦\",\n \"Ƒ\": \"F̦\",\n \"ᵮ\": \"f̴\",\n \"℻\": \"FAX\",\n \"ff\": \"ff\",\n \"ffi\": \"ffi\",\n \"ffl\": \"ffl\",\n \"fi\": \"fi\",\n \"fl\": \"fl\",\n \"ʩ\": \"fŋ\",\n \"ᖵ\": \"Ⅎ\",\n \"ꓞ\": \"Ⅎ\",\n \"𝈰\": \"ꟻ\",\n \"ᖷ\": \"ꟻ\",\n \"\": \"g\",\n \"\": \"g\",\n \"𝐠\": \"g\",\n \"𝑔\": \"g\",\n \"𝒈\": \"g\",\n \"𝓰\": \"g\",\n \"𝔤\": \"g\",\n \"𝕘\": \"g\",\n \"𝖌\": \"g\",\n \"𝗀\": \"g\",\n \"𝗴\": \"g\",\n \"𝘨\": \"g\",\n \"𝙜\": \"g\",\n \"𝚐\": \"g\",\n \"ɡ\": \"g\",\n \"\": \"g\",\n \"ƍ\": \"g\",\n \"ց\": \"g\",\n \"𝐆\": \"G\",\n \"𝐺\": \"G\",\n \"𝑮\": \"G\",\n \"𝒢\": \"G\",\n \"𝓖\": \"G\",\n \"𝔊\": \"G\",\n \"𝔾\": \"G\",\n \"𝕲\": \"G\",\n \"𝖦\": \"G\",\n \"𝗚\": \"G\",\n \"𝘎\": \"G\",\n \"𝙂\": \"G\",\n \"𝙶\": \"G\",\n \"Ԍ\": \"G\",\n \"\": \"G\",\n \"\": \"G\",\n \"\": \"G\",\n \"ᶢ\": \"ᵍ\",\n \"ɠ\": \"g̔\",\n \"ǧ\": \"ğ\",\n \"Ǧ\": \"Ğ\",\n \"ǵ\": \"ģ\",\n \"ǥ\": \"g̵\",\n \"Ǥ\": \"G̵\",\n \"Ɠ\": \"G'\",\n \"ԍ\": \"ɢ\",\n \"ꮐ\": \"ɢ\",\n \"ᏻ\": \"ɢ\",\n \"\": \"h\",\n \"\": \"h\",\n \"𝐡\": \"h\",\n \"𝒉\": \"h\",\n \"𝒽\": \"h\",\n \"𝓱\": \"h\",\n \"𝔥\": \"h\",\n \"𝕙\": \"h\",\n \"𝖍\": \"h\",\n \"𝗁\": \"h\",\n \"𝗵\": \"h\",\n \"𝘩\": \"h\",\n \"𝙝\": \"h\",\n \"𝚑\": \"h\",\n \"һ\": \"h\",\n \"հ\": \"h\",\n \"\": \"h\",\n \"\": \"H\",\n \"\": \"H\",\n \"\": \"H\",\n \"\": \"H\",\n \"𝐇\": \"H\",\n \"𝐻\": \"H\",\n \"𝑯\": \"H\",\n \"𝓗\": \"H\",\n \"𝕳\": \"H\",\n \"𝖧\": \"H\",\n \"𝗛\": \"H\",\n \"𝘏\": \"H\",\n \"𝙃\": \"H\",\n \"𝙷\": \"H\",\n \"Η\": \"H\",\n \"𝚮\": \"H\",\n \"𝛨\": \"H\",\n \"𝜢\": \"H\",\n \"𝝜\": \"H\",\n \"𝞖\": \"H\",\n \"\": \"H\",\n \"Н\": \"H\",\n \"\": \"H\",\n \"\": \"H\",\n \"\": \"H\",\n \"𐋏\": \"H\",\n \"ᵸ\": \"ᴴ\",\n \"ɦ\": \"h̔\",\n \"ꚕ\": \"h̔\",\n \"Ᏺ\": \"h̔\",\n \"Ⱨ\": \"H̩\",\n \"Ң\": \"H̩\",\n \"ħ\": \"h̵\",\n \"ℏ\": \"h̵\",\n \"ћ\": \"h̵\",\n \"Ħ\": \"H̵\",\n \"Ӊ\": \"H̦\",\n \"Ӈ\": \"H̦\",\n \"н\": \"ʜ\",\n \"ꮋ\": \"ʜ\",\n \"ң\": \"ʜ̩\",\n \"ӊ\": \"ʜ̦\",\n \"ӈ\": \"ʜ̦\",\n \"Ԋ\": \"Ƕ\",\n \"ꮀ\": \"ⱶ\",\n \"Ͱ\": \"Ⱶ\",\n \"Ꭸ\": \"Ⱶ\",\n \"Ꮀ\": \"Ⱶ\",\n \"ꚱ\": \"Ⱶ\",\n \"ꞕ\": \"ꜧ\",\n \"˛\": \"i\",\n \"\": \"i\",\n \"\": \"i\",\n \"\": \"i\",\n \"\": \"i\",\n \"\": \"i\",\n \"𝐢\": \"i\",\n \"𝑖\": \"i\",\n \"𝒊\": \"i\",\n \"𝒾\": \"i\",\n \"𝓲\": \"i\",\n \"𝔦\": \"i\",\n \"𝕚\": \"i\",\n \"𝖎\": \"i\",\n \"𝗂\": \"i\",\n \"𝗶\": \"i\",\n \"𝘪\": \"i\",\n \"𝙞\": \"i\",\n \"𝚒\": \"i\",\n \"ı\": \"i\",\n \"𝚤\": \"i\",\n \"ɪ\": \"i\",\n \"ɩ\": \"i\",\n \"ι\": \"i\",\n \"\": \"i\",\n \"ͺ\": \"i\",\n \"𝛊\": \"i\",\n \"𝜄\": \"i\",\n \"𝜾\": \"i\",\n \"𝝸\": \"i\",\n \"𝞲\": \"i\",\n \"і\": \"i\",\n \"\": \"i\",\n \"ӏ\": \"i\",\n \"\": \"i\",\n \"\": \"i\",\n \"𑣃\": \"i\",\n \"ⓛ\": \"Ⓘ\",\n \"⍸\": \"i̲\",\n \"ǐ\": \"ĭ\",\n \"Ǐ\": \"Ĭ\",\n \"ɨ\": \"i̵\",\n \"ᵻ\": \"i̵\",\n \"ᵼ\": \"i̵\",\n \"ⅱ\": \"ii\",\n \"ⅲ\": \"iii\",\n \"ij\": \"ij\",\n \"ⅳ\": \"iv\",\n \"ⅸ\": \"ix\",\n \"\": \"j\",\n \"\": \"j\",\n \"𝐣\": \"j\",\n \"𝑗\": \"j\",\n \"𝒋\": \"j\",\n \"𝒿\": \"j\",\n \"𝓳\": \"j\",\n \"𝔧\": \"j\",\n \"𝕛\": \"j\",\n \"𝖏\": \"j\",\n \"𝗃\": \"j\",\n \"𝗷\": \"j\",\n \"𝘫\": \"j\",\n \"𝙟\": \"j\",\n \"𝚓\": \"j\",\n \"ϳ\": \"j\",\n \"ј\": \"j\",\n \"\": \"J\",\n \"𝐉\": \"J\",\n \"𝐽\": \"J\",\n \"𝑱\": \"J\",\n \"𝒥\": \"J\",\n \"𝓙\": \"J\",\n \"𝔍\": \"J\",\n \"𝕁\": \"J\",\n \"𝕵\": \"J\",\n \"𝖩\": \"J\",\n \"𝗝\": \"J\",\n \"𝘑\": \"J\",\n \"𝙅\": \"J\",\n \"𝙹\": \"J\",\n \"\": \"J\",\n \"Ϳ\": \"J\",\n \"Ј\": \"J\",\n \"\": \"J\",\n \"\": \"J\",\n \"\": \"J\",\n \"ɉ\": \"j̵\",\n \"Ɉ\": \"J̵\",\n \"ᒙ\": \"J·\",\n \"𝚥\": \"ȷ\",\n \"յ\": \"ȷ\",\n \"ꭻ\": \"ᴊ\",\n \"𝐤\": \"k\",\n \"𝑘\": \"k\",\n \"𝒌\": \"k\",\n \"𝓀\": \"k\",\n \"𝓴\": \"k\",\n \"𝔨\": \"k\",\n \"𝕜\": \"k\",\n \"𝖐\": \"k\",\n \"𝗄\": \"k\",\n \"𝗸\": \"k\",\n \"𝘬\": \"k\",\n \"𝙠\": \"k\",\n \"𝚔\": \"k\",\n \"\": \"K\",\n \"\": \"K\",\n \"𝐊\": \"K\",\n \"𝐾\": \"K\",\n \"𝑲\": \"K\",\n \"𝒦\": \"K\",\n \"𝓚\": \"K\",\n \"𝔎\": \"K\",\n \"𝕂\": \"K\",\n \"𝕶\": \"K\",\n \"𝖪\": \"K\",\n \"𝗞\": \"K\",\n \"𝘒\": \"K\",\n \"𝙆\": \"K\",\n \"𝙺\": \"K\",\n \"Κ\": \"K\",\n \"𝚱\": \"K\",\n \"𝛫\": \"K\",\n \"𝜥\": \"K\",\n \"𝝟\": \"K\",\n \"𝞙\": \"K\",\n \"\": \"K\",\n \"К\": \"K\",\n \"\": \"K\",\n \"\": \"K\",\n \"\": \"K\",\n \"𐔘\": \"K\",\n \"ƙ\": \"k̔\",\n \"Ⱪ\": \"K̩\",\n \"Қ\": \"K̩\",\n \"₭\": \"K̵\",\n \"Ꝁ\": \"K̵\",\n \"Ҟ\": \"K̵\",\n \"Ƙ\": \"K'\",\n \"׀\": \"l\",\n \"|\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"١\": \"l\",\n \"۱\": \"l\",\n \"𐌠\": \"l\",\n \"𞣇\": \"l\",\n \"𝟏\": \"l\",\n \"𝟙\": \"l\",\n \"𝟣\": \"l\",\n \"𝟭\": \"l\",\n \"𝟷\": \"l\",\n \"🯱\": \"l\",\n \"I\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"𝐈\": \"l\",\n \"𝐼\": \"l\",\n \"𝑰\": \"l\",\n \"𝓘\": \"l\",\n \"𝕀\": \"l\",\n \"𝕴\": \"l\",\n \"𝖨\": \"l\",\n \"𝗜\": \"l\",\n \"𝘐\": \"l\",\n \"𝙄\": \"l\",\n \"𝙸\": \"l\",\n \"Ɩ\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"𝐥\": \"l\",\n \"𝑙\": \"l\",\n \"𝒍\": \"l\",\n \"𝓁\": \"l\",\n \"𝓵\": \"l\",\n \"𝔩\": \"l\",\n \"𝕝\": \"l\",\n \"𝖑\": \"l\",\n \"𝗅\": \"l\",\n \"𝗹\": \"l\",\n \"𝘭\": \"l\",\n \"𝙡\": \"l\",\n \"𝚕\": \"l\",\n \"ǀ\": \"l\",\n \"Ι\": \"l\",\n \"𝚰\": \"l\",\n \"𝛪\": \"l\",\n \"𝜤\": \"l\",\n \"𝝞\": \"l\",\n \"𝞘\": \"l\",\n \"\": \"l\",\n \"І\": \"l\",\n \"Ӏ\": \"l\",\n \"ו\": \"l\",\n \"ן\": \"l\",\n \"ا\": \"l\",\n \"𞸀\": \"l\",\n \"𞺀\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"ߊ\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"\": \"l\",\n \"𖼨\": \"l\",\n \"𐊊\": \"l\",\n \"𐌉\": \"l\",\n \"𝈪\": \"L\",\n \"\": \"L\",\n \"\": \"L\",\n \"𝐋\": \"L\",\n \"𝐿\": \"L\",\n \"𝑳\": \"L\",\n \"𝓛\": \"L\",\n \"𝔏\": \"L\",\n \"𝕃\": \"L\",\n \"𝕷\": \"L\",\n \"𝖫\": \"L\",\n \"𝗟\": \"L\",\n \"𝘓\": \"L\",\n \"𝙇\": \"L\",\n \"𝙻\": \"L\",\n \"\": \"L\",\n \"\": \"L\",\n \"\": \"L\",\n \"\": \"L\",\n \"𖼖\": \"L\",\n \"𑢣\": \"L\",\n \"𑢲\": \"L\",\n \"𐐛\": \"L\",\n \"𐔦\": \"L\",\n \"ﴼ\": \"l̋\",\n \"ﴽ\": \"l̋\",\n \"ł\": \"l̸\",\n \"Ł\": \"L̸\",\n \"ɭ\": \"l̨\",\n \"Ɨ\": \"l̵\",\n \"ƚ\": \"l̵\",\n \"ɫ\": \"l̴\",\n \"إ\": \"lٕ\",\n \"ﺈ\": \"lٕ\",\n \"ﺇ\": \"lٕ\",\n \"ٳ\": \"lٕ\",\n \"ŀ\": \"l·\",\n \"Ŀ\": \"l·\",\n \"ᒷ\": \"l·\",\n \"🄂\": \"l,\",\n \"⒈\": \"l.\",\n \"ױ\": \"l'\",\n \"⒓\": \"l2.\",\n \"㏫\": \"l2日\",\n \"㋋\": \"l2月\",\n \"㍤\": \"l2点\",\n \"⒔\": \"l3.\",\n \"㏬\": \"l3日\",\n \"㍥\": \"l3点\",\n \"⒕\": \"l4.\",\n \"㏭\": \"l4日\",\n \"㍦\": \"l4点\",\n \"⒖\": \"l5.\",\n \"㏮\": \"l5日\",\n \"㍧\": \"l5点\",\n \"⒗\": \"l6.\",\n \"㏯\": \"l6日\",\n \"㍨\": \"l6点\",\n \"⒘\": \"l7.\",\n \"㏰\": \"l7日\",\n \"㍩\": \"l7点\",\n \"⒙\": \"l8.\",\n \"㏱\": \"l8日\",\n \"㍪\": \"l8点\",\n \"⒚\": \"l9.\",\n \"㏲\": \"l9日\",\n \"㍫\": \"l9点\",\n \"lj\": \"lj\",\n \"IJ\": \"lJ\",\n \"Lj\": \"Lj\",\n \"LJ\": \"LJ\",\n \"‖\": \"ll\",\n \"∥\": \"ll\",\n \"Ⅱ\": \"ll\",\n \"ǁ\": \"ll\",\n \"װ\": \"ll\",\n \"𐆙\": \"l̵l̵\",\n \"⒒\": \"ll.\",\n \"Ⅲ\": \"lll\",\n \"𐆘\": \"l̵l̵S̵\",\n \"㏪\": \"ll日\",\n \"㋊\": \"ll月\",\n \"㍣\": \"ll点\",\n \"Ю\": \"lO\",\n \"⒑\": \"lO.\",\n \"㏩\": \"lO日\",\n \"㋉\": \"lO月\",\n \"㍢\": \"lO点\",\n \"ʪ\": \"ls\",\n \"₶\": \"lt\",\n \"Ⅳ\": \"lV\",\n \"Ⅸ\": \"lX\",\n \"ɮ\": \"lȝ\",\n \"ʫ\": \"lz\",\n \"أ\": \"lٴ\",\n \"ﺄ\": \"lٴ\",\n \"ﺃ\": \"lٴ\",\n \"ٲ\": \"lٴ\",\n \"ٵ\": \"lٴ\",\n \"ﷳ\": \"lكبر\",\n \"ﷲ\": \"lللّٰo\",\n \"㏠\": \"l日\",\n \"㋀\": \"l月\",\n \"㍙\": \"l点\",\n \"ⳑ\": \"ʟ\",\n \"ꮮ\": \"ʟ\",\n \"𐑃\": \"ʟ\",\n \"\": \"M\",\n \"\": \"M\",\n \"\": \"M\",\n \"𝐌\": \"M\",\n \"𝑀\": \"M\",\n \"𝑴\": \"M\",\n \"𝓜\": \"M\",\n \"𝔐\": \"M\",\n \"𝕄\": \"M\",\n \"𝕸\": \"M\",\n \"𝖬\": \"M\",\n \"𝗠\": \"M\",\n \"𝘔\": \"M\",\n \"𝙈\": \"M\",\n \"𝙼\": \"M\",\n \"Μ\": \"M\",\n \"𝚳\": \"M\",\n \"𝛭\": \"M\",\n \"𝜧\": \"M\",\n \"𝝡\": \"M\",\n \"𝞛\": \"M\",\n \"Ϻ\": \"M\",\n \"\": \"M\",\n \"М\": \"M\",\n \"\": \"M\",\n \"\": \"M\",\n \"\": \"M\",\n \"\": \"M\",\n \"𐊰\": \"M\",\n \"𐌑\": \"M\",\n \"Ӎ\": \"M̦\",\n \"🝫\": \"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 \"𝖭\": \"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\",\n \"Nj\": \"Nj\",\n \"NJ\": \"NJ\",\n \"№\": \"No\",\n \"ͷ\": \"ᴎ\",\n \"и\": \"ᴎ\",\n \"𐑍\": \"ᴎ\",\n \"ņ\": \"ɲ\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"٥\": \"o\",\n \"۵\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"𝐨\": \"o\",\n \"𝑜\": \"o\",\n \"𝒐\": \"o\",\n \"𝓸\": \"o\",\n \"𝔬\": \"o\",\n \"𝕠\": \"o\",\n \"𝖔\": \"o\",\n \"𝗈\": \"o\",\n \"𝗼\": \"o\",\n \"𝘰\": \"o\",\n \"𝙤\": \"o\",\n \"𝚘\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"ο\": \"o\",\n \"𝛐\": \"o\",\n \"𝜊\": \"o\",\n \"𝝄\": \"o\",\n \"𝝾\": \"o\",\n \"𝞸\": \"o\",\n \"σ\": \"o\",\n \"𝛔\": \"o\",\n \"𝜎\": \"o\",\n \"𝝈\": \"o\",\n \"𝞂\": \"o\",\n \"𝞼\": \"o\",\n \"\": \"o\",\n \"о\": \"o\",\n \"\": \"o\",\n \"օ\": \"o\",\n \"ס\": \"o\",\n \"ه\": \"o\",\n \"𞸤\": \"o\",\n \"𞹤\": \"o\",\n \"𞺄\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"ھ\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"ہ\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"ە\": \"o\",\n \"\": \"o\",\n \"\": \"o\",\n \"𐓪\": \"o\",\n \"𑣈\": \"o\",\n \"𑣗\": \"o\",\n \"𐐬\": \"o\",\n \"߀\": \"O\",\n \"\": \"O\",\n \"\": \"O\",\n \"\": \"O\",\n \"𑓐\": \"O\",\n \"𑣠\": \"O\",\n \"𝟎\": \"O\",\n \"𝟘\": \"O\",\n \"𝟢\": \"O\",\n \"𝟬\": \"O\",\n \"𝟶\": \"O\",\n \"🯰\": \"O\",\n \"\": \"O\",\n \"𝐎\": \"O\",\n \"𝑂\": \"O\",\n \"𝑶\": \"O\",\n \"𝒪\": \"O\",\n \"𝓞\": \"O\",\n \"𝔒\": \"O\",\n \"𝕆\": \"O\",\n \"𝕺\": \"O\",\n \"𝖮\": \"O\",\n \"𝗢\": \"O\",\n \"𝘖\": \"O\",\n \"𝙊\": \"O\",\n \"𝙾\": \"O\",\n \"Ο\": \"O\",\n \"𝚶\": \"O\",\n \"𝛰\": \"O\",\n \"𝜪\": \"O\",\n \"𝝤\": \"O\",\n \"𝞞\": \"O\",\n \"\": \"O\",\n \"О\": \"O\",\n \"Օ\": \"O\",\n \"\": \"O\",\n \"\": \"O\",\n \"\": \"O\",\n \"𐓂\": \"O\",\n \"\": \"O\",\n \"𑢵\": \"O\",\n \"𐊒\": \"O\",\n \"𐊫\": \"O\",\n \"𐐄\": \"O\",\n \"𐔖\": \"O\",\n \"⁰\": \"º\",\n \"ᵒ\": \"º\",\n \"ǒ\": \"ŏ\",\n \"Ǒ\": \"Ŏ\",\n \"ۿ\": \"ô\",\n \"Ő\": \"Ö\",\n \"ø\": \"o̸\",\n \"ꬾ\": \"o̸\",\n \"Ø\": \"O̸\",\n \"ⵁ\": \"O̸\",\n \"Ǿ\": \"Ó̸\",\n \"ɵ\": \"o̵\",\n \"ꝋ\": \"o̵\",\n \"ө\": \"o̵\",\n \"ѳ\": \"o̵\",\n \"ꮎ\": \"o̵\",\n \"ꮻ\": \"o̵\",\n \"⊖\": \"O̵\",\n \"⊝\": \"O̵\",\n \"⍬\": \"O̵\",\n \"𝈚\": \"O̵\",\n \"🜔\": \"O̵\",\n \"Ɵ\": \"O̵\",\n \"Ꝋ\": \"O̵\",\n \"θ\": \"O̵\",\n \"ϑ\": \"O̵\",\n \"𝛉\": \"O̵\",\n \"𝛝\": \"O̵\",\n \"𝜃\": \"O̵\",\n \"𝜗\": \"O̵\",\n \"𝜽\": \"O̵\",\n \"𝝑\": \"O̵\",\n \"𝝷\": \"O̵\",\n \"𝞋\": \"O̵\",\n \"𝞱\": \"O̵\",\n \"𝟅\": \"O̵\",\n \"Θ\": \"O̵\",\n \"ϴ\": \"O̵\",\n \"𝚯\": \"O̵\",\n \"𝚹\": \"O̵\",\n \"𝛩\": \"O̵\",\n \"𝛳\": \"O̵\",\n \"𝜣\": \"O̵\",\n \"𝜭\": \"O̵\",\n \"𝝝\": \"O̵\",\n \"𝝧\": \"O̵\",\n \"𝞗\": \"O̵\",\n \"𝞡\": \"O̵\",\n \"Ө\": \"O̵\",\n \"Ѳ\": \"O̵\",\n \"ⴱ\": \"O̵\",\n \"Ꮎ\": \"O̵\",\n \"Ꮻ\": \"O̵\",\n \"ꭴ\": \"ơ\",\n \"ﳙ\": \"oٰ\",\n \"🄁\": \"O,\",\n \"🄀\": \"O.\",\n \"ơ\": \"o'\",\n \"Ơ\": \"O'\",\n \"Ꭴ\": \"O'\",\n \"%\": \"º/₀\",\n \"٪\": \"º/₀\",\n \"⁒\": \"º/₀\",\n \"‰\": \"º/₀₀\",\n \"؉\": \"º/₀₀\",\n \"‱\": \"º/₀₀₀\",\n \"؊\": \"º/₀₀₀\",\n \"œ\": \"oe\",\n \"Œ\": \"OE\",\n \"ɶ\": \"oᴇ\",\n \"∞\": \"oo\",\n \"ꝏ\": \"oo\",\n \"ꚙ\": \"oo\",\n \"Ꝏ\": \"OO\",\n \"Ꚙ\": \"OO\",\n \"ﳗ\": \"oج\",\n \"ﱑ\": \"oج\",\n \"ﳘ\": \"oم\",\n \"ﱒ\": \"oم\",\n \"ﶓ\": \"oمج\",\n \"ﶔ\": \"oمم\",\n \"ﱓ\": \"oى\",\n \"ﱔ\": \"oى\",\n \"ൟ\": \"oരo\",\n \"တ\": \"oာ\",\n \"㍘\": \"O点\",\n \"ↄ\": \"ɔ\",\n \"ᴐ\": \"ɔ\",\n \"ͻ\": \"ɔ\",\n \"𐑋\": \"ɔ\",\n \"Ↄ\": \"Ɔ\",\n \"Ͻ\": \"Ɔ\",\n \"ꓛ\": \"Ɔ\",\n \"𐐣\": \"Ɔ\",\n \"ꬿ\": \"ɔ̸\",\n \"ꭢ\": \"ɔe\",\n \"𐐿\": \"ɷ\",\n \"\": \"p\",\n \"\": \"p\",\n \"𝐩\": \"p\",\n \"𝑝\": \"p\",\n \"𝒑\": \"p\",\n \"𝓅\": \"p\",\n \"𝓹\": \"p\",\n \"𝔭\": \"p\",\n \"𝕡\": \"p\",\n \"𝖕\": \"p\",\n \"𝗉\": \"p\",\n \"𝗽\": \"p\",\n \"𝘱\": \"p\",\n \"𝙥\": \"p\",\n \"𝚙\": \"p\",\n \"ρ\": \"p\",\n \"ϱ\": \"p\",\n \"𝛒\": \"p\",\n \"𝛠\": \"p\",\n \"𝜌\": \"p\",\n \"𝜚\": \"p\",\n \"𝝆\": \"p\",\n \"𝝔\": \"p\",\n \"𝞀\": \"p\",\n \"𝞎\": \"p\",\n \"𝞺\": \"p\",\n \"𝟈\": \"p\",\n \"\": \"p\",\n \"р\": \"p\",\n \"\": \"P\",\n \"\": \"P\",\n \"𝐏\": \"P\",\n \"𝑃\": \"P\",\n \"𝑷\": \"P\",\n \"𝒫\": \"P\",\n \"𝓟\": \"P\",\n \"𝔓\": \"P\",\n \"𝕻\": \"P\",\n \"𝖯\": \"P\",\n \"𝗣\": \"P\",\n \"𝘗\": \"P\",\n \"𝙋\": \"P\",\n \"𝙿\": \"P\",\n \"Ρ\": \"P\",\n \"𝚸\": \"P\",\n \"𝛲\": \"P\",\n \"𝜬\": \"P\",\n \"𝝦\": \"P\",\n \"𝞠\": \"P\",\n \"\": \"P\",\n \"Р\": \"P\",\n \"\": \"P\",\n \"\": \"P\",\n \"\": \"P\",\n \"𐊕\": \"P\",\n \"ƥ\": \"p̔\",\n \"ᵽ\": \"p̵\",\n \"ᑷ\": \"p·\",\n \"ᒆ\": \"P'\",\n \"ᴩ\": \"ᴘ\",\n \"ꮲ\": \"ᴘ\",\n \"φ\": \"ɸ\",\n \"ϕ\": \"ɸ\",\n \"𝛗\": \"ɸ\",\n \"𝛟\": \"ɸ\",\n \"𝜑\": \"ɸ\",\n \"𝜙\": \"ɸ\",\n \"𝝋\": \"ɸ\",\n \"𝝓\": \"ɸ\",\n \"𝞅\": \"ɸ\",\n \"𝞍\": \"ɸ\",\n \"𝞿\": \"ɸ\",\n \"𝟇\": \"ɸ\",\n \"ⲫ\": \"ɸ\",\n \"ф\": \"ɸ\",\n \"𝐪\": \"q\",\n \"𝑞\": \"q\",\n \"𝒒\": \"q\",\n \"𝓆\": \"q\",\n \"𝓺\": \"q\",\n \"𝔮\": \"q\",\n \"𝕢\": \"q\",\n \"𝖖\": \"q\",\n \"𝗊\": \"q\",\n \"𝗾\": \"q\",\n \"𝘲\": \"q\",\n \"𝙦\": \"q\",\n \"𝚚\": \"q\",\n \"ԛ\": \"q\",\n \"գ\": \"q\",\n \"զ\": \"q\",\n \"\": \"Q\",\n \"𝐐\": \"Q\",\n \"𝑄\": \"Q\",\n \"𝑸\": \"Q\",\n \"𝒬\": \"Q\",\n \"𝓠\": \"Q\",\n \"𝔔\": \"Q\",\n \"𝕼\": \"Q\",\n \"𝖰\": \"Q\",\n \"𝗤\": \"Q\",\n \"𝘘\": \"Q\",\n \"𝙌\": \"Q\",\n \"𝚀\": \"Q\",\n \"\": \"Q\",\n \"ʠ\": \"q̔\",\n \"🜀\": \"QE\",\n \"ᶐ\": \"ɋ\",\n \"ᴋ\": \"ĸ\",\n \"κ\": \"ĸ\",\n \"ϰ\": \"ĸ\",\n \"𝛋\": \"ĸ\",\n \"𝛞\": \"ĸ\",\n \"𝜅\": \"ĸ\",\n \"𝜘\": \"ĸ\",\n \"𝜿\": \"ĸ\",\n \"𝝒\": \"ĸ\",\n \"𝝹\": \"ĸ\",\n \"𝞌\": \"ĸ\",\n \"𝞳\": \"ĸ\",\n \"𝟆\": \"ĸ\",\n \"ⲕ\": \"ĸ\",\n \"к\": \"ĸ\",\n \"ꮶ\": \"ĸ\",\n \"қ\": \"ĸ̩\",\n \"ҟ\": \"ĸ̵\",\n \"𝐫\": \"r\",\n \"𝑟\": \"r\",\n \"𝒓\": \"r\",\n \"𝓇\": \"r\",\n \"𝓻\": \"r\",\n \"𝔯\": \"r\",\n \"𝕣\": \"r\",\n \"𝖗\": \"r\",\n \"𝗋\": \"r\",\n \"𝗿\": \"r\",\n \"𝘳\": \"r\",\n \"𝙧\": \"r\",\n \"𝚛\": \"r\",\n \"\": \"r\",\n \"\": \"r\",\n \"\": \"r\",\n \"\": \"r\",\n \"г\": \"r\",\n \"\": \"r\",\n \"𝈖\": \"R\",\n \"\": \"R\",\n \"\": \"R\",\n \"\": \"R\",\n \"𝐑\": \"R\",\n \"𝑅\": \"R\",\n \"𝑹\": \"R\",\n \"𝓡\": \"R\",\n \"𝕽\": \"R\",\n \"𝖱\": \"R\",\n \"𝗥\": \"R\",\n \"𝘙\": \"R\",\n \"𝙍\": \"R\",\n \"𝚁\": \"R\",\n \"Ʀ\": \"R\",\n \"\": \"R\",\n \"\": \"R\",\n \"𐒴\": \"R\",\n \"\": \"R\",\n \"\": \"R\",\n \"𖼵\": \"R\",\n \"ɽ\": \"r̨\",\n \"ɼ\": \"r̩\",\n \"ɍ\": \"r̵\",\n \"ғ\": \"r̵\",\n \"ᵲ\": \"r̴\",\n \"ґ\": \"r'\",\n \"𑣣\": \"rn\",\n \"m\": \"rn\",\n \"ⅿ\": \"rn\",\n \"𝐦\": \"rn\",\n \"𝑚\": \"rn\",\n \"𝒎\": \"rn\",\n \"𝓂\": \"rn\",\n \"𝓶\": \"rn\",\n \"𝔪\": \"rn\",\n \"𝕞\": \"rn\",\n \"𝖒\": \"rn\",\n \"𝗆\": \"rn\",\n \"𝗺\": \"rn\",\n \"𝘮\": \"rn\",\n \"𝙢\": \"rn\",\n \"𝚖\": \"rn\",\n \"𑜀\": \"rn\",\n \"₥\": \"rn̸\",\n \"ɱ\": \"rn̦\",\n \"ᵯ\": \"rn̴\",\n \"₨\": \"Rs\",\n \"ꭱ\": \"ʀ\",\n \"ꮢ\": \"ʀ\",\n \"я\": \"ᴙ\",\n \"ᵳ\": \"ɾ̴\",\n \"℩\": \"ɿ\",\n \"\": \"s\",\n \"𝐬\": \"s\",\n \"𝑠\": \"s\",\n \"𝒔\": \"s\",\n \"𝓈\": \"s\",\n \"𝓼\": \"s\",\n \"𝔰\": \"s\",\n \"𝕤\": \"s\",\n \"𝖘\": \"s\",\n \"𝗌\": \"s\",\n \"𝘀\": \"s\",\n \"𝘴\": \"s\",\n \"𝙨\": \"s\",\n \"𝚜\": \"s\",\n \"\": \"s\",\n \"ƽ\": \"s\",\n \"ѕ\": \"s\",\n \"\": \"s\",\n \"𑣁\": \"s\",\n \"𐑈\": \"s\",\n \"\": \"S\",\n \"𝐒\": \"S\",\n \"𝑆\": \"S\",\n \"𝑺\": \"S\",\n \"𝒮\": \"S\",\n \"𝓢\": \"S\",\n \"𝔖\": \"S\",\n \"𝕊\": \"S\",\n \"𝕾\": \"S\",\n \"𝖲\": \"S\",\n \"𝗦\": \"S\",\n \"𝘚\": \"S\",\n \"𝙎\": \"S\",\n \"𝚂\": \"S\",\n \"Ѕ\": \"S\",\n \"Տ\": \"S\",\n \"\": \"S\",\n \"\": \"S\",\n \"\": \"S\",\n \"𖼺\": \"S\",\n \"𐊖\": \"S\",\n \"𐐠\": \"S\",\n \"ʂ\": \"s̨\",\n \"ᵴ\": \"s̴\",\n \"ꞵ\": \"ß\",\n \"β\": \"ß\",\n \"ϐ\": \"ß\",\n \"𝛃\": \"ß\",\n \"𝛽\": \"ß\",\n \"𝜷\": \"ß\",\n \"𝝱\": \"ß\",\n \"𝞫\": \"ß\",\n \"Ᏸ\": \"ß\",\n \"🝜\": \"sss\",\n \"st\": \"st\",\n \"∫\": \"ʃ\",\n \"ꭍ\": \"ʃ\",\n \"∑\": \"Ʃ\",\n \"⅀\": \"Ʃ\",\n \"Σ\": \"Ʃ\",\n \"𝚺\": \"Ʃ\",\n \"𝛴\": \"Ʃ\",\n \"𝜮\": \"Ʃ\",\n \"𝝨\": \"Ʃ\",\n \"𝞢\": \"Ʃ\",\n \"ⵉ\": \"Ʃ\",\n \"∬\": \"ʃʃ\",\n \"∭\": \"ʃʃʃ\",\n \"⨌\": \"ʃʃʃʃ\",\n \"𝐭\": \"t\",\n \"𝑡\": \"t\",\n \"𝒕\": \"t\",\n \"𝓉\": \"t\",\n \"𝓽\": \"t\",\n \"𝔱\": \"t\",\n \"𝕥\": \"t\",\n \"𝖙\": \"t\",\n \"𝗍\": \"t\",\n \"𝘁\": \"t\",\n \"𝘵\": \"t\",\n \"𝙩\": \"t\",\n \"𝚝\": \"t\",\n \"\": \"T\",\n \"\": \"T\",\n \"🝨\": \"T\",\n \"\": \"T\",\n \"𝐓\": \"T\",\n \"𝑇\": \"T\",\n \"𝑻\": \"T\",\n \"𝒯\": \"T\",\n \"𝓣\": \"T\",\n \"𝔗\": \"T\",\n \"𝕋\": \"T\",\n \"𝕿\": \"T\",\n \"𝖳\": \"T\",\n \"𝗧\": \"T\",\n \"𝘛\": \"T\",\n \"𝙏\": \"T\",\n \"𝚃\": \"T\",\n \"Τ\": \"T\",\n \"𝚻\": \"T\",\n \"𝛵\": \"T\",\n \"𝜯\": \"T\",\n \"𝝩\": \"T\",\n \"𝞣\": \"T\",\n \"\": \"T\",\n \"Т\": \"T\",\n \"\": \"T\",\n \"\": \"T\",\n \"𖼊\": \"T\",\n \"𑢼\": \"T\",\n \"𐊗\": \"T\",\n \"𐊱\": \"T\",\n \"𐌕\": \"T\",\n \"ƭ\": \"t̔\",\n \"⍡\": \"T̈\",\n \"Ⱦ\": \"T̸\",\n \"Ț\": \"Ţ\",\n \"Ʈ\": \"T̨\",\n \"Ҭ\": \"T̩\",\n \"₮\": \"T⃫\",\n \"ŧ\": \"t̵\",\n \"Ŧ\": \"T̵\",\n \"ᵵ\": \"t̴\",\n \"Ⴀ\": \"Ꞇ\",\n \"Ꜩ\": \"T3\",\n \"ʨ\": \"tɕ\",\n \"℡\": \"TEL\",\n \"ꝷ\": \"tf\",\n \"ʦ\": \"ts\",\n \"ʧ\": \"tʃ\",\n \"ꜩ\": \"tȝ\",\n \"τ\": \"ᴛ\",\n \"𝛕\": \"ᴛ\",\n \"𝜏\": \"ᴛ\",\n \"𝝉\": \"ᴛ\",\n \"𝞃\": \"ᴛ\",\n \"𝞽\": \"ᴛ\",\n \"т\": \"ᴛ\",\n \"ꭲ\": \"ᴛ\",\n \"ҭ\": \"ᴛ̩\",\n \"ţ\": \"ƫ\",\n \"ț\": \"ƫ\",\n \"Ꮏ\": \"ƫ\",\n \"𝐮\": \"u\",\n \"𝑢\": \"u\",\n \"𝒖\": \"u\",\n \"𝓊\": \"u\",\n \"𝓾\": \"u\",\n \"𝔲\": \"u\",\n \"𝕦\": \"u\",\n \"𝖚\": \"u\",\n \"𝗎\": \"u\",\n \"𝘂\": \"u\",\n \"𝘶\": \"u\",\n \"𝙪\": \"u\",\n \"𝚞\": \"u\",\n \"\": \"u\",\n \"\": \"u\",\n \"\": \"u\",\n \"\": \"u\",\n \"ʋ\": \"u\",\n \"υ\": \"u\",\n \"𝛖\": \"u\",\n \"𝜐\": \"u\",\n \"𝝊\": \"u\",\n \"𝞄\": \"u\",\n \"𝞾\": \"u\",\n \"ս\": \"u\",\n \"𐓶\": \"u\",\n \"𑣘\": \"u\",\n \"\": \"U\",\n \"\": \"U\",\n \"𝐔\": \"U\",\n \"𝑈\": \"U\",\n \"𝑼\": \"U\",\n \"𝒰\": \"U\",\n \"𝓤\": \"U\",\n \"𝔘\": \"U\",\n \"𝕌\": \"U\",\n \"𝖀\": \"U\",\n \"𝖴\": \"U\",\n \"𝗨\": \"U\",\n \"𝘜\": \"U\",\n \"𝙐\": \"U\",\n \"𝚄\": \"U\",\n \"Ս\": \"U\",\n \"\": \"U\",\n \"𐓎\": \"U\",\n \"\": \"U\",\n \"\": \"U\",\n \"𖽂\": \"U\",\n \"𑢸\": \"U\",\n \"ǔ\": \"ŭ\",\n \"Ǔ\": \"Ŭ\",\n \"ᵾ\": \"u̵\",\n \"ꮜ\": \"u̵\",\n \"Ʉ\": \"U̵\",\n \"Ꮜ\": \"U̵\",\n \"ᑘ\": \"U·\",\n \"ᑧ\": \"U'\",\n \"ᵫ\": \"ue\",\n \"ꭣ\": \"uo\",\n \"ṃ\": \"ꭑ\",\n \"պ\": \"ɰ\",\n \"ሣ\": \"ɰ\",\n \"℧\": \"Ʊ\",\n \"ᘮ\": \"Ʊ\",\n \"ᘴ\": \"Ʊ\",\n \"ᵿ\": \"ʊ̵\",\n \"\": \"v\",\n \"\": \"v\",\n \"\": \"v\",\n \"\": \"v\",\n \"𝐯\": \"v\",\n \"𝑣\": \"v\",\n \"𝒗\": \"v\",\n \"𝓋\": \"v\",\n \"𝓿\": \"v\",\n \"𝔳\": \"v\",\n \"𝕧\": \"v\",\n \"𝖛\": \"v\",\n \"𝗏\": \"v\",\n \"𝘃\": \"v\",\n \"𝘷\": \"v\",\n \"𝙫\": \"v\",\n \"𝚟\": \"v\",\n \"\": \"v\",\n \"ν\": \"v\",\n \"𝛎\": \"v\",\n \"𝜈\": \"v\",\n \"𝝂\": \"v\",\n \"𝝼\": \"v\",\n \"𝞶\": \"v\",\n \"ѵ\": \"v\",\n \"ט\": \"v\",\n \"𑜆\": \"v\",\n \"\": \"v\",\n \"𑣀\": \"v\",\n \"𝈍\": \"V\",\n \"٧\": \"V\",\n \"۷\": \"V\",\n \"\": \"V\",\n \"𝐕\": \"V\",\n \"𝑉\": \"V\",\n \"𝑽\": \"V\",\n \"𝒱\": \"V\",\n \"𝓥\": \"V\",\n \"𝔙\": \"V\",\n \"𝕍\": \"V\",\n \"𝖁\": \"V\",\n \"𝖵\": \"V\",\n \"𝗩\": \"V\",\n \"𝘝\": \"V\",\n \"𝙑\": \"V\",\n \"𝚅\": \"V\",\n \"Ѵ\": \"V\",\n \"\": \"V\",\n \"\": \"V\",\n \"\": \"V\",\n \"\": \"V\",\n \"\": \"V\",\n \"𖼈\": \"V\",\n \"𑢠\": \"V\",\n \"𐔝\": \"V\",\n \"𐆗\": \"V̵\",\n \"ᐻ\": \"V·\",\n \"🝬\": \"VB\",\n \"ⅵ\": \"vi\",\n \"ⅶ\": \"vii\",\n \"ⅷ\": \"viii\",\n \"Ⅵ\": \"Vl\",\n \"Ⅶ\": \"Vll\",\n \"Ⅷ\": \"Vlll\",\n \"🜈\": \"Vᷤ\",\n \"ᴧ\": \"ʌ\",\n \"𐓘\": \"ʌ\",\n \"٨\": \"Ʌ\",\n \"۸\": \"Ʌ\",\n \"Λ\": \"Ʌ\",\n \"𝚲\": \"Ʌ\",\n \"𝛬\": \"Ʌ\",\n \"𝜦\": \"Ʌ\",\n \"𝝠\": \"Ʌ\",\n \"𝞚\": \"Ʌ\",\n \"Л\": \"Ʌ\",\n \"ⴷ\": \"Ʌ\",\n \"𐒰\": \"Ʌ\",\n \"ᐱ\": \"Ʌ\",\n \"ꛎ\": \"Ʌ\",\n \"ꓥ\": \"Ʌ\",\n \"𖼽\": \"Ʌ\",\n \"𐊍\": \"Ʌ\",\n \"Ӆ\": \"Ʌ̦\",\n \"ᐽ\": \"Ʌ·\",\n \"ɯ\": \"w\",\n \"𝐰\": \"w\",\n \"𝑤\": \"w\",\n \"𝒘\": \"w\",\n \"𝓌\": \"w\",\n \"𝔀\": \"w\",\n \"𝔴\": \"w\",\n \"𝕨\": \"w\",\n \"𝖜\": \"w\",\n \"𝗐\": \"w\",\n \"𝘄\": \"w\",\n \"𝘸\": \"w\",\n \"𝙬\": \"w\",\n \"𝚠\": \"w\",\n \"\": \"w\",\n \"ѡ\": \"w\",\n \"ԝ\": \"w\",\n \"ա\": \"w\",\n \"𑜊\": \"w\",\n \"𑜎\": \"w\",\n \"𑜏\": \"w\",\n \"\": \"w\",\n \"𑣯\": \"W\",\n \"𑣦\": \"W\",\n \"𝐖\": \"W\",\n \"𝑊\": \"W\",\n \"𝑾\": \"W\",\n \"𝒲\": \"W\",\n \"𝓦\": \"W\",\n \"𝔚\": \"W\",\n \"𝕎\": \"W\",\n \"𝖂\": \"W\",\n \"𝖶\": \"W\",\n \"𝗪\": \"W\",\n \"𝘞\": \"W\",\n \"𝙒\": \"W\",\n \"𝚆\": \"W\",\n \"Ԝ\": \"W\",\n \"\": \"W\",\n \"\": \"W\",\n \"\": \"W\",\n \"ѽ\": \"w҆҇\",\n \"𑓅\": \"ẇ\",\n \"₩\": \"W̵\",\n \"ꝡ\": \"w̦\",\n \"ᴍ\": \"ʍ\",\n \"м\": \"ʍ\",\n \"ꮇ\": \"ʍ\",\n \"ӎ\": \"ʍ̦\",\n \"\": \"x\",\n \"×\": \"x\",\n \"\": \"x\",\n \"\": \"x\",\n \"\": \"x\",\n \"\": \"x\",\n \"\": \"x\",\n \"𝐱\": \"x\",\n \"𝑥\": \"x\",\n \"𝒙\": \"x\",\n \"𝓍\": \"x\",\n \"𝔁\": \"x\",\n \"𝔵\": \"x\",\n \"𝕩\": \"x\",\n \"𝖝\": \"x\",\n \"𝗑\": \"x\",\n \"𝘅\": \"x\",\n \"𝘹\": \"x\",\n \"𝙭\": \"x\",\n \"𝚡\": \"x\",\n \"х\": \"x\",\n \"\": \"x\",\n \"\": \"x\",\n \"ⷯ\": \"ͯ\",\n \"\": \"X\",\n \"\": \"X\",\n \"𐌢\": \"X\",\n \"𑣬\": \"X\",\n \"\": \"X\",\n \"\": \"X\",\n \"𝐗\": \"X\",\n \"𝑋\": \"X\",\n \"𝑿\": \"X\",\n \"𝒳\": \"X\",\n \"𝓧\": \"X\",\n \"𝔛\": \"X\",\n \"𝕏\": \"X\",\n \"𝖃\": \"X\",\n \"𝖷\": \"X\",\n \"𝗫\": \"X\",\n \"𝘟\": \"X\",\n \"𝙓\": \"X\",\n \"𝚇\": \"X\",\n \"\": \"X\",\n \"Χ\": \"X\",\n \"𝚾\": \"X\",\n \"𝛸\": \"X\",\n \"𝜲\": \"X\",\n \"𝝬\": \"X\",\n \"𝞦\": \"X\",\n \"\": \"X\",\n \"Х\": \"X\",\n \"\": \"X\",\n \"\": \"X\",\n \"\": \"X\",\n \"𐊐\": \"X\",\n \"𐊴\": \"X\",\n \"𐌗\": \"X\",\n \"𐔧\": \"X\",\n \"⨰\": \"ẋ\",\n \"Ҳ\": \"X̩\",\n \"𐆖\": \"X̵\",\n \"ⅺ\": \"xi\",\n \"ⅻ\": \"xii\",\n \"Ⅺ\": \"Xl\",\n \"Ⅻ\": \"Xll\",\n \"ɣ\": \"y\",\n \"\": \"y\",\n \"\": \"y\",\n \"𝐲\": \"y\",\n \"𝑦\": \"y\",\n \"𝒚\": \"y\",\n \"𝓎\": \"y\",\n \"𝔂\": \"y\",\n \"𝔶\": \"y\",\n \"𝕪\": \"y\",\n \"𝖞\": \"y\",\n \"𝗒\": \"y\",\n \"𝘆\": \"y\",\n \"𝘺\": \"y\",\n \"𝙮\": \"y\",\n \"𝚢\": \"y\",\n \"ʏ\": \"y\",\n \"ỿ\": \"y\",\n \"\": \"y\",\n \"γ\": \"y\",\n \"\": \"y\",\n \"𝛄\": \"y\",\n \"𝛾\": \"y\",\n \"𝜸\": \"y\",\n \"𝝲\": \"y\",\n \"𝞬\": \"y\",\n \"у\": \"y\",\n \"ү\": \"y\",\n \"\": \"y\",\n \"𑣜\": \"y\",\n \"\": \"Y\",\n \"𝐘\": \"Y\",\n \"𝑌\": \"Y\",\n \"𝒀\": \"Y\",\n \"𝒴\": \"Y\",\n \"𝓨\": \"Y\",\n \"𝔜\": \"Y\",\n \"𝕐\": \"Y\",\n \"𝖄\": \"Y\",\n \"𝖸\": \"Y\",\n \"𝗬\": \"Y\",\n \"𝘠\": \"Y\",\n \"𝙔\": \"Y\",\n \"𝚈\": \"Y\",\n \"Υ\": \"Y\",\n \"ϒ\": \"Y\",\n \"𝚼\": \"Y\",\n \"𝛶\": \"Y\",\n \"𝜰\": \"Y\",\n \"𝝪\": \"Y\",\n \"𝞤\": \"Y\",\n \"\": \"Y\",\n \"У\": \"Y\",\n \"Ү\": \"Y\",\n \"\": \"Y\",\n \"\": \"Y\",\n \"\": \"Y\",\n \"𖽃\": \"Y\",\n \"𑢤\": \"Y\",\n \"𐊲\": \"Y\",\n \"ƴ\": \"y̔\",\n \"ɏ\": \"y̵\",\n \"ұ\": \"y̵\",\n \"¥\": \"Y̵\",\n \"Ɏ\": \"Y̵\",\n \"Ұ\": \"Y̵\",\n \"ʒ\": \"ȝ\",\n \"ꝫ\": \"ȝ\",\n \"ⳍ\": \"ȝ\",\n \"ӡ\": \"ȝ\",\n \"ჳ\": \"ȝ\",\n \"𝐳\": \"z\",\n \"𝑧\": \"z\",\n \"𝒛\": \"z\",\n \"𝓏\": \"z\",\n \"𝔃\": \"z\",\n \"𝔷\": \"z\",\n \"𝕫\": \"z\",\n \"𝖟\": \"z\",\n \"𝗓\": \"z\",\n \"𝘇\": \"z\",\n \"𝘻\": \"z\",\n \"𝙯\": \"z\",\n \"𝚣\": \"z\",\n \"\": \"z\",\n \"\": \"z\",\n \"𑣄\": \"z\",\n \"𐋵\": \"Z\",\n \"𑣥\": \"Z\",\n \"\": \"Z\",\n \"\": \"Z\",\n \"\": \"Z\",\n \"𝐙\": \"Z\",\n \"𝑍\": \"Z\",\n \"𝒁\": \"Z\",\n \"𝒵\": \"Z\",\n \"𝓩\": \"Z\",\n \"𝖅\": \"Z\",\n \"𝖹\": \"Z\",\n \"𝗭\": \"Z\",\n \"𝘡\": \"Z\",\n \"𝙕\": \"Z\",\n \"𝚉\": \"Z\",\n \"Ζ\": \"Z\",\n \"𝚭\": \"Z\",\n \"𝛧\": \"Z\",\n \"𝜡\": \"Z\",\n \"𝝛\": \"Z\",\n \"𝞕\": \"Z\",\n \"\": \"Z\",\n \"\": \"Z\",\n \"𑢩\": \"Z\",\n \"ʐ\": \"z̨\",\n \"ƶ\": \"z̵\",\n \"Ƶ\": \"Z̵\",\n \"ȥ\": \"z̦\",\n \"Ȥ\": \"Z̦\",\n \"ᵶ\": \"z̴\",\n \"ƿ\": \"þ\",\n \"ϸ\": \"þ\",\n \"Ϸ\": \"Þ\",\n \"𐓄\": \"Þ\",\n \"⁹\": \"ꝰ\",\n \"ᴤ\": \"ƨ\",\n \"ϩ\": \"ƨ\",\n \"ꙅ\": \"ƨ\",\n \"ь\": \"ƅ\",\n \"ꮟ\": \"ƅ\",\n \"ы\": \"ƅi\",\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 \"𝝀\": \"λ\",\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 \"𝝇\": \"ς\",\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 \"𝛺\": \"Ω\",\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 \"Ꙑ\": \"Ъl\",\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 \"𞸡\": \"ب\",\n \"𞹡\": \"ب\",\n \"𞺁\": \"ب\",\n \"𞺡\": \"ب\",\n \"ﺑ\": \"ب\",\n \"ﺒ\": \"ب\",\n \"ﺐ\": \"ب\",\n \"ﺏ\": \"ب\",\n \"ݑ\": \"بۛ\",\n \"ࢶ\": \"بۢ\",\n \"ࢡ\": \"بٔ\",\n \"ﲠ\": \"بo\",\n \"ﳢ\": \"بo\",\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 \"ﺕ\": \"ت\",\n \"ﲥ\": \"تo\",\n \"ﳤ\": \"تo\",\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 \"ﲧ\": \"جح\",\n \"ﰕ\": \"جح\",\n \"ﶦ\": \"جحى\",\n \"ﶾ\": \"جحى\",\n \"ﷻ\": \"جل جلlلo\",\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 \"ﴀ\": \"حى\",\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 \"ڑ\": \"رؕ\",\n \"ﮍ\": \"رؕ\",\n \"ﮌ\": \"رؕ\",\n \"ژ\": \"رۛ\",\n \"ﮋ\": \"رۛ\",\n \"ﮊ\": \"رۛ\",\n \"ڒ\": \"ر̆\",\n \"ࢹ\": \"ر̆̇\",\n \"ۯ\": \"ر̂\",\n \"ݬ\": \"رٔ\",\n \"ﱜ\": \"رٰ\",\n \"ﷶ\": \"رسول\",\n \"﷼\": \"رىlل\",\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 \"ﴱ\": \"سo\",\n \"ﳨ\": \"سo\",\n \"ﴲ\": \"سۛo\",\n \"ﳪ\": \"سۛo\",\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 \"ﵬ\": \"سۛمم\",\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 \"ﷺ\": \"صلى lللo علىo وسلم\",\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 \"ﴺ\": \"طم\",\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 \"ﷷ\": \"علىo\",\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 \"ﳁ\": \"فم\",\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 \"𞹪\": \"ك\",\n \"ﻛ\": \"ك\",\n \"ﻜ\": \"ك\",\n \"ﻚ\": \"ك\",\n \"ﻙ\": \"ك\",\n \"ک\": \"ك\",\n \"ﮐ\": \"ك\",\n \"ﮑ\": \"ك\",\n \"ﮏ\": \"ك\",\n \"ﮎ\": \"ك\",\n \"ڪ\": \"ك\",\n \"ڭ\": \"كۛ\",\n \"ﯕ\": \"كۛ\",\n \"ﯖ\": \"كۛ\",\n \"ﯔ\": \"كۛ\",\n \"ﯓ\": \"كۛ\",\n \"ݣ\": \"كۛ\",\n \"ﲀ\": \"كl\",\n \"ﰷ\": \"كl\",\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 \"ﻼ\": \"لl\",\n \"ﻻ\": \"لl\",\n \"ﻺ\": \"لlٕ\",\n \"ﻹ\": \"لlٕ\",\n \"ﻸ\": \"لlٴ\",\n \"ﻷ\": \"لlٴ\",\n \"ﳍ\": \"لo\",\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 \"ﲈ\": \"مl\",\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 \"ﳖ\": \"نo\",\n \"ﳯ\": \"نo\",\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 \"ﯜ\": \"وٰ\",\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 \"𞺩\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ﺊ\": \"ىٴ\",\n \"ﺉ\": \"ىٴ\",\n \"ٸ\": \"ىٴ\",\n \"ﯫ\": \"ىٴl\",\n \"ﯪ\": \"ىٴl\",\n \"ﲛ\": \"ىٴo\",\n \"ﳠ\": \"ىٴo\",\n \"ﯭ\": \"ىٴo\",\n \"ﯬ\": \"ىٴo\",\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 \"ﱸ\": \"ىۛم\",\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 \"𑒔\": \"চ\",\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 \"ഊ\": \"உൗ\",\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 \"ഈ\": \"ഇൗ\",\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 \"។\": \"ฯ\",\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 \"ᐘ\": \"ᐊ·\",\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 \"ᓡ\": \"ᓖ·\",\n \"ᓣ\": \"ᓗ·\",\n \"ᓥ\": \"ᓘ·\",\n \"ᘇ\": \"ᓚ\",\n \"ᓧ\": \"ᓚ·\",\n \"ᓩ\": \"ᓛ·\",\n \"ᓷ\": \"ᓭ·\",\n \"ᓹ\": \"ᓯ·\",\n \"ᓻ\": \"ᓰ·\",\n \"ᓽ\": \"ᓱ·\",\n \"ᓿ\": \"ᓲ·\",\n \"ᔁ\": \"ᓴ·\",\n \"ᔃ\": \"ᓵ·\",\n \"ᔌ\": \"ᔋ<\",\n \"ᔎ\": \"ᔋb\",\n \"ᔍ\": \"ᔋᑕ\",\n \"ᔏ\": \"ᔋᒐ\",\n \"ᔘ\": \"ᔐ·\",\n \"ᔚ\": \"ᔑ·\",\n \"ᔜ\": \"ᔒ·\",\n \"ᔞ\": \"ᔓ·\",\n \"ᔠ\": \"ᔔ·\",\n \"ᔢ\": \"ᔕ·\",\n \"ᔤ\": \"ᔖ·\",\n \"ᔲ\": \"ᔨ·\",\n \"ᔴ\": \"ᔩ·\",\n \"ᔶ\": \"ᔪ·\",\n \"ᔸ\": \"ᔫ·\",\n \"ᔺ\": \"ᔭ·\",\n \"ᔼ\": \"ᔮ·\",\n \"ᘢ\": \"ᕃ\",\n \"ᣠ\": \"ᕃ·\",\n \"ᘣ\": \"ᕆ\",\n \"ᘤ\": \"ᕊ\",\n \"ᕏ\": \"ᕌ·\",\n \"ᖃ\": \"ᕐb\",\n \"ᖄ\": \"ᕐḃ\",\n \"ᖁ\": \"ᕐd\",\n \"ᕿ\": \"ᕐP\",\n \"ᙯ\": \"ᕐᑫ\",\n \"ᕾ\": \"ᕐᑬ\",\n \"ᖀ\": \"ᕐᑮ\",\n \"ᖂ\": \"ᕐᑰ\",\n \"ᖅ\": \"ᕐᒃ\",\n \"ᕜ\": \"ᕚ·\",\n \"ᣣ\": \"ᕞ·\",\n \"ᣤ\": \"ᕦ·\",\n \"ᕩ\": \"ᕧ·\",\n \"ᣥ\": \"ᕫ·\",\n \"ᣨ\": \"ᖆ·\",\n \"ᖑ\": \"ᖕJ\",\n \"ᙰ\": \"ᖕᒉ\",\n \"ᖎ\": \"ᖕᒊ\",\n \"ᖏ\": \"ᖕᒋ\",\n \"ᖐ\": \"ᖕᒌ\",\n \"ᖒ\": \"ᖕᒎ\",\n \"ᖓ\": \"ᖕᒐ\",\n \"ᖔ\": \"ᖕᒑ\",\n \"ᙳ\": \"ᖖJ\",\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 \"𐓐\": \"ᛦ\",\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 \"ퟍ\": \"ᄃᄃ\",\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 \"ᇔ\": \"ᄅᄇᄒ\",\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 \"ㅂ\": \"ᄇ\",\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 \"ᄯ\": \"ᄉᄃ\",\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 \"ꥷ\": \"ᄋᄒ\",\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 \"ퟶ\": \"ᅌᄒ\",\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 \"ᆄ\": \"ᅭᅣ\",\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 \"꒨\": \"ꄲ\",\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 \"〹\": \"卄\",\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 \"⺅\": \"亻\",\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 \"⼍\": \"冖\",\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 \"匆\": \"匆\",\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 \"咢\": \"咢\",\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 \"壮\": \"壮\",\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 \"尢\": \"尢\",\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 \"㡼\": \"㡼\",\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 \"惇\": \"惇\",\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 \"捨\": \"捨\",\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 \"暑\": \"暑\",\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 \"梎\": \"梎\",\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 \"⺢\": \"氺\",\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 \"濾\": \"濾\",\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 \"𤜵\": \"𤜵\",\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 \"瘐\": \"瘐\",\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 \"碌\": \"碌\",\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 \"竮\": \"竮\",\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 \"缾\": \"缾\",\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 \"𦞵\": \"𦞵\",\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 \"著\": \"著\",\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 \"蠁\": \"蠁\",\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 \"謁\": \"謁\",\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 \"輻\": \"輻\",\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 \"鐕\": \"鐕\",\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 \"⾰\": \"革\",\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 \"⾼\": \"高\",\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 \"鼅\": \"鼅\",\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}",
"'use strict';\n\n\nvar data = require('./data.json');\n\nfunction escapeRegexp(str) {\n return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n}\n\nvar REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');\n\nfunction replace_fn(match) {\n return data[match];\n}\n\nfunction unhomoglyph(str) {\n return str.replace(REPLACE_RE, replace_fn);\n}\n\nmodule.exports = unhomoglyph;\n",
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n this.hostname = this.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = this.hostname[0] === '[' &&\n this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) this.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n //to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (util.isString(obj)) obj = urlParse(obj);\n if (!(obj instanceof Url)) return Url.prototype.format.call(obj);\n return obj.format();\n}\n\nUrl.prototype.format = function() {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ?\n this.hostname :\n '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query &&\n util.isObject(this.query) &&\n Object.keys(this.query).length) {\n query = querystring.stringify(this.query);\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (this.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (util.isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!util.isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) this.hostname = host;\n};\n",
"'use strict';\n\nmodule.exports = {\n isString: function(arg) {\n return typeof(arg) === 'string';\n },\n isObject: function(arg) {\n return typeof(arg) === 'object' && arg !== null;\n },\n isNull: function(arg) {\n return arg === null;\n },\n isNullOrUndefined: function(arg) {\n return arg == null;\n }\n};\n",
"/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"../NamespacedValue\";\n\nexport enum EventType {\n // Room state events\n RoomCanonicalAlias = \"m.room.canonical_alias\",\n RoomCreate = \"m.room.create\",\n RoomJoinRules = \"m.room.join_rules\",\n RoomMember = \"m.room.member\",\n RoomThirdPartyInvite = \"m.room.third_party_invite\",\n RoomPowerLevels = \"m.room.power_levels\",\n RoomName = \"m.room.name\",\n RoomTopic = \"m.room.topic\",\n RoomAvatar = \"m.room.avatar\",\n RoomPinnedEvents = \"m.room.pinned_events\",\n RoomEncryption = \"m.room.encryption\",\n RoomHistoryVisibility = \"m.room.history_visibility\",\n RoomGuestAccess = \"m.room.guest_access\",\n RoomServerAcl = \"m.room.server_acl\",\n RoomTombstone = \"m.room.tombstone\",\n /**\n * @deprecated Should not be used.\n */\n RoomAliases = \"m.room.aliases\", // deprecated https://matrix.org/docs/spec/client_server/r0.6.1#historical-events\n\n SpaceChild = \"m.space.child\",\n SpaceParent = \"m.space.parent\",\n\n // Room timeline events\n RoomRedaction = \"m.room.redaction\",\n RoomMessage = \"m.room.message\",\n RoomMessageEncrypted = \"m.room.encrypted\",\n Sticker = \"m.sticker\",\n CallInvite = \"m.call.invite\",\n CallCandidates = \"m.call.candidates\",\n CallAnswer = \"m.call.answer\",\n CallHangup = \"m.call.hangup\",\n CallReject = \"m.call.reject\",\n CallSelectAnswer = \"m.call.select_answer\",\n CallNegotiate = \"m.call.negotiate\",\n CallReplaces = \"m.call.replaces\",\n CallAssertedIdentity = \"m.call.asserted_identity\",\n CallAssertedIdentityPrefix = \"org.matrix.call.asserted_identity\",\n KeyVerificationRequest = \"m.key.verification.request\",\n KeyVerificationStart = \"m.key.verification.start\",\n KeyVerificationCancel = \"m.key.verification.cancel\",\n KeyVerificationMac = \"m.key.verification.mac\",\n KeyVerificationDone = \"m.key.verification.done\",\n // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback\n RoomMessageFeedback = \"m.room.message.feedback\",\n Reaction = \"m.reaction\",\n\n // Room ephemeral events\n Typing = \"m.typing\",\n Receipt = \"m.receipt\",\n Presence = \"m.presence\",\n\n // Room account_data events\n FullyRead = \"m.fully_read\",\n Tag = \"m.tag\",\n SpaceOrder = \"org.matrix.msc3230.space_order\", // MSC3230\n\n // User account_data events\n PushRules = \"m.push_rules\",\n Direct = \"m.direct\",\n IgnoredUserList = \"m.ignored_user_list\",\n\n // to_device events\n RoomKey = \"m.room_key\",\n RoomKeyRequest = \"m.room_key_request\",\n ForwardedRoomKey = \"m.forwarded_room_key\",\n Dummy = \"m.dummy\",\n}\n\nexport enum RelationType {\n Annotation = \"m.annotation\",\n Replace = \"m.replace\",\n}\n\nexport enum MsgType {\n Text = \"m.text\",\n Emote = \"m.emote\",\n Notice = \"m.notice\",\n Image = \"m.image\",\n File = \"m.file\",\n Audio = \"m.audio\",\n Location = \"m.location\",\n Video = \"m.video\",\n}\n\nexport const RoomCreateTypeField = \"type\";\n\nexport enum RoomType {\n Space = \"m.space\",\n}\n\n/**\n * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC3088_PURPOSE = new UnstableValue(\"m.room.purpose\", \"org.matrix.msc3088.purpose\");\n\n/**\n * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC3088_ENABLED = new UnstableValue(\"m.enabled\", \"org.matrix.msc3088.enabled\");\n\n/**\n * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport const UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue(\"m.data_tree\", \"org.matrix.msc3089.data_tree\");\n\n/**\n * Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport const UNSTABLE_MSC3089_LEAF = new UnstableValue(\"m.leaf\", \"org.matrix.msc3089.leaf\");\n\n/**\n * Branch (Leaf Reference) type for the index approach in a\n * [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is\n * UNSTABLE and subject to breaking changes, including its eventual removal.\n */\nexport const UNSTABLE_MSC3089_BRANCH = new UnstableValue(\"m.branch\", \"org.matrix.msc3089.branch\");\n\nexport interface IEncryptedFile {\n url: string;\n mimetype?: string;\n key: {\n alg: string;\n key_ops: string[]; // eslint-disable-line camelcase\n kty: string;\n k: string;\n ext: boolean;\n };\n iv: string;\n hashes: {[alg: string]: string};\n v: string;\n}\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport interface IImageInfo {\n size?: number;\n mimetype?: string;\n thumbnail_info?: { // eslint-disable-line camelcase\n w?: number;\n h?: number;\n size?: number;\n mimetype?: string;\n };\n w?: number;\n h?: number;\n}\n\nexport enum Visibility {\n Public = \"public\",\n Private = \"private\",\n}\n\nexport enum Preset {\n PrivateChat = \"private_chat\",\n TrustedPrivateChat = \"trusted_private_chat\",\n PublicChat = \"public_chat\",\n}\n\nexport type ResizeMethod = \"crop\" | \"scale\";\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nexport class NamespacedValue<S extends string, U extends string> {\n // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n // Goal is to to have developers explicitly say there is no stable value (if applicable).\n public constructor(public readonly stable: S | null | undefined, public readonly unstable?: U) {\n if (!this.unstable && !this.stable) {\n throw new Error(\"One of stable or unstable values must be supplied\");\n }\n }\n\n public get name(): U | S {\n if (this.stable) {\n return this.stable;\n }\n return this.unstable;\n }\n\n public get altName(): U | S | null {\n if (!this.stable) {\n return null;\n }\n return this.unstable;\n }\n\n public matches(val: string): boolean {\n return this.name === val || this.altName === val;\n }\n\n // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n // so we can instantiate `NamespacedValue<string, _, _>` as a default type for that namespace.\n public findIn<T>(obj: any): T {\n let val: T;\n if (this.name) {\n val = obj?.[this.name];\n }\n if (!val && this.altName) {\n val = obj?.[this.altName];\n }\n return val;\n }\n\n public includedIn(arr: any[]): boolean {\n let included = false;\n if (this.name) {\n included = arr.includes(this.name);\n }\n if (!included && this.altName) {\n included = arr.includes(this.altName);\n }\n return included;\n }\n}\n\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\nexport class UnstableValue<S extends string, U extends string> extends NamespacedValue<S, U> {\n // Note: Constructor difference is that `unstable` is *required*.\n public constructor(stable: S, unstable: U) {\n super(stable, unstable);\n if (!this.unstable) {\n throw new Error(\"Unstable value must be supplied\");\n }\n }\n\n public get name(): U {\n return this.unstable;\n }\n\n public get altName(): S {\n return this.stable;\n }\n}\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventEmitter } from \"events\";\n\nexport class ReEmitter {\n private target: EventEmitter;\n\n constructor(target: EventEmitter) {\n this.target = target;\n }\n\n reEmit(source: EventEmitter, eventNames: string[]) {\n for (const eventName of eventNames) {\n // We include the source as the last argument for event handlers which may need it,\n // such as read receipt listeners on the client class which won't have the context\n // of the room.\n const forSource = (...args) => {\n // EventEmitter special cases 'error' to make the emit function throw if no\n // handler is attached, which sort of makes sense for making sure that something\n // handles an error, but for re-emitting, there could be a listener on the original\n // source object so the test doesn't really work. We *could* try to replicate the\n // same logic and throw if there is no listener on either the source or the target,\n // but this behaviour is fairly undesireable for us anyway: the main place we throw\n // 'error' events is for calls, where error events are usually emitted some time\n // later by a different part of the code where 'emit' throwing because the app hasn't\n // added an error handler isn't terribly helpful. (A better fix in retrospect may\n // have been to just avoid using the event name 'error', but backwards compat...)\n if (eventName === 'error' && this.target.listenerCount('error') === 0) return;\n this.target.emit(eventName, ...args, source);\n };\n source.on(eventName, forSource);\n }\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module auto-discovery */\n\nimport { logger } from './logger';\nimport { URL as NodeURL } from \"url\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\n/**\n * Description for what an automatically discovered client configuration\n * would look like. Although this is a class, it is recommended that it\n * be treated as an interface definition rather than as a class.\n *\n * Additional properties than those defined here may be present, and\n * should follow the Java package naming convention.\n */\nclass DiscoveredClientConfig { // eslint-disable-line no-unused-vars\n // Dev note: this is basically a copy/paste of the .well-known response\n // object as defined in the spec. It does have additional information,\n // however. Overall, this exists to serve as a place for documentation\n // and not functionality.\n // See https://matrix.org/docs/spec/client_server/r0.4.0.html#get-well-known-matrix-client\n\n constructor() {\n /**\n * The homeserver configuration the client should use. This will\n * always be present on the object.\n * @type {{state: string, base_url: string}} The configuration.\n */\n this[\"m.homeserver\"] = {\n /**\n * The lookup result state. If this is anything other than\n * AutoDiscovery.SUCCESS then base_url may be falsey. Additionally,\n * if this is not AutoDiscovery.SUCCESS then the client should\n * assume the other properties in the client config (such as\n * the identity server configuration) are not valid.\n */\n state: AutoDiscovery.PROMPT,\n\n /**\n * If the state is AutoDiscovery.FAIL_ERROR or .FAIL_PROMPT\n * then this will contain a human-readable (English) message\n * for what went wrong. If the state is none of those previously\n * mentioned, this will be falsey.\n */\n error: \"Something went wrong\",\n\n /**\n * The base URL clients should use to talk to the homeserver,\n * particularly for the login process. May be falsey if the\n * state is not AutoDiscovery.SUCCESS.\n */\n base_url: \"https://matrix.org\",\n };\n\n /**\n * The identity server configuration the client should use. This\n * will always be present on teh object.\n * @type {{state: string, base_url: string}} The configuration.\n */\n this[\"m.identity_server\"] = {\n /**\n * The lookup result state. If this is anything other than\n * AutoDiscovery.SUCCESS then base_url may be falsey.\n */\n state: AutoDiscovery.PROMPT,\n\n /**\n * The base URL clients should use for interacting with the\n * identity server. May be falsey if the state is not\n * AutoDiscovery.SUCCESS.\n */\n base_url: \"https://vector.im\",\n };\n }\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n static get ERROR_INVALID() {\n return \"Invalid homeserver discovery response\";\n }\n\n static get ERROR_GENERIC_FAILURE() {\n return \"Failed to get autodiscovery configuration from server\";\n }\n\n static get ERROR_INVALID_HS_BASE_URL() {\n return \"Invalid base_url for m.homeserver\";\n }\n\n static get ERROR_INVALID_HOMESERVER() {\n return \"Homeserver URL does not appear to be a valid Matrix homeserver\";\n }\n\n static get ERROR_INVALID_IS_BASE_URL() {\n return \"Invalid base_url for m.identity_server\";\n }\n\n static get ERROR_INVALID_IDENTITY_SERVER() {\n return \"Identity server URL does not appear to be a valid identity server\";\n }\n\n static get ERROR_INVALID_IS() {\n return \"Invalid identity server discovery response\";\n }\n\n static get ERROR_MISSING_WELLKNOWN() {\n return \"No .well-known JSON file found\";\n }\n\n static get ERROR_INVALID_JSON() {\n return \"Invalid JSON\";\n }\n\n static get ALL_ERRORS() {\n return [\n AutoDiscovery.ERROR_INVALID,\n AutoDiscovery.ERROR_GENERIC_FAILURE,\n AutoDiscovery.ERROR_INVALID_HS_BASE_URL,\n AutoDiscovery.ERROR_INVALID_HOMESERVER,\n AutoDiscovery.ERROR_INVALID_IS_BASE_URL,\n AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER,\n AutoDiscovery.ERROR_INVALID_IS,\n AutoDiscovery.ERROR_MISSING_WELLKNOWN,\n AutoDiscovery.ERROR_INVALID_JSON,\n ];\n }\n\n /**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n * @return {string}\n * @constructor\n */\n static get FAIL_ERROR() { return \"FAIL_ERROR\"; }\n\n /**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n * @return {string}\n * @constructor\n */\n static get FAIL_PROMPT() { return \"FAIL_PROMPT\"; }\n\n /**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n * @return {string}\n * @constructor\n */\n static get PROMPT() { return \"PROMPT\"; }\n\n /**\n * The auto discovery was successful.\n * @return {string}\n * @constructor\n */\n static get SUCCESS() { return \"SUCCESS\"; }\n\n /**\n * Validates and verifies client configuration information for purposes\n * of logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be included, and will be transparently brought into the\n * response object unaltered.\n * @param {string} wellknown The configuration object itself, as returned\n * by the .well-known auto-discovery endpoint.\n * @return {Promise<DiscoveredClientConfig>} Resolves to the verified\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when verification fails.\n */\n static async fromDiscoveryConfig(wellknown) {\n // Step 1 is to get the config, which is provided to us here.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n if (!wellknown || !wellknown[\"m.homeserver\"]) {\n logger.error(\"No m.homeserver key in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n\n return Promise.resolve(clientConfig);\n }\n\n if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n logger.error(\"No m.homeserver base_url in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n // sure it points to a homeserver in Step 3.\n const hsUrl = this._sanitizeWellKnownUrl(\n wellknown[\"m.homeserver\"][\"base_url\"],\n );\n if (!hsUrl) {\n logger.error(\"Invalid base_url for m.homeserver\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n return Promise.resolve(clientConfig);\n }\n\n // Step 3: Make sure the homeserver URL points to a homeserver.\n const hsVersions = await this._fetchWellKnownObject(\n `${hsUrl}/_matrix/client/versions`,\n );\n if (!hsVersions || !hsVersions.raw[\"versions\"]) {\n logger.error(\"Invalid /versions response\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 4: Now that the homeserver looks valid, update our client config.\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: hsUrl,\n };\n\n // Step 5: Try to pull out the identity server configuration\n let isUrl = \"\";\n if (wellknown[\"m.identity_server\"]) {\n // We prepare a failing identity server response to save lines later\n // in this branch.\n const failingClientConfig = {\n \"m.homeserver\": clientConfig[\"m.homeserver\"],\n \"m.identity_server\": {\n state: AutoDiscovery.FAIL_PROMPT,\n error: AutoDiscovery.ERROR_INVALID_IS,\n base_url: null,\n },\n };\n\n // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n // points to an identity server in Step 5b.\n isUrl = this._sanitizeWellKnownUrl(\n wellknown[\"m.identity_server\"][\"base_url\"],\n );\n if (!isUrl) {\n logger.error(\"Invalid base_url for m.identity_server\");\n failingClientConfig[\"m.identity_server\"].error =\n AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n return Promise.resolve(failingClientConfig);\n }\n\n // Step 5b: Verify there is an identity server listening on the provided\n // URL.\n const isResponse = await this._fetchWellKnownObject(\n `${isUrl}/_matrix/identity/api/v1`,\n );\n if (!isResponse || !isResponse.raw || isResponse.action !== \"SUCCESS\") {\n logger.error(\"Invalid /api/v1 response\");\n failingClientConfig[\"m.identity_server\"].error =\n AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Supply the base_url to the caller because they may be ignoring\n // liveliness errors, like this one.\n failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n\n return Promise.resolve(failingClientConfig);\n }\n }\n\n // Step 6: Now that the identity server is valid, or never existed,\n // populate the IS section.\n if (isUrl && isUrl.length > 0) {\n clientConfig[\"m.identity_server\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: isUrl,\n };\n }\n\n // Step 7: Copy any other keys directly into the clientConfig. This is for\n // things like custom configuration of services.\n Object.keys(wellknown)\n .map((k) => {\n if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n // Only copy selected parts of the config to avoid overwriting\n // properties computed by the validation logic above.\n const notProps = [\"error\", \"state\", \"base_url\"];\n for (const prop of Object.keys(wellknown[k])) {\n if (notProps.includes(prop)) continue;\n clientConfig[k][prop] = wellknown[k][prop];\n }\n } else {\n // Just copy the whole thing over otherwise\n clientConfig[k] = wellknown[k];\n }\n });\n\n // Step 8: Give the config to the caller (finally)\n return Promise.resolve(clientConfig);\n }\n\n /**\n * Attempts to automatically discover client configuration information\n * prior to logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be discovered, and will be transparently included in the\n * response object unaltered.\n * @param {string} domain The homeserver domain to perform discovery\n * on. For example, \"matrix.org\".\n * @return {Promise<DiscoveredClientConfig>} Resolves to the discovered\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when discovery fails.\n */\n static async findClientConfig(domain) {\n if (!domain || typeof(domain) !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n // We use a .well-known lookup for all cases. According to the spec, we\n // can do other discovery mechanisms if we want such as custom lookups\n // however we won't bother with that here (mostly because the spec only\n // supports .well-known right now).\n //\n // By using .well-known, we need to ensure we at least pull out a URL\n // for the homeserver. We don't really need an identity server configuration\n // but will return one anyways (with state PROMPT) to make development\n // easier for clients. If we can't get a homeserver URL, all bets are\n // off on the rest of the config and we'll assume it is invalid too.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n // Step 1: Actually request the .well-known JSON file and make sure it\n // at least has a homeserver definition.\n const wellknown = await this._fetchWellKnownObject(\n `https://${domain}/.well-known/matrix/client`,\n );\n if (!wellknown || wellknown.action !== \"SUCCESS\") {\n logger.error(\"No response or error when parsing .well-known\");\n if (wellknown.reason) logger.error(wellknown.reason);\n if (wellknown.action === \"IGNORE\") {\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n };\n } else {\n // this can only ever be FAIL_PROMPT at this point.\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n }\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Validate and parse the config\n return AutoDiscovery.fromDiscoveryConfig(wellknown.raw);\n }\n\n /**\n * Gets the raw discovery client configuration for the given domain name.\n * Should only be used if there's no validation to be done on the resulting\n * object, otherwise use findClientConfig().\n * @param {string} domain The domain to get the client config for.\n * @returns {Promise<object>} Resolves to the domain's client config. Can\n * be an empty object.\n */\n static async getRawClientConfig(domain) {\n if (!domain || typeof(domain) !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n const response = await this._fetchWellKnownObject(\n `https://${domain}/.well-known/matrix/client`,\n );\n if (!response) return {};\n return response.raw || {};\n }\n\n /**\n * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n * is suitable for the requirements laid out by .well-known auto discovery.\n * If valid, the URL will also be stripped of any trailing slashes.\n * @param {string} url The potentially invalid URL to sanitize.\n * @return {string|boolean} The sanitized URL or a falsey value if the URL is invalid.\n * @private\n */\n static _sanitizeWellKnownUrl(url) {\n if (!url) return false;\n\n try {\n // We have to try and parse the URL using the NodeJS URL\n // library if we're on NodeJS and use the browser's URL\n // library when we're in a browser. To accomplish this, we\n // try the NodeJS version first and fall back to the browser.\n let parsed = null;\n try {\n if (NodeURL) parsed = new NodeURL(url);\n else parsed = new URL(url);\n } catch (e) {\n parsed = new URL(url);\n }\n\n if (!parsed || !parsed.hostname) return false;\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n const path = parsed.pathname ? parsed.pathname : \"\";\n let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;\n if (saferUrl.endsWith(\"/\")) {\n saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n }\n return saferUrl;\n } catch (e) {\n logger.error(e);\n return false;\n }\n }\n\n /**\n * Fetches a JSON object from a given URL, as expected by all .well-known\n * related lookups. If the server gives a 404 then the `action` will be\n * IGNORE. If the server returns something that isn't JSON, the `action`\n * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n *\n * The returned object will be a result of the call in object form with\n * the following properties:\n * raw: The JSON object returned by the server.\n * action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n * reason: Relatively human readable description of what went wrong.\n * error: The actual Error, if one exists.\n * @param {string} url The URL to fetch a JSON object from.\n * @return {Promise<object>} Resolves to the returned state.\n * @private\n */\n static async _fetchWellKnownObject(url) {\n return new Promise(function(resolve, reject) {\n const request = require(\"./matrix\").getRequest();\n if (!request) throw new Error(\"No request library available\");\n request(\n { method: \"GET\", uri: url, timeout: 5000 },\n (err, response, body) => {\n if (err || response &&\n (response.statusCode < 200 || response.statusCode >= 300)\n ) {\n let action = \"FAIL_PROMPT\";\n let reason = (err ? err.message : null) || \"General failure\";\n if (response && response.statusCode === 404) {\n action = \"IGNORE\";\n reason = AutoDiscovery.ERROR_MISSING_WELLKNOWN;\n }\n resolve({ raw: {}, action: action, reason: reason, error: err });\n return;\n }\n\n try {\n resolve({ raw: JSON.parse(body), action: \"SUCCESS\" });\n } catch (e) {\n let reason = AutoDiscovery.ERROR_INVALID;\n if (e.name === \"SyntaxError\") {\n reason = AutoDiscovery.ERROR_INVALID_JSON;\n }\n resolve({\n raw: {},\n action: \"FAIL_PROMPT\",\n reason: reason,\n error: e,\n });\n }\n },\n );\n });\n }\n}\n",
"/*\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport * as matrixcs from \"./matrix\";\nimport request from \"browser-request\";\nimport queryString from \"qs\";\n\nmatrixcs.request(function(opts, fn) {\n // We manually fix the query string for browser-request because\n // it doesn't correctly handle cases like ?via=one&via=two. Instead\n // we mimic `request`'s query string interface to make it all work\n // as expected.\n // browser-request will happily take the constructed string as the\n // query string without trying to modify it further.\n opts.qs = queryString.stringify(opts.qs || {}, opts.qsStringifyOptions);\n return request(opts, fn);\n});\n\n// just *accessing* indexedDB throws an exception in firefox with\n// indexeddb disabled.\nlet indexedDB;\ntry {\n indexedDB = global.indexedDB;\n} catch (e) {}\n\n// if our browser (appears to) support indexeddb, use an indexeddb crypto store.\nif (indexedDB) {\n matrixcs.setCryptoStoreFactory(\n function() {\n return new matrixcs.IndexedDBCryptoStore(\n indexedDB, \"matrix-js-sdk:crypto\",\n );\n },\n );\n}\n\n// We export 3 things to make browserify happy as well as downstream projects.\n// It's awkward, but required.\nexport * from \"./matrix\";\nexport default matrixcs; // keep export for browserify package deps\nglobal.matrixcs = matrixcs;\n",
"/*\nCopyright 2015-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n * @module client\n */\n\nimport { EventEmitter } from \"events\";\nimport { SyncApi } from \"./sync\";\nimport { EventStatus, IDecryptOptions, MatrixEvent } from \"./models/event\";\nimport { StubStore } from \"./store/stub\";\nimport { createNewMatrixCall, MatrixCall, ConstraintsType, getUserMediaContraints } from \"./webrtc/call\";\nimport { Filter } from \"./filter\";\nimport { CallEventHandler } from './webrtc/callEventHandler';\nimport * as utils from './utils';\nimport { sleep } from './utils';\nimport { Group } from \"./models/group\";\nimport { EventTimeline } from \"./models/event-timeline\";\nimport { PushAction, PushProcessor } from \"./pushprocessor\";\nimport { AutoDiscovery } from \"./autodiscovery\";\nimport * as olmlib from \"./crypto/olmlib\";\nimport { decodeBase64, encodeBase64 } from \"./crypto/olmlib\";\nimport { ReEmitter } from './ReEmitter';\nimport { RoomList } from './crypto/RoomList';\nimport { logger } from './logger';\nimport { SERVICE_TYPES } from './service-types';\nimport {\n MatrixError,\n MatrixHttpApi,\n PREFIX_IDENTITY_V2,\n PREFIX_MEDIA_R0,\n PREFIX_R0,\n PREFIX_UNSTABLE,\n retryNetworkOperation,\n} from \"./http-api\";\nimport { Crypto, fixBackupKey, IBootstrapCrossSigningOpts, IMegolmSessionData, isCryptoAvailable } from './crypto';\nimport { DeviceInfo, IDevice } from \"./crypto/deviceinfo\";\nimport { decodeRecoveryKey } from './crypto/recoverykey';\nimport { keyFromAuthData } from './crypto/key_passphrase';\nimport { User } from \"./models/user\";\nimport { getHttpUriForMxc } from \"./content-repo\";\nimport { SearchResult } from \"./models/search-result\";\nimport { DEHYDRATION_ALGORITHM, IDehydratedDevice, IDehydratedDeviceKeyInfo } from \"./crypto/dehydration\";\nimport {\n IKeyBackupPrepareOpts,\n IKeyBackupRestoreOpts,\n IKeyBackupRestoreResult,\n IKeyBackupInfo,\n} from \"./crypto/keybackup\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider\";\nimport type Request from \"request\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { ICryptoCallbacks, NotificationCountType } from \"./matrix\";\nimport { ISecretStorageKeyInfo } from \"./crypto/api\";\nimport { MemoryCryptoStore } from \"./crypto/store/memory-crypto-store\";\nimport { LocalStorageCryptoStore } from \"./crypto/store/localStorage-crypto-store\";\nimport { IndexedDBCryptoStore } from \"./crypto/store/indexeddb-crypto-store\";\nimport { MemoryStore } from \"./store/memory\";\nimport { LocalIndexedDBStoreBackend } from \"./store/indexeddb-local-backend\";\nimport { RemoteIndexedDBStoreBackend } from \"./store/indexeddb-remote-backend\";\nimport { SyncState } from \"./sync.api\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { VerificationRequest } from \"./crypto/verification/request/VerificationRequest\";\nimport { Base as Verification } from \"./crypto/verification/Base\";\nimport * as ContentHelpers from \"./content-helpers\";\nimport {\n CrossSigningKey,\n IAddSecretStorageKeyOpts,\n ICreateSecretStorageOpts,\n IEncryptedEventInfo,\n IImportRoomKeysOpts,\n IRecoveryKey,\n} from \"./crypto/api\";\nimport { CrossSigningInfo, DeviceTrustLevel, UserTrustLevel } from \"./crypto/CrossSigning\";\nimport { Room } from \"./models/room\";\nimport {\n ICreateRoomOpts,\n IEventSearchOpts,\n IGuestAccessOpts,\n IJoinRoomOpts,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n IUploadOpts,\n} from \"./@types/requests\";\nimport {\n EventType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n} from \"./@types/event\";\nimport { IImageInfo, Preset } from \"./@types/partials\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper\";\nimport url from \"url\";\nimport { randomString } from \"./randomstring\";\nimport { ReadStream } from \"fs\";\nimport { WebStorageSessionStore } from \"./store/session/webstorage\";\nimport { BackupManager, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from \"./crypto/backup\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace\";\nimport { ISignatures } from \"./@types/signed\";\n\nexport type Store = StubStore | MemoryStore | LocalIndexedDBStoreBackend | RemoteIndexedDBStoreBackend;\nexport type SessionStore = WebStorageSessionStore;\nexport type CryptoStore = MemoryCryptoStore | LocalStorageCryptoStore | IndexedDBCryptoStore;\n\nexport type Callback = (err: Error | any | null, data?: any) => void;\nexport type ResetTimelineCallback = (roomId: string) => boolean;\n\nconst SCROLLBACK_DELAY_MS = 3000;\nexport const CRYPTO_ENABLED: boolean = isCryptoAvailable();\nconst CAPABILITIES_CACHE_MS = 21600000; // 6 hours - an arbitrary value\nconst TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes\n\ninterface IOlmDevice {\n pickledAccount: string;\n sessions: Array<Record<string, any>>;\n pickleKey: string;\n}\n\ninterface IExportedDevice {\n olmDevice: IOlmDevice;\n userId: string;\n deviceId: string;\n}\n\nexport interface IKeysUploadResponse {\n one_time_key_counts: { // eslint-disable-line camelcase\n [algorithm: string]: number;\n };\n}\n\nexport interface ICreateClientOpts {\n baseUrl: string;\n\n idBaseUrl?: string;\n\n /**\n * The data store used for sync data from the homeserver. If not specified,\n * this client will not store any HTTP responses. The `createClient` helper\n * will create a default store if needed.\n */\n store?: Store;\n\n /**\n * A store to be used for end-to-end crypto session data. If not specified,\n * end-to-end crypto will be disabled. The `createClient` helper will create\n * a default store if needed.\n */\n cryptoStore?: CryptoStore;\n\n /**\n * The scheduler to use. If not\n * specified, this client will not retry requests on failure. This client\n * will supply its own processing function to\n * {@link module:scheduler~MatrixScheduler#setProcessFunction}.\n */\n scheduler?: MatrixScheduler;\n\n /**\n * The function to invoke for HTTP\n * requests. The value of this property is typically <code>require(\"request\")\n * </code> as it returns a function which meets the required interface. See\n * {@link requestFunction} for more information.\n */\n request?: Request;\n\n userId?: string;\n\n /**\n * A unique identifier for this device; used for tracking things like crypto\n * keys and access tokens. If not specified, end-to-end encryption will be\n * disabled.\n */\n deviceId?: string;\n\n accessToken?: string;\n\n /**\n * Identity server provider to retrieve the user's access token when accessing\n * the identity server. See also https://github.com/vector-im/element-web/issues/10615\n * which seeks to replace the previous approach of manual access tokens params\n * with this callback throughout the SDK.\n */\n identityServer?: IIdentityServerProvider;\n\n /**\n * The default maximum amount of\n * time to wait before timing out HTTP requests. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n\n /**\n * Set to true to use\n * Authorization header instead of query param to send the access token to the server.\n *\n * Default false.\n */\n useAuthorizationHeader?: boolean;\n\n /**\n * Set to true to enable\n * improved timeline support ({@link module:client~MatrixClient#getEventTimeline getEventTimeline}). It is\n * disabled by default for compatibility with older clients - in particular to\n * maintain support for back-paginating the live timeline after a '/sync'\n * result with a gap.\n */\n timelineSupport?: boolean;\n\n /**\n * Extra query parameters to append\n * to all requests with this client. Useful for application services which require\n * <code>?user_id=</code>.\n */\n queryParams?: Record<string, unknown>;\n\n /**\n * Device data exported with\n * \"exportDevice\" method that must be imported to recreate this device.\n * Should only be useful for devices with end-to-end crypto enabled.\n * If provided, deviceId and userId should **NOT** be provided at the top\n * level (they are present in the exported data).\n */\n deviceToImport?: IExportedDevice;\n\n /**\n * Key used to pickle olm objects or other sensitive data.\n */\n pickleKey?: string;\n\n /**\n * A store to be used for end-to-end crypto session data. Most data has been\n * migrated out of here to `cryptoStore` instead. If not specified,\n * end-to-end crypto will be disabled. The `createClient` helper\n * _will not_ create this store at the moment.\n */\n sessionStore?: SessionStore;\n\n /**\n * Set to true to enable client-side aggregation of event relations\n * via `EventTimelineSet#getRelationsForEvent`.\n * This feature is currently unstable and the API may change without notice.\n */\n unstableClientRelationAggregation?: boolean;\n\n verificationMethods?: Array<any>;\n\n /**\n * Whether relaying calls through a TURN server should be forced. Default false.\n */\n forceTURN?: boolean;\n\n /**\n * Up to this many ICE candidates will be gathered when an incoming call arrives.\n * Gathering does not send data to the caller, but will communicate with the configured TURN\n * server. Default 0.\n */\n iceCandidatePoolSize?: number;\n\n /**\n * True to advertise support for call transfers to other parties on Matrix calls. Default false.\n */\n supportsCallTransfer?: boolean;\n\n /**\n * Whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.\n */\n fallbackICEServerAllowed?: boolean;\n\n cryptoCallbacks?: ICryptoCallbacks;\n}\n\nexport interface IMatrixClientCreateOpts extends ICreateClientOpts {\n /**\n * Whether to allow sending messages to encrypted rooms when encryption\n * is not available internally within this SDK. This is useful if you are using an external\n * E2E proxy, for example. Defaults to false.\n */\n usingExternalCrypto?: boolean;\n}\n\nexport enum PendingEventOrdering {\n Chronological = \"chronological\",\n Detached = \"detached\",\n}\n\nexport interface IStartClientOpts {\n /**\n * The event <code>limit=</code> to apply to initial sync. Default: 8.\n */\n initialSyncLimit?: number;\n\n /**\n * True to put <code>archived=true</code> on the <code>/initialSync</code> request. Default: false.\n */\n includeArchivedRooms?: boolean;\n\n /**\n * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.\n */\n resolveInvitesToProfiles?: boolean;\n\n /**\n * Controls where pending messages appear in a room's timeline. If \"<b>chronological</b>\", messages will\n * appear in the timeline when the call to <code>sendEvent</code> was made. If \"<b>detached</b>\",\n * pending messages will appear in a separate list, accessbile via {@link module:models/room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n\n /**\n * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).\n */\n pollTimeout?: number;\n\n /**\n * The filter to apply to /sync calls. This will override the opts.initialSyncLimit, which would\n * normally result in a timeline limit filter.\n */\n filter?: Filter;\n\n /**\n * True to perform syncing without automatically updating presence.\n */\n disablePresence?: boolean;\n\n /**\n * True to not load all membership events during initial sync but fetch them when needed by calling\n * `loadOutOfBandMembers` This will override the filter option at this moment.\n */\n lazyLoadMembers?: boolean;\n\n /**\n * The number of seconds between polls to /.well-known/matrix/client, undefined to disable.\n * This should be in the order of hours. Default: undefined.\n */\n clientWellKnownPollPeriod?: number;\n}\n\nexport interface IStoredClientOpts extends IStartClientOpts {\n crypto: Crypto;\n canResetEntireTimeline: ResetTimelineCallback;\n}\n\nexport enum RoomVersionStability {\n Stable = \"stable\",\n Unstable = \"unstable\",\n}\n\nexport interface IRoomVersionsCapability {\n default: string;\n available: Record<string, RoomVersionStability>;\n}\n\nexport interface IChangePasswordCapability {\n enabled: boolean;\n}\n\ninterface ICapabilities {\n [key: string]: any;\n \"m.change_password\"?: IChangePasswordCapability;\n \"m.room_versions\"?: IRoomVersionsCapability;\n}\n\n/* eslint-disable camelcase */\nexport interface ICrossSigningKey {\n keys: { [algorithm: string]: string };\n signatures?: ISignatures;\n usage: string[];\n user_id: string;\n}\n\nenum CrossSigningKeyType {\n MasterKey = \"master_key\",\n SelfSigningKey = \"self_signing_key\",\n UserSigningKey = \"user_signing_key\",\n}\n\nexport type CrossSigningKeys = Record<CrossSigningKeyType, ICrossSigningKey>;\n\nexport interface ISignedKey {\n keys: Record<string, string>;\n signatures: ISignatures;\n user_id: string;\n algorithms: string[];\n device_id: string;\n}\n/* eslint-enable camelcase */\n\nexport type KeySignatures = Record<string, Record<string, ICrossSigningKey | ISignedKey>>;\ninterface IUploadKeySignaturesResponse {\n failures: Record<string, Record<string, {\n errcode: string;\n error: string;\n }>>;\n}\n\nexport interface IPreviewUrlResponse {\n [key: string]: string | number;\n \"og:title\": string;\n \"og:type\": string;\n \"og:url\": string;\n \"og:image\"?: string;\n \"og:image:type\"?: string;\n \"og:image:height\"?: number;\n \"og:image:width\"?: number;\n \"og:description\"?: string;\n \"matrix:image:size\"?: number;\n}\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends EventEmitter {\n public static readonly RESTORE_BACKUP_ERROR_BAD_KEY = 'RESTORE_BACKUP_ERROR_BAD_KEY';\n\n public reEmitter = new ReEmitter(this);\n public olmVersion: string = null; // populated after initCrypto\n public usingExternalCrypto = false;\n public store: Store;\n public deviceId?: string;\n public credentials: { userId?: string };\n public pickleKey: string;\n public scheduler: MatrixScheduler;\n public clientRunning = false;\n public timelineSupport = false;\n public urlPreviewCache: { [key: string]: Promise<any> } = {}; // TODO: Types\n public unstableClientRelationAggregation = false;\n public identityServer: IIdentityServerProvider;\n public sessionStore: SessionStore; // XXX: Intended private, used in code.\n public http: MatrixHttpApi; // XXX: Intended private, used in code.\n public crypto: Crypto; // XXX: Intended private, used in code.\n public cryptoCallbacks: ICryptoCallbacks; // XXX: Intended private, used in code.\n public callEventHandler: CallEventHandler; // XXX: Intended private, used in code.\n public supportsCallTransfer = false; // XXX: Intended private, used in code.\n public forceTURN = false; // XXX: Intended private, used in code.\n public iceCandidatePoolSize = 0; // XXX: Intended private, used in code.\n public idBaseUrl: string;\n public baseUrl: string;\n private localAVStreamType: ConstraintsType;\n private localAVStream: MediaStream;\n\n // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n // We don't technically support this usage, but have reasons to do this.\n\n protected canSupportVoip = false;\n protected peekSync: SyncApi = null;\n protected isGuestAccount = false;\n protected ongoingScrollbacks: {[roomId: string]: {promise?: Promise<any>, errorTs?: number}} = {}; // TODO: Types\n protected notifTimelineSet: EventTimelineSet = null;\n protected cryptoStore: CryptoStore;\n protected verificationMethods: string[];\n protected fallbackICEServerAllowed = false;\n protected roomList: RoomList;\n protected syncApi: SyncApi;\n public pushRules: any; // TODO: Types\n protected syncLeftRoomsPromise: Promise<Room[]>;\n protected syncedLeftRooms = false;\n protected clientOpts: IStoredClientOpts;\n protected clientWellKnownIntervalID: number;\n protected canResetTimelineCallback: ResetTimelineCallback;\n\n // The pushprocessor caches useful things, so keep one and re-use it\n protected pushProcessor = new PushProcessor(this);\n\n // Promise to a response of the server's /versions response\n // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n protected serverVersionsPromise: Promise<any>;\n\n protected cachedCapabilities: {\n capabilities: ICapabilities;\n expiration: number;\n };\n protected clientWellKnown: any;\n protected clientWellKnownPromise: Promise<any>;\n protected turnServers: any[] = []; // TODO: Types\n protected turnServersExpiry = 0;\n protected checkTurnServersIntervalID: number;\n protected exportedOlmDeviceToImport: IOlmDevice;\n protected txnCtr = 0;\n\n constructor(opts: IMatrixClientCreateOpts) {\n super();\n\n opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n\n this.baseUrl = opts.baseUrl;\n this.idBaseUrl = opts.idBaseUrl;\n\n this.usingExternalCrypto = opts.usingExternalCrypto;\n this.store = opts.store || new StubStore();\n this.deviceId = opts.deviceId || null;\n\n const userId = opts.userId || null;\n this.credentials = { userId };\n\n this.http = new MatrixHttpApi(this, {\n baseUrl: opts.baseUrl,\n idBaseUrl: opts.idBaseUrl,\n accessToken: opts.accessToken,\n request: opts.request,\n prefix: PREFIX_R0,\n onlyData: true,\n extraParams: opts.queryParams,\n localTimeoutMs: opts.localTimeoutMs,\n useAuthorizationHeader: opts.useAuthorizationHeader,\n });\n\n if (opts.deviceToImport) {\n if (this.deviceId) {\n logger.warn(\n 'not importing device because device ID is provided to ' +\n 'constructor independently of exported data',\n );\n } else if (this.credentials.userId) {\n logger.warn(\n 'not importing device because user ID is provided to ' +\n 'constructor independently of exported data',\n );\n } else if (!opts.deviceToImport.deviceId) {\n logger.warn('not importing device because no device ID in exported data');\n } else {\n this.deviceId = opts.deviceToImport.deviceId;\n this.credentials.userId = opts.deviceToImport.userId;\n // will be used during async initialization of the crypto\n this.exportedOlmDeviceToImport = opts.deviceToImport.olmDevice;\n }\n } else if (opts.pickleKey) {\n this.pickleKey = opts.pickleKey;\n }\n\n this.scheduler = opts.scheduler;\n if (this.scheduler) {\n this.scheduler.setProcessFunction(async (eventToSend) => {\n const room = this.getRoom(eventToSend.getRoomId());\n if (eventToSend.status !== EventStatus.SENDING) {\n this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n }\n const res = await this.sendEventHttpRequest(eventToSend);\n if (room) {\n // ensure we update pending event before the next scheduler run so that any listeners to event id\n // updates on the synchronous event emitter get a chance to run first.\n room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n }\n return res;\n });\n }\n\n // try constructing a MatrixCall to see if we are running in an environment\n // which has WebRTC. If we are, listen for and handle m.call.* events.\n const call = createNewMatrixCall(this, undefined, undefined);\n if (call) {\n this.callEventHandler = new CallEventHandler(this);\n this.canSupportVoip = true;\n // Start listening for calls after the initial sync is done\n // We do not need to backfill the call event buffer\n // with encrypted events that might never get decrypted\n this.on(\"sync\", this.startCallEventHandler);\n }\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation;\n\n this.cryptoStore = opts.cryptoStore;\n this.sessionStore = opts.sessionStore;\n this.verificationMethods = opts.verificationMethods;\n this.cryptoCallbacks = opts.cryptoCallbacks || {};\n\n this.forceTURN = opts.forceTURN || false;\n this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n this.supportsCallTransfer = opts.supportsCallTransfer || false;\n this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n\n // List of which rooms have encryption enabled: separate from crypto because\n // we still want to know which rooms are encrypted even if crypto is disabled:\n // we don't want to start sending unencrypted events to them.\n this.roomList = new RoomList(this.cryptoStore);\n\n // The SDK doesn't really provide a clean way for events to recalculate the push\n // actions for themselves, so we have to kinda help them out when they are encrypted.\n // We do this so that push rules are correctly executed on events in their decrypted\n // state, such as highlights when the user's name is mentioned.\n this.on(\"Event.decrypted\", (event) => {\n const oldActions = event.getPushActions();\n const actions = this.pushProcessor.actionsForEvent(event);\n event.setPushActions(actions); // Might as well while we're here\n\n const room = this.getRoom(event.getRoomId());\n if (!room) return;\n\n const currentCount = room.getUnreadNotificationCount(NotificationCountType.Highlight);\n\n // Ensure the unread counts are kept up to date if the event is encrypted\n // We also want to make sure that the notification count goes up if we already\n // have encrypted events to avoid other code from resetting 'highlight' to zero.\n const oldHighlight = oldActions && oldActions.tweaks\n ? !!oldActions.tweaks.highlight : false;\n const newHighlight = actions && actions.tweaks\n ? !!actions.tweaks.highlight : false;\n if (oldHighlight !== newHighlight || currentCount > 0) {\n // TODO: Handle mentions received while the client is offline\n // See also https://github.com/vector-im/element-web/issues/9069\n if (!room.hasUserReadEvent(this.getUserId(), event.getId())) {\n let newCount = currentCount;\n if (newHighlight && !oldHighlight) newCount++;\n if (!newHighlight && oldHighlight) newCount--;\n room.setUnreadNotificationCount(NotificationCountType.Highlight, newCount);\n\n // Fix 'Mentions Only' rooms from not having the right badge count\n const totalCount = room.getUnreadNotificationCount(NotificationCountType.Total);\n if (totalCount < newCount) {\n room.setUnreadNotificationCount(NotificationCountType.Total, newCount);\n }\n }\n }\n });\n\n // Like above, we have to listen for read receipts from ourselves in order to\n // correctly handle notification counts on encrypted rooms.\n // This fixes https://github.com/vector-im/element-web/issues/9421\n this.on(\"Room.receipt\", (event, room) => {\n if (room && this.isRoomEncrypted(room.roomId)) {\n // Figure out if we've read something or if it's just informational\n const content = event.getContent();\n const isSelf = Object.keys(content).filter(eid => {\n return Object.keys(content[eid]['m.read']).includes(this.getUserId());\n }).length > 0;\n\n if (!isSelf) return;\n\n // Work backwards to determine how many events are unread. We also set\n // a limit for how back we'll look to avoid spinning CPU for too long.\n // If we hit the limit, we assume the count is unchanged.\n const maxHistory = 20;\n const events = room.getLiveTimeline().getEvents();\n\n let highlightCount = 0;\n\n for (let i = events.length - 1; i >= 0; i--) {\n if (i === events.length - maxHistory) return; // limit reached\n\n const event = events[i];\n\n if (room.hasUserReadEvent(this.getUserId(), event.getId())) {\n // If the user has read the event, then the counting is done.\n break;\n }\n\n const pushActions = this.getPushActionsForEvent(event);\n highlightCount += pushActions.tweaks &&\n pushActions.tweaks.highlight ? 1 : 0;\n }\n\n // Note: we don't need to handle 'total' notifications because the counts\n // will come from the server.\n room.setUnreadNotificationCount(\"highlight\", highlightCount);\n }\n });\n }\n\n /**\n * High level helper method to begin syncing and poll for new events. To listen for these\n * events, add a listener for {@link module:client~MatrixClient#event:\"event\"}\n * via {@link module:client~MatrixClient#on}. Alternatively, listen for specific\n * state change events.\n * @param {Object=} opts Options to apply when syncing.\n */\n public async startClient(opts: IStartClientOpts) {\n if (this.clientRunning) {\n // client is already running.\n return;\n }\n this.clientRunning = true;\n // backwards compat for when 'opts' was 'historyLen'.\n if (typeof opts === \"number\") {\n opts = {\n initialSyncLimit: opts,\n };\n }\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n if (this.crypto) {\n this.crypto.uploadDeviceKeys();\n this.crypto.start();\n }\n\n // periodically poll for turn servers if we support voip\n if (this.canSupportVoip) {\n this.checkTurnServersIntervalID = setInterval(() => {\n this.checkTurnServers();\n }, TURN_CHECK_INTERVAL) as any as number; // XXX: Typecast because we know better\n // noinspection ES6MissingAwait\n this.checkTurnServers();\n }\n\n if (this.syncApi) {\n // This shouldn't happen since we thought the client was not running\n logger.error(\"Still have sync object whilst not running: stopping old one\");\n this.syncApi.stop();\n }\n\n // shallow-copy the opts dict before modifying and storing it\n this.clientOpts = <any>Object.assign({}, opts); // XXX: Typecast because we're about to add the missing props\n this.clientOpts.crypto = this.crypto;\n this.clientOpts.canResetEntireTimeline = (roomId) => {\n if (!this.canResetTimelineCallback) {\n return false;\n }\n return this.canResetTimelineCallback(roomId);\n };\n this.syncApi = new SyncApi(this, this.clientOpts);\n this.syncApi.sync();\n\n if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {\n this.clientWellKnownIntervalID =\n // XXX: Typecast on timer ID because we know better\n setInterval(() => {\n this.fetchClientWellKnown();\n }, 1000 * this.clientOpts.clientWellKnownPollPeriod) as any as number;\n this.fetchClientWellKnown();\n }\n }\n\n /**\n * High level helper method to stop the client from polling and allow a\n * clean shutdown.\n */\n public stopClient() {\n logger.log('stopping MatrixClient');\n\n this.clientRunning = false;\n\n this.syncApi?.stop();\n this.syncApi = null;\n\n this.crypto?.stop();\n this.peekSync?.stopPeeking();\n\n this.callEventHandler?.stop();\n this.callEventHandler = null;\n\n global.clearInterval(this.checkTurnServersIntervalID);\n if (this.clientWellKnownIntervalID !== undefined) {\n global.clearInterval(this.clientWellKnownIntervalID);\n }\n }\n\n /**\n * Try to rehydrate a device if available. The client must have been\n * initialized with a `cryptoCallback.getDehydrationKey` option, and this\n * function must be called before initCrypto and startClient are called.\n *\n * @return {Promise<string>} Resolves to undefined if a device could not be dehydrated, or\n * to the new device ID if the dehydration was successful.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async rehydrateDevice(): Promise<string> {\n if (this.crypto) {\n throw new Error(\"Cannot rehydrate device after crypto is initialized\");\n }\n\n if (!this.cryptoCallbacks.getDehydrationKey) {\n return;\n }\n\n const getDeviceResult = await this.getDehydratedDevice();\n if (!getDeviceResult) {\n return;\n }\n\n if (!getDeviceResult.device_data || !getDeviceResult.device_id) {\n logger.info(\"no dehydrated device found\");\n return;\n }\n\n const account = new global.Olm.Account();\n try {\n const deviceData = getDeviceResult.device_data;\n if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {\n logger.warn(\"Wrong algorithm for dehydrated device\");\n return;\n }\n logger.log(\"unpickling dehydrated device\");\n const key = await this.cryptoCallbacks.getDehydrationKey(\n deviceData,\n (k) => {\n // copy the key so that it doesn't get clobbered\n account.unpickle(new Uint8Array(k), deviceData.account);\n },\n );\n account.unpickle(key, deviceData.account);\n logger.log(\"unpickled device\");\n\n const rehydrateResult = await this.http.authedRequest(\n undefined,\n \"POST\",\n \"/dehydrated_device/claim\",\n undefined,\n {\n device_id: getDeviceResult.device_id,\n },\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n\n if (rehydrateResult.success === true) {\n this.deviceId = getDeviceResult.device_id;\n logger.info(\"using dehydrated device\");\n const pickleKey = this.pickleKey || \"DEFAULT_KEY\";\n this.exportedOlmDeviceToImport = {\n pickledAccount: account.pickle(pickleKey),\n sessions: [],\n pickleKey: pickleKey,\n };\n account.free();\n return this.deviceId;\n } else {\n account.free();\n logger.info(\"not using dehydrated device\");\n return;\n }\n } catch (e) {\n account.free();\n logger.warn(\"could not unpickle\", e);\n }\n }\n\n /**\n * Get the current dehydrated device, if any\n * @return {Promise} A promise of an object containing the dehydrated device\n */\n public async getDehydratedDevice(): Promise<IDehydratedDevice> {\n try {\n return await this.http.authedRequest(\n undefined,\n \"GET\",\n \"/dehydrated_device\",\n undefined, undefined,\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n } catch (e) {\n logger.info(\"could not get dehydrated device\", e.toString());\n return;\n }\n }\n\n /**\n * Set the dehydration key. This will also periodically dehydrate devices to\n * the server.\n *\n * @param {Uint8Array} key the dehydration key\n * @param {IDehydratedDeviceKeyInfo} [keyInfo] Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param {string} [deviceDisplayName] The device display name for the\n * dehydrated device.\n * @return {Promise} A promise that resolves when the dehydrated device is stored.\n */\n public async setDehydrationKey(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise<void> {\n if (!this.crypto) {\n logger.warn('not dehydrating device if crypto is not enabled');\n return;\n }\n // XXX: Private member access.\n return await this.crypto.dehydrationManager.setKeyAndQueueDehydration(\n key, keyInfo, deviceDisplayName,\n );\n }\n\n /**\n * Creates a new dehydrated device (without queuing periodic dehydration)\n * @param {Uint8Array} key the dehydration key\n * @param {IDehydratedDeviceKeyInfo} [keyInfo] Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param {string} [deviceDisplayName] The device display name for the\n * dehydrated device.\n * @return {Promise<String>} the device id of the newly created dehydrated device\n */\n public async createDehydratedDevice(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise<string> {\n if (!this.crypto) {\n logger.warn('not dehydrating device if crypto is not enabled');\n return;\n }\n await this.crypto.dehydrationManager.setKey(\n key, keyInfo, deviceDisplayName,\n );\n // XXX: Private member access.\n return await this.crypto.dehydrationManager.dehydrateDevice();\n }\n\n public async exportDevice(): Promise<IExportedDevice> {\n if (!this.crypto) {\n logger.warn('not exporting device if crypto is not enabled');\n return;\n }\n return {\n userId: this.credentials.userId,\n deviceId: this.deviceId,\n // XXX: Private member access.\n olmDevice: await this.crypto.olmDevice.export(),\n };\n }\n\n /**\n * Clear any data out of the persistent stores used by the client.\n *\n * @returns {Promise} Promise which resolves when the stores have been cleared.\n */\n public clearStores(): Promise<void> {\n if (this.clientRunning) {\n throw new Error(\"Cannot clear stores while client is running\");\n }\n\n const promises = [];\n\n promises.push(this.store.deleteAllData());\n if (this.cryptoStore) {\n promises.push(this.cryptoStore.deleteAllData());\n }\n return Promise.all(promises).then(); // .then to fix types\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @return {?string} MXID for the logged-in user, or null if not logged in\n */\n public getUserId(): string {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId;\n }\n return null;\n }\n\n /**\n * Get the domain for this client's MXID\n * @return {?string} Domain of this MXID\n */\n public getDomain(): string {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.replace(/^.*?:/, '');\n }\n return null;\n }\n\n /**\n * Get the local part of the current user ID e.g. \"foo\" in \"@foo:bar\".\n * @return {?string} The user ID localpart or null.\n */\n public getUserIdLocalpart(): string {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.split(\":\")[0].substring(1);\n }\n return null;\n }\n\n /**\n * Get the device ID of this client\n * @return {?string} device ID\n */\n public getDeviceId(): string {\n return this.deviceId;\n }\n\n /**\n * Check if the runtime environment supports VoIP calling.\n * @return {boolean} True if VoIP is supported.\n */\n public supportsVoip(): boolean {\n return this.canSupportVoip;\n }\n\n /**\n * Set whether VoIP calls are forced to use only TURN\n * candidates. This is the same as the forceTURN option\n * when creating the client.\n * @param {boolean} force True to force use of TURN servers\n */\n public setForceTURN(force: boolean) {\n this.forceTURN = force;\n }\n\n /**\n * Set whether to advertise transfer support to other parties on Matrix calls.\n * @param {boolean} support True to advertise the 'm.call.transferee' capability\n */\n public setSupportsCallTransfer(support: boolean) {\n this.supportsCallTransfer = support;\n }\n\n public async getLocalVideoStream() {\n if (this.localAVStreamType === ConstraintsType.Video) {\n return this.localAVStream.clone();\n }\n\n const constraints = getUserMediaContraints(ConstraintsType.Video);\n logger.log(\"Getting user media with constraints\", constraints);\n const mediaStream = await navigator.mediaDevices.getUserMedia(constraints);\n this.localAVStreamType = ConstraintsType.Video;\n this.localAVStream = mediaStream;\n return mediaStream;\n }\n\n public async getLocalAudioStream() {\n if (this.localAVStreamType === ConstraintsType.Audio) {\n return this.localAVStream.clone();\n }\n\n const constraints = getUserMediaContraints(ConstraintsType.Audio);\n logger.log(\"Getting user media with constraints\", constraints);\n const mediaStream = await navigator.mediaDevices.getUserMedia(constraints);\n this.localAVStreamType = ConstraintsType.Audio;\n this.localAVStream = mediaStream;\n return mediaStream;\n }\n\n public stopLocalMediaStream() {\n if (this.localAVStream) {\n for (const track of this.localAVStream.getTracks()) {\n track.stop();\n }\n\n this.localAVStreamType = null;\n this.localAVStream = null;\n }\n }\n\n /**\n * Creates a new call.\n * The place*Call methods on the returned call can be used to actually place a call\n *\n * @param {string} roomId The room the call is to be placed in.\n * @param {string} invitee The user to call in the given room.\n * @return {MatrixCall} the call or null if the browser doesn't support calling.\n */\n public createCall(roomId: string, invitee?: string): MatrixCall {\n return createNewMatrixCall(this, roomId, { invitee });\n }\n\n /**\n * Get the current sync state.\n * @return {?SyncState} the sync state, which may be null.\n * @see module:client~MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState {\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncState();\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n * @return {?Object}\n */\n public getSyncStateData(): any { // TODO: Unify types.\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncStateData();\n }\n\n /**\n * Whether the initial sync has completed.\n * @return {boolean} True if at least one sync has happened.\n */\n public isInitialSyncComplete(): boolean {\n const state = this.getSyncState();\n if (!state) {\n return false;\n }\n return state === SyncState.Prepared || state === SyncState.Syncing;\n }\n\n /**\n * Return whether the client is configured for a guest account.\n * @return {boolean} True if this is a guest access_token (or no token is supplied).\n */\n public isGuest(): boolean {\n return this.isGuestAccount;\n }\n\n /**\n * Set whether this client is a guest account. <b>This method is experimental\n * and may change without warning.</b>\n * @param {boolean} guest True if this is a guest account.\n */\n public setGuest(guest: boolean) {\n // EXPERIMENTAL:\n // If the token is a macaroon, it should be encoded in it that it is a 'guest'\n // access token, which means that the SDK can determine this entirely without\n // the dev manually flipping this flag.\n this.isGuestAccount = guest;\n }\n\n /**\n * Return the provided scheduler, if any.\n * @return {?module:scheduler~MatrixScheduler} The scheduler or null\n */\n public getScheduler(): MatrixScheduler {\n return this.scheduler;\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * @return {boolean} True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n return this.syncApi.retryImmediately();\n }\n\n /**\n * Return the global notification EventTimelineSet, if any\n *\n * @return {EventTimelineSet} the globl notification EventTimelineSet\n */\n public getNotifTimelineSet(): EventTimelineSet {\n return this.notifTimelineSet;\n }\n\n /**\n * Set the global notification EventTimelineSet\n *\n * @param {EventTimelineSet} set\n */\n public setNotifTimelineSet(set: EventTimelineSet) {\n this.notifTimelineSet = set;\n }\n\n /**\n * Gets the capabilities of the homeserver. Always returns an object of\n * capability keys and their options, which may be empty.\n * @param {boolean} fresh True to ignore any cached values.\n * @return {Promise} Resolves to the capabilities of the homeserver\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getCapabilities(fresh = false): Promise<ICapabilities> {\n const now = new Date().getTime();\n\n if (this.cachedCapabilities && !fresh) {\n if (now < this.cachedCapabilities.expiration) {\n logger.log(\"Returning cached capabilities\");\n return Promise.resolve(this.cachedCapabilities.capabilities);\n }\n }\n\n // We swallow errors because we need a default object anyhow\n return this.http.authedRequest(\n undefined, \"GET\", \"/capabilities\",\n ).catch((e) => {\n logger.error(e);\n return null; // otherwise consume the error\n }).then((r) => {\n if (!r) r = {};\n const capabilities: ICapabilities = r[\"capabilities\"] || {};\n\n // If the capabilities missed the cache, cache it for a shorter amount\n // of time to try and refresh them later.\n const cacheMs = Object.keys(capabilities).length\n ? CAPABILITIES_CACHE_MS\n : 60000 + (Math.random() * 5000);\n\n this.cachedCapabilities = {\n capabilities,\n expiration: now + cacheMs,\n };\n\n logger.log(\"Caching capabilities: \", capabilities);\n return capabilities;\n });\n }\n\n /**\n * Initialise support for end-to-end encryption in this client\n *\n * You should call this method after creating the matrixclient, but *before*\n * calling `startClient`, if you want to support end-to-end encryption.\n *\n * It will return a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n */\n public async initCrypto(): Promise<void> {\n if (!isCryptoAvailable()) {\n throw new Error(\n `End-to-end encryption not supported in this js-sdk build: did ` +\n `you remember to load the olm library?`,\n );\n }\n\n if (this.crypto) {\n logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n if (!this.sessionStore) {\n // this is temporary, the sessionstore is supposed to be going away\n throw new Error(`Cannot enable encryption: no sessionStore provided`);\n }\n if (!this.cryptoStore) {\n // the cryptostore is provided by sdk.createClient, so this shouldn't happen\n throw new Error(`Cannot enable encryption: no cryptoStore provided`);\n }\n\n logger.log(\"Crypto: Starting up crypto store...\");\n await this.cryptoStore.startup();\n\n // initialise the list of encrypted rooms (whether or not crypto is enabled)\n logger.log(\"Crypto: initialising roomlist...\");\n await this.roomList.init();\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n if (this.deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n const crypto = new Crypto(\n this,\n this.sessionStore,\n userId, this.deviceId,\n this.store,\n this.cryptoStore,\n this.roomList,\n this.verificationMethods,\n );\n\n this.reEmitter.reEmit(crypto, [\n \"crypto.keyBackupFailed\",\n \"crypto.keyBackupSessionsRemaining\",\n \"crypto.roomKeyRequest\",\n \"crypto.roomKeyRequestCancellation\",\n \"crypto.warning\",\n \"crypto.devicesUpdated\",\n \"crypto.willUpdateDevices\",\n \"deviceVerificationChanged\",\n \"userTrustStatusChanged\",\n \"crossSigning.keysChanged\",\n ]);\n\n logger.log(\"Crypto: initialising crypto object...\");\n await crypto.init({\n exportedOlmDevice: this.exportedOlmDeviceToImport,\n pickleKey: this.pickleKey,\n });\n delete this.exportedOlmDeviceToImport;\n\n this.olmVersion = Crypto.getOlmVersion();\n\n // if crypto initialisation was successful, tell it to attach its event\n // handlers.\n crypto.registerEventHandlers(this);\n this.crypto = crypto;\n }\n\n /**\n * Is end-to-end crypto enabled for this client.\n * @return {boolean} True if end-to-end is enabled.\n */\n public isCryptoEnabled(): boolean {\n return !!this.crypto;\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @return {?string} base64-encoded ed25519 key. Null if crypto is\n * disabled.\n */\n public getDeviceEd25519Key(): string {\n if (!this.crypto) return null;\n return this.crypto.getDeviceEd25519Key();\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @return {?string} base64-encoded curve25519 key. Null if crypto is\n * disabled.\n */\n public getDeviceCurve25519Key(): string {\n if (!this.crypto) return null;\n return this.crypto.getDeviceCurve25519Key();\n }\n\n /**\n * Upload the device keys to the homeserver.\n * @return {Promise<void>} A promise that will resolve when the keys are uploaded.\n */\n public async uploadKeys(): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.uploadDeviceKeys();\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param {Array} userIds The users to fetch.\n * @param {boolean} forceDownload Always download the keys even if cached.\n *\n * @return {Promise} A promise which resolves to a map userId->deviceId->{@link\n * module:crypto~DeviceInfo|DeviceInfo}.\n */\n public downloadKeys(\n userIds: string[],\n forceDownload?: boolean,\n ): Promise<Record<string, Record<string, IDevice>>> {\n if (!this.crypto) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.crypto.downloadKeys(userIds, forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param {string} userId the user to list keys for.\n *\n * @return {module:crypto/deviceinfo[]} list of devices\n */\n public getStoredDevicesForUser(userId: string): DeviceInfo[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevicesForUser(userId) || [];\n }\n\n /**\n * Get the stored device key for a user id and device id\n *\n * @param {string} userId the user to list keys for.\n * @param {string} deviceId unique identifier for the device\n *\n * @return {module:crypto/deviceinfo} device or null\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevice(userId, deviceId) || null;\n }\n\n /**\n * Mark the given device as verified\n *\n * @param {string} userId owner of the device\n * @param {string} deviceId unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param {boolean=} verified whether to mark the device as verified. defaults\n * to 'true'.\n *\n * @returns {Promise}\n *\n * @fires module:client~event:MatrixClient\"deviceVerificationChanged\"\n */\n public setDeviceVerified(userId: string, deviceId: string, verified = true): Promise<void> {\n const prom = this.setDeviceVerification(userId, deviceId, verified, null, null);\n\n // if one of the user's own devices is being marked as verified / unverified,\n // check the key backup status, since whether or not we use this depends on\n // whether it has a signature from a verified device\n if (userId == this.credentials.userId) {\n this.checkKeyBackup();\n }\n return prom;\n }\n\n /**\n * Mark the given device as blocked/unblocked\n *\n * @param {string} userId owner of the device\n * @param {string} deviceId unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param {boolean=} blocked whether to mark the device as blocked. defaults\n * to 'true'.\n *\n * @returns {Promise}\n *\n * @fires module:client~event:MatrixClient\"deviceVerificationChanged\"\n */\n public setDeviceBlocked(userId: string, deviceId: string, blocked = true): Promise<void> {\n return this.setDeviceVerification(userId, deviceId, null, blocked, null);\n }\n\n /**\n * Mark the given device as known/unknown\n *\n * @param {string} userId owner of the device\n * @param {string} deviceId unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param {boolean=} known whether to mark the device as known. defaults\n * to 'true'.\n *\n * @returns {Promise}\n *\n * @fires module:client~event:MatrixClient\"deviceVerificationChanged\"\n */\n public setDeviceKnown(userId: string, deviceId: string, known = true): Promise<void> {\n return this.setDeviceVerification(userId, deviceId, null, null, known);\n }\n\n private async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified: boolean,\n blocked: boolean,\n known: boolean,\n ): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n await this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known);\n }\n\n /**\n * Request a key verification from another user, using a DM.\n *\n * @param {string} userId the user to request verification with\n * @param {string} roomId the room to use for verification\n *\n * @returns {Promise<module:crypto/verification/request/VerificationRequest>} resolves to a VerificationRequest\n * when the request has been sent to the other party.\n */\n public requestVerificationDM(userId: string, roomId: string): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerificationDM(userId, roomId);\n }\n\n /**\n * Finds a DM verification request that is already in progress for the given room id\n *\n * @param {string} roomId the room to use for verification\n *\n * @returns {module:crypto/verification/request/VerificationRequest?} the VerificationRequest that is in progress, if any\n */\n public findVerificationRequestDMInProgress(roomId: string): VerificationRequest {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.findVerificationRequestDMInProgress(roomId);\n }\n\n /**\n * Returns all to-device verification requests that are already in progress for the given user id\n *\n * @param {string} userId the ID of the user to query\n *\n * @returns {module:crypto/verification/request/VerificationRequest[]} the VerificationRequests that are in progress\n */\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getVerificationRequestsToDeviceInProgress(userId);\n }\n\n /**\n * Request a key verification from another user.\n *\n * @param {string} userId the user to request verification with\n * @param {Array} devices array of device IDs to send requests to. Defaults to\n * all devices owned by the user\n *\n * @returns {Promise<module:crypto/verification/request/VerificationRequest>} resolves to a VerificationRequest\n * when the request has been sent to the other party.\n */\n public requestVerification(userId: string, devices?: string[]): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerification(userId, devices);\n }\n\n /**\n * Begin a key verification.\n *\n * @param {string} method the verification method to use\n * @param {string} userId the user to verify keys with\n * @param {string} deviceId the device to verify\n *\n * @returns {Verification} a verification object\n */\n public beginKeyVerification(method: string, userId: string, deviceId: string): Verification {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.beginKeyVerification(method, userId, deviceId);\n }\n\n public checkSecretStorageKey(key: any, info: any): Promise<any> { // TODO: Types\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkSecretStorageKey(key, info);\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param {boolean} value whether to blacklist all unverified devices by default\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.setGlobalBlacklistUnverifiedDevices(value);\n }\n\n /**\n * @return {boolean} whether to blacklist all unverified devices by default\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getGlobalBlacklistUnverifiedDevices();\n }\n\n /**\n * Set whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send them message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n *\n * @param {boolean} value whether error on unknown devices\n */\n public setGlobalErrorOnUnknownDevices(value: boolean) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.setGlobalErrorOnUnknownDevices(value);\n }\n\n /**\n * @return {boolean} whether to error on unknown devices\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n */\n public getGlobalErrorOnUnknownDevices(): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getGlobalErrorOnUnknownDevices();\n }\n\n /**\n * Get the user's cross-signing key ID.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {CrossSigningKey} [type=master] The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns {string} the key ID\n */\n public getCrossSigningId(type: CrossSigningKey | string = CrossSigningKey.Master): string {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getCrossSigningId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {string} userId the user ID to get the cross-signing info for.\n *\n * @returns {CrossSigningInfo} the cross signing information for the user.\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {string} userId The ID of the user to check.\n *\n * @returns {UserTrustLevel}\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkUserTrust(userId);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @function module:client~MatrixClient#checkDeviceTrust\n * @param {string} userId The ID of the user whose devices is to be checked.\n * @param {string} deviceId The ID of the device to check\n *\n * @returns {DeviceTrustLevel}\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkDeviceTrust(userId, deviceId);\n }\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n * @param {Object} opts TODO\n */\n public checkOwnCrossSigningTrust(opts?: any): Promise<any> { // TODO: Types\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkOwnCrossSigningTrust(opts);\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n * @param {Uint8Array} privateKey The private key\n * @param {string} expectedPublicKey The public key\n * @returns {boolean} true if the key matches, otherwise false\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey);\n }\n\n public legacyDeviceVerification(userId: string, deviceId: string, method: string): Promise<VerificationRequest> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.legacyDeviceVerification(userId, deviceId, method);\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n * @param {module:models/room} room the room the event is in\n */\n public prepareToEncrypt(room: Room) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.prepareToEncrypt(room);\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n * @return {boolean} True if cross-signing is ready to be used on this device\n */\n public isCrossSigningReady(): Promise<boolean> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.isCrossSigningReady();\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been setup)\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {function} opts.authUploadDeviceSigningKeys Function\n * called to await an interactive auth flow when uploading device signing keys.\n * @param {boolean} [opts.setupNewCrossSigning] Optional. Reset even if keys\n * already exist.\n * Args:\n * {function} A function that makes the request requiring auth. Receives the\n * auth data as an object. Can be called multiple times, first with an empty\n * authDict, to obtain the flows.\n */\n public bootstrapCrossSigning(opts: IBootstrapCrossSigningOpts) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.bootstrapCrossSigning(opts);\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @return {boolean} True if trusting cross-signed devices\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getCryptoTrustCrossSignedDevices();\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n\n * This may be set before initCrypto() is called to ensure no races occur.\n *\n * @param {boolean} val True to trust cross-signed devices\n */\n public setCryptoTrustCrossSignedDevices(val: boolean) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.setCryptoTrustCrossSignedDevices(val);\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns {Promise<int>} Resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise<number> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.countSessionsNeedingBackup();\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param {module:models/event.MatrixEvent} event event to be checked\n * @returns {IEncryptedEventInfo} The event information.\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getEventEncryptionInfo(event);\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} password Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns {Promise<Object>} Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n public createRecoveryKeyFromPassphrase(password: string): Promise<IRecoveryKey> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.createRecoveryKeyFromPassphrase(password);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @return {boolean} True if secret storage is ready to be used on this device\n */\n public isSecretStorageReady(): Promise<boolean> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.isSecretStorageReady();\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n * @param opts\n */\n public bootstrapSecretStorage(opts: ICreateSecretStorageOpts): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.bootstrapSecretStorage(opts);\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} algorithm the algorithm used by the key\n * @param {object} opts the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param {string} [keyName] the name of the key. If not given, a random name will be generated.\n *\n * @return {object} An object with:\n * keyId: {string} the ID of the key\n * keyInfo: {object} details about the key (iv, mac, passphrase)\n */\n public addSecretStorageKey(\n algorithm: string,\n opts: IAddSecretStorageKeyOpts,\n keyName?: string,\n ): Promise<{keyId: string, keyInfo: ISecretStorageKeyInfo}> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.addSecretStorageKey(algorithm, opts, keyName);\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} [keyId = default key's ID] The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @return {boolean} Whether we have the key.\n */\n public hasSecretStorageKey(keyId?: string): Promise<boolean> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.hasSecretStorageKey(keyId);\n }\n\n /**\n * Store an encrypted secret on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} name The name of the secret\n * @param {string} secret The secret contents.\n * @param {Array} keys The IDs of the keys to use to encrypt the secret or null/undefined\n * to use the default (will throw if no default key is set).\n */\n public storeSecret(name: string, secret: string, keys?: string[]) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.storeSecret(name, secret, keys);\n }\n\n /**\n * Get a secret from storage.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} name the name of the secret\n *\n * @return {string} the contents of the secret\n */\n public getSecret(name: string): Promise<string> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getSecret(name);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} name the name of the secret\n * @param {boolean} checkKey check if the secret is encrypted by a trusted\n * key\n *\n * @return {object?} map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public isSecretStored(name: string, checkKey: boolean): Promise<Record<string, ISecretStorageKeyInfo>> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.isSecretStored(name, checkKey);\n }\n\n /**\n * Request a secret from another device.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} name the name of the secret to request\n * @param {string[]} devices the devices to request the secret from\n *\n * @return {string} the contents of the secret\n */\n public requestSecret(name: string, devices: string[]): any { // TODO types\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestSecret(name, devices);\n }\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @return {string} The default key ID or null if no default key ID is set\n */\n public getDefaultSecretStorageKeyId(): Promise<string> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getDefaultSecretStorageKeyId();\n }\n\n /**\n * Set the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {string} keyId The new default key ID\n */\n public setDefaultSecretStorageKeyId(keyId: string) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.setDefaultSecretStorageKeyId(keyId);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {Uint8Array} privateKey The private key\n * @param {string} expectedPublicKey The public key\n * @returns {boolean} true if the key matches, otherwise false\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey);\n }\n\n /**\n * Get e2e information on the device that sent an event\n *\n * @param {MatrixEvent} event event to be checked\n *\n * @return {Promise<module:crypto/deviceinfo?>}\n */\n public async getEventSenderDeviceInfo(event: MatrixEvent): Promise<DeviceInfo> {\n if (!this.crypto) {\n return null;\n }\n return this.crypto.getEventSenderDeviceInfo(event);\n }\n\n /**\n * Check if the sender of an event is verified\n *\n * @param {MatrixEvent} event event to be checked\n *\n * @return {boolean} true if the sender of this event has been verified using\n * {@link module:client~MatrixClient#setDeviceVerified|setDeviceVerified}.\n */\n public async isEventSenderVerified(event: MatrixEvent): Promise<boolean> {\n const device = await this.getEventSenderDeviceInfo(event);\n if (!device) {\n return false;\n }\n return device.isVerified();\n }\n\n /**\n * Cancel a room key request for this event if one is ongoing and resend the\n * request.\n * @param {MatrixEvent} event event of which to cancel and resend the room\n * key request.\n * @return {Promise} A promise that will resolve when the key request is queued\n */\n public cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise<void> {\n return event.cancelAndResendKeyRequest(this.crypto, this.getUserId());\n }\n\n /**\n * Enable end-to-end encryption for a room. This does not modify room state.\n * Any messages sent before the returned promise resolves will be sent unencrypted.\n * @param {string} roomId The room ID to enable encryption in.\n * @param {object} config The encryption config for the room.\n * @return {Promise} A promise that will resolve when encryption is set up.\n */\n public setRoomEncryption(roomId: string, config: any): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.setRoomEncryption(roomId, config);\n }\n\n /**\n * Whether encryption is enabled for a room.\n * @param {string} roomId the room id to query.\n * @return {boolean} whether encryption is enabled.\n */\n public isRoomEncrypted(roomId: string): boolean {\n const room = this.getRoom(roomId);\n if (!room) {\n // we don't know about this room, so can't determine if it should be\n // encrypted. Let's assume not.\n return false;\n }\n\n // if there is an 'm.room.encryption' event in this room, it should be\n // encrypted (independently of whether we actually support encryption)\n const ev = room.currentState.getStateEvents(\"m.room.encryption\", \"\");\n if (ev) {\n return true;\n }\n\n // we don't have an m.room.encrypted event, but that might be because\n // the server is hiding it from us. Check the store to see if it was\n // previously encrypted.\n return this.roomList.isRoomEncrypted(roomId);\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param {string} roomId The ID of the room to discard the session for\n *\n * This should not normally be necessary.\n */\n public forceDiscardSession(roomId: string) {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n this.crypto.forceDiscardSession(roomId);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * This should be encrypted before returning it to the user.\n *\n * @return {Promise} a promise which resolves to a list of\n * session export objects\n */\n public exportRoomKeys(): Promise<any[]> { // TODO: Types\n if (!this.crypto) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.crypto.exportRoomKeys();\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param {Object[]} keys a list of session export objects\n * @param {Object} opts\n * @param {Function} opts.progressCallback called with an object that has a \"stage\" param\n *\n * @return {Promise} a promise which resolves when the keys\n * have been imported\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts: IImportRoomKeysOpts): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.importRoomKeys(keys, opts);\n }\n\n /**\n * Force a re-check of the local key backup status against\n * what's on the server.\n *\n * @returns {Object} Object with backup info (as returned by\n * getKeyBackupVersion) in backupInfo and\n * trust information (as returned by isKeyBackupTrusted)\n * in trustInfo.\n */\n public checkKeyBackup(): Promise<IKeyBackupCheck> {\n return this.crypto.backupManager.checkKeyBackup();\n }\n\n /**\n * Get information about the current key backup.\n * @returns {Promise} Information object from API or null\n */\n public async getKeyBackupVersion(): Promise<IKeyBackupInfo> {\n let res;\n try {\n res = await this.http.authedRequest(\n undefined, \"GET\", \"/room_keys/version\", undefined, undefined,\n { prefix: PREFIX_UNSTABLE },\n );\n } catch (e) {\n if (e.errcode === 'M_NOT_FOUND') {\n return null;\n } else {\n throw e;\n }\n }\n try {\n BackupManager.checkBackupVersion(res);\n } catch (e) {\n throw e;\n }\n return res;\n }\n\n /**\n * @param {object} info key backup info dict from getKeyBackupVersion()\n * @return {object} {\n * usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device\n * sigs: [\n * valid: [bool],\n * device: [DeviceInfo],\n * ]\n * }\n */\n public isKeyBackupTrusted(info: IKeyBackupInfo): Promise<TrustInfo> {\n return this.crypto.backupManager.isKeyBackupTrusted(info);\n }\n\n /**\n * @returns {boolean} true if the client is configured to back up keys to\n * the server, otherwise false. If we haven't completed a successful check\n * of key backup status yet, returns null.\n */\n public getKeyBackupEnabled(): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.getKeyBackupEnabled();\n }\n\n /**\n * Enable backing up of keys, using data previously returned from\n * getKeyBackupVersion.\n *\n * @param {object} info Backup information object as returned by getKeyBackupVersion\n * @returns {Promise<void>} Resolves when complete.\n */\n public enableKeyBackup(info: IKeyBackupInfo): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.enableKeyBackup(info);\n }\n\n /**\n * Disable backing up of keys.\n */\n public disableKeyBackup() {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n this.crypto.backupManager.disableKeyBackup();\n }\n\n /**\n * Set up the data required to create a new backup version. The backup version\n * will not be created and enabled until createKeyBackupVersion is called.\n *\n * @param {string} password Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @param {boolean} [opts.secureSecretStorage = false] Whether to use Secure\n * Secret Storage to store the key encrypting key backups.\n * Optional, defaults to false.\n *\n * @returns {Promise<object>} Object that can be passed to createKeyBackupVersion and\n * additionally has a 'recovery_key' member with the user-facing recovery key string.\n */\n // TODO: Verify types\n public async prepareKeyBackupVersion(\n password: string,\n opts: IKeyBackupPrepareOpts = { secureSecretStorage: false },\n ): Promise<Pick<IPreparedKeyBackupVersion, \"algorithm\" | \"auth_data\" | \"recovery_key\">> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n // eslint-disable-next-line camelcase\n const { algorithm, auth_data, recovery_key, privateKey } =\n await this.crypto.backupManager.prepareKeyBackupVersion(password);\n\n if (opts.secureSecretStorage) {\n await this.storeSecret(\"m.megolm_backup.v1\", encodeBase64(privateKey));\n logger.info(\"Key backup private key stored in secret storage\");\n }\n\n return {\n algorithm,\n auth_data,\n recovery_key,\n };\n }\n\n /**\n * Check whether the key backup private key is stored in secret storage.\n * @return {Promise<object?>} map of key name to key info the secret is\n * encrypted with, or null if it is not present or not encrypted with a\n * trusted key\n */\n public isKeyBackupKeyStored(): Promise<Record<string, ISecretStorageKeyInfo>> {\n return Promise.resolve(this.isSecretStored(\"m.megolm_backup.v1\", false /* checkKey */));\n }\n\n /**\n * Create a new key backup version and enable it, using the information return\n * from prepareKeyBackupVersion.\n *\n * @param {object} info Info object from prepareKeyBackupVersion\n * @returns {Promise<object>} Object with 'version' param indicating the version created\n */\n // TODO: Fix types\n public async createKeyBackupVersion(info: IKeyBackupInfo): Promise<IKeyBackupInfo> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.createKeyBackupVersion(info);\n\n const data = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign the backup auth data with the device key for backwards compat with\n // older devices with cross-signing. This can probably go away very soon in\n // favour of just signing with the cross-singing master key.\n // XXX: Private member access\n await this.crypto.signObject(data.auth_data);\n\n if (\n this.cryptoCallbacks.getCrossSigningKey &&\n // XXX: Private member access\n this.crypto.crossSigningInfo.getId()\n ) {\n // now also sign the auth data with the cross-signing master key\n // we check for the callback explicitly here because we still want to be able\n // to create an un-cross-signed key backup if there is a cross-signing key but\n // no callback supplied.\n // XXX: Private member access\n await this.crypto.crossSigningInfo.signObject(data.auth_data, \"master\");\n }\n\n const res = await this.http.authedRequest(\n undefined, \"POST\", \"/room_keys/version\", undefined, data,\n { prefix: PREFIX_UNSTABLE },\n );\n\n // We could assume everything's okay and enable directly, but this ensures\n // we run the same signature verification that will be used for future\n // sessions.\n await this.checkKeyBackup();\n if (!this.getKeyBackupEnabled()) {\n logger.error(\"Key backup not usable even though we just created it\");\n }\n\n return res;\n }\n\n public deleteKeyBackupVersion(version: string): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n // If we're currently backing up to this backup... stop.\n // (We start using it automatically in createKeyBackupVersion\n // so this is symmetrical).\n if (this.crypto.backupManager.version) {\n this.crypto.backupManager.disableKeyBackup();\n }\n\n const path = utils.encodeUri(\"/room_keys/version/$version\", {\n $version: version,\n });\n\n return this.http.authedRequest(\n undefined, \"DELETE\", path, undefined, undefined,\n { prefix: PREFIX_UNSTABLE },\n );\n }\n\n private makeKeyBackupPath(roomId: string, sessionId: string, version: string): { path: string, queryData: any } {\n let path;\n if (sessionId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId,\n $sessionId: sessionId,\n });\n } else if (roomId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId\", {\n $roomId: roomId,\n });\n } else {\n path = \"/room_keys/keys\";\n }\n const queryData = version === undefined ? undefined : { version: version };\n return {\n path: path,\n queryData: queryData,\n };\n }\n\n /**\n * Back up session keys to the homeserver.\n * @param {string} roomId ID of the room that the keys are for Optional.\n * @param {string} sessionId ID of the session that the keys are for Optional.\n * @param {number} version backup version Optional.\n * @param {object} data Object keys to send\n * @return {Promise} a promise that will resolve when the keys\n * are uploaded\n */\n // TODO: Verify types\n public sendKeyBackup(roomId: string, sessionId: string, version: string, data: any): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const path = this.makeKeyBackupPath(roomId, sessionId, version);\n return this.http.authedRequest(\n undefined, \"PUT\", path.path, path.queryData, data,\n { prefix: PREFIX_UNSTABLE },\n );\n }\n\n /**\n * Marks all group sessions as needing to be backed up and schedules them to\n * upload in the background as soon as possible.\n */\n public async scheduleAllGroupSessionsForBackup() {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.scheduleAllGroupSessionsForBackup();\n }\n\n /**\n * Marks all group sessions as needing to be backed up without scheduling\n * them to upload in the background.\n * @returns {Promise<int>} Resolves to the number of sessions requiring a backup.\n */\n public flagAllGroupSessionsForBackup(): Promise<number> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.flagAllGroupSessionsForBackup();\n }\n\n public isValidRecoveryKey(recoveryKey: string): boolean {\n try {\n decodeRecoveryKey(recoveryKey);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Get the raw key for a key backup from the password\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {string} password Passphrase\n * @param {object} backupInfo Backup metadata from `checkKeyBackup`\n * @return {Promise<Uint8Array>} key backup key\n */\n public keyBackupKeyFromPassword(password: string, backupInfo: IKeyBackupInfo): Promise<Uint8Array> {\n return keyFromAuthData(backupInfo.auth_data, password);\n }\n\n /**\n * Get the raw key for a key backup from the recovery key\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {string} recoveryKey The recovery key\n * @return {Uint8Array} key backup key\n */\n public keyBackupKeyFromRecoveryKey(recoveryKey: string): Uint8Array {\n return decodeRecoveryKey(recoveryKey);\n }\n\n /**\n * Restore from an existing key backup via a passphrase.\n *\n * @param {string} password Passphrase\n * @param {string} [targetRoomId] Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param {string} [targetSessionId] Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param {object} backupInfo Backup metadata from `checkKeyBackup`\n * @param {object} opts Optional params such as callbacks\n * @return {Promise<object>} Status of restoration with `total` and `imported`\n * key counts.\n */\n // TODO: Types\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = await keyFromAuthData(backupInfo.auth_data, password);\n return this.restoreKeyBackup(\n privKey, targetRoomId, targetSessionId, backupInfo, opts,\n );\n }\n\n /**\n * Restore from an existing key backup via a private key stored in secret\n * storage.\n *\n * @param {object} backupInfo Backup metadata from `checkKeyBackup`\n * @param {string} [targetRoomId] Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param {string} [targetSessionId] Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param {object} opts Optional params such as callbacks\n * @return {Promise<object>} Status of restoration with `total` and `imported`\n * key counts.\n */\n // TODO: Types\n public async restoreKeyBackupWithSecretStorage(\n backupInfo: IKeyBackupInfo,\n targetRoomId?: string,\n targetSessionId?: string,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const storedKey = await this.getSecret(\"m.megolm_backup.v1\");\n\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const [keyId] = await this.crypto.getSecretStorageKey();\n await this.storeSecret(\"m.megolm_backup.v1\", fixedKey, [keyId]);\n }\n\n const privKey = decodeBase64(fixedKey || storedKey);\n return this.restoreKeyBackup(\n privKey, targetRoomId, targetSessionId, backupInfo, opts,\n );\n }\n\n /**\n * Restore from an existing key backup via an encoded recovery key.\n *\n * @param {string} recoveryKey Encoded recovery key\n * @param {string} [targetRoomId] Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param {string} [targetSessionId] Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param {object} backupInfo Backup metadata from `checkKeyBackup`\n * @param {object} opts Optional params such as callbacks\n\n * @return {Promise<object>} Status of restoration with `total` and `imported`\n * key counts.\n */\n // TODO: Types\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = decodeRecoveryKey(recoveryKey);\n return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts);\n }\n\n // TODO: Types\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const privKey = await this.crypto.getSessionBackupPrivateKey();\n if (!privKey) {\n throw new Error(\"Couldn't get key\");\n }\n return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts);\n }\n\n private async restoreKeyBackup(\n privKey: ArrayLike<number>,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise<IKeyBackupRestoreResult> {\n const cacheCompleteCallback = opts?.cacheCompleteCallback;\n const progressCallback = opts?.progressCallback;\n\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n let totalKeyCount = 0;\n let keys = [];\n\n const path = this.makeKeyBackupPath(\n targetRoomId, targetSessionId, backupInfo.version,\n );\n\n const algorithm = await BackupManager.makeAlgorithm(backupInfo, async () => { return privKey; });\n\n const untrusted = algorithm.untrusted;\n\n try {\n // If the pubkey computed from the private data we've been given\n // doesn't match the one in the auth_data, the user has entered\n // a different recovery key / the wrong passphrase.\n if (!await algorithm.keyMatches(privKey)) {\n return Promise.reject(new MatrixError({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY }));\n }\n\n // Cache the key, if possible.\n // This is async.\n this.crypto.storeSessionBackupPrivateKey(privKey)\n .catch((e) => {\n logger.warn(\"Error caching session backup key:\", e);\n }).then(cacheCompleteCallback);\n\n if (progressCallback) {\n progressCallback({\n stage: \"fetch\",\n });\n }\n\n const res = await this.http.authedRequest(\n undefined, \"GET\", path.path, path.queryData, undefined,\n { prefix: PREFIX_UNSTABLE },\n );\n\n if (res.rooms) {\n // TODO: Types\n for (const [roomId, roomData] of Object.entries<any>(res.rooms)) {\n if (!roomData.sessions) continue;\n\n totalKeyCount += Object.keys(roomData.sessions).length;\n const roomKeys = await algorithm.decryptSessions(\n roomData.sessions,\n );\n for (const k of roomKeys) {\n k.room_id = roomId;\n keys.push(k);\n }\n }\n } else if (res.sessions) {\n totalKeyCount = Object.keys(res.sessions).length;\n keys = await algorithm.decryptSessions(\n res.sessions,\n );\n for (const k of keys) {\n k.room_id = targetRoomId;\n }\n } else {\n totalKeyCount = 1;\n try {\n const [key] = await algorithm.decryptSessions({\n [targetSessionId]: res,\n });\n key.room_id = targetRoomId;\n key.session_id = targetSessionId;\n keys.push(key);\n } catch (e) {\n logger.log(\"Failed to decrypt megolm session from backup\", e);\n }\n }\n } finally {\n algorithm.free();\n }\n\n await this.importRoomKeys(keys, {\n progressCallback,\n untrusted,\n source: \"backup\",\n });\n\n await this.checkKeyBackup();\n\n return { total: totalKeyCount, imported: keys.length };\n }\n\n public deleteKeysFromBackup(roomId: string, sessionId: string, version: string): Promise<void> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const path = this.makeKeyBackupPath(roomId, sessionId, version);\n return this.http.authedRequest(\n undefined, \"DELETE\", path.path, path.queryData, undefined,\n { prefix: PREFIX_UNSTABLE },\n );\n }\n\n /**\n * Share shared-history decryption keys with the given users.\n *\n * @param {string} roomId the room for which keys should be shared.\n * @param {array} userIds a list of users to share with. The keys will be sent to\n * all of the user's current devices.\n */\n public async sendSharedHistoryKeys(roomId: string, userIds: string[]) {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const roomEncryption = this.roomList.getRoomEncryption(roomId);\n if (!roomEncryption) {\n // unknown room, or unencrypted room\n logger.error(\"Unknown room. Not sharing decryption keys\");\n return;\n }\n\n const deviceInfos = await this.crypto.downloadKeys(userIds);\n const devicesByUser = {};\n for (const [userId, devices] of Object.entries(deviceInfos)) {\n devicesByUser[userId] = Object.values(devices);\n }\n\n // XXX: Private member access\n const alg = this.crypto.getRoomDecryptor(roomId, roomEncryption.algorithm);\n if (alg.sendSharedHistoryInboundSessions) {\n await alg.sendSharedHistoryInboundSessions(devicesByUser);\n } else {\n logger.warn(\"Algorithm does not support sharing previous keys\", roomEncryption.algorithm);\n }\n }\n\n /**\n * Get the group for the given group ID.\n * This function will return a valid group for any group for which a Group event\n * has been emitted.\n * @param {string} groupId The group ID\n * @return {Group} The Group or null if the group is not known or there is no data store.\n */\n public getGroup(groupId: string): Group {\n return this.store.getGroup(groupId);\n }\n\n /**\n * Retrieve all known groups.\n * @return {Group[]} A list of groups, or an empty list if there is no data store.\n */\n public getGroups(): Group[] {\n return this.store.getGroups();\n }\n\n /**\n * Get the config for the media repository.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves with an object containing the config.\n */\n public getMediaConfig(callback?: Callback): Promise<any> { // TODO: Types\n return this.http.authedRequest(\n callback, \"GET\", \"/config\", undefined, undefined, {\n prefix: PREFIX_MEDIA_R0,\n },\n );\n }\n\n /**\n * Get the room for the given room ID.\n * This function will return a valid room for any room for which a Room event\n * has been emitted. Note in particular that other events, eg. RoomState.members\n * will be emitted for a room before this function will return the given room.\n * @param {string} roomId The room ID\n * @return {Room} The Room or null if it doesn't exist or there is no data store.\n */\n public getRoom(roomId: string): Room {\n return this.store.getRoom(roomId);\n }\n\n /**\n * Retrieve all known rooms.\n * @return {Room[]} A list of rooms, or an empty list if there is no data store.\n */\n public getRooms(): Room[] {\n return this.store.getRooms();\n }\n\n /**\n * Retrieve all rooms that should be displayed to the user\n * This is essentially getRooms() with some rooms filtered out, eg. old versions\n * of rooms that have been replaced or (in future) other rooms that have been\n * marked at the protocol level as not to be displayed to the user.\n * @return {Room[]} A list of rooms, or an empty list if there is no data store.\n */\n public getVisibleRooms(): Room[] {\n const allRooms = this.store.getRooms();\n\n const replacedRooms = new Set();\n for (const r of allRooms) {\n const createEvent = r.currentState.getStateEvents('m.room.create', '');\n // invites are included in this list and we don't know their create events yet\n if (createEvent) {\n const predecessor = createEvent.getContent()['predecessor'];\n if (predecessor && predecessor['room_id']) {\n replacedRooms.add(predecessor['room_id']);\n }\n }\n }\n\n return allRooms.filter((r) => {\n const tombstone = r.currentState.getStateEvents('m.room.tombstone', '');\n if (tombstone && replacedRooms.has(r.roomId)) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Retrieve a user.\n * @param {string} userId The user ID to retrieve.\n * @return {?User} A user or null if there is no data store or the user does\n * not exist.\n */\n public getUser(userId: string): User {\n return this.store.getUser(userId);\n }\n\n /**\n * Retrieve all known users.\n * @return {User[]} A list of users, or an empty list if there is no data store.\n */\n public getUsers(): User[] {\n return this.store.getUsers();\n }\n\n /**\n * Set account data event for the current user.\n * It will retry the request up to 5 times.\n * @param {string} eventType The event type\n * @param {Object} content the contents object for the event\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setAccountData(eventType: EventType | string, content: any, callback?: Callback): Promise<void> {\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId,\n $type: eventType,\n });\n const promise = retryNetworkOperation(5, () => {\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, content);\n });\n if (callback) {\n promise.then(result => callback(null, result), callback);\n }\n return promise;\n }\n\n /**\n * Get account data event of given type for the current user.\n * @param {string} eventType The event type\n * @return {?object} The contents of the given account data event\n */\n public getAccountData(eventType: string): MatrixEvent {\n return this.store.getAccountData(eventType);\n }\n\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n * @param {string} eventType The event type\n * @return {Promise} Resolves: The contents of the given account\n * data event.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async getAccountDataFromServer(eventType: string): Promise<any> {\n if (this.isInitialSyncComplete()) {\n const event = this.store.getAccountData(eventType);\n if (!event) {\n return null;\n }\n // The network version below returns just the content, so this branch\n // does the same to match.\n return event.getContent();\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId,\n $type: eventType,\n });\n try {\n return await this.http.authedRequest(\n undefined, \"GET\", path, undefined,\n );\n } catch (e) {\n if (e.data && e.data.errcode === 'M_NOT_FOUND') {\n return null;\n }\n throw e;\n }\n }\n\n /**\n * Gets the users that are ignored by this client\n * @returns {string[]} The array of users that are ignored (empty if none)\n */\n public getIgnoredUsers(): string[] {\n const event = this.getAccountData(\"m.ignored_user_list\");\n if (!event || !event.getContent() || !event.getContent()[\"ignored_users\"]) return [];\n return Object.keys(event.getContent()[\"ignored_users\"]);\n }\n\n /**\n * Sets the users that the current user should ignore.\n * @param {string[]} userIds the user IDs to ignore\n * @param {module:client.callback} [callback] Optional.\n * @return {Promise} Resolves: Account data event\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setIgnoredUsers(userIds: string[], callback?: Callback): Promise<any> {\n const content = { ignored_users: {} };\n userIds.map((u) => content.ignored_users[u] = {});\n return this.setAccountData(\"m.ignored_user_list\", content, callback);\n }\n\n /**\n * Gets whether or not a specific user is being ignored by this client.\n * @param {string} userId the user ID to check\n * @returns {boolean} true if the user is ignored, false otherwise\n */\n public isUserIgnored(userId: string): boolean {\n return this.getIgnoredUsers().includes(userId);\n }\n\n /**\n * Join a room. If you have already joined the room, this will no-op.\n * @param {string} roomIdOrAlias The room ID or room alias to join.\n * @param {Object} opts Options when joining the room.\n * @param {boolean} opts.syncRoom True to do a room initial sync on the resulting\n * room. If false, the <strong>returned Room object will have no current state.\n * </strong> Default: true.\n * @param {boolean} opts.inviteSignUrl If the caller has a keypair 3pid invite, the signing URL is passed in this parameter.\n * @param {string[]} opts.viaServers The server names to try and join through in addition to those that are automatically chosen.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Room object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async joinRoom(roomIdOrAlias: string, opts?: IJoinRoomOpts, callback?: Callback): Promise<Room> {\n // to help people when upgrading..\n if (utils.isFunction(opts)) {\n throw new Error(\"Expected 'opts' object, got function.\");\n }\n opts = opts || {};\n if (opts.syncRoom === undefined) {\n opts.syncRoom = true;\n }\n\n const room = this.getRoom(roomIdOrAlias);\n if (room && room.hasMembershipState(this.credentials.userId, \"join\")) {\n return Promise.resolve(room);\n }\n\n let signPromise = Promise.resolve();\n\n if (opts.inviteSignUrl) {\n signPromise = this.http.requestOtherUrl(\n undefined, 'POST',\n opts.inviteSignUrl, { mxid: this.credentials.userId },\n );\n }\n\n const queryString = {};\n if (opts.viaServers) {\n queryString[\"server_name\"] = opts.viaServers;\n }\n\n const reqOpts = { qsStringifyOptions: { arrayFormat: 'repeat' } };\n\n try {\n const data: any = {};\n // XXX: Explicit cast due to underlying types not existing\n const signedInviteObj = <Promise<any>><any>(await signPromise);\n if (signedInviteObj) {\n data['third_party_signed'] = signedInviteObj;\n }\n\n const path = utils.encodeUri(\"/join/$roomid\", { $roomid: roomIdOrAlias });\n const res = await this.http.authedRequest(undefined, \"POST\", path, queryString, data, reqOpts);\n\n const roomId = res['room_id'];\n const syncApi = new SyncApi(this, this.clientOpts);\n const room = syncApi.createRoom(roomId);\n if (opts.syncRoom) {\n // v2 will do this for us\n // return syncApi.syncRoom(room);\n }\n callback?.(null, room);\n return room;\n } catch (e) {\n callback?.(e);\n throw e; // rethrow for reject\n }\n }\n\n /**\n * Resend an event.\n * @param {MatrixEvent} event The event to resend.\n * @param {Room} room Optional. The room the event is in. Will update the\n * timeline entry if provided.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public resendEvent(event: MatrixEvent, room: Room): Promise<any> { // TODO: Types\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n return this.encryptAndSendEvent(room, event);\n }\n\n /**\n * Cancel a queued or unsent event.\n *\n * @param {MatrixEvent} event Event to cancel\n * @throws Error if the event is not in QUEUED or NOT_SENT state\n */\n public cancelPendingEvent(event: MatrixEvent) {\n if ([EventStatus.QUEUED, EventStatus.NOT_SENT].indexOf(event.status) < 0) {\n throw new Error(\"cannot cancel an event with status \" + event.status);\n }\n\n // first tell the scheduler to forget about it, if it's queued\n if (this.scheduler) {\n this.scheduler.removeEventFromQueue(event);\n }\n\n // then tell the room about the change of state, which will remove it\n // from the room's list of pending events.\n const room = this.getRoom(event.getRoomId());\n this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n }\n\n /**\n * @param {string} roomId\n * @param {string} name\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomName(roomId: string, name: string, callback?: Callback): Promise<void> {\n return this.sendStateEvent(roomId, \"m.room.name\", { name: name }, undefined, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} topic\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomTopic(roomId: string, topic: string, callback?: Callback): Promise<void> {\n return this.sendStateEvent(roomId, \"m.room.topic\", { topic: topic }, undefined, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getRoomTags(roomId: string, callback?: Callback): Promise<unknown> { // TODO: Types\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/\", {\n $userId: this.credentials.userId,\n $roomId: roomId,\n });\n return this.http.authedRequest(\n callback, \"GET\", path, undefined,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {string} tagName name of room tag to be set\n * @param {object} metadata associated with that tag to be stored\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomTag(roomId: string, tagName: string, metadata: any, callback?: Callback): Promise<unknown> { // TODO: Types\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, metadata,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {string} tagName name of room tag to be removed\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public deleteRoomTag(roomId: string, tagName: string, callback?: Callback): Promise<void> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(\n callback, \"DELETE\", path, undefined, undefined,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {string} eventType event type to be set\n * @param {object} content event content\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomAccountData(roomId: string, eventType: string, content: any, callback?: Callback): Promise<void> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n $userId: this.credentials.userId,\n $roomId: roomId,\n $type: eventType,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, content,\n );\n }\n\n /**\n * Set a user's power level.\n * @param {string} roomId\n * @param {string} userId\n * @param {Number} powerLevel\n * @param {MatrixEvent} event\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setPowerLevel(\n roomId: string,\n userId: string,\n powerLevel: number,\n event: MatrixEvent,\n callback?: Callback,\n ): Promise<void> {\n let content = {\n users: {},\n };\n if (event && event.getType() === \"m.room.power_levels\") {\n // take a copy of the content to ensure we don't corrupt\n // existing client state with a failed power level change\n content = utils.deepCopy(event.getContent()) as typeof content;\n }\n content.users[userId] = powerLevel;\n const path = utils.encodeUri(\"/rooms/$roomId/state/m.room.power_levels\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, content,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {string} eventType\n * @param {Object} content\n * @param {string} txnId Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendEvent(\n roomId: string,\n eventType: string,\n content: any,\n txnId?: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n return this.sendCompleteEvent(roomId, { type: eventType, content }, txnId, callback);\n }\n\n /**\n * @param {string} roomId\n * @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.\n * @param {string} txnId the txnId.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n eventObject: any,\n txnId: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n if (utils.isFunction(txnId)) {\n callback = txnId as any as Callback; // convert for legacy\n txnId = undefined;\n }\n\n if (!txnId) {\n txnId = this.makeTxnId();\n }\n\n // we always construct a MatrixEvent when sending because the store and\n // scheduler use them. We'll extract the params back out if it turns out\n // the client has no scheduler or store.\n const localEvent = new MatrixEvent(Object.assign(eventObject, {\n event_id: \"~\" + roomId + \":\" + txnId,\n user_id: this.credentials.userId,\n sender: this.credentials.userId,\n room_id: roomId,\n origin_server_ts: new Date().getTime(),\n }));\n\n const room = this.getRoom(roomId);\n\n // if this is a relation or redaction of an event\n // that hasn't been sent yet (e.g. with a local id starting with a ~)\n // then listen for the remote echo of that event so that by the time\n // this event does get sent, we have the correct event_id\n const targetId = localEvent.getAssociatedId();\n if (targetId && targetId.startsWith(\"~\")) {\n const target = room.getPendingEvents().find(e => e.getId() === targetId);\n target.once(\"Event.localEventIdReplaced\", () => {\n localEvent.updateAssociatedId(target.getId());\n });\n }\n\n const type = localEvent.getType();\n logger.log(`sendEvent of type ${type} in ${roomId} with txnId ${txnId}`);\n\n localEvent.setTxnId(txnId);\n localEvent.setStatus(EventStatus.SENDING);\n\n // add this event immediately to the local store as 'sending'.\n if (room) {\n room.addPendingEvent(localEvent, txnId);\n }\n\n // addPendingEvent can change the state to NOT_SENT if it believes\n // that there's other events that have failed. We won't bother to\n // try sending the event if the state has changed as such.\n if (localEvent.status === EventStatus.NOT_SENT) {\n return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n }\n\n return this.encryptAndSendEvent(room, localEvent, callback);\n }\n\n /**\n * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n * @param room\n * @param event\n * @param callback\n * @returns {Promise} returns a promise which resolves with the result of the send request\n * @private\n */\n private encryptAndSendEvent(room: Room, event: MatrixEvent, callback?: Callback): Promise<ISendEventResponse> {\n // Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections,\n // so that we can handle synchronous and asynchronous exceptions with the\n // same code path.\n return Promise.resolve().then(() => {\n const encryptionPromise = this.encryptEventIfNeeded(event, room);\n if (!encryptionPromise) return null;\n\n this.updatePendingEventStatus(room, event, EventStatus.ENCRYPTING);\n return encryptionPromise.then(() => this.updatePendingEventStatus(room, event, EventStatus.SENDING));\n }).then(() => {\n let promise: Promise<ISendEventResponse>;\n if (this.scheduler) {\n // if this returns a promise then the scheduler has control now and will\n // resolve/reject when it is done. Internally, the scheduler will invoke\n // processFn which is set to this._sendEventHttpRequest so the same code\n // path is executed regardless.\n promise = this.scheduler.queueEvent(event);\n if (promise && this.scheduler.getQueueForEvent(event).length > 1) {\n // event is processed FIFO so if the length is 2 or more we know\n // this event is stuck behind an earlier event.\n this.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n }\n }\n\n if (!promise) {\n promise = this.sendEventHttpRequest(event);\n if (room) {\n promise = promise.then(res => {\n room.updatePendingEvent(event, EventStatus.SENT, res['event_id']);\n return res;\n });\n }\n }\n\n return promise;\n }).then(res => {\n callback?.(null, res);\n return res;\n }).catch(err => {\n logger.error(\"Error sending event\", err.stack || err);\n try {\n // set the error on the event before we update the status:\n // updating the status emits the event, so the state should be\n // consistent at that point.\n event.error = err;\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n // also put the event object on the error: the caller will need this\n // to resend or cancel the event\n err.event = event;\n\n callback?.(err);\n } catch (e) {\n logger.error(\"Exception in error handler!\", e.stack || err);\n }\n throw err;\n });\n }\n\n private encryptEventIfNeeded(event: MatrixEvent, room?: Room): Promise<void> | null {\n if (event.isEncrypted()) {\n // this event has already been encrypted; this happens if the\n // encryption step succeeded, but the send step failed on the first\n // attempt.\n return null;\n }\n\n if (!this.isRoomEncrypted(event.getRoomId())) {\n return null;\n }\n\n if (!this.crypto && this.usingExternalCrypto) {\n // The client has opted to allow sending messages to encrypted\n // rooms even if the room is encrypted, and we haven't setup\n // crypto. This is useful for users of matrix-org/pantalaimon\n return null;\n }\n\n if (event.getType() === EventType.Reaction) {\n // For reactions, there is a very little gained by encrypting the entire\n // event, as relation data is already kept in the clear. Event\n // encryption for a reaction effectively only obscures the event type,\n // but the purpose is still obvious from the relation data, so nothing\n // is really gained. It also causes quite a few problems, such as:\n // * triggers notifications via default push rules\n // * prevents server-side bundling for reactions\n // The reaction key / content / emoji value does warrant encrypting, but\n // this will be handled separately by encrypting just this value.\n // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642\n return null;\n }\n\n if (!this.crypto) {\n throw new Error(\n \"This room is configured to use encryption, but your client does \" +\n \"not support encryption.\",\n );\n }\n\n return this.crypto.encryptEvent(event, room);\n }\n\n /**\n * Returns the eventType that should be used taking encryption into account\n * for a given eventType.\n * @param {MatrixClient} client the client\n * @param {string} roomId the room for the events `eventType` relates to\n * @param {string} eventType the event type\n * @return {string} the event type taking encryption into account\n */\n private getEncryptedIfNeededEventType(roomId: string, eventType: string): string {\n if (eventType === EventType.Reaction) return eventType;\n return this.isRoomEncrypted(roomId) ? EventType.RoomMessageEncrypted : eventType;\n }\n\n private updatePendingEventStatus(room: Room | null, event: MatrixEvent, newStatus: EventStatus) {\n if (room) {\n room.updatePendingEvent(event, newStatus);\n } else {\n event.setStatus(newStatus);\n }\n }\n\n private sendEventHttpRequest(event: MatrixEvent): Promise<ISendEventResponse> {\n let txnId = event.getTxnId();\n if (!txnId) {\n txnId = this.makeTxnId();\n event.setTxnId(txnId);\n }\n\n const pathParams = {\n $roomId: event.getRoomId(),\n $eventType: event.getWireType(),\n $stateKey: event.getStateKey(),\n $txnId: txnId,\n };\n\n let path;\n\n if (event.isState()) {\n let pathTemplate = \"/rooms/$roomId/state/$eventType\";\n if (event.getStateKey() && event.getStateKey().length > 0) {\n pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n }\n path = utils.encodeUri(pathTemplate, pathParams);\n } else if (event.isRedaction()) {\n const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;\n path = utils.encodeUri(pathTemplate, Object.assign({\n $redactsEventId: event.event.redacts,\n }, pathParams));\n } else {\n path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n }\n\n return this.http.authedRequest(\n undefined, \"PUT\", path, undefined, event.getWireContent(),\n ).then((res) => {\n logger.log(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);\n return res;\n });\n }\n\n /**\n * @param {string} roomId\n * @param {string} eventId\n * @param {string} [txnId] transaction id. One will be made up if not\n * supplied.\n * @param {object|module:client.callback} cbOrOpts\n * Options to pass on, may contain `reason`.\n * Can be callback for backwards compatibility.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public redactEvent(\n roomId: string,\n eventId: string,\n txnId?: string,\n cbOrOpts?: Callback | IRedactOpts,\n ): Promise<ISendEventResponse> {\n const opts = typeof (cbOrOpts) === 'object' ? cbOrOpts : {};\n const reason = opts.reason;\n const callback = typeof (cbOrOpts) === 'function' ? cbOrOpts : undefined;\n return this.sendCompleteEvent(roomId, {\n type: EventType.RoomRedaction,\n content: { reason: reason },\n redacts: eventId,\n }, txnId, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {Object} content\n * @param {string} txnId Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendMessage(roomId: string, content: any, txnId?: string, callback?: Callback): Promise<ISendEventResponse> {\n if (utils.isFunction(txnId)) {\n callback = txnId as any as Callback; // for legacy\n txnId = undefined;\n }\n return this.sendEvent(roomId, \"m.room.message\", content, txnId, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} body\n * @param {string} txnId Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendTextMessage(\n roomId: string,\n body: string,\n txnId?: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeTextMessage(body);\n return this.sendMessage(roomId, content, txnId, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} body\n * @param {string} txnId Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendNotice(roomId: string, body: string, txnId?: string, callback?: Callback): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeNotice(body);\n return this.sendMessage(roomId, content, txnId, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} body\n * @param {string} txnId Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendEmoteMessage(\n roomId: string,\n body: string,\n txnId?: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeEmoteMessage(body);\n return this.sendMessage(roomId, content, txnId, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} url\n * @param {Object} info\n * @param {string} text\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendImageMessage(\n roomId: string,\n url: string,\n info?: IImageInfo,\n text = \"Image\",\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n if (utils.isFunction(text)) {\n callback = text as any as Callback; // legacy\n text = undefined;\n }\n const content = {\n msgtype: \"m.image\",\n url: url,\n info: info,\n body: text,\n };\n return this.sendMessage(roomId, content, undefined, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} url\n * @param {Object} info\n * @param {string} text\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendStickerMessage(\n roomId: string,\n url: string,\n info?: IImageInfo,\n text = \"Sticker\",\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n if (utils.isFunction(text)) {\n callback = text as any as Callback; // legacy\n text = undefined;\n }\n const content = {\n url: url,\n info: info,\n body: text,\n };\n return this.sendEvent(roomId, EventType.Sticker, content, undefined, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} body\n * @param {string} htmlBody\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendHtmlMessage(\n roomId: string,\n body: string,\n htmlBody: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeHtmlMessage(body, htmlBody);\n return this.sendMessage(roomId, content, undefined, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} body\n * @param {string} htmlBody\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendHtmlNotice(\n roomId: string,\n body: string,\n htmlBody: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeHtmlNotice(body, htmlBody);\n return this.sendMessage(roomId, content, undefined, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {string} body\n * @param {string} htmlBody\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendHtmlEmote(\n roomId: string,\n body: string,\n htmlBody: string,\n callback?: Callback,\n ): Promise<ISendEventResponse> {\n const content = ContentHelpers.makeHtmlEmote(body, htmlBody);\n return this.sendMessage(roomId, content, undefined, callback);\n }\n\n /**\n * Send a receipt.\n * @param {Event} event The event being acknowledged\n * @param {string} receiptType The kind of receipt e.g. \"m.read\"\n * @param {object} opts Additional content to send alongside the receipt.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendReceipt(event: MatrixEvent, receiptType: string, body: any, callback?: Callback): Promise<any> {\n if (typeof (body) === 'function') {\n callback = body as any as Callback; // legacy\n body = {};\n }\n\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send receipts so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n $roomId: event.getRoomId(),\n $receiptType: receiptType,\n $eventId: event.getId(),\n });\n const promise = this.http.authedRequest(\n callback, \"POST\", path, undefined, body || {},\n );\n\n const room = this.getRoom(event.getRoomId());\n if (room) {\n room.addLocalEchoReceipt(this.credentials.userId, event, receiptType);\n }\n return promise;\n }\n\n /**\n * Send a read receipt.\n * @param {Event} event The event that has been read.\n * @param {object} opts The options for the read receipt.\n * @param {boolean} opts.hidden True to prevent the receipt from being sent to\n * other users and homeservers. Default false (send to everyone). <b>This\n * property is unstable and may change in the future.</b>\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async sendReadReceipt(event: MatrixEvent, opts: { hidden?: boolean }, callback?: Callback): Promise<any> {\n if (typeof (opts) === 'function') {\n callback = opts as any as Callback; // legacy\n opts = {};\n }\n if (!opts) opts = {};\n\n const eventId = event.getId();\n const room = this.getRoom(event.getRoomId());\n if (room && room.hasPendingEvent(eventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${eventId})`);\n }\n\n const addlContent = {\n \"m.hidden\": Boolean(opts.hidden),\n };\n\n return this.sendReceipt(event, \"m.read\", addlContent, callback);\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param {string} roomId ID of the room that has been read\n * @param {string} rmEventId ID of the event that has been read\n * @param {MatrixEvent} rrEvent the event tracked by the read receipt. This is here for\n * convenience because the RR and the RM are commonly updated at the same time as each\n * other. The local echo of this receipt will be done if set. Optional.\n * @param {object} opts Options for the read markers\n * @param {object} opts.hidden True to hide the receipt from other users and homeservers.\n * <b>This property is unstable and may change in the future.</b>\n * @return {Promise} Resolves: the empty object, {}.\n */\n public async setRoomReadMarkers(\n roomId: string,\n rmEventId: string,\n rrEvent: MatrixEvent,\n opts: { hidden?: boolean },\n ): Promise<any> { // TODO: Types\n const room = this.getRoom(roomId);\n if (room && room.hasPendingEvent(rmEventId)) {\n throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);\n }\n\n // Add the optional RR update, do local echo like `sendReceipt`\n let rrEventId;\n if (rrEvent) {\n rrEventId = rrEvent.getId();\n if (room && room.hasPendingEvent(rrEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);\n }\n if (room) {\n room.addLocalEchoReceipt(this.credentials.userId, rrEvent, \"m.read\");\n }\n }\n\n return this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, opts);\n }\n\n /**\n * Get a preview of the given URL as of (roughly) the given point in time,\n * described as an object with OpenGraph keys and associated values.\n * Attributes may be synthesized where actual OG metadata is lacking.\n * Caches results to prevent hammering the server.\n * @param {string} url The URL to get preview data for\n * @param {Number} ts The preferred point in time that the preview should\n * describe (ms since epoch). The preview returned will either be the most\n * recent one preceding this timestamp if available, or failing that the next\n * most recent available preview.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Object of OG metadata.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n * May return synthesized attributes if the URL lacked OG meta.\n */\n public getUrlPreview(url: string, ts: number, callback?: Callback): Promise<IPreviewUrlResponse> {\n // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n // Surely 60-second accuracy is enough for anyone.\n ts = Math.floor(ts / 60000) * 60000;\n\n const parsed = new URL(url);\n parsed.hash = \"\"; // strip the hash as it won't affect the preview\n url = parsed.toString();\n\n const key = ts + \"_\" + url;\n\n // If there's already a request in flight (or we've handled it), return that instead.\n const cachedPreview = this.urlPreviewCache[key];\n if (cachedPreview) {\n if (callback) {\n cachedPreview.then(callback).catch(callback);\n }\n return cachedPreview;\n }\n\n const resp = this.http.authedRequest(\n callback, \"GET\", \"/preview_url\", {\n url: url,\n ts: ts,\n }, undefined, {\n prefix: PREFIX_MEDIA_R0,\n },\n );\n // TODO: Expire the URL preview cache sometimes\n this.urlPreviewCache[key] = resp;\n return resp;\n }\n\n /**\n * @param {string} roomId\n * @param {boolean} isTyping\n * @param {Number} timeoutMs\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendTyping(roomId: string, isTyping: boolean, timeoutMs: number, callback?: Callback): Promise<any> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n $roomId: roomId,\n $userId: this.credentials.userId,\n });\n const data: any = {\n typing: isTyping,\n };\n if (isTyping) {\n data.timeout = timeoutMs ? timeoutMs : 20000;\n }\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, data,\n );\n }\n\n /**\n * Determines the history of room upgrades for a given room, as far as the\n * client can see. Returns an array of Rooms where the first entry is the\n * oldest and the last entry is the newest (likely current) room. If the\n * provided room is not found, this returns an empty list. This works in\n * both directions, looking for older and newer rooms of the given room.\n * @param {string} roomId The room ID to search from\n * @param {boolean} verifyLinks If true, the function will only return rooms\n * which can be proven to be linked. For example, rooms which have a create\n * event pointing to an old room which the client is not aware of or doesn't\n * have a matching tombstone would not be returned.\n * @return {Room[]} An array of rooms representing the upgrade\n * history.\n */\n public getRoomUpgradeHistory(roomId: string, verifyLinks = false): Room[] {\n let currentRoom = this.getRoom(roomId);\n if (!currentRoom) return [];\n\n const upgradeHistory = [currentRoom];\n\n // Work backwards first, looking at create events.\n let createEvent = currentRoom.currentState.getStateEvents(\"m.room.create\", \"\");\n while (createEvent) {\n logger.log(`Looking at ${createEvent.getId()}`);\n const predecessor = createEvent.getContent()['predecessor'];\n if (predecessor && predecessor['room_id']) {\n logger.log(`Looking at predecessor ${predecessor['room_id']}`);\n const refRoom = this.getRoom(predecessor['room_id']);\n if (!refRoom) break; // end of the chain\n\n if (verifyLinks) {\n const tombstone = refRoom.currentState\n .getStateEvents(\"m.room.tombstone\", \"\");\n\n if (!tombstone\n || tombstone.getContent()['replacement_room'] !== refRoom.roomId) {\n break;\n }\n }\n\n // Insert at the front because we're working backwards from the currentRoom\n upgradeHistory.splice(0, 0, refRoom);\n createEvent = refRoom.currentState.getStateEvents(\"m.room.create\", \"\");\n } else {\n // No further create events to look at\n break;\n }\n }\n\n // Work forwards next, looking at tombstone events\n let tombstoneEvent = currentRoom.currentState.getStateEvents(\"m.room.tombstone\", \"\");\n while (tombstoneEvent) {\n const refRoom = this.getRoom(tombstoneEvent.getContent()['replacement_room']);\n if (!refRoom) break; // end of the chain\n if (refRoom.roomId === currentRoom.roomId) break; // Tombstone is referencing it's own room\n\n if (verifyLinks) {\n createEvent = refRoom.currentState.getStateEvents(\"m.room.create\", \"\");\n if (!createEvent || !createEvent.getContent()['predecessor']) break;\n\n const predecessor = createEvent.getContent()['predecessor'];\n if (predecessor['room_id'] !== currentRoom.roomId) break;\n }\n\n // Push to the end because we're looking forwards\n upgradeHistory.push(refRoom);\n const roomIds = new Set(upgradeHistory.map((ref) => ref.roomId));\n if (roomIds.size < upgradeHistory.length) {\n // The last room added to the list introduced a previous roomId\n // To avoid recursion, return the last rooms - 1\n return upgradeHistory.slice(0, upgradeHistory.length - 1);\n }\n\n // Set the current room to the reference room so we know where we're at\n currentRoom = refRoom;\n tombstoneEvent = currentRoom.currentState.getStateEvents(\"m.room.tombstone\", \"\");\n }\n\n return upgradeHistory;\n }\n\n /**\n * @param {string} roomId\n * @param {string} userId\n * @param {module:client.callback} callback Optional.\n * @param {string} reason Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public invite(roomId: string, userId: string, callback?: Callback, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, \"invite\", reason, callback);\n }\n\n /**\n * Invite a user to a room based on their email address.\n * @param {string} roomId The room to invite the user to.\n * @param {string} email The email address to invite.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public inviteByEmail(roomId: string, email: string, callback?: Callback): Promise<{}> {\n return this.inviteByThreePid(roomId, \"email\", email, callback);\n }\n\n /**\n * Invite a user to a room based on a third-party identifier.\n * @param {string} roomId The room to invite the user to.\n * @param {string} medium The medium to invite the user e.g. \"email\".\n * @param {string} address The address for the specified medium.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async inviteByThreePid(roomId: string, medium: string, address: string, callback?: Callback): Promise<{}> {\n const path = utils.encodeUri(\n \"/rooms/$roomId/invite\",\n { $roomId: roomId },\n );\n\n const identityServerUrl = this.getIdentityServerUrl(true);\n if (!identityServerUrl) {\n return Promise.reject(new MatrixError({\n error: \"No supplied identity server URL\",\n errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\",\n }));\n }\n const params = {\n id_server: identityServerUrl,\n medium: medium,\n address: address,\n };\n\n if (\n this.identityServer &&\n this.identityServer.getAccessToken &&\n await this.doesServerAcceptIdentityAccessToken()\n ) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n params['id_access_token'] = identityAccessToken;\n }\n }\n\n return this.http.authedRequest(callback, \"POST\", path, undefined, params);\n }\n\n /**\n * @param {string} roomId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public leave(roomId: string, callback?: Callback): Promise<{}> {\n return this.membershipChange(roomId, undefined, \"leave\", undefined, callback);\n }\n\n /**\n * Leaves all rooms in the chain of room upgrades based on the given room. By\n * default, this will leave all the previous and upgraded rooms, including the\n * given room. To only leave the given room and any previous rooms, keeping the\n * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n * @param {string} roomId The room ID to start leaving at\n * @param {boolean} includeFuture If true, the whole chain (past and future) of\n * upgraded rooms will be left.\n * @return {Promise} Resolves when completed with an object keyed\n * by room ID and value of the error encountered when leaving or null.\n */\n public leaveRoomChain(\n roomId: string,\n includeFuture = true,\n ): Promise<{ [roomId: string]: Error | MatrixError | null }> {\n const upgradeHistory = this.getRoomUpgradeHistory(roomId);\n\n let eligibleToLeave = upgradeHistory;\n if (!includeFuture) {\n eligibleToLeave = [];\n for (const room of upgradeHistory) {\n eligibleToLeave.push(room);\n if (room.roomId === roomId) {\n break;\n }\n }\n }\n\n const populationResults = {}; // {roomId: Error}\n const promises = [];\n\n const doLeave = (roomId) => {\n return this.leave(roomId).then(() => {\n populationResults[roomId] = null;\n }).catch((err) => {\n populationResults[roomId] = err;\n return null; // suppress error\n });\n };\n\n for (const room of eligibleToLeave) {\n promises.push(doLeave(room.roomId));\n }\n\n return Promise.all(promises).then(() => populationResults);\n }\n\n /**\n * @param {string} roomId\n * @param {string} userId\n * @param {string} reason Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public ban(roomId: string, userId: string, reason?: string, callback?: Callback) {\n return this.membershipChange(roomId, userId, \"ban\", reason, callback);\n }\n\n /**\n * @param {string} roomId\n * @param {boolean} deleteRoom True to delete the room from the store on success.\n * Default: true.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public forget(roomId: string, deleteRoom?: boolean, callback?: Callback): Promise<{}> {\n if (deleteRoom === undefined) {\n deleteRoom = true;\n }\n const promise = this.membershipChange(roomId, undefined, \"forget\", undefined,\n callback);\n if (!deleteRoom) {\n return promise;\n }\n return promise.then((response) => {\n this.store.removeRoom(roomId);\n this.emit(\"deleteRoom\", roomId);\n return response;\n });\n }\n\n /**\n * @param {string} roomId\n * @param {string} userId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Object (currently empty)\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public unban(roomId: string, userId: string, callback?: Callback): Promise<void> {\n // unbanning != set their state to leave: this used to be\n // the case, but was then changed so that leaving was always\n // a revoking of privilege, otherwise two people racing to\n // kick / ban someone could end up banning and then un-banning\n // them.\n const path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n };\n return this.http.authedRequest(\n callback, \"POST\", path, undefined, data,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {string} userId\n * @param {string} reason Optional.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public kick(roomId: string, userId: string, reason?: string, callback?: Callback): Promise<{}> {\n return this.setMembershipState(roomId, userId, \"leave\", reason, callback);\n }\n\n /**\n * This is an internal method.\n * @param {MatrixClient} client\n * @param {string} roomId\n * @param {string} userId\n * @param {string} membershipValue\n * @param {string} reason\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n private setMembershipState(\n roomId: string,\n userId: string,\n membershipValue: string,\n reason?: string,\n callback?: Callback,\n ) {\n if (utils.isFunction(reason)) {\n callback = reason as any as Callback; // legacy\n reason = undefined;\n }\n\n const path = utils.encodeUri(\n \"/rooms/$roomId/state/m.room.member/$userId\",\n { $roomId: roomId, $userId: userId },\n );\n\n return this.http.authedRequest(callback, \"PUT\", path, undefined, {\n membership: membershipValue,\n reason: reason,\n });\n }\n\n private membershipChange(\n roomId: string,\n userId: string,\n membership: string,\n reason?: string,\n callback?: Callback,\n ): Promise<{}> {\n if (utils.isFunction(reason)) {\n callback = reason as any as Callback; // legacy\n reason = undefined;\n }\n\n const path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n $room_id: roomId,\n $membership: membership,\n });\n return this.http.authedRequest(\n callback, \"POST\", path, undefined, {\n user_id: userId, // may be undefined e.g. on leave\n reason: reason,\n },\n );\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param {MatrixEvent} event The event to get push actions for.\n * @return {module:pushprocessor~PushAction} A dict of actions to perform.\n */\n public getPushActionsForEvent(event: MatrixEvent): PushAction {\n if (!event.getPushActions()) {\n event.setPushActions(this.pushProcessor.actionsForEvent(event));\n }\n return event.getPushActions();\n }\n\n /**\n * @param {string} info The kind of info to set (e.g. 'avatar_url')\n * @param {Object} data The JSON object to set.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setProfileInfo(info: string, data: any, callback?: Callback): Promise<void> {\n const path = utils.encodeUri(\"/profile/$userId/$info\", {\n $userId: this.credentials.userId,\n $info: info,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, data,\n );\n }\n\n /**\n * @param {string} name\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async setDisplayName(name: string, callback?: Callback): Promise<any> {\n const prom = await this.setProfileInfo(\n \"displayname\", { displayname: name }, callback,\n );\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId());\n if (user) {\n user.displayName = name;\n user.emit(\"User.displayName\", user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * @param {string} url\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: {} an empty object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async setAvatarUrl(url: string, callback?: Callback): Promise<any> {\n const prom = await this.setProfileInfo(\n \"avatar_url\", { avatar_url: url }, callback,\n );\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId());\n if (user) {\n user.avatarUrl = url;\n user.emit(\"User.avatarUrl\", user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * Turn an MXC URL into an HTTP one. <strong>This method is experimental and\n * may change.</strong>\n * @param {string} mxcUrl The MXC URL\n * @param {Number} width The desired width of the thumbnail.\n * @param {Number} height The desired height of the thumbnail.\n * @param {string} resizeMethod The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return null for such URLs.\n * @return {?string} the avatar URL or null.\n */\n public mxcUrlToHttp(\n mxcUrl: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks?: boolean,\n ): string | null {\n return getHttpUriForMxc(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks);\n }\n\n /**\n * Sets a new status message for the user. The message may be null/falsey\n * to clear the message.\n * @param {string} newMessage The new message to set.\n * @return {Promise} Resolves: to nothing\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public _unstable_setStatusMessage(newMessage: string): Promise<void> { // eslint-disable-line camelcase\n const type = \"im.vector.user_status\";\n return Promise.all(this.getRooms().map((room) => {\n const isJoined = room.getMyMembership() === \"join\";\n const looksLikeDm = room.getInvitedAndJoinedMemberCount() === 2;\n if (!isJoined || !looksLikeDm) {\n return Promise.resolve();\n }\n // Check power level separately as it's a bit more expensive.\n const maySend = room.currentState.mayClientSendStateEvent(type, this);\n if (!maySend) {\n return Promise.resolve();\n }\n return this.sendStateEvent(room.roomId, type, {\n status: newMessage,\n }, this.getUserId());\n })).then(); // .then to fix return type\n }\n\n /**\n * @param {Object} opts Options to apply\n * @param {string} opts.presence One of \"online\", \"offline\" or \"unavailable\"\n * @param {string} opts.status_msg The status message to attach.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n * @throws If 'presence' isn't a valid presence enum value.\n */\n public setPresence(opts: IPresenceOpts, callback?: Callback): Promise<void> {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: this.credentials.userId,\n });\n\n if (typeof opts === \"string\") {\n opts = { presence: opts }; // legacy\n }\n\n const validStates = [\"offline\", \"online\", \"unavailable\"];\n if (validStates.indexOf(opts.presence) === -1) {\n throw new Error(\"Bad presence value: \" + opts.presence);\n }\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, opts,\n );\n }\n\n /**\n * @param {string} userId The user to get presence for\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: The presence state for this user.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getPresence(userId: string, callback?: Callback): Promise<unknown> { // TODO: Types\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: userId,\n });\n\n return this.http.authedRequest(callback, \"GET\", path, undefined, undefined);\n }\n\n /**\n * Retrieve older messages from the given room and put them in the timeline.\n *\n * If this is called multiple times whilst a request is ongoing, the <i>same</i>\n * Promise will be returned. If there was a problem requesting scrollback, there\n * will be a small delay before another request can be made (to prevent tight-looping\n * when there is no connection).\n *\n * @param {Room} room The room to get older messages in.\n * @param {Integer} limit Optional. The maximum number of previous events to\n * pull in. Default: 30.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Room. If you are at the beginning\n * of the timeline, <code>Room.oldState.paginationToken</code> will be\n * <code>null</code>.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public scrollback(room: Room, limit: number, callback?: Callback): Promise<Room> {\n if (utils.isFunction(limit)) {\n callback = limit as any as Callback; // legacy\n limit = undefined;\n }\n limit = limit || 30;\n let timeToWaitMs = 0;\n\n let info = this.ongoingScrollbacks[room.roomId] || {};\n if (info.promise) {\n return info.promise;\n } else if (info.errorTs) {\n const timeWaitedMs = Date.now() - info.errorTs;\n timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n }\n\n if (room.oldState.paginationToken === null) {\n return Promise.resolve(room); // already at the start.\n }\n // attempt to grab more events from the store first\n const numAdded = this.store.scrollback(room, limit).length;\n if (numAdded === limit) {\n // store contained everything we needed.\n return Promise.resolve(room);\n }\n // reduce the required number of events appropriately\n limit = limit - numAdded;\n\n const prom = new Promise<Room>((resolve, reject) => {\n // wait for a time before doing this request\n // (which may be 0 in order not to special case the code paths)\n sleep(timeToWaitMs).then(() => {\n return this.createMessagesRequest(\n room.roomId,\n room.oldState.paginationToken,\n limit,\n 'b');\n }).then((res: any) => { // TODO: Types\n const matrixEvents = res.chunk.map(this.getEventMapper());\n if (res.state) {\n const stateEvents = res.state.map(this.getEventMapper());\n room.currentState.setUnknownStateEvents(stateEvents);\n }\n room.addEventsToTimeline(matrixEvents, true, room.getLiveTimeline());\n room.oldState.paginationToken = res.end;\n if (res.chunk.length === 0) {\n room.oldState.paginationToken = null;\n }\n this.store.storeEvents(room, matrixEvents, res.end, true);\n this.ongoingScrollbacks[room.roomId] = null;\n callback?.(null, room);\n resolve(room);\n }).catch((err) => {\n this.ongoingScrollbacks[room.roomId] = {\n errorTs: Date.now(),\n };\n callback?.(err);\n reject(err);\n });\n });\n\n info = {\n promise: prom,\n errorTs: null,\n };\n\n this.ongoingScrollbacks[room.roomId] = info;\n return prom;\n }\n\n /**\n * @param {object} [options]\n * @param {boolean} options.preventReEmit don't reemit events emitted on an event mapped by this mapper on the client\n * @param {boolean} options.decrypt decrypt event proactively\n * @return {Function}\n */\n public getEventMapper(options?: MapperOpts): EventMapper {\n return eventMapperFor(this, options || {});\n }\n\n /**\n * Get an EventTimeline for the given event\n *\n * <p>If the EventTimelineSet object already has the given event in its store, the\n * corresponding timeline will be returned. Otherwise, a /context request is\n * made, and used to construct an EventTimeline.\n *\n * @param {EventTimelineSet} timelineSet The timelineSet to look for the event in\n * @param {string} eventId The ID of the event to look for\n *\n * @return {Promise} Resolves:\n * {@link module:models/event-timeline~EventTimeline} including the given\n * event\n */\n public getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise<EventTimeline> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable\" +\n \" it.\");\n }\n\n if (timelineSet.getTimelineForEvent(eventId)) {\n return Promise.resolve(timelineSet.getTimelineForEvent(eventId));\n }\n\n const path = utils.encodeUri(\n \"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n },\n );\n\n let params = undefined;\n if (this.clientOpts.lazyLoadMembers) {\n params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n const promise = this.http.authedRequest(undefined, \"GET\", path, params).then((res) => {\n if (!res.event) {\n throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n }\n\n // by the time the request completes, the event might have ended up in\n // the timeline.\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n // we start with the last event, since that's the point at which we\n // have known state.\n // events_after is already backwards; events_before is forwards.\n res.events_after.reverse();\n const events = res.events_after\n .concat([res.event])\n .concat(res.events_before);\n const matrixEvents = events.map(this.getEventMapper());\n\n let timeline = timelineSet.getTimelineForEvent(matrixEvents[0].getId());\n if (!timeline) {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(this.getEventMapper()));\n timeline.getState(EventTimeline.FORWARDS).paginationToken = res.end;\n } else {\n const stateEvents = res.state.map(this.getEventMapper());\n timeline.getState(EventTimeline.BACKWARDS).setUnknownStateEvents(stateEvents);\n }\n timelineSet.addEventsToTimeline(matrixEvents, true, timeline, res.start);\n\n // there is no guarantee that the event ended up in \"timeline\" (we\n // might have switched to a neighbouring timeline) - so check the\n // room's index again. On the other hand, there's no guarantee the\n // event ended up anywhere, if it was later redacted, so we just\n // return the timeline we first thought of.\n return timelineSet.getTimelineForEvent(eventId) || timeline;\n });\n return promise;\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param {string} roomId\n * @param {string} fromToken\n * @param {number} limit the maximum amount of events the retrieve\n * @param {string} dir 'f' or 'b'\n * @param {Filter} timelineFilter the timeline filter to pass\n * @return {Promise}\n */\n // XXX: Intended private, used in code.\n public createMessagesRequest(\n roomId: string,\n fromToken: string,\n limit: number,\n dir: string,\n timelineFilter?: Filter,\n ): Promise<unknown> { // TODO: Types\n const path = utils.encodeUri(\n \"/rooms/$roomId/messages\", { $roomId: roomId },\n );\n if (limit === undefined) {\n limit = 30;\n }\n const params: any = {\n from: fromToken,\n limit: limit,\n dir: dir,\n };\n\n let filter = null;\n if (this.clientOpts.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = filter || {};\n Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()?.toJSON());\n }\n if (filter) {\n params.filter = JSON.stringify(filter);\n }\n return this.http.authedRequest(undefined, \"GET\", path, params);\n }\n\n /**\n * Take an EventTimeline, and back/forward-fill results.\n *\n * @param {module:models/event-timeline~EventTimeline} eventTimeline timeline\n * object to be updated\n * @param {Object} [opts]\n * @param {boolean} [opts.backwards = false] true to fill backwards,\n * false to go forwards\n * @param {number} [opts.limit = 30] number of events to request\n *\n * @return {Promise} Resolves to a boolean: false if there are no\n * events and we reached either end of the timeline; else true.\n */\n public paginateEventTimeline(eventTimeline: EventTimeline, opts: IPaginateOpts): Promise<boolean> {\n const isNotifTimeline = (eventTimeline.getTimelineSet() === this.notifTimelineSet);\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n opts = opts || {};\n const backwards = opts.backwards || false;\n\n if (isNotifTimeline) {\n if (!backwards) {\n throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n }\n }\n\n const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n\n const token = eventTimeline.getPaginationToken(dir);\n if (!token) {\n // no token - no results.\n return Promise.resolve(false);\n }\n\n const pendingRequest = eventTimeline.paginationRequests[dir];\n\n if (pendingRequest) {\n // already a request in progress - return the existing promise\n return pendingRequest;\n }\n\n let path;\n let params;\n let promise;\n\n if (isNotifTimeline) {\n path = \"/notifications\";\n params = {\n limit: ('limit' in opts) ? opts.limit : 30,\n only: 'highlight',\n };\n\n if (token && token !== \"end\") {\n params.from = token;\n }\n\n promise = this.http.authedRequest(\n undefined, \"GET\", path, params, undefined,\n ).then((res) => {\n const token = res.next_token;\n const matrixEvents = [];\n\n for (let i = 0; i < res.notifications.length; i++) {\n const notification = res.notifications[i];\n const event = this.getEventMapper()(notification.event);\n event.setPushActions(\n PushProcessor.actionListToActionsObject(notification.actions),\n );\n event.event.room_id = notification.room_id; // XXX: gutwrenching\n matrixEvents[i] = event;\n }\n\n eventTimeline.getTimelineSet()\n .addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !res.next_token) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.next_token ? true : false;\n }).finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else {\n const room = this.getRoom(eventTimeline.getRoomId());\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.createMessagesRequest(\n eventTimeline.getRoomId(),\n token,\n opts.limit,\n dir,\n eventTimeline.getFilter());\n promise.then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir);\n const stateEvents = res.state.map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.map(this.getEventMapper());\n eventTimeline.getTimelineSet()\n .addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && res.end == res.start) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.end != res.start;\n }).finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n }\n\n return promise;\n }\n\n /**\n * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n * a starting point for subsequent pagination.\n */\n public resetNotifTimelineSet() {\n if (!this.notifTimelineSet) {\n return;\n }\n\n // FIXME: This thing is a total hack, and results in duplicate events being\n // added to the timeline both from /sync and /notifications, and lots of\n // slow and wasteful processing and pagination. The correct solution is to\n // extend /messages or /search or something to filter on notifications.\n\n // use the fictitious token 'end'. in practice we would ideally give it\n // the oldest backwards pagination token from /sync, but /sync doesn't\n // know about /notifications, so we have no choice but to start paginating\n // from the current point in time. This may well overlap with historical\n // notifs which are then inserted into the timeline by /sync responses.\n this.notifTimelineSet.resetLiveTimeline('end', null);\n\n // we could try to paginate a single event at this point in order to get\n // a more valid pagination token, but it just ends up with an out of order\n // timeline. given what a mess this is and given we're going to have duplicate\n // events anyway, just leave it with the dummy token for now.\n /*\n this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n backwards: true,\n limit: 1\n });\n */\n }\n\n /**\n * Peek into a room and receive updates about the room. This only works if the\n * history visibility for the room is world_readable.\n * @param {String} roomId The room to attempt to peek into.\n * @return {Promise} Resolves: Room object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public peekInRoom(roomId: string): Promise<Room> {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n }\n this.peekSync = new SyncApi(this, this.clientOpts);\n return this.peekSync.peek(roomId);\n }\n\n /**\n * Stop any ongoing room peeking.\n */\n public stopPeeking() {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n this.peekSync = null;\n }\n }\n\n /**\n * Set r/w flags for guest access in a room.\n * @param {string} roomId The room to configure guest access in.\n * @param {Object} opts Options\n * @param {boolean} opts.allowJoin True to allow guests to join this room. This\n * implicitly gives guests write access. If false or not given, guests are\n * explicitly forbidden from joining the room.\n * @param {boolean} opts.allowRead True to set history visibility to\n * be world_readable. This gives guests read access *from this point forward*.\n * If false or not given, history visibility is not modified.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setGuestAccess(roomId: string, opts: IGuestAccessOpts): Promise<void> {\n const writePromise = this.sendStateEvent(roomId, \"m.room.guest_access\", {\n guest_access: opts.allowJoin ? \"can_join\" : \"forbidden\",\n }, \"\");\n\n let readPromise = Promise.resolve();\n if (opts.allowRead) {\n readPromise = this.sendStateEvent(roomId, \"m.room.history_visibility\", {\n history_visibility: \"world_readable\",\n }, \"\");\n }\n\n return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n }\n\n /**\n * Requests an email verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * Parameters and return value are as for requestEmailToken\n\n * @param {string} email As requestEmailToken\n * @param {string} clientSecret As requestEmailToken\n * @param {number} sendAttempt As requestEmailToken\n * @param {string} nextLink As requestEmailToken\n * @return {Promise} Resolves: As requestEmailToken\n */\n public requestRegisterEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<any> { // TODO: Types\n return this.requestTokenFromEndpoint(\n \"/register/email/requestToken\",\n {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n },\n );\n }\n\n /**\n * Requests a text message verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * @param {string} phoneCountry The ISO 3166-1 alpha-2 code for the country in which\n * phoneNumber should be parsed relative to.\n * @param {string} phoneNumber The phone number, in national or international format\n * @param {string} clientSecret As requestEmailToken\n * @param {number} sendAttempt As requestEmailToken\n * @param {string} nextLink As requestEmailToken\n * @return {Promise} Resolves: As requestEmailToken\n */\n public requestRegisterMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise<any> { // TODO: Types\n return this.requestTokenFromEndpoint(\n \"/register/msisdn/requestToken\",\n {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n },\n );\n }\n\n /**\n * Requests an email verification token for the purposes of adding a\n * third party identifier to an account.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n * If an account with the given email address already exists and is\n * associated with an account other than the one the user is authed as,\n * it will either send an email to the address informing them of this\n * or return M_THREEPID_IN_USE (which one is up to the Home Server).\n *\n * @param {string} email As requestEmailToken\n * @param {string} clientSecret As requestEmailToken\n * @param {number} sendAttempt As requestEmailToken\n * @param {string} nextLink As requestEmailToken\n * @return {Promise} Resolves: As requestEmailToken\n */\n public requestAdd3pidEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<any> { // TODO: Types\n return this.requestTokenFromEndpoint(\n \"/account/3pid/email/requestToken\",\n {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n },\n );\n }\n\n /**\n * Requests a text message verification token for the purposes of adding a\n * third party identifier to an account.\n * This API proxies the Identity Server /validate/email/requestToken API,\n * adding specific behaviour for the addition of phone numbers to an\n * account, as requestAdd3pidEmailToken.\n *\n * @param {string} phoneCountry As requestRegisterMsisdnToken\n * @param {string} phoneNumber As requestRegisterMsisdnToken\n * @param {string} clientSecret As requestEmailToken\n * @param {number} sendAttempt As requestEmailToken\n * @param {string} nextLink As requestEmailToken\n * @return {Promise} Resolves: As requestEmailToken\n */\n public requestAdd3pidMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<any> { // TODO: Types\n return this.requestTokenFromEndpoint(\n \"/account/3pid/msisdn/requestToken\",\n {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n },\n );\n }\n\n /**\n * Requests an email verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the Identity Server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting. Specifically,\n * if no account with the given email address exists, it may either\n * return M_THREEPID_NOT_FOUND or send an email\n * to the address informing them of this (which one is up to the Home Server).\n *\n * requestEmailToken calls the equivalent API directly on the ID server,\n * therefore bypassing the password reset specific logic.\n *\n * @param {string} email As requestEmailToken\n * @param {string} clientSecret As requestEmailToken\n * @param {number} sendAttempt As requestEmailToken\n * @param {string} nextLink As requestEmailToken\n * @param {module:client.callback} callback Optional. As requestEmailToken\n * @return {Promise} Resolves: As requestEmailToken\n */\n public requestPasswordEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<any> { // TODO: Types\n return this.requestTokenFromEndpoint(\n \"/account/password/email/requestToken\",\n {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n },\n );\n }\n\n /**\n * Requests a text message verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the Identity Server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n *\n * @param {string} phoneCountry As requestRegisterMsisdnToken\n * @param {string} phoneNumber As requestRegisterMsisdnToken\n * @param {string} clientSecret As requestEmailToken\n * @param {number} sendAttempt As requestEmailToken\n * @param {string} nextLink As requestEmailToken\n * @return {Promise} Resolves: As requestEmailToken\n */\n public requestPasswordMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise<any> { // TODO: Types\n return this.requestTokenFromEndpoint(\n \"/account/password/msisdn/requestToken\",\n {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n },\n );\n }\n\n /**\n * Internal utility function for requesting validation tokens from usage-specific\n * requestToken endpoints.\n *\n * @param {string} endpoint The endpoint to send the request to\n * @param {object} params Parameters for the POST request\n * @return {Promise} Resolves: As requestEmailToken\n */\n private async requestTokenFromEndpoint(endpoint: string, params: any): Promise<void> {\n const postParams = Object.assign({}, params);\n\n // If the HS supports separate add and bind, then requestToken endpoints\n // don't need an IS as they are all validated by the HS directly.\n if (!await this.doesServerSupportSeparateAddAndBind() && this.idBaseUrl) {\n const idServerUrl = url.parse(this.idBaseUrl);\n if (!idServerUrl.host) {\n throw new Error(\"Invalid ID server URL: \" + this.idBaseUrl);\n }\n postParams.id_server = idServerUrl.host;\n\n if (\n this.identityServer &&\n this.identityServer.getAccessToken &&\n await this.doesServerAcceptIdentityAccessToken()\n ) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n postParams.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.request(\n undefined, \"POST\", endpoint, undefined,\n postParams,\n );\n }\n\n /**\n * Get the room-kind push rule associated with a room.\n * @param {string} scope \"global\" or device-specific.\n * @param {string} roomId the id of the room.\n * @return {object} the rule or undefined.\n */\n public getRoomPushRule(scope: string, roomId: string): any { // TODO: Types\n // There can be only room-kind push rule per room\n // and its id is the room id.\n if (this.pushRules) {\n for (let i = 0; i < this.pushRules[scope].room.length; i++) {\n const rule = this.pushRules[scope].room[i];\n if (rule.rule_id === roomId) {\n return rule;\n }\n }\n } else {\n throw new Error(\n \"SyncApi.sync() must be done before accessing to push rules.\",\n );\n }\n }\n\n /**\n * Set a room-kind muting push rule in a room.\n * The operation also updates MatrixClient.pushRules at the end.\n * @param {string} scope \"global\" or device-specific.\n * @param {string} roomId the id of the room.\n * @param {string} mute the mute state.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomMutePushRule(scope: string, roomId: string, mute: string): any { // TODO: Types\n let deferred;\n let hasDontNotifyRule;\n\n // Get the existing room-kind push rule if any\n const roomPushRule = this.getRoomPushRule(scope, roomId);\n if (roomPushRule) {\n if (0 <= roomPushRule.actions.indexOf(\"dont_notify\")) {\n hasDontNotifyRule = true;\n }\n }\n\n if (!mute) {\n // Remove the rule only if it is a muting rule\n if (hasDontNotifyRule) {\n deferred = this.deletePushRule(scope, \"room\", roomPushRule.rule_id);\n }\n } else {\n if (!roomPushRule) {\n deferred = this.addPushRule(scope, \"room\", roomId, {\n actions: [\"dont_notify\"],\n });\n } else if (!hasDontNotifyRule) {\n // Remove the existing one before setting the mute push rule\n // This is a workaround to SYN-590 (Push rule update fails)\n deferred = utils.defer();\n this.deletePushRule(scope, \"room\", roomPushRule.rule_id)\n .then(() => {\n this.addPushRule(scope, \"room\", roomId, {\n actions: [\"dont_notify\"],\n }).then(() => {\n deferred.resolve();\n }).catch((err) => {\n deferred.reject(err);\n });\n }).catch((err) => {\n deferred.reject(err);\n });\n\n deferred = deferred.promise;\n }\n }\n\n if (deferred) {\n return new Promise<void>((resolve, reject) => {\n // Update this.pushRules when the operation completes\n deferred.then(() => {\n this.getPushRules().then((result) => {\n this.pushRules = result;\n resolve();\n }).catch((err) => {\n reject(err);\n });\n }).catch((err) => {\n // Update it even if the previous operation fails. This can help the\n // app to recover when push settings has been modifed from another client\n this.getPushRules().then((result) => {\n this.pushRules = result;\n reject(err);\n }).catch((err2) => {\n reject(err);\n });\n });\n });\n }\n }\n\n public searchMessageText(opts: ISearchOpts, callback?: Callback): Promise<any> { // TODO: Types\n const roomEvents: any = {\n search_term: opts.query,\n };\n\n if ('keys' in opts) {\n roomEvents.keys = opts.keys;\n }\n\n return this.search({\n body: {\n search_categories: {\n room_events: roomEvents,\n },\n },\n }, callback);\n }\n\n /**\n * Perform a server-side search for room events.\n *\n * The returned promise resolves to an object containing the fields:\n *\n * * {number} count: estimate of the number of results\n * * {string} next_batch: token for back-pagination; if undefined, there are\n * no more results\n * * {Array} highlights: a list of words to highlight from the stemming\n * algorithm\n * * {Array} results: a list of results\n *\n * Each entry in the results list is a {module:models/search-result.SearchResult}.\n *\n * @param {Object} opts\n * @param {string} opts.term the term to search for\n * @param {Object} opts.filter a JSON filter object to pass in the request\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public searchRoomEvents(opts: IEventSearchOpts): Promise<any> { // TODO: Types\n // TODO: support groups\n\n const body = {\n search_categories: {\n room_events: {\n search_term: opts.term,\n filter: opts.filter,\n order_by: \"recent\",\n event_context: {\n before_limit: 1,\n after_limit: 1,\n include_profile: true,\n },\n },\n },\n };\n\n const searchResults = {\n _query: body,\n results: [],\n highlights: [],\n };\n\n return this.search({ body: body }).then(res => this.processRoomEventsSearch(searchResults, res));\n }\n\n /**\n * Take a result from an earlier searchRoomEvents call, and backfill results.\n *\n * @param {object} searchResults the results object to be updated\n * @return {Promise} Resolves: updated result object\n * @return {Error} Rejects: with an error response.\n */\n public backPaginateRoomEventsSearch(searchResults: any): Promise<any> { // TODO: Types\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n\n if (!searchResults.next_batch) {\n return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n }\n\n if (searchResults.pendingRequest) {\n // already a request in progress - return the existing promise\n return searchResults.pendingRequest;\n }\n\n const searchOpts = {\n body: searchResults._query,\n next_batch: searchResults.next_batch,\n };\n\n const promise = this.search(searchOpts)\n .then(res => this.processRoomEventsSearch(searchResults, res))\n .finally(() => {\n searchResults.pendingRequest = null;\n });\n searchResults.pendingRequest = promise;\n\n return promise;\n }\n\n /**\n * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n * response from the API call and updates the searchResults\n *\n * @param {Object} searchResults\n * @param {Object} response\n * @return {Object} searchResults\n * @private\n */\n public processRoomEventsSearch(searchResults: any, response: any): any { // XXX: Intended private, used in code\n const roomEvents = response.search_categories.room_events; // eslint-disable-line camelcase\n\n searchResults.count = roomEvents.count;\n searchResults.next_batch = roomEvents.next_batch;\n\n // combine the highlight list with our existing list; build an object\n // to avoid O(N^2) fail\n const highlights = {};\n roomEvents.highlights.forEach((hl) => {\n highlights[hl] = 1;\n });\n searchResults.highlights.forEach((hl) => {\n highlights[hl] = 1;\n });\n\n // turn it back into a list.\n searchResults.highlights = Object.keys(highlights);\n\n // append the new results to our existing results\n const resultsLength = roomEvents.results ? roomEvents.results.length : 0;\n for (let i = 0; i < resultsLength; i++) {\n const sr = SearchResult.fromJson(roomEvents.results[i], this.getEventMapper());\n searchResults.results.push(sr);\n }\n return searchResults;\n }\n\n /**\n * Populate the store with rooms the user has left.\n * @return {Promise} Resolves: TODO - Resolved when the rooms have\n * been added to the data store.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public syncLeftRooms(): Promise<Room[]> {\n // Guard against multiple calls whilst ongoing and multiple calls post success\n if (this.syncedLeftRooms) {\n return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n }\n if (this.syncLeftRoomsPromise) {\n return this.syncLeftRoomsPromise; // return the ongoing request\n }\n const syncApi = new SyncApi(this, this.clientOpts);\n this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n // cleanup locks\n this.syncLeftRoomsPromise.then((res) => {\n logger.log(\"Marking success of sync left room request\");\n this.syncedLeftRooms = true; // flip the bit on success\n }).finally(() => {\n this.syncLeftRoomsPromise = null; // cleanup ongoing request state\n });\n\n return this.syncLeftRoomsPromise;\n }\n\n /**\n * Create a new filter.\n * @param {Object} content The HTTP body for the request\n * @return {Filter} Resolves to a Filter object.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public createFilter(content: any): Promise<Filter> { // TODO: Types\n const path = utils.encodeUri(\"/user/$userId/filter\", {\n $userId: this.credentials.userId,\n });\n return this.http.authedRequest(undefined, \"POST\", path, undefined, content).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(\n this.credentials.userId, response.filter_id, content,\n );\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * Retrieve a filter.\n * @param {string} userId The user ID of the filter owner\n * @param {string} filterId The filter ID to retrieve\n * @param {boolean} allowCached True to allow cached filters to be returned.\n * Default: True.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getFilter(userId: string, filterId: string, allowCached: boolean): Promise<Filter> {\n if (allowCached) {\n const filter = this.store.getFilter(userId, filterId);\n if (filter) {\n return Promise.resolve(filter);\n }\n }\n\n const path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n $userId: userId,\n $filterId: filterId,\n });\n\n return this.http.authedRequest(\n undefined, \"GET\", path, undefined, undefined,\n ).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(\n userId, filterId, response,\n );\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * @param {string} filterName\n * @param {Filter} filter\n * @return {Promise<String>} Filter ID\n */\n public async getOrCreateFilter(filterName: string, filter: Filter): Promise<string> {\n const filterId = this.store.getFilterIdByName(filterName);\n let existingId = undefined;\n\n if (filterId) {\n // check that the existing filter matches our expectations\n try {\n const existingFilter =\n await this.getFilter(this.credentials.userId, filterId, true);\n if (existingFilter) {\n const oldDef = existingFilter.getDefinition();\n const newDef = filter.getDefinition();\n\n if (utils.deepCompare(oldDef, newDef)) {\n // super, just use that.\n // debuglog(\"Using existing filter ID %s: %s\", filterId,\n // JSON.stringify(oldDef));\n existingId = filterId;\n }\n }\n } catch (error) {\n // Synapse currently returns the following when the filter cannot be found:\n // {\n // errcode: \"M_UNKNOWN\",\n // name: \"M_UNKNOWN\",\n // message: \"No row found\",\n // }\n if (error.errcode !== \"M_UNKNOWN\" && error.errcode !== \"M_NOT_FOUND\") {\n throw error;\n }\n }\n // if the filter doesn't exist anymore on the server, remove from store\n if (!existingId) {\n this.store.setFilterIdByName(filterName, undefined);\n }\n }\n\n if (existingId) {\n return existingId;\n }\n\n // create a new filter\n const createdFilter = await this.createFilter(filter.getDefinition());\n\n // debuglog(\"Created new filter ID %s: %s\", createdFilter.filterId,\n // JSON.stringify(createdFilter.getDefinition()));\n this.store.setFilterIdByName(filterName, createdFilter.filterId);\n return createdFilter.filterId;\n }\n\n /**\n * Gets a bearer token from the Home Server that the user can\n * present to a third party in order to prove their ownership\n * of the Matrix account they are logged into.\n * @return {Promise} Resolves: Token object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getOpenIdToken(): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n $userId: this.credentials.userId,\n });\n\n return this.http.authedRequest(\n undefined, \"POST\", path, undefined, {},\n );\n }\n\n private startCallEventHandler = () => {\n if (this.isInitialSyncComplete()) {\n this.callEventHandler.start();\n this.off(\"sync\", this.startCallEventHandler);\n }\n };\n\n /**\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public turnServer(callback?: Callback): Promise<any> { // TODO: Types\n return this.http.authedRequest(callback, \"GET\", \"/voip/turnServer\");\n }\n\n /**\n * Get the TURN servers for this home server.\n * @return {Array<Object>} The servers or an empty list.\n */\n public getTurnServers(): any[] { // TODO: Types\n return this.turnServers || [];\n }\n\n /**\n * Get the unix timestamp (in seconds) at which the current\n * TURN credentials (from getTurnServers) expire\n * @return {number} The expiry timestamp, in seconds, or null if no credentials\n */\n public getTurnServersExpiry(): number | null {\n return this.turnServersExpiry;\n }\n\n // XXX: Intended private, used in code.\n public async checkTurnServers(): Promise<boolean> {\n if (!this.canSupportVoip) {\n return;\n }\n\n let credentialsGood = false;\n const remainingTime = this.turnServersExpiry - Date.now();\n if (remainingTime > TURN_CHECK_INTERVAL) {\n logger.debug(\"TURN creds are valid for another \" + remainingTime + \" ms: not fetching new ones.\");\n credentialsGood = true;\n } else {\n logger.debug(\"Fetching new TURN credentials\");\n try {\n const res = await this.turnServer();\n if (res.uris) {\n logger.log(\"Got TURN URIs: \" + res.uris + \" refresh in \" + res.ttl + \" secs\");\n // map the response to a format that can be fed to RTCPeerConnection\n const servers = {\n urls: res.uris,\n username: res.username,\n credential: res.password,\n };\n this.turnServers = [servers];\n // The TTL is in seconds but we work in ms\n this.turnServersExpiry = Date.now() + (res.ttl * 1000);\n credentialsGood = true;\n }\n } catch (err) {\n logger.error(\"Failed to get TURN URIs\", err);\n // If we get a 403, there's no point in looping forever.\n if (err.httpStatus === 403) {\n logger.info(\"TURN access unavailable for this account: stopping credentials checks\");\n if (this.checkTurnServersIntervalID !== null) global.clearInterval(this.checkTurnServersIntervalID);\n this.checkTurnServersIntervalID = null;\n }\n }\n // otherwise, if we failed for whatever reason, try again the next time we're called.\n }\n\n return credentialsGood;\n }\n\n /**\n * Set whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @param {boolean} allow\n */\n public setFallbackICEServerAllowed(allow: boolean) {\n this.fallbackICEServerAllowed = allow;\n }\n\n /**\n * Get whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @returns {boolean}\n */\n public isFallbackICEServerAllowed(): boolean {\n return this.fallbackICEServerAllowed;\n }\n\n /**\n * Determines if the current user is an administrator of the Synapse homeserver.\n * Returns false if untrue or the homeserver does not appear to be a Synapse\n * homeserver. <strong>This function is implementation specific and may change\n * as a result.</strong>\n * @return {boolean} true if the user appears to be a Synapse administrator.\n */\n public isSynapseAdministrator(): Promise<boolean> {\n const path = utils.encodeUri(\n \"/_synapse/admin/v1/users/$userId/admin\",\n { $userId: this.getUserId() },\n );\n return this.http.authedRequest(\n undefined, 'GET', path, undefined, undefined, { prefix: '' },\n ).then(r => r['admin']); // pull out the specific boolean we want\n }\n\n /**\n * Performs a whois lookup on a user using Synapse's administrator API.\n * <strong>This function is implementation specific and may change as a\n * result.</strong>\n * @param {string} userId the User ID to look up.\n * @return {object} the whois response - see Synapse docs for information.\n */\n public whoisSynapseUser(userId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/_synapse/admin/v1/whois/$userId\",\n { $userId: userId },\n );\n return this.http.authedRequest(\n undefined, 'GET', path, undefined, undefined, { prefix: '' },\n );\n }\n\n /**\n * Deactivates a user using Synapse's administrator API. <strong>This\n * function is implementation specific and may change as a result.</strong>\n * @param {string} userId the User ID to deactivate.\n * @return {object} the deactivate response - see Synapse docs for information.\n */\n public deactivateSynapseUser(userId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/_synapse/admin/v1/deactivate/$userId\",\n { $userId: userId },\n );\n return this.http.authedRequest(\n undefined, 'POST', path, undefined, undefined, { prefix: '' },\n );\n }\n\n private async fetchClientWellKnown() {\n // `getRawClientConfig` does not throw or reject on network errors, instead\n // it absorbs errors and returns `{}`.\n this.clientWellKnownPromise = AutoDiscovery.getRawClientConfig(\n this.getDomain(),\n );\n this.clientWellKnown = await this.clientWellKnownPromise;\n this.emit(\"WellKnown.client\", this.clientWellKnown);\n }\n\n public getClientWellKnown(): any {\n return this.clientWellKnown;\n }\n\n public waitForClientWellKnown(): Promise<any> {\n return this.clientWellKnownPromise;\n }\n\n /**\n * store client options with boolean/string/numeric values\n * to know in the next session what flags the sync data was\n * created with (e.g. lazy loading)\n * @param {object} opts the complete set of client options\n * @return {Promise} for store operation\n */\n public storeClientOptions() { // XXX: Intended private, used in code\n const primTypes = [\"boolean\", \"string\", \"number\"];\n const serializableOpts = Object.entries(this.clientOpts)\n .filter(([key, value]) => {\n return primTypes.includes(typeof value);\n })\n .reduce((obj, [key, value]) => {\n obj[key] = value;\n return obj;\n }, {});\n return this.store.storeClientOptions(serializableOpts);\n }\n\n /**\n * Gets a set of room IDs in common with another user\n * @param {string} userId The userId to check.\n * @return {Promise<string[]>} Resolves to a set of rooms\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async _unstable_getSharedRooms(userId: string): Promise<string[]> { // eslint-disable-line camelcase\n if (!(await this.doesServerSupportUnstableFeature(\"uk.half-shot.msc2666\"))) {\n throw Error('Server does not support shared_rooms API');\n }\n const path = utils.encodeUri(\"/uk.half-shot.msc2666/user/shared_rooms/$userId\", {\n $userId: userId,\n });\n const res = await this.http.authedRequest(\n undefined, \"GET\", path, undefined, undefined,\n { prefix: PREFIX_UNSTABLE },\n );\n return res.joined;\n }\n\n /**\n * Get the API versions supported by the server, along with any\n * unstable APIs it supports\n * @return {Promise<object>} The server /versions response\n */\n public getVersions(): Promise<any> { // TODO: Types\n if (this.serverVersionsPromise) {\n return this.serverVersionsPromise;\n }\n\n this.serverVersionsPromise = this.http.request(\n undefined, // callback\n \"GET\", \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: '',\n },\n ).catch((e) => {\n // Need to unset this if it fails, otherwise we'll never retry\n this.serverVersionsPromise = null;\n // but rethrow the exception to anything that was waiting\n throw e;\n });\n\n return this.serverVersionsPromise;\n }\n\n /**\n * Check if a particular spec version is supported by the server.\n * @param {string} version The spec version (such as \"r0.5.0\") to check for.\n * @return {Promise<bool>} Whether it is supported\n */\n public async isVersionSupported(version: string): Promise<boolean> {\n const { versions } = await this.getVersions();\n return versions && versions.includes(version);\n }\n\n /**\n * Query the server to see if it support members lazy loading\n * @return {Promise<boolean>} true if server supports lazy loading\n */\n public async doesServerSupportLazyLoading(): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n\n const versions = response[\"versions\"];\n const unstableFeatures = response[\"unstable_features\"];\n\n return (versions && versions.includes(\"r0.5.0\"))\n || (unstableFeatures && unstableFeatures[\"m.lazy_load_members\"]);\n }\n\n /**\n * Query the server to see if the `id_server` parameter is required\n * when registering with an 3pid, adding a 3pid or resetting password.\n * @return {Promise<boolean>} true if id_server parameter is required\n */\n public async doesServerRequireIdServerParam(): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return true;\n\n const versions = response[\"versions\"];\n\n // Supporting r0.6.0 is the same as having the flag set to false\n if (versions && versions.includes(\"r0.6.0\")) {\n return false;\n }\n\n const unstableFeatures = response[\"unstable_features\"];\n if (!unstableFeatures) return true;\n if (unstableFeatures[\"m.require_identity_server\"] === undefined) {\n return true;\n } else {\n return unstableFeatures[\"m.require_identity_server\"];\n }\n }\n\n /**\n * Query the server to see if the `id_access_token` parameter can be safely\n * passed to the homeserver. Some homeservers may trigger errors if they are not\n * prepared for the new parameter.\n * @return {Promise<boolean>} true if id_access_token can be sent\n */\n public async doesServerAcceptIdentityAccessToken(): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n\n const versions = response[\"versions\"];\n const unstableFeatures = response[\"unstable_features\"];\n return (versions && versions.includes(\"r0.6.0\"))\n || (unstableFeatures && unstableFeatures[\"m.id_access_token\"]);\n }\n\n /**\n * Query the server to see if it supports separate 3PID add and bind functions.\n * This affects the sequence of API calls clients should use for these operations,\n * so it's helpful to be able to check for support.\n * @return {Promise<boolean>} true if separate functions are supported\n */\n public async doesServerSupportSeparateAddAndBind(): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n\n const versions = response[\"versions\"];\n const unstableFeatures = response[\"unstable_features\"];\n\n return (versions && versions.includes(\"r0.6.0\"))\n || (unstableFeatures && unstableFeatures[\"m.separate_add_and_bind\"]);\n }\n\n /**\n * Query the server to see if it lists support for an unstable feature\n * in the /versions response\n * @param {string} feature the feature name\n * @return {Promise<boolean>} true if the feature is supported\n */\n public async doesServerSupportUnstableFeature(feature: string): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n return unstableFeatures && !!unstableFeatures[feature];\n }\n\n /**\n * Query the server to see if it is forcing encryption to be enabled for\n * a given room preset, based on the /versions response.\n * @param {Preset} presetName The name of the preset to check.\n * @returns {Promise<boolean>} true if the server is forcing encryption\n * for the preset.\n */\n public async doesServerForceEncryptionForPreset(presetName: Preset): Promise<boolean> {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n\n // The preset name in the versions response will be without the _chat suffix.\n const versionsPresetName = presetName.includes(\"_chat\")\n ? presetName.substring(0, presetName.indexOf(\"_chat\"))\n : presetName;\n\n return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];\n }\n\n /**\n * Get if lazy loading members is being used.\n * @return {boolean} Whether or not members are lazy loaded by this client\n */\n public hasLazyLoadMembersEnabled(): boolean {\n return !!this.clientOpts.lazyLoadMembers;\n }\n\n /**\n * Set a function which is called when /sync returns a 'limited' response.\n * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n * can SAFELY remove events from this room. It may not be safe to remove events if there\n * are other references to the timelines for this room, e.g because the client is\n * actively viewing events in this room.\n * Default: returns false.\n * @param {Function} cb The callback which will be invoked.\n */\n public setCanResetTimelineCallback(cb: ResetTimelineCallback) {\n this.canResetTimelineCallback = cb;\n }\n\n /**\n * Get the callback set via `setCanResetTimelineCallback`.\n * @return {?Function} The callback or null\n */\n public getCanResetTimelineCallback(): ResetTimelineCallback {\n return this.canResetTimelineCallback;\n }\n\n /**\n * Returns relations for a given event. Handles encryption transparently,\n * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n * When the returned promise resolves, all messages should have finished trying to decrypt.\n * @param {string} roomId the room of the event\n * @param {string} eventId the id of the event\n * @param {string} relationType the rel_type of the relations requested\n * @param {string} eventType the event type of the relations requested\n * @param {Object} opts options with optional values for the request.\n * @param {Object} opts.from the pagination token returned from a previous request as `nextBatch` to return following relations.\n * @return {Object} an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n */\n public async relations(\n roomId: string,\n eventId: string,\n relationType: string,\n eventType: string,\n opts: { from: string },\n ): Promise<{ originalEvent: MatrixEvent, events: MatrixEvent[], nextBatch?: string }> {\n const fetchedEventType = this.getEncryptedIfNeededEventType(roomId, eventType);\n const result = await this.fetchRelations(\n roomId,\n eventId,\n relationType,\n fetchedEventType,\n opts);\n const mapper = this.getEventMapper();\n let originalEvent;\n if (result.original_event) {\n originalEvent = mapper(result.original_event);\n }\n let events = result.chunk.map(mapper);\n if (fetchedEventType === \"m.room.encrypted\") {\n const allEvents = originalEvent ? events.concat(originalEvent) : events;\n await Promise.all(allEvents.map(e => {\n return new Promise(resolve => e.once(\"Event.decrypted\", resolve));\n }));\n events = events.filter(e => e.getType() === eventType);\n }\n if (originalEvent && relationType === \"m.replace\") {\n events = events.filter(e => e.getSender() === originalEvent.getSender());\n }\n return {\n originalEvent,\n events,\n nextBatch: result.next_batch,\n };\n }\n\n /**\n * The app may wish to see if we have a key cached without\n * triggering a user interaction.\n * @return {object}\n */\n public getCrossSigningCacheCallbacks(): any { // TODO: Types\n // XXX: Private member access\n return this.crypto?.crossSigningInfo.getCacheCallbacks();\n }\n\n /**\n * Generates a random string suitable for use as a client secret. <strong>This\n * method is experimental and may change.</strong>\n * @return {string} A new client secret\n */\n public generateClientSecret(): string {\n return randomString(32);\n }\n\n /**\n * Attempts to decrypt an event\n * @param {MatrixEvent} event The event to decrypt\n * @returns {Promise<void>} A decryption promise\n * @param {object} options\n * @param {boolean} options.isRetry True if this is a retry (enables more logging)\n * @param {boolean} options.emit Emits \"event.decrypted\" if set to true\n */\n public decryptEventIfNeeded(event: MatrixEvent, options?: IDecryptOptions): Promise<void> {\n if (event.shouldAttemptDecryption()) {\n event.attemptDecryption(this.crypto, options);\n }\n\n if (event.isBeingDecrypted()) {\n return event.getDecryptionPromise();\n } else {\n return Promise.resolve();\n }\n }\n\n private termsUrlForService(serviceType: SERVICE_TYPES, baseUrl: string) {\n switch (serviceType) {\n case SERVICE_TYPES.IS:\n return baseUrl + PREFIX_IDENTITY_V2 + '/terms';\n case SERVICE_TYPES.IM:\n return baseUrl + '/_matrix/integrations/v1/terms';\n default:\n throw new Error('Unsupported service type');\n }\n }\n\n /**\n * Get the Homeserver URL of this client\n * @return {string} Homeserver URL of this client\n */\n public getHomeserverUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get the Identity Server URL of this client\n * @param {boolean} stripProto whether or not to strip the protocol from the URL\n * @return {string} Identity Server URL of this client\n */\n public getIdentityServerUrl(stripProto = false): string {\n if (stripProto && (this.idBaseUrl.startsWith(\"http://\") ||\n this.idBaseUrl.startsWith(\"https://\"))) {\n return this.idBaseUrl.split(\"://\")[1];\n }\n return this.idBaseUrl;\n }\n\n /**\n * Set the Identity Server URL of this client\n * @param {string} url New Identity Server URL\n */\n public setIdentityServerUrl(url: string) {\n this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n this.http.setIdBaseUrl(this.idBaseUrl);\n }\n\n /**\n * Get the access token associated with this account.\n * @return {?String} The access_token or null\n */\n public getAccessToken(): string {\n return this.http.opts.accessToken || null;\n }\n\n /**\n * @return {boolean} true if there is a valid access_token for this client.\n */\n public isLoggedIn(): boolean {\n return this.http.opts.accessToken !== undefined;\n }\n\n /**\n * Make up a new transaction id\n *\n * @return {string} a new, unique, transaction id\n */\n public makeTxnId(): string {\n return \"m\" + new Date().getTime() + \".\" + (this.txnCtr++);\n }\n\n /**\n * Check whether a username is available prior to registration. An error response\n * indicates an invalid/unavailable username.\n * @param {string} username The username to check the availability of.\n * @return {Promise} Resolves: to `true`.\n */\n public isUsernameAvailable(username: string): Promise<true> {\n return this.http.authedRequest(\n undefined, \"GET\", '/register/available', { username: username },\n ).then((response) => {\n return response.available;\n });\n }\n\n /**\n * @param {string} username\n * @param {string} password\n * @param {string} sessionId\n * @param {Object} auth\n * @param {Object} bindThreepids Set key 'email' to true to bind any email\n * threepid uses during registration in the ID server. Set 'msisdn' to\n * true to bind msisdn.\n * @param {string} guestAccessToken\n * @param {string} inhibitLogin\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public register(\n username: string,\n password: string,\n sessionId: string,\n auth: any,\n bindThreepids: any,\n guestAccessToken: string,\n inhibitLogin: boolean,\n callback?: Callback,\n ): Promise<any> { // TODO: Types (many)\n // backwards compat\n if (bindThreepids === true) {\n bindThreepids = { email: true };\n } else if (bindThreepids === null || bindThreepids === undefined) {\n bindThreepids = {};\n }\n if (typeof inhibitLogin === 'function') {\n callback = inhibitLogin;\n inhibitLogin = undefined;\n }\n\n if (sessionId) {\n auth.session = sessionId;\n }\n\n const params: any = {\n auth: auth,\n };\n if (username !== undefined && username !== null) {\n params.username = username;\n }\n if (password !== undefined && password !== null) {\n params.password = password;\n }\n if (bindThreepids.email) {\n params.bind_email = true;\n }\n if (bindThreepids.msisdn) {\n params.bind_msisdn = true;\n }\n if (guestAccessToken !== undefined && guestAccessToken !== null) {\n params.guest_access_token = guestAccessToken;\n }\n if (inhibitLogin !== undefined && inhibitLogin !== null) {\n params.inhibit_login = inhibitLogin;\n }\n // Temporary parameter added to make the register endpoint advertise\n // msisdn flows. This exists because there are clients that break\n // when given stages they don't recognise. This parameter will cease\n // to be necessary once these old clients are gone.\n // Only send it if we send any params at all (the password param is\n // mandatory, so if we send any params, we'll send the password param)\n if (password !== undefined && password !== null) {\n params.x_show_msisdn = true;\n }\n\n return this.registerRequest(params, undefined, callback);\n }\n\n /**\n * Register a guest account.\n * This method returns the auth info needed to create a new authenticated client,\n * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n * ```javascript\n * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n * const client = createClient({\n * baseUrl: MATRIX_INSTANCE,\n * accessToken: access_token,\n * userId: user_id,\n * deviceId: device_id,\n * })\n * client.setGuest(true);\n * ```\n *\n * @param {Object=} opts Registration options\n * @param {Object} opts.body JSON HTTP body to provide.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: JSON object that contains:\n * { user_id, device_id, access_token, home_server }\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public registerGuest(opts: { body?: any }, callback?: Callback): Promise<any> { // TODO: Types\n opts = opts || {};\n opts.body = opts.body || {};\n return this.registerRequest(opts.body, \"guest\", callback);\n }\n\n /**\n * @param {Object} data parameters for registration request\n * @param {string=} kind type of user to register. may be \"guest\"\n * @param {module:client.callback=} callback\n * @return {Promise} Resolves: to the /register response\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public registerRequest(data: any, kind?: string, callback?: Callback): Promise<any> { // TODO: Types\n const params: any = {};\n if (kind) {\n params.kind = kind;\n }\n\n return this.http.request(callback, \"POST\", \"/register\", params, data);\n }\n\n /**\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public loginFlows(callback?: Callback): Promise<any> { // TODO: Types\n return this.http.request(callback, \"GET\", \"/login\");\n }\n\n /**\n * @param {string} loginType\n * @param {Object} data\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public login(loginType: string, data: any, callback?: Callback): Promise<any> { // TODO: Types\n const loginData = {\n type: loginType,\n };\n\n // merge data into loginData\n utils.extend(loginData, data);\n\n return this.http.authedRequest(\n (error, response) => {\n if (response && response.access_token && response.user_id) {\n this.http.opts.accessToken = response.access_token;\n this.credentials = {\n userId: response.user_id,\n };\n }\n\n if (callback) {\n callback(error, response);\n }\n }, \"POST\", \"/login\", undefined, loginData,\n );\n }\n\n /**\n * @param {string} user\n * @param {string} password\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public loginWithPassword(user: string, password: string, callback?: Callback): Promise<any> { // TODO: Types\n return this.login(\"m.login.password\", {\n user: user,\n password: password,\n }, callback);\n }\n\n /**\n * @param {string} relayState URL Callback after SAML2 Authentication\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public loginWithSAML2(relayState: string, callback?: Callback): Promise<any> { // TODO: Types\n return this.login(\"m.login.saml2\", {\n relay_state: relayState,\n }, callback);\n }\n\n /**\n * @param {string} redirectUrl The URL to redirect to after the HS\n * authenticates with CAS.\n * @return {string} The HS URL to hit to begin the CAS login process.\n */\n public getCasLoginUrl(redirectUrl: string): string {\n return this.getSsoLoginUrl(redirectUrl, \"cas\");\n }\n\n /**\n * @param {string} redirectUrl The URL to redirect to after the HS\n * authenticates with the SSO.\n * @param {string} loginType The type of SSO login we are doing (sso or cas).\n * Defaults to 'sso'.\n * @param {string} idpId The ID of the Identity Provider being targeted, optional.\n * @return {string} The HS URL to hit to begin the SSO login process.\n */\n public getSsoLoginUrl(redirectUrl: string, loginType = \"sso\", idpId?: string): string {\n let url = \"/login/\" + loginType + \"/redirect\";\n if (idpId) {\n url += \"/\" + idpId;\n }\n\n return this.http.getUrl(url, { redirectUrl }, PREFIX_R0);\n }\n\n /**\n * @param {string} token Login token previously received from homeserver\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public loginWithToken(token: string, callback?: Callback): Promise<any> { // TODO: Types\n return this.login(\"m.login.token\", {\n token: token,\n }, callback);\n }\n\n /**\n * Logs out the current session.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: On success, the empty object\n */\n public logout(callback?: Callback): Promise<{}> {\n return this.http.authedRequest(\n callback, \"POST\", '/logout',\n );\n }\n\n /**\n * Deactivates the logged-in account.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param {object} auth Optional. Auth data to supply for User-Interactive auth.\n * @param {boolean} erase Optional. If set, send as `erase` attribute in the\n * JSON request body, indicating whether the account should be erased. Defaults\n * to false.\n * @return {Promise} Resolves: On success, the empty object\n */\n public deactivateAccount(auth?: any, erase?: boolean): Promise<{}> {\n if (typeof (erase) === 'function') {\n throw new Error(\n 'deactivateAccount no longer accepts a callback parameter',\n );\n }\n\n const body: any = {};\n if (auth) {\n body.auth = auth;\n }\n if (erase !== undefined) {\n body.erase = erase;\n }\n\n return this.http.authedRequest(\n undefined, \"POST\", '/account/deactivate', undefined, body,\n );\n }\n\n /**\n * Get the fallback URL to use for unknown interactive-auth stages.\n *\n * @param {string} loginType the type of stage being attempted\n * @param {string} authSessionId the auth session ID provided by the homeserver\n *\n * @return {string} HS URL to hit to for the fallback interface\n */\n public getFallbackAuthUrl(loginType: string, authSessionId: string): string {\n const path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n $loginType: loginType,\n });\n\n return this.http.getUrl(path, {\n session: authSessionId,\n }, PREFIX_R0);\n }\n\n /**\n * Create a new room.\n * @param {Object} options a list of options to pass to the /createRoom API.\n * @param {string} options.room_alias_name The alias localpart to assign to\n * this room.\n * @param {string} options.visibility Either 'public' or 'private'.\n * @param {string[]} options.invite A list of user IDs to invite to this room.\n * @param {string} options.name The name to give this room.\n * @param {string} options.topic The topic to give this room.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: <code>{room_id: {string},\n * room_alias: {string(opt)}}</code>\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async createRoom(\n options: ICreateRoomOpts,\n callback?: Callback,\n ): Promise<{ room_id: string, room_alias?: string }> { // eslint-disable-line camelcase\n // some valid options include: room_alias_name, visibility, invite\n\n // inject the id_access_token if inviting 3rd party addresses\n const invitesNeedingToken = (options.invite_3pid || [])\n .filter(i => !i.id_access_token);\n if (\n invitesNeedingToken.length > 0 &&\n this.identityServer &&\n this.identityServer.getAccessToken &&\n await this.doesServerAcceptIdentityAccessToken()\n ) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n for (const invite of invitesNeedingToken) {\n invite.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.authedRequest(\n callback, \"POST\", \"/createRoom\", undefined, options,\n );\n }\n\n /**\n * Fetches relations for a given event\n * @param {string} roomId the room of the event\n * @param {string} eventId the id of the event\n * @param {string} relationType the rel_type of the relations requested\n * @param {string} eventType the event type of the relations requested\n * @param {Object} opts options with optional values for the request.\n * @param {Object} opts.from the pagination token returned from a previous request as `next_batch` to return following relations.\n * @return {Object} the response, with chunk and next_batch.\n */\n public async fetchRelations(\n roomId: string,\n eventId: string,\n relationType: string,\n eventType: string,\n opts: { from: string },\n ): Promise<any> { // TODO: Types\n const queryParams: any = {};\n if (opts.from) {\n queryParams.from = opts.from;\n }\n const queryString = utils.encodeParams(queryParams);\n const path = utils.encodeUri(\n \"/rooms/$roomId/relations/$eventId/$relationType/$eventType?\" + queryString, {\n $roomId: roomId,\n $eventId: eventId,\n $relationType: relationType,\n $eventType: eventType,\n });\n return await this.http.authedRequest(\n undefined, \"GET\", path, null, null, {\n prefix: PREFIX_UNSTABLE,\n },\n );\n }\n\n /**\n * @param {string} roomId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public roomState(roomId: string, callback?: Callback): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/rooms/$roomId/state\", { $roomId: roomId });\n return this.http.authedRequest(callback, \"GET\", path);\n }\n\n /**\n * Get an event in a room by its event id.\n * @param {string} roomId\n * @param {string} eventId\n * @param {module:client.callback} callback Optional.\n *\n * @return {Promise} Resolves to an object containing the event.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public fetchRoomEvent(roomId: string, eventId: string, callback?: Callback): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\n \"/rooms/$roomId/event/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n },\n );\n return this.http.authedRequest(callback, \"GET\", path);\n }\n\n /**\n * @param {string} roomId\n * @param {string} includeMembership the membership type to include in the response\n * @param {string} excludeMembership the membership type to exclude from the response\n * @param {string} atEventId the id of the event for which moment in the timeline the members should be returned for\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: dictionary of userid to profile information\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public members(\n roomId: string,\n includeMembership?: string[],\n excludeMembership?: string[],\n atEventId?: string,\n callback?: Callback,\n ): Promise<{ [userId: string]: any }> {\n const queryParams: any = {};\n if (includeMembership) {\n queryParams.membership = includeMembership;\n }\n if (excludeMembership) {\n queryParams.not_membership = excludeMembership;\n }\n if (atEventId) {\n queryParams.at = atEventId;\n }\n\n const queryString = utils.encodeParams(queryParams);\n\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString,\n { $roomId: roomId });\n return this.http.authedRequest(callback, \"GET\", path);\n }\n\n /**\n * Upgrades a room to a new protocol version\n * @param {string} roomId\n * @param {string} newVersion The target version to upgrade to\n * @return {Promise} Resolves: Object with key 'replacement_room'\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public upgradeRoom(\n roomId: string,\n newVersion: string,\n ): Promise<{ replacement_room: string }> { // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/rooms/$roomId/upgrade\", { $roomId: roomId });\n return this.http.authedRequest(\n undefined, \"POST\", path, undefined, { new_version: newVersion },\n );\n }\n\n /**\n * Retrieve a state event.\n * @param {string} roomId\n * @param {string} eventType\n * @param {string} stateKey\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getStateEvent(roomId: string, eventType: string, stateKey: string, callback?: Callback): Promise<any> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(\n callback, \"GET\", path,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {string} eventType\n * @param {Object} content\n * @param {string} stateKey\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public sendStateEvent(\n roomId: string,\n eventType: string,\n content: any,\n stateKey = \"\",\n callback?: Callback,\n ): Promise<any> { // TODO: Types\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, content,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {Number} limit\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public roomInitialSync(roomId: string, limit: number, callback?: Callback): Promise<any> { // TODO: Types\n if (utils.isFunction(limit)) {\n callback = limit as any as Callback; // legacy\n limit = undefined;\n }\n const path = utils.encodeUri(\"/rooms/$roomId/initialSync\",\n { $roomId: roomId },\n );\n if (!limit) {\n limit = 30;\n }\n return this.http.authedRequest(\n callback, \"GET\", path, { limit: limit },\n );\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param {string} roomId ID of the room that has been read\n * @param {string} rmEventId ID of the event that has been read\n * @param {string} rrEventId ID of the event tracked by the read receipt. This is here\n * for convenience because the RR and the RM are commonly updated at the same time as\n * each other. Optional.\n * @param {object} opts Options for the read markers.\n * @param {object} opts.hidden True to hide the read receipt from other users. <b>This\n * property is currently unstable and may change in the future.</b>\n * @return {Promise} Resolves: the empty object, {}.\n */\n public setRoomReadMarkersHttpRequest(\n roomId: string,\n rmEventId: string,\n rrEventId: string,\n opts: { hidden?: boolean },\n ): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n $roomId: roomId,\n });\n\n const content = {\n \"m.fully_read\": rmEventId,\n \"m.read\": rrEventId,\n \"m.hidden\": Boolean(opts ? opts.hidden : false),\n };\n\n return this.http.authedRequest(\n undefined, \"POST\", path, undefined, content,\n );\n }\n\n /**\n * @return {Promise} Resolves: A list of the user's current rooms\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getJoinedRooms(): Promise<string[]> {\n const path = utils.encodeUri(\"/joined_rooms\", {});\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * Retrieve membership info. for a room.\n * @param {string} roomId ID of the room to get membership for\n * @return {Promise} Resolves: A list of currently joined users\n * and their profile data.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getJoinedRoomMembers(roomId: string): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {Object} options Options for this request\n * @param {string} options.server The remote server to query for the room list.\n * Optional. If unspecified, get the local home\n * server's public room list.\n * @param {number} options.limit Maximum number of entries to return\n * @param {string} options.since Token to paginate from\n * @param {object} options.filter Filter parameters\n * @param {string} options.filter.generic_search_term String to search for\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public publicRooms(options: IRoomDirectoryOptions, callback?: Callback): Promise<any> { // TODO: Types\n if (typeof (options) == 'function') {\n callback = options;\n options = {};\n }\n if (options === undefined) {\n options = {};\n }\n\n const queryParams: any = {};\n if (options.server) {\n queryParams.server = options.server;\n delete options.server;\n }\n\n if (Object.keys(options).length === 0 && Object.keys(queryParams).length === 0) {\n return this.http.authedRequest(callback, \"GET\", \"/publicRooms\");\n } else {\n return this.http.authedRequest(\n callback, \"POST\", \"/publicRooms\", queryParams, options,\n );\n }\n }\n\n /**\n * Create an alias to room ID mapping.\n * @param {string} alias The room alias to create.\n * @param {string} roomId The room ID to link the alias to.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public createAlias(alias: string, roomId: string, callback?: Callback): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n const data = {\n room_id: roomId,\n };\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, data,\n );\n }\n\n /**\n * Delete an alias to room ID mapping. This alias must be on your local server\n * and you must have sufficient access to do this operation.\n * @param {string} alias The room alias to delete.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public deleteAlias(alias: string, callback?: Callback): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(\n callback, \"DELETE\", path, undefined, undefined,\n );\n }\n\n /**\n * @param {string} roomId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: an object with an `aliases` property, containing an array of local aliases\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public unstableGetLocalAliases(roomId: string, callback?: Callback): Promise<{ aliases: string[] }> {\n const path = utils.encodeUri(\"/rooms/$roomId/aliases\",\n { $roomId: roomId });\n const prefix = PREFIX_UNSTABLE + \"/org.matrix.msc2432\";\n return this.http.authedRequest(callback, \"GET\", path,\n null, null, { prefix });\n }\n\n /**\n * Get room info for the given alias.\n * @param {string} alias The room alias to resolve.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Object with room_id and servers.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getRoomIdForAlias(\n alias: string,\n callback?: Callback,\n ): Promise<{ room_id: string, servers: string[] }> { // eslint-disable-line camelcase\n // TODO: deprecate this or resolveRoomAlias\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(\n callback, \"GET\", path,\n );\n }\n\n /**\n * @param {string} roomAlias\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public resolveRoomAlias(roomAlias: string, callback?: Callback): Promise<any> { // TODO: Types\n // TODO: deprecate this or getRoomIdForAlias\n const path = utils.encodeUri(\"/directory/room/$alias\", { $alias: roomAlias });\n return this.http.request(callback, \"GET\", path);\n }\n\n /**\n * Get the visibility of a room in the current HS's room directory\n * @param {string} roomId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getRoomDirectoryVisibility(roomId: string, callback?: Callback): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(callback, \"GET\", path);\n }\n\n /**\n * Set the visbility of a room in the current HS's room directory\n * @param {string} roomId\n * @param {string} visibility \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomDirectoryVisibility(\n roomId: string,\n visibility: \"public\" | \"private\",\n callback?: Callback,\n ): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, { \"visibility\": visibility },\n );\n }\n\n /**\n * Set the visbility of a room bridged to a 3rd party network in\n * the current HS's room directory.\n * @param {string} networkId the network ID of the 3rd party\n * instance under which this room is published under.\n * @param {string} roomId\n * @param {string} visibility \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setRoomDirectoryVisibilityAppService(\n networkId: string,\n roomId: string,\n visibility: \"public\" | \"private\",\n callback?: Callback,\n ): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/directory/list/appservice/$networkId/$roomId\", {\n $networkId: networkId,\n $roomId: roomId,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, { \"visibility\": visibility },\n );\n }\n\n /**\n * Query the user directory with a term matching user IDs, display names and domains.\n * @param {object} opts options\n * @param {string} opts.term the term with which to search.\n * @param {number} opts.limit the maximum number of results to return. The server will\n * apply a limit if unspecified.\n * @return {Promise} Resolves: an array of results.\n */\n public searchUserDirectory(opts: { term: string, limit?: number }): Promise<any> { // TODO: Types\n const body: any = {\n search_term: opts.term,\n };\n\n if (opts.limit !== undefined) {\n body.limit = opts.limit;\n }\n\n return this.http.authedRequest(\n undefined, \"POST\", \"/user_directory/search\", undefined, body,\n );\n }\n\n /**\n * Upload a file to the media repository on the home server.\n *\n * @param {object} file The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a a Buffer, String or ReadStream.\n *\n * @param {object} opts options object\n *\n * @param {string=} opts.name Name to give the file on the server. Defaults\n * to <tt>file.name</tt>.\n *\n * @param {boolean=} opts.includeFilename if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n *\n * @param {string=} opts.type Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n *\n * @param {boolean=} opts.rawResponse Return the raw body, rather than\n * parsing the JSON. Defaults to false (except on node.js, where it\n * defaults to true for backwards compatibility).\n *\n * @param {boolean=} opts.onlyContentUri Just return the content URI,\n * rather than the whole body. Defaults to false (except on browsers,\n * where it defaults to true for backwards compatibility). Ignored if\n * opts.rawResponse is true.\n *\n * @param {Function=} opts.callback Deprecated. Optional. The callback to\n * invoke on success/failure. See the promise return values for more\n * information.\n *\n * @param {Function=} opts.progressHandler Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n *\n * @return {Promise} Resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(\n file: File | String | Buffer | ReadStream | Blob,\n opts?: IUploadOpts,\n ): Promise<any> { // TODO: Advanced types\n return this.http.uploadContent(file, opts);\n }\n\n /**\n * Cancel a file upload in progress\n * @param {Promise} promise The promise returned from uploadContent\n * @return {boolean} true if canceled, otherwise false\n */\n public cancelUpload(promise: Promise<any>): boolean { // TODO: Advanced types\n return this.http.cancelUpload(promise);\n }\n\n /**\n * Get a list of all file uploads in progress\n * @return {array} Array of objects representing current uploads.\n * Currently in progress is element 0. Keys:\n * - promise: The promise associated with the upload\n * - loaded: Number of bytes uploaded\n * - total: Total number of bytes to upload\n */\n public getCurrentUploads(): { promise: Promise<any>, loaded: number, total: number }[] { // TODO: Advanced types (promise)\n return this.http.getCurrentUploads();\n }\n\n /**\n * @param {string} userId\n * @param {string} info The kind of info to retrieve (e.g. 'displayname',\n * 'avatar_url').\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getProfileInfo(userId: string, info?: string, callback?: Callback): Promise<any> { // TODO: Types\n if (utils.isFunction(info)) {\n callback = info as any as Callback; // legacy\n info = undefined;\n }\n\n const path = info ?\n utils.encodeUri(\"/profile/$userId/$info\",\n { $userId: userId, $info: info }) :\n utils.encodeUri(\"/profile/$userId\",\n { $userId: userId });\n return this.http.authedRequest(callback, \"GET\", path);\n }\n\n /**\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getThreePids(callback?: Callback): Promise<any> { // TODO: Types\n const path = \"/account/3pid\";\n return this.http.authedRequest(\n callback, \"GET\", path, undefined, undefined,\n );\n }\n\n /**\n * Add a 3PID to your homeserver account and optionally bind it to an identity\n * server as well. An identity server is required as part of the `creds` object.\n *\n * This API is deprecated, and you should instead use `addThreePidOnly`\n * for homeservers that support it.\n *\n * @param {Object} creds\n * @param {boolean} bind\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: on success\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public addThreePid(creds: any, bind: boolean, callback?: Callback): Promise<any> { // TODO: Types\n const path = \"/account/3pid\";\n const data = {\n 'threePidCreds': creds,\n 'bind': bind,\n };\n return this.http.authedRequest(\n callback, \"POST\", path, null, data,\n );\n }\n\n /**\n * Add a 3PID to your homeserver account. This API does not use an identity\n * server, as the homeserver is expected to handle 3PID ownership validation.\n *\n * You can check whether a homeserver supports this API via\n * `doesServerSupportSeparateAddAndBind`.\n *\n * @param {Object} data A object with 3PID validation data from having called\n * `account/3pid/<medium>/requestToken` on the homeserver.\n * @return {Promise} Resolves: on success\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async addThreePidOnly(data: any): Promise<void> { // TODO: Types\n const path = \"/account/3pid/add\";\n const prefix = await this.isVersionSupported(\"r0.6.0\") ?\n PREFIX_R0 : PREFIX_UNSTABLE;\n return this.http.authedRequest(\n undefined, \"POST\", path, null, data, { prefix },\n );\n }\n\n /**\n * Bind a 3PID for discovery onto an identity server via the homeserver. The\n * identity server handles 3PID ownership validation and the homeserver records\n * the new binding to track where all 3PIDs for the account are bound.\n *\n * You can check whether a homeserver supports this API via\n * `doesServerSupportSeparateAddAndBind`.\n *\n * @param {Object} data A object with 3PID validation data from having called\n * `validate/<medium>/requestToken` on the identity server. It should also\n * contain `id_server` and `id_access_token` fields as well.\n * @return {Promise} Resolves: on success\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async bindThreePid(data: any): Promise<void> { // TODO: Types\n const path = \"/account/3pid/bind\";\n const prefix = await this.isVersionSupported(\"r0.6.0\") ?\n PREFIX_R0 : PREFIX_UNSTABLE;\n return this.http.authedRequest(\n undefined, \"POST\", path, null, data, { prefix },\n );\n }\n\n /**\n * Unbind a 3PID for discovery on an identity server via the homeserver. The\n * homeserver removes its record of the binding to keep an updated record of\n * where all 3PIDs for the account are bound.\n *\n * @param {string} medium The threepid medium (eg. 'email')\n * @param {string} address The threepid address (eg. 'bob@example.com')\n * this must be as returned by getThreePids.\n * @return {Promise} Resolves: on success\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async unbindThreePid(medium: string, address: string): Promise<void> {\n const path = \"/account/3pid/unbind\";\n const data = {\n medium,\n address,\n id_server: this.getIdentityServerUrl(true),\n };\n const prefix = await this.isVersionSupported(\"r0.6.0\") ?\n PREFIX_R0 : PREFIX_UNSTABLE;\n return this.http.authedRequest(\n undefined, \"POST\", path, null, data, { prefix },\n );\n }\n\n /**\n * @param {string} medium The threepid medium (eg. 'email')\n * @param {string} address The threepid address (eg. 'bob@example.com')\n * this must be as returned by getThreePids.\n * @return {Promise} Resolves: The server response on success\n * (generally the empty JSON object)\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public deleteThreePid(medium: string, address: string): Promise<void> {\n const path = \"/account/3pid/delete\";\n const data = {\n 'medium': medium,\n 'address': address,\n };\n return this.http.authedRequest(undefined, \"POST\", path, null, data);\n }\n\n /**\n * Make a request to change your password.\n * @param {Object} authDict\n * @param {string} newPassword The new desired password.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setPassword(authDict: any, newPassword: string, callback?: Callback): Promise<any> { // TODO: Types\n const path = \"/account/password\";\n const data = {\n 'auth': authDict,\n 'new_password': newPassword,\n };\n\n return this.http.authedRequest(\n callback, \"POST\", path, null, data,\n );\n }\n\n /**\n * Gets all devices recorded for the logged-in user\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getDevices(): Promise<any> { // TODO: Types\n return this.http.authedRequest(\n undefined, 'GET', \"/devices\", undefined, undefined,\n );\n }\n\n /**\n * Gets specific device details for the logged-in user\n * @param {string} deviceId device to query\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getDevice(deviceId: string): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n return this.http.authedRequest(\n undefined, 'GET', path, undefined, undefined,\n );\n }\n\n /**\n * Update the given device\n *\n * @param {string} deviceId device to update\n * @param {Object} body body of request\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setDeviceDetails(deviceId: string, body: any): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, body);\n }\n\n /**\n * Delete the given device\n *\n * @param {string} deviceId device to delete\n * @param {object} auth Optional. Auth data to supply for User-Interactive auth.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public deleteDevice(deviceId: string, auth?: any): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n const body: any = {};\n\n if (auth) {\n body.auth = auth;\n }\n\n return this.http.authedRequest(undefined, \"DELETE\", path, undefined, body);\n }\n\n /**\n * Delete multiple device\n *\n * @param {string[]} devices IDs of the devices to delete\n * @param {object} auth Optional. Auth data to supply for User-Interactive auth.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public deleteMultipleDevices(devices: string[], auth?: any): Promise<any> { // TODO: Types\n const body: any = { devices };\n\n if (auth) {\n body.auth = auth;\n }\n\n const path = \"/delete_devices\";\n return this.http.authedRequest(undefined, \"POST\", path, undefined, body);\n }\n\n /**\n * Gets all pushers registered for the logged-in user\n *\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Array of objects representing pushers\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getPushers(callback?: Callback): Promise<any> { // TODO: Types\n const path = \"/pushers\";\n return this.http.authedRequest(\n callback, \"GET\", path, undefined, undefined,\n );\n }\n\n /**\n * Adds a new pusher or updates an existing pusher\n *\n * @param {Object} pusher Object representing a pusher\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: Empty json object on success\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setPusher(pusher: any, callback?: Callback): Promise<any> { // TODO: Types\n const path = \"/pushers/set\";\n return this.http.authedRequest(\n callback, \"POST\", path, null, pusher,\n );\n }\n\n /**\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getPushRules(callback?: Callback): Promise<any> { // TODO: Types\n return this.http.authedRequest(callback, \"GET\", \"/pushrules/\").then(rules => {\n return PushProcessor.rewriteDefaultRules(rules);\n });\n }\n\n /**\n * @param {string} scope\n * @param {string} kind\n * @param {string} ruleId\n * @param {Object} body\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public addPushRule(scope: string, kind: string, ruleId: string, body: any, callback?: Callback): Promise<any> { // TODO: Types\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, body,\n );\n }\n\n /**\n * @param {string} scope\n * @param {string} kind\n * @param {string} ruleId\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public deletePushRule(scope: string, kind: string, ruleId: string, callback?: Callback): Promise<any> { // TODO: Types\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(callback, \"DELETE\", path);\n }\n\n /**\n * Enable or disable a push notification rule.\n * @param {string} scope\n * @param {string} kind\n * @param {string} ruleId\n * @param {boolean} enabled\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setPushRuleEnabled(\n scope: string,\n kind: string,\n ruleId: string,\n enabled: boolean,\n callback?: Callback,\n ): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, { \"enabled\": enabled },\n );\n }\n\n /**\n * Set the actions for a push notification rule.\n * @param {string} scope\n * @param {string} kind\n * @param {string} ruleId\n * @param {array} actions\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: result object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setPushRuleActions(\n scope: string,\n kind: string,\n ruleId: string,\n actions: string[],\n callback?: Callback,\n ): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(\n callback, \"PUT\", path, undefined, { \"actions\": actions },\n );\n }\n\n /**\n * Perform a server-side search.\n * @param {Object} opts\n * @param {string} opts.next_batch the batch token to pass in the query string\n * @param {Object} opts.body the JSON object to pass to the request body.\n * @param {module:client.callback} callback Optional.\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public search(\n opts: { body: any, next_batch?: string }, // eslint-disable-line camelcase\n callback?: Callback,\n ): Promise<any> { // TODO: Types\n const queryParams: any = {};\n if (opts.next_batch) {\n queryParams.next_batch = opts.next_batch;\n }\n return this.http.authedRequest(\n callback, \"POST\", \"/search\", queryParams, opts.body,\n );\n }\n\n /**\n * Upload keys\n *\n * @param {Object} content body of upload request\n *\n * @param {Object=} opts this method no longer takes any opts,\n * used to take opts.device_id but this was not removed from the spec as a redundant parameter\n *\n * @param {module:client.callback=} callback\n *\n * @return {Promise} Resolves: result object. Rejects: with\n * an error response ({@link module:http-api.MatrixError}).\n */\n public uploadKeysRequest(content: any, opts?: any, callback?: Callback): Promise<IKeysUploadResponse> {\n return this.http.authedRequest(callback, \"POST\", \"/keys/upload\", undefined, content);\n }\n\n public uploadKeySignatures(content: KeySignatures): Promise<IUploadKeySignaturesResponse> {\n return this.http.authedRequest(\n undefined, \"POST\", '/keys/signatures/upload', undefined,\n content, {\n prefix: PREFIX_UNSTABLE,\n },\n );\n }\n\n /**\n * Download device keys\n *\n * @param {string[]} userIds list of users to get keys for\n *\n * @param {Object=} opts\n *\n * @param {string=} opts.token sync token to pass in the query request, to help\n * the HS give the most recent results\n *\n * @return {Promise} Resolves: result object. Rejects: with\n * an error response ({@link module:http-api.MatrixError}).\n */\n public downloadKeysForUsers(userIds: string[], opts: { token?: string }): Promise<any> { // TODO: Types\n if (utils.isFunction(opts)) {\n // opts used to be 'callback'.\n throw new Error(\n 'downloadKeysForUsers no longer accepts a callback parameter',\n );\n }\n opts = opts || {};\n\n const content: any = {\n device_keys: {},\n };\n if ('token' in opts) {\n content.token = opts.token;\n }\n userIds.forEach((u) => {\n content.device_keys[u] = [];\n });\n\n return this.http.authedRequest(undefined, \"POST\", \"/keys/query\", undefined, content);\n }\n\n /**\n * Claim one-time keys\n *\n * @param {string[]} devices a list of [userId, deviceId] pairs\n *\n * @param {string} [keyAlgorithm = signed_curve25519] desired key type\n *\n * @param {number} [timeout] the time (in milliseconds) to wait for keys from remote\n * servers\n *\n * @return {Promise} Resolves: result object. Rejects: with\n * an error response ({@link module:http-api.MatrixError}).\n */\n public claimOneTimeKeys(devices: string[], keyAlgorithm = \"signed_curve25519\", timeout?: number): Promise<any> { // TODO: Types\n const queries = {};\n\n if (keyAlgorithm === undefined) {\n keyAlgorithm = \"signed_curve25519\";\n }\n\n for (let i = 0; i < devices.length; ++i) {\n const userId = devices[i][0];\n const deviceId = devices[i][1];\n const query = queries[userId] || {};\n queries[userId] = query;\n query[deviceId] = keyAlgorithm;\n }\n const content: any = { one_time_keys: queries };\n if (timeout) {\n content.timeout = timeout;\n }\n const path = \"/keys/claim\";\n return this.http.authedRequest(undefined, \"POST\", path, undefined, content);\n }\n\n /**\n * Ask the server for a list of users who have changed their device lists\n * between a pair of sync tokens\n *\n * @param {string} oldToken\n * @param {string} newToken\n *\n * @return {Promise} Resolves: result object. Rejects: with\n * an error response ({@link module:http-api.MatrixError}).\n */\n public getKeyChanges(oldToken: string, newToken: string): Promise<any> { // TODO: Types\n const qps = {\n from: oldToken,\n to: newToken,\n };\n\n const path = \"/keys/changes\";\n return this.http.authedRequest(undefined, \"GET\", path, qps, undefined);\n }\n\n public uploadDeviceSigningKeys(auth: any, keys: CrossSigningKeys): Promise<{}> { // TODO: types\n const data = Object.assign({}, keys);\n if (auth) Object.assign(data, { auth });\n return this.http.authedRequest(\n undefined, \"POST\", \"/keys/device_signing/upload\", undefined, data, {\n prefix: PREFIX_UNSTABLE,\n },\n );\n }\n\n /**\n * Register with an Identity Server using the OpenID token from the user's\n * Homeserver, which can be retrieved via\n * {@link module:client~MatrixClient#getOpenIdToken}.\n *\n * Note that the `/account/register` endpoint (as well as IS authentication in\n * general) was added as part of the v2 API version.\n *\n * @param {object} hsOpenIdToken\n * @return {Promise} Resolves: with object containing an Identity\n * Server access token.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public registerWithIdentityServer(hsOpenIdToken: any): Promise<any> { // TODO: Types\n if (!this.idBaseUrl) {\n throw new Error(\"No Identity Server base URL set\");\n }\n\n const uri = this.idBaseUrl + PREFIX_IDENTITY_V2 + \"/account/register\";\n return this.http.requestOtherUrl(\n undefined, \"POST\", uri,\n null, hsOpenIdToken,\n );\n }\n\n /**\n * Requests an email verification token directly from an identity server.\n *\n * This API is used as part of binding an email for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param {string} email The email address to request a token for\n * @param {string} clientSecret A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param {number} sendAttempt If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another email.\n * To request another email to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param {string} nextLink Optional If specified, the client will be redirected\n * to this link after validation.\n * @param {module:client.callback} callback Optional.\n * @param {string} identityAccessToken The `access_token` field of the identity\n * server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public async requestEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n callback?: Callback,\n identityAccessToken?: string,\n ): Promise<any> { // TODO: Types\n const params = {\n client_secret: clientSecret,\n email: email,\n send_attempt: sendAttempt,\n next_link: nextLink,\n };\n\n return await this.http.idServerRequest(\n callback, \"POST\", \"/validate/email/requestToken\",\n params, PREFIX_IDENTITY_V2, identityAccessToken,\n );\n }\n\n /**\n * Requests a MSISDN verification token directly from an identity server.\n *\n * This API is used as part of binding a MSISDN for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param {string} phoneCountry The ISO 3166-1 alpha-2 code for the country in\n * which phoneNumber should be parsed relative to.\n * @param {string} phoneNumber The phone number, in national or international\n * format\n * @param {string} clientSecret A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param {number} sendAttempt If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another SMS.\n * To request another SMS to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param {string} nextLink Optional If specified, the client will be redirected\n * to this link after validation.\n * @param {module:client.callback} callback Optional.\n * @param {string} identityAccessToken The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @return {Promise} Resolves: TODO\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public async requestMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n callback?: Callback,\n identityAccessToken?: string,\n ): Promise<any> { // TODO: Types\n const params = {\n client_secret: clientSecret,\n country: phoneCountry,\n phone_number: phoneNumber,\n send_attempt: sendAttempt,\n next_link: nextLink,\n };\n\n return await this.http.idServerRequest(\n callback, \"POST\", \"/validate/msisdn/requestToken\",\n params, PREFIX_IDENTITY_V2, identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to the identity server\n *\n * This is used when submitting the code sent by SMS to a phone number.\n * The ID server has an equivalent API for email but the js-sdk does\n * not expose this, since email is normally validated by the user clicking\n * a link rather than entering a code.\n *\n * @param {string} sid The sid given in the response to requestToken\n * @param {string} clientSecret A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param {string} msisdnToken The MSISDN token, as enetered by the user.\n * @param {string} identityAccessToken The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @return {Promise} Resolves: Object, currently with no parameters.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n * @throws Error if No ID server is set\n */\n public async submitMsisdnToken(\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n identityAccessToken: string,\n ): Promise<any> { // TODO: Types\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return await this.http.idServerRequest(\n undefined, \"POST\", \"/validate/msisdn/submitToken\",\n params, PREFIX_IDENTITY_V2, identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to an arbitrary URL.\n *\n * This is used when submitting the code sent by SMS to a phone number in the\n * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n * `submit_url` to specify where the token should be sent, and this helper can\n * be used to pass the token to this URL.\n *\n * @param {string} url The URL to submit the token to\n * @param {string} sid The sid given in the response to requestToken\n * @param {string} clientSecret A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param {string} msisdnToken The MSISDN token, as enetered by the user.\n *\n * @return {Promise} Resolves: Object, currently with no parameters.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public submitMsisdnTokenOtherUrl(\n url: string,\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n ): Promise<any> { // TODO: Types\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return this.http.requestOtherUrl(\n undefined, \"POST\", url, undefined, params,\n );\n }\n\n /**\n * Gets the V2 hashing information from the identity server. Primarily useful for\n * lookups.\n * @param {string} identityAccessToken The access token for the identity server.\n * @returns {Promise<object>} The hashing information for the identity server.\n */\n public getIdentityHashDetails(identityAccessToken: string): Promise<any> { // TODO: Types\n return this.http.idServerRequest(\n undefined, \"GET\", \"/hash_details\",\n null, PREFIX_IDENTITY_V2, identityAccessToken,\n );\n }\n\n /**\n * Performs a hashed lookup of addresses against the identity server. This is\n * only supported on identity servers which have at least the version 2 API.\n * @param {Array<Array<string,string>>} addressPairs An array of 2 element arrays.\n * The first element of each pair is the address, the second is the 3PID medium.\n * Eg: [\"email@example.org\", \"email\"]\n * @param {string} identityAccessToken The access token for the identity server.\n * @returns {Promise<Array<{address, mxid}>>} A collection of address mappings to\n * found MXIDs. Results where no user could be found will not be listed.\n */\n public async identityHashedLookup(\n addressPairs: [string, string][],\n identityAccessToken: string,\n ): Promise<{ address: string, mxid: string }[]> {\n const params = {\n // addresses: [\"email@example.org\", \"10005550000\"],\n // algorithm: \"sha256\",\n // pepper: \"abc123\"\n };\n\n // Get hash information first before trying to do a lookup\n const hashes = await this.getIdentityHashDetails(identityAccessToken);\n if (!hashes || !hashes['lookup_pepper'] || !hashes['algorithms']) {\n throw new Error(\"Unsupported identity server: bad response\");\n }\n\n params['pepper'] = hashes['lookup_pepper'];\n\n const localMapping = {\n // hashed identifier => plain text address\n // For use in this function's return format\n };\n\n // When picking an algorithm, we pick the hashed over no hashes\n if (hashes['algorithms'].includes('sha256')) {\n // Abuse the olm hashing\n const olmutil = new global.Olm.Utility();\n params[\"addresses\"] = addressPairs.map(p => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const hashed = olmutil.sha256(`${addr} ${med} ${params['pepper']}`)\n .replace(/\\+/g, '-').replace(/\\//g, '_'); // URL-safe base64\n // Map the hash to a known (case-sensitive) address. We use the case\n // sensitive version because the caller might be expecting that.\n localMapping[hashed] = p[0];\n return hashed;\n });\n params[\"algorithm\"] = \"sha256\";\n } else if (hashes['algorithms'].includes('none')) {\n params[\"addresses\"] = addressPairs.map(p => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const unhashed = `${addr} ${med}`;\n // Map the unhashed values to a known (case-sensitive) address. We use\n // the case sensitive version because the caller might be expecting that.\n localMapping[unhashed] = p[0];\n return unhashed;\n });\n params[\"algorithm\"] = \"none\";\n } else {\n throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n }\n\n const response = await this.http.idServerRequest(\n undefined, \"POST\", \"/lookup\",\n params, PREFIX_IDENTITY_V2, identityAccessToken,\n );\n\n if (!response || !response['mappings']) return []; // no results\n\n const foundAddresses = [/* {address: \"plain@example.org\", mxid} */];\n for (const hashed of Object.keys(response['mappings'])) {\n const mxid = response['mappings'][hashed];\n const plainAddress = localMapping[hashed];\n if (!plainAddress) {\n throw new Error(\"Identity server returned more results than expected\");\n }\n\n foundAddresses.push({ address: plainAddress, mxid });\n }\n return foundAddresses;\n }\n\n /**\n * Looks up the public Matrix ID mapping for a given 3rd party\n * identifier from the Identity Server\n *\n * @param {string} medium The medium of the threepid, eg. 'email'\n * @param {string} address The textual address of the threepid\n * @param {module:client.callback} callback Optional.\n * @param {string} identityAccessToken The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @return {Promise} Resolves: A threepid mapping\n * object or the empty object if no mapping\n * exists\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async lookupThreePid(\n medium: string,\n address: string,\n callback?: Callback,\n identityAccessToken?: string,\n ): Promise<any> { // TODO: Types\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n [[address, medium]], identityAccessToken,\n );\n const result = response.find(p => p.address === address);\n if (!result) {\n if (callback) callback(null, {});\n return {};\n }\n\n const mapping = {\n address,\n medium,\n mxid: result.mxid,\n\n // We can't reasonably fill these parameters:\n // not_before\n // not_after\n // ts\n // signatures\n };\n\n if (callback) callback(null, mapping);\n return mapping;\n }\n\n /**\n * Looks up the public Matrix ID mappings for multiple 3PIDs.\n *\n * @param {Array.<Array.<string>>} query Array of arrays containing\n * [medium, address]\n * @param {string} identityAccessToken The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @return {Promise} Resolves: Lookup results from IS.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public async bulkLookupThreePids(query: [string, string][], identityAccessToken: string): Promise<any> { // TODO: Types\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n // We have to reverse the query order to get [address, medium] pairs\n query.map(p => [p[1], p[0]]), identityAccessToken,\n );\n\n const v1results = [];\n for (const mapping of response) {\n const originalQuery = query.find(p => p[1] === mapping.address);\n if (!originalQuery) {\n throw new Error(\"Identity sever returned unexpected results\");\n }\n\n v1results.push([\n originalQuery[0], // medium\n mapping.address,\n mapping.mxid,\n ]);\n }\n\n return { threepids: v1results };\n }\n\n /**\n * Get account info from the Identity Server. This is useful as a neutral check\n * to verify that other APIs are likely to approve access by testing that the\n * token is valid, terms have been agreed, etc.\n *\n * @param {string} identityAccessToken The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @return {Promise} Resolves: an object with account info.\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getIdentityAccount(identityAccessToken: string): Promise<any> { // TODO: Types\n return this.http.idServerRequest(\n undefined, \"GET\", \"/account\",\n undefined, PREFIX_IDENTITY_V2, identityAccessToken,\n );\n }\n\n /**\n * Send an event to a specific list of devices\n *\n * @param {string} eventType type of event to send\n * @param {Object.<string, Object<string, Object>>} contentMap\n * content to send. Map from user_id to device_id to content object.\n * @param {string=} txnId transaction id. One will be made up if not\n * supplied.\n * @return {Promise} Resolves to the result object\n */\n public sendToDevice(\n eventType: string,\n contentMap: { [userId: string]: { [deviceId: string]: Record<string, any> } },\n txnId?: string,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n $eventType: eventType,\n $txnId: txnId ? txnId : this.makeTxnId(),\n });\n\n const body = {\n messages: contentMap,\n };\n\n const targets = Object.keys(contentMap).reduce((obj, key) => {\n obj[key] = Object.keys(contentMap[key]);\n return obj;\n }, {});\n logger.log(`PUT ${path}`, targets);\n\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, body);\n }\n\n /**\n * Get the third party protocols that can be reached using\n * this HS\n * @return {Promise} Resolves to the result object\n */\n public getThirdpartyProtocols(): Promise<any> { // TODO: Types\n return this.http.authedRequest(\n undefined, \"GET\", \"/thirdparty/protocols\", undefined, undefined,\n ).then((response) => {\n // sanity check\n if (!response || typeof (response) !== 'object') {\n throw new Error(\n `/thirdparty/protocols did not return an object: ${response}`,\n );\n }\n return response;\n });\n }\n\n /**\n * Get information on how a specific place on a third party protocol\n * may be reached.\n * @param {string} protocol The protocol given in getThirdpartyProtocols()\n * @param {object} params Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @return {Promise} Resolves to the result object\n */\n public getThirdpartyLocation(protocol: string, params: any): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(undefined, \"GET\", path, params, undefined);\n }\n\n /**\n * Get information on how a specific user on a third party protocol\n * may be reached.\n * @param {string} protocol The protocol given in getThirdpartyProtocols()\n * @param {object} params Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @return {Promise} Resolves to the result object\n */\n public getThirdpartyUser(protocol: string, params: any): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(undefined, \"GET\", path, params, undefined);\n }\n\n public getTerms(serviceType: SERVICE_TYPES, baseUrl: string): Promise<any> { // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n return this.http.requestOtherUrl(\n undefined, 'GET', url,\n );\n }\n\n public agreeToTerms(\n serviceType: SERVICE_TYPES,\n baseUrl: string,\n accessToken: string,\n termsUrls: string[],\n ): Promise<any> { // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n const headers = {\n Authorization: \"Bearer \" + accessToken,\n };\n return this.http.requestOtherUrl(\n undefined, 'POST', url, null, { user_accepts: termsUrls }, { headers },\n );\n }\n\n /**\n * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n * @param {string} roomId The room in which the event being reported is located.\n * @param {string} eventId The event to report.\n * @param {number} score The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n * @param {string} reason The reason the content is being reported. May be blank.\n * @returns {Promise} Resolves to an empty object if successful\n */\n public reportEvent(roomId: string, eventId: string, score: number, reason: string): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n\n return this.http.authedRequest(undefined, \"POST\", path, null, { score, reason });\n }\n\n /**\n * Fetches or paginates a summary of a space as defined by MSC2946\n * @param {string} roomId The ID of the space-room to use as the root of the summary.\n * @param {number?} maxRoomsPerSpace The maximum number of rooms to return per subspace.\n * @param {boolean?} suggestedOnly Whether to only return rooms with suggested=true.\n * @param {boolean?} autoJoinOnly Whether to only return rooms with auto_join=true.\n * @param {number?} limit The maximum number of rooms to return in total.\n * @param {string?} batch The opaque token to paginate a previous summary request.\n * @returns {Promise} the response, with next_batch, rooms, events fields.\n */\n public getSpaceSummary(\n roomId: string,\n maxRoomsPerSpace?: number,\n suggestedOnly?: boolean,\n autoJoinOnly?: boolean,\n limit?: number,\n batch?: string,\n ): Promise<any> { // TODO: Types\n const path = utils.encodeUri(\"/rooms/$roomId/spaces\", {\n $roomId: roomId,\n });\n\n return this.http.authedRequest(undefined, \"POST\", path, null, {\n max_rooms_per_space: maxRoomsPerSpace,\n suggested_only: suggestedOnly,\n auto_join_only: autoJoinOnly,\n limit,\n batch,\n }, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2946\",\n });\n }\n\n /**\n * Creates a new file tree space with the given name. The client will pick\n * defaults for how it expects to be able to support the remaining API offered\n * by the returned class.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param {string} name The name of the tree space.\n * @returns {Promise<MSC3089TreeSpace>} Resolves to the created space.\n */\n public async unstableCreateFileTree(name: string): Promise<MSC3089TreeSpace> {\n const { room_id: roomId } = await this.createRoom({\n name: name,\n preset: Preset.PrivateChat,\n power_level_content_override: {\n ...DEFAULT_TREE_POWER_LEVELS_TEMPLATE,\n users: {\n [this.getUserId()]: 100,\n },\n },\n creation_content: {\n [RoomCreateTypeField]: RoomType.Space,\n },\n initial_state: [\n {\n type: UNSTABLE_MSC3088_PURPOSE.name,\n state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n content: {\n [UNSTABLE_MSC3088_ENABLED.name]: true,\n },\n },\n {\n type: EventType.RoomEncryption,\n state_key: \"\",\n content: {\n algorithm: olmlib.MEGOLM_ALGORITHM,\n },\n },\n ],\n });\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n * does not appear to be a tree space then null is returned.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param {string} roomId The room ID to get a tree space reference for.\n * @returns {MSC3089TreeSpace} The tree space, or null if not a tree space.\n */\n public unstableGetFileTreeSpace(roomId: string): MSC3089TreeSpace {\n const room = this.getRoom(roomId);\n if (!room) return null;\n\n const createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n const purposeEvent = room.currentState.getStateEvents(\n UNSTABLE_MSC3088_PURPOSE.name,\n UNSTABLE_MSC3089_TREE_SUBTYPE.name);\n\n if (!createEvent) throw new Error(\"Expected single room create event\");\n\n if (!purposeEvent?.getContent()?.[UNSTABLE_MSC3088_ENABLED.name]) return null;\n if (createEvent.getContent()?.[RoomCreateTypeField] !== RoomType.Space) return null;\n\n return new MSC3089TreeSpace(this, roomId);\n }\n\n // TODO: Remove this warning, alongside the functions\n // See https://github.com/vector-im/element-web/issues/17532\n // ======================================================\n // ** ANCIENT APIS BELOW **\n // ======================================================\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Group summary object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getGroupSummary(groupId: string): Promise<any> {\n const path = utils.encodeUri(\"/groups/$groupId/summary\", { $groupId: groupId });\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Group profile object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getGroupProfile(groupId: string): Promise<any> {\n const path = utils.encodeUri(\"/groups/$groupId/profile\", { $groupId: groupId });\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {string} groupId\n * @param {Object} profile The group profile object\n * @param {string=} profile.name Name of the group\n * @param {string=} profile.avatar_url MXC avatar URL\n * @param {string=} profile.short_description A short description of the room\n * @param {string=} profile.long_description A longer HTML description of the room\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setGroupProfile(groupId: string, profile: any): Promise<any> {\n const path = utils.encodeUri(\"/groups/$groupId/profile\", { $groupId: groupId });\n return this.http.authedRequest(\n undefined, \"POST\", path, undefined, profile,\n );\n }\n\n /**\n * @param {string} groupId\n * @param {object} policy The join policy for the group. Must include at\n * least a 'type' field which is 'open' if anyone can join the group\n * the group without prior approval, or 'invite' if an invite is\n * required to join.\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setGroupJoinPolicy(groupId: string, policy: any): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/settings/m.join_policy\",\n { $groupId: groupId },\n );\n return this.http.authedRequest(\n undefined, \"PUT\", path, undefined, {\n 'm.join_policy': policy,\n },\n );\n }\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Group users list object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getGroupUsers(groupId: string): Promise<any> {\n const path = utils.encodeUri(\"/groups/$groupId/users\", { $groupId: groupId });\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Group users list object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getGroupInvitedUsers(groupId: string): Promise<any> {\n const path = utils.encodeUri(\"/groups/$groupId/invited_users\", { $groupId: groupId });\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Group rooms list object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getGroupRooms(groupId: string): Promise<any> {\n const path = utils.encodeUri(\"/groups/$groupId/rooms\", { $groupId: groupId });\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {string} groupId\n * @param {string} userId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public inviteUserToGroup(groupId: string, userId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/admin/users/invite/$userId\",\n { $groupId: groupId, $userId: userId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {string} userId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public removeUserFromGroup(groupId: string, userId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/admin/users/remove/$userId\",\n { $groupId: groupId, $userId: userId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {string} userId\n * @param {string} roleId Optional.\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public addUserToGroupSummary(groupId: string, userId: string, roleId: string): Promise<any> {\n const path = utils.encodeUri(\n roleId ?\n \"/groups/$groupId/summary/$roleId/users/$userId\" :\n \"/groups/$groupId/summary/users/$userId\",\n { $groupId: groupId, $roleId: roleId, $userId: userId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {string} userId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public removeUserFromGroupSummary(groupId: string, userId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/summary/users/$userId\",\n { $groupId: groupId, $userId: userId },\n );\n return this.http.authedRequest(undefined, \"DELETE\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {string} roomId\n * @param {string} categoryId Optional.\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public addRoomToGroupSummary(groupId: string, roomId: string, categoryId: string): Promise<any> {\n const path = utils.encodeUri(\n categoryId ?\n \"/groups/$groupId/summary/$categoryId/rooms/$roomId\" :\n \"/groups/$groupId/summary/rooms/$roomId\",\n { $groupId: groupId, $categoryId: categoryId, $roomId: roomId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {string} roomId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public removeRoomFromGroupSummary(groupId: string, roomId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/summary/rooms/$roomId\",\n { $groupId: groupId, $roomId: roomId },\n );\n return this.http.authedRequest(undefined, \"DELETE\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {string} roomId\n * @param {boolean} isPublic Whether the room-group association is visible to non-members\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public addRoomToGroup(groupId: string, roomId: string, isPublic: boolean): Promise<any> {\n if (isPublic === undefined) {\n isPublic = true;\n }\n const path = utils.encodeUri(\n \"/groups/$groupId/admin/rooms/$roomId\",\n { $groupId: groupId, $roomId: roomId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined,\n { \"m.visibility\": { type: isPublic ? \"public\" : \"private\" } },\n );\n }\n\n /**\n * Configure the visibility of a room-group association.\n * @param {string} groupId\n * @param {string} roomId\n * @param {boolean} isPublic Whether the room-group association is visible to non-members\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public updateGroupRoomVisibility(groupId: string, roomId: string, isPublic: boolean): Promise<any> {\n // NB: The /config API is generic but there's not much point in exposing this yet as synapse\n // is the only server to implement this. In future we should consider an API that allows\n // arbitrary configuration, i.e. \"config/$configKey\".\n\n const path = utils.encodeUri(\n \"/groups/$groupId/admin/rooms/$roomId/config/m.visibility\",\n { $groupId: groupId, $roomId: roomId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined,\n { type: isPublic ? \"public\" : \"private\" },\n );\n }\n\n /**\n * @param {string} groupId\n * @param {string} roomId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public removeRoomFromGroup(groupId: string, roomId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/admin/rooms/$roomId\",\n { $groupId: groupId, $roomId: roomId },\n );\n return this.http.authedRequest(undefined, \"DELETE\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @param {Object} opts Additional options to send alongside the acceptance.\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public acceptGroupInvite(groupId: string, opts = null): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/self/accept_invite\",\n { $groupId: groupId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, opts || {});\n }\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public joinGroup(groupId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/self/join\",\n { $groupId: groupId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {});\n }\n\n /**\n * @param {string} groupId\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public leaveGroup(groupId: string): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/self/leave\",\n { $groupId: groupId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {});\n }\n\n /**\n * @return {Promise} Resolves: The groups to which the user is joined\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getJoinedGroups(): Promise<any> {\n const path = utils.encodeUri(\"/joined_groups\", {});\n return this.http.authedRequest(undefined, \"GET\", path);\n }\n\n /**\n * @param {Object} content Request content\n * @param {string} content.localpart The local part of the desired group ID\n * @param {Object} content.profile Group profile object\n * @return {Promise} Resolves: Object with key group_id: id of the created group\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public createGroup(content: any): Promise<any> {\n const path = utils.encodeUri(\"/create_group\", {});\n return this.http.authedRequest(\n undefined, \"POST\", path, undefined, content,\n );\n }\n\n /**\n * @param {string[]} userIds List of user IDs\n * @return {Promise} Resolves: Object as exmaple below\n *\n * {\n * \"users\": {\n * \"@bob:example.com\": {\n * \"+example:example.com\"\n * }\n * }\n * }\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public getPublicisedGroups(userIds: string[]): Promise<any> {\n const path = utils.encodeUri(\"/publicised_groups\", {});\n return this.http.authedRequest(\n undefined, \"POST\", path, undefined, { user_ids: userIds },\n );\n }\n\n /**\n * @param {string} groupId\n * @param {boolean} isPublic Whether the user's membership of this group is made public\n * @return {Promise} Resolves: Empty object\n * @return {module:http-api.MatrixError} Rejects: with an error response.\n */\n public setGroupPublicity(groupId: string, isPublic: boolean): Promise<any> {\n const path = utils.encodeUri(\n \"/groups/$groupId/self/update_publicity\",\n { $groupId: groupId },\n );\n return this.http.authedRequest(undefined, \"PUT\", path, undefined, {\n publicise: isPublic,\n });\n }\n}\n\n/**\n * Fires whenever the SDK receives a new event.\n * <p>\n * This is only fired for live events received via /sync - it is not fired for\n * events received over context, search, or pagination APIs.\n *\n * @event module:client~MatrixClient#\"event\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @example\n * matrixClient.on(\"event\", function(event){\n * var sender = event.getSender();\n * });\n */\n\n/**\n * Fires whenever the SDK receives a new to-device event.\n * @event module:client~MatrixClient#\"toDeviceEvent\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @example\n * matrixClient.on(\"toDeviceEvent\", function(event){\n * var sender = event.getSender();\n * });\n */\n\n/**\n * Fires whenever the SDK's syncing state is updated. The state can be one of:\n * <ul>\n *\n * <li>PREPARED: The client has synced with the server at least once and is\n * ready for methods to be called on it. This will be immediately followed by\n * a state of SYNCING. <i>This is the equivalent of \"syncComplete\" in the\n * previous API.</i></li>\n *\n * <li>CATCHUP: The client has detected the connection to the server might be\n * available again and will now try to do a sync again. As this sync might take\n * a long time (depending how long ago was last synced, and general server\n * performance) the client is put in this mode so the UI can reflect trying\n * to catch up with the server after losing connection.</li>\n *\n * <li>SYNCING : The client is currently polling for new events from the server.\n * This will be called <i>after</i> processing latest events from a sync.</li>\n *\n * <li>ERROR : The client has had a problem syncing with the server. If this is\n * called <i>before</i> PREPARED then there was a problem performing the initial\n * sync. If this is called <i>after</i> PREPARED then there was a problem polling\n * the server for updates. This may be called multiple times even if the state is\n * already ERROR. <i>This is the equivalent of \"syncError\" in the previous\n * API.</i></li>\n *\n * <li>RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n * should be considered erroneous.\n * </li>\n *\n * <li>STOPPED: The client has stopped syncing with server due to stopClient\n * being called.\n * </li>\n * </ul>\n * State transition diagram:\n * <pre>\n * +---->STOPPED\n * |\n * +----->PREPARED -------> SYNCING <--+\n * | ^ | ^ |\n * | CATCHUP ----------+ | | |\n * | ^ V | |\n * null ------+ | +------- RECONNECTING |\n * | V V |\n * +------->ERROR ---------------------+\n *\n * NB: 'null' will never be emitted by this event.\n *\n * </pre>\n * Transitions:\n * <ul>\n *\n * <li><code>null -> PREPARED</code> : Occurs when the initial sync is completed\n * first time. This involves setting up filters and obtaining push rules.\n *\n * <li><code>null -> ERROR</code> : Occurs when the initial sync failed first time.\n *\n * <li><code>ERROR -> PREPARED</code> : Occurs when the initial sync succeeds\n * after previously failing.\n *\n * <li><code>PREPARED -> SYNCING</code> : Occurs immediately after transitioning\n * to PREPARED. Starts listening for live updates rather than catching up.\n *\n * <li><code>SYNCING -> RECONNECTING</code> : Occurs when the live update fails.\n *\n * <li><code>RECONNECTING -> RECONNECTING</code> : Can occur if the update calls\n * continue to fail, but the keepalive calls (to /versions) succeed.\n *\n * <li><code>RECONNECTING -> ERROR</code> : Occurs when the keepalive call also fails\n *\n * <li><code>ERROR -> SYNCING</code> : Occurs when the client has performed a\n * live update after having previously failed.\n *\n * <li><code>ERROR -> ERROR</code> : Occurs when the client has failed to keepalive\n * for a second time or more.</li>\n *\n * <li><code>SYNCING -> SYNCING</code> : Occurs when the client has performed a live\n * update. This is called <i>after</i> processing.</li>\n *\n * <li><code>* -> STOPPED</code> : Occurs once the client has stopped syncing or\n * trying to sync after stopClient has been called.</li>\n * </ul>\n *\n * @event module:client~MatrixClient#\"sync\"\n *\n * @param {string} state An enum representing the syncing state. One of \"PREPARED\",\n * \"SYNCING\", \"ERROR\", \"STOPPED\".\n *\n * @param {?string} prevState An enum representing the previous syncing state.\n * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" <b>or null</b>.\n *\n * @param {?Object} data Data about this transition.\n *\n * @param {MatrixError} data.error The matrix error if <code>state=ERROR</code>.\n *\n * @param {String} data.oldSyncToken The 'since' token passed to /sync.\n * <code>null</code> for the first successful sync since this client was\n * started. Only present if <code>state=PREPARED</code> or\n * <code>state=SYNCING</code>.\n *\n * @param {String} data.nextSyncToken The 'next_batch' result from /sync, which\n * will become the 'since' token for the next call to /sync. Only present if\n * <code>state=PREPARED</code> or <code>state=SYNCING</code>.\n *\n * @param {boolean} data.catchingUp True if we are working our way through a\n * backlog of events after connecting. Only present if <code>state=SYNCING</code>.\n *\n * @example\n * matrixClient.on(\"sync\", function(state, prevState, data) {\n * switch (state) {\n * case \"ERROR\":\n * // update UI to say \"Connection Lost\"\n * break;\n * case \"SYNCING\":\n * // update UI to remove any \"Connection Lost\" message\n * break;\n * case \"PREPARED\":\n * // the client instance is ready to be queried.\n * var rooms = matrixClient.getRooms();\n * break;\n * }\n * });\n */\n\n/**\n * Fires whenever the sdk learns about a new group. <strong>This event\n * is experimental and may change.</strong>\n * @event module:client~MatrixClient#\"Group\"\n * @param {Group} group The newly created, fully populated group.\n * @example\n * matrixClient.on(\"Group\", function(group){\n * var groupId = group.groupId;\n * });\n */\n\n/**\n * Fires whenever a new Room is added. This will fire when you are invited to a\n * room, as well as when you join a room. <strong>This event is experimental and\n * may change.</strong>\n * @event module:client~MatrixClient#\"Room\"\n * @param {Room} room The newly created, fully populated room.\n * @example\n * matrixClient.on(\"Room\", function(room){\n * var roomId = room.roomId;\n * });\n */\n\n/**\n * Fires whenever a Room is removed. This will fire when you forget a room.\n * <strong>This event is experimental and may change.</strong>\n * @event module:client~MatrixClient#\"deleteRoom\"\n * @param {string} roomId The deleted room ID.\n * @example\n * matrixClient.on(\"deleteRoom\", function(roomId){\n * // update UI from getRooms()\n * });\n */\n\n/**\n * Fires whenever an incoming call arrives.\n * @event module:client~MatrixClient#\"Call.incoming\"\n * @param {module:webrtc/call~MatrixCall} call The incoming call.\n * @example\n * matrixClient.on(\"Call.incoming\", function(call){\n * call.answer(); // auto-answer\n * });\n */\n\n/**\n * Fires whenever the login session the JS SDK is using is no\n * longer valid and the user must log in again.\n * NB. This only fires when action is required from the user, not\n * when then login session can be renewed by using a refresh token.\n * @event module:client~MatrixClient#\"Session.logged_out\"\n * @example\n * matrixClient.on(\"Session.logged_out\", function(errorObj){\n * // show the login screen\n * });\n */\n\n/**\n * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response\n * to a HTTP request.\n * @event module:client~MatrixClient#\"no_consent\"\n * @example\n * matrixClient.on(\"no_consent\", function(message, contentUri) {\n * console.info(message + ' Go to ' + contentUri);\n * });\n */\n\n/**\n * Fires when a device is marked as verified/unverified/blocked/unblocked by\n * {@link module:client~MatrixClient#setDeviceVerified|MatrixClient.setDeviceVerified} or\n * {@link module:client~MatrixClient#setDeviceBlocked|MatrixClient.setDeviceBlocked}.\n *\n * @event module:client~MatrixClient#\"deviceVerificationChanged\"\n * @param {string} userId the owner of the verified device\n * @param {string} deviceId the id of the verified device\n * @param {module:crypto/deviceinfo} deviceInfo updated device information\n */\n\n/**\n * Fires when the trust status of a user changes\n * If userId is the userId of the logged in user, this indicated a change\n * in the trust status of the cross-signing data on the account.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @event module:client~MatrixClient#\"userTrustStatusChanged\"\n * @param {string} userId the userId of the user in question\n * @param {UserTrustLevel} trustLevel The new trust level of the user\n */\n\n/**\n * Fires when the user's cross-signing keys have changed or cross-signing\n * has been enabled/disabled. The client can use getStoredCrossSigningForUser\n * with the user ID of the logged in user to check if cross-signing is\n * enabled on the account. If enabled, it can test whether the current key\n * is trusted using with checkUserTrust with the user ID of the logged\n * in user. The checkOwnCrossSigningTrust function may be used to reconcile\n * the trust in the account key.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @event module:client~MatrixClient#\"crossSigning.keysChanged\"\n */\n\n/**\n * Fires whenever new user-scoped account_data is added.\n * @event module:client~MatrixClient#\"accountData\"\n * @param {MatrixEvent} event The event describing the account_data just added\n * @param {MatrixEvent} event The previous account data, if known.\n * @example\n * matrixClient.on(\"accountData\", function(event, oldEvent){\n * myAccountData[event.type] = event.content;\n * });\n */\n\n/**\n * Fires whenever the stored devices for a user have changed\n * @event module:client~MatrixClient#\"crypto.devicesUpdated\"\n * @param {String[]} users A list of user IDs that were updated\n * @param {boolean} initialFetch If true, the store was empty (apart\n * from our own device) and has been seeded.\n */\n\n/**\n * Fires whenever the stored devices for a user will be updated\n * @event module:client~MatrixClient#\"crypto.willUpdateDevices\"\n * @param {String[]} users A list of user IDs that will be updated\n * @param {boolean} initialFetch If true, the store is empty (apart\n * from our own device) and is being seeded.\n */\n\n/**\n * Fires whenever the status of e2e key backup changes, as returned by getKeyBackupEnabled()\n * @event module:client~MatrixClient#\"crypto.keyBackupStatus\"\n * @param {boolean} enabled true if key backup has been enabled, otherwise false\n * @example\n * matrixClient.on(\"crypto.keyBackupStatus\", function(enabled){\n * if (enabled) {\n * [...]\n * }\n * });\n */\n\n/**\n * Fires when we want to suggest to the user that they restore their megolm keys\n * from backup or by cross-signing the device.\n *\n * @event module:client~MatrixClient#\"crypto.suggestKeyRestore\"\n */\n\n/**\n * Fires when a key verification is requested.\n * @event module:client~MatrixClient#\"crypto.verification.request\"\n * @param {object} data\n * @param {MatrixEvent} data.event the original verification request message\n * @param {Array} data.methods the verification methods that can be used\n * @param {Number} data.timeout the amount of milliseconds that should be waited\n * before cancelling the request automatically.\n * @param {Function} data.beginKeyVerification a function to call if a key\n * verification should be performed. The function takes one argument: the\n * name of the key verification method (taken from data.methods) to use.\n * @param {Function} data.cancel a function to call if the key verification is\n * rejected.\n */\n\n/**\n * Fires when a key verification is requested with an unknown method.\n * @event module:client~MatrixClient#\"crypto.verification.request.unknown\"\n * @param {string} userId the user ID who requested the key verification\n * @param {Function} cancel a function that will send a cancellation message to\n * reject the key verification.\n */\n\n/**\n * Fires when a secret request has been cancelled. If the client is prompting\n * the user to ask whether they want to share a secret, the prompt can be\n * dismissed.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @event module:client~MatrixClient#\"crypto.secrets.requestCancelled\"\n * @param {object} data\n * @param {string} data.user_id The user ID of the client that had requested the secret.\n * @param {string} data.device_id The device ID of the client that had requested the\n * secret.\n * @param {string} data.request_id The ID of the original request.\n */\n\n/**\n * Fires when the client .well-known info is fetched.\n *\n * @event module:client~MatrixClient#\"WellKnown.client\"\n * @param {object} data The JSON object returned by the server\n */\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module ContentHelpers */\n\n/**\n * Generates the content for a HTML Message event\n * @param {string} body the plaintext body of the message\n * @param {string} htmlBody the HTML representation of the message\n * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}\n */\nexport function makeHtmlMessage(body: string, htmlBody: string) {\n return {\n msgtype: \"m.text\",\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Notice event\n * @param {string} body the plaintext body of the notice\n * @param {string} htmlBody the HTML representation of the notice\n * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}\n */\nexport function makeHtmlNotice(body: string, htmlBody: string) {\n return {\n msgtype: \"m.notice\",\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Emote event\n * @param {string} body the plaintext body of the emote\n * @param {string} htmlBody the HTML representation of the emote\n * @returns {{msgtype: string, format: string, body: string, formatted_body: string}}\n */\nexport function makeHtmlEmote(body: string, htmlBody: string) {\n return {\n msgtype: \"m.emote\",\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a Plaintext Message event\n * @param {string} body the plaintext body of the emote\n * @returns {{msgtype: string, body: string}}\n */\nexport function makeTextMessage(body: string) {\n return {\n msgtype: \"m.text\",\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Notice event\n * @param {string} body the plaintext body of the notice\n * @returns {{msgtype: string, body: string}}\n */\nexport function makeNotice(body: string) {\n return {\n msgtype: \"m.notice\",\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Emote event\n * @param {string} body the plaintext body of the emote\n * @returns {{msgtype: string, body: string}}\n */\nexport function makeEmoteMessage(body: string) {\n return {\n msgtype: \"m.emote\",\n body: body,\n };\n}\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n/**\n * @module content-repo\n */\n\nimport * as utils from \"./utils\";\n\n/**\n * Get the HTTP URL for an MXC URI.\n * @param {string} baseUrl The base homeserver url which has a content repo.\n * @param {string} mxc The mxc:// URI.\n * @param {Number} width The desired width of the thumbnail.\n * @param {Number} height The desired height of the thumbnail.\n * @param {string} resizeMethod The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param {Boolean} allowDirectLinks If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return the emptry string\n * for such URLs.\n * @return {string} The complete URL to the content.\n */\nexport function getHttpUriForMxc(\n baseUrl: string,\n mxc: string,\n width: number,\n height: number,\n resizeMethod: string,\n allowDirectLinks = false,\n): string {\n if (typeof mxc !== \"string\" || !mxc) {\n return '';\n }\n if (mxc.indexOf(\"mxc://\") !== 0) {\n if (allowDirectLinks) {\n return mxc;\n } else {\n return '';\n }\n }\n let serverAndMediaId = mxc.slice(6); // strips mxc://\n let prefix = \"/_matrix/media/r0/download/\";\n const params = {};\n\n if (width) {\n params[\"width\"] = Math.round(width);\n }\n if (height) {\n params[\"height\"] = Math.round(height);\n }\n if (resizeMethod) {\n params[\"method\"] = resizeMethod;\n }\n if (Object.keys(params).length > 0) {\n // these are thumbnailing params so they probably want the\n // thumbnailing API...\n prefix = \"/_matrix/media/r0/thumbnail/\";\n }\n\n const fragmentOffset = serverAndMediaId.indexOf(\"#\");\n let fragment = \"\";\n if (fragmentOffset >= 0) {\n fragment = serverAndMediaId.substr(fragmentOffset);\n serverAndMediaId = serverAndMediaId.substr(0, fragmentOffset);\n }\n\n const urlParams = (Object.keys(params).length === 0 ? \"\" : (\"?\" + utils.encodeParams(params)));\n return baseUrl + prefix + serverAndMediaId + urlParams + fragment;\n}\n",
"/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Cross signing methods\n * @module crypto/CrossSigning\n */\n\nimport { EventEmitter } from 'events';\n\nimport { decodeBase64, encodeBase64, pkSign, pkVerify } from './olmlib';\nimport { logger } from '../logger';\nimport { IndexedDBCryptoStore } from '../crypto/store/indexeddb-crypto-store';\nimport { decryptAES, encryptAES } from './aes';\nimport { PkSigning } from \"@matrix-org/olm\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { SecretStorage } from \"./SecretStorage\";\nimport { CryptoStore, ICrossSigningKey, ISignedKey, MatrixClient } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { ICryptoCallbacks } from \"../matrix\";\nimport { ISignatures } from \"../@types/signed\";\n\nconst KEY_REQUEST_TIMEOUT_MS = 1000 * 60;\n\nfunction publicKeyFromKeyInfo(keyInfo: ICrossSigningKey): string {\n // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n // We assume only a single key, and we want the bare form without type\n // prefix, so we select the values.\n return Object.values(keyInfo.keys)[0];\n}\n\nexport interface ICacheCallbacks {\n getCrossSigningKeyCache?(type: string, expectedPublicKey?: string): Promise<Uint8Array>;\n storeCrossSigningKeyCache?(type: string, key: Uint8Array): Promise<void>;\n}\n\nexport class CrossSigningInfo extends EventEmitter {\n public keys: Record<string, ICrossSigningKey> = {};\n public firstUse = true;\n // This tracks whether we've ever verified this user with any identity.\n // When you verify a user, any devices online at the time that receive\n // the verifying signature via the homeserver will latch this to true\n // and can use it in the future to detect cases where the user has\n // become unverified later for any reason.\n private crossSigningVerifiedBefore = false;\n\n /**\n * Information about a user's cross-signing keys\n *\n * @class\n *\n * @param {string} userId the user that the information is about\n * @param {object} callbacks Callbacks used to interact with the app\n * Requires getCrossSigningKey and saveCrossSigningKeys\n * @param {object} cacheCallbacks Callbacks used to interact with the cache\n */\n constructor(\n public readonly userId: string,\n private callbacks: ICryptoCallbacks = {},\n private cacheCallbacks: ICacheCallbacks = {},\n ) {\n super();\n }\n\n public static fromStorage(obj: object, userId: string): CrossSigningInfo {\n const res = new CrossSigningInfo(userId);\n for (const prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n res[prop] = obj[prop];\n }\n }\n return res;\n }\n\n public toStorage(): object {\n return {\n keys: this.keys,\n firstUse: this.firstUse,\n crossSigningVerifiedBefore: this.crossSigningVerifiedBefore,\n };\n }\n\n /**\n * Calls the app callback to ask for a private key\n *\n * @param {string} type The key type (\"master\", \"self_signing\", or \"user_signing\")\n * @param {string} expectedPubkey The matching public key or undefined to use\n * the stored public key for the given key type.\n * @returns {Array} An array with [ public key, Olm.PkSigning ]\n */\n public async getCrossSigningKey(type: string, expectedPubkey?: string): Promise<[string, PkSigning]> {\n const shouldCache = [\"master\", \"self_signing\", \"user_signing\"].indexOf(type) >= 0;\n\n if (!this.callbacks.getCrossSigningKey) {\n throw new Error(\"No getCrossSigningKey callback supplied\");\n }\n\n if (expectedPubkey === undefined) {\n expectedPubkey = this.getId(type);\n }\n\n function validateKey(key: Uint8Array): [string, PkSigning] {\n if (!key) return;\n const signing = new global.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(key);\n if (gotPubkey === expectedPubkey) {\n return [gotPubkey, signing];\n }\n signing.free();\n }\n\n let privkey;\n if (this.cacheCallbacks.getCrossSigningKeyCache && shouldCache) {\n privkey = await this.cacheCallbacks.getCrossSigningKeyCache(type, expectedPubkey);\n }\n\n const cacheresult = validateKey(privkey);\n if (cacheresult) {\n return cacheresult;\n }\n\n privkey = await this.callbacks.getCrossSigningKey(type, expectedPubkey);\n const result = validateKey(privkey);\n if (result) {\n if (this.cacheCallbacks.storeCrossSigningKeyCache && shouldCache) {\n await this.cacheCallbacks.storeCrossSigningKeyCache(type, privkey);\n }\n return result;\n }\n\n /* No keysource even returned a key */\n if (!privkey) {\n throw new Error(\n \"getCrossSigningKey callback for \" + type + \" returned falsey\",\n );\n }\n\n /* We got some keys from the keysource, but none of them were valid */\n throw new Error(\n \"Key type \" + type + \" from getCrossSigningKey callback did not match\",\n );\n }\n\n /**\n * Check whether the private keys exist in secret storage.\n * XXX: This could be static, be we often seem to have an instance when we\n * want to know this anyway...\n *\n * @param {SecretStorage} secretStorage The secret store using account data\n * @returns {object} map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStoredInSecretStorage(secretStorage: SecretStorage): Promise<Record<string, object>> {\n // check what SSSS keys have encrypted the master key (if any)\n const stored = await secretStorage.isStored(\"m.cross_signing.master\", false) || {};\n // then check which of those SSSS keys have also encrypted the SSK and USK\n function intersect(s) {\n for (const k of Object.keys(stored)) {\n if (!s[k]) {\n delete stored[k];\n }\n }\n }\n for (const type of [\"self_signing\", \"user_signing\"]) {\n intersect(await secretStorage.isStored(`m.cross_signing.${type}`, false) || {});\n }\n return Object.keys(stored).length ? stored : null;\n }\n\n /**\n * Store private keys in secret storage for use by other devices. This is\n * typically called in conjunction with the creation of new cross-signing\n * keys.\n *\n * @param {Map} keys The keys to store\n * @param {SecretStorage} secretStorage The secret store using account data\n */\n public static async storeInSecretStorage(\n keys: Map<string, Uint8Array>,\n secretStorage: SecretStorage,\n ): Promise<void> {\n for (const [type, privateKey] of keys) {\n const encodedKey = encodeBase64(privateKey);\n await secretStorage.store(`m.cross_signing.${type}`, encodedKey);\n }\n }\n\n /**\n * Get private keys from secret storage created by some other device. This\n * also passes the private keys to the app-specific callback.\n *\n * @param {string} type The type of key to get. One of \"master\",\n * \"self_signing\", or \"user_signing\".\n * @param {SecretStorage} secretStorage The secret store using account data\n * @return {Uint8Array} The private key\n */\n public static async getFromSecretStorage(type: string, secretStorage: SecretStorage): Promise<Uint8Array> {\n const encodedKey = await secretStorage.get(`m.cross_signing.${type}`);\n if (!encodedKey) {\n return null;\n }\n return decodeBase64(encodedKey);\n }\n\n /**\n * Check whether the private keys exist in the local key cache.\n *\n * @param {string} [type] The type of key to get. One of \"master\",\n * \"self_signing\", or \"user_signing\". Optional, will check all by default.\n * @returns {boolean} True if all keys are stored in the local cache.\n */\n public async isStoredInKeyCache(type?: string): Promise<boolean> {\n const cacheCallbacks = this.cacheCallbacks;\n if (!cacheCallbacks) return false;\n const types = type ? [type] : [\"master\", \"self_signing\", \"user_signing\"];\n for (const t of types) {\n if (!await cacheCallbacks.getCrossSigningKeyCache(t)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Get cross-signing private keys from the local cache.\n *\n * @returns {Map} A map from key type (string) to private key (Uint8Array)\n */\n public async getCrossSigningKeysFromCache(): Promise<Map<string, Uint8Array>> {\n const keys = new Map();\n const cacheCallbacks = this.cacheCallbacks;\n if (!cacheCallbacks) return keys;\n for (const type of [\"master\", \"self_signing\", \"user_signing\"]) {\n const privKey = await cacheCallbacks.getCrossSigningKeyCache(type);\n if (!privKey) {\n continue;\n }\n keys.set(type, privKey);\n }\n return keys;\n }\n\n /**\n * Get the ID used to identify the user. This can also be used to test for\n * the existence of a given key type.\n *\n * @param {string} type The type of key to get the ID of. One of \"master\",\n * \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @return {string} the ID\n */\n public getId(type = \"master\"): string {\n if (!this.keys[type]) return null;\n const keyInfo = this.keys[type];\n return publicKeyFromKeyInfo(keyInfo);\n }\n\n /**\n * Create new cross-signing keys for the given key types. The public keys\n * will be held in this class, while the private keys are passed off to the\n * `saveCrossSigningKeys` application callback.\n *\n * @param {CrossSigningLevel} level The key types to reset\n */\n public async resetKeys(level?: CrossSigningLevel): Promise<void> {\n if (!this.callbacks.saveCrossSigningKeys) {\n throw new Error(\"No saveCrossSigningKeys callback supplied\");\n }\n\n // If we're resetting the master key, we reset all keys\n if (\n level === undefined ||\n level & CrossSigningLevel.MASTER ||\n !this.keys.master\n ) {\n level = (\n CrossSigningLevel.MASTER |\n CrossSigningLevel.USER_SIGNING |\n CrossSigningLevel.SELF_SIGNING\n );\n } else if (level === 0 as CrossSigningLevel) {\n return;\n }\n\n const privateKeys: Record<string, Uint8Array> = {};\n const keys: Record<string, any> = {}; // TODO types\n let masterSigning;\n let masterPub;\n\n try {\n if (level & CrossSigningLevel.MASTER) {\n masterSigning = new global.Olm.PkSigning();\n privateKeys.master = masterSigning.generate_seed();\n masterPub = masterSigning.init_with_seed(privateKeys.master);\n keys.master = {\n user_id: this.userId,\n usage: ['master'],\n keys: {\n ['ed25519:' + masterPub]: masterPub,\n },\n };\n } else {\n [masterPub, masterSigning] = await this.getCrossSigningKey(\"master\");\n }\n\n if (level & CrossSigningLevel.SELF_SIGNING) {\n const sskSigning = new global.Olm.PkSigning();\n try {\n privateKeys.self_signing = sskSigning.generate_seed();\n const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);\n keys.self_signing = {\n user_id: this.userId,\n usage: ['self_signing'],\n keys: {\n ['ed25519:' + sskPub]: sskPub,\n },\n };\n pkSign(keys.self_signing, masterSigning, this.userId, masterPub);\n } finally {\n sskSigning.free();\n }\n }\n\n if (level & CrossSigningLevel.USER_SIGNING) {\n const uskSigning = new global.Olm.PkSigning();\n try {\n privateKeys.user_signing = uskSigning.generate_seed();\n const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);\n keys.user_signing = {\n user_id: this.userId,\n usage: ['user_signing'],\n keys: {\n ['ed25519:' + uskPub]: uskPub,\n },\n };\n pkSign(keys.user_signing, masterSigning, this.userId, masterPub);\n } finally {\n uskSigning.free();\n }\n }\n\n Object.assign(this.keys, keys);\n this.callbacks.saveCrossSigningKeys(privateKeys);\n } finally {\n if (masterSigning) {\n masterSigning.free();\n }\n }\n }\n\n /**\n * unsets the keys, used when another session has reset the keys, to disable cross-signing\n */\n public clearKeys(): void {\n this.keys = {};\n }\n\n public setKeys(keys: Record<string, ICrossSigningKey>): void {\n const signingKeys: Record<string, ICrossSigningKey> = {};\n if (keys.master) {\n if (keys.master.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id +\n \" in master key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n if (!this.keys.master) {\n // this is the first key we've seen, so first-use is true\n this.firstUse = true;\n } else if (publicKeyFromKeyInfo(keys.master) !== this.getId()) {\n // this is a different key, so first-use is false\n this.firstUse = false;\n } // otherwise, same key, so no change\n signingKeys.master = keys.master;\n } else if (this.keys.master) {\n signingKeys.master = this.keys.master;\n } else {\n throw new Error(\"Tried to set cross-signing keys without a master key\");\n }\n const masterKey = publicKeyFromKeyInfo(signingKeys.master);\n\n // verify signatures\n if (keys.user_signing) {\n if (keys.user_signing.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id +\n \" in user_signing key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n try {\n pkVerify(keys.user_signing, masterKey, this.userId);\n } catch (e) {\n logger.error(\"invalid signature on user-signing key\");\n // FIXME: what do we want to do here?\n throw e;\n }\n }\n if (keys.self_signing) {\n if (keys.self_signing.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id +\n \" in self_signing key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n try {\n pkVerify(keys.self_signing, masterKey, this.userId);\n } catch (e) {\n logger.error(\"invalid signature on self-signing key\");\n // FIXME: what do we want to do here?\n throw e;\n }\n }\n\n // if everything checks out, then save the keys\n if (keys.master) {\n this.keys.master = keys.master;\n // if the master key is set, then the old self-signing and\n // user-signing keys are obsolete\n this.keys.self_signing = null;\n this.keys.user_signing = null;\n }\n if (keys.self_signing) {\n this.keys.self_signing = keys.self_signing;\n }\n if (keys.user_signing) {\n this.keys.user_signing = keys.user_signing;\n }\n }\n\n public updateCrossSigningVerifiedBefore(isCrossSigningVerified: boolean): void {\n // It is critical that this value latches forward from false to true but\n // never back to false to avoid a downgrade attack.\n if (!this.crossSigningVerifiedBefore && isCrossSigningVerified) {\n this.crossSigningVerifiedBefore = true;\n }\n }\n\n public async signObject<T extends object>(data: T, type: string): Promise<T & { signatures: ISignatures }> {\n if (!this.keys[type]) {\n throw new Error(\n \"Attempted to sign with \" + type + \" key but no such key present\",\n );\n }\n const [pubkey, signing] = await this.getCrossSigningKey(type);\n try {\n pkSign(data, signing, this.userId, pubkey);\n return data as T & { signatures: ISignatures };\n } finally {\n signing.free();\n }\n }\n\n public async signUser(key: CrossSigningInfo): Promise<ICrossSigningKey> {\n if (!this.keys.user_signing) {\n logger.info(\"No user signing key: not signing user\");\n return;\n }\n return this.signObject(key.keys.master, \"user_signing\");\n }\n\n public async signDevice(userId: string, device: DeviceInfo): Promise<ISignedKey> {\n if (userId !== this.userId) {\n throw new Error(\n `Trying to sign ${userId}'s device; can only sign our own device`,\n );\n }\n if (!this.keys.self_signing) {\n logger.info(\"No self signing key: not signing device\");\n return;\n }\n return this.signObject<Omit<ISignedKey, \"signatures\">>(\n {\n algorithms: device.algorithms,\n keys: device.keys,\n device_id: device.deviceId,\n user_id: userId,\n }, \"self_signing\",\n );\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * @param {CrossSigningInfo} userCrossSigning Cross signing info for user\n *\n * @returns {UserTrustLevel}\n */\n public checkUserTrust(userCrossSigning: CrossSigningInfo): UserTrustLevel {\n // if we're checking our own key, then it's trusted if the master key\n // and self-signing key match\n if (this.userId === userCrossSigning.userId\n && this.getId() && this.getId() === userCrossSigning.getId()\n && this.getId(\"self_signing\")\n && this.getId(\"self_signing\") === userCrossSigning.getId(\"self_signing\")\n ) {\n return new UserTrustLevel(true, true, this.firstUse);\n }\n\n if (!this.keys.user_signing) {\n // If there's no user signing key, they can't possibly be verified.\n // They may be TOFU trusted though.\n return new UserTrustLevel(false, false, userCrossSigning.firstUse);\n }\n\n let userTrusted;\n const userMaster = userCrossSigning.keys.master;\n const uskId = this.getId('user_signing');\n try {\n pkVerify(userMaster, uskId, this.userId);\n userTrusted = true;\n } catch (e) {\n userTrusted = false;\n }\n return new UserTrustLevel(\n userTrusted,\n userCrossSigning.crossSigningVerifiedBefore,\n userCrossSigning.firstUse,\n );\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * @param {CrossSigningInfo} userCrossSigning Cross signing info for user\n * @param {module:crypto/deviceinfo} device The device to check\n * @param {boolean} localTrust Whether the device is trusted locally\n * @param {boolean} trustCrossSignedDevices Whether we trust cross signed devices\n *\n * @returns {DeviceTrustLevel}\n */\n public checkDeviceTrust(\n userCrossSigning: CrossSigningInfo,\n device: DeviceInfo,\n localTrust: boolean,\n trustCrossSignedDevices: boolean,\n ): DeviceTrustLevel {\n const userTrust = this.checkUserTrust(userCrossSigning);\n\n const userSSK = userCrossSigning.keys.self_signing;\n if (!userSSK) {\n // if the user has no self-signing key then we cannot make any\n // trust assertions about this device from cross-signing\n return new DeviceTrustLevel(\n false, false, localTrust, trustCrossSignedDevices,\n );\n }\n\n const deviceObj = deviceToObject(device, userCrossSigning.userId);\n try {\n // if we can verify the user's SSK from their master key...\n pkVerify(userSSK, userCrossSigning.getId(), userCrossSigning.userId);\n // ...and this device's key from their SSK...\n pkVerify(deviceObj, publicKeyFromKeyInfo(userSSK), userCrossSigning.userId);\n // ...then we trust this device as much as far as we trust the user\n return DeviceTrustLevel.fromUserTrustLevel(userTrust, localTrust, trustCrossSignedDevices);\n } catch (e) {\n return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);\n }\n }\n\n /**\n * @returns {object} Cache callbacks\n */\n public getCacheCallbacks(): ICacheCallbacks {\n return this.cacheCallbacks;\n }\n}\n\nfunction deviceToObject(device: DeviceInfo, userId: string) {\n return {\n algorithms: device.algorithms,\n keys: device.keys,\n device_id: device.deviceId,\n user_id: userId,\n signatures: device.signatures,\n };\n}\n\nexport enum CrossSigningLevel {\n MASTER = 4,\n USER_SIGNING = 2,\n SELF_SIGNING = 1,\n}\n\n/**\n * Represents the ways in which we trust a user\n */\nexport class UserTrustLevel {\n constructor(\n private readonly crossSigningVerified: boolean,\n private readonly crossSigningVerifiedBefore: boolean,\n private readonly tofu: boolean,\n ) {}\n\n /**\n * @returns {boolean} true if this user is verified via any means\n */\n public isVerified(): boolean {\n return this.isCrossSigningVerified();\n }\n\n /**\n * @returns {boolean} true if this user is verified via cross signing\n */\n public isCrossSigningVerified(): boolean {\n return this.crossSigningVerified;\n }\n\n /**\n * @returns {boolean} true if we ever verified this user before (at least for\n * the history of verifications observed by this device).\n */\n public wasCrossSigningVerified(): boolean {\n return this.crossSigningVerifiedBefore;\n }\n\n /**\n * @returns {boolean} true if this user's key is trusted on first use\n */\n public isTofu(): boolean {\n return this.tofu;\n }\n}\n\n/**\n * Represents the ways in which we trust a device\n */\nexport class DeviceTrustLevel {\n constructor(\n public readonly crossSigningVerified: boolean,\n public readonly tofu: boolean,\n private readonly localVerified: boolean,\n private readonly trustCrossSignedDevices: boolean,\n ) {}\n\n public static fromUserTrustLevel(\n userTrustLevel: UserTrustLevel,\n localVerified: boolean,\n trustCrossSignedDevices: boolean,\n ): DeviceTrustLevel {\n return new DeviceTrustLevel(\n userTrustLevel.isCrossSigningVerified(),\n userTrustLevel.isTofu(),\n localVerified,\n trustCrossSignedDevices,\n );\n }\n\n /**\n * @returns {boolean} true if this device is verified via any means\n */\n public isVerified(): boolean {\n return Boolean(this.isLocallyVerified() || (\n this.trustCrossSignedDevices && this.isCrossSigningVerified()\n ));\n }\n\n /**\n * @returns {boolean} true if this device is verified via cross signing\n */\n public isCrossSigningVerified(): boolean {\n return this.crossSigningVerified;\n }\n\n /**\n * @returns {boolean} true if this device is verified locally\n */\n public isLocallyVerified(): boolean {\n return this.localVerified;\n }\n\n /**\n * @returns {boolean} true if this device is trusted from a user's key\n * that is trusted on first use\n */\n public isTofu(): boolean {\n return this.tofu;\n }\n}\n\nexport function createCryptoStoreCacheCallbacks(store: CryptoStore, olmDevice: OlmDevice): ICacheCallbacks {\n return {\n getCrossSigningKeyCache: async function(type: string, _expectedPublicKey: string): Promise<Uint8Array> {\n const key = await new Promise<any>((resolve) => {\n return store.doTxn(\n 'readonly',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n store.getSecretStorePrivateKey(txn, resolve, type);\n },\n );\n });\n\n if (key && key.ciphertext) {\n const pickleKey = Buffer.from(olmDevice._pickleKey);\n const decrypted = await decryptAES(key, pickleKey, type);\n return decodeBase64(decrypted);\n } else {\n return key;\n }\n },\n storeCrossSigningKeyCache: async function(type: string, key: Uint8Array): Promise<void> {\n if (!(key instanceof Uint8Array)) {\n throw new Error(\n `storeCrossSigningKeyCache expects Uint8Array, got ${key}`,\n );\n }\n const pickleKey = Buffer.from(olmDevice._pickleKey);\n const encryptedKey = await encryptAES(encodeBase64(key), pickleKey, type);\n return store.doTxn(\n 'readwrite',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n store.storeSecretStorePrivateKey(txn, type, encryptedKey);\n },\n );\n },\n };\n}\n\n/**\n * Request cross-signing keys from another device during verification.\n *\n * @param {MatrixClient} baseApis base Matrix API interface\n * @param {string} userId The user ID being verified\n * @param {string} deviceId The device ID being verified\n */\nexport async function requestKeysDuringVerification(baseApis: MatrixClient, userId: string, deviceId: string) {\n // If this is a self-verification, ask the other party for keys\n if (baseApis.getUserId() !== userId) {\n return;\n }\n logger.log(\"Cross-signing: Self-verification done; requesting keys\");\n // This happens asynchronously, and we're not concerned about waiting for\n // it. We return here in order to test.\n return new Promise((resolve, reject) => {\n const client = baseApis;\n const original = client.crypto.crossSigningInfo;\n\n // We already have all of the infrastructure we need to validate and\n // cache cross-signing keys, so instead of replicating that, here we set\n // up callbacks that request them from the other device and call\n // CrossSigningInfo.getCrossSigningKey() to validate/cache\n const crossSigning = new CrossSigningInfo(\n original.userId,\n { getCrossSigningKey: async (type) => {\n logger.debug(\"Cross-signing: requesting secret\", type, deviceId);\n const { promise } = client.requestSecret(\n `m.cross_signing.${type}`, [deviceId],\n );\n const result = await promise;\n const decoded = decodeBase64(result);\n return Uint8Array.from(decoded);\n } },\n original.getCacheCallbacks(),\n );\n crossSigning.keys = original.keys;\n\n // XXX: get all keys out if we get one key out\n // https://github.com/vector-im/element-web/issues/12604\n // then change here to reject on the timeout\n // Requests can be ignored, so don't wait around forever\n const timeout = new Promise((resolve, reject) => {\n setTimeout(\n resolve,\n KEY_REQUEST_TIMEOUT_MS,\n new Error(\"Timeout\"),\n );\n });\n\n // also request and cache the key backup key\n const backupKeyPromise = (async () => {\n const cachedKey = await client.crypto.getSessionBackupPrivateKey();\n if (!cachedKey) {\n logger.info(\"No cached backup key found. Requesting...\");\n const secretReq = client.requestSecret(\n 'm.megolm_backup.v1', [deviceId],\n );\n const base64Key = await secretReq.promise;\n logger.info(\"Got key backup key, decoding...\");\n const decodedKey = decodeBase64(base64Key);\n logger.info(\"Decoded backup key, storing...\");\n client.crypto.storeSessionBackupPrivateKey(\n Uint8Array.from(decodedKey),\n );\n logger.info(\"Backup key stored. Starting backup restore...\");\n const backupInfo = await client.getKeyBackupVersion();\n // no need to await for this - just let it go in the bg\n client.restoreKeyBackupWithCache(undefined, undefined, backupInfo).then(() => {\n logger.info(\"Backup restored.\");\n });\n }\n })();\n\n // We call getCrossSigningKey() for its side-effects\n return Promise.race([\n Promise.all([\n crossSigning.getCrossSigningKey(\"master\"),\n crossSigning.getCrossSigningKey(\"self_signing\"),\n crossSigning.getCrossSigningKey(\"user_signing\"),\n backupKeyPromise,\n ]),\n timeout,\n ]).then(resolve, reject);\n }).catch((e) => {\n logger.warn(\"Cross-signing: failure while requesting keys:\", e);\n });\n}\n",
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto/DeviceList\n *\n * Manages the list of other users' devices\n */\n\nimport { EventEmitter } from 'events';\n\nimport { logger } from '../logger';\nimport { DeviceInfo, IDevice } from './deviceinfo';\nimport { CrossSigningInfo } from './CrossSigning';\nimport * as olmlib from './olmlib';\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { chunkPromises, defer, IDeferred, sleep } from '../utils';\nimport { MatrixClient, CryptoStore } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\n\n/* State transition diagram for DeviceList.deviceTrackingStatus\n *\n * |\n * stopTrackingDeviceList V\n * +---------------------> NOT_TRACKED\n * | |\n * +<--------------------+ | startTrackingDeviceList\n * | | V\n * | +-------------> PENDING_DOWNLOAD <--------------------+-+\n * | | ^ | | |\n * | | restart download | | start download | | invalidateUserDeviceList\n * | | client failed | | | |\n * | | | V | |\n * | +------------ DOWNLOAD_IN_PROGRESS -------------------+ |\n * | | | |\n * +<-------------------+ | download successful |\n * ^ V |\n * +----------------------- UP_TO_DATE ------------------------+\n */\n\n// constants for DeviceList.deviceTrackingStatus\nenum TrackingStatus {\n NotTracked,\n PendingDownload,\n DownloadInProgress,\n UpToDate,\n}\n\nexport type DeviceInfoMap = Record<string, Record<string, DeviceInfo>>;\n\n/**\n * @alias module:crypto/DeviceList\n */\nexport class DeviceList extends EventEmitter {\n // userId -> {\n // deviceId -> {\n // [device info]\n // }\n // }\n private devices: Record<string, Record<string, IDevice>> = {};\n\n // userId -> {\n // [key info]\n // }\n public crossSigningInfo: Record<string, object> = {};\n\n // map of identity keys to the user who owns it\n private userByIdentityKey: Record<string, string> = {};\n\n // which users we are tracking device status for.\n // userId -> TRACKING_STATUS_*\n private deviceTrackingStatus: Record<string, TrackingStatus> = {}; // loaded from storage in load()\n\n // The 'next_batch' sync token at the point the data was written,\n // ie. a token representing the point immediately after the\n // moment represented by the snapshot in the db.\n private syncToken: string = null;\n\n // userId -> promise\n private keyDownloadsInProgressByUser: Record<string, Promise<void>> = {};\n\n // Set whenever changes are made other than setting the sync token\n private dirty = false;\n\n // Promise resolved when device data is saved\n private savePromise: Promise<boolean> = null;\n // Function that resolves the save promise\n private resolveSavePromise: (saved: boolean) => void = null;\n // The time the save is scheduled for\n private savePromiseTime: number = null;\n // The timer used to delay the save\n private saveTimer: NodeJS.Timeout = null;\n // True if we have fetched data from the server or loaded a non-empty\n // set of device data from the store\n private hasFetched: boolean = null;\n\n private readonly serialiser: DeviceListUpdateSerialiser;\n\n constructor(\n baseApis: MatrixClient,\n private readonly cryptoStore: CryptoStore,\n olmDevice: OlmDevice,\n // Maximum number of user IDs per request to prevent server overload (#1619)\n public readonly keyDownloadChunkSize = 250,\n ) {\n super();\n\n this.serialiser = new DeviceListUpdateSerialiser(baseApis, olmDevice, this);\n }\n\n /**\n * Load the device tracking state from storage\n */\n public async load() {\n await this.cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {\n this.cryptoStore.getEndToEndDeviceData(txn, (deviceData) => {\n this.hasFetched = Boolean(deviceData && deviceData.devices);\n this.devices = deviceData ? deviceData.devices : {},\n this.crossSigningInfo = deviceData ?\n deviceData.crossSigningInfo || {} : {};\n this.deviceTrackingStatus = deviceData ?\n deviceData.trackingStatus : {};\n this.syncToken = deviceData ? deviceData.syncToken : null;\n this.userByIdentityKey = {};\n for (const user of Object.keys(this.devices)) {\n const userDevices = this.devices[user];\n for (const device of Object.keys(userDevices)) {\n const idKey = userDevices[device].keys['curve25519:'+device];\n if (idKey !== undefined) {\n this.userByIdentityKey[idKey] = user;\n }\n }\n }\n });\n },\n );\n\n for (const u of Object.keys(this.deviceTrackingStatus)) {\n // if a download was in progress when we got shut down, it isn't any more.\n if (this.deviceTrackingStatus[u] == TrackingStatus.DownloadInProgress) {\n this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload;\n }\n }\n }\n\n public stop() {\n if (this.saveTimer !== null) {\n clearTimeout(this.saveTimer);\n }\n }\n\n /**\n * Save the device tracking state to storage, if any changes are\n * pending other than updating the sync token\n *\n * The actual save will be delayed by a short amount of time to\n * aggregate multiple writes to the database.\n *\n * @param {number} delay Time in ms before which the save actually happens.\n * By default, the save is delayed for a short period in order to batch\n * multiple writes, but this behaviour can be disabled by passing 0.\n *\n * @return {Promise<boolean>} true if the data was saved, false if\n * it was not (eg. because no changes were pending). The promise\n * will only resolve once the data is saved, so may take some time\n * to resolve.\n */\n public async saveIfDirty(delay = 500): Promise<boolean> {\n if (!this.dirty) return Promise.resolve(false);\n // Delay saves for a bit so we can aggregate multiple saves that happen\n // in quick succession (eg. when a whole room's devices are marked as known)\n\n const targetTime = Date.now() + delay;\n if (this.savePromiseTime && targetTime < this.savePromiseTime) {\n // There's a save scheduled but for after we would like: cancel\n // it & schedule one for the time we want\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n this.savePromiseTime = null;\n // (but keep the save promise since whatever called save before\n // will still want to know when the save is done)\n }\n\n let savePromise = this.savePromise;\n if (savePromise === null) {\n savePromise = new Promise((resolve, reject) => {\n this.resolveSavePromise = resolve;\n });\n this.savePromise = savePromise;\n }\n\n if (this.saveTimer === null) {\n const resolveSavePromise = this.resolveSavePromise;\n this.savePromiseTime = targetTime;\n this.saveTimer = setTimeout(() => {\n logger.log('Saving device tracking data', this.syncToken);\n\n // null out savePromise now (after the delay but before the write),\n // otherwise we could return the existing promise when the save has\n // actually already happened.\n this.savePromiseTime = null;\n this.saveTimer = null;\n this.savePromise = null;\n this.resolveSavePromise = null;\n\n this.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {\n this.cryptoStore.storeEndToEndDeviceData({\n devices: this.devices,\n crossSigningInfo: this.crossSigningInfo,\n trackingStatus: this.deviceTrackingStatus,\n syncToken: this.syncToken,\n }, txn);\n },\n ).then(() => {\n // The device list is considered dirty until the write completes.\n this.dirty = false;\n resolveSavePromise(true);\n }, err => {\n logger.error('Failed to save device tracking data', this.syncToken);\n logger.error(err);\n });\n }, delay);\n }\n\n return savePromise;\n }\n\n /**\n * Gets the sync token last set with setSyncToken\n *\n * @return {string} The sync token\n */\n public getSyncToken(): string {\n return this.syncToken;\n }\n\n /**\n * Sets the sync token that the app will pass as the 'since' to the /sync\n * endpoint next time it syncs.\n * The sync token must always be set after any changes made as a result of\n * data in that sync since setting the sync token to a newer one will mean\n * those changed will not be synced from the server if a new client starts\n * up with that data.\n *\n * @param {string} st The sync token\n */\n public setSyncToken(st: string): void {\n this.syncToken = st;\n }\n\n /**\n * Ensures up to date keys for a list of users are stored in the session store,\n * downloading and storing them if they're not (or if forceDownload is\n * true).\n * @param {Array} userIds The users to fetch.\n * @param {boolean} forceDownload Always download the keys even if cached.\n *\n * @return {Promise} A promise which resolves to a map userId->deviceId->{@link\n * module:crypto/deviceinfo|DeviceInfo}.\n */\n public downloadKeys(userIds: string[], forceDownload: boolean): Promise<DeviceInfoMap> {\n const usersToDownload = [];\n const promises = [];\n\n userIds.forEach((u) => {\n const trackingStatus = this.deviceTrackingStatus[u];\n if (this.keyDownloadsInProgressByUser[u]) {\n // already a key download in progress/queued for this user; its results\n // will be good enough for us.\n logger.log(\n `downloadKeys: already have a download in progress for ` +\n `${u}: awaiting its result`,\n );\n promises.push(this.keyDownloadsInProgressByUser[u]);\n } else if (forceDownload || trackingStatus != TrackingStatus.UpToDate) {\n usersToDownload.push(u);\n }\n });\n\n if (usersToDownload.length != 0) {\n logger.log(\"downloadKeys: downloading for\", usersToDownload);\n const downloadPromise = this.doKeyDownload(usersToDownload);\n promises.push(downloadPromise);\n }\n\n if (promises.length === 0) {\n logger.log(\"downloadKeys: already have all necessary keys\");\n }\n\n return Promise.all(promises).then(() => {\n return this.getDevicesFromStore(userIds);\n });\n }\n\n /**\n * Get the stored device keys for a list of user ids\n *\n * @param {string[]} userIds the list of users to list keys for.\n *\n * @return {Object} userId->deviceId->{@link module:crypto/deviceinfo|DeviceInfo}.\n */\n private getDevicesFromStore(userIds: string[]): DeviceInfoMap {\n const stored: DeviceInfoMap = {};\n userIds.map((u) => {\n stored[u] = {};\n const devices = this.getStoredDevicesForUser(u) || [];\n devices.map(function(dev) {\n stored[u][dev.deviceId] = dev;\n });\n });\n return stored;\n }\n\n /**\n * Returns a list of all user IDs the DeviceList knows about\n *\n * @return {array} All known user IDs\n */\n public getKnownUserIds(): string[] {\n return Object.keys(this.devices);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param {string} userId the user to list keys for.\n *\n * @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't\n * managed to get a list of devices for this user yet.\n */\n public getStoredDevicesForUser(userId: string): DeviceInfo[] | null {\n const devs = this.devices[userId];\n if (!devs) {\n return null;\n }\n const res = [];\n for (const deviceId in devs) {\n if (devs.hasOwnProperty(deviceId)) {\n res.push(DeviceInfo.fromStorage(devs[deviceId], deviceId));\n }\n }\n return res;\n }\n\n /**\n * Get the stored device data for a user, in raw object form\n *\n * @param {string} userId the user to get data for\n *\n * @return {Object} deviceId->{object} devices, or undefined if\n * there is no data for this user.\n */\n public getRawStoredDevicesForUser(userId: string): Record<string, IDevice> {\n return this.devices[userId];\n }\n\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo {\n if (!this.crossSigningInfo[userId]) return null;\n\n return CrossSigningInfo.fromStorage(this.crossSigningInfo[userId], userId);\n }\n\n public storeCrossSigningForUser(userId: string, info: CrossSigningInfo): void {\n this.crossSigningInfo[userId] = info;\n this.dirty = true;\n }\n\n /**\n * Get the stored keys for a single device\n *\n * @param {string} userId\n * @param {string} deviceId\n *\n * @return {module:crypto/deviceinfo?} device, or undefined\n * if we don't know about this device\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo {\n const devs = this.devices[userId];\n if (!devs || !devs[deviceId]) {\n return undefined;\n }\n return DeviceInfo.fromStorage(devs[deviceId], deviceId);\n }\n\n /**\n * Get a user ID by one of their device's curve25519 identity key\n *\n * @param {string} algorithm encryption algorithm\n * @param {string} senderKey curve25519 key to match\n *\n * @return {string} user ID\n */\n public getUserByIdentityKey(algorithm: string, senderKey: string): string {\n if (\n algorithm !== olmlib.OLM_ALGORITHM &&\n algorithm !== olmlib.MEGOLM_ALGORITHM\n ) {\n // we only deal in olm keys\n return null;\n }\n\n return this.userByIdentityKey[senderKey];\n }\n\n /**\n * Find a device by curve25519 identity key\n *\n * @param {string} algorithm encryption algorithm\n * @param {string} senderKey curve25519 key to match\n *\n * @return {module:crypto/deviceinfo?}\n */\n public getDeviceByIdentityKey(algorithm: string, senderKey: string): DeviceInfo | null {\n const userId = this.getUserByIdentityKey(algorithm, senderKey);\n if (!userId) {\n return null;\n }\n\n const devices = this.devices[userId];\n if (!devices) {\n return null;\n }\n\n for (const deviceId in devices) {\n if (!devices.hasOwnProperty(deviceId)) {\n continue;\n }\n\n const device = devices[deviceId];\n for (const keyId in device.keys) {\n if (!device.keys.hasOwnProperty(keyId)) {\n continue;\n }\n if (keyId.indexOf(\"curve25519:\") !== 0) {\n continue;\n }\n const deviceKey = device.keys[keyId];\n if (deviceKey == senderKey) {\n return DeviceInfo.fromStorage(device, deviceId);\n }\n }\n }\n\n // doesn't match a known device\n return null;\n }\n\n /**\n * Replaces the list of devices for a user with the given device list\n *\n * @param {string} userId The user ID\n * @param {Object} devices New device info for user\n */\n public storeDevicesForUser(userId: string, devices: Record<string, IDevice>): void {\n this.setRawStoredDevicesForUser(userId, devices);\n this.dirty = true;\n }\n\n /**\n * flag the given user for device-list tracking, if they are not already.\n *\n * This will mean that a subsequent call to refreshOutdatedDeviceLists()\n * will download the device list for the user, and that subsequent calls to\n * invalidateUserDeviceList will trigger more updates.\n *\n * @param {String} userId\n */\n public startTrackingDeviceList(userId: string): void {\n // sanity-check the userId. This is mostly paranoia, but if synapse\n // can't parse the userId we give it as an mxid, it 500s the whole\n // request and we can never update the device lists again (because\n // the broken userId is always 'invalid' and always included in any\n // refresh request).\n // By checking it is at least a string, we can eliminate a class of\n // silly errors.\n if (typeof userId !== 'string') {\n throw new Error('userId must be a string; was '+userId);\n }\n if (!this.deviceTrackingStatus[userId]) {\n logger.log('Now tracking device list for ' + userId);\n this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload;\n // we don't yet persist the tracking status, since there may be a lot\n // of calls; we save all data together once the sync is done\n this.dirty = true;\n }\n }\n\n /**\n * Mark the given user as no longer being tracked for device-list updates.\n *\n * This won't affect any in-progress downloads, which will still go on to\n * complete; it will just mean that we don't think that we have an up-to-date\n * list for future calls to downloadKeys.\n *\n * @param {String} userId\n */\n public stopTrackingDeviceList(userId: string): void {\n if (this.deviceTrackingStatus[userId]) {\n logger.log('No longer tracking device list for ' + userId);\n this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked;\n\n // we don't yet persist the tracking status, since there may be a lot\n // of calls; we save all data together once the sync is done\n this.dirty = true;\n }\n }\n\n /**\n * Set all users we're currently tracking to untracked\n *\n * This will flag each user whose devices we are tracking as in need of an\n * update.\n */\n public stopTrackingAllDeviceLists(): void {\n for (const userId of Object.keys(this.deviceTrackingStatus)) {\n this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked;\n }\n this.dirty = true;\n }\n\n /**\n * Mark the cached device list for the given user outdated.\n *\n * If we are not tracking this user's devices, we'll do nothing. Otherwise\n * we flag the user as needing an update.\n *\n * This doesn't actually set off an update, so that several users can be\n * batched together. Call refreshOutdatedDeviceLists() for that.\n *\n * @param {String} userId\n */\n public invalidateUserDeviceList(userId: string): void {\n if (this.deviceTrackingStatus[userId]) {\n logger.log(\"Marking device list outdated for\", userId);\n this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload;\n\n // we don't yet persist the tracking status, since there may be a lot\n // of calls; we save all data together once the sync is done\n this.dirty = true;\n }\n }\n\n /**\n * If we have users who have outdated device lists, start key downloads for them\n *\n * @returns {Promise} which completes when the download completes; normally there\n * is no need to wait for this (it's mostly for the unit tests).\n */\n public refreshOutdatedDeviceLists(): Promise<void> {\n this.saveIfDirty();\n\n const usersToDownload = [];\n for (const userId of Object.keys(this.deviceTrackingStatus)) {\n const stat = this.deviceTrackingStatus[userId];\n if (stat == TrackingStatus.PendingDownload) {\n usersToDownload.push(userId);\n }\n }\n\n return this.doKeyDownload(usersToDownload);\n }\n\n /**\n * Set the stored device data for a user, in raw object form\n * Used only by internal class DeviceListUpdateSerialiser\n *\n * @param {string} userId the user to get data for\n *\n * @param {Object} devices deviceId->{object} the new devices\n */\n public setRawStoredDevicesForUser(userId: string, devices: Record<string, IDevice>): void {\n // remove old devices from userByIdentityKey\n if (this.devices[userId] !== undefined) {\n for (const [deviceId, dev] of Object.entries(this.devices[userId])) {\n const identityKey = dev.keys['curve25519:'+deviceId];\n\n delete this.userByIdentityKey[identityKey];\n }\n }\n\n this.devices[userId] = devices;\n\n // add new devices into userByIdentityKey\n for (const [deviceId, dev] of Object.entries(devices)) {\n const identityKey = dev.keys['curve25519:'+deviceId];\n\n this.userByIdentityKey[identityKey] = userId;\n }\n }\n\n public setRawStoredCrossSigningForUser(userId: string, info: object): void {\n this.crossSigningInfo[userId] = info;\n }\n\n /**\n * Fire off download update requests for the given users, and update the\n * device list tracking status for them, and the\n * keyDownloadsInProgressByUser map for them.\n *\n * @param {String[]} users list of userIds\n *\n * @return {Promise} resolves when all the users listed have\n * been updated. rejects if there was a problem updating any of the\n * users.\n */\n private doKeyDownload(users: string[]): Promise<void> {\n if (users.length === 0) {\n // nothing to do\n return Promise.resolve();\n }\n\n const prom = this.serialiser.updateDevicesForUsers(users, this.syncToken).then(() => {\n finished(true);\n }, (e) => {\n logger.error(\n 'Error downloading keys for ' + users + \":\", e,\n );\n finished(false);\n throw e;\n });\n\n users.forEach((u) => {\n this.keyDownloadsInProgressByUser[u] = prom;\n const stat = this.deviceTrackingStatus[u];\n if (stat == TrackingStatus.PendingDownload) {\n this.deviceTrackingStatus[u] = TrackingStatus.DownloadInProgress;\n }\n });\n\n const finished = (success) => {\n this.emit(\"crypto.willUpdateDevices\", users, !this.hasFetched);\n users.forEach((u) => {\n this.dirty = true;\n\n // we may have queued up another download request for this user\n // since we started this request. If that happens, we should\n // ignore the completion of the first one.\n if (this.keyDownloadsInProgressByUser[u] !== prom) {\n logger.log('Another update in the queue for', u, '- not marking up-to-date');\n return;\n }\n delete this.keyDownloadsInProgressByUser[u];\n const stat = this.deviceTrackingStatus[u];\n if (stat == TrackingStatus.DownloadInProgress) {\n if (success) {\n // we didn't get any new invalidations since this download started:\n // this user's device list is now up to date.\n this.deviceTrackingStatus[u] = TrackingStatus.UpToDate;\n logger.log(\"Device list for\", u, \"now up to date\");\n } else {\n this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload;\n }\n }\n });\n this.saveIfDirty();\n this.emit(\"crypto.devicesUpdated\", users, !this.hasFetched);\n this.hasFetched = true;\n };\n\n return prom;\n }\n}\n\n/**\n * Serialises updates to device lists\n *\n * Ensures that results from /keys/query are not overwritten if a second call\n * completes *before* an earlier one.\n *\n * It currently does this by ensuring only one call to /keys/query happens at a\n * time (and queuing other requests up).\n */\nclass DeviceListUpdateSerialiser {\n private downloadInProgress = false;\n\n // users which are queued for download\n // userId -> true\n private keyDownloadsQueuedByUser: Record<string, boolean> = {};\n\n // deferred which is resolved when the queued users are downloaded.\n // non-null indicates that we have users queued for download.\n private queuedQueryDeferred: IDeferred<void> = null;\n\n private syncToken: string = null; // The sync token we send with the requests\n\n /*\n * @param {object} baseApis Base API object\n * @param {object} olmDevice The Olm Device\n * @param {object} deviceList The device list object, the device list to be updated\n */\n constructor(\n private readonly baseApis: MatrixClient,\n private readonly olmDevice: OlmDevice,\n private readonly deviceList: DeviceList,\n ) {}\n\n /**\n * Make a key query request for the given users\n *\n * @param {String[]} users list of user ids\n *\n * @param {String} syncToken sync token to pass in the query request, to\n * help the HS give the most recent results\n *\n * @return {Promise} resolves when all the users listed have\n * been updated. rejects if there was a problem updating any of the\n * users.\n */\n public updateDevicesForUsers(users: string[], syncToken: string): Promise<void> {\n users.forEach((u) => {\n this.keyDownloadsQueuedByUser[u] = true;\n });\n\n if (!this.queuedQueryDeferred) {\n this.queuedQueryDeferred = defer();\n }\n\n // We always take the new sync token and just use the latest one we've\n // been given, since it just needs to be at least as recent as the\n // sync response the device invalidation message arrived in\n this.syncToken = syncToken;\n\n if (this.downloadInProgress) {\n // just queue up these users\n logger.log('Queued key download for', users);\n return this.queuedQueryDeferred.promise;\n }\n\n // start a new download.\n return this.doQueuedQueries();\n }\n\n private doQueuedQueries(): Promise<void> {\n if (this.downloadInProgress) {\n throw new Error(\n \"DeviceListUpdateSerialiser.doQueuedQueries called with request active\",\n );\n }\n\n const downloadUsers = Object.keys(this.keyDownloadsQueuedByUser);\n this.keyDownloadsQueuedByUser = {};\n const deferred = this.queuedQueryDeferred;\n this.queuedQueryDeferred = null;\n\n logger.log('Starting key download for', downloadUsers);\n this.downloadInProgress = true;\n\n const opts: Parameters<MatrixClient[\"downloadKeysForUsers\"]>[1] = {};\n if (this.syncToken) {\n opts.token = this.syncToken;\n }\n\n const factories = [];\n for (let i = 0; i < downloadUsers.length; i += this.deviceList.keyDownloadChunkSize) {\n const userSlice = downloadUsers.slice(i, i + this.deviceList.keyDownloadChunkSize);\n factories.push(() => this.baseApis.downloadKeysForUsers(userSlice, opts));\n }\n\n chunkPromises(factories, 3).then(async (responses: any[]) => {\n const dk = Object.assign({}, ...(responses.map(res => res.device_keys || {})));\n const masterKeys = Object.assign({}, ...(responses.map(res => res.master_keys || {})));\n const ssks = Object.assign({}, ...(responses.map(res => res.self_signing_keys || {})));\n const usks = Object.assign({}, ...(responses.map(res => res.user_signing_keys || {})));\n\n // yield to other things that want to execute in between users, to\n // avoid wedging the CPU\n // (https://github.com/vector-im/element-web/issues/3158)\n //\n // of course we ought to do this in a web worker or similar, but\n // this serves as an easy solution for now.\n for (const userId of downloadUsers) {\n await sleep(5);\n try {\n await this.processQueryResponseForUser(\n userId, dk[userId], {\n master: masterKeys[userId],\n self_signing: ssks[userId],\n user_signing: usks[userId],\n },\n );\n } catch (e) {\n // log the error but continue, so that one bad key\n // doesn't kill the whole process\n logger.error(`Error processing keys for ${userId}:`, e);\n }\n }\n }).then(() => {\n logger.log('Completed key download for ' + downloadUsers);\n\n this.downloadInProgress = false;\n deferred.resolve();\n\n // if we have queued users, fire off another request.\n if (this.queuedQueryDeferred) {\n this.doQueuedQueries();\n }\n }, (e) => {\n logger.warn('Error downloading keys for ' + downloadUsers + ':', e);\n this.downloadInProgress = false;\n deferred.reject(e);\n });\n\n return deferred.promise;\n }\n\n private async processQueryResponseForUser(\n userId: string,\n dkResponse: object,\n crossSigningResponse: any, // TODO types\n ): Promise<void> {\n logger.log('got device keys for ' + userId + ':', dkResponse);\n logger.log('got cross-signing keys for ' + userId + ':', crossSigningResponse);\n\n {\n // map from deviceid -> deviceinfo for this user\n const userStore: Record<string, DeviceInfo> = {};\n const devs = this.deviceList.getRawStoredDevicesForUser(userId);\n if (devs) {\n Object.keys(devs).forEach((deviceId) => {\n const d = DeviceInfo.fromStorage(devs[deviceId], deviceId);\n userStore[deviceId] = d;\n });\n }\n\n await updateStoredDeviceKeysForUser(\n this.olmDevice, userId, userStore, dkResponse || {},\n this.baseApis.getUserId(), this.baseApis.deviceId,\n );\n\n // put the updates into the object that will be returned as our results\n const storage: Record<string, IDevice> = {};\n Object.keys(userStore).forEach((deviceId) => {\n storage[deviceId] = userStore[deviceId].toStorage();\n });\n\n this.deviceList.setRawStoredDevicesForUser(userId, storage);\n }\n\n // now do the same for the cross-signing keys\n {\n // FIXME: should we be ignoring empty cross-signing responses, or\n // should we be dropping the keys?\n if (crossSigningResponse\n && (crossSigningResponse.master || crossSigningResponse.self_signing\n || crossSigningResponse.user_signing)) {\n const crossSigning\n = this.deviceList.getStoredCrossSigningForUser(userId)\n || new CrossSigningInfo(userId);\n\n crossSigning.setKeys(crossSigningResponse);\n\n this.deviceList.setRawStoredCrossSigningForUser(\n userId, crossSigning.toStorage(),\n );\n\n // NB. Unlike most events in the js-sdk, this one is internal to the\n // js-sdk and is not re-emitted\n this.deviceList.emit('userCrossSigningUpdated', userId);\n }\n }\n }\n}\n\nasync function updateStoredDeviceKeysForUser(\n olmDevice: OlmDevice,\n userId: string,\n userStore: Record<string, DeviceInfo>,\n userResult: object,\n localUserId: string,\n localDeviceId: string,\n): Promise<boolean> {\n let updated = false;\n\n // remove any devices in the store which aren't in the response\n for (const deviceId in userStore) {\n if (!userStore.hasOwnProperty(deviceId)) {\n continue;\n }\n\n if (!(deviceId in userResult)) {\n if (userId === localUserId && deviceId === localDeviceId) {\n logger.warn(\n `Local device ${deviceId} missing from sync, skipping removal`,\n );\n continue;\n }\n\n logger.log(\"Device \" + userId + \":\" + deviceId +\n \" has been removed\");\n delete userStore[deviceId];\n updated = true;\n }\n }\n\n for (const deviceId in userResult) {\n if (!userResult.hasOwnProperty(deviceId)) {\n continue;\n }\n\n const deviceResult = userResult[deviceId];\n\n // check that the user_id and device_id in the response object are\n // correct\n if (deviceResult.user_id !== userId) {\n logger.warn(\"Mismatched user_id \" + deviceResult.user_id +\n \" in keys from \" + userId + \":\" + deviceId);\n continue;\n }\n if (deviceResult.device_id !== deviceId) {\n logger.warn(\"Mismatched device_id \" + deviceResult.device_id +\n \" in keys from \" + userId + \":\" + deviceId);\n continue;\n }\n\n if (await storeDeviceKeys(olmDevice, userStore, deviceResult)) {\n updated = true;\n }\n }\n\n return updated;\n}\n\n/*\n * Process a device in a /query response, and add it to the userStore\n *\n * returns (a promise for) true if a change was made, else false\n */\nasync function storeDeviceKeys(\n olmDevice: OlmDevice,\n userStore: Record<string, DeviceInfo>,\n deviceResult: any, // TODO types\n): Promise<boolean> {\n if (!deviceResult.keys) {\n // no keys?\n return false;\n }\n\n const deviceId = deviceResult.device_id;\n const userId = deviceResult.user_id;\n\n const signKeyId = \"ed25519:\" + deviceId;\n const signKey = deviceResult.keys[signKeyId];\n if (!signKey) {\n logger.warn(\"Device \" + userId + \":\" + deviceId + \" has no ed25519 key\");\n return false;\n }\n\n const unsigned = deviceResult.unsigned || {};\n const signatures = deviceResult.signatures || {};\n\n try {\n await olmlib.verifySignature(olmDevice, deviceResult, userId, deviceId, signKey);\n } catch (e) {\n logger.warn(\"Unable to verify signature on device \" + userId + \":\" + deviceId + \":\" + e);\n return false;\n }\n\n // DeviceInfo\n let deviceStore;\n\n if (deviceId in userStore) {\n // already have this device.\n deviceStore = userStore[deviceId];\n\n if (deviceStore.getFingerprint() != signKey) {\n // this should only happen if the list has been MITMed; we are\n // best off sticking with the original keys.\n //\n // Should we warn the user about it somehow?\n logger.warn(\"Ed25519 key for device \" + userId + \":\" +\n deviceId + \" has changed\");\n return false;\n }\n } else {\n userStore[deviceId] = deviceStore = new DeviceInfo(deviceId);\n }\n\n deviceStore.keys = deviceResult.keys || {};\n deviceStore.algorithms = deviceResult.algorithms || [];\n deviceStore.unsigned = unsigned;\n deviceStore.signatures = signatures;\n return true;\n}\n",
"import { logger } from \"../logger\";\nimport { MatrixEvent } from \"../models/event\";\nimport { EventEmitter } from \"events\";\nimport { createCryptoStoreCacheCallbacks, ICacheCallbacks } from \"./CrossSigning\";\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { PREFIX_UNSTABLE } from \"../http-api\";\nimport { Crypto, IBootstrapCrossSigningOpts } from \"./index\";\nimport {\n CrossSigningKeys,\n ICrossSigningKey,\n ICryptoCallbacks,\n ISignedKey,\n KeySignatures,\n} from \"../matrix\";\nimport { ISecretStorageKeyInfo } from \"./api\";\nimport { IKeyBackupInfo } from \"./keybackup\";\n\ninterface ICrossSigningKeys {\n authUpload: IBootstrapCrossSigningOpts[\"authUploadDeviceSigningKeys\"];\n keys: Record<string, ICrossSigningKey>;\n}\n\n/**\n * Builds an EncryptionSetupOperation by calling any of the add.. methods.\n * Once done, `buildOperation()` can be called which allows to apply to operation.\n *\n * This is used as a helper by Crypto to keep track of all the network requests\n * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future)\n * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them\n * more than once.\n */\nexport class EncryptionSetupBuilder {\n public readonly accountDataClientAdapter: AccountDataClientAdapter;\n public readonly crossSigningCallbacks: CrossSigningCallbacks;\n public readonly ssssCryptoCallbacks: SSSSCryptoCallbacks;\n\n private crossSigningKeys: ICrossSigningKeys = null;\n private keySignatures: KeySignatures = null;\n private keyBackupInfo: IKeyBackupInfo = null;\n private sessionBackupPrivateKey: Uint8Array;\n\n /**\n * @param {Object.<String, MatrixEvent>} accountData pre-existing account data, will only be read, not written.\n * @param {CryptoCallbacks} delegateCryptoCallbacks crypto callbacks to delegate to if the key isn't in cache yet\n */\n constructor(accountData: Record<string, MatrixEvent>, delegateCryptoCallbacks: ICryptoCallbacks) {\n this.accountDataClientAdapter = new AccountDataClientAdapter(accountData);\n this.crossSigningCallbacks = new CrossSigningCallbacks();\n this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks);\n }\n\n /**\n * Adds new cross-signing public keys\n *\n * @param {function} authUpload Function called to await an interactive auth\n * flow when uploading device signing keys.\n * Args:\n * {function} A function that makes the request requiring auth. Receives\n * the auth data as an object. Can be called multiple times, first with\n * an empty authDict, to obtain the flows.\n * @param {Object} keys the new keys\n */\n public addCrossSigningKeys(authUpload: ICrossSigningKeys[\"authUpload\"], keys: ICrossSigningKeys[\"keys\"]): void {\n this.crossSigningKeys = { authUpload, keys };\n }\n\n /**\n * Adds the key backup info to be updated on the server\n *\n * Used either to create a new key backup, or add signatures\n * from the new MSK.\n *\n * @param {Object} keyBackupInfo as received from/sent to the server\n */\n public addSessionBackup(keyBackupInfo: IKeyBackupInfo): void {\n this.keyBackupInfo = keyBackupInfo;\n }\n\n /**\n * Adds the session backup private key to be updated in the local cache\n *\n * Used after fixing the format of the key\n *\n * @param {Uint8Array} privateKey\n */\n public addSessionBackupPrivateKeyToCache(privateKey: Uint8Array): void {\n this.sessionBackupPrivateKey = privateKey;\n }\n\n /**\n * Add signatures from a given user and device/x-sign key\n * Used to sign the new cross-signing key with the device key\n *\n * @param {String} userId\n * @param {String} deviceId\n * @param {Object} signature\n */\n public addKeySignature(userId: string, deviceId: string, signature: ISignedKey): void {\n if (!this.keySignatures) {\n this.keySignatures = {};\n }\n const userSignatures = this.keySignatures[userId] || {};\n this.keySignatures[userId] = userSignatures;\n userSignatures[deviceId] = signature;\n }\n\n /**\n * @param {String} type\n * @param {Object} content\n * @return {Promise}\n */\n public setAccountData(type: string, content: object): Promise<void> {\n return this.accountDataClientAdapter.setAccountData(type, content);\n }\n\n /**\n * builds the operation containing all the parts that have been added to the builder\n * @return {EncryptionSetupOperation}\n */\n public buildOperation(): EncryptionSetupOperation {\n const accountData = this.accountDataClientAdapter.values;\n return new EncryptionSetupOperation(\n accountData,\n this.crossSigningKeys,\n this.keyBackupInfo,\n this.keySignatures,\n );\n }\n\n /**\n * Stores the created keys locally.\n *\n * This does not yet store the operation in a way that it can be restored,\n * but that is the idea in the future.\n *\n * @param {Crypto} crypto\n * @return {Promise}\n */\n public async persist(crypto: Crypto): Promise<void> {\n // store private keys in cache\n if (this.crossSigningKeys) {\n const cacheCallbacks = createCryptoStoreCacheCallbacks(crypto.cryptoStore, crypto.olmDevice);\n for (const type of [\"master\", \"self_signing\", \"user_signing\"]) {\n logger.log(`Cache ${type} cross-signing private key locally`);\n const privateKey = this.crossSigningCallbacks.privateKeys.get(type);\n await cacheCallbacks.storeCrossSigningKeyCache(type, privateKey);\n }\n // store own cross-sign pubkeys as trusted\n await crypto.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n crypto.cryptoStore.storeCrossSigningKeys(\n txn, this.crossSigningKeys.keys);\n },\n );\n }\n // store session backup key in cache\n if (this.sessionBackupPrivateKey) {\n await crypto.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey);\n }\n }\n}\n\n/**\n * Can be created from EncryptionSetupBuilder, or\n * (in a follow-up PR, not implemented yet) restored from storage, to retry.\n *\n * It does not have knowledge of any private keys, unlike the builder.\n */\nexport class EncryptionSetupOperation {\n /**\n * @param {Map<String, Object>} accountData\n * @param {Object} crossSigningKeys\n * @param {Object} keyBackupInfo\n * @param {Object} keySignatures\n */\n constructor(\n private readonly accountData: Map<string, object>,\n private readonly crossSigningKeys: ICrossSigningKeys,\n private readonly keyBackupInfo: IKeyBackupInfo,\n private readonly keySignatures: KeySignatures,\n ) {}\n\n /**\n * Runs the (remaining part of, in the future) operation by sending requests to the server.\n * @param {Crypto} crypto\n */\n public async apply(crypto: Crypto): Promise<void> {\n const baseApis = crypto.baseApis;\n // upload cross-signing keys\n if (this.crossSigningKeys) {\n const keys: Partial<CrossSigningKeys> = {};\n for (const [name, key] of Object.entries(this.crossSigningKeys.keys)) {\n keys[name + \"_key\"] = key;\n }\n\n // We must only call `uploadDeviceSigningKeys` from inside this auth\n // helper to ensure we properly handle auth errors.\n await this.crossSigningKeys.authUpload(authDict => {\n return baseApis.uploadDeviceSigningKeys(authDict, keys as CrossSigningKeys);\n });\n\n // pass the new keys to the main instance of our own CrossSigningInfo.\n crypto.crossSigningInfo.setKeys(this.crossSigningKeys.keys);\n }\n // set account data\n if (this.accountData) {\n for (const [type, content] of this.accountData) {\n await baseApis.setAccountData(type, content);\n }\n }\n // upload first cross-signing signatures with the new key\n // (e.g. signing our own device)\n if (this.keySignatures) {\n await baseApis.uploadKeySignatures(this.keySignatures);\n }\n // need to create/update key backup info\n if (this.keyBackupInfo) {\n if (this.keyBackupInfo.version) {\n // session backup signature\n // The backup is trusted because the user provided the private key.\n // Sign the backup with the cross signing key so the key backup can\n // be trusted via cross-signing.\n await baseApis.http.authedRequest(\n undefined, \"PUT\", \"/room_keys/version/\" + this.keyBackupInfo.version,\n undefined, {\n algorithm: this.keyBackupInfo.algorithm,\n auth_data: this.keyBackupInfo.auth_data,\n },\n { prefix: PREFIX_UNSTABLE },\n );\n } else {\n // add new key backup\n await baseApis.http.authedRequest(\n undefined, \"POST\", \"/room_keys/version\",\n undefined, this.keyBackupInfo,\n { prefix: PREFIX_UNSTABLE },\n );\n }\n }\n }\n}\n\n/**\n * Catches account data set by SecretStorage during bootstrapping by\n * implementing the methods related to account data in MatrixClient\n */\nclass AccountDataClientAdapter extends EventEmitter {\n public readonly values = new Map<string, MatrixEvent>();\n\n /**\n * @param {Object.<String, MatrixEvent>} existingValues existing account data\n */\n constructor(private readonly existingValues: Record<string, MatrixEvent>) {\n super();\n }\n\n /**\n * @param {String} type\n * @return {Promise<Object>} the content of the account data\n */\n public getAccountDataFromServer(type: string): Promise<any> {\n return Promise.resolve(this.getAccountData(type));\n }\n\n /**\n * @param {String} type\n * @return {Object} the content of the account data\n */\n public getAccountData(type: string): MatrixEvent {\n const modifiedValue = this.values.get(type);\n if (modifiedValue) {\n return modifiedValue;\n }\n const existingValue = this.existingValues[type];\n if (existingValue) {\n return existingValue.getContent();\n }\n return null;\n }\n\n /**\n * @param {String} type\n * @param {Object} content\n * @return {Promise}\n */\n public setAccountData(type: string, content: any): Promise<void> {\n const lastEvent = this.values.get(type);\n this.values.set(type, content);\n // ensure accountData is emitted on the next tick,\n // as SecretStorage listens for it while calling this method\n // and it seems to rely on this.\n return Promise.resolve().then(() => {\n const event = new MatrixEvent({ type, content });\n this.emit(\"accountData\", event, lastEvent);\n });\n }\n}\n\n/**\n * Catches the private cross-signing keys set during bootstrapping\n * by both cache callbacks (see createCryptoStoreCacheCallbacks) as non-cache callbacks.\n * See CrossSigningInfo constructor\n */\nclass CrossSigningCallbacks implements ICryptoCallbacks, ICacheCallbacks {\n public readonly privateKeys = new Map<string, Uint8Array>();\n\n // cache callbacks\n public getCrossSigningKeyCache(type: string, expectedPublicKey: string): Promise<Uint8Array> {\n return this.getCrossSigningKey(type, expectedPublicKey);\n }\n\n public storeCrossSigningKeyCache(type: string, key: Uint8Array): Promise<void> {\n this.privateKeys.set(type, key);\n return Promise.resolve();\n }\n\n // non-cache callbacks\n public getCrossSigningKey(type: string, expectedPubkey: string): Promise<Uint8Array> {\n return Promise.resolve(this.privateKeys.get(type));\n }\n\n public saveCrossSigningKeys(privateKeys: Record<string, Uint8Array>) {\n for (const [type, privateKey] of Object.entries(privateKeys)) {\n this.privateKeys.set(type, privateKey);\n }\n }\n}\n\n/**\n * Catches the 4S private key set during bootstrapping by implementing\n * the SecretStorage crypto callbacks\n */\nclass SSSSCryptoCallbacks {\n private readonly privateKeys = new Map<string, Uint8Array>();\n\n constructor(private readonly delegateCryptoCallbacks: ICryptoCallbacks) {}\n\n public async getSecretStorageKey(\n { keys }: { keys: Record<string, ISecretStorageKeyInfo> },\n name: string,\n ): Promise<[string, Uint8Array]> {\n for (const keyId of Object.keys(keys)) {\n const privateKey = this.privateKeys.get(keyId);\n if (privateKey) {\n return [keyId, privateKey];\n }\n }\n // if we don't have the key cached yet, ask\n // for it to the general crypto callbacks and cache it\n if (this.delegateCryptoCallbacks) {\n const result = await this.delegateCryptoCallbacks.\n getSecretStorageKey({ keys }, name);\n if (result) {\n const [keyId, privateKey] = result;\n this.privateKeys.set(keyId, privateKey);\n }\n return result;\n }\n }\n\n public addPrivateKey(keyId: string, keyInfo: ISecretStorageKeyInfo, privKey: Uint8Array): void {\n this.privateKeys.set(keyId, privKey);\n // Also pass along to application to cache if it wishes\n this.delegateCryptoCallbacks?.cacheSecretStorageKey?.(keyId, keyInfo, privKey);\n }\n}\n",
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017, 2019 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../logger';\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport * as algorithms from './algorithms';\n\n// The maximum size of an event is 65K, and we base64 the content, so this is a\n// reasonable approximation to the biggest plaintext we can encrypt.\nconst MAX_PLAINTEXT_LENGTH = 65536 * 3 / 4;\n\nfunction checkPayloadLength(payloadString) {\n if (payloadString === undefined) {\n throw new Error(\"payloadString undefined\");\n }\n\n if (payloadString.length > MAX_PLAINTEXT_LENGTH) {\n // might as well fail early here rather than letting the olm library throw\n // a cryptic memory allocation error.\n //\n // Note that even if we manage to do the encryption, the message send may fail,\n // because by the time we've wrapped the ciphertext in the event object, it may\n // exceed 65K. But at least we won't just fail with \"abort()\" in that case.\n const err = new Error(\"Message too long (\" + payloadString.length + \" bytes). \" +\n \"The maximum for an encrypted message is \" +\n MAX_PLAINTEXT_LENGTH + \" bytes.\");\n // TODO: [TypeScript] We should have our own error types\n err.data = {\n errcode: \"M_TOO_LARGE\",\n error: \"Payload too large for encrypted message\",\n };\n throw err;\n }\n}\n\n/**\n * The type of object we use for importing and exporting megolm session data.\n *\n * @typedef {Object} module:crypto/OlmDevice.MegolmSessionData\n * @property {String} sender_key Sender's Curve25519 device key\n * @property {String[]} forwarding_curve25519_key_chain Devices which forwarded\n * this session to us (normally empty).\n * @property {Object<string, string>} sender_claimed_keys Other keys the sender claims.\n * @property {String} room_id Room this session is used in\n * @property {String} session_id Unique id for the session\n * @property {String} session_key Base64'ed key data\n */\n\n/**\n * Manages the olm cryptography functions. Each OlmDevice has a single\n * OlmAccount and a number of OlmSessions.\n *\n * Accounts and sessions are kept pickled in the cryptoStore.\n *\n * @constructor\n * @alias module:crypto/OlmDevice\n *\n * @param {Object} cryptoStore A store for crypto data\n *\n * @property {string} deviceCurve25519Key Curve25519 key for the account\n * @property {string} deviceEd25519Key Ed25519 key for the account\n */\nexport function OlmDevice(cryptoStore) {\n this._cryptoStore = cryptoStore;\n this._pickleKey = \"DEFAULT_KEY\";\n\n // don't know these until we load the account from storage in init()\n this.deviceCurve25519Key = null;\n this.deviceEd25519Key = null;\n this._maxOneTimeKeys = null;\n\n // we don't bother stashing outboundgroupsessions in the cryptoStore -\n // instead we keep them here.\n this._outboundGroupSessionStore = {};\n\n // Store a set of decrypted message indexes for each group session.\n // This partially mitigates a replay attack where a MITM resends a group\n // message into the room.\n //\n // When we decrypt a message and the message index matches a previously\n // decrypted message, one possible cause of that is that we are decrypting\n // the same event, and may not indicate an actual replay attack. For\n // example, this could happen if we receive events, forget about them, and\n // then re-fetch them when we backfill. So we store the event ID and\n // timestamp corresponding to each message index when we first decrypt it,\n // and compare these against the event ID and timestamp every time we use\n // that same index. If they match, then we're probably decrypting the same\n // event and we don't consider it a replay attack.\n //\n // Keys are strings of form \"<senderKey>|<session_id>|<message_index>\"\n // Values are objects of the form \"{id: <event id>, timestamp: <ts>}\"\n this._inboundGroupSessionMessageIndexes = {};\n\n // Keep track of sessions that we're starting, so that we don't start\n // multiple sessions for the same device at the same time.\n this._sessionsInProgress = {};\n\n // Used by olm to serialise prekey message decryptions\n this._olmPrekeyPromise = Promise.resolve();\n}\n\n/**\n * Initialise the OlmAccount. This must be called before any other operations\n * on the OlmDevice.\n *\n * Data from an exported Olm device can be provided\n * in order to re-create this device.\n *\n * Attempts to load the OlmAccount from the crypto store, or creates one if none is\n * found.\n *\n * Reads the device keys from the OlmAccount object.\n *\n * @param {object} opts\n * @param {object} opts.fromExportedDevice (Optional) data from exported device\n * that must be re-created.\n * If present, opts.pickleKey is ignored\n * (exported data already provides a pickle key)\n * @param {object} opts.pickleKey (Optional) pickle key to set instead of default one\n */\nOlmDevice.prototype.init = async function(opts = {}) {\n let e2eKeys;\n const account = new global.Olm.Account();\n\n const { pickleKey, fromExportedDevice } = opts;\n\n try {\n if (fromExportedDevice) {\n if (pickleKey) {\n logger.warn(\n 'ignoring opts.pickleKey'\n + ' because opts.fromExportedDevice is present.',\n );\n }\n this._pickleKey = fromExportedDevice.pickleKey;\n await _initialiseFromExportedDevice(\n fromExportedDevice,\n this._cryptoStore,\n this._pickleKey,\n account,\n );\n } else {\n if (pickleKey) {\n this._pickleKey = pickleKey;\n }\n await _initialiseAccount(\n this._cryptoStore,\n this._pickleKey,\n account,\n );\n }\n e2eKeys = JSON.parse(account.identity_keys());\n\n this._maxOneTimeKeys = account.max_number_of_one_time_keys();\n } finally {\n account.free();\n }\n\n this.deviceCurve25519Key = e2eKeys.curve25519;\n this.deviceEd25519Key = e2eKeys.ed25519;\n};\n\n/**\n * Populates the crypto store using data that was exported from an existing device.\n * Note that for now only the “account” and “sessions” stores are populated;\n * Other stores will be as with a new device.\n *\n * @param {Object} exportedData Data exported from another device\n * through the “export” method.\n * @param {module:crypto/store/base~CryptoStore} cryptoStore storage for the crypto layer\n * @param {string} pickleKey the key that was used to pickle the exported data\n * @param {Olm.Account} account an olm account to initialize\n */\nasync function _initialiseFromExportedDevice(\n exportedData,\n cryptoStore,\n pickleKey,\n account,\n) {\n await cryptoStore.doTxn(\n 'readwrite',\n [\n IndexedDBCryptoStore.STORE_ACCOUNT,\n IndexedDBCryptoStore.STORE_SESSIONS,\n ],\n (txn) => {\n cryptoStore.storeAccount(txn, exportedData.pickledAccount);\n exportedData.sessions.forEach((session) => {\n const {\n deviceKey,\n sessionId,\n } = session;\n const sessionInfo = {\n session: session.session,\n lastReceivedMessageTs: session.lastReceivedMessageTs,\n };\n cryptoStore.storeEndToEndSession(\n deviceKey,\n sessionId,\n sessionInfo,\n txn,\n );\n });\n });\n account.unpickle(pickleKey, exportedData.pickledAccount);\n}\n\nasync function _initialiseAccount(cryptoStore, pickleKey, account) {\n await cryptoStore.doTxn(\n 'readwrite',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n cryptoStore.getAccount(txn, (pickledAccount) => {\n if (pickledAccount !== null) {\n account.unpickle(pickleKey, pickledAccount);\n } else {\n account.create();\n pickledAccount = account.pickle(pickleKey);\n cryptoStore.storeAccount(txn, pickledAccount);\n }\n });\n },\n );\n}\n\n/**\n * @return {array} The version of Olm.\n */\nOlmDevice.getOlmVersion = function() {\n return global.Olm.get_library_version();\n};\n\n/**\n * extract our OlmAccount from the crypto store and call the given function\n * with the account object\n * The `account` object is useable only within the callback passed to this\n * function and will be freed as soon the callback returns. It is *not*\n * useable for the rest of the lifetime of the transaction.\n * This function requires a live transaction object from cryptoStore.doTxn()\n * and therefore may only be called in a doTxn() callback.\n *\n * @param {*} txn Opaque transaction object from cryptoStore.doTxn()\n * @param {function} func\n * @private\n */\nOlmDevice.prototype._getAccount = function(txn, func) {\n this._cryptoStore.getAccount(txn, (pickledAccount) => {\n const account = new global.Olm.Account();\n try {\n account.unpickle(this._pickleKey, pickledAccount);\n func(account);\n } finally {\n account.free();\n }\n });\n};\n\n/*\n * Saves an account to the crypto store.\n * This function requires a live transaction object from cryptoStore.doTxn()\n * and therefore may only be called in a doTxn() callback.\n *\n * @param {*} txn Opaque transaction object from cryptoStore.doTxn()\n * @param {object} Olm.Account object\n * @private\n */\nOlmDevice.prototype._storeAccount = function(txn, account) {\n this._cryptoStore.storeAccount(txn, account.pickle(this._pickleKey));\n};\n\n/**\n * Export data for re-creating the Olm device later.\n * TODO export data other than just account and (P2P) sessions.\n *\n * @return {Promise<object>} The exported data\n*/\nOlmDevice.prototype.export = async function() {\n const result = {\n pickleKey: this._pickleKey,\n };\n await this._cryptoStore.doTxn(\n 'readonly',\n [\n IndexedDBCryptoStore.STORE_ACCOUNT,\n IndexedDBCryptoStore.STORE_SESSIONS,\n ],\n (txn) => {\n this._cryptoStore.getAccount(txn, (pickledAccount) => {\n result.pickledAccount = pickledAccount;\n });\n result.sessions = [];\n // Note that the pickledSession object we get in the callback\n // is not exactly the same thing you get in method _getSession\n // see documentation of IndexedDBCryptoStore.getAllEndToEndSessions\n this._cryptoStore.getAllEndToEndSessions(txn, (pickledSession) => {\n result.sessions.push(pickledSession);\n });\n },\n );\n return result;\n};\n\n/**\n * extract an OlmSession from the session store and call the given function\n * The session is useable only within the callback passed to this\n * function and will be freed as soon the callback returns. It is *not*\n * useable for the rest of the lifetime of the transaction.\n *\n * @param {string} deviceKey\n * @param {string} sessionId\n * @param {*} txn Opaque transaction object from cryptoStore.doTxn()\n * @param {function} func\n * @private\n */\nOlmDevice.prototype._getSession = function(deviceKey, sessionId, txn, func) {\n this._cryptoStore.getEndToEndSession(\n deviceKey, sessionId, txn, (sessionInfo) => {\n this._unpickleSession(sessionInfo, func);\n },\n );\n};\n\n/**\n * Creates a session object from a session pickle and executes the given\n * function with it. The session object is destroyed once the function\n * returns.\n *\n * @param {object} sessionInfo\n * @param {function} func\n * @private\n */\nOlmDevice.prototype._unpickleSession = function(sessionInfo, func) {\n const session = new global.Olm.Session();\n try {\n session.unpickle(this._pickleKey, sessionInfo.session);\n const unpickledSessInfo = Object.assign({}, sessionInfo, { session });\n\n func(unpickledSessInfo);\n } finally {\n session.free();\n }\n};\n\n/**\n * store our OlmSession in the session store\n *\n * @param {string} deviceKey\n * @param {object} sessionInfo {session: OlmSession, lastReceivedMessageTs: int}\n * @param {*} txn Opaque transaction object from cryptoStore.doTxn()\n * @private\n */\nOlmDevice.prototype._saveSession = function(deviceKey, sessionInfo, txn) {\n const sessionId = sessionInfo.session.session_id();\n const pickledSessionInfo = Object.assign(sessionInfo, {\n session: sessionInfo.session.pickle(this._pickleKey),\n });\n this._cryptoStore.storeEndToEndSession(\n deviceKey, sessionId, pickledSessionInfo, txn,\n );\n};\n\n/**\n * get an OlmUtility and call the given function\n *\n * @param {function} func\n * @return {object} result of func\n * @private\n */\nOlmDevice.prototype._getUtility = function(func) {\n const utility = new global.Olm.Utility();\n try {\n return func(utility);\n } finally {\n utility.free();\n }\n};\n\n/**\n * Signs a message with the ed25519 key for this account.\n *\n * @param {string} message message to be signed\n * @return {Promise<string>} base64-encoded signature\n */\nOlmDevice.prototype.sign = async function(message) {\n let result;\n await this._cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this._getAccount(txn, (account) => {\n result = account.sign(message);\n },\n );\n });\n return result;\n};\n\n/**\n * Get the current (unused, unpublished) one-time keys for this account.\n *\n * @return {object} one time keys; an object with the single property\n * <tt>curve25519</tt>, which is itself an object mapping key id to Curve25519\n * key.\n */\nOlmDevice.prototype.getOneTimeKeys = async function() {\n let result;\n await this._cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this._getAccount(txn, (account) => {\n result = JSON.parse(account.one_time_keys());\n });\n },\n );\n\n return result;\n};\n\n/**\n * Get the maximum number of one-time keys we can store.\n *\n * @return {number} number of keys\n */\nOlmDevice.prototype.maxNumberOfOneTimeKeys = function() {\n return this._maxOneTimeKeys;\n};\n\n/**\n * Marks all of the one-time keys as published.\n */\nOlmDevice.prototype.markKeysAsPublished = async function() {\n await this._cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this._getAccount(txn, (account) => {\n account.mark_keys_as_published();\n this._storeAccount(txn, account);\n });\n },\n );\n};\n\n/**\n * Generate some new one-time keys\n *\n * @param {number} numKeys number of keys to generate\n * @return {Promise} Resolved once the account is saved back having generated the keys\n */\nOlmDevice.prototype.generateOneTimeKeys = function(numKeys) {\n return this._cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this._getAccount(txn, (account) => {\n account.generate_one_time_keys(numKeys);\n this._storeAccount(txn, account);\n });\n },\n );\n};\n\n/**\n * Generate a new fallback keys\n *\n * @return {Promise} Resolved once the account is saved back having generated the key\n */\nOlmDevice.prototype.generateFallbackKey = async function() {\n await this._cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this._getAccount(txn, (account) => {\n account.generate_fallback_key();\n this._storeAccount(txn, account);\n });\n },\n );\n};\n\nOlmDevice.prototype.getFallbackKey = async function() {\n let result;\n await this._cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this._getAccount(txn, (account) => {\n result = JSON.parse(account.fallback_key());\n });\n },\n );\n return result;\n};\n\n/**\n * Generate a new outbound session\n *\n * The new session will be stored in the cryptoStore.\n *\n * @param {string} theirIdentityKey remote user's Curve25519 identity key\n * @param {string} theirOneTimeKey remote user's one-time Curve25519 key\n * @return {string} sessionId for the outbound session.\n */\nOlmDevice.prototype.createOutboundSession = async function(\n theirIdentityKey, theirOneTimeKey,\n) {\n let newSessionId;\n await this._cryptoStore.doTxn(\n 'readwrite', [\n IndexedDBCryptoStore.STORE_ACCOUNT,\n IndexedDBCryptoStore.STORE_SESSIONS,\n ],\n (txn) => {\n this._getAccount(txn, (account) => {\n const session = new global.Olm.Session();\n try {\n session.create_outbound(account, theirIdentityKey, theirOneTimeKey);\n newSessionId = session.session_id();\n this._storeAccount(txn, account);\n const sessionInfo = {\n session,\n // Pretend we've received a message at this point, otherwise\n // if we try to send a message to the device, it won't use\n // this session\n lastReceivedMessageTs: Date.now(),\n };\n this._saveSession(theirIdentityKey, sessionInfo, txn);\n } finally {\n session.free();\n }\n });\n },\n logger.withPrefix(\"[createOutboundSession]\"),\n );\n return newSessionId;\n};\n\n/**\n * Generate a new inbound session, given an incoming message\n *\n * @param {string} theirDeviceIdentityKey remote user's Curve25519 identity key\n * @param {number} messageType messageType field from the received message (must be 0)\n * @param {string} ciphertext base64-encoded body from the received message\n *\n * @return {{payload: string, session_id: string}} decrypted payload, and\n * session id of new session\n *\n * @raises {Error} if the received message was not valid (for instance, it\n * didn't use a valid one-time key).\n */\nOlmDevice.prototype.createInboundSession = async function(\n theirDeviceIdentityKey, messageType, ciphertext,\n) {\n if (messageType !== 0) {\n throw new Error(\"Need messageType == 0 to create inbound session\");\n }\n\n let result;\n await this._cryptoStore.doTxn(\n 'readwrite', [\n IndexedDBCryptoStore.STORE_ACCOUNT,\n IndexedDBCryptoStore.STORE_SESSIONS,\n ],\n (txn) => {\n this._getAccount(txn, (account) => {\n const session = new global.Olm.Session();\n try {\n session.create_inbound_from(\n account, theirDeviceIdentityKey, ciphertext,\n );\n account.remove_one_time_keys(session);\n this._storeAccount(txn, account);\n\n const payloadString = session.decrypt(messageType, ciphertext);\n\n const sessionInfo = {\n session,\n // this counts as a received message: set last received message time\n // to now\n lastReceivedMessageTs: Date.now(),\n };\n this._saveSession(theirDeviceIdentityKey, sessionInfo, txn);\n\n result = {\n payload: payloadString,\n session_id: session.session_id(),\n };\n } finally {\n session.free();\n }\n });\n },\n logger.withPrefix(\"[createInboundSession]\"),\n );\n\n return result;\n};\n\n/**\n * Get a list of known session IDs for the given device\n *\n * @param {string} theirDeviceIdentityKey Curve25519 identity key for the\n * remote device\n * @return {Promise<string[]>} a list of known session ids for the device\n */\nOlmDevice.prototype.getSessionIdsForDevice = async function(theirDeviceIdentityKey) {\n const log = logger.withPrefix(\"[getSessionIdsForDevice]\");\n\n if (this._sessionsInProgress[theirDeviceIdentityKey]) {\n log.debug(`Waiting for Olm session for ${theirDeviceIdentityKey} to be created`);\n try {\n await this._sessionsInProgress[theirDeviceIdentityKey];\n } catch (e) {\n // if the session failed to be created, just fall through and\n // return an empty result\n }\n }\n let sessionIds;\n await this._cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this._cryptoStore.getEndToEndSessions(\n theirDeviceIdentityKey, txn, (sessions) => {\n sessionIds = Object.keys(sessions);\n },\n );\n },\n log,\n );\n\n return sessionIds;\n};\n\n/**\n * Get the right olm session id for encrypting messages to the given identity key\n *\n * @param {string} theirDeviceIdentityKey Curve25519 identity key for the\n * remote device\n * @param {boolean} nowait Don't wait for an in-progress session to complete.\n * This should only be set to true of the calling function is the function\n * that marked the session as being in-progress.\n * @param {Logger} [log] A possibly customised log\n * @return {Promise<?string>} session id, or null if no established session\n */\nOlmDevice.prototype.getSessionIdForDevice = async function(\n theirDeviceIdentityKey, nowait, log,\n) {\n const sessionInfos = await this.getSessionInfoForDevice(\n theirDeviceIdentityKey, nowait, log,\n );\n\n if (sessionInfos.length === 0) {\n return null;\n }\n // Use the session that has most recently received a message\n let idxOfBest = 0;\n for (let i = 1; i < sessionInfos.length; i++) {\n const thisSessInfo = sessionInfos[i];\n const thisLastReceived = thisSessInfo.lastReceivedMessageTs === undefined ?\n 0 : thisSessInfo.lastReceivedMessageTs;\n\n const bestSessInfo = sessionInfos[idxOfBest];\n const bestLastReceived = bestSessInfo.lastReceivedMessageTs === undefined ?\n 0 : bestSessInfo.lastReceivedMessageTs;\n if (\n thisLastReceived > bestLastReceived || (\n thisLastReceived === bestLastReceived &&\n thisSessInfo.sessionId < bestSessInfo.sessionId\n )\n ) {\n idxOfBest = i;\n }\n }\n return sessionInfos[idxOfBest].sessionId;\n};\n\n/**\n * Get information on the active Olm sessions for a device.\n * <p>\n * Returns an array, with an entry for each active session. The first entry in\n * the result will be the one used for outgoing messages. Each entry contains\n * the keys 'hasReceivedMessage' (true if the session has received an incoming\n * message and is therefore past the pre-key stage), and 'sessionId'.\n *\n * @param {string} deviceIdentityKey Curve25519 identity key for the device\n * @param {boolean} nowait Don't wait for an in-progress session to complete.\n * This should only be set to true of the calling function is the function\n * that marked the session as being in-progress.\n * @param {Logger} [log] A possibly customised log\n * @return {Array.<{sessionId: string, hasReceivedMessage: Boolean}>}\n */\nOlmDevice.prototype.getSessionInfoForDevice = async function(\n deviceIdentityKey, nowait, log = logger,\n) {\n log = log.withPrefix(\"[getSessionInfoForDevice]\");\n\n if (this._sessionsInProgress[deviceIdentityKey] && !nowait) {\n log.debug(`Waiting for Olm session for ${deviceIdentityKey} to be created`);\n try {\n await this._sessionsInProgress[deviceIdentityKey];\n } catch (e) {\n // if the session failed to be created, then just fall through and\n // return an empty result\n }\n }\n const info = [];\n\n await this._cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this._cryptoStore.getEndToEndSessions(deviceIdentityKey, txn, (sessions) => {\n const sessionIds = Object.keys(sessions).sort();\n for (const sessionId of sessionIds) {\n this._unpickleSession(sessions[sessionId], (sessInfo) => {\n info.push({\n lastReceivedMessageTs: sessInfo.lastReceivedMessageTs,\n hasReceivedMessage: sessInfo.session.has_received_message(),\n sessionId: sessionId,\n });\n });\n }\n });\n },\n log,\n );\n\n return info;\n};\n\n/**\n * Encrypt an outgoing message using an existing session\n *\n * @param {string} theirDeviceIdentityKey Curve25519 identity key for the\n * remote device\n * @param {string} sessionId the id of the active session\n * @param {string} payloadString payload to be encrypted and sent\n *\n * @return {Promise<string>} ciphertext\n */\nOlmDevice.prototype.encryptMessage = async function(\n theirDeviceIdentityKey, sessionId, payloadString,\n) {\n checkPayloadLength(payloadString);\n\n let res;\n await this._cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this._getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => {\n const sessionDesc = sessionInfo.session.describe();\n logger.log(\n \"encryptMessage: Olm Session ID \" + sessionId + \" to \" +\n theirDeviceIdentityKey + \": \" + sessionDesc,\n );\n res = sessionInfo.session.encrypt(payloadString);\n this._saveSession(theirDeviceIdentityKey, sessionInfo, txn);\n });\n },\n logger.withPrefix(\"[encryptMessage]\"),\n );\n return res;\n};\n\n/**\n * Decrypt an incoming message using an existing session\n *\n * @param {string} theirDeviceIdentityKey Curve25519 identity key for the\n * remote device\n * @param {string} sessionId the id of the active session\n * @param {number} messageType messageType field from the received message\n * @param {string} ciphertext base64-encoded body from the received message\n *\n * @return {Promise<string>} decrypted payload.\n */\nOlmDevice.prototype.decryptMessage = async function(\n theirDeviceIdentityKey, sessionId, messageType, ciphertext,\n) {\n let payloadString;\n await this._cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this._getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => {\n const sessionDesc = sessionInfo.session.describe();\n logger.log(\n \"decryptMessage: Olm Session ID \" + sessionId + \" from \" +\n theirDeviceIdentityKey + \": \" + sessionDesc,\n );\n payloadString = sessionInfo.session.decrypt(messageType, ciphertext);\n sessionInfo.lastReceivedMessageTs = Date.now();\n this._saveSession(theirDeviceIdentityKey, sessionInfo, txn);\n });\n },\n logger.withPrefix(\"[decryptMessage]\"),\n );\n return payloadString;\n};\n\n/**\n * Determine if an incoming messages is a prekey message matching an existing session\n *\n * @param {string} theirDeviceIdentityKey Curve25519 identity key for the\n * remote device\n * @param {string} sessionId the id of the active session\n * @param {number} messageType messageType field from the received message\n * @param {string} ciphertext base64-encoded body from the received message\n *\n * @return {Promise<boolean>} true if the received message is a prekey message which matches\n * the given session.\n */\nOlmDevice.prototype.matchesSession = async function(\n theirDeviceIdentityKey, sessionId, messageType, ciphertext,\n) {\n if (messageType !== 0) {\n return false;\n }\n\n let matches;\n await this._cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this._getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => {\n matches = sessionInfo.session.matches_inbound(ciphertext);\n });\n },\n logger.withPrefix(\"[matchesSession]\"),\n );\n return matches;\n};\n\nOlmDevice.prototype.recordSessionProblem = async function(deviceKey, type, fixed) {\n await this._cryptoStore.storeEndToEndSessionProblem(deviceKey, type, fixed);\n};\n\nOlmDevice.prototype.sessionMayHaveProblems = async function(deviceKey, timestamp) {\n return await this._cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp);\n};\n\nOlmDevice.prototype.filterOutNotifiedErrorDevices = async function(devices) {\n return await this._cryptoStore.filterOutNotifiedErrorDevices(devices);\n};\n\n// Outbound group session\n// ======================\n\n/**\n * store an OutboundGroupSession in _outboundGroupSessionStore\n *\n * @param {Olm.OutboundGroupSession} session\n * @private\n */\nOlmDevice.prototype._saveOutboundGroupSession = function(session) {\n const pickledSession = session.pickle(this._pickleKey);\n this._outboundGroupSessionStore[session.session_id()] = pickledSession;\n};\n\n/**\n * extract an OutboundGroupSession from _outboundGroupSessionStore and call the\n * given function\n *\n * @param {string} sessionId\n * @param {function} func\n * @return {object} result of func\n * @private\n */\nOlmDevice.prototype._getOutboundGroupSession = function(sessionId, func) {\n const pickled = this._outboundGroupSessionStore[sessionId];\n if (pickled === undefined) {\n throw new Error(\"Unknown outbound group session \" + sessionId);\n }\n\n const session = new global.Olm.OutboundGroupSession();\n try {\n session.unpickle(this._pickleKey, pickled);\n return func(session);\n } finally {\n session.free();\n }\n};\n\n/**\n * Generate a new outbound group session\n *\n * @return {string} sessionId for the outbound session.\n */\nOlmDevice.prototype.createOutboundGroupSession = function() {\n const session = new global.Olm.OutboundGroupSession();\n try {\n session.create();\n this._saveOutboundGroupSession(session);\n return session.session_id();\n } finally {\n session.free();\n }\n};\n\n/**\n * Encrypt an outgoing message with an outbound group session\n *\n * @param {string} sessionId the id of the outboundgroupsession\n * @param {string} payloadString payload to be encrypted and sent\n *\n * @return {string} ciphertext\n */\nOlmDevice.prototype.encryptGroupMessage = function(sessionId, payloadString) {\n const self = this;\n\n logger.log(`encrypting msg with megolm session ${sessionId}`);\n\n checkPayloadLength(payloadString);\n\n return this._getOutboundGroupSession(sessionId, function(session) {\n const res = session.encrypt(payloadString);\n self._saveOutboundGroupSession(session);\n return res;\n });\n};\n\n/**\n * Get the session keys for an outbound group session\n *\n * @param {string} sessionId the id of the outbound group session\n *\n * @return {{chain_index: number, key: string}} current chain index, and\n * base64-encoded secret key.\n */\nOlmDevice.prototype.getOutboundGroupSessionKey = function(sessionId) {\n return this._getOutboundGroupSession(sessionId, function(session) {\n return {\n chain_index: session.message_index(),\n key: session.session_key(),\n };\n });\n};\n\n// Inbound group session\n// =====================\n\n/**\n * data stored in the session store about an inbound group session\n *\n * @typedef {Object} InboundGroupSessionData\n * @property {string} room_Id\n * @property {string} session pickled Olm.InboundGroupSession\n * @property {Object<string, string>} keysClaimed\n * @property {Array<string>} forwardingCurve25519KeyChain Devices involved in forwarding\n * this session to us (normally empty).\n */\n\n/**\n * Unpickle a session from a sessionData object and invoke the given function.\n * The session is valid only until func returns.\n *\n * @param {Object} sessionData Object describing the session.\n * @param {function(Olm.InboundGroupSession)} func Invoked with the unpickled session\n * @return {*} result of func\n */\nOlmDevice.prototype._unpickleInboundGroupSession = function(sessionData, func) {\n const session = new global.Olm.InboundGroupSession();\n try {\n session.unpickle(this._pickleKey, sessionData.session);\n return func(session);\n } finally {\n session.free();\n }\n};\n\n/**\n * extract an InboundGroupSession from the crypto store and call the given function\n *\n * @param {string} roomId The room ID to extract the session for, or null to fetch\n * sessions for any room.\n * @param {string} senderKey\n * @param {string} sessionId\n * @param {*} txn Opaque transaction object from cryptoStore.doTxn()\n * @param {function(Olm.InboundGroupSession, InboundGroupSessionData)} func\n * function to call.\n *\n * @private\n */\nOlmDevice.prototype._getInboundGroupSession = function(\n roomId, senderKey, sessionId, txn, func,\n) {\n this._cryptoStore.getEndToEndInboundGroupSession(\n senderKey, sessionId, txn, (sessionData, withheld) => {\n if (sessionData === null) {\n func(null, null, withheld);\n return;\n }\n\n // if we were given a room ID, check that the it matches the original one for the session. This stops\n // the HS pretending a message was targeting a different room.\n if (roomId !== null && roomId !== sessionData.room_id) {\n throw new Error(\n \"Mismatched room_id for inbound group session (expected \" +\n sessionData.room_id + \", was \" + roomId + \")\",\n );\n }\n\n this._unpickleInboundGroupSession(sessionData, (session) => {\n func(session, sessionData, withheld);\n });\n },\n );\n};\n\n/**\n * Add an inbound group session to the session store\n *\n * @param {string} roomId room in which this session will be used\n * @param {string} senderKey base64-encoded curve25519 key of the sender\n * @param {Array<string>} forwardingCurve25519KeyChain Devices involved in forwarding\n * this session to us.\n * @param {string} sessionId session identifier\n * @param {string} sessionKey base64-encoded secret key\n * @param {Object<string, string>} keysClaimed Other keys the sender claims.\n * @param {boolean} exportFormat true if the megolm keys are in export format\n * (ie, they lack an ed25519 signature)\n * @param {Object} [extraSessionData={}] any other data to be include with the session\n */\nOlmDevice.prototype.addInboundGroupSession = async function(\n roomId, senderKey, forwardingCurve25519KeyChain,\n sessionId, sessionKey, keysClaimed,\n exportFormat, extraSessionData = {},\n) {\n await this._cryptoStore.doTxn(\n 'readwrite', [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS,\n ], (txn) => {\n /* if we already have this session, consider updating it */\n this._getInboundGroupSession(\n roomId, senderKey, sessionId, txn,\n (existingSession, existingSessionData) => {\n // new session.\n const session = new global.Olm.InboundGroupSession();\n try {\n if (exportFormat) {\n session.import_session(sessionKey);\n } else {\n session.create(sessionKey);\n }\n if (sessionId != session.session_id()) {\n throw new Error(\n \"Mismatched group session ID from senderKey: \" +\n senderKey,\n );\n }\n\n if (existingSession) {\n logger.log(\n \"Update for megolm session \"\n + senderKey + \"/\" + sessionId,\n );\n if (existingSession.first_known_index()\n <= session.first_known_index()\n && !(existingSession.first_known_index() == session.first_known_index()\n && !extraSessionData.untrusted\n && existingSessionData.untrusted)) {\n // existing session has lower index (i.e. can\n // decrypt more), or they have the same index and\n // the new sessions trust does not win over the old\n // sessions trust, so keep it\n logger.log(\n `Keeping existing megolm session ${sessionId}`,\n );\n return;\n }\n }\n\n logger.info(\n \"Storing megolm session \" + senderKey + \"/\" + sessionId +\n \" with first index \" + session.first_known_index(),\n );\n\n const sessionData = Object.assign({}, extraSessionData, {\n room_id: roomId,\n session: session.pickle(this._pickleKey),\n keysClaimed: keysClaimed,\n forwardingCurve25519KeyChain: forwardingCurve25519KeyChain,\n });\n\n this._cryptoStore.storeEndToEndInboundGroupSession(\n senderKey, sessionId, sessionData, txn,\n );\n\n if (!existingSession && extraSessionData.sharedHistory) {\n this._cryptoStore.addSharedHistoryInboundGroupSession(\n roomId, senderKey, sessionId, txn,\n );\n }\n } finally {\n session.free();\n }\n },\n );\n },\n logger.withPrefix(\"[addInboundGroupSession]\"),\n );\n};\n\n/**\n * Record in the data store why an inbound group session was withheld.\n *\n * @param {string} roomId room that the session belongs to\n * @param {string} senderKey base64-encoded curve25519 key of the sender\n * @param {string} sessionId session identifier\n * @param {string} code reason code\n * @param {string} reason human-readable version of `code`\n */\nOlmDevice.prototype.addInboundGroupSessionWithheld = async function(\n roomId, senderKey, sessionId, code, reason,\n) {\n await this._cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],\n (txn) => {\n this._cryptoStore.storeEndToEndInboundGroupSessionWithheld(\n senderKey, sessionId,\n {\n room_id: roomId,\n code: code,\n reason: reason,\n },\n txn,\n );\n },\n );\n};\n\nexport const WITHHELD_MESSAGES = {\n \"m.unverified\": \"The sender has disabled encrypting to unverified devices.\",\n \"m.blacklisted\": \"The sender has blocked you.\",\n \"m.unauthorised\": \"You are not authorised to read the message.\",\n \"m.no_olm\": \"Unable to establish a secure channel.\",\n};\n\n/**\n * Calculate the message to use for the exception when a session key is withheld.\n *\n * @param {object} withheld An object that describes why the key was withheld.\n *\n * @return {string} the message\n *\n * @private\n */\nfunction _calculateWithheldMessage(withheld) {\n if (withheld.code && withheld.code in WITHHELD_MESSAGES) {\n return WITHHELD_MESSAGES[withheld.code];\n } else if (withheld.reason) {\n return withheld.reason;\n } else {\n return \"decryption key withheld\";\n }\n}\n\n/**\n * Decrypt a received message with an inbound group session\n *\n * @param {string} roomId room in which the message was received\n * @param {string} senderKey base64-encoded curve25519 key of the sender\n * @param {string} sessionId session identifier\n * @param {string} body base64-encoded body of the encrypted message\n * @param {string} eventId ID of the event being decrypted\n * @param {Number} timestamp timestamp of the event being decrypted\n *\n * @return {null} the sessionId is unknown\n *\n * @return {Promise<{result: string, senderKey: string,\n * forwardingCurve25519KeyChain: Array<string>,\n * keysClaimed: Object<string, string>}>}\n */\nOlmDevice.prototype.decryptGroupMessage = async function(\n roomId, senderKey, sessionId, body, eventId, timestamp,\n) {\n let result;\n // when the localstorage crypto store is used as an indexeddb backend,\n // exceptions thrown from within the inner function are not passed through\n // to the top level, so we store exceptions in a variable and raise them at\n // the end\n let error;\n\n await this._cryptoStore.doTxn(\n 'readwrite', [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ], (txn) => {\n this._getInboundGroupSession(\n roomId, senderKey, sessionId, txn, (session, sessionData, withheld) => {\n if (session === null) {\n if (withheld) {\n error = new algorithms.DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n _calculateWithheldMessage(withheld),\n {\n session: senderKey + '|' + sessionId,\n },\n );\n }\n result = null;\n return;\n }\n let res;\n try {\n res = session.decrypt(body);\n } catch (e) {\n if (e && e.message === 'OLM.UNKNOWN_MESSAGE_INDEX' && withheld) {\n error = new algorithms.DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n _calculateWithheldMessage(withheld),\n {\n session: senderKey + '|' + sessionId,\n },\n );\n } else {\n error = e;\n }\n return;\n }\n\n let plaintext = res.plaintext;\n if (plaintext === undefined) {\n // Compatibility for older olm versions.\n plaintext = res;\n } else {\n // Check if we have seen this message index before to detect replay attacks.\n // If the event ID and timestamp are specified, and the match the event ID\n // and timestamp from the last time we used this message index, then we\n // don't consider it a replay attack.\n const messageIndexKey = (\n senderKey + \"|\" + sessionId + \"|\" + res.message_index\n );\n if (messageIndexKey in this._inboundGroupSessionMessageIndexes) {\n const msgInfo = (\n this._inboundGroupSessionMessageIndexes[messageIndexKey]\n );\n if (\n msgInfo.id !== eventId ||\n msgInfo.timestamp !== timestamp\n ) {\n error = new Error(\n \"Duplicate message index, possible replay attack: \" +\n messageIndexKey,\n );\n return;\n }\n }\n this._inboundGroupSessionMessageIndexes[messageIndexKey] = {\n id: eventId,\n timestamp: timestamp,\n };\n }\n\n sessionData.session = session.pickle(this._pickleKey);\n this._cryptoStore.storeEndToEndInboundGroupSession(\n senderKey, sessionId, sessionData, txn,\n );\n result = {\n result: plaintext,\n keysClaimed: sessionData.keysClaimed || {},\n senderKey: senderKey,\n forwardingCurve25519KeyChain: (\n sessionData.forwardingCurve25519KeyChain || []\n ),\n untrusted: sessionData.untrusted,\n };\n },\n );\n },\n logger.withPrefix(\"[decryptGroupMessage]\"),\n );\n\n if (error) {\n throw error;\n }\n return result;\n};\n\n/**\n * Determine if we have the keys for a given megolm session\n *\n * @param {string} roomId room in which the message was received\n * @param {string} senderKey base64-encoded curve25519 key of the sender\n * @param {string} sessionId session identifier\n *\n * @returns {Promise<boolean>} true if we have the keys to this session\n */\nOlmDevice.prototype.hasInboundSessionKeys = async function(roomId, senderKey, sessionId) {\n let result;\n await this._cryptoStore.doTxn(\n 'readonly', [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ], (txn) => {\n this._cryptoStore.getEndToEndInboundGroupSession(\n senderKey, sessionId, txn, (sessionData) => {\n if (sessionData === null) {\n result = false;\n return;\n }\n\n if (roomId !== sessionData.room_id) {\n logger.warn(\n `requested keys for inbound group session ${senderKey}|` +\n `${sessionId}, with incorrect room_id ` +\n `(expected ${sessionData.room_id}, ` +\n `was ${roomId})`,\n );\n result = false;\n } else {\n result = true;\n }\n },\n );\n },\n logger.withPrefix(\"[hasInboundSessionKeys]\"),\n );\n\n return result;\n};\n\n/**\n * Extract the keys to a given megolm session, for sharing\n *\n * @param {string} roomId room in which the message was received\n * @param {string} senderKey base64-encoded curve25519 key of the sender\n * @param {string} sessionId session identifier\n * @param {integer} chainIndex The chain index at which to export the session.\n * If omitted, export at the first index we know about.\n *\n * @returns {Promise<{chain_index: number, key: string,\n * forwarding_curve25519_key_chain: Array<string>,\n * sender_claimed_ed25519_key: string\n * }>}\n * details of the session key. The key is a base64-encoded megolm key in\n * export format.\n *\n * @throws Error If the given chain index could not be obtained from the known\n * index (ie. the given chain index is before the first we have).\n */\nOlmDevice.prototype.getInboundGroupSessionKey = async function(\n roomId, senderKey, sessionId, chainIndex,\n) {\n let result;\n await this._cryptoStore.doTxn(\n 'readonly', [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ], (txn) => {\n this._getInboundGroupSession(\n roomId, senderKey, sessionId, txn, (session, sessionData) => {\n if (session === null) {\n result = null;\n return;\n }\n\n if (chainIndex === undefined) {\n chainIndex = session.first_known_index();\n }\n\n const exportedSession = session.export_session(chainIndex);\n\n const claimedKeys = sessionData.keysClaimed || {};\n const senderEd25519Key = claimedKeys.ed25519 || null;\n\n result = {\n \"chain_index\": chainIndex,\n \"key\": exportedSession,\n \"forwarding_curve25519_key_chain\":\n sessionData.forwardingCurve25519KeyChain || [],\n \"sender_claimed_ed25519_key\": senderEd25519Key,\n \"shared_history\": sessionData.sharedHistory || false,\n };\n },\n );\n },\n logger.withPrefix(\"[getInboundGroupSessionKey]\"),\n );\n\n return result;\n};\n\n/**\n * Export an inbound group session\n *\n * @param {string} senderKey base64-encoded curve25519 key of the sender\n * @param {string} sessionId session identifier\n * @param {string} sessionData The session object from the store\n * @return {module:crypto/OlmDevice.MegolmSessionData} exported session data\n */\nOlmDevice.prototype.exportInboundGroupSession = function(\n senderKey, sessionId, sessionData,\n) {\n return this._unpickleInboundGroupSession(sessionData, (session) => {\n const messageIndex = session.first_known_index();\n\n return {\n \"sender_key\": senderKey,\n \"sender_claimed_keys\": sessionData.keysClaimed,\n \"room_id\": sessionData.room_id,\n \"session_id\": sessionId,\n \"session_key\": session.export_session(messageIndex),\n \"forwarding_curve25519_key_chain\": session.forwardingCurve25519KeyChain || [],\n \"first_known_index\": session.first_known_index(),\n \"org.matrix.msc3061.shared_history\": sessionData.sharedHistory || false,\n };\n });\n};\n\nOlmDevice.prototype.getSharedHistoryInboundGroupSessions = async function(roomId) {\n let result;\n await this._cryptoStore.doTxn(\n 'readonly', [\n IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS,\n ], (txn) => {\n result = this._cryptoStore.getSharedHistoryInboundGroupSessions(roomId, txn);\n },\n logger.withPrefix(\"[getSharedHistoryInboundGroupSessionsForRoom]\"),\n );\n return result;\n};\n\n// Utilities\n// =========\n\n/**\n * Verify an ed25519 signature.\n *\n * @param {string} key ed25519 key\n * @param {string} message message which was signed\n * @param {string} signature base64-encoded signature to be checked\n *\n * @raises {Error} if there is a problem with the verification. If the key was\n * too small then the message will be \"OLM.INVALID_BASE64\". If the signature\n * was invalid then the message will be \"OLM.BAD_MESSAGE_MAC\".\n */\nOlmDevice.prototype.verifySignature = function(\n key, message, signature,\n) {\n this._getUtility(function(util) {\n util.ed25519_verify(key, message, signature);\n });\n};\n",
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../logger';\nimport { CryptoStore, MatrixClient } from \"../client\";\nimport { IRoomKeyRequestBody, IRoomKeyRequestRecipient } from \"./index\";\nimport { OutgoingRoomKeyRequest } from './store/base';\nimport { EventType } from \"../@types/event\";\n\n/**\n * Internal module. Management of outgoing room key requests.\n *\n * See https://docs.google.com/document/d/1m4gQkcnJkxNuBmb5NoFCIadIY-DyqqNAS3lloE73BlQ\n * for draft documentation on what we're supposed to be implementing here.\n *\n * @module\n */\n\n// delay between deciding we want some keys, and sending out the request, to\n// allow for (a) it turning up anyway, (b) grouping requests together\nconst SEND_KEY_REQUESTS_DELAY_MS = 500;\n\n/** possible states for a room key request\n *\n * The state machine looks like:\n *\n * | (cancellation sent)\n * | .-------------------------------------------------.\n * | | |\n * V V (cancellation requested) |\n * UNSENT -----------------------------+ |\n * | | |\n * | | |\n * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND\n * V | Λ\n * SENT | |\n * |-------------------------------- | --------------'\n * | | (cancellation requested with intent\n * | | to resend the original request)\n * | |\n * | (cancellation requested) |\n * V |\n * CANCELLATION_PENDING |\n * | |\n * | (cancellation sent) |\n * V |\n * (deleted) <---------------------------+\n *\n * @enum {number}\n */\nexport enum RoomKeyRequestState {\n /** request not yet sent */\n Unsent,\n /** request sent, awaiting reply */\n Sent,\n /** reply received, cancellation not yet sent */\n CancellationPending,\n /**\n * Cancellation not yet sent and will transition to UNSENT instead of\n * being deleted once the cancellation has been sent.\n */\n CancellationPendingAndWillResend,\n}\n\nexport class OutgoingRoomKeyRequestManager {\n // handle for the delayed call to sendOutgoingRoomKeyRequests. Non-null\n // if the callback has been set, or if it is still running.\n private sendOutgoingRoomKeyRequestsTimer: NodeJS.Timeout = null;\n\n // sanity check to ensure that we don't end up with two concurrent runs\n // of sendOutgoingRoomKeyRequests\n private sendOutgoingRoomKeyRequestsRunning = false;\n\n private clientRunning = false;\n\n constructor(\n private readonly baseApis: MatrixClient,\n private readonly deviceId: string,\n private readonly cryptoStore: CryptoStore,\n ) {}\n\n /**\n * Called when the client is started. Sets background processes running.\n */\n public start(): void {\n this.clientRunning = true;\n }\n\n /**\n * Called when the client is stopped. Stops any running background processes.\n */\n public stop(): void {\n logger.log('stopping OutgoingRoomKeyRequestManager');\n // stop the timer on the next run\n this.clientRunning = false;\n }\n\n /**\n * Send any requests that have been queued\n */\n public sendQueuedRequests(): void {\n this.startTimer();\n }\n\n /**\n * Queue up a room key request, if we haven't already queued or sent one.\n *\n * The `requestBody` is compared (with a deep-equality check) against\n * previous queued or sent requests and if it matches, no change is made.\n * Otherwise, a request is added to the pending list, and a job is started\n * in the background to send it.\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * @param {Array<{userId: string, deviceId: string}>} recipients\n * @param {boolean} resend whether to resend the key request if there is\n * already one\n *\n * @returns {Promise} resolves when the request has been added to the\n * pending list (or we have established that a similar request already\n * exists)\n */\n public async queueRoomKeyRequest(\n requestBody: IRoomKeyRequestBody,\n recipients: IRoomKeyRequestRecipient[],\n resend = false,\n ): Promise<void> {\n const req = await this.cryptoStore.getOutgoingRoomKeyRequest(\n requestBody,\n );\n if (!req) {\n await this.cryptoStore.getOrAddOutgoingRoomKeyRequest({\n requestBody: requestBody,\n recipients: recipients,\n requestId: this.baseApis.makeTxnId(),\n state: RoomKeyRequestState.Unsent,\n });\n } else {\n switch (req.state) {\n case RoomKeyRequestState.CancellationPendingAndWillResend:\n case RoomKeyRequestState.Unsent:\n // nothing to do here, since we're going to send a request anyways\n return;\n\n case RoomKeyRequestState.CancellationPending: {\n // existing request is about to be cancelled. If we want to\n // resend, then change the state so that it resends after\n // cancelling. Otherwise, just cancel the cancellation.\n const state = resend ?\n RoomKeyRequestState.CancellationPendingAndWillResend :\n RoomKeyRequestState.Sent;\n await this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId, RoomKeyRequestState.CancellationPending, {\n state,\n cancellationTxnId: this.baseApis.makeTxnId(),\n },\n );\n break;\n }\n case RoomKeyRequestState.Sent: {\n // a request has already been sent. If we don't want to\n // resend, then do nothing. If we do want to, then cancel the\n // existing request and send a new one.\n if (resend) {\n const state =\n RoomKeyRequestState.CancellationPendingAndWillResend;\n const updatedReq =\n await this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId, RoomKeyRequestState.Sent, {\n state,\n cancellationTxnId: this.baseApis.makeTxnId(),\n // need to use a new transaction ID so that\n // the request gets sent\n requestTxnId: this.baseApis.makeTxnId(),\n },\n );\n if (!updatedReq) {\n // updateOutgoingRoomKeyRequest couldn't find the request\n // in state ROOM_KEY_REQUEST_STATES.SENT, so we must have\n // raced with another tab to mark the request cancelled.\n // Try again, to make sure the request is resent.\n return await this.queueRoomKeyRequest(\n requestBody, recipients, resend,\n );\n }\n\n // We don't want to wait for the timer, so we send it\n // immediately. (We might actually end up racing with the timer,\n // but that's ok: even if we make the request twice, we'll do it\n // with the same transaction_id, so only one message will get\n // sent).\n //\n // (We also don't want to wait for the response from the server\n // here, as it will slow down processing of received keys if we\n // do.)\n try {\n await this.sendOutgoingRoomKeyRequestCancellation(\n updatedReq,\n true,\n );\n } catch (e) {\n logger.error(\n \"Error sending room key request cancellation;\"\n + \" will retry later.\", e,\n );\n }\n // The request has transitioned from\n // CANCELLATION_PENDING_AND_WILL_RESEND to UNSENT. We\n // still need to resend the request which is now UNSENT, so\n // start the timer if it isn't already started.\n }\n break;\n }\n default:\n throw new Error('unhandled state: ' + req.state);\n }\n }\n }\n\n /**\n * Cancel room key requests, if any match the given requestBody\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n *\n * @returns {Promise} resolves when the request has been updated in our\n * pending list.\n */\n public cancelRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise<void> {\n return this.cryptoStore.getOutgoingRoomKeyRequest(\n requestBody,\n ).then((req) => {\n if (!req) {\n // no request was made for this key\n return;\n }\n switch (req.state) {\n case RoomKeyRequestState.CancellationPending:\n case RoomKeyRequestState.CancellationPendingAndWillResend:\n // nothing to do here\n return;\n\n case RoomKeyRequestState.Unsent:\n // just delete it\n\n // FIXME: ghahah we may have attempted to send it, and\n // not yet got a successful response. So the server\n // may have seen it, so we still need to send a cancellation\n // in that case :/\n\n logger.log(\n 'deleting unnecessary room key request for ' +\n stringifyRequestBody(requestBody),\n );\n return this.cryptoStore.deleteOutgoingRoomKeyRequest(\n req.requestId, RoomKeyRequestState.Unsent,\n );\n\n case RoomKeyRequestState.Sent: {\n // send a cancellation.\n return this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId, RoomKeyRequestState.Sent, {\n state: RoomKeyRequestState.CancellationPending,\n cancellationTxnId: this.baseApis.makeTxnId(),\n },\n ).then((updatedReq) => {\n if (!updatedReq) {\n // updateOutgoingRoomKeyRequest couldn't find the\n // request in state ROOM_KEY_REQUEST_STATES.SENT,\n // so we must have raced with another tab to mark\n // the request cancelled. There is no point in\n // sending another cancellation since the other tab\n // will do it.\n logger.log(\n 'Tried to cancel room key request for ' +\n stringifyRequestBody(requestBody) +\n ' but it was already cancelled in another tab',\n );\n return;\n }\n\n // We don't want to wait for the timer, so we send it\n // immediately. (We might actually end up racing with the timer,\n // but that's ok: even if we make the request twice, we'll do it\n // with the same transaction_id, so only one message will get\n // sent).\n //\n // (We also don't want to wait for the response from the server\n // here, as it will slow down processing of received keys if we\n // do.)\n this.sendOutgoingRoomKeyRequestCancellation(\n updatedReq,\n ).catch((e) => {\n logger.error(\n \"Error sending room key request cancellation;\"\n + \" will retry later.\", e,\n );\n this.startTimer();\n });\n });\n }\n default:\n throw new Error('unhandled state: ' + req.state);\n }\n });\n }\n\n /**\n * Look for room key requests by target device and state\n *\n * @param {string} userId Target user ID\n * @param {string} deviceId Target device ID\n *\n * @return {Promise} resolves to a list of all the\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}\n */\n public getOutgoingSentRoomKeyRequest(userId: string, deviceId: string): OutgoingRoomKeyRequest[] {\n return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, [RoomKeyRequestState.Sent]);\n }\n\n /**\n * Find anything in `sent` state, and kick it around the loop again.\n * This is intended for situations where something substantial has changed, and we\n * don't really expect the other end to even care about the cancellation.\n * For example, after initialization or self-verification.\n * @return {Promise} An array of `queueRoomKeyRequest` outputs.\n */\n public async cancelAndResendAllOutgoingRequests(): Promise<void[]> {\n const outgoings = await this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(RoomKeyRequestState.Sent);\n return Promise.all(outgoings.map(({ requestBody, recipients }) =>\n this.queueRoomKeyRequest(requestBody, recipients, true)));\n }\n\n // start the background timer to send queued requests, if the timer isn't\n // already running\n private startTimer(): void {\n if (this.sendOutgoingRoomKeyRequestsTimer) {\n return;\n }\n\n const startSendingOutgoingRoomKeyRequests = () => {\n if (this.sendOutgoingRoomKeyRequestsRunning) {\n throw new Error(\"RoomKeyRequestSend already in progress!\");\n }\n this.sendOutgoingRoomKeyRequestsRunning = true;\n\n this.sendOutgoingRoomKeyRequests().finally(() => {\n this.sendOutgoingRoomKeyRequestsRunning = false;\n }).catch((e) => {\n // this should only happen if there is an indexeddb error,\n // in which case we're a bit stuffed anyway.\n logger.warn(\n `error in OutgoingRoomKeyRequestManager: ${e}`,\n );\n });\n };\n\n this.sendOutgoingRoomKeyRequestsTimer = global.setTimeout(\n startSendingOutgoingRoomKeyRequests,\n SEND_KEY_REQUESTS_DELAY_MS,\n );\n }\n\n // look for and send any queued requests. Runs itself recursively until\n // there are no more requests, or there is an error (in which case, the\n // timer will be restarted before the promise resolves).\n private sendOutgoingRoomKeyRequests(): Promise<void> {\n if (!this.clientRunning) {\n this.sendOutgoingRoomKeyRequestsTimer = null;\n return Promise.resolve();\n }\n\n return this.cryptoStore.getOutgoingRoomKeyRequestByState([\n RoomKeyRequestState.CancellationPending,\n RoomKeyRequestState.CancellationPendingAndWillResend,\n RoomKeyRequestState.Unsent,\n ]).then((req: OutgoingRoomKeyRequest) => {\n if (!req) {\n this.sendOutgoingRoomKeyRequestsTimer = null;\n return;\n }\n\n let prom;\n switch (req.state) {\n case RoomKeyRequestState.Unsent:\n prom = this.sendOutgoingRoomKeyRequest(req);\n break;\n case RoomKeyRequestState.CancellationPending:\n prom = this.sendOutgoingRoomKeyRequestCancellation(req);\n break;\n case RoomKeyRequestState.CancellationPendingAndWillResend:\n prom = this.sendOutgoingRoomKeyRequestCancellation(req, true);\n break;\n }\n\n return prom.then(() => {\n // go around the loop again\n return this.sendOutgoingRoomKeyRequests();\n }).catch((e) => {\n logger.error(\"Error sending room key request; will retry later.\", e);\n this.sendOutgoingRoomKeyRequestsTimer = null;\n });\n });\n }\n\n // given a RoomKeyRequest, send it and update the request record\n private sendOutgoingRoomKeyRequest(req: OutgoingRoomKeyRequest): Promise<void> {\n logger.log(\n `Requesting keys for ${stringifyRequestBody(req.requestBody)}` +\n ` from ${stringifyRecipientList(req.recipients)}` +\n `(id ${req.requestId})`,\n );\n\n const requestMessage = {\n action: \"request\",\n requesting_device_id: this.deviceId,\n request_id: req.requestId,\n body: req.requestBody,\n };\n\n return this.sendMessageToDevices(\n requestMessage, req.recipients, req.requestTxnId || req.requestId,\n ).then(() => {\n return this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId, RoomKeyRequestState.Unsent,\n { state: RoomKeyRequestState.Sent },\n );\n });\n }\n\n // Given a RoomKeyRequest, cancel it and delete the request record unless\n // andResend is set, in which case transition to UNSENT.\n private sendOutgoingRoomKeyRequestCancellation(req: OutgoingRoomKeyRequest, andResend = false): Promise<void> {\n logger.log(\n `Sending cancellation for key request for ` +\n `${stringifyRequestBody(req.requestBody)} to ` +\n `${stringifyRecipientList(req.recipients)} ` +\n `(cancellation id ${req.cancellationTxnId})`,\n );\n\n const requestMessage = {\n action: \"request_cancellation\",\n requesting_device_id: this.deviceId,\n request_id: req.requestId,\n };\n\n return this.sendMessageToDevices(\n requestMessage, req.recipients, req.cancellationTxnId,\n ).then(() => {\n if (andResend) {\n // We want to resend, so transition to UNSENT\n return this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId,\n RoomKeyRequestState.CancellationPendingAndWillResend,\n { state: RoomKeyRequestState.Unsent },\n );\n }\n return this.cryptoStore.deleteOutgoingRoomKeyRequest(\n req.requestId, RoomKeyRequestState.CancellationPending,\n );\n });\n }\n\n // send a RoomKeyRequest to a list of recipients\n private sendMessageToDevices(message, recipients, txnId: string): Promise<{}> {\n const contentMap: Record<string, Record<string, Record<string, any>>> = {};\n for (const recip of recipients) {\n if (!contentMap[recip.userId]) {\n contentMap[recip.userId] = {};\n }\n contentMap[recip.userId][recip.deviceId] = message;\n }\n\n return this.baseApis.sendToDevice(EventType.RoomKeyRequest, contentMap, txnId);\n }\n}\n\nfunction stringifyRequestBody(requestBody) {\n // we assume that the request is for megolm keys, which are identified by\n // room id and session id\n return requestBody.room_id + \" / \" + requestBody.session_id;\n}\n\nfunction stringifyRecipientList(recipients) {\n return '['\n + recipients.map((r) => `${r.userId}:${r.deviceId}`).join(\",\")\n + ']';\n}\n\n",
"/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto/RoomList\n *\n * Manages the list of encrypted rooms\n */\n\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { CryptoStore } from \"../client\";\n\n/* eslint-disable camelcase */\ninterface IRoomEncryption {\n algorithm: string;\n rotation_period_ms: number;\n rotation_period_msgs: number;\n}\n/* eslint-enable camelcase */\n\n/**\n * @alias module:crypto/RoomList\n */\nexport class RoomList {\n // Object of roomId -> room e2e info object (body of the m.room.encryption event)\n private roomEncryption: Record<string, IRoomEncryption> = {};\n\n constructor(private readonly cryptoStore: CryptoStore) {}\n\n public async init(): Promise<void> {\n await this.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ROOMS], (txn) => {\n this.cryptoStore.getEndToEndRooms(txn, (result) => {\n this.roomEncryption = result;\n });\n },\n );\n }\n\n public getRoomEncryption(roomId: string): IRoomEncryption {\n return this.roomEncryption[roomId] || null;\n }\n\n public isRoomEncrypted(roomId: string): boolean {\n return Boolean(this.getRoomEncryption(roomId));\n }\n\n public async setRoomEncryption(roomId: string, roomInfo: IRoomEncryption): Promise<void> {\n // important that this happens before calling into the store\n // as it prevents the Crypto::setRoomEncryption from calling\n // this twice for consecutive m.room.encryption events\n this.roomEncryption[roomId] = roomInfo;\n await this.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ROOMS], (txn) => {\n this.cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn);\n },\n );\n }\n}\n",
"/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../logger';\nimport * as olmlib from './olmlib';\nimport { randomString } from '../randomstring';\nimport { encryptAES, decryptAES, IEncryptedPayload, calculateKeyCheck } from './aes';\nimport { encodeBase64 } from \"./olmlib\";\nimport { ICryptoCallbacks, MatrixClient, MatrixEvent } from '../matrix';\nimport { IAddSecretStorageKeyOpts, ISecretStorageKeyInfo } from './api';\nimport { EventEmitter } from 'stream';\n\nexport const SECRET_STORAGE_ALGORITHM_V1_AES = \"m.secret_storage.v1.aes-hmac-sha2\";\n\n// Some of the key functions use a tuple and some use an object...\nexport type SecretStorageKeyTuple = [keyId: string, keyInfo: ISecretStorageKeyInfo];\nexport type SecretStorageKeyObject = {keyId: string, keyInfo: ISecretStorageKeyInfo};\n\nexport interface ISecretRequest {\n requestId: string;\n promise: Promise<string>;\n cancel: (reason: string) => void;\n}\n\nexport interface IAccountDataClient extends EventEmitter {\n // Subset of MatrixClient (which also uses any for the event content)\n getAccountDataFromServer: (eventType: string) => Promise<any>;\n getAccountData: (eventType: string) => MatrixEvent;\n setAccountData: (eventType: string, content: any) => Promise<void>;\n}\n\ninterface ISecretRequestInternal {\n name: string;\n devices: string[];\n resolve: (reason: string) => void;\n reject: (error: Error) => void;\n}\n\ninterface IDecryptors {\n encrypt: (plaintext: string) => Promise<IEncryptedPayload>;\n decrypt: (ciphertext: IEncryptedPayload) => Promise<string>;\n}\n\n/**\n * Implements Secure Secret Storage and Sharing (MSC1946)\n * @module crypto/SecretStorage\n */\nexport class SecretStorage {\n private requests = new Map<string, ISecretRequestInternal>();\n\n // In it's pure javascript days, this was relying on some proper Javascript-style\n // type-abuse where sometimes we'd pass in a fake client object with just the account\n // data methods implemented, which is all this class needs unless you use the secret\n // sharing code, so it was fine. As a low-touch TypeScript migration, this now has\n // an extra, optional param for a real matrix client, so you can not pass it as long\n // as you don't request any secrets.\n // A better solution would probably be to split this class up into secret storage and\n // secret sharing which are really two separate things, even though they share an MSC.\n constructor(\n private readonly accountDataAdapter: IAccountDataClient,\n private readonly cryptoCallbacks: ICryptoCallbacks,\n private readonly baseApis?: MatrixClient,\n ) {}\n\n public async getDefaultKeyId(): Promise<string> {\n const defaultKey = await this.accountDataAdapter.getAccountDataFromServer(\n 'm.secret_storage.default_key',\n );\n if (!defaultKey) return null;\n return defaultKey.key;\n }\n\n public setDefaultKeyId(keyId: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const listener = (ev: MatrixEvent): void => {\n if (\n ev.getType() === 'm.secret_storage.default_key' &&\n ev.getContent().key === keyId\n ) {\n this.accountDataAdapter.removeListener('accountData', listener);\n resolve();\n }\n };\n this.accountDataAdapter.on('accountData', listener);\n\n this.accountDataAdapter.setAccountData(\n 'm.secret_storage.default_key',\n { key: keyId },\n ).catch(e => {\n this.accountDataAdapter.removeListener('accountData', listener);\n reject(e);\n });\n });\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * @param {string} algorithm the algorithm used by the key.\n * @param {object} opts the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param {string} [keyId] the ID of the key. If not given, a random\n * ID will be generated.\n *\n * @return {object} An object with:\n * keyId: {string} the ID of the key\n * keyInfo: {object} details about the key (iv, mac, passphrase)\n */\n public async addKey(\n algorithm: string,\n opts: IAddSecretStorageKeyOpts,\n keyId?: string,\n ): Promise<SecretStorageKeyObject> {\n const keyInfo = { algorithm } as ISecretStorageKeyInfo;\n\n if (!opts) opts = {} as IAddSecretStorageKeyOpts;\n\n if (opts.name) {\n keyInfo.name = opts.name;\n }\n\n if (algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (opts.passphrase) {\n keyInfo.passphrase = opts.passphrase;\n }\n if (opts.key) {\n const { iv, mac } = await calculateKeyCheck(opts.key);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n }\n } else {\n throw new Error(`Unknown key algorithm ${algorithm}`);\n }\n\n if (!keyId) {\n do {\n keyId = randomString(32);\n } while (\n await this.accountDataAdapter.getAccountDataFromServer(\n `m.secret_storage.key.${keyId}`,\n )\n );\n }\n\n await this.accountDataAdapter.setAccountData(\n `m.secret_storage.key.${keyId}`, keyInfo,\n );\n\n return {\n keyId,\n keyInfo,\n };\n }\n\n /**\n * Get the key information for a given ID.\n *\n * @param {string} [keyId = default key's ID] The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns {Array?} If the key was found, the return value is an array of\n * the form [keyId, keyInfo]. Otherwise, null is returned.\n * XXX: why is this an array when addKey returns an object?\n */\n public async getKey(keyId: string): Promise<SecretStorageKeyTuple> {\n if (!keyId) {\n keyId = await this.getDefaultKeyId();\n }\n if (!keyId) {\n return null;\n }\n\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n return keyInfo ? [keyId, keyInfo] : null;\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * @param {string} [keyId = default key's ID] The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @return {boolean} Whether we have the key.\n */\n public async hasKey(keyId?: string): Promise<boolean> {\n return Boolean(await this.getKey(keyId));\n }\n\n /**\n * Check whether a key matches what we expect based on the key info\n *\n * @param {Uint8Array} key the key to check\n * @param {object} info the key info\n *\n * @return {boolean} whether or not the key matches\n */\n public async checkKey(key: Uint8Array, info: ISecretStorageKeyInfo): Promise<boolean> {\n if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (info.mac) {\n const { mac } = await calculateKeyCheck(key, info.iv);\n return info.mac.replace(/=+$/g, '') === mac.replace(/=+$/g, '');\n } else {\n // if we have no information, we have to assume the key is right\n return true;\n }\n } else {\n throw new Error(\"Unknown algorithm\");\n }\n }\n\n /**\n * Store an encrypted secret on the server\n *\n * @param {string} name The name of the secret\n * @param {string} secret The secret contents.\n * @param {Array} keys The IDs of the keys to use to encrypt the secret\n * or null/undefined to use the default key.\n */\n public async store(name: string, secret: string, keys?: string[]): Promise<void> {\n const encrypted = {};\n\n if (!keys) {\n const defaultKeyId = await this.getDefaultKeyId();\n if (!defaultKeyId) {\n throw new Error(\"No keys specified and no default key present\");\n }\n keys = [defaultKeyId];\n }\n\n if (keys.length === 0) {\n throw new Error(\"Zero keys given to encrypt with!\");\n }\n\n for (const keyId of keys) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n if (!keyInfo) {\n throw new Error(\"Unknown key: \" + keyId);\n }\n\n // encrypt secret, based on the algorithm\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const keys = { [keyId]: keyInfo };\n const [, encryption] = await this.getSecretStorageKey(keys, name);\n encrypted[keyId] = await encryption.encrypt(secret);\n } else {\n logger.warn(\"unknown algorithm for secret storage key \" + keyId\n + \": \" + keyInfo.algorithm);\n // do nothing if we don't understand the encryption algorithm\n }\n }\n\n // save encrypted secret\n await this.accountDataAdapter.setAccountData(name, { encrypted });\n }\n\n /**\n * Get a secret from storage.\n *\n * @param {string} name the name of the secret\n *\n * @return {string} the contents of the secret\n */\n public async get(name: string): Promise<string> {\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo) {\n return;\n }\n if (!secretInfo.encrypted) {\n throw new Error(\"Content is not encrypted!\");\n }\n\n // get possible keys to decrypt\n const keys = {};\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n const encInfo = secretInfo.encrypted[keyId];\n // only use keys we understand the encryption algorithm of\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n keys[keyId] = keyInfo;\n }\n }\n }\n\n if (Object.keys(keys).length === 0) {\n throw new Error(`Could not decrypt ${name} because none of ` +\n `the keys it is encrypted with are for a supported algorithm`);\n }\n\n let keyId;\n let decryption;\n try {\n // fetch private key from app\n [keyId, decryption] = await this.getSecretStorageKey(keys, name);\n\n const encInfo = secretInfo.encrypted[keyId];\n\n // We don't actually need the decryption object if it's a passthrough\n // since we just want to return the key itself. It must be base64\n // encoded, since this is how a key would normally be stored.\n if (encInfo.passthrough) return encodeBase64(decryption.get_private_key());\n\n return await decryption.decrypt(encInfo);\n } finally {\n if (decryption && decryption.free) decryption.free();\n }\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * @param {string} name the name of the secret\n * @param {boolean} checkKey check if the secret is encrypted by a trusted key\n *\n * @return {object?} map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStored(name: string, checkKey: boolean): Promise<Record<string, ISecretStorageKeyInfo>> {\n // check if secret exists\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo) return null;\n if (!secretInfo.encrypted) {\n return null;\n }\n\n if (checkKey === undefined) checkKey = true;\n\n const ret = {};\n\n // filter secret encryption keys with supported algorithm\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n if (!keyInfo) continue;\n const encInfo = secretInfo.encrypted[keyId];\n\n // only use keys we understand the encryption algorithm of\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n ret[keyId] = keyInfo;\n }\n }\n }\n return Object.keys(ret).length ? ret : null;\n }\n\n /**\n * Request a secret from another device\n *\n * @param {string} name the name of the secret to request\n * @param {string[]} devices the devices to request the secret from\n */\n public request(name: string, devices: string[]): ISecretRequest {\n const requestId = this.baseApis.makeTxnId();\n\n let resolve: (string) => void;\n let reject: (Error) => void;\n const promise = new Promise<string>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n this.requests.set(requestId, {\n name,\n devices,\n resolve,\n reject,\n });\n\n const cancel = (reason: string) => {\n // send cancellation event\n const cancelData = {\n action: \"request_cancellation\",\n requesting_device_id: this.baseApis.deviceId,\n request_id: requestId,\n };\n const toDevice = {};\n for (const device of devices) {\n toDevice[device] = cancelData;\n }\n this.baseApis.sendToDevice(\"m.secret.request\", {\n [this.baseApis.getUserId()]: toDevice,\n });\n\n // and reject the promise so that anyone waiting on it will be\n // notified\n reject(new Error(reason || \"Cancelled\"));\n };\n\n // send request to devices\n const requestData = {\n name,\n action: \"request\",\n requesting_device_id: this.baseApis.deviceId,\n request_id: requestId,\n };\n const toDevice = {};\n for (const device of devices) {\n toDevice[device] = requestData;\n }\n logger.info(`Request secret ${name} from ${devices}, id ${requestId}`);\n this.baseApis.sendToDevice(\"m.secret.request\", {\n [this.baseApis.getUserId()]: toDevice,\n });\n\n return {\n requestId,\n promise,\n cancel,\n };\n }\n\n public async onRequestReceived(event: MatrixEvent): Promise<void> {\n const sender = event.getSender();\n const content = event.getContent();\n if (sender !== this.baseApis.getUserId()\n || !(content.name && content.action\n && content.requesting_device_id && content.request_id)) {\n // ignore requests from anyone else, for now\n return;\n }\n const deviceId = content.requesting_device_id;\n // check if it's a cancel\n if (content.action === \"request_cancellation\") {\n /*\n Looks like we intended to emit events when we got cancelations, but\n we never put anything in the _incomingRequests object, and the request\n itself doesn't use events anyway so if we were to wire up cancellations,\n they probably ought to use the same callback interface. I'm leaving them\n disabled for now while converting this file to typescript.\n if (this._incomingRequests[deviceId]\n && this._incomingRequests[deviceId][content.request_id]) {\n logger.info(\n \"received request cancellation for secret (\" + sender +\n \", \" + deviceId + \", \" + content.request_id + \")\",\n );\n this.baseApis.emit(\"crypto.secrets.requestCancelled\", {\n user_id: sender,\n device_id: deviceId,\n request_id: content.request_id,\n });\n }\n */\n } else if (content.action === \"request\") {\n if (deviceId === this.baseApis.deviceId) {\n // no point in trying to send ourself the secret\n return;\n }\n\n // check if we have the secret\n logger.info(\n \"received request for secret (\" + sender +\n \", \" + deviceId + \", \" + content.request_id + \")\",\n );\n if (!this.cryptoCallbacks.onSecretRequested) {\n return;\n }\n const secret = await this.cryptoCallbacks.onSecretRequested(\n sender,\n deviceId,\n content.request_id,\n content.name,\n this.baseApis.checkDeviceTrust(sender, deviceId),\n );\n if (secret) {\n logger.info(`Preparing ${content.name} secret for ${deviceId}`);\n const payload = {\n type: \"m.secret.send\",\n content: {\n request_id: content.request_id,\n secret: secret,\n },\n };\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.baseApis.crypto.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n await olmlib.ensureOlmSessionsForDevices(\n this.baseApis.crypto.olmDevice,\n this.baseApis,\n {\n [sender]: [\n this.baseApis.getStoredDevice(sender, deviceId),\n ],\n },\n );\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.baseApis.getUserId(),\n this.baseApis.deviceId,\n this.baseApis.crypto.olmDevice,\n sender,\n this.baseApis.getStoredDevice(sender, deviceId),\n payload,\n );\n const contentMap = {\n [sender]: {\n [deviceId]: encryptedContent,\n },\n };\n\n logger.info(`Sending ${content.name} secret for ${deviceId}`);\n this.baseApis.sendToDevice(\"m.room.encrypted\", contentMap);\n } else {\n logger.info(`Request denied for ${content.name} secret for ${deviceId}`);\n }\n }\n }\n\n public onSecretReceived(event: MatrixEvent): void {\n if (event.getSender() !== this.baseApis.getUserId()) {\n // we shouldn't be receiving secrets from anyone else, so ignore\n // because someone could be trying to send us bogus data\n return;\n }\n const content = event.getContent();\n logger.log(\"got secret share for request\", content.request_id);\n const requestControl = this.requests.get(content.request_id);\n if (requestControl) {\n // make sure that the device that sent it is one of the devices that\n // we requested from\n const deviceInfo = this.baseApis.crypto.deviceList.getDeviceByIdentityKey(\n olmlib.OLM_ALGORITHM,\n event.getSenderKey(),\n );\n if (!deviceInfo) {\n logger.log(\n \"secret share from unknown device with key\", event.getSenderKey(),\n );\n return;\n }\n if (!requestControl.devices.includes(deviceInfo.deviceId)) {\n logger.log(\"unsolicited secret share from device\", deviceInfo.deviceId);\n return;\n }\n\n logger.log(\n `Successfully received secret ${requestControl.name} ` +\n `from ${deviceInfo.deviceId}`,\n );\n requestControl.resolve(content.secret);\n }\n }\n\n private async getSecretStorageKey(\n keys: Record<string, ISecretStorageKeyInfo>,\n name: string,\n ): Promise<[string, IDecryptors]> {\n if (!this.cryptoCallbacks.getSecretStorageKey) {\n throw new Error(\"No getSecretStorageKey callback supplied\");\n }\n\n const returned = await this.cryptoCallbacks.getSecretStorageKey({ keys }, name);\n\n if (!returned) {\n throw new Error(\"getSecretStorageKey callback returned falsey\");\n }\n if (returned.length < 2) {\n throw new Error(\"getSecretStorageKey callback returned invalid data\");\n }\n\n const [keyId, privateKey] = returned;\n if (!keys[keyId]) {\n throw new Error(\"App returned unknown key from getSecretStorageKey!\");\n }\n\n if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const decryption = {\n encrypt: async function(secret: string): Promise<IEncryptedPayload> {\n return await encryptAES(secret, privateKey, name);\n },\n decrypt: async function(encInfo: IEncryptedPayload): Promise<string> {\n return await decryptAES(encInfo, privateKey, name);\n },\n };\n return [keyId, decryption];\n } else {\n throw new Error(\"Unknown key type: \" + keys[keyId].algorithm);\n }\n }\n}\n",
"/*\nCopyright 2020 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { BinaryLike } from \"crypto\";\n\nimport { getCrypto } from '../utils';\nimport { decodeBase64, encodeBase64 } from './olmlib';\n\nconst subtleCrypto = (typeof window !== \"undefined\" && window.crypto) ?\n (window.crypto.subtle || window.crypto.webkitSubtle) : null;\n\n// salt for HKDF, with 8 bytes of zeros\nconst zeroSalt = new Uint8Array(8);\n\nexport interface IEncryptedPayload {\n iv: string;\n ciphertext: string;\n mac: string;\n}\n\n/**\n * encrypt a string in Node.js\n *\n * @param {string} data the plaintext to encrypt\n * @param {Uint8Array} key the encryption key to use\n * @param {string} name the name of the secret\n * @param {string} ivStr the initialization vector to use\n */\nasync function encryptNode(data: string, key: Uint8Array, name: string, ivStr?: string): Promise<IEncryptedPayload> {\n const crypto = getCrypto();\n if (!crypto) {\n throw new Error(\"No usable crypto implementation\");\n }\n\n let iv;\n if (ivStr) {\n iv = decodeBase64(ivStr);\n } else {\n iv = crypto.randomBytes(16);\n }\n\n // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary\n // (which would mean we wouldn't be able to decrypt on Android). The loss\n // of a single bit of iv is a price we have to pay.\n iv[8] &= 0x7f;\n\n const [aesKey, hmacKey] = deriveKeysNode(key, name);\n\n const cipher = crypto.createCipheriv(\"aes-256-ctr\", aesKey, iv);\n const ciphertext = Buffer.concat([\n cipher.update(data, \"utf8\"),\n cipher.final(),\n ]);\n\n const hmac = crypto.createHmac(\"sha256\", hmacKey)\n .update(ciphertext).digest(\"base64\");\n\n return {\n iv: encodeBase64(iv),\n ciphertext: ciphertext.toString(\"base64\"),\n mac: hmac,\n };\n}\n\n/**\n * decrypt a string in Node.js\n *\n * @param {object} data the encrypted data\n * @param {string} data.ciphertext the ciphertext in base64\n * @param {string} data.iv the initialization vector in base64\n * @param {string} data.mac the HMAC in base64\n * @param {Uint8Array} key the encryption key to use\n * @param {string} name the name of the secret\n */\nasync function decryptNode(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {\n const crypto = getCrypto();\n if (!crypto) {\n throw new Error(\"No usable crypto implementation\");\n }\n\n const [aesKey, hmacKey] = deriveKeysNode(key, name);\n\n const hmac = crypto.createHmac(\"sha256\", hmacKey)\n .update(Buffer.from(data.ciphertext, \"base64\"))\n .digest(\"base64\").replace(/=+$/g, '');\n\n if (hmac !== data.mac.replace(/=+$/g, '')) {\n throw new Error(`Error decrypting secret ${name}: bad MAC`);\n }\n\n const decipher = crypto.createDecipheriv(\n \"aes-256-ctr\", aesKey, decodeBase64(data.iv),\n );\n return decipher.update(data.ciphertext, \"base64\", \"utf8\")\n + decipher.final(\"utf8\");\n}\n\nfunction deriveKeysNode(key: BinaryLike, name: string): [Buffer, Buffer] {\n const crypto = getCrypto();\n const prk = crypto.createHmac(\"sha256\", zeroSalt).update(key).digest();\n\n const b = Buffer.alloc(1, 1);\n const aesKey = crypto.createHmac(\"sha256\", prk)\n .update(name, \"utf8\").update(b).digest();\n b[0] = 2;\n const hmacKey = crypto.createHmac(\"sha256\", prk)\n .update(aesKey).update(name, \"utf8\").update(b).digest();\n\n return [aesKey, hmacKey];\n}\n\n/**\n * encrypt a string in Node.js\n *\n * @param {string} data the plaintext to encrypt\n * @param {Uint8Array} key the encryption key to use\n * @param {string} name the name of the secret\n * @param {string} ivStr the initialization vector to use\n */\nasync function encryptBrowser(data: string, key: Uint8Array, name: string, ivStr?: string): Promise<IEncryptedPayload> {\n let iv;\n if (ivStr) {\n iv = decodeBase64(ivStr);\n } else {\n iv = new Uint8Array(16);\n window.crypto.getRandomValues(iv);\n }\n\n // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary\n // (which would mean we wouldn't be able to decrypt on Android). The loss\n // of a single bit of iv is a price we have to pay.\n iv[8] &= 0x7f;\n\n const [aesKey, hmacKey] = await deriveKeysBrowser(key, name);\n const encodedData = new TextEncoder().encode(data);\n\n const ciphertext = await subtleCrypto.encrypt(\n {\n name: \"AES-CTR\",\n counter: iv,\n length: 64,\n },\n aesKey,\n encodedData,\n );\n\n const hmac = await subtleCrypto.sign(\n { name: 'HMAC' },\n hmacKey,\n ciphertext,\n );\n\n return {\n iv: encodeBase64(iv),\n ciphertext: encodeBase64(ciphertext),\n mac: encodeBase64(hmac),\n };\n}\n\n/**\n * decrypt a string in the browser\n *\n * @param {object} data the encrypted data\n * @param {string} data.ciphertext the ciphertext in base64\n * @param {string} data.iv the initialization vector in base64\n * @param {string} data.mac the HMAC in base64\n * @param {Uint8Array} key the encryption key to use\n * @param {string} name the name of the secret\n */\nasync function decryptBrowser(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {\n const [aesKey, hmacKey] = await deriveKeysBrowser(key, name);\n\n const ciphertext = decodeBase64(data.ciphertext);\n\n if (!await subtleCrypto.verify(\n { name: \"HMAC\" },\n hmacKey,\n decodeBase64(data.mac),\n ciphertext,\n )) {\n throw new Error(`Error decrypting secret ${name}: bad MAC`);\n }\n\n const plaintext = await subtleCrypto.decrypt(\n {\n name: \"AES-CTR\",\n counter: decodeBase64(data.iv),\n length: 64,\n },\n aesKey,\n ciphertext,\n );\n\n return new TextDecoder().decode(new Uint8Array(plaintext));\n}\n\nasync function deriveKeysBrowser(key: Uint8Array, name: string): Promise<[CryptoKey, CryptoKey]> {\n const hkdfkey = await subtleCrypto.importKey(\n 'raw',\n key,\n { name: \"HKDF\" },\n false,\n [\"deriveBits\"],\n );\n const keybits = await subtleCrypto.deriveBits(\n {\n name: \"HKDF\",\n salt: zeroSalt,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879\n info: (new TextEncoder().encode(name)),\n hash: \"SHA-256\",\n },\n hkdfkey,\n 512,\n );\n\n const aesKey = keybits.slice(0, 32);\n const hmacKey = keybits.slice(32);\n\n const aesProm = subtleCrypto.importKey(\n 'raw',\n aesKey,\n { name: 'AES-CTR' },\n false,\n ['encrypt', 'decrypt'],\n );\n\n const hmacProm = subtleCrypto.importKey(\n 'raw',\n hmacKey,\n {\n name: 'HMAC',\n hash: { name: 'SHA-256' },\n },\n false,\n ['sign', 'verify'],\n );\n\n return await Promise.all([aesProm, hmacProm]);\n}\n\nexport function encryptAES(data: string, key: Uint8Array, name: string, ivStr?: string): Promise<IEncryptedPayload> {\n return subtleCrypto ? encryptBrowser(data, key, name, ivStr) : encryptNode(data, key, name, ivStr);\n}\n\nexport function decryptAES(data: IEncryptedPayload, key: Uint8Array, name: string): Promise<string> {\n return subtleCrypto ? decryptBrowser(data, key, name) : decryptNode(data, key, name);\n}\n\n// string of zeroes, for calculating the key check\nconst 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\";\n\n/** Calculate the MAC for checking the key.\n *\n * @param {Uint8Array} key the key to use\n * @param {string} [iv] The initialization vector as a base64-encoded string.\n * If omitted, a random initialization vector will be created.\n * @return {Promise<object>} An object that contains, `mac` and `iv` properties.\n */\nexport function calculateKeyCheck(key: Uint8Array, iv?: string): Promise<IEncryptedPayload> {\n return encryptAES(ZERO_STR, key, \"\", iv);\n}\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Internal module. Defines the base classes of the encryption implementations\n *\n * @module\n */\n\nimport { MatrixClient } from \"../../client\";\nimport { Room } from \"../../models/room\";\nimport { OlmDevice } from \"../OlmDevice\";\nimport { MatrixEvent, RoomMember } from \"../..\";\nimport { Crypto, IEventDecryptionResult, IMegolmSessionData, IncomingRoomKeyRequest } from \"..\";\nimport { DeviceInfo } from \"../deviceinfo\";\n\n/**\n * map of registered encryption algorithm classes. A map from string to {@link\n * module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm} class\n *\n * @type {Object.<string, function(new: module:crypto/algorithms/base.EncryptionAlgorithm)>}\n */\nexport const ENCRYPTION_CLASSES: Record<string, new (params: IParams) => EncryptionAlgorithm> = {};\n\ntype DecryptionClassParams = Omit<IParams, \"deviceId\" | \"config\">;\n\n/**\n * map of registered encryption algorithm classes. Map from string to {@link\n * module:crypto/algorithms/base.DecryptionAlgorithm|DecryptionAlgorithm} class\n *\n * @type {Object.<string, function(new: module:crypto/algorithms/base.DecryptionAlgorithm)>}\n */\nexport const DECRYPTION_CLASSES: Record<string, new (params: DecryptionClassParams) => DecryptionAlgorithm> = {};\n\ninterface IParams {\n userId: string;\n deviceId: string;\n crypto: Crypto;\n olmDevice: OlmDevice;\n baseApis: MatrixClient;\n roomId: string;\n config: object;\n}\n\n/**\n * base type for encryption implementations\n *\n * @alias module:crypto/algorithms/base.EncryptionAlgorithm\n *\n * @param {object} params parameters\n * @param {string} params.userId The UserID for the local user\n * @param {string} params.deviceId The identifier for this device.\n * @param {module:crypto} params.crypto crypto core\n * @param {module:crypto/OlmDevice} params.olmDevice olm.js wrapper\n * @param {MatrixClient} baseApis base matrix api interface\n * @param {string} params.roomId The ID of the room we will be sending to\n * @param {object} params.config The body of the m.room.encryption event\n */\nexport abstract class EncryptionAlgorithm {\n protected readonly userId: string;\n protected readonly deviceId: string;\n protected readonly crypto: Crypto;\n protected readonly olmDevice: OlmDevice;\n protected readonly baseApis: MatrixClient;\n protected readonly roomId: string;\n\n constructor(params: IParams) {\n this.userId = params.userId;\n this.deviceId = params.deviceId;\n this.crypto = params.crypto;\n this.olmDevice = params.olmDevice;\n this.baseApis = params.baseApis;\n this.roomId = params.roomId;\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param {module:models/room} room the room the event is in\n */\n public prepareToEncrypt(room: Room): void {}\n\n /**\n * Encrypt a message event\n *\n * @method module:crypto/algorithms/base.EncryptionAlgorithm.encryptMessage\n * @public\n * @abstract\n *\n * @param {module:models/room} room\n * @param {string} eventType\n * @param {object} content event content\n *\n * @return {Promise} Promise which resolves to the new event body\n */\n public abstract encryptMessage(room: Room, eventType: string, content: object): Promise<object>;\n\n /**\n * Called when the membership of a member of the room changes.\n *\n * @param {module:models/event.MatrixEvent} event event causing the change\n * @param {module:models/room-member} member user whose membership changed\n * @param {string=} oldMembership previous membership\n * @public\n * @abstract\n */\n public onRoomMembership(event: MatrixEvent, member: RoomMember, oldMembership?: string): void {}\n\n public reshareKeyWithDevice?(\n senderKey: string,\n sessionId: string,\n userId: string,\n device: DeviceInfo,\n ): Promise<void>;\n\n public forceDiscardSession?(): void;\n}\n\n/**\n * base type for decryption implementations\n *\n * @alias module:crypto/algorithms/base.DecryptionAlgorithm\n * @param {object} params parameters\n * @param {string} params.userId The UserID for the local user\n * @param {module:crypto} params.crypto crypto core\n * @param {module:crypto/OlmDevice} params.olmDevice olm.js wrapper\n * @param {MatrixClient} baseApis base matrix api interface\n * @param {string=} params.roomId The ID of the room we will be receiving\n * from. Null for to-device events.\n */\nexport abstract class DecryptionAlgorithm {\n protected readonly userId: string;\n protected readonly crypto: Crypto;\n protected readonly olmDevice: OlmDevice;\n protected readonly baseApis: MatrixClient;\n protected readonly roomId: string;\n\n constructor(params: DecryptionClassParams) {\n this.userId = params.userId;\n this.crypto = params.crypto;\n this.olmDevice = params.olmDevice;\n this.baseApis = params.baseApis;\n this.roomId = params.roomId;\n }\n\n /**\n * Decrypt an event\n *\n * @method module:crypto/algorithms/base.DecryptionAlgorithm#decryptEvent\n * @abstract\n *\n * @param {MatrixEvent} event undecrypted event\n *\n * @return {Promise<module:crypto~EventDecryptionResult>} promise which\n * resolves once we have finished decrypting. Rejects with an\n * `algorithms.DecryptionError` if there is a problem decrypting the event.\n */\n public abstract decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult>;\n\n /**\n * Handle a key event\n *\n * @method module:crypto/algorithms/base.DecryptionAlgorithm#onRoomKeyEvent\n *\n * @param {module:models/event.MatrixEvent} params event key event\n */\n public onRoomKeyEvent(params: MatrixEvent): void {\n // ignore by default\n }\n\n /**\n * Import a room key\n *\n * @param {module:crypto/OlmDevice.MegolmSessionData} session\n * @param {object} opts object\n */\n public async importRoomKey(session: IMegolmSessionData, opts: object): Promise<void> {\n // ignore by default\n }\n\n /**\n * Determine if we have the keys necessary to respond to a room key request\n *\n * @param {module:crypto~IncomingRoomKeyRequest} keyRequest\n * @return {Promise<boolean>} true if we have the keys and could (theoretically) share\n * them; else false.\n */\n public hasKeysForKeyRequest(keyRequest: IncomingRoomKeyRequest): Promise<boolean> {\n return Promise.resolve(false);\n }\n\n /**\n * Send the response to a room key request\n *\n * @param {module:crypto~IncomingRoomKeyRequest} keyRequest\n */\n public shareKeysWithDevice(keyRequest: IncomingRoomKeyRequest): void {\n throw new Error(\"shareKeysWithDevice not supported for this DecryptionAlgorithm\");\n }\n\n /**\n * Retry decrypting all the events from a sender that haven't been\n * decrypted yet.\n *\n * @param {string} senderKey the sender's key\n */\n public async retryDecryptionFromSender(senderKey: string): Promise<boolean> {\n // ignore by default\n return false;\n }\n\n public onRoomKeyWithheldEvent?(event: MatrixEvent): Promise<void>;\n public sendSharedHistoryInboundSessions?(devicesByUser: Record<string, DeviceInfo[]>): Promise<void>;\n}\n\n/**\n * Exception thrown when decryption fails\n *\n * @alias module:crypto/algorithms/base.DecryptionError\n * @param {string} msg user-visible message describing the problem\n *\n * @param {Object=} details key/value pairs reported in the logs but not shown\n * to the user.\n *\n * @extends Error\n */\nexport class DecryptionError extends Error {\n public readonly detailedString: string;\n\n constructor(public readonly code: string, msg: string, details?: Record<string, string>) {\n super(msg);\n this.code = code;\n this.name = 'DecryptionError';\n this.detailedString = detailedStringForDecryptionError(this, details);\n }\n}\n\nfunction detailedStringForDecryptionError(err: DecryptionError, details?: Record<string, string>): string {\n let result = err.name + '[msg: ' + err.message;\n\n if (details) {\n result += ', ' + Object.keys(details).map((k) => k + ': ' + details[k]).join(', ');\n }\n\n result += ']';\n\n return result;\n}\n\n/**\n * Exception thrown specifically when we want to warn the user to consider\n * the security of their conversation before continuing\n *\n * @param {string} msg message describing the problem\n * @param {Object} devices userId -> {deviceId -> object}\n * set of unknown devices per user we're warning about\n * @extends Error\n */\nexport class UnknownDeviceError extends Error {\n constructor(msg: string, public readonly devices: Record<string, Record<string, object>>) {\n super(msg);\n this.name = \"UnknownDeviceError\";\n this.devices = devices;\n }\n}\n\n/**\n * Registers an encryption/decryption class for a particular algorithm\n *\n * @param {string} algorithm algorithm tag to register for\n *\n * @param {class} encryptor {@link\n * module:crypto/algorithms/base.EncryptionAlgorithm|EncryptionAlgorithm}\n * implementation\n *\n * @param {class} decryptor {@link\n * module:crypto/algorithms/base.DecryptionAlgorithm|DecryptionAlgorithm}\n * implementation\n */\nexport function registerAlgorithm(\n algorithm: string,\n encryptor: new (params: IParams) => EncryptionAlgorithm,\n decryptor: new (params: Omit<IParams, \"deviceId\">) => DecryptionAlgorithm,\n): void {\n ENCRYPTION_CLASSES[algorithm] = encryptor;\n DECRYPTION_CLASSES[algorithm] = decryptor;\n}\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto/algorithms\n */\n\nimport \"./olm\";\nimport \"./megolm\";\n\nexport * from \"./base\";\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Defines m.olm encryption/decryption\n *\n * @module crypto/algorithms/megolm\n */\n\nimport { logger } from '../../logger';\nimport * as olmlib from \"../olmlib\";\nimport {\n DecryptionAlgorithm,\n DecryptionError,\n EncryptionAlgorithm,\n registerAlgorithm,\n UnknownDeviceError,\n} from \"./base\";\nimport { WITHHELD_MESSAGES } from '../OlmDevice';\nimport { Room } from '../../models/room';\nimport { DeviceInfo } from \"../deviceinfo\";\nimport { IOlmSessionResult } from \"../olmlib\";\nimport { DeviceInfoMap } from \"../DeviceList\";\nimport { MatrixEvent } from \"../..\";\nimport { IEventDecryptionResult, IMegolmSessionData, IncomingRoomKeyRequest } from \"../index\";\n\n// determine whether the key can be shared with invitees\nexport function isRoomSharedHistory(room: Room): boolean {\n const visibilityEvent = room?.currentState?.getStateEvents(\"m.room.history_visibility\", \"\");\n // NOTE: if the room visibility is unset, it would normally default to\n // \"world_readable\".\n // (https://spec.matrix.org/unstable/client-server-api/#server-behaviour-5)\n // But we will be paranoid here, and treat it as a situation where the room\n // is not shared-history\n const visibility = visibilityEvent?.getContent()?.history_visibility;\n return [\"world_readable\", \"shared\"].includes(visibility);\n}\n\ninterface IBlockedDevice {\n code: string;\n reason: string;\n deviceInfo: DeviceInfo;\n}\n\ninterface IBlockedMap {\n [userId: string]: {\n [deviceId: string]: IBlockedDevice;\n };\n}\n\ninterface IOlmDevice<T = DeviceInfo> {\n userId: string;\n deviceInfo: T;\n}\n\n/* eslint-disable camelcase */\ninterface IOutboundGroupSessionKey {\n chain_index: number;\n key: string;\n}\n\ninterface IMessage {\n type: string;\n content: {\n algorithm: string;\n room_id: string;\n sender_key?: string;\n sender_claimed_ed25519_key?: string;\n session_id: string;\n session_key: string;\n chain_index: number;\n forwarding_curve25519_key_chain?: string[];\n \"org.matrix.msc3061.shared_history\": boolean;\n };\n}\n\ninterface IKeyForwardingMessage extends IMessage {\n type: \"m.forwarded_room_key\";\n}\n\ninterface IPayload extends Partial<IMessage> {\n code?: string;\n reason?: string;\n room_id?: string;\n session_id?: string;\n algorithm?: string;\n sender_key?: string;\n}\n/* eslint-enable camelcase */\n\n/**\n * @private\n * @constructor\n *\n * @param {string} sessionId\n * @param {boolean} sharedHistory whether the session can be freely shared with\n * other group members, according to the room history visibility settings\n *\n * @property {string} sessionId\n * @property {Number} useCount number of times this session has been used\n * @property {Number} creationTime when the session was created (ms since the epoch)\n *\n * @property {object} sharedWithDevices\n * devices with which we have shared the session key\n * userId -> {deviceId -> msgindex}\n */\nclass OutboundSessionInfo {\n public useCount = 0;\n public creationTime: number;\n public sharedWithDevices: Record<string, Record<string, number>> = {};\n public blockedDevicesNotified: Record<string, Record<string, boolean>> = {};\n\n constructor(public readonly sessionId: string, public readonly sharedHistory = false) {\n this.creationTime = new Date().getTime();\n }\n\n /**\n * Check if it's time to rotate the session\n *\n * @param {Number} rotationPeriodMsgs\n * @param {Number} rotationPeriodMs\n * @return {Boolean}\n */\n public needsRotation(rotationPeriodMsgs: number, rotationPeriodMs: number): boolean {\n const sessionLifetime = new Date().getTime() - this.creationTime;\n\n if (this.useCount >= rotationPeriodMsgs ||\n sessionLifetime >= rotationPeriodMs\n ) {\n logger.log(\n \"Rotating megolm session after \" + this.useCount +\n \" messages, \" + sessionLifetime + \"ms\",\n );\n return true;\n }\n\n return false;\n }\n\n public markSharedWithDevice(userId: string, deviceId: string, chainIndex: number): void {\n if (!this.sharedWithDevices[userId]) {\n this.sharedWithDevices[userId] = {};\n }\n this.sharedWithDevices[userId][deviceId] = chainIndex;\n }\n\n public markNotifiedBlockedDevice(userId: string, deviceId: string): void {\n if (!this.blockedDevicesNotified[userId]) {\n this.blockedDevicesNotified[userId] = {};\n }\n this.blockedDevicesNotified[userId][deviceId] = true;\n }\n\n /**\n * Determine if this session has been shared with devices which it shouldn't\n * have been.\n *\n * @param {Object} devicesInRoom userId -> {deviceId -> object}\n * devices we should shared the session with.\n *\n * @return {Boolean} true if we have shared the session with devices which aren't\n * in devicesInRoom.\n */\n public sharedWithTooManyDevices(devicesInRoom: Record<string, Record<string, object>>): boolean {\n for (const userId in this.sharedWithDevices) {\n if (!this.sharedWithDevices.hasOwnProperty(userId)) {\n continue;\n }\n\n if (!devicesInRoom.hasOwnProperty(userId)) {\n logger.log(\"Starting new megolm session because we shared with \" + userId);\n return true;\n }\n\n for (const deviceId in this.sharedWithDevices[userId]) {\n if (!this.sharedWithDevices[userId].hasOwnProperty(deviceId)) {\n continue;\n }\n\n if (!devicesInRoom[userId].hasOwnProperty(deviceId)) {\n logger.log(\n \"Starting new megolm session because we shared with \" +\n userId + \":\" + deviceId,\n );\n return true;\n }\n }\n }\n }\n}\n\n/**\n * Megolm encryption implementation\n *\n * @constructor\n * @extends {module:crypto/algorithms/EncryptionAlgorithm}\n *\n * @param {object} params parameters, as per\n * {@link module:crypto/algorithms/EncryptionAlgorithm}\n */\nclass MegolmEncryption extends EncryptionAlgorithm {\n // the most recent attempt to set up a session. This is used to serialise\n // the session setups, so that we have a race-free view of which session we\n // are using, and which devices we have shared the keys with. It resolves\n // with an OutboundSessionInfo (or undefined, for the first message in the\n // room).\n private setupPromise = Promise.resolve<OutboundSessionInfo>(undefined);\n\n // Map of outbound sessions by sessions ID. Used if we need a particular\n // session (the session we're currently using to send is always obtained\n // using setupPromise).\n private outboundSessions: Record<string, OutboundSessionInfo> = {};\n\n private readonly sessionRotationPeriodMsgs: number;\n private readonly sessionRotationPeriodMs: number;\n private encryptionPreparation: Promise<void>;\n private encryptionPreparationMetadata: {\n startTime: number;\n };\n\n constructor(params) {\n super(params);\n\n this.sessionRotationPeriodMsgs = params.config?.rotation_period_msgs ?? 100;\n this.sessionRotationPeriodMs = params.config?.rotation_period_ms ?? 7 * 24 * 3600 * 1000;\n }\n\n /**\n * @private\n *\n * @param {module:models/room} room\n * @param {Object} devicesInRoom The devices in this room, indexed by user ID\n * @param {Object} blocked The devices that are blocked, indexed by user ID\n * @param {boolean} [singleOlmCreationPhase] Only perform one round of olm\n * session creation\n *\n * @return {Promise} Promise which resolves to the\n * OutboundSessionInfo when setup is complete.\n */\n private async ensureOutboundSession(\n room: Room,\n devicesInRoom: DeviceInfoMap,\n blocked: IBlockedMap,\n singleOlmCreationPhase = false,\n ): Promise<OutboundSessionInfo> {\n let session;\n\n // takes the previous OutboundSessionInfo, and considers whether to create\n // a new one. Also shares the key with any (new) devices in the room.\n // Updates `session` to hold the final OutboundSessionInfo.\n //\n // returns a promise which resolves once the keyshare is successful.\n const prepareSession = async (oldSession: OutboundSessionInfo) => {\n session = oldSession;\n\n const sharedHistory = isRoomSharedHistory(room);\n\n // history visibility changed\n if (session && sharedHistory !== session.sharedHistory) {\n session = null;\n }\n\n // need to make a brand new session?\n if (session && session.needsRotation(this.sessionRotationPeriodMsgs,\n this.sessionRotationPeriodMs)\n ) {\n logger.log(\"Starting new megolm session because we need to rotate.\");\n session = null;\n }\n\n // determine if we have shared with anyone we shouldn't have\n if (session && session.sharedWithTooManyDevices(devicesInRoom)) {\n session = null;\n }\n\n if (!session) {\n logger.log(`Starting new megolm session for room ${this.roomId}`);\n session = await this.prepareNewSession(sharedHistory);\n logger.log(`Started new megolm session ${session.sessionId} ` +\n `for room ${this.roomId}`);\n this.outboundSessions[session.sessionId] = session;\n }\n\n // now check if we need to share with any devices\n const shareMap = {};\n\n for (const [userId, userDevices] of Object.entries(devicesInRoom)) {\n for (const [deviceId, deviceInfo] of Object.entries(userDevices)) {\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother sending to ourself\n continue;\n }\n\n if (\n !session.sharedWithDevices[userId] ||\n session.sharedWithDevices[userId][deviceId] === undefined\n ) {\n shareMap[userId] = shareMap[userId] || [];\n shareMap[userId].push(deviceInfo);\n }\n }\n }\n\n const key = this.olmDevice.getOutboundGroupSessionKey(session.sessionId);\n const payload: IPayload = {\n type: \"m.room_key\",\n content: {\n \"algorithm\": olmlib.MEGOLM_ALGORITHM,\n \"room_id\": this.roomId,\n \"session_id\": session.sessionId,\n \"session_key\": key.key,\n \"chain_index\": key.chain_index,\n \"org.matrix.msc3061.shared_history\": sharedHistory,\n },\n };\n const [devicesWithoutSession, olmSessions] = await olmlib.getExistingOlmSessions(\n this.olmDevice, this.baseApis, shareMap,\n );\n\n await Promise.all([\n (async () => {\n // share keys with devices that we already have a session for\n logger.debug(`Sharing keys with existing Olm sessions in ${this.roomId}`);\n await this.shareKeyWithOlmSessions(session, key, payload, olmSessions);\n logger.debug(`Shared keys with existing Olm sessions in ${this.roomId}`);\n })(),\n (async () => {\n logger.debug(`Sharing keys (start phase 1) with new Olm sessions in ${this.roomId}`);\n const errorDevices = [];\n\n // meanwhile, establish olm sessions for devices that we don't\n // already have a session for, and share keys with them. If\n // we're doing two phases of olm session creation, use a\n // shorter timeout when fetching one-time keys for the first\n // phase.\n const start = Date.now();\n const failedServers = [];\n await this.shareKeyWithDevices(\n session, key, payload, devicesWithoutSession, errorDevices,\n singleOlmCreationPhase ? 10000 : 2000, failedServers,\n );\n logger.debug(`Shared keys (end phase 1) with new Olm sessions in ${this.roomId}`);\n\n if (!singleOlmCreationPhase && (Date.now() - start < 10000)) {\n // perform the second phase of olm session creation if requested,\n // and if the first phase didn't take too long\n (async () => {\n // Retry sending keys to devices that we were unable to establish\n // an olm session for. This time, we use a longer timeout, but we\n // do this in the background and don't block anything else while we\n // do this. We only need to retry users from servers that didn't\n // respond the first time.\n const retryDevices = {};\n const failedServerMap = new Set;\n for (const server of failedServers) {\n failedServerMap.add(server);\n }\n const failedDevices = [];\n for (const { userId, deviceInfo } of errorDevices) {\n const userHS = userId.slice(userId.indexOf(\":\") + 1);\n if (failedServerMap.has(userHS)) {\n retryDevices[userId] = retryDevices[userId] || [];\n retryDevices[userId].push(deviceInfo);\n } else {\n // if we aren't going to retry, then handle it\n // as a failed device\n failedDevices.push({ userId, deviceInfo });\n }\n }\n\n logger.debug(`Sharing keys (start phase 2) with new Olm sessions in ${this.roomId}`);\n await this.shareKeyWithDevices(\n session, key, payload, retryDevices, failedDevices, 30000,\n );\n logger.debug(`Shared keys (end phase 2) with new Olm sessions in ${this.roomId}`);\n\n await this.notifyFailedOlmDevices(session, key, failedDevices);\n })();\n } else {\n await this.notifyFailedOlmDevices(session, key, errorDevices);\n }\n logger.debug(`Shared keys (all phases done) with new Olm sessions in ${this.roomId}`);\n })(),\n (async () => {\n logger.debug(`Notifying blocked devices in ${this.roomId}`);\n // also, notify blocked devices that they're blocked\n const blockedMap: Record<string, Record<string, { device: IBlockedDevice }>> = {};\n let blockedCount = 0;\n for (const [userId, userBlockedDevices] of Object.entries(blocked)) {\n for (const [deviceId, device] of Object.entries(userBlockedDevices)) {\n if (\n !session.blockedDevicesNotified[userId] ||\n session.blockedDevicesNotified[userId][deviceId] === undefined\n ) {\n blockedMap[userId] = blockedMap[userId] || {};\n blockedMap[userId][deviceId] = { device };\n blockedCount++;\n }\n }\n }\n\n await this.notifyBlockedDevices(session, blockedMap);\n logger.debug(`Notified ${blockedCount} blocked devices in ${this.roomId}`);\n })(),\n ]);\n };\n\n // helper which returns the session prepared by prepareSession\n function returnSession() {\n return session;\n }\n\n // first wait for the previous share to complete\n const prom = this.setupPromise.then(prepareSession);\n\n // Ensure any failures are logged for debugging\n prom.catch(e => {\n logger.error(`Failed to ensure outbound session in ${this.roomId}`, e);\n });\n\n // setupPromise resolves to `session` whether or not the share succeeds\n this.setupPromise = prom.then(returnSession, returnSession);\n\n // but we return a promise which only resolves if the share was successful.\n return prom.then(returnSession);\n }\n\n /**\n * @private\n *\n * @param {boolean} sharedHistory\n *\n * @return {module:crypto/algorithms/megolm.OutboundSessionInfo} session\n */\n private async prepareNewSession(sharedHistory: boolean): Promise<OutboundSessionInfo> {\n const sessionId = this.olmDevice.createOutboundGroupSession();\n const key = this.olmDevice.getOutboundGroupSessionKey(sessionId);\n\n await this.olmDevice.addInboundGroupSession(\n this.roomId, this.olmDevice.deviceCurve25519Key, [], sessionId,\n key.key, { ed25519: this.olmDevice.deviceEd25519Key }, false,\n { sharedHistory },\n );\n\n // don't wait for it to complete\n this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key, sessionId);\n\n return new OutboundSessionInfo(sessionId, sharedHistory);\n }\n\n /**\n * Determines what devices in devicesByUser don't have an olm session as given\n * in devicemap.\n *\n * @private\n *\n * @param {object} devicemap the devices that have olm sessions, as returned by\n * olmlib.ensureOlmSessionsForDevices.\n * @param {object} devicesByUser a map of user IDs to array of deviceInfo\n * @param {array} [noOlmDevices] an array to fill with devices that don't have\n * olm sessions\n *\n * @return {array} an array of devices that don't have olm sessions. If\n * noOlmDevices is specified, then noOlmDevices will be returned.\n */\n private getDevicesWithoutSessions(\n devicemap: Record<string, Record<string, IOlmSessionResult>>,\n devicesByUser: Record<string, DeviceInfo[]>,\n noOlmDevices: IOlmDevice[] = [],\n ): IOlmDevice[] {\n for (const [userId, devicesToShareWith] of Object.entries(devicesByUser)) {\n const sessionResults = devicemap[userId];\n\n for (const deviceInfo of devicesToShareWith) {\n const deviceId = deviceInfo.deviceId;\n\n const sessionResult = sessionResults[deviceId];\n if (!sessionResult.sessionId) {\n // no session with this device, probably because there\n // were no one-time keys.\n\n noOlmDevices.push({ userId, deviceInfo });\n delete sessionResults[deviceId];\n\n // ensureOlmSessionsForUsers has already done the logging,\n // so just skip it.\n continue;\n }\n }\n }\n\n return noOlmDevices;\n }\n\n /**\n * Splits the user device map into multiple chunks to reduce the number of\n * devices we encrypt to per API call.\n *\n * @private\n *\n * @param {object} devicesByUser map from userid to list of devices\n *\n * @return {array<array<object>>} the blocked devices, split into chunks\n */\n private splitDevices<T extends DeviceInfo | IBlockedDevice>(\n devicesByUser: Record<string, Record<string, { device: T }>>,\n ): IOlmDevice<T>[][] {\n const maxDevicesPerRequest = 20;\n\n // use an array where the slices of a content map gets stored\n let currentSlice: IOlmDevice<T>[] = [];\n const mapSlices = [currentSlice];\n\n for (const [userId, userDevices] of Object.entries(devicesByUser)) {\n for (const deviceInfo of Object.values(userDevices)) {\n currentSlice.push({\n userId: userId,\n deviceInfo: deviceInfo.device,\n });\n }\n\n // We do this in the per-user loop as we prefer that all messages to the\n // same user end up in the same API call to make it easier for the\n // server (e.g. only have to send one EDU if a remote user, etc). This\n // does mean that if a user has many devices we may go over the desired\n // limit, but its not a hard limit so that is fine.\n if (currentSlice.length > maxDevicesPerRequest) {\n // the current slice is filled up. Start inserting into the next slice\n currentSlice = [];\n mapSlices.push(currentSlice);\n }\n }\n if (currentSlice.length === 0) {\n mapSlices.pop();\n }\n return mapSlices;\n }\n\n /**\n * @private\n *\n * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session\n *\n * @param {number} chainIndex current chain index\n *\n * @param {object<userId, deviceInfo>} userDeviceMap\n * mapping from userId to deviceInfo\n *\n * @param {object} payload fields to include in the encrypted payload\n *\n * @return {Promise} Promise which resolves once the key sharing\n * for the given userDeviceMap is generated and has been sent.\n */\n private encryptAndSendKeysToDevices(\n session: OutboundSessionInfo,\n chainIndex: number,\n userDeviceMap: IOlmDevice[],\n payload: IPayload,\n ): Promise<void> {\n const contentMap = {};\n\n const promises = [];\n for (let i = 0; i < userDeviceMap.length; i++) {\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n const val = userDeviceMap[i];\n const userId = val.userId;\n const deviceInfo = val.deviceInfo;\n const deviceId = deviceInfo.deviceId;\n\n if (!contentMap[userId]) {\n contentMap[userId] = {};\n }\n contentMap[userId][deviceId] = encryptedContent;\n\n promises.push(\n olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n userId,\n deviceInfo,\n payload,\n ),\n );\n }\n\n return Promise.all(promises).then(() => {\n // prune out any devices that encryptMessageForDevice could not encrypt for,\n // in which case it will have just not added anything to the ciphertext object.\n // There's no point sending messages to devices if we couldn't encrypt to them,\n // since that's effectively a blank message.\n for (const userId of Object.keys(contentMap)) {\n for (const deviceId of Object.keys(contentMap[userId])) {\n if (Object.keys(contentMap[userId][deviceId].ciphertext).length === 0) {\n logger.log(\n \"No ciphertext for device \" +\n userId + \":\" + deviceId + \": pruning\",\n );\n delete contentMap[userId][deviceId];\n }\n }\n // No devices left for that user? Strip that too.\n if (Object.keys(contentMap[userId]).length === 0) {\n logger.log(\"Pruned all devices for user \" + userId);\n delete contentMap[userId];\n }\n }\n\n // Is there anything left?\n if (Object.keys(contentMap).length === 0) {\n logger.log(\"No users left to send to: aborting\");\n return;\n }\n\n return this.baseApis.sendToDevice(\"m.room.encrypted\", contentMap).then(() => {\n // store that we successfully uploaded the keys of the current slice\n for (const userId of Object.keys(contentMap)) {\n for (const deviceId of Object.keys(contentMap[userId])) {\n session.markSharedWithDevice(\n userId, deviceId, chainIndex,\n );\n }\n }\n });\n });\n }\n\n /**\n * @private\n *\n * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session\n *\n * @param {array<object>} userDeviceMap list of blocked devices to notify\n *\n * @param {object} payload fields to include in the notification payload\n *\n * @return {Promise} Promise which resolves once the notifications\n * for the given userDeviceMap is generated and has been sent.\n */\n private async sendBlockedNotificationsToDevices(\n session: OutboundSessionInfo,\n userDeviceMap: IOlmDevice<IBlockedDevice>[],\n payload: IPayload,\n ): Promise<void> {\n const contentMap = {};\n\n for (const val of userDeviceMap) {\n const userId = val.userId;\n const blockedInfo = val.deviceInfo;\n const deviceInfo = blockedInfo.deviceInfo;\n const deviceId = deviceInfo.deviceId;\n\n const message = Object.assign({}, payload);\n message.code = blockedInfo.code;\n message.reason = blockedInfo.reason;\n if (message.code === \"m.no_olm\") {\n delete message.room_id;\n delete message.session_id;\n }\n\n if (!contentMap[userId]) {\n contentMap[userId] = {};\n }\n contentMap[userId][deviceId] = message;\n }\n\n await this.baseApis.sendToDevice(\"org.matrix.room_key.withheld\", contentMap);\n\n // store that we successfully uploaded the keys of the current slice\n for (const userId of Object.keys(contentMap)) {\n for (const deviceId of Object.keys(contentMap[userId])) {\n session.markNotifiedBlockedDevice(userId, deviceId);\n }\n }\n }\n\n /**\n * Re-shares a megolm session key with devices if the key has already been\n * sent to them.\n *\n * @param {string} senderKey The key of the originating device for the session\n * @param {string} sessionId ID of the outbound session to share\n * @param {string} userId ID of the user who owns the target device\n * @param {module:crypto/deviceinfo} device The target device\n */\n public async reshareKeyWithDevice(\n senderKey: string,\n sessionId: string,\n userId: string,\n device: DeviceInfo,\n ): Promise<void> {\n const obSessionInfo = this.outboundSessions[sessionId];\n if (!obSessionInfo) {\n logger.debug(`megolm session ${sessionId} not found: not re-sharing keys`);\n return;\n }\n\n // The chain index of the key we previously sent this device\n if (obSessionInfo.sharedWithDevices[userId] === undefined) {\n logger.debug(`megolm session ${sessionId} never shared with user ${userId}`);\n return;\n }\n const sentChainIndex = obSessionInfo.sharedWithDevices[userId][device.deviceId];\n if (sentChainIndex === undefined) {\n logger.debug(\n \"megolm session ID \" + sessionId + \" never shared with device \" +\n userId + \":\" + device.deviceId,\n );\n return;\n }\n\n // get the key from the inbound session: the outbound one will already\n // have been ratcheted to the next chain index.\n const key = await this.olmDevice.getInboundGroupSessionKey(\n this.roomId, senderKey, sessionId, sentChainIndex,\n );\n\n if (!key) {\n logger.warn(\n `No inbound session key found for megolm ${sessionId}: not re-sharing keys`,\n );\n return;\n }\n\n await olmlib.ensureOlmSessionsForDevices(\n this.olmDevice, this.baseApis, {\n [userId]: [device],\n },\n );\n\n const payload = {\n type: \"m.forwarded_room_key\",\n content: {\n \"algorithm\": olmlib.MEGOLM_ALGORITHM,\n \"room_id\": this.roomId,\n \"session_id\": sessionId,\n \"session_key\": key.key,\n \"chain_index\": key.chain_index,\n \"sender_key\": senderKey,\n \"sender_claimed_ed25519_key\": key.sender_claimed_ed25519_key,\n \"forwarding_curve25519_key_chain\": key.forwarding_curve25519_key_chain,\n \"org.matrix.msc3061.shared_history\": key.shared_history || false,\n },\n };\n\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n userId,\n device,\n payload,\n );\n\n await this.baseApis.sendToDevice(\"m.room.encrypted\", {\n [userId]: {\n [device.deviceId]: encryptedContent,\n },\n });\n logger.debug(`Re-shared key for megolm session ${sessionId} with ${userId}:${device.deviceId}`);\n }\n\n /**\n * @private\n *\n * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session\n *\n * @param {object} key the session key as returned by\n * OlmDevice.getOutboundGroupSessionKey\n *\n * @param {object} payload the base to-device message payload for sharing keys\n *\n * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser\n * map from userid to list of devices\n *\n * @param {array<object>} errorDevices\n * array that will be populated with the devices that we can't get an\n * olm session for\n *\n * @param {Number} [otkTimeout] The timeout in milliseconds when requesting\n * one-time keys for establishing new olm sessions.\n *\n * @param {Array} [failedServers] An array to fill with remote servers that\n * failed to respond to one-time-key requests.\n */\n private async shareKeyWithDevices(\n session: OutboundSessionInfo,\n key: IOutboundGroupSessionKey,\n payload: IPayload,\n devicesByUser: Record<string, DeviceInfo[]>,\n errorDevices: IOlmDevice[],\n otkTimeout: number,\n failedServers?: string[],\n ) {\n logger.debug(`Ensuring Olm sessions for devices in ${this.roomId}`);\n const devicemap = await olmlib.ensureOlmSessionsForDevices(\n this.olmDevice, this.baseApis, devicesByUser, false, otkTimeout, failedServers,\n logger.withPrefix(`[${this.roomId}]`),\n );\n logger.debug(`Ensured Olm sessions for devices in ${this.roomId}`);\n\n this.getDevicesWithoutSessions(devicemap, devicesByUser, errorDevices);\n\n logger.debug(`Sharing keys with Olm sessions in ${this.roomId}`);\n await this.shareKeyWithOlmSessions(session, key, payload, devicemap);\n logger.debug(`Shared keys with Olm sessions in ${this.roomId}`);\n }\n\n private async shareKeyWithOlmSessions(\n session: OutboundSessionInfo,\n key: IOutboundGroupSessionKey,\n payload: IPayload,\n devicemap: Record<string, Record<string, IOlmSessionResult>>,\n ): Promise<void> {\n const userDeviceMaps = this.splitDevices(devicemap);\n\n for (let i = 0; i < userDeviceMaps.length; i++) {\n const taskDetail =\n `megolm keys for ${session.sessionId} ` +\n `in ${this.roomId} (slice ${i + 1}/${userDeviceMaps.length})`;\n try {\n logger.debug(`Sharing ${taskDetail}`);\n await this.encryptAndSendKeysToDevices(\n session, key.chain_index, userDeviceMaps[i], payload,\n );\n logger.debug(`Shared ${taskDetail}`);\n } catch (e) {\n logger.error(`Failed to share ${taskDetail}`);\n throw e;\n }\n }\n }\n\n /**\n * Notify devices that we weren't able to create olm sessions.\n *\n * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session\n *\n * @param {object} key\n *\n * @param {Array<object>} failedDevices the devices that we were unable to\n * create olm sessions for, as returned by shareKeyWithDevices\n */\n private async notifyFailedOlmDevices(\n session: OutboundSessionInfo,\n key: IOutboundGroupSessionKey,\n failedDevices: IOlmDevice[],\n ): Promise<void> {\n logger.debug(\n `Notifying ${failedDevices.length} devices we failed to ` +\n `create Olm sessions in ${this.roomId}`,\n );\n\n // mark the devices that failed as \"handled\" because we don't want to try\n // to claim a one-time-key for dead devices on every message.\n for (const { userId, deviceInfo } of failedDevices) {\n const deviceId = deviceInfo.deviceId;\n\n session.markSharedWithDevice(\n userId, deviceId, key.chain_index,\n );\n }\n\n const filteredFailedDevices =\n await this.olmDevice.filterOutNotifiedErrorDevices(\n failedDevices,\n );\n logger.debug(\n `Filtered down to ${filteredFailedDevices.length} error devices ` +\n `in ${this.roomId}`,\n );\n const blockedMap: Record<string, Record<string, { device: IBlockedDevice }>> = {};\n for (const { userId, deviceInfo } of filteredFailedDevices) {\n blockedMap[userId] = blockedMap[userId] || {};\n // we use a similar format to what\n // olmlib.ensureOlmSessionsForDevices returns, so that\n // we can use the same function to split\n blockedMap[userId][deviceInfo.deviceId] = {\n device: {\n code: \"m.no_olm\",\n reason: WITHHELD_MESSAGES[\"m.no_olm\"],\n deviceInfo,\n },\n };\n }\n\n // send the notifications\n await this.notifyBlockedDevices(session, blockedMap);\n logger.debug(\n `Notified ${filteredFailedDevices.length} devices we failed to ` +\n `create Olm sessions in ${this.roomId}`,\n );\n }\n\n /**\n * Notify blocked devices that they have been blocked.\n *\n * @param {module:crypto/algorithms/megolm.OutboundSessionInfo} session\n *\n * @param {object<string, object>} devicesByUser\n * map from userid to device ID to blocked data\n */\n private async notifyBlockedDevices(\n session: OutboundSessionInfo,\n devicesByUser: Record<string, Record<string, { device: IBlockedDevice }>>,\n ): Promise<void> {\n const payload: IPayload = {\n room_id: this.roomId,\n session_id: session.sessionId,\n algorithm: olmlib.MEGOLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n };\n\n const userDeviceMaps = this.splitDevices(devicesByUser);\n\n for (let i = 0; i < userDeviceMaps.length; i++) {\n try {\n await this.sendBlockedNotificationsToDevices(session, userDeviceMaps[i], payload);\n logger.log(`Completed blacklist notification for ${session.sessionId} `\n + `in ${this.roomId} (slice ${i + 1}/${userDeviceMaps.length})`);\n } catch (e) {\n logger.log(`blacklist notification for ${session.sessionId} in `\n + `${this.roomId} (slice ${i + 1}/${userDeviceMaps.length}) failed`);\n\n throw e;\n }\n }\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param {module:models/room} room the room the event is in\n */\n public prepareToEncrypt(room: Room): void {\n if (this.encryptionPreparation) {\n // We're already preparing something, so don't do anything else.\n // FIXME: check if we need to restart\n // (https://github.com/matrix-org/matrix-js-sdk/issues/1255)\n const elapsedTime = Date.now() - this.encryptionPreparationMetadata.startTime;\n logger.debug(\n `Already started preparing to encrypt for ${this.roomId} ` +\n `${elapsedTime} ms ago, skipping`,\n );\n return;\n }\n\n logger.debug(`Preparing to encrypt events for ${this.roomId}`);\n\n this.encryptionPreparationMetadata = {\n startTime: Date.now(),\n };\n this.encryptionPreparation = (async () => {\n try {\n logger.debug(`Getting devices in ${this.roomId}`);\n const [devicesInRoom, blocked] = await this.getDevicesInRoom(room);\n\n if (this.crypto.getGlobalErrorOnUnknownDevices()) {\n // Drop unknown devices for now. When the message gets sent, we'll\n // throw an error, but we'll still be prepared to send to the known\n // devices.\n this.removeUnknownDevices(devicesInRoom);\n }\n\n logger.debug(`Ensuring outbound session in ${this.roomId}`);\n await this.ensureOutboundSession(room, devicesInRoom, blocked, true);\n\n logger.debug(`Ready to encrypt events for ${this.roomId}`);\n } catch (e) {\n logger.error(`Failed to prepare to encrypt events for ${this.roomId}`, e);\n } finally {\n delete this.encryptionPreparationMetadata;\n delete this.encryptionPreparation;\n }\n })();\n }\n\n /**\n * @inheritdoc\n *\n * @param {module:models/room} room\n * @param {string} eventType\n * @param {object} content plaintext event content\n *\n * @return {Promise} Promise which resolves to the new event body\n */\n public async encryptMessage(room: Room, eventType: string, content: object): Promise<object> {\n logger.log(`Starting to encrypt event for ${this.roomId}`);\n\n if (this.encryptionPreparation) {\n // If we started sending keys, wait for it to be done.\n // FIXME: check if we need to cancel\n // (https://github.com/matrix-org/matrix-js-sdk/issues/1255)\n try {\n await this.encryptionPreparation;\n } catch (e) {\n // ignore any errors -- if the preparation failed, we'll just\n // restart everything here\n }\n }\n\n const [devicesInRoom, blocked] = await this.getDevicesInRoom(room);\n\n // check if any of these devices are not yet known to the user.\n // if so, warn the user so they can verify or ignore.\n if (this.crypto.getGlobalErrorOnUnknownDevices()) {\n this.checkForUnknownDevices(devicesInRoom);\n }\n\n const session = await this.ensureOutboundSession(room, devicesInRoom, blocked);\n const payloadJson = {\n room_id: this.roomId,\n type: eventType,\n content: content,\n };\n\n const ciphertext = this.olmDevice.encryptGroupMessage(\n session.sessionId, JSON.stringify(payloadJson),\n );\n const encryptedContent = {\n algorithm: olmlib.MEGOLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: ciphertext,\n session_id: session.sessionId,\n // Include our device ID so that recipients can send us a\n // m.new_device message if they don't have our session key.\n // XXX: Do we still need this now that m.new_device messages\n // no longer exist since #483?\n device_id: this.deviceId,\n };\n\n session.useCount++;\n return encryptedContent;\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * This should not normally be necessary.\n */\n public forceDiscardSession(): void {\n this.setupPromise = this.setupPromise.then(() => null);\n }\n\n /**\n * Checks the devices we're about to send to and see if any are entirely\n * unknown to the user. If so, warn the user, and mark them as known to\n * give the user a chance to go verify them before re-sending this message.\n *\n * @param {Object} devicesInRoom userId -> {deviceId -> object}\n * devices we should shared the session with.\n */\n private checkForUnknownDevices(devicesInRoom: DeviceInfoMap): void {\n const unknownDevices = {};\n\n Object.keys(devicesInRoom).forEach((userId)=>{\n Object.keys(devicesInRoom[userId]).forEach((deviceId)=>{\n const device = devicesInRoom[userId][deviceId];\n if (device.isUnverified() && !device.isKnown()) {\n if (!unknownDevices[userId]) {\n unknownDevices[userId] = {};\n }\n unknownDevices[userId][deviceId] = device;\n }\n });\n });\n\n if (Object.keys(unknownDevices).length) {\n // it'd be kind to pass unknownDevices up to the user in this error\n throw new UnknownDeviceError(\n \"This room contains unknown devices which have not been verified. \" +\n \"We strongly recommend you verify them before continuing.\", unknownDevices);\n }\n }\n\n /**\n * Remove unknown devices from a set of devices. The devicesInRoom parameter\n * will be modified.\n *\n * @param {Object} devicesInRoom userId -> {deviceId -> object}\n * devices we should shared the session with.\n */\n private removeUnknownDevices(devicesInRoom: DeviceInfoMap): void {\n for (const [userId, userDevices] of Object.entries(devicesInRoom)) {\n for (const [deviceId, device] of Object.entries(userDevices)) {\n if (device.isUnverified() && !device.isKnown()) {\n delete userDevices[deviceId];\n }\n }\n\n if (Object.keys(userDevices).length === 0) {\n delete devicesInRoom[userId];\n }\n }\n }\n\n /**\n * Get the list of unblocked devices for all users in the room\n *\n * @param {module:models/room} room\n *\n * @return {Promise} Promise which resolves to an array whose\n * first element is a map from userId to deviceId to deviceInfo indicating\n * the devices that messages should be encrypted to, and whose second\n * element is a map from userId to deviceId to data indicating the devices\n * that are in the room but that have been blocked\n */\n private async getDevicesInRoom(room: Room): Promise<[DeviceInfoMap, IBlockedMap]> {\n const members = await room.getEncryptionTargetMembers();\n const roomMembers = members.map(function(u) {\n return u.userId;\n });\n\n // The global value is treated as a default for when rooms don't specify a value.\n let isBlacklisting = this.crypto.getGlobalBlacklistUnverifiedDevices();\n if (typeof room.getBlacklistUnverifiedDevices() === 'boolean') {\n isBlacklisting = room.getBlacklistUnverifiedDevices();\n }\n\n // We are happy to use a cached version here: we assume that if we already\n // have a list of the user's devices, then we already share an e2e room\n // with them, which means that they will have announced any new devices via\n // device_lists in their /sync response. This cache should then be maintained\n // using all the device_lists changes and left fields.\n // See https://github.com/vector-im/element-web/issues/2305 for details.\n const devices = await this.crypto.downloadKeys(roomMembers, false);\n const blocked: IBlockedMap = {};\n // remove any blocked devices\n for (const userId in devices) {\n if (!devices.hasOwnProperty(userId)) {\n continue;\n }\n\n const userDevices = devices[userId];\n for (const deviceId in userDevices) {\n if (!userDevices.hasOwnProperty(deviceId)) {\n continue;\n }\n\n const deviceTrust = this.crypto.checkDeviceTrust(userId, deviceId);\n\n if (userDevices[deviceId].isBlocked() ||\n (!deviceTrust.isVerified() && isBlacklisting)\n ) {\n if (!blocked[userId]) {\n blocked[userId] = {};\n }\n const isBlocked = userDevices[deviceId].isBlocked();\n blocked[userId][deviceId] = {\n code: isBlocked ? \"m.blacklisted\" : \"m.unverified\",\n reason: WITHHELD_MESSAGES[isBlocked ? \"m.blacklisted\" : \"m.unverified\"],\n deviceInfo: userDevices[deviceId],\n };\n delete userDevices[deviceId];\n }\n }\n }\n\n return [devices, blocked];\n }\n}\n\n/**\n * Megolm decryption implementation\n *\n * @constructor\n * @extends {module:crypto/algorithms/DecryptionAlgorithm}\n *\n * @param {object} params parameters, as per\n * {@link module:crypto/algorithms/DecryptionAlgorithm}\n */\nclass MegolmDecryption extends DecryptionAlgorithm {\n // events which we couldn't decrypt due to unknown sessions / indexes: map from\n // senderKey|sessionId to Set of MatrixEvents\n private pendingEvents: Record<string, Map<string, Set<MatrixEvent>>> = {};\n\n // this gets stubbed out by the unit tests.\n private olmlib = olmlib;\n\n /**\n * @inheritdoc\n *\n * @param {MatrixEvent} event\n *\n * returns a promise which resolves to a\n * {@link module:crypto~EventDecryptionResult} once we have finished\n * decrypting, or rejects with an `algorithms.DecryptionError` if there is a\n * problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult> {\n const content = event.getWireContent();\n\n if (!content.sender_key || !content.session_id ||\n !content.ciphertext\n ) {\n throw new DecryptionError(\n \"MEGOLM_MISSING_FIELDS\",\n \"Missing fields in input\",\n );\n }\n\n // we add the event to the pending list *before* we start decryption.\n //\n // then, if the key turns up while decryption is in progress (and\n // decryption fails), we will schedule a retry.\n // (fixes https://github.com/vector-im/element-web/issues/5001)\n this.addEventToPendingList(event);\n\n let res;\n try {\n res = await this.olmDevice.decryptGroupMessage(\n event.getRoomId(), content.sender_key, content.session_id, content.ciphertext,\n event.getId(), event.getTs(),\n );\n } catch (e) {\n if (e.name === \"DecryptionError\") {\n // re-throw decryption errors as-is\n throw e;\n }\n\n let errorCode = \"OLM_DECRYPT_GROUP_MESSAGE_ERROR\";\n\n if (e && e.message === 'OLM.UNKNOWN_MESSAGE_INDEX') {\n this.requestKeysForEvent(event);\n\n errorCode = 'OLM_UNKNOWN_MESSAGE_INDEX';\n }\n\n throw new DecryptionError(\n errorCode,\n e ? e.toString() : \"Unknown Error: Error is undefined\", {\n session: content.sender_key + '|' + content.session_id,\n },\n );\n }\n\n if (res === null) {\n // We've got a message for a session we don't have.\n //\n // (XXX: We might actually have received this key since we started\n // decrypting, in which case we'll have scheduled a retry, and this\n // request will be redundant. We could probably check to see if the\n // event is still in the pending list; if not, a retry will have been\n // scheduled, so we needn't send out the request here.)\n this.requestKeysForEvent(event);\n\n // See if there was a problem with the olm session at the time the\n // event was sent. Use a fuzz factor of 2 minutes.\n const problem = await this.olmDevice.sessionMayHaveProblems(\n content.sender_key, event.getTs() - 120000,\n );\n if (problem) {\n let problemDescription = PROBLEM_DESCRIPTIONS[problem.type]\n || PROBLEM_DESCRIPTIONS.unknown;\n if (problem.fixed) {\n problemDescription +=\n \" Trying to create a new secure channel and re-requesting the keys.\";\n }\n throw new DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n problemDescription,\n {\n session: content.sender_key + '|' + content.session_id,\n },\n );\n }\n\n throw new DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n \"The sender's device has not sent us the keys for this message.\",\n {\n session: content.sender_key + '|' + content.session_id,\n },\n );\n }\n\n // success. We can remove the event from the pending list, if that hasn't\n // already happened.\n this.removeEventFromPendingList(event);\n\n const payload = JSON.parse(res.result);\n\n // belt-and-braces check that the room id matches that indicated by the HS\n // (this is somewhat redundant, since the megolm session is scoped to the\n // room, so neither the sender nor a MITM can lie about the room_id).\n if (payload.room_id !== event.getRoomId()) {\n throw new DecryptionError(\n \"MEGOLM_BAD_ROOM\",\n \"Message intended for room \" + payload.room_id,\n );\n }\n\n return {\n clearEvent: payload,\n senderCurve25519Key: res.senderKey,\n claimedEd25519Key: res.keysClaimed.ed25519,\n forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain,\n untrusted: res.untrusted,\n };\n }\n\n private requestKeysForEvent(event: MatrixEvent): void {\n const wireContent = event.getWireContent();\n\n const recipients = event.getKeyRequestRecipients(this.userId);\n\n this.crypto.requestRoomKey({\n room_id: event.getRoomId(),\n algorithm: wireContent.algorithm,\n sender_key: wireContent.sender_key,\n session_id: wireContent.session_id,\n }, recipients);\n }\n\n /**\n * Add an event to the list of those awaiting their session keys.\n *\n * @private\n *\n * @param {module:models/event.MatrixEvent} event\n */\n private addEventToPendingList(event: MatrixEvent): void {\n const content = event.getWireContent();\n const senderKey = content.sender_key;\n const sessionId = content.session_id;\n if (!this.pendingEvents[senderKey]) {\n this.pendingEvents[senderKey] = new Map();\n }\n const senderPendingEvents = this.pendingEvents[senderKey];\n if (!senderPendingEvents.has(sessionId)) {\n senderPendingEvents.set(sessionId, new Set());\n }\n senderPendingEvents.get(sessionId).add(event);\n }\n\n /**\n * Remove an event from the list of those awaiting their session keys.\n *\n * @private\n *\n * @param {module:models/event.MatrixEvent} event\n */\n private removeEventFromPendingList(event: MatrixEvent): void {\n const content = event.getWireContent();\n const senderKey = content.sender_key;\n const sessionId = content.session_id;\n const senderPendingEvents = this.pendingEvents[senderKey];\n const pendingEvents = senderPendingEvents && senderPendingEvents.get(sessionId);\n if (!pendingEvents) {\n return;\n }\n\n pendingEvents.delete(event);\n if (pendingEvents.size === 0) {\n senderPendingEvents.delete(senderKey);\n }\n if (senderPendingEvents.size === 0) {\n delete this.pendingEvents[senderKey];\n }\n }\n\n /**\n * @inheritdoc\n *\n * @param {module:models/event.MatrixEvent} event key event\n */\n public onRoomKeyEvent(event: MatrixEvent): void {\n const content = event.getContent();\n const sessionId = content.session_id;\n let senderKey = event.getSenderKey();\n let forwardingKeyChain = [];\n let exportFormat = false;\n let keysClaimed;\n\n if (!content.room_id ||\n !sessionId ||\n !content.session_key\n ) {\n logger.error(\"key event is missing fields\");\n return;\n }\n\n if (!senderKey) {\n logger.error(\"key event has no sender key (not encrypted?)\");\n return;\n }\n\n if (event.getType() == \"m.forwarded_room_key\") {\n exportFormat = true;\n forwardingKeyChain = content.forwarding_curve25519_key_chain;\n if (!Array.isArray(forwardingKeyChain)) {\n forwardingKeyChain = [];\n }\n\n // copy content before we modify it\n forwardingKeyChain = forwardingKeyChain.slice();\n forwardingKeyChain.push(senderKey);\n\n senderKey = content.sender_key;\n if (!senderKey) {\n logger.error(\"forwarded_room_key event is missing sender_key field\");\n return;\n }\n\n const ed25519Key = content.sender_claimed_ed25519_key;\n if (!ed25519Key) {\n logger.error(\n `forwarded_room_key_event is missing sender_claimed_ed25519_key field`,\n );\n return;\n }\n\n keysClaimed = {\n ed25519: ed25519Key,\n };\n } else {\n keysClaimed = event.getKeysClaimed();\n }\n\n const extraSessionData: any = {};\n if (content[\"org.matrix.msc3061.shared_history\"]) {\n extraSessionData.sharedHistory = true;\n }\n return this.olmDevice.addInboundGroupSession(\n content.room_id, senderKey, forwardingKeyChain, sessionId,\n content.session_key, keysClaimed,\n exportFormat, extraSessionData,\n ).then(() => {\n // have another go at decrypting events sent with this session.\n this.retryDecryption(senderKey, sessionId)\n .then((success) => {\n // cancel any outstanding room key requests for this session.\n // Only do this if we managed to decrypt every message in the\n // session, because if we didn't, we leave the other key\n // requests in the hopes that someone sends us a key that\n // includes an earlier index.\n if (success) {\n this.crypto.cancelRoomKeyRequest({\n algorithm: content.algorithm,\n room_id: content.room_id,\n session_id: content.session_id,\n sender_key: senderKey,\n });\n }\n });\n }).then(() => {\n // don't wait for the keys to be backed up for the server\n this.crypto.backupManager.backupGroupSession(senderKey, content.session_id);\n }).catch((e) => {\n logger.error(`Error handling m.room_key_event: ${e}`);\n });\n }\n\n /**\n * @inheritdoc\n *\n * @param {module:models/event.MatrixEvent} event key event\n */\n public async onRoomKeyWithheldEvent(event: MatrixEvent): Promise<void> {\n const content = event.getContent();\n const senderKey = content.sender_key;\n\n if (content.code === \"m.no_olm\") {\n const sender = event.getSender();\n logger.warn(\n `${sender}:${senderKey} was unable to establish an olm session with us`,\n );\n // if the sender says that they haven't been able to establish an olm\n // session, let's proactively establish one\n\n // Note: after we record that the olm session has had a problem, we\n // trigger retrying decryption for all the messages from the sender's\n // key, so that we can update the error message to indicate the olm\n // session problem.\n\n if (await this.olmDevice.getSessionIdForDevice(senderKey)) {\n // a session has already been established, so we don't need to\n // create a new one.\n logger.debug(\"New session already created. Not creating a new one.\");\n await this.olmDevice.recordSessionProblem(senderKey, \"no_olm\", true);\n this.retryDecryptionFromSender(senderKey);\n return;\n }\n let device = this.crypto.deviceList.getDeviceByIdentityKey(\n content.algorithm, senderKey,\n );\n if (!device) {\n // if we don't know about the device, fetch the user's devices again\n // and retry before giving up\n await this.crypto.downloadKeys([sender], false);\n device = this.crypto.deviceList.getDeviceByIdentityKey(\n content.algorithm, senderKey,\n );\n if (!device) {\n logger.info(\n \"Couldn't find device for identity key \" + senderKey +\n \": not establishing session\",\n );\n await this.olmDevice.recordSessionProblem(senderKey, \"no_olm\", false);\n this.retryDecryptionFromSender(senderKey);\n return;\n }\n }\n await olmlib.ensureOlmSessionsForDevices(\n this.olmDevice, this.baseApis, { [sender]: [device] }, false,\n );\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n undefined,\n this.olmDevice,\n sender,\n device,\n { type: \"m.dummy\" },\n );\n\n await this.olmDevice.recordSessionProblem(senderKey, \"no_olm\", true);\n this.retryDecryptionFromSender(senderKey);\n\n await this.baseApis.sendToDevice(\"m.room.encrypted\", {\n [sender]: {\n [device.deviceId]: encryptedContent,\n },\n });\n } else {\n await this.olmDevice.addInboundGroupSessionWithheld(\n content.room_id, senderKey, content.session_id, content.code,\n content.reason,\n );\n }\n }\n\n /**\n * @inheritdoc\n */\n public hasKeysForKeyRequest(keyRequest: IncomingRoomKeyRequest): Promise<boolean> {\n const body = keyRequest.requestBody;\n\n return this.olmDevice.hasInboundSessionKeys(\n body.room_id,\n body.sender_key,\n body.session_id,\n // TODO: ratchet index\n );\n }\n\n /**\n * @inheritdoc\n */\n public shareKeysWithDevice(keyRequest: IncomingRoomKeyRequest): void {\n const userId = keyRequest.userId;\n const deviceId = keyRequest.deviceId;\n const deviceInfo = this.crypto.getStoredDevice(userId, deviceId);\n const body = keyRequest.requestBody;\n\n this.olmlib.ensureOlmSessionsForDevices(\n this.olmDevice, this.baseApis, {\n [userId]: [deviceInfo],\n },\n ).then((devicemap) => {\n const olmSessionResult = devicemap[userId][deviceId];\n if (!olmSessionResult.sessionId) {\n // no session with this device, probably because there\n // were no one-time keys.\n //\n // ensureOlmSessionsForUsers has already done the logging,\n // so just skip it.\n return null;\n }\n\n logger.log(\n \"sharing keys for session \" + body.sender_key + \"|\"\n + body.session_id + \" with device \"\n + userId + \":\" + deviceId,\n );\n\n return this.buildKeyForwardingMessage(\n body.room_id, body.sender_key, body.session_id,\n );\n }).then((payload) => {\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n\n return this.olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n undefined,\n this.olmDevice,\n userId,\n deviceInfo,\n payload,\n ).then(() => {\n const contentMap = {\n [userId]: {\n [deviceId]: encryptedContent,\n },\n };\n\n // TODO: retries\n return this.baseApis.sendToDevice(\"m.room.encrypted\", contentMap);\n });\n });\n }\n\n private async buildKeyForwardingMessage(\n roomId: string,\n senderKey: string,\n sessionId: string,\n ): Promise<IKeyForwardingMessage> {\n const key = await this.olmDevice.getInboundGroupSessionKey(roomId, senderKey, sessionId);\n\n return {\n type: \"m.forwarded_room_key\",\n content: {\n \"algorithm\": olmlib.MEGOLM_ALGORITHM,\n \"room_id\": roomId,\n \"sender_key\": senderKey,\n \"sender_claimed_ed25519_key\": key.sender_claimed_ed25519_key,\n \"session_id\": sessionId,\n \"session_key\": key.key,\n \"chain_index\": key.chain_index,\n \"forwarding_curve25519_key_chain\": key.forwarding_curve25519_key_chain,\n \"org.matrix.msc3061.shared_history\": key.shared_history || false,\n },\n };\n }\n\n /**\n * @inheritdoc\n *\n * @param {module:crypto/OlmDevice.MegolmSessionData} session\n * @param {object} [opts={}] options for the import\n * @param {boolean} [opts.untrusted] whether the key should be considered as untrusted\n * @param {string} [opts.source] where the key came from\n */\n public importRoomKey(session: IMegolmSessionData, opts: any = {}): Promise<void> {\n const extraSessionData: any = {};\n if (opts.untrusted || session.untrusted) {\n extraSessionData.untrusted = true;\n }\n if (session[\"org.matrix.msc3061.shared_history\"]) {\n extraSessionData.sharedHistory = true;\n }\n return this.olmDevice.addInboundGroupSession(\n session.room_id,\n session.sender_key,\n session.forwarding_curve25519_key_chain,\n session.session_id,\n session.session_key,\n session.sender_claimed_keys,\n true,\n extraSessionData,\n ).then(() => {\n if (opts.source !== \"backup\") {\n // don't wait for it to complete\n this.crypto.backupManager.backupGroupSession(\n session.sender_key, session.session_id,\n ).catch((e) => {\n // This throws if the upload failed, but this is fine\n // since it will have written it to the db and will retry.\n logger.log(\"Failed to back up megolm session\", e);\n });\n }\n // have another go at decrypting events sent with this session.\n this.retryDecryption(session.sender_key, session.session_id);\n });\n }\n\n /**\n * Have another go at decrypting events after we receive a key. Resolves once\n * decryption has been re-attempted on all events.\n *\n * @private\n * @param {String} senderKey\n * @param {String} sessionId\n *\n * @return {Boolean} whether all messages were successfully decrypted\n */\n private async retryDecryption(senderKey: string, sessionId: string): Promise<boolean> {\n const senderPendingEvents = this.pendingEvents[senderKey];\n if (!senderPendingEvents) {\n return true;\n }\n\n const pending = senderPendingEvents.get(sessionId);\n if (!pending) {\n return true;\n }\n\n logger.debug(\"Retrying decryption on events\", [...pending]);\n\n await Promise.all([...pending].map(async (ev) => {\n try {\n await ev.attemptDecryption(this.crypto, { isRetry: true });\n } catch (e) {\n // don't die if something goes wrong\n }\n }));\n\n // If decrypted successfully, they'll have been removed from pendingEvents\n return !((this.pendingEvents[senderKey] || {})[sessionId]);\n }\n\n public async retryDecryptionFromSender(senderKey: string): Promise<boolean> {\n const senderPendingEvents = this.pendingEvents[senderKey];\n if (!senderPendingEvents) {\n return true;\n }\n\n delete this.pendingEvents[senderKey];\n\n await Promise.all([...senderPendingEvents].map(async ([_sessionId, pending]) => {\n await Promise.all([...pending].map(async (ev) => {\n try {\n await ev.attemptDecryption(this.crypto);\n } catch (e) {\n // don't die if something goes wrong\n }\n }));\n }));\n\n return !this.pendingEvents[senderKey];\n }\n\n public async sendSharedHistoryInboundSessions(devicesByUser: Record<string, DeviceInfo[]>): Promise<void> {\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser);\n\n logger.log(\"sendSharedHistoryInboundSessions to users\", Object.keys(devicesByUser));\n\n const sharedHistorySessions = await this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);\n logger.log(\"shared-history sessions\", sharedHistorySessions);\n for (const [senderKey, sessionId] of sharedHistorySessions) {\n const payload = await this.buildKeyForwardingMessage(this.roomId, senderKey, sessionId);\n\n const promises = [];\n const contentMap = {};\n for (const [userId, devices] of Object.entries(devicesByUser)) {\n contentMap[userId] = {};\n for (const deviceInfo of devices) {\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n contentMap[userId][deviceInfo.deviceId] = encryptedContent;\n promises.push(\n olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n undefined,\n this.olmDevice,\n userId,\n deviceInfo,\n payload,\n ),\n );\n }\n }\n await Promise.all(promises);\n\n // prune out any devices that encryptMessageForDevice could not encrypt for,\n // in which case it will have just not added anything to the ciphertext object.\n // There's no point sending messages to devices if we couldn't encrypt to them,\n // since that's effectively a blank message.\n for (const userId of Object.keys(contentMap)) {\n for (const deviceId of Object.keys(contentMap[userId])) {\n if (Object.keys(contentMap[userId][deviceId].ciphertext).length === 0) {\n logger.log(\n \"No ciphertext for device \" +\n userId + \":\" + deviceId + \": pruning\",\n );\n delete contentMap[userId][deviceId];\n }\n }\n // No devices left for that user? Strip that too.\n if (Object.keys(contentMap[userId]).length === 0) {\n logger.log(\"Pruned all devices for user \" + userId);\n delete contentMap[userId];\n }\n }\n\n // Is there anything left?\n if (Object.keys(contentMap).length === 0) {\n logger.log(\"No users left to send to: aborting\");\n return;\n }\n\n await this.baseApis.sendToDevice(\"m.room.encrypted\", contentMap);\n }\n }\n}\n\nconst PROBLEM_DESCRIPTIONS = {\n no_olm: \"The sender was unable to establish a secure channel.\",\n unknown: \"The secure channel with the sender was corrupted.\",\n};\n\nregisterAlgorithm(olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption);\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Defines m.olm encryption/decryption\n *\n * @module crypto/algorithms/olm\n */\n\nimport { logger } from '../../logger';\nimport * as olmlib from \"../olmlib\";\nimport { DeviceInfo } from \"../deviceinfo\";\nimport {\n DecryptionAlgorithm,\n DecryptionError,\n EncryptionAlgorithm,\n registerAlgorithm,\n} from \"./base\";\nimport { Room } from '../../models/room';\nimport { MatrixEvent } from \"../..\";\nimport { IEventDecryptionResult } from \"../index\";\n\nconst DeviceVerification = DeviceInfo.DeviceVerification;\n\ninterface IMessage {\n type: number | string;\n body: string;\n}\n\n/**\n * Olm encryption implementation\n *\n * @constructor\n * @extends {module:crypto/algorithms/EncryptionAlgorithm}\n *\n * @param {object} params parameters, as per\n * {@link module:crypto/algorithms/EncryptionAlgorithm}\n */\nclass OlmEncryption extends EncryptionAlgorithm {\n private sessionPrepared = false;\n private prepPromise: Promise<void> = null;\n\n /**\n * @private\n\n * @param {string[]} roomMembers list of currently-joined users in the room\n * @return {Promise} Promise which resolves when setup is complete\n */\n private ensureSession(roomMembers: string[]): Promise<void> {\n if (this.prepPromise) {\n // prep already in progress\n return this.prepPromise;\n }\n\n if (this.sessionPrepared) {\n // prep already done\n return Promise.resolve();\n }\n\n this.prepPromise = this.crypto.downloadKeys(roomMembers).then((res) => {\n return this.crypto.ensureOlmSessionsForUsers(roomMembers);\n }).then(() => {\n this.sessionPrepared = true;\n }).finally(() => {\n this.prepPromise = null;\n });\n\n return this.prepPromise;\n }\n\n /**\n * @inheritdoc\n *\n * @param {module:models/room} room\n * @param {string} eventType\n * @param {object} content plaintext event content\n *\n * @return {Promise} Promise which resolves to the new event body\n */\n public async encryptMessage(room: Room, eventType: string, content: object): Promise<object> {\n // pick the list of recipients based on the membership list.\n //\n // TODO: there is a race condition here! What if a new user turns up\n // just as you are sending a secret message?\n\n const members = await room.getEncryptionTargetMembers();\n\n const users = members.map(function(u) {\n return u.userId;\n });\n\n await this.ensureSession(users);\n\n const payloadFields = {\n room_id: room.roomId,\n type: eventType,\n content: content,\n };\n\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n\n const promises = [];\n\n for (let i = 0; i < users.length; ++i) {\n const userId = users[i];\n const devices = this.crypto.getStoredDevicesForUser(userId);\n\n for (let j = 0; j < devices.length; ++j) {\n const deviceInfo = devices[j];\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother sending to ourself\n continue;\n }\n if (deviceInfo.verified == DeviceVerification.BLOCKED) {\n // don't bother setting up sessions with blocked users\n continue;\n }\n\n promises.push(\n olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId, this.deviceId, this.olmDevice,\n userId, deviceInfo, payloadFields,\n ),\n );\n }\n }\n\n return await Promise.all(promises).then(() => encryptedContent);\n }\n}\n\n/**\n * Olm decryption implementation\n *\n * @constructor\n * @extends {module:crypto/algorithms/DecryptionAlgorithm}\n * @param {object} params parameters, as per\n * {@link module:crypto/algorithms/DecryptionAlgorithm}\n */\nclass OlmDecryption extends DecryptionAlgorithm {\n /**\n * @inheritdoc\n *\n * @param {MatrixEvent} event\n *\n * returns a promise which resolves to a\n * {@link module:crypto~EventDecryptionResult} once we have finished\n * decrypting. Rejects with an `algorithms.DecryptionError` if there is a\n * problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult> {\n const content = event.getWireContent();\n const deviceKey = content.sender_key;\n const ciphertext = content.ciphertext;\n\n if (!ciphertext) {\n throw new DecryptionError(\n \"OLM_MISSING_CIPHERTEXT\",\n \"Missing ciphertext\",\n );\n }\n\n if (!(this.olmDevice.deviceCurve25519Key in ciphertext)) {\n throw new DecryptionError(\n \"OLM_NOT_INCLUDED_IN_RECIPIENTS\",\n \"Not included in recipients\",\n );\n }\n const message = ciphertext[this.olmDevice.deviceCurve25519Key];\n let payloadString;\n\n try {\n payloadString = await this.decryptMessage(deviceKey, message);\n } catch (e) {\n throw new DecryptionError(\n \"OLM_BAD_ENCRYPTED_MESSAGE\",\n \"Bad Encrypted Message\", {\n sender: deviceKey,\n err: e,\n },\n );\n }\n\n const payload = JSON.parse(payloadString);\n\n // check that we were the intended recipient, to avoid unknown-key attack\n // https://github.com/vector-im/vector-web/issues/2483\n if (payload.recipient != this.userId) {\n throw new DecryptionError(\n \"OLM_BAD_RECIPIENT\",\n \"Message was intented for \" + payload.recipient,\n );\n }\n\n if (payload.recipient_keys.ed25519 != this.olmDevice.deviceEd25519Key) {\n throw new DecryptionError(\n \"OLM_BAD_RECIPIENT_KEY\",\n \"Message not intended for this device\", {\n intended: payload.recipient_keys.ed25519,\n our_key: this.olmDevice.deviceEd25519Key,\n },\n );\n }\n\n // check that the original sender matches what the homeserver told us, to\n // avoid people masquerading as others.\n // (this check is also provided via the sender's embedded ed25519 key,\n // which is checked elsewhere).\n if (payload.sender != event.getSender()) {\n throw new DecryptionError(\n \"OLM_FORWARDED_MESSAGE\",\n \"Message forwarded from \" + payload.sender, {\n reported_sender: event.getSender(),\n },\n );\n }\n\n // Olm events intended for a room have a room_id.\n if (payload.room_id !== event.getRoomId()) {\n throw new DecryptionError(\n \"OLM_BAD_ROOM\",\n \"Message intended for room \" + payload.room_id, {\n reported_room: event.getRoomId(),\n },\n );\n }\n\n const claimedKeys = payload.keys || {};\n\n return {\n clearEvent: payload,\n senderCurve25519Key: deviceKey,\n claimedEd25519Key: claimedKeys.ed25519 || null,\n };\n }\n\n /**\n * Attempt to decrypt an Olm message\n *\n * @param {string} theirDeviceIdentityKey Curve25519 identity key of the sender\n * @param {object} message message object, with 'type' and 'body' fields\n *\n * @return {string} payload, if decrypted successfully.\n */\n private async decryptMessage(theirDeviceIdentityKey: string, message: IMessage): Promise<string> {\n // This is a wrapper that serialises decryptions of prekey messages, because\n // otherwise we race between deciding we have no active sessions for the message\n // and creating a new one, which we can only do once because it removes the OTK.\n if (message.type !== 0) {\n // not a prekey message: we can safely just try & decrypt it\n return this.reallyDecryptMessage(theirDeviceIdentityKey, message);\n } else {\n const myPromise = this.olmDevice._olmPrekeyPromise.then(() => {\n return this.reallyDecryptMessage(theirDeviceIdentityKey, message);\n });\n // we want the error, but don't propagate it to the next decryption\n this.olmDevice._olmPrekeyPromise = myPromise.catch(() => {});\n return await myPromise;\n }\n }\n\n private async reallyDecryptMessage(theirDeviceIdentityKey: string, message: IMessage): Promise<string> {\n const sessionIds = await this.olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey);\n\n // try each session in turn.\n const decryptionErrors = {};\n for (let i = 0; i < sessionIds.length; i++) {\n const sessionId = sessionIds[i];\n try {\n const payload = await this.olmDevice.decryptMessage(\n theirDeviceIdentityKey, sessionId, message.type, message.body,\n );\n logger.log(\n \"Decrypted Olm message from \" + theirDeviceIdentityKey +\n \" with session \" + sessionId,\n );\n return payload;\n } catch (e) {\n const foundSession = await this.olmDevice.matchesSession(\n theirDeviceIdentityKey, sessionId, message.type, message.body,\n );\n\n if (foundSession) {\n // decryption failed, but it was a prekey message matching this\n // session, so it should have worked.\n throw new Error(\n \"Error decrypting prekey message with existing session id \" +\n sessionId + \": \" + e.message,\n );\n }\n\n // otherwise it's probably a message for another session; carry on, but\n // keep a record of the error\n decryptionErrors[sessionId] = e.message;\n }\n }\n\n if (message.type !== 0) {\n // not a prekey message, so it should have matched an existing session, but it\n // didn't work.\n\n if (sessionIds.length === 0) {\n throw new Error(\"No existing sessions\");\n }\n\n throw new Error(\n \"Error decrypting non-prekey message with existing sessions: \" +\n JSON.stringify(decryptionErrors),\n );\n }\n\n // prekey message which doesn't match any existing sessions: make a new\n // session.\n\n let res;\n try {\n res = await this.olmDevice.createInboundSession(\n theirDeviceIdentityKey, message.type, message.body,\n );\n } catch (e) {\n decryptionErrors[\"(new)\"] = e.message;\n throw new Error(\n \"Error decrypting prekey message: \" +\n JSON.stringify(decryptionErrors),\n );\n }\n\n logger.log(\n \"created new inbound Olm session ID \" +\n res.session_id + \" with \" + theirDeviceIdentityKey,\n );\n return res.payload;\n }\n}\n\nregisterAlgorithm(olmlib.OLM_ALGORITHM, OlmEncryption, OlmDecryption);\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { IKeyBackupInfo } from \"./keybackup\";\n\n// TODO: Merge this with crypto.js once converted\n\nexport enum CrossSigningKey {\n Master = \"master\",\n SelfSigning = \"self_signing\",\n UserSigning = \"user_signing\",\n}\n\nexport interface IEncryptedEventInfo {\n /**\n * whether the event is encrypted (if not encrypted, some of the other properties may not be set)\n */\n encrypted: boolean;\n\n /**\n * the sender's key\n */\n senderKey: string;\n\n /**\n * the algorithm used to encrypt the event\n */\n algorithm: string;\n\n /**\n * whether we can be sure that the owner of the senderKey sent the event\n */\n authenticated: boolean;\n\n /**\n * the sender's device information, if available\n */\n sender?: DeviceInfo;\n\n /**\n * if the event's ed25519 and curve25519 keys don't match (only meaningful if `sender` is set)\n */\n mismatchedSender: boolean;\n}\n\nexport interface IRecoveryKey {\n keyInfo: {\n pubkey: string;\n passphrase?: {\n algorithm: string;\n iterations: number;\n salt: string;\n };\n };\n privateKey: Uint8Array;\n encodedPrivateKey: string;\n}\n\nexport interface ICreateSecretStorageOpts {\n /**\n * Function called to await a secret storage key creation flow.\n * Returns:\n * {Promise<Object>} Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n createSecretStorageKey?: () => Promise<IRecoveryKey>;\n\n /**\n * The current key backup object. If passed,\n * the passphrase and recovery key from this backup will be used.\n */\n keyBackupInfo?: IKeyBackupInfo;\n\n /**\n * If true, a new key backup version will be\n * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo\n * is supplied.\n */\n setupNewKeyBackup?: boolean;\n\n /**\n * Reset even if keys already exist.\n */\n setupNewSecretStorage?: boolean;\n\n /**\n * Function called to get the user's\n * current key backup passphrase. Should return a promise that resolves with a Uint8Array\n * containing the key, or rejects if the key cannot be obtained.\n */\n getKeyBackupPassphrase?: () => Promise<Uint8Array>;\n}\n\nexport interface ISecretStorageKeyInfo {\n name: string;\n algorithm: string;\n // technically the below are specific to AES keys. If we ever introduce another type,\n // we can split into separate interfaces.\n iv: string;\n mac: string;\n passphrase: IPassphraseInfo;\n}\n\nexport interface ISecretStorageKey {\n keyId: string;\n keyInfo: ISecretStorageKeyInfo;\n}\n\nexport interface IPassphraseInfo {\n algorithm: \"m.pbkdf2\";\n iterations: number;\n salt: string;\n bits: number;\n}\n\nexport interface IAddSecretStorageKeyOpts {\n name: string;\n passphrase: IPassphraseInfo;\n key: Uint8Array;\n}\n\nexport interface IImportOpts {\n stage: string; // TODO: Enum\n successes: number;\n failures: number;\n total: number;\n}\n\nexport interface IImportRoomKeysOpts {\n progressCallback: (stage: IImportOpts) => void;\n untrusted?: boolean;\n source?: string; // TODO: Enum\n}\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto/backup\n *\n * Classes for dealing with key backup.\n */\n\nimport { MatrixClient } from \"../client\";\nimport { logger } from \"../logger\";\nimport { MEGOLM_ALGORITHM, verifySignature } from \"./olmlib\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { DeviceTrustLevel } from './CrossSigning';\nimport { keyFromPassphrase } from './key_passphrase';\nimport { sleep } from \"../utils\";\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { encodeRecoveryKey } from './recoverykey';\nimport { encryptAES, decryptAES, calculateKeyCheck } from './aes';\nimport { getCrypto } from '../utils';\nimport { ICurve25519AuthData, IAes256AuthData, IKeyBackupInfo } from \"./keybackup\";\nimport { UnstableValue } from \"../NamespacedValue\";\n\nconst KEY_BACKUP_KEYS_PER_REQUEST = 200;\n\ntype AuthData = IKeyBackupInfo[\"auth_data\"];\n\ntype SigInfo = {\n deviceId: string;\n valid?: boolean | null; // true: valid, false: invalid, null: cannot attempt validation\n device?: DeviceInfo | null;\n crossSigningId?: boolean;\n deviceTrust?: DeviceTrustLevel;\n};\n\nexport type TrustInfo = {\n usable: boolean; // is the backup trusted, true iff there is a sig that is valid & from a trusted device\n sigs: SigInfo[];\n};\n\nexport interface IKeyBackupCheck {\n backupInfo: IKeyBackupInfo;\n trustInfo: TrustInfo;\n}\n\n/* eslint-disable camelcase */\nexport interface IPreparedKeyBackupVersion {\n algorithm: string;\n auth_data: AuthData;\n recovery_key: string;\n privateKey: Uint8Array;\n}\n/* eslint-enable camelcase */\n\n/** A function used to get the secret key for a backup.\n */\ntype GetKey = () => Promise<ArrayLike<number>>;\n\ninterface BackupAlgorithmClass {\n algorithmName: string;\n // initialize from an existing backup\n init(authData: AuthData, getKey: GetKey): Promise<BackupAlgorithm>;\n\n // prepare a brand new backup\n prepare(\n key: string | Uint8Array | null,\n ): Promise<[Uint8Array, AuthData]>;\n\n checkBackupVersion(info: IKeyBackupInfo): void;\n}\n\ninterface BackupAlgorithm {\n untrusted: boolean;\n encryptSession(data: Record<string, any>): Promise<any>;\n decryptSessions(ciphertexts: Record<string, any>): Promise<Record<string, any>[]>;\n authData: AuthData;\n keyMatches(key: ArrayLike<number>): Promise<boolean>;\n free(): void;\n}\n\n/**\n * Manages the key backup.\n */\nexport class BackupManager {\n private algorithm: BackupAlgorithm | undefined;\n public backupInfo: IKeyBackupInfo | undefined; // The info dict from /room_keys/version\n public checkedForBackup: boolean; // Have we checked the server for a backup we can use?\n private sendingBackups: boolean; // Are we currently sending backups?\n constructor(private readonly baseApis: MatrixClient, public readonly getKey: GetKey) {\n this.checkedForBackup = false;\n this.sendingBackups = false;\n }\n\n public get version(): string | undefined {\n return this.backupInfo && this.backupInfo.version;\n }\n\n /**\n * Performs a quick check to ensure that the backup info looks sane.\n *\n * Throws an error if a problem is detected.\n *\n * @param {IKeyBackupInfo} info the key backup info\n */\n public static checkBackupVersion(info: IKeyBackupInfo): void {\n const Algorithm = algorithmsByName[info.algorithm];\n if (!Algorithm) {\n throw new Error(\"Unknown backup algorithm: \" + info.algorithm);\n }\n if (!(typeof info.auth_data === \"object\")) {\n throw new Error(\"Invalid backup data returned\");\n }\n return Algorithm.checkBackupVersion(info);\n }\n\n public static async makeAlgorithm(info: IKeyBackupInfo, getKey: GetKey): Promise<BackupAlgorithm> {\n const Algorithm = algorithmsByName[info.algorithm];\n if (!Algorithm) {\n throw new Error(\"Unknown backup algorithm\");\n }\n return await Algorithm.init(info.auth_data, getKey);\n }\n\n public async enableKeyBackup(info: IKeyBackupInfo): Promise<void> {\n this.backupInfo = info;\n if (this.algorithm) {\n this.algorithm.free();\n }\n\n this.algorithm = await BackupManager.makeAlgorithm(info, this.getKey);\n\n this.baseApis.emit('crypto.keyBackupStatus', true);\n\n // There may be keys left over from a partially completed backup, so\n // schedule a send to check.\n this.scheduleKeyBackupSend();\n }\n\n /**\n * Disable backing up of keys.\n */\n public disableKeyBackup(): void {\n if (this.algorithm) {\n this.algorithm.free();\n }\n this.algorithm = undefined;\n\n this.backupInfo = undefined;\n\n this.baseApis.emit('crypto.keyBackupStatus', false);\n }\n\n public getKeyBackupEnabled(): boolean | null {\n if (!this.checkedForBackup) {\n return null;\n }\n return Boolean(this.algorithm);\n }\n\n public async prepareKeyBackupVersion(\n key?: string | Uint8Array | null,\n algorithm?: string | undefined,\n // eslint-disable-next-line camelcase\n ): Promise<IPreparedKeyBackupVersion> {\n const Algorithm = algorithm ? algorithmsByName[algorithm] : DefaultAlgorithm;\n if (!Algorithm) {\n throw new Error(\"Unknown backup algorithm\");\n }\n\n const [privateKey, authData] = await Algorithm.prepare(key);\n const recoveryKey = encodeRecoveryKey(privateKey);\n return {\n algorithm: Algorithm.algorithmName,\n auth_data: authData,\n recovery_key: recoveryKey,\n privateKey,\n };\n }\n\n public async createKeyBackupVersion(info: IKeyBackupInfo): Promise<void> {\n this.algorithm = await BackupManager.makeAlgorithm(info, this.getKey);\n }\n\n /**\n * Check the server for an active key backup and\n * if one is present and has a valid signature from\n * one of the user's verified devices, start backing up\n * to it.\n */\n public async checkAndStart(): Promise<IKeyBackupCheck> {\n logger.log(\"Checking key backup status...\");\n if (this.baseApis.isGuest()) {\n logger.log(\"Skipping key backup check since user is guest\");\n this.checkedForBackup = true;\n return null;\n }\n let backupInfo: IKeyBackupInfo;\n try {\n backupInfo = await this.baseApis.getKeyBackupVersion();\n } catch (e) {\n logger.log(\"Error checking for active key backup\", e);\n if (e.httpStatus === 404) {\n // 404 is returned when the key backup does not exist, so that\n // counts as successfully checking.\n this.checkedForBackup = true;\n }\n return null;\n }\n this.checkedForBackup = true;\n\n const trustInfo = await this.isKeyBackupTrusted(backupInfo);\n\n if (trustInfo.usable && !this.backupInfo) {\n logger.log(\n \"Found usable key backup v\" + backupInfo.version +\n \": enabling key backups\",\n );\n await this.enableKeyBackup(backupInfo);\n } else if (!trustInfo.usable && this.backupInfo) {\n logger.log(\"No usable key backup: disabling key backup\");\n this.disableKeyBackup();\n } else if (!trustInfo.usable && !this.backupInfo) {\n logger.log(\"No usable key backup: not enabling key backup\");\n } else if (trustInfo.usable && this.backupInfo) {\n // may not be the same version: if not, we should switch\n if (backupInfo.version !== this.backupInfo.version) {\n logger.log(\n \"On backup version \" + this.backupInfo.version + \" but found \" +\n \"version \" + backupInfo.version + \": switching.\",\n );\n this.disableKeyBackup();\n await this.enableKeyBackup(backupInfo);\n // We're now using a new backup, so schedule all the keys we have to be\n // uploaded to the new backup. This is a bit of a workaround to upload\n // keys to a new backup in *most* cases, but it won't cover all cases\n // because we don't remember what backup version we uploaded keys to:\n // see https://github.com/vector-im/element-web/issues/14833\n await this.scheduleAllGroupSessionsForBackup();\n } else {\n logger.log(\"Backup version \" + backupInfo.version + \" still current\");\n }\n }\n\n return { backupInfo, trustInfo };\n }\n\n /**\n * Forces a re-check of the key backup and enables/disables it\n * as appropriate.\n *\n * @return {Object} Object with backup info (as returned by\n * getKeyBackupVersion) in backupInfo and\n * trust information (as returned by isKeyBackupTrusted)\n * in trustInfo.\n */\n public async checkKeyBackup(): Promise<IKeyBackupCheck> {\n this.checkedForBackup = false;\n return this.checkAndStart();\n }\n\n /**\n * Check if the given backup info is trusted.\n *\n * @param {IKeyBackupInfo} backupInfo key backup info dict from /room_keys/version\n * @return {object} {\n * usable: [bool], // is the backup trusted, true iff there is a sig that is valid & from a trusted device\n * sigs: [\n * valid: [bool || null], // true: valid, false: invalid, null: cannot attempt validation\n * deviceId: [string],\n * device: [DeviceInfo || null],\n * ]\n * }\n */\n public async isKeyBackupTrusted(backupInfo: IKeyBackupInfo): Promise<TrustInfo> {\n const ret = {\n usable: false,\n trusted_locally: false,\n sigs: [],\n };\n\n if (\n !backupInfo ||\n !backupInfo.algorithm ||\n !backupInfo.auth_data ||\n !backupInfo.auth_data.signatures\n ) {\n logger.info(\"Key backup is absent or missing required data\");\n return ret;\n }\n\n const trustedPubkey = this.baseApis.crypto.sessionStore.getLocalTrustedBackupPubKey();\n\n if (\"public_key\" in backupInfo.auth_data && backupInfo.auth_data.public_key === trustedPubkey) {\n logger.info(\"Backup public key \" + trustedPubkey + \" is trusted locally\");\n ret.trusted_locally = true;\n }\n\n const mySigs = backupInfo.auth_data.signatures[this.baseApis.getUserId()] || [];\n\n for (const keyId of Object.keys(mySigs)) {\n const keyIdParts = keyId.split(':');\n if (keyIdParts[0] !== 'ed25519') {\n logger.log(\"Ignoring unknown signature type: \" + keyIdParts[0]);\n continue;\n }\n // Could be a cross-signing master key, but just say this is the device\n // ID for backwards compat\n const sigInfo: SigInfo = { deviceId: keyIdParts[1] };\n\n // first check to see if it's from our cross-signing key\n const crossSigningId = this.baseApis.crypto.crossSigningInfo.getId();\n if (crossSigningId === sigInfo.deviceId) {\n sigInfo.crossSigningId = true;\n try {\n await verifySignature(\n this.baseApis.crypto.olmDevice,\n backupInfo.auth_data,\n this.baseApis.getUserId(),\n sigInfo.deviceId,\n crossSigningId,\n );\n sigInfo.valid = true;\n } catch (e) {\n logger.warn(\n \"Bad signature from cross signing key \" + crossSigningId, e,\n );\n sigInfo.valid = false;\n }\n ret.sigs.push(sigInfo);\n continue;\n }\n\n // Now look for a sig from a device\n // At some point this can probably go away and we'll just support\n // it being signed by the cross-signing master key\n const device = this.baseApis.crypto.deviceList.getStoredDevice(\n this.baseApis.getUserId(), sigInfo.deviceId,\n );\n if (device) {\n sigInfo.device = device;\n sigInfo.deviceTrust = await this.baseApis.checkDeviceTrust(\n this.baseApis.getUserId(), sigInfo.deviceId,\n );\n try {\n await verifySignature(\n this.baseApis.crypto.olmDevice,\n backupInfo.auth_data,\n this.baseApis.getUserId(),\n device.deviceId,\n device.getFingerprint(),\n );\n sigInfo.valid = true;\n } catch (e) {\n logger.info(\n \"Bad signature from key ID \" + keyId + \" userID \" + this.baseApis.getUserId() +\n \" device ID \" + device.deviceId + \" fingerprint: \" +\n device.getFingerprint(), backupInfo.auth_data, e,\n );\n sigInfo.valid = false;\n }\n } else {\n sigInfo.valid = null; // Can't determine validity because we don't have the signing device\n logger.info(\"Ignoring signature from unknown key \" + keyId);\n }\n ret.sigs.push(sigInfo);\n }\n\n ret.usable = ret.sigs.some((s) => {\n return (\n s.valid && (\n (s.device && s.deviceTrust.isVerified()) ||\n (s.crossSigningId)\n )\n );\n });\n ret.usable = ret.usable || ret.trusted_locally;\n return ret;\n }\n\n /**\n * Schedules sending all keys waiting to be sent to the backup, if not already\n * scheduled. Retries if necessary.\n *\n * @param maxDelay Maximum delay to wait in ms. 0 means no delay.\n */\n public async scheduleKeyBackupSend(maxDelay = 10000): Promise<void> {\n if (this.sendingBackups) return;\n\n this.sendingBackups = true;\n\n try {\n // wait between 0 and `maxDelay` seconds, to avoid backup\n // requests from different clients hitting the server all at\n // the same time when a new key is sent\n const delay = Math.random() * maxDelay;\n await sleep(delay, undefined);\n let numFailures = 0; // number of consecutive failures\n for (;;) {\n if (!this.algorithm) {\n return;\n }\n try {\n const numBackedUp =\n await this.backupPendingKeys(KEY_BACKUP_KEYS_PER_REQUEST);\n if (numBackedUp === 0) {\n // no sessions left needing backup: we're done\n return;\n }\n numFailures = 0;\n } catch (err) {\n numFailures++;\n logger.log(\"Key backup request failed\", err);\n if (err.data) {\n if (\n err.data.errcode == 'M_NOT_FOUND' ||\n err.data.errcode == 'M_WRONG_ROOM_KEYS_VERSION'\n ) {\n // Re-check key backup status on error, so we can be\n // sure to present the current situation when asked.\n await this.checkKeyBackup();\n // Backup version has changed or this backup version\n // has been deleted\n this.baseApis.crypto.emit(\"crypto.keyBackupFailed\", err.data.errcode);\n throw err;\n }\n }\n }\n if (numFailures) {\n // exponential backoff if we have failures\n await sleep(1000 * Math.pow(2, Math.min(numFailures - 1, 4)), undefined);\n }\n }\n } finally {\n this.sendingBackups = false;\n }\n }\n\n /**\n * Take some e2e keys waiting to be backed up and send them\n * to the backup.\n *\n * @param {integer} limit Maximum number of keys to back up\n * @returns {integer} Number of sessions backed up\n */\n private async backupPendingKeys(limit: number): Promise<number> {\n const sessions = await this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(limit);\n if (!sessions.length) {\n return 0;\n }\n\n let remaining = await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();\n this.baseApis.crypto.emit(\"crypto.keyBackupSessionsRemaining\", remaining);\n\n const data = {};\n for (const session of sessions) {\n const roomId = session.sessionData.room_id;\n if (data[roomId] === undefined) {\n data[roomId] = { sessions: {} };\n }\n\n const sessionData = await this.baseApis.crypto.olmDevice.exportInboundGroupSession(\n session.senderKey, session.sessionId, session.sessionData,\n );\n sessionData.algorithm = MEGOLM_ALGORITHM;\n\n const forwardedCount =\n (sessionData.forwarding_curve25519_key_chain || []).length;\n\n const userId = this.baseApis.crypto.deviceList.getUserByIdentityKey(\n MEGOLM_ALGORITHM, session.senderKey,\n );\n const device = this.baseApis.crypto.deviceList.getDeviceByIdentityKey(\n MEGOLM_ALGORITHM, session.senderKey,\n );\n const verified = this.baseApis.crypto.checkDeviceInfoTrust(userId, device).isVerified();\n\n data[roomId]['sessions'][session.sessionId] = {\n first_message_index: sessionData.first_known_index,\n forwarded_count: forwardedCount,\n is_verified: verified,\n session_data: await this.algorithm.encryptSession(sessionData),\n };\n }\n\n await this.baseApis.sendKeyBackup(\n undefined, undefined, this.backupInfo.version,\n { rooms: data },\n );\n\n await this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(sessions);\n remaining = await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();\n this.baseApis.crypto.emit(\"crypto.keyBackupSessionsRemaining\", remaining);\n\n return sessions.length;\n }\n\n public async backupGroupSession(\n senderKey: string, sessionId: string,\n ): Promise<void> {\n await this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{\n senderKey: senderKey,\n sessionId: sessionId,\n }]);\n\n if (this.backupInfo) {\n // don't wait for this to complete: it will delay so\n // happens in the background\n this.scheduleKeyBackupSend();\n }\n // if this.backupInfo is not set, then the keys will be backed up when\n // this.enableKeyBackup is called\n }\n\n /**\n * Marks all group sessions as needing to be backed up and schedules them to\n * upload in the background as soon as possible.\n */\n public async scheduleAllGroupSessionsForBackup(): Promise<void> {\n await this.flagAllGroupSessionsForBackup();\n\n // Schedule keys to upload in the background as soon as possible.\n this.scheduleKeyBackupSend(0 /* maxDelay */);\n }\n\n /**\n * Marks all group sessions as needing to be backed up without scheduling\n * them to upload in the background.\n * @returns {Promise<int>} Resolves to the number of sessions now requiring a backup\n * (which will be equal to the number of sessions in the store).\n */\n public async flagAllGroupSessionsForBackup(): Promise<number> {\n await this.baseApis.crypto.cryptoStore.doTxn(\n 'readwrite',\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_BACKUP,\n ],\n (txn) => {\n this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (session) => {\n if (session !== null) {\n this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([session], txn);\n }\n });\n },\n );\n\n const remaining = await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();\n this.baseApis.emit(\"crypto.keyBackupSessionsRemaining\", remaining);\n return remaining;\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns {Promise<int>} Resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise<number> {\n return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();\n }\n}\n\nexport class Curve25519 implements BackupAlgorithm {\n public static algorithmName = \"m.megolm_backup.v1.curve25519-aes-sha2\";\n\n constructor(\n public authData: ICurve25519AuthData,\n private publicKey: any, // FIXME: PkEncryption\n private getKey: () => Promise<Uint8Array>,\n ) {}\n\n public static async init(\n authData: AuthData,\n getKey: () => Promise<Uint8Array>,\n ): Promise<Curve25519> {\n if (!authData || !(\"public_key\" in authData)) {\n throw new Error(\"auth_data missing required information\");\n }\n const publicKey = new global.Olm.PkEncryption();\n publicKey.set_recipient_key(authData.public_key);\n return new Curve25519(authData as ICurve25519AuthData, publicKey, getKey);\n }\n\n public static async prepare(\n key: string | Uint8Array | null,\n ): Promise<[Uint8Array, AuthData]> {\n const decryption = new global.Olm.PkDecryption();\n try {\n const authData: Partial<ICurve25519AuthData> = {};\n if (!key) {\n authData.public_key = decryption.generate_key();\n } else if (key instanceof Uint8Array) {\n authData.public_key = decryption.init_with_private_key(key);\n } else {\n const derivation = await keyFromPassphrase(key);\n authData.private_key_salt = derivation.salt;\n authData.private_key_iterations = derivation.iterations;\n authData.public_key = decryption.init_with_private_key(derivation.key);\n }\n const publicKey = new global.Olm.PkEncryption();\n publicKey.set_recipient_key(authData.public_key);\n\n return [\n decryption.get_private_key(),\n authData as AuthData,\n ];\n } finally {\n decryption.free();\n }\n }\n\n public static checkBackupVersion(info: IKeyBackupInfo): void {\n if (!(\"public_key\" in info.auth_data)) {\n throw new Error(\"Invalid backup data returned\");\n }\n }\n\n public get untrusted() { return true; }\n\n public async encryptSession(data: Record<string, any>): Promise<any> {\n const plainText: Record<string, any> = Object.assign({}, data);\n delete plainText.session_id;\n delete plainText.room_id;\n delete plainText.first_known_index;\n return this.publicKey.encrypt(JSON.stringify(plainText));\n }\n\n public async decryptSessions(sessions: Record<string, Record<string, any>>): Promise<Record<string, any>[]> {\n const privKey = await this.getKey();\n const decryption = new global.Olm.PkDecryption();\n try {\n const backupPubKey = decryption.init_with_private_key(privKey);\n\n if (backupPubKey !== this.authData.public_key) {\n // eslint-disable-next-line no-throw-literal\n throw { errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY };\n }\n\n const keys = [];\n\n for (const [sessionId, sessionData] of Object.entries(sessions)) {\n try {\n const decrypted = JSON.parse(decryption.decrypt(\n sessionData.session_data.ephemeral,\n sessionData.session_data.mac,\n sessionData.session_data.ciphertext,\n ));\n decrypted.session_id = sessionId;\n keys.push(decrypted);\n } catch (e) {\n logger.log(\"Failed to decrypt megolm session from backup\", e, sessionData);\n }\n }\n return keys;\n } finally {\n decryption.free();\n }\n }\n\n public async keyMatches(key: Uint8Array): Promise<boolean> {\n const decryption = new global.Olm.PkDecryption();\n let pubKey;\n try {\n pubKey = decryption.init_with_private_key(key);\n } finally {\n decryption.free();\n }\n\n return pubKey === this.authData.public_key;\n }\n\n public free(): void {\n this.publicKey.free();\n }\n}\n\nfunction randomBytes(size: number): Uint8Array {\n const crypto: {randomBytes: (n: number) => Uint8Array} | undefined = getCrypto() as any;\n if (crypto) {\n // nodejs version\n return crypto.randomBytes(size);\n }\n if (window?.crypto) {\n // browser version\n const buf = new Uint8Array(size);\n window.crypto.getRandomValues(buf);\n return buf;\n }\n throw new Error(\"No usable crypto implementation\");\n}\n\nconst UNSTABLE_MSC3270_NAME = new UnstableValue(null, \"org.matrix.msc3270.v1.aes-hmac-sha2\");\n\nexport class Aes256 implements BackupAlgorithm {\n public static algorithmName = UNSTABLE_MSC3270_NAME.name;\n\n constructor(\n public readonly authData: IAes256AuthData,\n private readonly key: Uint8Array,\n ) {}\n\n public static async init(\n authData: IAes256AuthData,\n getKey: () => Promise<Uint8Array>,\n ): Promise<Aes256> {\n if (!authData) {\n throw new Error(\"auth_data missing\");\n }\n const key = await getKey();\n if (authData.mac) {\n const { mac } = await calculateKeyCheck(key, authData.iv);\n if (authData.mac.replace(/=+$/g, '') !== mac.replace(/=+/g, '')) {\n throw new Error(\"Key does not match\");\n }\n }\n return new Aes256(authData, key);\n }\n\n public static async prepare(\n key: string | Uint8Array | null,\n ): Promise<[Uint8Array, AuthData]> {\n let outKey: Uint8Array;\n const authData: Partial<IAes256AuthData> = {};\n if (!key) {\n outKey = randomBytes(32);\n } else if (key instanceof Uint8Array) {\n outKey = new Uint8Array(key);\n } else {\n const derivation = await keyFromPassphrase(key);\n authData.private_key_salt = derivation.salt;\n authData.private_key_iterations = derivation.iterations;\n outKey = derivation.key;\n }\n\n const { iv, mac } = await calculateKeyCheck(outKey);\n authData.iv = iv;\n authData.mac = mac;\n\n return [outKey, authData as AuthData];\n }\n\n public static checkBackupVersion(info: IKeyBackupInfo): void {\n if (!(\"iv\" in info.auth_data && \"mac\" in info.auth_data)) {\n throw new Error(\"Invalid backup data returned\");\n }\n }\n\n public get untrusted() { return false; }\n\n async encryptSession(data: Record<string, any>): Promise<any> {\n const plainText: Record<string, any> = Object.assign({}, data);\n delete plainText.session_id;\n delete plainText.room_id;\n delete plainText.first_known_index;\n return await encryptAES(JSON.stringify(plainText), this.key, data.session_id);\n }\n\n async decryptSessions(sessions: Record<string, any>): Promise<Record<string, any>[]> {\n const keys = [];\n\n for (const [sessionId, sessionData] of Object.entries(sessions)) {\n try {\n const decrypted = JSON.parse(await decryptAES(\n sessionData.session_data, this.key, sessionId,\n ));\n decrypted.session_id = sessionId;\n keys.push(decrypted);\n } catch (e) {\n logger.log(\"Failed to decrypt megolm session from backup\", e, sessionData);\n }\n }\n return keys;\n }\n\n async keyMatches(key: Uint8Array): Promise<boolean> {\n if (this.authData.mac) {\n const { mac } = await calculateKeyCheck(key, this.authData.iv);\n return this.authData.mac.replace(/=+$/g, '') === mac.replace(/=+/g, '');\n } else {\n // if we have no information, we have to assume the key is right\n return true;\n }\n }\n\n public free(): void {\n this.key.fill(0);\n }\n}\n\nexport const algorithmsByName: Record<string, BackupAlgorithmClass> = {\n [Curve25519.algorithmName]: Curve25519,\n [Aes256.algorithmName]: Aes256,\n};\n\nexport const DefaultAlgorithm: BackupAlgorithmClass = Curve25519;\n",
"/*\nCopyright 2020-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { decodeBase64, encodeBase64 } from './olmlib';\nimport { IndexedDBCryptoStore } from '../crypto/store/indexeddb-crypto-store';\nimport { decryptAES, encryptAES } from './aes';\nimport anotherjson from \"another-json\";\nimport { logger } from '../logger';\nimport { ISecretStorageKeyInfo } from \"./api\";\n\n// FIXME: these types should eventually go in a different file\ntype Signatures = Record<string, Record<string, string>>;\n\nexport interface IDehydratedDevice {\n device_id: string; // eslint-disable-line camelcase\n device_data: ISecretStorageKeyInfo & { // eslint-disable-line camelcase\n algorithm: string;\n account: string; // pickle\n };\n}\n\nexport interface IDehydratedDeviceKeyInfo {\n passphrase?: string;\n}\n\ninterface DeviceKeys {\n algorithms: Array<string>;\n device_id: string; // eslint-disable-line camelcase\n user_id: string; // eslint-disable-line camelcase\n keys: Record<string, string>;\n signatures?: Signatures;\n}\n\nexport interface OneTimeKey {\n key: string;\n fallback?: boolean;\n signatures?: Signatures;\n}\n\nexport const DEHYDRATION_ALGORITHM = \"org.matrix.msc2697.v1.olm.libolm_pickle\";\n\nconst oneweek = 7 * 24 * 60 * 60 * 1000;\n\nexport class DehydrationManager {\n private inProgress = false;\n private timeoutId: any;\n private key: Uint8Array;\n private keyInfo: {[props: string]: any};\n private deviceDisplayName: string;\n constructor(private crypto) {\n this.getDehydrationKeyFromCache();\n }\n async getDehydrationKeyFromCache(): Promise<void> {\n return await this.crypto.cryptoStore.doTxn(\n 'readonly',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.crypto.cryptoStore.getSecretStorePrivateKey(\n txn,\n async (result) => {\n if (result) {\n const { key, keyInfo, deviceDisplayName, time } = result;\n const pickleKey = Buffer.from(this.crypto.olmDevice._pickleKey);\n const decrypted = await decryptAES(key, pickleKey, DEHYDRATION_ALGORITHM);\n this.key = decodeBase64(decrypted);\n this.keyInfo = keyInfo;\n this.deviceDisplayName = deviceDisplayName;\n const now = Date.now();\n const delay = Math.max(1, time + oneweek - now);\n this.timeoutId = global.setTimeout(\n this.dehydrateDevice.bind(this), delay,\n );\n }\n },\n \"dehydration\",\n );\n },\n );\n }\n\n /** set the key, and queue periodic dehydration to the server in the background */\n async setKeyAndQueueDehydration(\n key: Uint8Array, keyInfo: {[props: string]: any} = {},\n deviceDisplayName: string = undefined,\n ): Promise<void> {\n const matches = await this.setKey(key, keyInfo, deviceDisplayName);\n if (!matches) {\n // start dehydration in the background\n this.dehydrateDevice();\n }\n }\n\n async setKey(\n key: Uint8Array, keyInfo: {[props: string]: any} = {},\n deviceDisplayName: string = undefined,\n ): Promise<boolean> {\n if (!key) {\n // unsetting the key -- cancel any pending dehydration task\n if (this.timeoutId) {\n global.clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n // clear storage\n await this.crypto.cryptoStore.doTxn(\n 'readwrite',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.crypto.cryptoStore.storeSecretStorePrivateKey(\n txn, \"dehydration\", null,\n );\n },\n );\n this.key = undefined;\n this.keyInfo = undefined;\n return;\n }\n\n // Check to see if it's the same key as before. If it's different,\n // dehydrate a new device. If it's the same, we can keep the same\n // device. (Assume that keyInfo and deviceDisplayName will be the\n // same if the key is the same.)\n let matches: boolean = this.key && key.length == this.key.length;\n for (let i = 0; matches && i < key.length; i++) {\n if (key[i] != this.key[i]) {\n matches = false;\n }\n }\n if (!matches) {\n this.key = key;\n this.keyInfo = keyInfo;\n this.deviceDisplayName = deviceDisplayName;\n }\n return matches;\n }\n\n /** returns the device id of the newly created dehydrated device */\n async dehydrateDevice(): Promise<string> {\n if (this.inProgress) {\n logger.log(\"Dehydration already in progress -- not starting new dehydration\");\n return;\n }\n this.inProgress = true;\n if (this.timeoutId) {\n global.clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n try {\n const pickleKey = Buffer.from(this.crypto.olmDevice._pickleKey);\n\n // update the crypto store with the timestamp\n const key = await encryptAES(encodeBase64(this.key), pickleKey, DEHYDRATION_ALGORITHM);\n await this.crypto.cryptoStore.doTxn(\n 'readwrite',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.crypto.cryptoStore.storeSecretStorePrivateKey(\n txn, \"dehydration\",\n {\n keyInfo: this.keyInfo,\n key,\n deviceDisplayName: this.deviceDisplayName,\n time: Date.now(),\n },\n );\n },\n );\n logger.log(\"Attempting to dehydrate device\");\n\n logger.log(\"Creating account\");\n // create the account and all the necessary keys\n const account = new global.Olm.Account();\n account.create();\n const e2eKeys = JSON.parse(account.identity_keys());\n\n const maxKeys = account.max_number_of_one_time_keys();\n // FIXME: generate in small batches?\n account.generate_one_time_keys(maxKeys / 2);\n account.generate_fallback_key();\n const otks: Record<string, string> = JSON.parse(account.one_time_keys());\n const fallbacks: Record<string, string> = JSON.parse(account.fallback_key());\n account.mark_keys_as_published();\n\n // dehydrate the account and store it on the server\n const pickledAccount = account.pickle(new Uint8Array(this.key));\n\n const deviceData: {[props: string]: any} = {\n algorithm: DEHYDRATION_ALGORITHM,\n account: pickledAccount,\n };\n if (this.keyInfo.passphrase) {\n deviceData.passphrase = this.keyInfo.passphrase;\n }\n\n logger.log(\"Uploading account to server\");\n const dehydrateResult = await this.crypto.baseApis.http.authedRequest(\n undefined,\n \"PUT\",\n \"/dehydrated_device\",\n undefined,\n {\n device_data: deviceData,\n initial_device_display_name: this.deviceDisplayName,\n },\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n\n // send the keys to the server\n const deviceId = dehydrateResult.device_id;\n logger.log(\"Preparing device keys\", deviceId);\n const deviceKeys: DeviceKeys = {\n algorithms: this.crypto.supportedAlgorithms,\n device_id: deviceId,\n user_id: this.crypto.userId,\n keys: {\n [`ed25519:${deviceId}`]: e2eKeys.ed25519,\n [`curve25519:${deviceId}`]: e2eKeys.curve25519,\n },\n };\n const deviceSignature = account.sign(anotherjson.stringify(deviceKeys));\n deviceKeys.signatures = {\n [this.crypto.userId]: {\n [`ed25519:${deviceId}`]: deviceSignature,\n },\n };\n if (this.crypto.crossSigningInfo.getId(\"self_signing\")) {\n await this.crypto.crossSigningInfo.signObject(deviceKeys, \"self_signing\");\n }\n\n logger.log(\"Preparing one-time keys\");\n const oneTimeKeys = {};\n for (const [keyId, key] of Object.entries(otks.curve25519)) {\n const k: OneTimeKey = { key };\n const signature = account.sign(anotherjson.stringify(k));\n k.signatures = {\n [this.crypto.userId]: {\n [`ed25519:${deviceId}`]: signature,\n },\n };\n oneTimeKeys[`signed_curve25519:${keyId}`] = k;\n }\n\n logger.log(\"Preparing fallback keys\");\n const fallbackKeys = {};\n for (const [keyId, key] of Object.entries(fallbacks.curve25519)) {\n const k: OneTimeKey = { key, fallback: true };\n const signature = account.sign(anotherjson.stringify(k));\n k.signatures = {\n [this.crypto.userId]: {\n [`ed25519:${deviceId}`]: signature,\n },\n };\n fallbackKeys[`signed_curve25519:${keyId}`] = k;\n }\n\n logger.log(\"Uploading keys to server\");\n await this.crypto.baseApis.http.authedRequest(\n undefined,\n \"POST\",\n \"/keys/upload/\" + encodeURI(deviceId),\n undefined,\n {\n \"device_keys\": deviceKeys,\n \"one_time_keys\": oneTimeKeys,\n \"org.matrix.msc2732.fallback_keys\": fallbackKeys,\n },\n );\n logger.log(\"Done dehydrating\");\n\n // dehydrate again in a week\n this.timeoutId = global.setTimeout(\n this.dehydrateDevice.bind(this), oneweek,\n );\n\n return deviceId;\n } finally {\n this.inProgress = false;\n }\n }\n\n public stop() {\n if (this.timeoutId) {\n global.clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n }\n}\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ISignatures } from \"../@types/signed\";\n\n/**\n * @module crypto/deviceinfo\n */\n\nexport interface IDevice {\n keys: Record<string, string>;\n algorithms: string[];\n verified: DeviceVerification;\n known: boolean;\n unsigned?: Record<string, any>;\n signatures?: ISignatures;\n}\n\nenum DeviceVerification {\n Blocked = -1,\n Unverified = 0,\n Verified = 1,\n}\n\n/**\n * Information about a user's device\n *\n * @constructor\n * @alias module:crypto/deviceinfo\n *\n * @property {string} deviceId the ID of this device\n *\n * @property {string[]} algorithms list of algorithms supported by this device\n *\n * @property {Object.<string,string>} keys a map from\n * &lt;key type&gt;:&lt;id&gt; -> &lt;base64-encoded key&gt;>\n *\n * @property {module:crypto/deviceinfo.DeviceVerification} verified\n * whether the device has been verified/blocked by the user\n *\n * @property {boolean} known\n * whether the user knows of this device's existence (useful when warning\n * the user that a user has added new devices)\n *\n * @property {Object} unsigned additional data from the homeserver\n *\n * @param {string} deviceId id of the device\n */\nexport class DeviceInfo {\n /**\n * rehydrate a DeviceInfo from the session store\n *\n * @param {object} obj raw object from session store\n * @param {string} deviceId id of the device\n *\n * @return {module:crypto~DeviceInfo} new DeviceInfo\n */\n public static fromStorage(obj: IDevice, deviceId: string): DeviceInfo {\n const res = new DeviceInfo(deviceId);\n for (const prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n res[prop] = obj[prop];\n }\n }\n return res;\n }\n\n /**\n * @enum\n */\n public static DeviceVerification = {\n VERIFIED: DeviceVerification.Verified,\n UNVERIFIED: DeviceVerification.Unverified,\n BLOCKED: DeviceVerification.Blocked,\n };\n\n public algorithms: string[];\n public keys: Record<string, string> = {};\n public verified = DeviceVerification.Unverified;\n public known = false;\n public unsigned: Record<string, any> = {};\n public signatures: ISignatures = {};\n\n constructor(public readonly deviceId: string) {}\n\n /**\n * Prepare a DeviceInfo for JSON serialisation in the session store\n *\n * @return {object} deviceinfo with non-serialised members removed\n */\n public toStorage(): IDevice {\n return {\n algorithms: this.algorithms,\n keys: this.keys,\n verified: this.verified,\n known: this.known,\n unsigned: this.unsigned,\n signatures: this.signatures,\n };\n }\n\n /**\n * Get the fingerprint for this device (ie, the Ed25519 key)\n *\n * @return {string} base64-encoded fingerprint of this device\n */\n public getFingerprint(): string {\n return this.keys[\"ed25519:\" + this.deviceId];\n }\n\n /**\n * Get the identity key for this device (ie, the Curve25519 key)\n *\n * @return {string} base64-encoded identity key of this device\n */\n public getIdentityKey(): string {\n return this.keys[\"curve25519:\" + this.deviceId];\n }\n\n /**\n * Get the configured display name for this device, if any\n *\n * @return {string?} displayname\n */\n public getDisplayName(): string | null {\n return this.unsigned.device_display_name || null;\n }\n\n /**\n * Returns true if this device is blocked\n *\n * @return {Boolean} true if blocked\n */\n public isBlocked(): boolean {\n return this.verified == DeviceVerification.Blocked;\n }\n\n /**\n * Returns true if this device is verified\n *\n * @return {Boolean} true if verified\n */\n public isVerified(): boolean {\n return this.verified == DeviceVerification.Verified;\n }\n\n /**\n * Returns true if this device is unverified\n *\n * @return {Boolean} true if unverified\n */\n public isUnverified(): boolean {\n return this.verified == DeviceVerification.Unverified;\n }\n\n /**\n * Returns true if the user knows about this device's existence\n *\n * @return {Boolean} true if known\n */\n public isKnown(): boolean {\n return this.known === true;\n }\n}\n",
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2018-2019 New Vector Ltd\nCopyright 2019-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module crypto\n */\n\nimport anotherjson from \"another-json\";\nimport { EventEmitter } from 'events';\n\nimport { ReEmitter } from '../ReEmitter';\nimport { logger } from '../logger';\nimport { OlmDevice } from \"./OlmDevice\";\nimport * as olmlib from \"./olmlib\";\nimport { DeviceInfoMap, DeviceList } from \"./DeviceList\";\nimport { DeviceInfo, IDevice } from \"./deviceinfo\";\nimport * as algorithms from \"./algorithms\";\nimport { createCryptoStoreCacheCallbacks, CrossSigningInfo, DeviceTrustLevel, UserTrustLevel } from './CrossSigning';\nimport { EncryptionSetupBuilder } from \"./EncryptionSetup\";\nimport {\n SECRET_STORAGE_ALGORITHM_V1_AES,\n SecretStorage,\n SecretStorageKeyTuple,\n ISecretRequest,\n SecretStorageKeyObject,\n} from './SecretStorage';\nimport { IAddSecretStorageKeyOpts, ISecretStorageKeyInfo } from \"./api\";\nimport { OutgoingRoomKeyRequestManager } from './OutgoingRoomKeyRequestManager';\nimport { IndexedDBCryptoStore } from './store/indexeddb-crypto-store';\nimport { ReciprocateQRCode, SCAN_QR_CODE_METHOD, SHOW_QR_CODE_METHOD } from './verification/QRCode';\nimport { SAS } from './verification/SAS';\nimport { keyFromPassphrase } from './key_passphrase';\nimport { decodeRecoveryKey, encodeRecoveryKey } from './recoverykey';\nimport { VerificationRequest } from \"./verification/request/VerificationRequest\";\nimport { InRoomChannel, InRoomRequests } from \"./verification/request/InRoomChannel\";\nimport { ToDeviceChannel, ToDeviceRequests } from \"./verification/request/ToDeviceChannel\";\nimport { IllegalMethod } from \"./verification/IllegalMethod\";\nimport { KeySignatureUploadError } from \"../errors\";\nimport { decryptAES, encryptAES, calculateKeyCheck } from './aes';\nimport { DehydrationManager } from './dehydration';\nimport { BackupManager } from \"./backup\";\nimport { IStore } from \"../store\";\nimport { Room } from \"../models/room\";\nimport { RoomMember } from \"../models/room-member\";\nimport { MatrixEvent } from \"../models/event\";\nimport { MatrixClient, IKeysUploadResponse, SessionStore, CryptoStore, ISignedKey } from \"../client\";\nimport type { EncryptionAlgorithm, DecryptionAlgorithm } from \"./algorithms/base\";\nimport type { RoomList } from \"./RoomList\";\nimport { IRecoveryKey, IEncryptedEventInfo } from \"./api\";\nimport { IKeyBackupInfo } from \"./keybackup\";\nimport { ISyncStateData } from \"../sync\";\n\nconst DeviceVerification = DeviceInfo.DeviceVerification;\n\nconst defaultVerificationMethods = {\n [ReciprocateQRCode.NAME]: ReciprocateQRCode,\n [SAS.NAME]: SAS,\n\n // These two can't be used for actual verification, but we do\n // need to be able to define them here for the verification flows\n // to start.\n [SHOW_QR_CODE_METHOD]: IllegalMethod,\n [SCAN_QR_CODE_METHOD]: IllegalMethod,\n};\n\n/**\n * verification method names\n */\nexport const verificationMethods = {\n RECIPROCATE_QR_CODE: ReciprocateQRCode.NAME,\n SAS: SAS.NAME,\n};\n\nexport function isCryptoAvailable(): boolean {\n return Boolean(global.Olm);\n}\n\nconst MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000;\n\ninterface IInitOpts {\n exportedOlmDevice?: any; // TODO types\n pickleKey?: string;\n}\n\nexport interface IBootstrapCrossSigningOpts {\n setupNewCrossSigning?: boolean;\n authUploadDeviceSigningKeys?(makeRequest: (authData: any) => {}): Promise<void>;\n}\n\ninterface IBootstrapSecretStorageOpts {\n keyBackupInfo?: any; // TODO types\n setupNewKeyBackup?: boolean;\n setupNewSecretStorage?: boolean;\n createSecretStorageKey?(): Promise<{\n keyInfo?: any; // TODO types\n privateKey?: Uint8Array;\n }>;\n getKeyBackupPassphrase?(): Promise<Uint8Array | null>;\n}\n\n/* eslint-disable camelcase */\ninterface IRoomKey {\n room_id: string;\n algorithm: string;\n}\n\nexport interface IRoomKeyRequestBody extends IRoomKey {\n session_id: string;\n sender_key: string;\n}\n\nexport interface IMegolmSessionData {\n sender_key: string;\n forwarding_curve25519_key_chain: string[];\n sender_claimed_keys: Record<string, string>;\n room_id: string;\n session_id: string;\n session_key: string;\n algorithm: string;\n untrusted?: boolean;\n}\n/* eslint-enable camelcase */\n\ninterface IDeviceVerificationUpgrade {\n devices: DeviceInfo[];\n crossSigningInfo: CrossSigningInfo;\n}\n\n/**\n * @typedef {Object} module:crypto~OlmSessionResult\n * @property {module:crypto/deviceinfo} device device info\n * @property {string?} sessionId base64 olm session id; null if no session\n * could be established\n */\n\ninterface IUserOlmSession {\n deviceIdKey: string;\n sessions: {\n sessionId: string;\n hasReceivedMessage: boolean;\n }[];\n}\n\ninterface ISyncDeviceLists {\n changed: string[];\n left: string[];\n}\n\nexport interface IRoomKeyRequestRecipient {\n userId: string;\n deviceId: string;\n}\n\ninterface ISignableObject {\n signatures?: object;\n unsigned?: object;\n}\n\nexport interface IEventDecryptionResult {\n clearEvent: object;\n senderCurve25519Key?: string;\n claimedEd25519Key?: string;\n forwardingCurve25519KeyChain?: string[];\n untrusted?: boolean;\n}\n\nexport class Crypto extends EventEmitter {\n /**\n * @return {string} The version of Olm.\n */\n static getOlmVersion(): string {\n return OlmDevice.getOlmVersion();\n }\n\n public readonly backupManager: BackupManager;\n public readonly crossSigningInfo: CrossSigningInfo;\n public readonly olmDevice: OlmDevice;\n public readonly deviceList: DeviceList;\n public readonly dehydrationManager: DehydrationManager;\n public readonly secretStorage: SecretStorage;\n\n private readonly reEmitter: ReEmitter;\n private readonly verificationMethods: any; // TODO types\n private readonly supportedAlgorithms: string[];\n private readonly outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager;\n private readonly toDeviceVerificationRequests: ToDeviceRequests;\n public readonly inRoomVerificationRequests: InRoomRequests;\n\n private trustCrossSignedDevices = true;\n // the last time we did a check for the number of one-time-keys on the server.\n private lastOneTimeKeyCheck: number = null;\n private oneTimeKeyCheckInProgress = false;\n\n // EncryptionAlgorithm instance for each room\n private roomEncryptors: Record<string, EncryptionAlgorithm> = {};\n // map from algorithm to DecryptionAlgorithm instance, for each room\n private roomDecryptors: Record<string, Record<string, DecryptionAlgorithm>> = {};\n\n private deviceKeys: Record<string, string> = {}; // type: key\n\n private globalBlacklistUnverifiedDevices = false;\n private globalErrorOnUnknownDevices = true;\n\n // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations\n // we received in the current sync.\n private receivedRoomKeyRequests: IncomingRoomKeyRequest[] = [];\n private receivedRoomKeyRequestCancellations: IncomingRoomKeyRequestCancellation[] = [];\n // true if we are currently processing received room key requests\n private processingRoomKeyRequests = false;\n // controls whether device tracking is delayed\n // until calling encryptEvent or trackRoomDevices,\n // or done immediately upon enabling room encryption.\n private lazyLoadMembers = false;\n // in case lazyLoadMembers is true,\n // track if an initial tracking of all the room members\n // has happened for a given room. This is delayed\n // to avoid loading room members as long as possible.\n private roomDeviceTrackingState: Record<string, Promise<void>> = {}; // roomId: Promise<void\n\n // The timestamp of the last time we forced establishment\n // of a new session for each device, in milliseconds.\n // {\n // userId: {\n // deviceId: 1234567890000,\n // },\n // }\n private lastNewSessionForced: Record<string, Record<string, number>> = {};\n\n // This flag will be unset whilst the client processes a sync response\n // so that we don't start requesting keys until we've actually finished\n // processing the response.\n private sendKeyRequestsImmediately = false;\n\n private oneTimeKeyCount: number;\n private needsNewFallback: boolean;\n\n /**\n * Cryptography bits\n *\n * This module is internal to the js-sdk; the public API is via MatrixClient.\n *\n * @constructor\n * @alias module:crypto\n *\n * @internal\n *\n * @param {MatrixClient} baseApis base matrix api interface\n *\n * @param {module:store/session/webstorage~WebStorageSessionStore} sessionStore\n * Store to be used for end-to-end crypto session data\n *\n * @param {string} userId The user ID for the local user\n *\n * @param {string} deviceId The identifier for this device.\n *\n * @param {Object} clientStore the MatrixClient data store.\n *\n * @param {module:crypto/store/base~CryptoStore} cryptoStore\n * storage for the crypto layer.\n *\n * @param {RoomList} roomList An initialised RoomList object\n *\n * @param {Array} verificationMethods Array of verification methods to use.\n * Each element can either be a string from MatrixClient.verificationMethods\n * or a class that implements a verification method.\n */\n constructor(\n public readonly baseApis: MatrixClient,\n public readonly sessionStore: SessionStore,\n private readonly userId: string,\n private readonly deviceId: string,\n private readonly clientStore: IStore,\n public readonly cryptoStore: CryptoStore,\n private readonly roomList: RoomList,\n verificationMethods: any[], // TODO types\n ) {\n super();\n this.reEmitter = new ReEmitter(this);\n\n if (verificationMethods) {\n this.verificationMethods = new Map();\n for (const method of verificationMethods) {\n if (typeof method === \"string\") {\n if (defaultVerificationMethods[method]) {\n this.verificationMethods.set(\n method,\n defaultVerificationMethods[method],\n );\n }\n } else if (method.NAME) {\n this.verificationMethods.set(\n method.NAME,\n method,\n );\n } else {\n logger.warn(`Excluding unknown verification method ${method}`);\n }\n }\n } else {\n this.verificationMethods = defaultVerificationMethods;\n }\n\n this.backupManager = new BackupManager(baseApis, async () => {\n // try to get key from cache\n const cachedKey = await this.getSessionBackupPrivateKey();\n if (cachedKey) {\n return cachedKey;\n }\n\n // try to get key from secret storage\n const storedKey = await this.getSecret(\"m.megolm_backup.v1\");\n\n if (storedKey) {\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const [keyId] = await this.getSecretStorageKey();\n await this.storeSecret(\"m.megolm_backup.v1\", fixedKey, [keyId]);\n }\n\n return olmlib.decodeBase64(fixedKey || storedKey);\n }\n\n // try to get key from app\n if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) {\n return await this.baseApis.cryptoCallbacks.getBackupKey();\n }\n\n throw new Error(\"Unable to get private key\");\n });\n\n this.olmDevice = new OlmDevice(cryptoStore);\n this.deviceList = new DeviceList(baseApis, cryptoStore, this.olmDevice);\n\n // XXX: This isn't removed at any point, but then none of the event listeners\n // this class sets seem to be removed at any point... :/\n this.deviceList.on('userCrossSigningUpdated', this.onDeviceListUserCrossSigningUpdated);\n this.reEmitter.reEmit(this.deviceList, [\"crypto.devicesUpdated\", \"crypto.willUpdateDevices\"]);\n\n this.supportedAlgorithms = Object.keys(algorithms.DECRYPTION_CLASSES);\n\n this.outgoingRoomKeyRequestManager = new OutgoingRoomKeyRequestManager(\n baseApis, this.deviceId, this.cryptoStore,\n );\n\n this.toDeviceVerificationRequests = new ToDeviceRequests();\n this.inRoomVerificationRequests = new InRoomRequests();\n\n const cryptoCallbacks = this.baseApis.cryptoCallbacks || {};\n const cacheCallbacks = createCryptoStoreCacheCallbacks(cryptoStore, this.olmDevice);\n\n this.crossSigningInfo = new CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks);\n // Yes, we pass the client twice here: see SecretStorage\n this.secretStorage = new SecretStorage(baseApis, cryptoCallbacks, baseApis);\n this.dehydrationManager = new DehydrationManager(this);\n\n // Assuming no app-supplied callback, default to getting from SSSS.\n if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) {\n cryptoCallbacks.getCrossSigningKey = async (type) => {\n return CrossSigningInfo.getFromSecretStorage(type, this.secretStorage);\n };\n }\n }\n\n /**\n * Initialise the crypto module so that it is ready for use\n *\n * Returns a promise which resolves once the crypto module is ready for use.\n *\n * @param {Object} opts keyword arguments.\n * @param {string} opts.exportedOlmDevice (Optional) data from exported device\n * that must be re-created.\n */\n public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise<void> {\n logger.log(\"Crypto: initialising Olm...\");\n await global.Olm.init();\n logger.log(exportedOlmDevice\n ? \"Crypto: initialising Olm device from exported device...\"\n : \"Crypto: initialising Olm device...\",\n );\n await this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey });\n logger.log(\"Crypto: loading device list...\");\n await this.deviceList.load();\n\n // build our device keys: these will later be uploaded\n this.deviceKeys[\"ed25519:\" + this.deviceId] = this.olmDevice.deviceEd25519Key;\n this.deviceKeys[\"curve25519:\" + this.deviceId] = this.olmDevice.deviceCurve25519Key;\n\n logger.log(\"Crypto: fetching own devices...\");\n let myDevices = this.deviceList.getRawStoredDevicesForUser(this.userId);\n\n if (!myDevices) {\n myDevices = {};\n }\n\n if (!myDevices[this.deviceId]) {\n // add our own deviceinfo to the cryptoStore\n logger.log(\"Crypto: adding this device to the store...\");\n const deviceInfo = {\n keys: this.deviceKeys,\n algorithms: this.supportedAlgorithms,\n verified: DeviceVerification.VERIFIED,\n known: true,\n };\n\n myDevices[this.deviceId] = deviceInfo;\n this.deviceList.storeDevicesForUser(this.userId, myDevices);\n this.deviceList.saveIfDirty();\n }\n\n await this.cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.cryptoStore.getCrossSigningKeys(txn, (keys) => {\n // can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys\n if (keys && Object.keys(keys).length !== 0) {\n logger.log(\"Loaded cross-signing public keys from crypto store\");\n this.crossSigningInfo.setKeys(keys);\n }\n });\n },\n );\n // make sure we are keeping track of our own devices\n // (this is important for key backups & things)\n this.deviceList.startTrackingDeviceList(this.userId);\n\n logger.log(\"Crypto: checking for key backup...\");\n this.backupManager.checkAndStart();\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @return {boolean} True if trusting cross-signed devices\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n return this.trustCrossSignedDevices;\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n\n * This may be set before initCrypto() is called to ensure no races occur.\n *\n * @param {boolean} val True to trust cross-signed devices\n */\n public setCryptoTrustCrossSignedDevices(val: boolean): void {\n this.trustCrossSignedDevices = val;\n\n for (const userId of this.deviceList.getKnownUserIds()) {\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n for (const deviceId of Object.keys(devices)) {\n const deviceTrust = this.checkDeviceTrust(userId, deviceId);\n // If the device is locally verified then isVerified() is always true,\n // so this will only have caused the value to change if the device is\n // cross-signing verified but not locally verified\n if (\n !deviceTrust.isLocallyVerified() &&\n deviceTrust.isCrossSigningVerified()\n ) {\n const deviceObj = this.deviceList.getStoredDevice(userId, deviceId);\n this.emit(\"deviceVerificationChanged\", userId, deviceId, deviceObj);\n }\n }\n }\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * @param {string} password Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns {Promise<Object>} Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n public async createRecoveryKeyFromPassphrase(password: string): Promise<IRecoveryKey> {\n const decryption = new global.Olm.PkDecryption();\n try {\n const keyInfo: Partial<IRecoveryKey[\"keyInfo\"]> = {};\n if (password) {\n const derivation = await keyFromPassphrase(password);\n keyInfo.passphrase = {\n algorithm: \"m.pbkdf2\",\n iterations: derivation.iterations,\n salt: derivation.salt,\n };\n keyInfo.pubkey = decryption.init_with_private_key(derivation.key);\n } else {\n keyInfo.pubkey = decryption.generate_key();\n }\n const privateKey = decryption.get_private_key();\n const encodedPrivateKey = encodeRecoveryKey(privateKey);\n return {\n keyInfo: keyInfo as IRecoveryKey[\"keyInfo\"],\n encodedPrivateKey,\n privateKey,\n };\n } finally {\n if (decryption) decryption.free();\n }\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @return {boolean} True if cross-signing is ready to be used on this device\n */\n public async isCrossSigningReady(): Promise<boolean> {\n const publicKeysOnDevice = this.crossSigningInfo.getId();\n const privateKeysExistSomewhere = (\n await this.crossSigningInfo.isStoredInKeyCache() ||\n await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage)\n );\n\n return !!(publicKeysOnDevice && privateKeysExistSomewhere);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @return {boolean} True if secret storage is ready to be used on this device\n */\n public async isSecretStorageReady(): Promise<boolean> {\n const secretStorageKeyInAccount = await this.secretStorage.hasKey();\n const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(\n this.secretStorage,\n );\n const sessionBackupInStorage = (\n !this.backupManager.getKeyBackupEnabled() ||\n await this.baseApis.isKeyBackupKeyStored()\n );\n\n return !!(\n secretStorageKeyInAccount &&\n privateKeysInStorage &&\n sessionBackupInStorage\n );\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been setup)\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param {function} opts.authUploadDeviceSigningKeys Function\n * called to await an interactive auth flow when uploading device signing keys.\n * @param {boolean} [opts.setupNewCrossSigning] Optional. Reset even if keys\n * already exist.\n * Args:\n * {function} A function that makes the request requiring auth. Receives the\n * auth data as an object. Can be called multiple times, first with an empty\n * authDict, to obtain the flows.\n */\n public async bootstrapCrossSigning({\n authUploadDeviceSigningKeys,\n setupNewCrossSigning,\n }: IBootstrapCrossSigningOpts = {}): Promise<void> {\n logger.log(\"Bootstrapping cross-signing\");\n\n const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;\n const builder = new EncryptionSetupBuilder(\n this.baseApis.store.accountData,\n delegateCryptoCallbacks,\n );\n const crossSigningInfo = new CrossSigningInfo(\n this.userId,\n builder.crossSigningCallbacks,\n builder.crossSigningCallbacks,\n );\n\n // Reset the cross-signing keys\n const resetCrossSigning = async () => {\n crossSigningInfo.resetKeys();\n // Sign master key with device key\n await this.signObject(crossSigningInfo.keys.master);\n\n // Store auth flow helper function, as we need to call it when uploading\n // to ensure we handle auth errors properly.\n builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys);\n\n // Cross-sign own device\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId);\n const deviceSignature = await crossSigningInfo.signDevice(this.userId, device) as ISignedKey;\n builder.addKeySignature(this.userId, this.deviceId, deviceSignature);\n\n // Sign message key backup with cross-signing master key\n if (this.backupManager.backupInfo) {\n await crossSigningInfo.signObject(\n this.backupManager.backupInfo.auth_data, \"master\",\n );\n builder.addSessionBackup(this.backupManager.backupInfo);\n }\n };\n\n const publicKeysOnDevice = this.crossSigningInfo.getId();\n const privateKeysInCache = await this.crossSigningInfo.isStoredInKeyCache();\n const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(\n this.secretStorage,\n );\n const privateKeysExistSomewhere = (\n privateKeysInCache ||\n privateKeysInStorage\n );\n\n // Log all relevant state for easier parsing of debug logs.\n logger.log({\n setupNewCrossSigning,\n publicKeysOnDevice,\n privateKeysInCache,\n privateKeysInStorage,\n privateKeysExistSomewhere,\n });\n\n if (!privateKeysExistSomewhere || setupNewCrossSigning) {\n logger.log(\n \"Cross-signing private keys not found locally or in secret storage, \" +\n \"creating new keys\",\n );\n // If a user has multiple devices, it important to only call bootstrap\n // as part of some UI flow (and not silently during startup), as they\n // may have setup cross-signing on a platform which has not saved keys\n // to secret storage, and this would reset them. In such a case, you\n // should prompt the user to verify any existing devices first (and\n // request private keys from those devices) before calling bootstrap.\n await resetCrossSigning();\n } else if (publicKeysOnDevice && privateKeysInCache) {\n logger.log(\n \"Cross-signing public keys trusted and private keys found locally\",\n );\n } else if (privateKeysInStorage) {\n logger.log(\n \"Cross-signing private keys not found locally, but they are available \" +\n \"in secret storage, reading storage and caching locally\",\n );\n await this.checkOwnCrossSigningTrust({\n allowPrivateKeyRequests: true,\n });\n }\n\n // Assuming no app-supplied callback, default to storing new private keys in\n // secret storage if it exists. If it does not, it is assumed this will be\n // done as part of setting up secret storage later.\n const crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys;\n if (\n crossSigningPrivateKeys.size &&\n !this.baseApis.cryptoCallbacks.saveCrossSigningKeys\n ) {\n const secretStorage = new SecretStorage(\n builder.accountDataClientAdapter,\n builder.ssssCryptoCallbacks);\n if (await secretStorage.hasKey()) {\n logger.log(\"Storing new cross-signing private keys in secret storage\");\n // This is writing to in-memory account data in\n // builder.accountDataClientAdapter so won't fail\n await CrossSigningInfo.storeInSecretStorage(\n crossSigningPrivateKeys,\n secretStorage,\n );\n }\n }\n\n const operation = builder.buildOperation();\n await operation.apply(this);\n // This persists private keys and public keys as trusted,\n // only do this if apply succeeded for now as retry isn't in place yet\n await builder.persist(this);\n\n logger.log(\"Cross-signing ready\");\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param {function} [opts.createSecretStorageKey] Optional. Function\n * called to await a secret storage key creation flow.\n * Returns:\n * {Promise<Object>} Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n * @param {object} [opts.keyBackupInfo] The current key backup object. If passed,\n * the passphrase and recovery key from this backup will be used.\n * @param {boolean} [opts.setupNewKeyBackup] If true, a new key backup version will be\n * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo\n * is supplied.\n * @param {boolean} [opts.setupNewSecretStorage] Optional. Reset even if keys already exist.\n * @param {func} [opts.getKeyBackupPassphrase] Optional. Function called to get the user's\n * current key backup passphrase. Should return a promise that resolves with a Buffer\n * containing the key, or rejects if the key cannot be obtained.\n * Returns:\n * {Promise} A promise which resolves to key creation data for\n * SecretStorage#addKey: an object with `passphrase` etc fields.\n */\n // TODO this does not resolve with what it says it does\n public async bootstrapSecretStorage({\n createSecretStorageKey = async () => ({ }),\n keyBackupInfo,\n setupNewKeyBackup,\n setupNewSecretStorage,\n getKeyBackupPassphrase,\n }: IBootstrapSecretStorageOpts = {}) {\n logger.log(\"Bootstrapping Secure Secret Storage\");\n const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;\n const builder = new EncryptionSetupBuilder(\n this.baseApis.store.accountData,\n delegateCryptoCallbacks,\n );\n const secretStorage = new SecretStorage(\n builder.accountDataClientAdapter,\n builder.ssssCryptoCallbacks,\n );\n\n // the ID of the new SSSS key, if we create one\n let newKeyId = null;\n\n // create a new SSSS key and set it as default\n const createSSSS = async (opts, privateKey: Uint8Array) => {\n opts = opts || {};\n if (privateKey) {\n opts.key = privateKey;\n }\n\n const { keyId, keyInfo } = await secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, opts);\n\n if (privateKey) {\n // make the private key available to encrypt 4S secrets\n builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);\n }\n\n await secretStorage.setDefaultKeyId(keyId);\n return keyId;\n };\n\n const ensureCanCheckPassphrase = async (keyId, keyInfo) => {\n if (!keyInfo.mac) {\n const key = await this.baseApis.cryptoCallbacks.getSecretStorageKey(\n { keys: { [keyId]: keyInfo } }, \"\",\n );\n if (key) {\n const privateKey = key[1];\n builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);\n const { iv, mac } = await calculateKeyCheck(privateKey);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n\n await builder.setAccountData(\n `m.secret_storage.key.${keyId}`, keyInfo,\n );\n }\n }\n };\n\n const signKeyBackupWithCrossSigning = async (keyBackupAuthData) => {\n if (\n this.crossSigningInfo.getId() &&\n await this.crossSigningInfo.isStoredInKeyCache(\"master\")\n ) {\n try {\n logger.log(\"Adding cross-signing signature to key backup\");\n await this.crossSigningInfo.signObject(keyBackupAuthData, \"master\");\n } catch (e) {\n // This step is not critical (just helpful), so we catch here\n // and continue if it fails.\n logger.error(\"Signing key backup with cross-signing keys failed\", e);\n }\n } else {\n logger.warn(\n \"Cross-signing keys not available, skipping signature on key backup\",\n );\n }\n };\n\n const oldSSSSKey = await this.getSecretStorageKey();\n const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null];\n const storageExists = (\n !setupNewSecretStorage &&\n oldKeyInfo &&\n oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES\n );\n\n // Log all relevant state for easier parsing of debug logs.\n logger.log({\n keyBackupInfo,\n setupNewKeyBackup,\n setupNewSecretStorage,\n storageExists,\n oldKeyInfo,\n });\n\n if (!storageExists && !keyBackupInfo) {\n // either we don't have anything, or we've been asked to restart\n // from scratch\n logger.log(\n \"Secret storage does not exist, creating new storage key\",\n );\n\n // if we already have a usable default SSSS key and aren't resetting\n // SSSS just use it. otherwise, create a new one\n // Note: we leave the old SSSS key in place: there could be other\n // secrets using it, in theory. We could move them to the new key but a)\n // that would mean we'd need to prompt for the old passphrase, and b)\n // it's not clear that would be the right thing to do anyway.\n const { keyInfo, privateKey } = await createSecretStorageKey();\n newKeyId = await createSSSS(keyInfo, privateKey);\n } else if (!storageExists && keyBackupInfo) {\n // we have an existing backup, but no SSSS\n logger.log(\"Secret storage does not exist, using key backup key\");\n\n // if we have the backup key already cached, use it; otherwise use the\n // callback to prompt for the key\n const backupKey = await this.getSessionBackupPrivateKey() || await getKeyBackupPassphrase();\n\n // create a new SSSS key and use the backup key as the new SSSS key\n const opts: any = {}; // TODO types\n\n if (\n keyBackupInfo.auth_data.private_key_salt &&\n keyBackupInfo.auth_data.private_key_iterations\n ) {\n // FIXME: ???\n opts.passphrase = {\n algorithm: \"m.pbkdf2\",\n iterations: keyBackupInfo.auth_data.private_key_iterations,\n salt: keyBackupInfo.auth_data.private_key_salt,\n bits: 256,\n };\n }\n\n newKeyId = await createSSSS(opts, backupKey);\n\n // store the backup key in secret storage\n await secretStorage.store(\n \"m.megolm_backup.v1\", olmlib.encodeBase64(backupKey), [newKeyId],\n );\n\n // The backup is trusted because the user provided the private key.\n // Sign the backup with the cross-signing key so the key backup can\n // be trusted via cross-signing.\n await signKeyBackupWithCrossSigning(keyBackupInfo.auth_data);\n\n builder.addSessionBackup(keyBackupInfo);\n } else {\n // 4S is already set up\n logger.log(\"Secret storage exists\");\n\n if (oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n // make sure that the default key has the information needed to\n // check the passphrase\n await ensureCanCheckPassphrase(oldKeyId, oldKeyInfo);\n }\n }\n\n // If we have cross-signing private keys cached, store them in secret\n // storage if they are not there already.\n if (\n !this.baseApis.cryptoCallbacks.saveCrossSigningKeys &&\n await this.isCrossSigningReady() &&\n (newKeyId || !await this.crossSigningInfo.isStoredInSecretStorage(secretStorage))\n ) {\n logger.log(\"Copying cross-signing private keys from cache to secret storage\");\n const crossSigningPrivateKeys =\n await this.crossSigningInfo.getCrossSigningKeysFromCache();\n // This is writing to in-memory account data in\n // builder.accountDataClientAdapter so won't fail\n await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);\n }\n\n if (setupNewKeyBackup && !keyBackupInfo) {\n logger.log(\"Creating new message key backup version\");\n const info = await this.baseApis.prepareKeyBackupVersion(\n null /* random key */,\n // don't write to secret storage, as it will write to this.secretStorage.\n // Here, we want to capture all the side-effects of bootstrapping,\n // and want to write to the local secretStorage object\n { secureSecretStorage: false },\n );\n // write the key ourselves to 4S\n const privateKey = decodeRecoveryKey(info.recovery_key);\n await secretStorage.store(\"m.megolm_backup.v1\", olmlib.encodeBase64(privateKey));\n\n // create keyBackupInfo object to add to builder\n const data: IKeyBackupInfo = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign with cross-signing master key\n await signKeyBackupWithCrossSigning(data.auth_data);\n\n // sign with the device fingerprint\n await this.signObject(data.auth_data);\n\n builder.addSessionBackup(data);\n }\n\n // Cache the session backup key\n const sessionBackupKey = await secretStorage.get('m.megolm_backup.v1');\n if (sessionBackupKey) {\n logger.info(\"Got session backup key from secret storage: caching\");\n // fix up the backup key if it's in the wrong format, and replace\n // in secret storage\n const fixedBackupKey = fixBackupKey(sessionBackupKey);\n if (fixedBackupKey) {\n await secretStorage.store(\"m.megolm_backup.v1\",\n fixedBackupKey, [newKeyId || oldKeyId],\n );\n }\n const decodedBackupKey = new Uint8Array(olmlib.decodeBase64(\n fixedBackupKey || sessionBackupKey,\n ));\n await builder.addSessionBackupPrivateKeyToCache(decodedBackupKey);\n } else if (this.backupManager.getKeyBackupEnabled()) {\n // key backup is enabled but we don't have a session backup key in SSSS: see if we have one in\n // the cache or the user can provide one, and if so, write it to SSSS\n const backupKey = await this.getSessionBackupPrivateKey() || await getKeyBackupPassphrase();\n if (!backupKey) {\n // This will require user intervention to recover from since we don't have the key\n // backup key anywhere. The user should probably just set up a new key backup and\n // the key for the new backup will be stored. If we hit this scenario in the wild\n // with any frequency, we should do more than just log an error.\n logger.error(\"Key backup is enabled but couldn't get key backup key!\");\n return;\n }\n logger.info(\"Got session backup key from cache/user that wasn't in SSSS: saving to SSSS\");\n await secretStorage.store(\"m.megolm_backup.v1\", olmlib.encodeBase64(backupKey));\n }\n\n const operation = builder.buildOperation();\n await operation.apply(this);\n // this persists private keys and public keys as trusted,\n // only do this if apply succeeded for now as retry isn't in place yet\n await builder.persist(this);\n\n logger.log(\"Secure Secret Storage ready\");\n }\n\n public addSecretStorageKey(\n algorithm: string,\n opts: IAddSecretStorageKeyOpts,\n keyID: string,\n ): Promise<SecretStorageKeyObject> {\n return this.secretStorage.addKey(algorithm, opts, keyID);\n }\n\n public hasSecretStorageKey(keyID: string): Promise<boolean> {\n return this.secretStorage.hasKey(keyID);\n }\n\n public getSecretStorageKey(keyID?: string): Promise<SecretStorageKeyTuple> {\n return this.secretStorage.getKey(keyID);\n }\n\n public storeSecret(name: string, secret: string, keys?: string[]): Promise<void> {\n return this.secretStorage.store(name, secret, keys);\n }\n\n public getSecret(name: string): Promise<string> {\n return this.secretStorage.get(name);\n }\n\n public isSecretStored(\n name: string,\n checkKey?: boolean,\n ): Promise<Record<string, ISecretStorageKeyInfo>> {\n return this.secretStorage.isStored(name, checkKey);\n }\n\n public requestSecret(name: string, devices: string[]): ISecretRequest {\n if (!devices) {\n devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId));\n }\n return this.secretStorage.request(name, devices);\n }\n\n public getDefaultSecretStorageKeyId(): Promise<string> {\n return this.secretStorage.getDefaultKeyId();\n }\n\n public setDefaultSecretStorageKeyId(k: string): Promise<void> {\n return this.secretStorage.setDefaultKeyId(k);\n }\n\n public checkSecretStorageKey(key: Uint8Array, info: ISecretStorageKeyInfo): Promise<boolean> {\n return this.secretStorage.checkKey(key, info);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * @param {Uint8Array} privateKey The private key\n * @param {string} expectedPublicKey The public key\n * @returns {boolean} true if the key matches, otherwise false\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n let decryption = null;\n try {\n decryption = new global.Olm.PkDecryption();\n const gotPubkey = decryption.init_with_private_key(privateKey);\n // make sure it agrees with the given pubkey\n return gotPubkey === expectedPublicKey;\n } finally {\n if (decryption) decryption.free();\n }\n }\n\n /**\n * Fetches the backup private key, if cached\n * @returns {Promise} the key, if any, or null\n */\n public async getSessionBackupPrivateKey(): Promise<Uint8Array | null> {\n let key = await new Promise<any>((resolve) => { // TODO types\n this.cryptoStore.doTxn(\n 'readonly',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.cryptoStore.getSecretStorePrivateKey(\n txn,\n resolve,\n \"m.megolm_backup.v1\",\n );\n },\n );\n });\n\n // make sure we have a Uint8Array, rather than a string\n if (key && typeof key === \"string\") {\n key = new Uint8Array(olmlib.decodeBase64(fixBackupKey(key) || key));\n await this.storeSessionBackupPrivateKey(key);\n }\n if (key && key.ciphertext) {\n const pickleKey = Buffer.from(this.olmDevice._pickleKey);\n const decrypted = await decryptAES(key, pickleKey, \"m.megolm_backup.v1\");\n key = olmlib.decodeBase64(decrypted);\n }\n return key;\n }\n\n /**\n * Stores the session backup key to the cache\n * @param {Uint8Array} key the private key\n * @returns {Promise} so you can catch failures\n */\n public async storeSessionBackupPrivateKey(key: ArrayLike<number>): Promise<void> {\n if (!(key instanceof Uint8Array)) {\n throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${key}`);\n }\n const pickleKey = Buffer.from(this.olmDevice._pickleKey);\n const encryptedKey = await encryptAES(olmlib.encodeBase64(key), pickleKey, \"m.megolm_backup.v1\");\n return this.cryptoStore.doTxn(\n 'readwrite',\n [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.cryptoStore.storeSecretStorePrivateKey(txn, \"m.megolm_backup.v1\", encryptedKey);\n },\n );\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * @param {Uint8Array} privateKey The private key\n * @param {string} expectedPublicKey The public key\n * @returns {boolean} true if the key matches, otherwise false\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n let signing = null;\n try {\n signing = new global.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(privateKey);\n // make sure it agrees with the given pubkey\n return gotPubkey === expectedPublicKey;\n } finally {\n if (signing) signing.free();\n }\n }\n\n /**\n * Run various follow-up actions after cross-signing keys have changed locally\n * (either by resetting the keys for the account or by getting them from secret\n * storage), such as signing the current device, upgrading device\n * verifications, etc.\n */\n private async afterCrossSigningLocalKeyChange(): Promise<void> {\n logger.info(\"Starting cross-signing key change post-processing\");\n\n // sign the current device with the new key, and upload to the server\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId);\n const signedDevice = await this.crossSigningInfo.signDevice(this.userId, device);\n logger.info(`Starting background key sig upload for ${this.deviceId}`);\n\n const upload = ({ shouldEmit }) => {\n return this.baseApis.uploadKeySignatures({\n [this.userId]: {\n [this.deviceId]: signedDevice,\n },\n }).then((response) => {\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n \"crypto.keySignatureUploadFailure\",\n failures,\n \"afterCrossSigningLocalKeyChange\",\n upload, // continuation\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n logger.info(`Finished background key sig upload for ${this.deviceId}`);\n }).catch(e => {\n logger.error(\n `Error during background key sig upload for ${this.deviceId}`,\n e,\n );\n });\n };\n upload({ shouldEmit: true });\n\n const shouldUpgradeCb = (\n this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications\n );\n if (shouldUpgradeCb) {\n logger.info(\"Starting device verification upgrade\");\n\n // Check all users for signatures if upgrade callback present\n // FIXME: do this in batches\n const users = {};\n for (const [userId, crossSigningInfo]\n of Object.entries(this.deviceList.crossSigningInfo)) {\n const upgradeInfo = await this.checkForDeviceVerificationUpgrade(\n userId, CrossSigningInfo.fromStorage(crossSigningInfo, userId),\n );\n if (upgradeInfo) {\n users[userId] = upgradeInfo;\n }\n }\n\n if (Object.keys(users).length > 0) {\n logger.info(`Found ${Object.keys(users).length} verif users to upgrade`);\n try {\n const usersToUpgrade = await shouldUpgradeCb({ users: users });\n if (usersToUpgrade) {\n for (const userId of usersToUpgrade) {\n if (userId in users) {\n await this.baseApis.setDeviceVerified(\n userId, users[userId].crossSigningInfo.getId(),\n );\n }\n }\n }\n } catch (e) {\n logger.log(\n \"shouldUpgradeDeviceVerifications threw an error: not upgrading\", e,\n );\n }\n }\n\n logger.info(\"Finished device verification upgrade\");\n }\n\n logger.info(\"Finished cross-signing key change post-processing\");\n }\n\n /**\n * Check if a user's cross-signing key is a candidate for upgrading from device\n * verification.\n *\n * @param {string} userId the user whose cross-signing information is to be checked\n * @param {object} crossSigningInfo the cross-signing information to check\n */\n private async checkForDeviceVerificationUpgrade(\n userId: string,\n crossSigningInfo: CrossSigningInfo,\n ): Promise<IDeviceVerificationUpgrade> {\n // only upgrade if this is the first cross-signing key that we've seen for\n // them, and if their cross-signing key isn't already verified\n const trustLevel = this.crossSigningInfo.checkUserTrust(crossSigningInfo);\n if (crossSigningInfo.firstUse && !trustLevel.isVerified()) {\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n const deviceIds = await this.checkForValidDeviceSignature(\n userId, crossSigningInfo.keys.master, devices,\n );\n if (deviceIds.length) {\n return {\n devices: deviceIds.map(\n deviceId => DeviceInfo.fromStorage(devices[deviceId], deviceId),\n ),\n crossSigningInfo,\n };\n }\n }\n }\n\n /**\n * Check if the cross-signing key is signed by a verified device.\n *\n * @param {string} userId the user ID whose key is being checked\n * @param {object} key the key that is being checked\n * @param {object} devices the user's devices. Should be a map from device ID\n * to device info\n */\n private async checkForValidDeviceSignature(\n userId: string,\n key: any, // TODO types\n devices: Record<string, IDevice>,\n ): Promise<string[]> {\n const deviceIds: string[] = [];\n if (devices && key.signatures && key.signatures[userId]) {\n for (const signame of Object.keys(key.signatures[userId])) {\n const [, deviceId] = signame.split(':', 2);\n if (deviceId in devices\n && devices[deviceId].verified === DeviceVerification.VERIFIED) {\n try {\n await olmlib.verifySignature(\n this.olmDevice,\n key,\n userId,\n deviceId,\n devices[deviceId].keys[signame],\n );\n deviceIds.push(deviceId);\n } catch (e) {}\n }\n }\n }\n return deviceIds;\n }\n\n /**\n * Get the user's cross-signing key ID.\n *\n * @param {string} [type=master] The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns {string} the key ID\n */\n public getCrossSigningId(type: string): string {\n return this.crossSigningInfo.getId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * @param {string} userId the user ID to get the cross-signing info for.\n *\n * @returns {CrossSigningInfo} the cross signing information for the user.\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo {\n return this.deviceList.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * @param {string} userId The ID of the user to check.\n *\n * @returns {UserTrustLevel}\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (!userCrossSigning) {\n return new UserTrustLevel(false, false, false);\n }\n return this.crossSigningInfo.checkUserTrust(userCrossSigning);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * @param {string} userId The ID of the user whose devices is to be checked.\n * @param {string} deviceId The ID of the device to check\n *\n * @returns {DeviceTrustLevel}\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n return this.checkDeviceInfoTrust(userId, device);\n }\n\n /**\n * Check whether a given deviceinfo is trusted.\n *\n * @param {string} userId The ID of the user whose devices is to be checked.\n * @param {module:crypto/deviceinfo?} device The device info object to check\n *\n * @returns {DeviceTrustLevel}\n */\n public checkDeviceInfoTrust(userId: string, device: DeviceInfo): DeviceTrustLevel {\n const trustedLocally = !!(device && device.isVerified());\n\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (device && userCrossSigning) {\n // The trustCrossSignedDevices only affects trust of other people's cross-signing\n // signatures\n const trustCrossSig = this.trustCrossSignedDevices || userId === this.userId;\n return this.crossSigningInfo.checkDeviceTrust(\n userCrossSigning, device, trustedLocally, trustCrossSig,\n );\n } else {\n return new DeviceTrustLevel(false, false, trustedLocally, false);\n }\n }\n\n /*\n * Event handler for DeviceList's userNewDevices event\n */\n private onDeviceListUserCrossSigningUpdated = async (userId: string) => {\n if (userId === this.userId) {\n // An update to our own cross-signing key.\n // Get the new key first:\n const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n const seenPubkey = newCrossSigning ? newCrossSigning.getId() : null;\n const currentPubkey = this.crossSigningInfo.getId();\n const changed = currentPubkey !== seenPubkey;\n\n if (currentPubkey && seenPubkey && !changed) {\n // If it's not changed, just make sure everything is up to date\n await this.checkOwnCrossSigningTrust();\n } else {\n // We'll now be in a state where cross-signing on the account is not trusted\n // because our locally stored cross-signing keys will not match the ones\n // on the server for our account. So we clear our own stored cross-signing keys,\n // effectively disabling cross-signing until the user gets verified by the device\n // that reset the keys\n this.storeTrustedSelfKeys(null);\n // emit cross-signing has been disabled\n this.emit(\"crossSigning.keysChanged\", {});\n // as the trust for our own user has changed,\n // also emit an event for this\n this.emit(\"userTrustStatusChanged\",\n this.userId, this.checkUserTrust(userId));\n }\n } else {\n await this.checkDeviceVerifications(userId);\n\n // Update verified before latch using the current state and save the new\n // latch value in the device list store.\n const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigning) {\n crossSigning.updateCrossSigningVerifiedBefore(\n this.checkUserTrust(userId).isCrossSigningVerified(),\n );\n this.deviceList.setRawStoredCrossSigningForUser(\n userId, crossSigning.toStorage(),\n );\n }\n\n this.emit(\"userTrustStatusChanged\", userId, this.checkUserTrust(userId));\n }\n };\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n */\n async checkOwnCrossSigningTrust({\n allowPrivateKeyRequests = false,\n } = {}) {\n const userId = this.userId;\n\n // Before proceeding, ensure our cross-signing public keys have been\n // downloaded via the device list.\n await this.downloadKeys([this.userId]);\n\n // Also check which private keys are locally cached.\n const crossSigningPrivateKeys =\n await this.crossSigningInfo.getCrossSigningKeysFromCache();\n\n // If we see an update to our own master key, check it against the master\n // key we have and, if it matches, mark it as verified\n\n // First, get the new cross-signing info\n const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (!newCrossSigning) {\n logger.error(\n \"Got cross-signing update event for user \" + userId +\n \" but no new cross-signing information found!\",\n );\n return;\n }\n\n const seenPubkey = newCrossSigning.getId();\n const masterChanged = this.crossSigningInfo.getId() !== seenPubkey;\n const masterExistsNotLocallyCached =\n newCrossSigning.getId() && !crossSigningPrivateKeys.has(\"master\");\n if (masterChanged) {\n logger.info(\"Got new master public key\", seenPubkey);\n }\n if (\n allowPrivateKeyRequests &&\n (masterChanged || masterExistsNotLocallyCached)\n ) {\n logger.info(\"Attempting to retrieve cross-signing master private key\");\n let signing = null;\n // It's important for control flow that we leave any errors alone for\n // higher levels to handle so that e.g. cancelling access properly\n // aborts any larger operation as well.\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n 'master', seenPubkey,\n );\n signing = ret[1];\n logger.info(\"Got cross-signing master private key\");\n } finally {\n if (signing) signing.free();\n }\n }\n\n const oldSelfSigningId = this.crossSigningInfo.getId(\"self_signing\");\n const oldUserSigningId = this.crossSigningInfo.getId(\"user_signing\");\n\n // Update the version of our keys in our cross-signing object and the local store\n this.storeTrustedSelfKeys(newCrossSigning.keys);\n\n const selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId(\"self_signing\");\n const userSigningChanged = oldUserSigningId !== newCrossSigning.getId(\"user_signing\");\n\n const selfSigningExistsNotLocallyCached = (\n newCrossSigning.getId(\"self_signing\") &&\n !crossSigningPrivateKeys.has(\"self_signing\")\n );\n const userSigningExistsNotLocallyCached = (\n newCrossSigning.getId(\"user_signing\") &&\n !crossSigningPrivateKeys.has(\"user_signing\")\n );\n\n const keySignatures = {};\n\n if (selfSigningChanged) {\n logger.info(\"Got new self-signing key\", newCrossSigning.getId(\"self_signing\"));\n }\n if (\n allowPrivateKeyRequests &&\n (selfSigningChanged || selfSigningExistsNotLocallyCached)\n ) {\n logger.info(\"Attempting to retrieve cross-signing self-signing private key\");\n let signing = null;\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n \"self_signing\", newCrossSigning.getId(\"self_signing\"),\n );\n signing = ret[1];\n logger.info(\"Got cross-signing self-signing private key\");\n } finally {\n if (signing) signing.free();\n }\n\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId);\n const signedDevice = await this.crossSigningInfo.signDevice(\n this.userId, device,\n );\n keySignatures[this.deviceId] = signedDevice;\n }\n if (userSigningChanged) {\n logger.info(\"Got new user-signing key\", newCrossSigning.getId(\"user_signing\"));\n }\n if (\n allowPrivateKeyRequests &&\n (userSigningChanged || userSigningExistsNotLocallyCached)\n ) {\n logger.info(\"Attempting to retrieve cross-signing user-signing private key\");\n let signing = null;\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n \"user_signing\", newCrossSigning.getId(\"user_signing\"),\n );\n signing = ret[1];\n logger.info(\"Got cross-signing user-signing private key\");\n } finally {\n if (signing) signing.free();\n }\n }\n\n if (masterChanged) {\n const masterKey = this.crossSigningInfo.keys.master;\n await this.signObject(masterKey);\n const deviceSig = masterKey.signatures[this.userId][\"ed25519:\" + this.deviceId];\n // Include only the _new_ device signature in the upload.\n // We may have existing signatures from deleted devices, which will cause\n // the entire upload to fail.\n keySignatures[this.crossSigningInfo.getId()] = Object.assign(\n {},\n masterKey,\n {\n signatures: {\n [this.userId]: {\n [\"ed25519:\" + this.deviceId]: deviceSig,\n },\n },\n },\n );\n }\n\n const keysToUpload = Object.keys(keySignatures);\n if (keysToUpload.length) {\n const upload = ({ shouldEmit }) => {\n logger.info(`Starting background key sig upload for ${keysToUpload}`);\n return this.baseApis.uploadKeySignatures({ [this.userId]: keySignatures })\n .then((response) => {\n const { failures } = response || {};\n logger.info(`Finished background key sig upload for ${keysToUpload}`);\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n \"crypto.keySignatureUploadFailure\",\n failures,\n \"checkOwnCrossSigningTrust\",\n upload,\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n }).catch(e => {\n logger.error(\n `Error during background key sig upload for ${keysToUpload}`,\n e,\n );\n });\n };\n upload({ shouldEmit: true });\n }\n\n this.emit(\"userTrustStatusChanged\", userId, this.checkUserTrust(userId));\n\n if (masterChanged) {\n this.baseApis.emit(\"crossSigning.keysChanged\", {});\n await this.afterCrossSigningLocalKeyChange();\n }\n\n // Now we may be able to trust our key backup\n await this.backupManager.checkKeyBackup();\n // FIXME: if we previously trusted the backup, should we automatically sign\n // the backup with the new key (if not already signed)?\n }\n\n /**\n * Store a set of keys as our own, trusted, cross-signing keys.\n *\n * @param {object} keys The new trusted set of keys\n */\n private async storeTrustedSelfKeys(keys: any): Promise<void> { // TODO types\n if (keys) {\n this.crossSigningInfo.setKeys(keys);\n } else {\n this.crossSigningInfo.clearKeys();\n }\n await this.cryptoStore.doTxn(\n 'readwrite', [IndexedDBCryptoStore.STORE_ACCOUNT],\n (txn) => {\n this.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningInfo.keys);\n },\n );\n }\n\n /**\n * Check if the master key is signed by a verified device, and if so, prompt\n * the application to mark it as verified.\n *\n * @param {string} userId the user ID whose key should be checked\n */\n private async checkDeviceVerifications(userId: string): Promise<void> {\n const shouldUpgradeCb = (\n this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications\n );\n if (!shouldUpgradeCb) {\n // Upgrading skipped when callback is not present.\n return;\n }\n logger.info(`Starting device verification upgrade for ${userId}`);\n if (this.crossSigningInfo.keys.user_signing) {\n const crossSigningInfo = this.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigningInfo) {\n const upgradeInfo = await this.checkForDeviceVerificationUpgrade(\n userId, crossSigningInfo,\n );\n if (upgradeInfo) {\n const usersToUpgrade = await shouldUpgradeCb({\n users: {\n [userId]: upgradeInfo,\n },\n });\n if (usersToUpgrade.includes(userId)) {\n await this.baseApis.setDeviceVerified(\n userId, crossSigningInfo.getId(),\n );\n }\n }\n }\n }\n logger.info(`Finished device verification upgrade for ${userId}`);\n }\n\n public async setTrustedBackupPubKey(trustedPubKey: string): Promise<void> {\n // This should be redundant post cross-signing is a thing, so just\n // plonk it in localStorage for now.\n this.sessionStore.setLocalTrustedBackupPubKey(trustedPubKey);\n await this.backupManager.checkKeyBackup();\n }\n\n /**\n */\n public enableLazyLoading(): void {\n this.lazyLoadMembers = true;\n }\n\n /**\n * Tell the crypto module to register for MatrixClient events which it needs to\n * listen for\n *\n * @param {external:EventEmitter} eventEmitter event source where we can register\n * for event notifications\n */\n public registerEventHandlers(eventEmitter: EventEmitter): void {\n eventEmitter.on(\"RoomMember.membership\", (event: MatrixEvent, member: RoomMember, oldMembership?: string) => {\n try {\n this.onRoomMembership(event, member, oldMembership);\n } catch (e) {\n logger.error(\"Error handling membership change:\", e);\n }\n });\n\n eventEmitter.on(\"toDeviceEvent\", this.onToDeviceEvent);\n eventEmitter.on(\"Room.timeline\", this.onTimelineEvent);\n eventEmitter.on(\"Event.decrypted\", this.onTimelineEvent);\n }\n\n /** Start background processes related to crypto */\n public start(): void {\n this.outgoingRoomKeyRequestManager.start();\n }\n\n /** Stop background processes related to crypto */\n public stop(): void {\n this.outgoingRoomKeyRequestManager.stop();\n this.deviceList.stop();\n this.dehydrationManager.stop();\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @return {string} base64-encoded ed25519 key.\n */\n public getDeviceEd25519Key(): string {\n return this.olmDevice.deviceEd25519Key;\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @return {string} base64-encoded curve25519 key.\n */\n public getDeviceCurve25519Key(): string {\n return this.olmDevice.deviceCurve25519Key;\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param {boolean} value whether to blacklist all unverified devices by default\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean): void {\n this.globalBlacklistUnverifiedDevices = value;\n }\n\n /**\n * @return {boolean} whether to blacklist all unverified devices by default\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n return this.globalBlacklistUnverifiedDevices;\n }\n\n /**\n * Set whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send them message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n *\n * @param {boolean} value whether error on unknown devices\n */\n public setGlobalErrorOnUnknownDevices(value: boolean): void {\n this.globalErrorOnUnknownDevices = value;\n }\n\n /**\n * @return {boolean} whether to error on unknown devices\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n */\n public getGlobalErrorOnUnknownDevices(): boolean {\n return this.globalErrorOnUnknownDevices;\n }\n\n /**\n * Upload the device keys to the homeserver.\n * @return {object} A promise that will resolve when the keys are uploaded.\n */\n public uploadDeviceKeys(): Promise<IKeysUploadResponse> {\n const deviceKeys = {\n algorithms: this.supportedAlgorithms,\n device_id: this.deviceId,\n keys: this.deviceKeys,\n user_id: this.userId,\n };\n\n return this.signObject(deviceKeys).then(() => {\n return this.baseApis.uploadKeysRequest({\n device_keys: deviceKeys,\n });\n });\n }\n\n /**\n * Stores the current one_time_key count which will be handled later (in a call of\n * onSyncCompleted). The count is e.g. coming from a /sync response.\n *\n * @param {Number} currentCount The current count of one_time_keys to be stored\n */\n public updateOneTimeKeyCount(currentCount: number): void {\n if (isFinite(currentCount)) {\n this.oneTimeKeyCount = currentCount;\n } else {\n throw new TypeError(\"Parameter for updateOneTimeKeyCount has to be a number\");\n }\n }\n\n public setNeedsNewFallback(needsNewFallback: boolean) {\n this.needsNewFallback = !!needsNewFallback;\n }\n\n public getNeedsNewFallback(): boolean {\n return this.needsNewFallback;\n }\n\n // check if it's time to upload one-time keys, and do so if so.\n private maybeUploadOneTimeKeys() {\n // frequency with which to check & upload one-time keys\n const uploadPeriod = 1000 * 60; // one minute\n\n // max number of keys to upload at once\n // Creating keys can be an expensive operation so we limit the\n // number we generate in one go to avoid blocking the application\n // for too long.\n const maxKeysPerCycle = 5;\n\n if (this.oneTimeKeyCheckInProgress) {\n return;\n }\n\n const now = Date.now();\n if (this.lastOneTimeKeyCheck !== null &&\n now - this.lastOneTimeKeyCheck < uploadPeriod\n ) {\n // we've done a key upload recently.\n return;\n }\n\n this.lastOneTimeKeyCheck = now;\n\n // We need to keep a pool of one time public keys on the server so that\n // other devices can start conversations with us. But we can only store\n // a finite number of private keys in the olm Account object.\n // To complicate things further then can be a delay between a device\n // claiming a public one time key from the server and it sending us a\n // message. We need to keep the corresponding private key locally until\n // we receive the message.\n // But that message might never arrive leaving us stuck with duff\n // private keys clogging up our local storage.\n // So we need some kind of engineering compromise to balance all of\n // these factors.\n\n // Check how many keys we can store in the Account object.\n const maxOneTimeKeys = this.olmDevice.maxNumberOfOneTimeKeys();\n // Try to keep at most half that number on the server. This leaves the\n // rest of the slots free to hold keys that have been claimed from the\n // server but we haven't received a message for.\n // If we run out of slots when generating new keys then olm will\n // discard the oldest private keys first. This will eventually clean\n // out stale private keys that won't receive a message.\n const keyLimit = Math.floor(maxOneTimeKeys / 2);\n\n const uploadLoop = async (keyCount: number) => {\n while (keyLimit > keyCount || this.getNeedsNewFallback()) {\n // Ask olm to generate new one time keys, then upload them to synapse.\n if (keyLimit > keyCount) {\n logger.info(\"generating oneTimeKeys\");\n const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle);\n await this.olmDevice.generateOneTimeKeys(keysThisLoop);\n }\n\n if (this.getNeedsNewFallback()) {\n logger.info(\"generating fallback key\");\n await this.olmDevice.generateFallbackKey();\n }\n\n logger.info(\"calling uploadOneTimeKeys\");\n const res = await this.uploadOneTimeKeys();\n if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) {\n // if the response contains a more up to date value use this\n // for the next loop\n keyCount = res.one_time_key_counts.signed_curve25519;\n } else {\n throw new Error(\"response for uploading keys does not contain \" +\n \"one_time_key_counts.signed_curve25519\");\n }\n }\n };\n\n this.oneTimeKeyCheckInProgress = true;\n Promise.resolve().then(() => {\n if (this.oneTimeKeyCount !== undefined) {\n // We already have the current one_time_key count from a /sync response.\n // Use this value instead of asking the server for the current key count.\n return Promise.resolve(this.oneTimeKeyCount);\n }\n // ask the server how many keys we have\n return this.baseApis.uploadKeysRequest({}).then((res) => {\n return res.one_time_key_counts.signed_curve25519 || 0;\n });\n }).then((keyCount) => {\n // Start the uploadLoop with the current keyCount. The function checks if\n // we need to upload new keys or not.\n // If there are too many keys on the server then we don't need to\n // create any more keys.\n return uploadLoop(keyCount);\n }).catch((e) => {\n logger.error(\"Error uploading one-time keys\", e.stack || e);\n }).finally(() => {\n // reset oneTimeKeyCount to prevent start uploading based on old data.\n // it will be set again on the next /sync-response\n this.oneTimeKeyCount = undefined;\n this.oneTimeKeyCheckInProgress = false;\n });\n }\n\n // returns a promise which resolves to the response\n private async uploadOneTimeKeys() {\n const promises = [];\n\n const fallbackJson = {};\n if (this.getNeedsNewFallback()) {\n const fallbackKeys = await this.olmDevice.getFallbackKey();\n for (const [keyId, key] of Object.entries(fallbackKeys.curve25519)) {\n const k = { key, fallback: true };\n fallbackJson[\"signed_curve25519:\" + keyId] = k;\n promises.push(this.signObject(k));\n }\n this.setNeedsNewFallback(false);\n }\n\n const oneTimeKeys = await this.olmDevice.getOneTimeKeys();\n const oneTimeJson = {};\n\n for (const keyId in oneTimeKeys.curve25519) {\n if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) {\n const k = {\n key: oneTimeKeys.curve25519[keyId],\n };\n oneTimeJson[\"signed_curve25519:\" + keyId] = k;\n promises.push(this.signObject(k));\n }\n }\n\n await Promise.all(promises);\n\n const res = await this.baseApis.uploadKeysRequest({\n \"one_time_keys\": oneTimeJson,\n \"org.matrix.msc2732.fallback_keys\": fallbackJson,\n });\n\n await this.olmDevice.markKeysAsPublished();\n return res;\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param {Array} userIds The users to fetch.\n * @param {boolean} forceDownload Always download the keys even if cached.\n *\n * @return {Promise} A promise which resolves to a map userId->deviceId->{@link\n * module:crypto/deviceinfo|DeviceInfo}.\n */\n public downloadKeys(userIds: string[], forceDownload?: boolean): Promise<DeviceInfoMap> {\n return this.deviceList.downloadKeys(userIds, forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param {string} userId the user to list keys for.\n *\n * @return {module:crypto/deviceinfo[]|null} list of devices, or null if we haven't\n * managed to get a list of devices for this user yet.\n */\n public getStoredDevicesForUser(userId: string): Array<DeviceInfo> | null {\n return this.deviceList.getStoredDevicesForUser(userId);\n }\n\n /**\n * Get the stored keys for a single device\n *\n * @param {string} userId\n * @param {string} deviceId\n *\n * @return {module:crypto/deviceinfo?} device, or undefined\n * if we don't know about this device\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | undefined {\n return this.deviceList.getStoredDevice(userId, deviceId);\n }\n\n /**\n * Save the device list, if necessary\n *\n * @param {number} delay Time in ms before which the save actually happens.\n * By default, the save is delayed for a short period in order to batch\n * multiple writes, but this behaviour can be disabled by passing 0.\n *\n * @return {Promise<boolean>} true if the data was saved, false if\n * it was not (eg. because no changes were pending). The promise\n * will only resolve once the data is saved, so may take some time\n * to resolve.\n */\n public saveDeviceList(delay: number): Promise<boolean> {\n return this.deviceList.saveIfDirty(delay);\n }\n\n /**\n * Update the blocked/verified state of the given device\n *\n * @param {string} userId owner of the device\n * @param {string} deviceId unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param {?boolean} verified whether to mark the device as verified. Null to\n * leave unchanged.\n *\n * @param {?boolean} blocked whether to mark the device as blocked. Null to\n * leave unchanged.\n *\n * @param {?boolean} known whether to mark that the user has been made aware of\n * the existence of this device. Null to leave unchanged\n *\n * @return {Promise<module:crypto/deviceinfo>} updated DeviceInfo\n */\n public async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified?: boolean,\n blocked?: boolean,\n known?: boolean,\n ): Promise<DeviceInfo | CrossSigningInfo> {\n // get rid of any `undefined`s here so we can just check\n // for null rather than null or undefined\n if (verified === undefined) verified = null;\n if (blocked === undefined) blocked = null;\n if (known === undefined) known = null;\n\n // Check if the 'device' is actually a cross signing key\n // The js-sdk's verification treats cross-signing keys as devices\n // and so uses this method to mark them verified.\n const xsk = this.deviceList.getStoredCrossSigningForUser(userId);\n if (xsk && xsk.getId() === deviceId) {\n if (blocked !== null || known !== null) {\n throw new Error(\"Cannot set blocked or known for a cross-signing key\");\n }\n if (!verified) {\n throw new Error(\"Cannot set a cross-signing key as unverified\");\n }\n\n if (!this.crossSigningInfo.getId() && userId === this.crossSigningInfo.userId) {\n this.storeTrustedSelfKeys(xsk.keys);\n // This will cause our own user trust to change, so emit the event\n this.emit(\n \"userTrustStatusChanged\", this.userId, this.checkUserTrust(userId),\n );\n }\n\n // Now sign the master key with our user signing key (unless it's ourself)\n if (userId !== this.userId) {\n logger.info(\n \"Master key \" + xsk.getId() + \" for \" + userId +\n \" marked verified. Signing...\",\n );\n const device = await this.crossSigningInfo.signUser(xsk);\n if (device) {\n const upload = async ({ shouldEmit }) => {\n logger.info(\"Uploading signature for \" + userId + \"...\");\n const response = await this.baseApis.uploadKeySignatures({\n [userId]: {\n [deviceId]: device,\n },\n });\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n \"crypto.keySignatureUploadFailure\",\n failures,\n \"setDeviceVerification\",\n upload,\n );\n }\n /* Throwing here causes the process to be cancelled and the other\n * user to be notified */\n throw new KeySignatureUploadError(\n \"Key upload failed\",\n { failures },\n );\n }\n };\n await upload({ shouldEmit: true });\n\n // This will emit events when it comes back down the sync\n // (we could do local echo to speed things up)\n }\n return device as any; // TODO types\n } else {\n return xsk;\n }\n }\n\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n if (!devices || !devices[deviceId]) {\n throw new Error(\"Unknown device \" + userId + \":\" + deviceId);\n }\n\n const dev = devices[deviceId];\n let verificationStatus = dev.verified;\n\n if (verified) {\n verificationStatus = DeviceVerification.VERIFIED;\n } else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) {\n verificationStatus = DeviceVerification.UNVERIFIED;\n }\n\n if (blocked) {\n verificationStatus = DeviceVerification.BLOCKED;\n } else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) {\n verificationStatus = DeviceVerification.UNVERIFIED;\n }\n\n let knownStatus = dev.known;\n if (known !== null) {\n knownStatus = known;\n }\n\n if (dev.verified !== verificationStatus || dev.known !== knownStatus) {\n dev.verified = verificationStatus;\n dev.known = knownStatus;\n this.deviceList.storeDevicesForUser(userId, devices);\n this.deviceList.saveIfDirty();\n }\n\n // do cross-signing\n if (verified && userId === this.userId) {\n logger.info(\"Own device \" + deviceId + \" marked verified: signing\");\n\n // Signing only needed if other device not already signed\n let device;\n const deviceTrust = this.checkDeviceTrust(userId, deviceId);\n if (deviceTrust.isCrossSigningVerified()) {\n logger.log(`Own device ${deviceId} already cross-signing verified`);\n } else {\n device = await this.crossSigningInfo.signDevice(\n userId, DeviceInfo.fromStorage(dev, deviceId),\n );\n }\n\n if (device) {\n const upload = async ({ shouldEmit }) => {\n logger.info(\"Uploading signature for \" + deviceId);\n const response = await this.baseApis.uploadKeySignatures({\n [userId]: {\n [deviceId]: device,\n },\n });\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n \"crypto.keySignatureUploadFailure\",\n failures,\n \"setDeviceVerification\",\n upload, // continuation\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n };\n await upload({ shouldEmit: true });\n // XXX: we'll need to wait for the device list to be updated\n }\n }\n\n const deviceObj = DeviceInfo.fromStorage(dev, deviceId);\n this.emit(\"deviceVerificationChanged\", userId, deviceId, deviceObj);\n return deviceObj;\n }\n\n public findVerificationRequestDMInProgress(roomId: string): VerificationRequest {\n return this.inRoomVerificationRequests.findRequestInProgress(roomId);\n }\n\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest {\n return this.toDeviceVerificationRequests.getRequestsInProgress(userId);\n }\n\n public requestVerificationDM(userId: string, roomId: string): VerificationRequest {\n const existingRequest = this.inRoomVerificationRequests.findRequestInProgress(roomId);\n if (existingRequest) {\n return Promise.resolve(existingRequest);\n }\n const channel = new InRoomChannel(this.baseApis, roomId, userId);\n return this.requestVerificationWithChannel(\n userId,\n channel,\n this.inRoomVerificationRequests,\n );\n }\n\n public requestVerification(userId: string, devices: string[]): VerificationRequest {\n if (!devices) {\n devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(userId));\n }\n const existingRequest = this.toDeviceVerificationRequests.findRequestInProgress(userId, devices);\n if (existingRequest) {\n return Promise.resolve(existingRequest);\n }\n const channel = new ToDeviceChannel(this.baseApis, userId, devices, ToDeviceChannel.makeTransactionId());\n return this.requestVerificationWithChannel(\n userId,\n channel,\n this.toDeviceVerificationRequests,\n );\n }\n\n private async requestVerificationWithChannel(\n userId: string,\n channel: any, // TODO types\n requestsMap: any, // TODO types\n ): VerificationRequest {\n let request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n // if transaction id is already known, add request\n if (channel.transactionId) {\n requestsMap.setRequestByChannel(channel, request);\n }\n await request.sendRequest();\n // don't replace the request created by a racing remote echo\n const racingRequest = requestsMap.getRequestByChannel(channel);\n if (racingRequest) {\n request = racingRequest;\n } else {\n logger.log(`Crypto: adding new request to ` +\n `requestsByTxnId with id ${channel.transactionId} ${channel.roomId}`);\n requestsMap.setRequestByChannel(channel, request);\n }\n return request;\n }\n\n public beginKeyVerification(\n method: string,\n userId: string,\n deviceId: string,\n transactionId: string = null,\n ): any { // TODO types\n let request;\n if (transactionId) {\n request = this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(userId, transactionId);\n if (!request) {\n throw new Error(\n `No request found for user ${userId} with ` +\n `transactionId ${transactionId}`);\n }\n } else {\n transactionId = ToDeviceChannel.makeTransactionId();\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);\n request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);\n }\n return request.beginKeyVerification(method, { userId, deviceId });\n }\n\n public async legacyDeviceVerification(\n userId: string,\n deviceId: string,\n method: string,\n ): VerificationRequest {\n const transactionId = ToDeviceChannel.makeTransactionId();\n const channel = new ToDeviceChannel(\n this.baseApis, userId, [deviceId], transactionId, deviceId);\n const request = new VerificationRequest(\n channel, this.verificationMethods, this.baseApis);\n this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(\n userId, transactionId, request);\n const verifier = request.beginKeyVerification(method, { userId, deviceId });\n // either reject by an error from verify() while sending .start\n // or resolve when the request receives the\n // local (fake remote) echo for sending the .start event\n await Promise.race([\n verifier.verify(),\n request.waitFor(r => r.started),\n ]);\n return request;\n }\n\n /**\n * Get information on the active olm sessions with a user\n * <p>\n * Returns a map from device id to an object with keys 'deviceIdKey' (the\n * device's curve25519 identity key) and 'sessions' (an array of objects in the\n * same format as that returned by\n * {@link module:crypto/OlmDevice#getSessionInfoForDevice}).\n * <p>\n * This method is provided for debugging purposes.\n *\n * @param {string} userId id of user to inspect\n *\n * @return {Promise<Object.<string, {deviceIdKey: string, sessions: object[]}>>}\n */\n public async getOlmSessionsForUser(userId: string): Promise<Record<string, IUserOlmSession>> {\n const devices = this.getStoredDevicesForUser(userId) || [];\n const result = {};\n for (let j = 0; j < devices.length; ++j) {\n const device = devices[j];\n const deviceKey = device.getIdentityKey();\n const sessions = await this.olmDevice.getSessionInfoForDevice(deviceKey);\n\n result[device.deviceId] = {\n deviceIdKey: deviceKey,\n sessions: sessions,\n };\n }\n return result;\n }\n\n /**\n * Get the device which sent an event\n *\n * @param {module:models/event.MatrixEvent} event event to be checked\n *\n * @return {module:crypto/deviceinfo?}\n */\n public getEventSenderDeviceInfo(event: MatrixEvent): DeviceInfo | null {\n const senderKey = event.getSenderKey();\n const algorithm = event.getWireContent().algorithm;\n\n if (!senderKey || !algorithm) {\n return null;\n }\n\n const forwardingChain = event.getForwardingCurve25519KeyChain();\n if (forwardingChain.length > 0) {\n // we got the key this event from somewhere else\n // TODO: check if we can trust the forwarders.\n return null;\n }\n\n if (event.isKeySourceUntrusted()) {\n // we got the key for this event from a source that we consider untrusted\n return null;\n }\n\n // senderKey is the Curve25519 identity key of the device which the event\n // was sent from. In the case of Megolm, it's actually the Curve25519\n // identity key of the device which set up the Megolm session.\n\n const device = this.deviceList.getDeviceByIdentityKey(\n algorithm, senderKey,\n );\n\n if (device === null) {\n // we haven't downloaded the details of this device yet.\n return null;\n }\n\n // so far so good, but now we need to check that the sender of this event\n // hadn't advertised someone else's Curve25519 key as their own. We do that\n // by checking the Ed25519 claimed by the event (or, in the case of megolm,\n // the event which set up the megolm session), to check that it matches the\n // fingerprint of the purported sending device.\n //\n // (see https://github.com/vector-im/vector-web/issues/2215)\n\n const claimedKey = event.getClaimedEd25519Key();\n if (!claimedKey) {\n logger.warn(\"Event \" + event.getId() + \" claims no ed25519 key: \" +\n \"cannot verify sending device\");\n return null;\n }\n\n if (claimedKey !== device.getFingerprint()) {\n logger.warn(\n \"Event \" + event.getId() + \" claims ed25519 key \" + claimedKey +\n \" but sender device has key \" + device.getFingerprint());\n return null;\n }\n\n return device;\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param {module:models/event.MatrixEvent} event event to be checked\n *\n * @return {object} An object with the fields:\n * - encrypted: whether the event is encrypted (if not encrypted, some of the\n * other properties may not be set)\n * - senderKey: the sender's key\n * - algorithm: the algorithm used to encrypt the event\n * - authenticated: whether we can be sure that the owner of the senderKey\n * sent the event\n * - sender: the sender's device information, if available\n * - mismatchedSender: if the event's ed25519 and curve25519 keys don't match\n * (only meaningful if `sender` is set)\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n const ret: Partial<IEncryptedEventInfo> = {};\n\n ret.senderKey = event.getSenderKey();\n ret.algorithm = event.getWireContent().algorithm;\n\n if (!ret.senderKey || !ret.algorithm) {\n ret.encrypted = false;\n return ret as IEncryptedEventInfo;\n }\n ret.encrypted = true;\n\n const forwardingChain = event.getForwardingCurve25519KeyChain();\n if (forwardingChain.length > 0 || event.isKeySourceUntrusted()) {\n // we got the key this event from somewhere else\n // TODO: check if we can trust the forwarders.\n ret.authenticated = false;\n } else {\n ret.authenticated = true;\n }\n\n // senderKey is the Curve25519 identity key of the device which the event\n // was sent from. In the case of Megolm, it's actually the Curve25519\n // identity key of the device which set up the Megolm session.\n\n ret.sender = this.deviceList.getDeviceByIdentityKey(ret.algorithm, ret.senderKey);\n\n // so far so good, but now we need to check that the sender of this event\n // hadn't advertised someone else's Curve25519 key as their own. We do that\n // by checking the Ed25519 claimed by the event (or, in the case of megolm,\n // the event which set up the megolm session), to check that it matches the\n // fingerprint of the purported sending device.\n //\n // (see https://github.com/vector-im/vector-web/issues/2215)\n\n const claimedKey = event.getClaimedEd25519Key();\n if (!claimedKey) {\n logger.warn(\"Event \" + event.getId() + \" claims no ed25519 key: \" +\n \"cannot verify sending device\");\n ret.mismatchedSender = true;\n }\n\n if (ret.sender && claimedKey !== ret.sender.getFingerprint()) {\n logger.warn(\n \"Event \" + event.getId() + \" claims ed25519 key \" + claimedKey +\n \"but sender device has key \" + ret.sender.getFingerprint());\n ret.mismatchedSender = true;\n }\n\n return ret as IEncryptedEventInfo;\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param {string} roomId The ID of the room to discard the session for\n *\n * This should not normally be necessary.\n */\n public forceDiscardSession(roomId: string): void {\n const alg = this.roomEncryptors[roomId];\n if (alg === undefined) throw new Error(\"Room not encrypted\");\n if (alg.forceDiscardSession === undefined) {\n throw new Error(\"Room encryption algorithm doesn't support session discarding\");\n }\n alg.forceDiscardSession();\n }\n\n /**\n * Configure a room to use encryption (ie, save a flag in the cryptoStore).\n *\n * @param {string} roomId The room ID to enable encryption in.\n *\n * @param {object} config The encryption config for the room.\n *\n * @param {boolean=} inhibitDeviceQuery true to suppress device list query for\n * users in the room (for now). In case lazy loading is enabled,\n * the device query is always inhibited as the members are not tracked.\n */\n public async setRoomEncryption(\n roomId: string,\n config: any, // TODO types\n inhibitDeviceQuery?: boolean,\n ): Promise<void> {\n // ignore crypto events with no algorithm defined\n // This will happen if a crypto event is redacted before we fetch the room state\n // It would otherwise just throw later as an unknown algorithm would, but we may\n // as well catch this here\n if (!config.algorithm) {\n logger.log(\"Ignoring setRoomEncryption with no algorithm\");\n return;\n }\n\n // if state is being replayed from storage, we might already have a configuration\n // for this room as they are persisted as well.\n // We just need to make sure the algorithm is initialized in this case.\n // However, if the new config is different,\n // we should bail out as room encryption can't be changed once set.\n const existingConfig = this.roomList.getRoomEncryption(roomId);\n if (existingConfig) {\n if (JSON.stringify(existingConfig) != JSON.stringify(config)) {\n logger.error(\"Ignoring m.room.encryption event which requests \" +\n \"a change of config in \" + roomId);\n return;\n }\n }\n // if we already have encryption in this room, we should ignore this event,\n // as it would reset the encryption algorithm.\n // This is at least expected to be called twice, as sync calls onCryptoEvent\n // for both the timeline and state sections in the /sync response,\n // the encryption event would appear in both.\n // If it's called more than twice though,\n // it signals a bug on client or server.\n const existingAlg = this.roomEncryptors[roomId];\n if (existingAlg) {\n return;\n }\n\n // _roomList.getRoomEncryption will not race with _roomList.setRoomEncryption\n // because it first stores in memory. We should await the promise only\n // after all the in-memory state (roomEncryptors and _roomList) has been updated\n // to avoid races when calling this method multiple times. Hence keep a hold of the promise.\n let storeConfigPromise = null;\n if (!existingConfig) {\n storeConfigPromise = this.roomList.setRoomEncryption(roomId, config);\n }\n\n const AlgClass = algorithms.ENCRYPTION_CLASSES[config.algorithm];\n if (!AlgClass) {\n throw new Error(\"Unable to encrypt with \" + config.algorithm);\n }\n\n const alg = new AlgClass({\n userId: this.userId,\n deviceId: this.deviceId,\n crypto: this,\n olmDevice: this.olmDevice,\n baseApis: this.baseApis,\n roomId: roomId,\n config: config,\n });\n this.roomEncryptors[roomId] = alg;\n\n if (storeConfigPromise) {\n await storeConfigPromise;\n }\n\n if (!this.lazyLoadMembers) {\n logger.log(\"Enabling encryption in \" + roomId + \"; \" +\n \"starting to track device lists for all users therein\");\n\n await this.trackRoomDevices(roomId);\n // TODO: this flag is only not used from MatrixClient::setRoomEncryption\n // which is never used (inside Element at least)\n // but didn't want to remove it as it technically would\n // be a breaking change.\n if (!inhibitDeviceQuery) {\n this.deviceList.refreshOutdatedDeviceLists();\n }\n } else {\n logger.log(\"Enabling encryption in \" + roomId);\n }\n }\n\n /**\n * Make sure we are tracking the device lists for all users in this room.\n *\n * @param {string} roomId The room ID to start tracking devices in.\n * @returns {Promise} when all devices for the room have been fetched and marked to track\n */\n public trackRoomDevices(roomId: string): Promise<void> {\n const trackMembers = async () => {\n // not an encrypted room\n if (!this.roomEncryptors[roomId]) {\n return;\n }\n const room = this.clientStore.getRoom(roomId);\n if (!room) {\n throw new Error(`Unable to start tracking devices in unknown room ${roomId}`);\n }\n logger.log(`Starting to track devices for room ${roomId} ...`);\n const members = await room.getEncryptionTargetMembers();\n members.forEach((m) => {\n this.deviceList.startTrackingDeviceList(m.userId);\n });\n };\n\n let promise = this.roomDeviceTrackingState[roomId];\n if (!promise) {\n promise = trackMembers();\n this.roomDeviceTrackingState[roomId] = promise.catch(err => {\n this.roomDeviceTrackingState[roomId] = null;\n throw err;\n });\n }\n return promise;\n }\n\n /**\n * Try to make sure we have established olm sessions for all known devices for\n * the given users.\n *\n * @param {string[]} users list of user ids\n *\n * @return {Promise} resolves once the sessions are complete, to\n * an Object mapping from userId to deviceId to\n * {@link module:crypto~OlmSessionResult}\n */\n ensureOlmSessionsForUsers(users: string[]): Promise<Record<string, Record<string, olmlib.IOlmSessionResult>>> {\n const devicesByUser = {};\n\n for (let i = 0; i < users.length; ++i) {\n const userId = users[i];\n devicesByUser[userId] = [];\n\n const devices = this.getStoredDevicesForUser(userId) || [];\n for (let j = 0; j < devices.length; ++j) {\n const deviceInfo = devices[j];\n\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother setting up session to ourself\n continue;\n }\n if (deviceInfo.verified == DeviceVerification.BLOCKED) {\n // don't bother setting up sessions with blocked users\n continue;\n }\n\n devicesByUser[userId].push(deviceInfo);\n }\n }\n\n return olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * @return {module:crypto/OlmDevice.MegolmSessionData[]} a list of session export objects\n */\n public async exportRoomKeys(): Promise<IMegolmSessionData[]> {\n const exportedSessions = [];\n await this.cryptoStore.doTxn(\n 'readonly', [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {\n this.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (s) => {\n if (s === null) return;\n\n const sess = this.olmDevice.exportInboundGroupSession(\n s.senderKey, s.sessionId, s.sessionData,\n );\n delete sess.first_known_index;\n sess.algorithm = olmlib.MEGOLM_ALGORITHM;\n exportedSessions.push(sess);\n });\n },\n );\n\n return exportedSessions;\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param {Object[]} keys a list of session export objects\n * @param {Object} opts\n * @param {Function} opts.progressCallback called with an object which has a stage param\n * @return {Promise} a promise which resolves once the keys have been imported\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts: any = {}): Promise<any> { // TODO types\n let successes = 0;\n let failures = 0;\n const total = keys.length;\n\n function updateProgress() {\n opts.progressCallback({\n stage: \"load_keys\",\n successes,\n failures,\n total,\n });\n }\n\n return Promise.all(keys.map((key) => {\n if (!key.room_id || !key.algorithm) {\n logger.warn(\"ignoring room key entry with missing fields\", key);\n failures++;\n if (opts.progressCallback) { updateProgress(); }\n return null;\n }\n\n const alg = this.getRoomDecryptor(key.room_id, key.algorithm);\n return alg.importRoomKey(key, opts).finally(() => {\n successes++;\n if (opts.progressCallback) { updateProgress(); }\n });\n }));\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns {Promise<number>} Resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise<number> {\n return this.backupManager.countSessionsNeedingBackup();\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param {module:models/room} room the room the event is in\n */\n public prepareToEncrypt(room: Room): void {\n const alg = this.roomEncryptors[room.roomId];\n if (alg) {\n alg.prepareToEncrypt(room);\n }\n }\n\n /* eslint-disable valid-jsdoc */ //https://github.com/eslint/eslint/issues/7307\n /**\n * Encrypt an event according to the configuration of the room.\n *\n * @param {module:models/event.MatrixEvent} event event to be sent\n *\n * @param {module:models/room} room destination room.\n *\n * @return {Promise?} Promise which resolves when the event has been\n * encrypted, or null if nothing was needed\n */\n /* eslint-enable valid-jsdoc */\n // TODO this return type lies\n public async encryptEvent(event: MatrixEvent, room: Room): Promise<void> {\n if (!room) {\n throw new Error(\"Cannot send encrypted messages in unknown rooms\");\n }\n\n const roomId = event.getRoomId();\n\n const alg = this.roomEncryptors[roomId];\n if (!alg) {\n // MatrixClient has already checked that this room should be encrypted,\n // so this is an unexpected situation.\n throw new Error(\n \"Room was previously configured to use encryption, but is \" +\n \"no longer. Perhaps the homeserver is hiding the \" +\n \"configuration event.\",\n );\n }\n\n if (!this.roomDeviceTrackingState[roomId]) {\n this.trackRoomDevices(roomId);\n }\n // wait for all the room devices to be loaded\n await this.roomDeviceTrackingState[roomId];\n\n let content = event.getContent();\n // If event has an m.relates_to then we need\n // to put this on the wrapping event instead\n const mRelatesTo = content['m.relates_to'];\n if (mRelatesTo) {\n // Clone content here so we don't remove `m.relates_to` from the local-echo\n content = Object.assign({}, content);\n delete content['m.relates_to'];\n }\n\n const encryptedContent = await alg.encryptMessage(\n room, event.getType(), content);\n\n if (mRelatesTo) {\n encryptedContent['m.relates_to'] = mRelatesTo;\n }\n\n event.makeEncrypted(\n \"m.room.encrypted\",\n encryptedContent,\n this.olmDevice.deviceCurve25519Key,\n this.olmDevice.deviceEd25519Key,\n );\n }\n\n /**\n * Decrypt a received event\n *\n * @param {MatrixEvent} event\n *\n * @return {Promise<module:crypto~EventDecryptionResult>} resolves once we have\n * finished decrypting. Rejects with an `algorithms.DecryptionError` if there\n * is a problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise<IEventDecryptionResult> {\n if (event.isRedacted()) {\n const redactionEvent = new MatrixEvent(event.getUnsigned().redacted_because);\n const decryptedEvent = await this.decryptEvent(redactionEvent);\n\n return {\n clearEvent: {\n room_id: event.getRoomId(),\n type: \"m.room.message\",\n content: {},\n unsigned: {\n redacted_because: decryptedEvent.clearEvent,\n },\n },\n };\n } else {\n const content = event.getWireContent();\n const alg = this.getRoomDecryptor(event.getRoomId(), content.algorithm);\n return await alg.decryptEvent(event);\n }\n }\n\n /**\n * Handle the notification from /sync or /keys/changes that device lists have\n * been changed.\n *\n * @param {Object} syncData Object containing sync tokens associated with this sync\n * @param {Object} syncDeviceLists device_lists field from /sync, or response from\n * /keys/changes\n */\n public async handleDeviceListChanges(syncData: ISyncStateData, syncDeviceLists: ISyncDeviceLists): Promise<void> {\n // Initial syncs don't have device change lists. We'll either get the complete list\n // of changes for the interval or will have invalidated everything in willProcessSync\n if (!syncData.oldSyncToken) return;\n\n // Here, we're relying on the fact that we only ever save the sync data after\n // sucessfully saving the device list data, so we're guaranteed that the device\n // list store is at least as fresh as the sync token from the sync store, ie.\n // any device changes received in sync tokens prior to the 'next' token here\n // have been processed and are reflected in the current device list.\n // If we didn't make this assumption, we'd have to use the /keys/changes API\n // to get key changes between the sync token in the device list and the 'old'\n // sync token used here to make sure we didn't miss any.\n await this.evalDeviceListChanges(syncDeviceLists);\n }\n\n /**\n * Send a request for some room keys, if we have not already done so\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * @param {Array<{userId: string, deviceId: string}>} recipients\n * @param {boolean} resend whether to resend the key request if there is\n * already one\n *\n * @return {Promise} a promise that resolves when the key request is queued\n */\n public requestRoomKey(\n requestBody: IRoomKeyRequestBody,\n recipients: IRoomKeyRequestRecipient[],\n resend = false,\n ): Promise<void> {\n return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(\n requestBody, recipients, resend,\n ).then(() => {\n if (this.sendKeyRequestsImmediately) {\n this.outgoingRoomKeyRequestManager.sendQueuedRequests();\n }\n }).catch((e) => {\n // this normally means we couldn't talk to the store\n logger.error(\n 'Error requesting key for event', e,\n );\n });\n }\n\n /**\n * Cancel any earlier room key request\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * parameters to match for cancellation\n */\n public cancelRoomKeyRequest(requestBody: IRoomKeyRequestBody): void {\n this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody)\n .catch((e) => {\n logger.warn(\"Error clearing pending room key requests\", e);\n });\n }\n\n /**\n * Re-send any outgoing key requests, eg after verification\n * @returns {Promise}\n */\n public async cancelAndResendAllOutgoingKeyRequests(): Promise<void> {\n await this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests();\n }\n\n /**\n * handle an m.room.encryption event\n *\n * @param {module:models/event.MatrixEvent} event encryption event\n */\n public async onCryptoEvent(event: MatrixEvent): Promise<void> {\n const roomId = event.getRoomId();\n const content = event.getContent();\n\n try {\n // inhibit the device list refresh for now - it will happen once we've\n // finished processing the sync, in onSyncCompleted.\n await this.setRoomEncryption(roomId, content, true);\n } catch (e) {\n logger.error(\"Error configuring encryption in room \" + roomId +\n \":\", e);\n }\n }\n\n /**\n * Called before the result of a sync is processed\n *\n * @param {Object} syncData the data from the 'MatrixClient.sync' event\n */\n public async onSyncWillProcess(syncData: ISyncStateData): Promise<void> {\n if (!syncData.oldSyncToken) {\n // If there is no old sync token, we start all our tracking from\n // scratch, so mark everything as untracked. onCryptoEvent will\n // be called for all e2e rooms during the processing of the sync,\n // at which point we'll start tracking all the users of that room.\n logger.log(\"Initial sync performed - resetting device tracking state\");\n this.deviceList.stopTrackingAllDeviceLists();\n // we always track our own device list (for key backups etc)\n this.deviceList.startTrackingDeviceList(this.userId);\n this.roomDeviceTrackingState = {};\n }\n\n this.sendKeyRequestsImmediately = false;\n }\n\n /**\n * handle the completion of a /sync\n *\n * This is called after the processing of each successful /sync response.\n * It is an opportunity to do a batch process on the information received.\n *\n * @param {Object} syncData the data from the 'MatrixClient.sync' event\n */\n public async onSyncCompleted(syncData: ISyncStateData): Promise<void> {\n this.deviceList.setSyncToken(syncData.nextSyncToken);\n this.deviceList.saveIfDirty();\n\n // we always track our own device list (for key backups etc)\n this.deviceList.startTrackingDeviceList(this.userId);\n\n this.deviceList.refreshOutdatedDeviceLists();\n\n // we don't start uploading one-time keys until we've caught up with\n // to-device messages, to help us avoid throwing away one-time-keys that we\n // are about to receive messages for\n // (https://github.com/vector-im/element-web/issues/2782).\n if (!syncData.catchingUp) {\n this.maybeUploadOneTimeKeys();\n this.processReceivedRoomKeyRequests();\n\n // likewise don't start requesting keys until we've caught up\n // on to_device messages, otherwise we'll request keys that we're\n // just about to get.\n this.outgoingRoomKeyRequestManager.sendQueuedRequests();\n\n // Sync has finished so send key requests straight away.\n this.sendKeyRequestsImmediately = true;\n }\n }\n\n /**\n * Trigger the appropriate invalidations and removes for a given\n * device list\n *\n * @param {Object} deviceLists device_lists field from /sync, or response from\n * /keys/changes\n */\n private async evalDeviceListChanges(deviceLists: ISyncDeviceLists): Promise<void> {\n if (deviceLists.changed && Array.isArray(deviceLists.changed)) {\n deviceLists.changed.forEach((u) => {\n this.deviceList.invalidateUserDeviceList(u);\n });\n }\n\n if (deviceLists.left && Array.isArray(deviceLists.left) &&\n deviceLists.left.length) {\n // Check we really don't share any rooms with these users\n // any more: the server isn't required to give us the\n // exact correct set.\n const e2eUserIds = new Set(await this.getTrackedE2eUsers());\n\n deviceLists.left.forEach((u) => {\n if (!e2eUserIds.has(u)) {\n this.deviceList.stopTrackingDeviceList(u);\n }\n });\n }\n }\n\n /**\n * Get a list of all the IDs of users we share an e2e room with\n * for which we are tracking devices already\n *\n * @returns {string[]} List of user IDs\n */\n private async getTrackedE2eUsers(): Promise<string[]> {\n const e2eUserIds = [];\n for (const room of this.getTrackedE2eRooms()) {\n const members = await room.getEncryptionTargetMembers();\n for (const member of members) {\n e2eUserIds.push(member.userId);\n }\n }\n return e2eUserIds;\n }\n\n /**\n * Get a list of the e2e-enabled rooms we are members of,\n * and for which we are already tracking the devices\n *\n * @returns {module:models.Room[]}\n */\n private getTrackedE2eRooms(): Room[] {\n return this.clientStore.getRooms().filter((room) => {\n // check for rooms with encryption enabled\n const alg = this.roomEncryptors[room.roomId];\n if (!alg) {\n return false;\n }\n if (!this.roomDeviceTrackingState[room.roomId]) {\n return false;\n }\n\n // ignore any rooms which we have left\n const myMembership = room.getMyMembership();\n return myMembership === \"join\" || myMembership === \"invite\";\n });\n }\n\n private onToDeviceEvent = (event: MatrixEvent): void => {\n try {\n logger.log(`received to_device ${event.getType()} from: ` +\n `${event.getSender()} id: ${event.getId()}`);\n\n if (event.getType() == \"m.room_key\"\n || event.getType() == \"m.forwarded_room_key\") {\n this.onRoomKeyEvent(event);\n } else if (event.getType() == \"m.room_key_request\") {\n this.onRoomKeyRequestEvent(event);\n } else if (event.getType() === \"m.secret.request\") {\n this.secretStorage.onRequestReceived(event);\n } else if (event.getType() === \"m.secret.send\") {\n this.secretStorage.onSecretReceived(event);\n } else if (event.getType() === \"org.matrix.room_key.withheld\") {\n this.onRoomKeyWithheldEvent(event);\n } else if (event.getContent().transaction_id) {\n this.onKeyVerificationMessage(event);\n } else if (event.getContent().msgtype === \"m.bad.encrypted\") {\n this.onToDeviceBadEncrypted(event);\n } else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n if (!event.isBeingDecrypted()) {\n event.attemptDecryption(this);\n }\n // once the event has been decrypted, try again\n event.once('Event.decrypted', (ev) => {\n this.onToDeviceEvent(ev);\n });\n }\n } catch (e) {\n logger.error(\"Error handling toDeviceEvent:\", e);\n }\n };\n\n /**\n * Handle a key event\n *\n * @private\n * @param {module:models/event.MatrixEvent} event key event\n */\n private onRoomKeyEvent(event: MatrixEvent): void {\n const content = event.getContent();\n\n if (!content.room_id || !content.algorithm) {\n logger.error(\"key event is missing fields\");\n return;\n }\n\n if (!this.backupManager.checkedForBackup) {\n // don't bother awaiting on this - the important thing is that we retry if we\n // haven't managed to check before\n this.backupManager.checkAndStart();\n }\n\n const alg = this.getRoomDecryptor(content.room_id, content.algorithm);\n alg.onRoomKeyEvent(event);\n }\n\n /**\n * Handle a key withheld event\n *\n * @private\n * @param {module:models/event.MatrixEvent} event key withheld event\n */\n private onRoomKeyWithheldEvent(event: MatrixEvent): void {\n const content = event.getContent();\n\n if ((content.code !== \"m.no_olm\" && (!content.room_id || !content.session_id))\n || !content.algorithm || !content.sender_key) {\n logger.error(\"key withheld event is missing fields\");\n return;\n }\n\n logger.info(\n `Got room key withheld event from ${event.getSender()} (${content.sender_key}) `\n + `for ${content.algorithm}/${content.room_id}/${content.session_id} `\n + `with reason ${content.code} (${content.reason})`,\n );\n\n const alg = this.getRoomDecryptor(content.room_id, content.algorithm);\n if (alg.onRoomKeyWithheldEvent) {\n alg.onRoomKeyWithheldEvent(event);\n }\n if (!content.room_id) {\n // retry decryption for all events sent by the sender_key. This will\n // update the events to show a message indicating that the olm session was\n // wedged.\n const roomDecryptors = this.getRoomDecryptors(content.algorithm);\n for (const decryptor of roomDecryptors) {\n decryptor.retryDecryptionFromSender(content.sender_key);\n }\n }\n }\n\n /**\n * Handle a general key verification event.\n *\n * @private\n * @param {module:models/event.MatrixEvent} event verification start event\n */\n private onKeyVerificationMessage(event: MatrixEvent): void {\n if (!ToDeviceChannel.validateEvent(event, this.baseApis)) {\n return;\n }\n const createRequest = event => {\n if (!ToDeviceChannel.canCreateRequest(ToDeviceChannel.getEventType(event))) {\n return;\n }\n const content = event.getContent();\n const deviceId = content && content.from_device;\n if (!deviceId) {\n return;\n }\n const userId = event.getSender();\n const channel = new ToDeviceChannel(\n this.baseApis,\n userId,\n [deviceId],\n );\n return new VerificationRequest(\n channel, this.verificationMethods, this.baseApis);\n };\n this.handleVerificationEvent(\n event,\n this.toDeviceVerificationRequests,\n createRequest,\n );\n }\n\n /**\n * Handle key verification requests sent as timeline events\n *\n * @private\n * @param {module:models/event.MatrixEvent} event the timeline event\n * @param {module:models/Room} room not used\n * @param {boolean} atStart not used\n * @param {boolean} removed not used\n * @param {boolean} { liveEvent } whether this is a live event\n */\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room,\n atStart: boolean,\n removed: boolean,\n { liveEvent = true } = {},\n ): void => {\n if (!InRoomChannel.validateEvent(event, this.baseApis)) {\n return;\n }\n const createRequest = event => {\n const channel = new InRoomChannel(\n this.baseApis,\n event.getRoomId(),\n );\n return new VerificationRequest(\n channel, this.verificationMethods, this.baseApis);\n };\n this.handleVerificationEvent(\n event,\n this.inRoomVerificationRequests,\n createRequest,\n liveEvent,\n );\n };\n\n private async handleVerificationEvent(\n event: MatrixEvent,\n requestsMap: any, // TODO types\n createRequest: any, // TODO types\n isLiveEvent = true,\n ): Promise<void> {\n let request = requestsMap.getRequest(event);\n let isNewRequest = false;\n if (!request) {\n request = createRequest(event);\n // a request could not be made from this event, so ignore event\n if (!request) {\n logger.log(`Crypto: could not find VerificationRequest for ` +\n `${event.getType()}, and could not create one, so ignoring.`);\n return;\n }\n isNewRequest = true;\n requestsMap.setRequest(event, request);\n }\n event.setVerificationRequest(request);\n try {\n await request.channel.handleEvent(event, request, isLiveEvent);\n } catch (err) {\n logger.error(\"error while handling verification event: \" + err.message);\n }\n const shouldEmit = isNewRequest &&\n !request.initiatedByMe &&\n !request.invalid && // check it has enough events to pass the UNSENT stage\n !request.observeOnly;\n if (shouldEmit) {\n this.baseApis.emit(\"crypto.verification.request\", request);\n }\n }\n\n /**\n * Handle a toDevice event that couldn't be decrypted\n *\n * @private\n * @param {module:models/event.MatrixEvent} event undecryptable event\n */\n private async onToDeviceBadEncrypted(event: MatrixEvent): Promise<void> {\n const content = event.getWireContent();\n const sender = event.getSender();\n const algorithm = content.algorithm;\n const deviceKey = content.sender_key;\n\n // retry decryption for all events sent by the sender_key. This will\n // update the events to show a message indicating that the olm session was\n // wedged.\n const retryDecryption = () => {\n const roomDecryptors = this.getRoomDecryptors(olmlib.MEGOLM_ALGORITHM);\n for (const decryptor of roomDecryptors) {\n decryptor.retryDecryptionFromSender(deviceKey);\n }\n };\n\n if (sender === undefined || deviceKey === undefined || deviceKey === undefined) {\n return;\n }\n\n // check when we last forced a new session with this device: if we've already done so\n // recently, don't do it again.\n this.lastNewSessionForced[sender] = this.lastNewSessionForced[sender] || {};\n const lastNewSessionForced = this.lastNewSessionForced[sender][deviceKey] || 0;\n if (lastNewSessionForced + MIN_FORCE_SESSION_INTERVAL_MS > Date.now()) {\n logger.debug(\n \"New session already forced with device \" + sender + \":\" + deviceKey +\n \" at \" + lastNewSessionForced + \": not forcing another\",\n );\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", true);\n retryDecryption();\n return;\n }\n\n // establish a new olm session with this device since we're failing to decrypt messages\n // on a current session.\n // Note that an undecryptable message from another device could easily be spoofed -\n // is there anything we can do to mitigate this?\n let device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);\n if (!device) {\n // if we don't know about the device, fetch the user's devices again\n // and retry before giving up\n await this.downloadKeys([sender], false);\n device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);\n if (!device) {\n logger.info(\n \"Couldn't find device for identity key \" + deviceKey +\n \": not re-establishing session\",\n );\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", false);\n retryDecryption();\n return;\n }\n }\n const devicesByUser = {};\n devicesByUser[sender] = [device];\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, true);\n\n this.lastNewSessionForced[sender][deviceKey] = Date.now();\n\n // Now send a blank message on that session so the other side knows about it.\n // (The keyshare request is sent in the clear so that won't do)\n // We send this first such that, as long as the toDevice messages arrive in the\n // same order we sent them, the other end will get this first, set up the new session,\n // then get the keyshare request and send the key over this new session (because it\n // is the session it has most recently received a message on).\n const encryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key,\n ciphertext: {},\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n sender,\n device,\n { type: \"m.dummy\" },\n );\n\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", true);\n retryDecryption();\n\n await this.baseApis.sendToDevice(\"m.room.encrypted\", {\n [sender]: {\n [device.deviceId]: encryptedContent,\n },\n });\n\n // Most of the time this probably won't be necessary since we'll have queued up a key request when\n // we failed to decrypt the message and will be waiting a bit for the key to arrive before sending\n // it. This won't always be the case though so we need to re-send any that have already been sent\n // to avoid races.\n const requestsToResend =\n await this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(sender, device.deviceId);\n for (const keyReq of requestsToResend) {\n this.requestRoomKey(keyReq.requestBody, keyReq.recipients, true);\n }\n }\n\n /**\n * Handle a change in the membership state of a member of a room\n *\n * @private\n * @param {module:models/event.MatrixEvent} event event causing the change\n * @param {module:models/room-member} member user whose membership changed\n * @param {string=} oldMembership previous membership\n */\n private onRoomMembership(event: MatrixEvent, member: RoomMember, oldMembership?: string): void {\n // this event handler is registered on the *client* (as opposed to the room\n // member itself), which means it is only called on changes to the *live*\n // membership state (ie, it is not called when we back-paginate, nor when\n // we load the state in the initialsync).\n //\n // Further, it is automatically registered and called when new members\n // arrive in the room.\n\n const roomId = member.roomId;\n\n const alg = this.roomEncryptors[roomId];\n if (!alg) {\n // not encrypting in this room\n return;\n }\n // only mark users in this room as tracked if we already started tracking in this room\n // this way we don't start device queries after sync on behalf of this room which we won't use\n // the result of anyway, as we'll need to do a query again once all the members are fetched\n // by calling _trackRoomDevices\n if (this.roomDeviceTrackingState[roomId]) {\n if (member.membership == 'join') {\n logger.log('Join event for ' + member.userId + ' in ' + roomId);\n // make sure we are tracking the deviceList for this user\n this.deviceList.startTrackingDeviceList(member.userId);\n } else if (member.membership == 'invite' &&\n this.clientStore.getRoom(roomId).shouldEncryptForInvitedMembers()) {\n logger.log('Invite event for ' + member.userId + ' in ' + roomId);\n this.deviceList.startTrackingDeviceList(member.userId);\n }\n }\n\n alg.onRoomMembership(event, member, oldMembership);\n }\n\n /**\n * Called when we get an m.room_key_request event.\n *\n * @private\n * @param {module:models/event.MatrixEvent} event key request event\n */\n private onRoomKeyRequestEvent(event: MatrixEvent): void {\n const content = event.getContent();\n if (content.action === \"request\") {\n // Queue it up for now, because they tend to arrive before the room state\n // events at initial sync, and we want to see if we know anything about the\n // room before passing them on to the app.\n const req = new IncomingRoomKeyRequest(event);\n this.receivedRoomKeyRequests.push(req);\n } else if (content.action === \"request_cancellation\") {\n const req = new IncomingRoomKeyRequestCancellation(event);\n this.receivedRoomKeyRequestCancellations.push(req);\n }\n }\n\n /**\n * Process any m.room_key_request events which were queued up during the\n * current sync.\n *\n * @private\n */\n private async processReceivedRoomKeyRequests(): Promise<void> {\n if (this.processingRoomKeyRequests) {\n // we're still processing last time's requests; keep queuing new ones\n // up for now.\n return;\n }\n this.processingRoomKeyRequests = true;\n\n try {\n // we need to grab and clear the queues in the synchronous bit of this method,\n // so that we don't end up racing with the next /sync.\n const requests = this.receivedRoomKeyRequests;\n this.receivedRoomKeyRequests = [];\n const cancellations = this.receivedRoomKeyRequestCancellations;\n this.receivedRoomKeyRequestCancellations = [];\n\n // Process all of the requests, *then* all of the cancellations.\n //\n // This makes sure that if we get a request and its cancellation in the\n // same /sync result, then we process the request before the\n // cancellation (and end up with a cancelled request), rather than the\n // cancellation before the request (and end up with an outstanding\n // request which should have been cancelled.)\n await Promise.all(requests.map((req) =>\n this.processReceivedRoomKeyRequest(req)));\n await Promise.all(cancellations.map((cancellation) =>\n this.processReceivedRoomKeyRequestCancellation(cancellation)));\n } catch (e) {\n logger.error(`Error processing room key requsts: ${e}`);\n } finally {\n this.processingRoomKeyRequests = false;\n }\n }\n\n /**\n * Helper for processReceivedRoomKeyRequests\n *\n * @param {IncomingRoomKeyRequest} req\n */\n private async processReceivedRoomKeyRequest(req: IncomingRoomKeyRequest): Promise<void> {\n const userId = req.userId;\n const deviceId = req.deviceId;\n\n const body = req.requestBody;\n const roomId = body.room_id;\n const alg = body.algorithm;\n\n logger.log(`m.room_key_request from ${userId}:${deviceId}` +\n ` for ${roomId} / ${body.session_id} (id ${req.requestId})`);\n\n if (userId !== this.userId) {\n if (!this.roomEncryptors[roomId]) {\n logger.debug(`room key request for unencrypted room ${roomId}`);\n return;\n }\n const encryptor = this.roomEncryptors[roomId];\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n if (!device) {\n logger.debug(`Ignoring keyshare for unknown device ${userId}:${deviceId}`);\n return;\n }\n\n try {\n await encryptor.reshareKeyWithDevice(body.sender_key, body.session_id, userId, device);\n } catch (e) {\n logger.warn(\n \"Failed to re-share keys for session \" + body.session_id +\n \" with device \" + userId + \":\" + device.deviceId, e,\n );\n }\n return;\n }\n\n if (deviceId === this.deviceId) {\n // We'll always get these because we send room key requests to\n // '*' (ie. 'all devices') which includes the sending device,\n // so ignore requests from ourself because apart from it being\n // very silly, it won't work because an Olm session cannot send\n // messages to itself.\n // The log here is probably superfluous since we know this will\n // always happen, but let's log anyway for now just in case it\n // causes issues.\n logger.log(\"Ignoring room key request from ourselves\");\n return;\n }\n\n // todo: should we queue up requests we don't yet have keys for,\n // in case they turn up later?\n\n // if we don't have a decryptor for this room/alg, we don't have\n // the keys for the requested events, and can drop the requests.\n if (!this.roomDecryptors[roomId]) {\n logger.log(`room key request for unencrypted room ${roomId}`);\n return;\n }\n\n const decryptor = this.roomDecryptors[roomId][alg];\n if (!decryptor) {\n logger.log(`room key request for unknown alg ${alg} in room ${roomId}`);\n return;\n }\n\n if (!await decryptor.hasKeysForKeyRequest(req)) {\n logger.log(\n `room key request for unknown session ${roomId} / ` +\n body.session_id,\n );\n return;\n }\n\n req.share = () => {\n decryptor.shareKeysWithDevice(req);\n };\n\n // if the device is verified already, share the keys\n if (this.checkDeviceTrust(userId, deviceId).isVerified()) {\n logger.log('device is already verified: sharing keys');\n req.share();\n return;\n }\n\n this.emit(\"crypto.roomKeyRequest\", req);\n }\n\n /**\n * Helper for processReceivedRoomKeyRequests\n *\n * @param {IncomingRoomKeyRequestCancellation} cancellation\n */\n private async processReceivedRoomKeyRequestCancellation(\n cancellation: IncomingRoomKeyRequestCancellation,\n ): Promise<void> {\n logger.log(\n `m.room_key_request cancellation for ${cancellation.userId}:` +\n `${cancellation.deviceId} (id ${cancellation.requestId})`,\n );\n\n // we should probably only notify the app of cancellations we told it\n // about, but we don't currently have a record of that, so we just pass\n // everything through.\n this.emit(\"crypto.roomKeyRequestCancellation\", cancellation);\n }\n\n /**\n * Get a decryptor for a given room and algorithm.\n *\n * If we already have a decryptor for the given room and algorithm, return\n * it. Otherwise try to instantiate it.\n *\n * @private\n *\n * @param {string?} roomId room id for decryptor. If undefined, a temporary\n * decryptor is instantiated.\n *\n * @param {string} algorithm crypto algorithm\n *\n * @return {module:crypto.algorithms.base.DecryptionAlgorithm}\n *\n * @raises {module:crypto.algorithms.DecryptionError} if the algorithm is\n * unknown\n */\n public getRoomDecryptor(roomId: string, algorithm: string): DecryptionAlgorithm {\n let decryptors: Record<string, DecryptionAlgorithm>;\n let alg: DecryptionAlgorithm;\n\n roomId = roomId || null;\n if (roomId) {\n decryptors = this.roomDecryptors[roomId];\n if (!decryptors) {\n this.roomDecryptors[roomId] = decryptors = {};\n }\n\n alg = decryptors[algorithm];\n if (alg) {\n return alg;\n }\n }\n\n const AlgClass = algorithms.DECRYPTION_CLASSES[algorithm];\n if (!AlgClass) {\n throw new algorithms.DecryptionError(\n 'UNKNOWN_ENCRYPTION_ALGORITHM',\n 'Unknown encryption algorithm \"' + algorithm + '\".',\n );\n }\n alg = new AlgClass({\n userId: this.userId,\n crypto: this,\n olmDevice: this.olmDevice,\n baseApis: this.baseApis,\n roomId: roomId,\n });\n\n if (decryptors) {\n decryptors[algorithm] = alg;\n }\n return alg;\n }\n\n /**\n * Get all the room decryptors for a given encryption algorithm.\n *\n * @param {string} algorithm The encryption algorithm\n *\n * @return {array} An array of room decryptors\n */\n private getRoomDecryptors(algorithm: string): DecryptionAlgorithm[] {\n const decryptors = [];\n for (const d of Object.values(this.roomDecryptors)) {\n if (algorithm in d) {\n decryptors.push(d[algorithm]);\n }\n }\n return decryptors;\n }\n\n /**\n * sign the given object with our ed25519 key\n *\n * @param {Object} obj Object to which we will add a 'signatures' property\n */\n public async signObject(obj: object & ISignableObject): Promise<void> {\n const sigs = obj.signatures || {};\n const unsigned = obj.unsigned;\n\n delete obj.signatures;\n delete obj.unsigned;\n\n sigs[this.userId] = sigs[this.userId] || {};\n sigs[this.userId][\"ed25519:\" + this.deviceId] = await this.olmDevice.sign(anotherjson.stringify(obj));\n obj.signatures = sigs;\n if (unsigned !== undefined) obj.unsigned = unsigned;\n }\n}\n\n/**\n * Fix up the backup key, that may be in the wrong format due to a bug in a\n * migration step. Some backup keys were stored as a comma-separated list of\n * integers, rather than a base64-encoded byte array. If this function is\n * passed a string that looks like a list of integers rather than a base64\n * string, it will attempt to convert it to the right format.\n *\n * @param {string} key the key to check\n * @returns {null | string} If the key is in the wrong format, then the fixed\n * key will be returned. Otherwise null will be returned.\n *\n */\nexport function fixBackupKey(key: string): string | null {\n if (typeof key !== \"string\" || key.indexOf(\",\") < 0) {\n return null;\n }\n const fixedKey = Uint8Array.from(key.split(\",\"), x => parseInt(x));\n return olmlib.encodeBase64(fixedKey);\n}\n\n/**\n * The parameters of a room key request. The details of the request may\n * vary with the crypto algorithm, but the management and storage layers for\n * outgoing requests expect it to have 'room_id' and 'session_id' properties.\n *\n * @typedef {Object} RoomKeyRequestBody\n */\n\n/**\n * Represents a received m.room_key_request event\n *\n * @property {string} userId user requesting the key\n * @property {string} deviceId device requesting the key\n * @property {string} requestId unique id for the request\n * @property {module:crypto~RoomKeyRequestBody} requestBody\n * @property {function()} share callback which, when called, will ask\n * the relevant crypto algorithm implementation to share the keys for\n * this request.\n */\nexport class IncomingRoomKeyRequest {\n public readonly userId: string;\n public readonly deviceId: string;\n public readonly requestId: string;\n public readonly requestBody: IRoomKeyRequestBody;\n public share: () => void;\n\n constructor(event: MatrixEvent) {\n const content = event.getContent();\n\n this.userId = event.getSender();\n this.deviceId = content.requesting_device_id;\n this.requestId = content.request_id;\n this.requestBody = content.body || {};\n this.share = () => {\n throw new Error(\"don't know how to share keys for this request yet\");\n };\n }\n}\n\n/**\n * Represents a received m.room_key_request cancellation\n *\n * @property {string} userId user requesting the cancellation\n * @property {string} deviceId device requesting the cancellation\n * @property {string} requestId unique id for the request to be cancelled\n */\nclass IncomingRoomKeyRequestCancellation {\n public readonly userId: string;\n public readonly deviceId: string;\n public readonly requestId: string;\n\n constructor(event: MatrixEvent) {\n const content = event.getContent();\n\n this.userId = event.getSender();\n this.deviceId = content.requesting_device_id;\n this.requestId = content.request_id;\n }\n}\n\n/**\n * The result of a (successful) call to decryptEvent.\n *\n * @typedef {Object} EventDecryptionResult\n *\n * @property {Object} clearEvent The plaintext payload for the event\n * (typically containing <tt>type</tt> and <tt>content</tt> fields).\n *\n * @property {?string} senderCurve25519Key Key owned by the sender of this\n * event. See {@link module:models/event.MatrixEvent#getSenderKey}.\n *\n * @property {?string} claimedEd25519Key ed25519 key claimed by the sender of\n * this event. See\n * {@link module:models/event.MatrixEvent#getClaimedEd25519Key}.\n *\n * @property {?Array<string>} forwardingCurve25519KeyChain list of curve25519\n * keys involved in telling us about the senderCurve25519Key and\n * claimedEd25519Key. See\n * {@link module:models/event.MatrixEvent#getForwardingCurve25519KeyChain}.\n */\n\n/**\n * Fires when we receive a room key request\n *\n * @event module:client~MatrixClient#\"crypto.roomKeyRequest\"\n * @param {module:crypto~IncomingRoomKeyRequest} req request details\n */\n\n/**\n * Fires when we receive a room key request cancellation\n *\n * @event module:client~MatrixClient#\"crypto.roomKeyRequestCancellation\"\n * @param {module:crypto~IncomingRoomKeyRequestCancellation} req\n */\n\n/**\n * Fires when the app may wish to warn the user about something related\n * the end-to-end crypto.\n *\n * @event module:client~MatrixClient#\"crypto.warning\"\n * @param {string} type One of the strings listed above\n */\n",
"/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { randomString } from '../randomstring';\n\nconst DEFAULT_ITERATIONS = 500000;\n\nconst DEFAULT_BITSIZE = 256;\n\n/* eslint-disable camelcase */\ninterface IAuthData {\n private_key_salt?: string;\n private_key_iterations?: number;\n private_key_bits?: number;\n}\n/* eslint-enable camelcase */\n\ninterface IKey {\n key: Uint8Array;\n salt: string;\n iterations: number;\n}\n\nexport async function keyFromAuthData(authData: IAuthData, password: string): Promise<Uint8Array> {\n if (!global.Olm) {\n throw new Error(\"Olm is not available\");\n }\n\n if (!authData.private_key_salt || !authData.private_key_iterations) {\n throw new Error(\n \"Salt and/or iterations not found: \" +\n \"this backup cannot be restored with a passphrase\",\n );\n }\n\n return await deriveKey(\n password, authData.private_key_salt,\n authData.private_key_iterations,\n authData.private_key_bits || DEFAULT_BITSIZE,\n );\n}\n\nexport async function keyFromPassphrase(password: string): Promise<IKey> {\n if (!global.Olm) {\n throw new Error(\"Olm is not available\");\n }\n\n const salt = randomString(32);\n\n const key = await deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE);\n\n return { key, salt, iterations: DEFAULT_ITERATIONS };\n}\n\nexport async function deriveKey(\n password: string,\n salt: string,\n iterations: number,\n numBits = DEFAULT_BITSIZE,\n): Promise<Uint8Array> {\n const subtleCrypto = global.crypto.subtle;\n const TextEncoder = global.TextEncoder;\n if (!subtleCrypto || !TextEncoder) {\n // TODO: Implement this for node\n throw new Error(\"Password-based backup is not avaiable on this platform\");\n }\n\n const key = await subtleCrypto.importKey(\n 'raw',\n new TextEncoder().encode(password),\n { name: 'PBKDF2' },\n false,\n ['deriveBits'],\n );\n\n const keybits = await subtleCrypto.deriveBits(\n {\n name: 'PBKDF2',\n salt: new TextEncoder().encode(salt),\n iterations: iterations,\n hash: 'SHA-512',\n },\n key,\n numBits,\n );\n\n return new Uint8Array(keybits);\n}\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module olmlib\n *\n * Utilities common to olm encryption algorithms\n */\n\nimport anotherjson from \"another-json\";\nimport type { PkSigning } from \"@matrix-org/olm\";\nimport { Logger } from \"loglevel\";\n\nimport OlmDevice from \"./OlmDevice\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { logger } from '../logger';\nimport * as utils from \"../utils\";\nimport { OneTimeKey } from \"./dehydration\";\nimport { MatrixClient } from \"../client\";\n\nenum Algorithm {\n Olm = \"m.olm.v1.curve25519-aes-sha2\",\n Megolm = \"m.megolm.v1.aes-sha2\",\n MegolmBackup = \"m.megolm_backup.v1.curve25519-aes-sha2\",\n}\n\n/**\n * matrix algorithm tag for olm\n */\nexport const OLM_ALGORITHM = Algorithm.Olm;\n\n/**\n * matrix algorithm tag for megolm\n */\nexport const MEGOLM_ALGORITHM = Algorithm.Megolm;\n\n/**\n * matrix algorithm tag for megolm backups\n */\nexport const MEGOLM_BACKUP_ALGORITHM = Algorithm.MegolmBackup;\n\nexport interface IOlmSessionResult {\n device: DeviceInfo;\n sessionId?: string;\n}\n\n/**\n * Encrypt an event payload for an Olm device\n *\n * @param {Object<string, string>} resultsObject The `ciphertext` property\n * of the m.room.encrypted event to which to add our result\n *\n * @param {string} ourUserId\n * @param {string} ourDeviceId\n * @param {module:crypto/OlmDevice} olmDevice olm.js wrapper\n * @param {string} recipientUserId\n * @param {module:crypto/deviceinfo} recipientDevice\n * @param {object} payloadFields fields to include in the encrypted payload\n *\n * Returns a promise which resolves (to undefined) when the payload\n * has been encrypted into `resultsObject`\n */\nexport async function encryptMessageForDevice(\n resultsObject: Record<string, string>,\n ourUserId: string,\n ourDeviceId: string,\n olmDevice: OlmDevice,\n recipientUserId: string,\n recipientDevice: DeviceInfo,\n payloadFields: Record<string, any>,\n) {\n const deviceKey = recipientDevice.getIdentityKey();\n const sessionId = await olmDevice.getSessionIdForDevice(deviceKey);\n if (sessionId === null) {\n // If we don't have a session for a device then\n // we can't encrypt a message for it.\n return;\n }\n\n logger.log(\n \"Using sessionid \" + sessionId + \" for device \" +\n recipientUserId + \":\" + recipientDevice.deviceId,\n );\n\n const payload = {\n sender: ourUserId,\n // TODO this appears to no longer be used whatsoever\n sender_device: ourDeviceId,\n\n // Include the Ed25519 key so that the recipient knows what\n // device this message came from.\n // We don't need to include the curve25519 key since the\n // recipient will already know this from the olm headers.\n // When combined with the device keys retrieved from the\n // homeserver signed by the ed25519 key this proves that\n // the curve25519 key and the ed25519 key are owned by\n // the same device.\n keys: {\n \"ed25519\": olmDevice.deviceEd25519Key,\n },\n\n // include the recipient device details in the payload,\n // to avoid unknown key attacks, per\n // https://github.com/vector-im/vector-web/issues/2483\n recipient: recipientUserId,\n recipient_keys: {\n \"ed25519\": recipientDevice.getFingerprint(),\n },\n };\n\n // TODO: technically, a bunch of that stuff only needs to be included for\n // pre-key messages: after that, both sides know exactly which devices are\n // involved in the session. If we're looking to reduce data transfer in the\n // future, we could elide them for subsequent messages.\n\n utils.extend(payload, payloadFields);\n\n resultsObject[deviceKey] = await olmDevice.encryptMessage(\n deviceKey, sessionId, JSON.stringify(payload),\n );\n}\n\n/**\n * Get the existing olm sessions for the given devices, and the devices that\n * don't have olm sessions.\n *\n * @param {module:crypto/OlmDevice} olmDevice\n *\n * @param {MatrixClient} baseApis\n *\n * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser\n * map from userid to list of devices to ensure sessions for\n *\n * @return {Promise} resolves to an array. The first element of the array is a\n * a map of user IDs to arrays of deviceInfo, representing the devices that\n * don't have established olm sessions. The second element of the array is\n * a map from userId to deviceId to {@link module:crypto~OlmSessionResult}\n */\nexport async function getExistingOlmSessions(\n olmDevice: OlmDevice,\n baseApis: MatrixClient,\n devicesByUser: Record<string, DeviceInfo[]>,\n) {\n const devicesWithoutSession = {};\n const sessions = {};\n\n const promises = [];\n\n for (const [userId, devices] of Object.entries(devicesByUser)) {\n for (const deviceInfo of devices) {\n const deviceId = deviceInfo.deviceId;\n const key = deviceInfo.getIdentityKey();\n promises.push((async () => {\n const sessionId = await olmDevice.getSessionIdForDevice(\n key, true,\n );\n if (sessionId === null) {\n devicesWithoutSession[userId] = devicesWithoutSession[userId] || [];\n devicesWithoutSession[userId].push(deviceInfo);\n } else {\n sessions[userId] = sessions[userId] || {};\n sessions[userId][deviceId] = {\n device: deviceInfo,\n sessionId: sessionId,\n };\n }\n })());\n }\n }\n\n await Promise.all(promises);\n\n return [devicesWithoutSession, sessions];\n}\n\n/**\n * Try to make sure we have established olm sessions for the given devices.\n *\n * @param {module:crypto/OlmDevice} olmDevice\n *\n * @param {MatrixClient} baseApis\n *\n * @param {object<string, module:crypto/deviceinfo[]>} devicesByUser\n * map from userid to list of devices to ensure sessions for\n *\n * @param {boolean} [force=false] If true, establish a new session even if one\n * already exists.\n *\n * @param {Number} [otkTimeout] The timeout in milliseconds when requesting\n * one-time keys for establishing new olm sessions.\n *\n * @param {Array} [failedServers] An array to fill with remote servers that\n * failed to respond to one-time-key requests.\n *\n * @param {Logger} [log] A possibly customised log\n *\n * @return {Promise} resolves once the sessions are complete, to\n * an Object mapping from userId to deviceId to\n * {@link module:crypto~OlmSessionResult}\n */\nexport async function ensureOlmSessionsForDevices(\n olmDevice: OlmDevice,\n baseApis: MatrixClient,\n devicesByUser: Record<string, DeviceInfo[]>,\n force = false,\n otkTimeout?: number,\n failedServers?: string[],\n log: Logger = logger,\n): Promise<Record<string, Record<string, IOlmSessionResult>>> {\n if (typeof force === \"number\") {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - backwards compatibility\n log = failedServers;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - backwards compatibility\n failedServers = otkTimeout;\n otkTimeout = force;\n force = false;\n }\n\n const devicesWithoutSession = [\n // [userId, deviceId], ...\n ];\n const result = {};\n const resolveSession: Record<string, (sessionId?: string) => void> = {};\n\n // Mark all sessions this task intends to update as in progress. It is\n // important to do this for all devices this task cares about in a single\n // synchronous operation, as otherwise it is possible to have deadlocks\n // where multiple tasks wait indefinitely on another task to update some set\n // of common devices.\n for (const [, devices] of Object.entries(devicesByUser)) {\n for (const deviceInfo of devices) {\n const key = deviceInfo.getIdentityKey();\n\n if (key === olmDevice.deviceCurve25519Key) {\n // We don't start sessions with ourself, so there's no need to\n // mark it in progress.\n continue;\n }\n\n if (!olmDevice._sessionsInProgress[key]) {\n // pre-emptively mark the session as in-progress to avoid race\n // conditions. If we find that we already have a session, then\n // we'll resolve\n olmDevice._sessionsInProgress[key] = new Promise(resolve => {\n resolveSession[key] = (v: any) => {\n delete olmDevice._sessionsInProgress[key];\n resolve(v);\n };\n });\n }\n }\n }\n\n for (const [userId, devices] of Object.entries(devicesByUser)) {\n result[userId] = {};\n for (const deviceInfo of devices) {\n const deviceId = deviceInfo.deviceId;\n const key = deviceInfo.getIdentityKey();\n\n if (key === olmDevice.deviceCurve25519Key) {\n // We should never be trying to start a session with ourself.\n // Apart from talking to yourself being the first sign of madness,\n // olm sessions can't do this because they get confused when\n // they get a message and see that the 'other side' has started a\n // new chain when this side has an active sender chain.\n // If you see this message being logged in the wild, we should find\n // the thing that is trying to send Olm messages to itself and fix it.\n log.info(\"Attempted to start session with ourself! Ignoring\");\n // We must fill in the section in the return value though, as callers\n // expect it to be there.\n result[userId][deviceId] = {\n device: deviceInfo,\n sessionId: null,\n };\n continue;\n }\n\n const forWhom = `for ${key} (${userId}:${deviceId})`;\n const sessionId = await olmDevice.getSessionIdForDevice(\n key, resolveSession[key], log,\n );\n if (sessionId !== null && resolveSession[key]) {\n // we found a session, but we had marked the session as\n // in-progress, so resolve it now, which will unmark it and\n // unblock anything that was waiting\n resolveSession[key]();\n }\n if (sessionId === null || force) {\n if (force) {\n log.info(`Forcing new Olm session ${forWhom}`);\n } else {\n log.info(`Making new Olm session ${forWhom}`);\n }\n devicesWithoutSession.push([userId, deviceId]);\n }\n result[userId][deviceId] = {\n device: deviceInfo,\n sessionId: sessionId,\n };\n }\n }\n\n if (devicesWithoutSession.length === 0) {\n return result;\n }\n\n const oneTimeKeyAlgorithm = \"signed_curve25519\";\n let res;\n let taskDetail = `one-time keys for ${devicesWithoutSession.length} devices`;\n try {\n log.debug(`Claiming ${taskDetail}`);\n res = await baseApis.claimOneTimeKeys(\n devicesWithoutSession, oneTimeKeyAlgorithm, otkTimeout,\n );\n log.debug(`Claimed ${taskDetail}`);\n } catch (e) {\n for (const resolver of Object.values(resolveSession)) {\n resolver();\n }\n log.log(`Failed to claim ${taskDetail}`, e, devicesWithoutSession);\n throw e;\n }\n\n if (failedServers && \"failures\" in res) {\n failedServers.push(...Object.keys(res.failures));\n }\n\n const otkResult = res.one_time_keys || {};\n const promises = [];\n for (const [userId, devices] of Object.entries(devicesByUser)) {\n const userRes = otkResult[userId] || {};\n for (let j = 0; j < devices.length; j++) {\n const deviceInfo = devices[j];\n const deviceId = deviceInfo.deviceId;\n const key = deviceInfo.getIdentityKey();\n\n if (key === olmDevice.deviceCurve25519Key) {\n // We've already logged about this above. Skip here too\n // otherwise we'll log saying there are no one-time keys\n // which will be confusing.\n continue;\n }\n\n if (result[userId][deviceId].sessionId && !force) {\n // we already have a result for this device\n continue;\n }\n\n const deviceRes = userRes[deviceId] || {};\n let oneTimeKey = null;\n for (const keyId in deviceRes) {\n if (keyId.indexOf(oneTimeKeyAlgorithm + \":\") === 0) {\n oneTimeKey = deviceRes[keyId];\n }\n }\n\n if (!oneTimeKey) {\n log.warn(\n `No one-time keys (alg=${oneTimeKeyAlgorithm}) ` +\n `for device ${userId}:${deviceId}`,\n );\n if (resolveSession[key]) {\n resolveSession[key]();\n }\n continue;\n }\n\n promises.push(\n _verifyKeyAndStartSession(\n olmDevice, oneTimeKey, userId, deviceInfo,\n ).then((sid) => {\n if (resolveSession[key]) {\n resolveSession[key](sid);\n }\n result[userId][deviceId].sessionId = sid;\n }, (e) => {\n if (resolveSession[key]) {\n resolveSession[key]();\n }\n throw e;\n }),\n );\n }\n }\n\n taskDetail = `Olm sessions for ${promises.length} devices`;\n log.debug(`Starting ${taskDetail}`);\n await Promise.all(promises);\n log.debug(`Started ${taskDetail}`);\n return result;\n}\n\nasync function _verifyKeyAndStartSession(\n olmDevice: OlmDevice,\n oneTimeKey: OneTimeKey,\n userId: string,\n deviceInfo: DeviceInfo,\n): Promise<string> {\n const deviceId = deviceInfo.deviceId;\n try {\n await verifySignature(\n olmDevice, oneTimeKey, userId, deviceId,\n deviceInfo.getFingerprint(),\n );\n } catch (e) {\n logger.error(\n \"Unable to verify signature on one-time key for device \" +\n userId + \":\" + deviceId + \":\", e,\n );\n return null;\n }\n\n let sid;\n try {\n sid = await olmDevice.createOutboundSession(\n deviceInfo.getIdentityKey(), oneTimeKey.key,\n );\n } catch (e) {\n // possibly a bad key\n logger.error(\"Error starting olm session with device \" +\n userId + \":\" + deviceId + \": \" + e);\n return null;\n }\n\n logger.log(\"Started new olm sessionid \" + sid +\n \" for device \" + userId + \":\" + deviceId);\n return sid;\n}\n\nexport interface IObject {\n unsigned?: object;\n signatures?: object;\n}\n\n/**\n * Verify the signature on an object\n *\n * @param {module:crypto/OlmDevice} olmDevice olm wrapper to use for verify op\n *\n * @param {Object} obj object to check signature on.\n *\n * @param {string} signingUserId ID of the user whose signature should be checked\n *\n * @param {string} signingDeviceId ID of the device whose signature should be checked\n *\n * @param {string} signingKey base64-ed ed25519 public key\n *\n * Returns a promise which resolves (to undefined) if the the signature is good,\n * or rejects with an Error if it is bad.\n */\nexport async function verifySignature(\n olmDevice: OlmDevice,\n obj: OneTimeKey | IObject,\n signingUserId: string,\n signingDeviceId: string,\n signingKey: string,\n) {\n const signKeyId = \"ed25519:\" + signingDeviceId;\n const signatures = obj.signatures || {};\n const userSigs = signatures[signingUserId] || {};\n const signature = userSigs[signKeyId];\n if (!signature) {\n throw Error(\"No signature\");\n }\n\n // prepare the canonical json: remove unsigned and signatures, and stringify with anotherjson\n const mangledObj = Object.assign({}, obj);\n if (\"unsigned\" in mangledObj) {\n delete mangledObj.unsigned;\n }\n delete mangledObj.signatures;\n const json = anotherjson.stringify(mangledObj);\n\n olmDevice.verifySignature(\n signingKey, json, signature,\n );\n}\n\n/**\n * Sign a JSON object using public key cryptography\n * @param {Object} obj Object to sign. The object will be modified to include\n * the new signature\n * @param {Olm.PkSigning|Uint8Array} key the signing object or the private key\n * seed\n * @param {string} userId The user ID who owns the signing key\n * @param {string} pubKey The public key (ignored if key is a seed)\n * @returns {string} the signature for the object\n */\nexport function pkSign(obj: IObject, key: PkSigning, userId: string, pubKey: string): string {\n let createdKey = false;\n if (key instanceof Uint8Array) {\n const keyObj = new global.Olm.PkSigning();\n pubKey = keyObj.init_with_seed(key);\n key = keyObj;\n createdKey = true;\n }\n const sigs = obj.signatures || {};\n delete obj.signatures;\n const unsigned = obj.unsigned;\n if (obj.unsigned) delete obj.unsigned;\n try {\n const mysigs = sigs[userId] || {};\n sigs[userId] = mysigs;\n\n return mysigs['ed25519:' + pubKey] = key.sign(anotherjson.stringify(obj));\n } finally {\n obj.signatures = sigs;\n if (unsigned) obj.unsigned = unsigned;\n if (createdKey) {\n key.free();\n }\n }\n}\n\n/**\n * Verify a signed JSON object\n * @param {Object} obj Object to verify\n * @param {string} pubKey The public key to use to verify\n * @param {string} userId The user ID who signed the object\n */\nexport function pkVerify(obj: IObject, pubKey: string, userId: string) {\n const keyId = \"ed25519:\" + pubKey;\n if (!(obj.signatures && obj.signatures[userId] && obj.signatures[userId][keyId])) {\n throw new Error(\"No signature\");\n }\n const signature = obj.signatures[userId][keyId];\n const util = new global.Olm.Utility();\n const sigs = obj.signatures;\n delete obj.signatures;\n const unsigned = obj.unsigned;\n if (obj.unsigned) delete obj.unsigned;\n try {\n util.ed25519_verify(pubKey, anotherjson.stringify(obj), signature);\n } finally {\n obj.signatures = sigs;\n if (unsigned) obj.unsigned = unsigned;\n util.free();\n }\n}\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param {Uint8Array} uint8Array The data to encode.\n * @return {string} The base64.\n */\nexport function encodeBase64(uint8Array: ArrayBuffer | Uint8Array): string {\n return Buffer.from(uint8Array).toString(\"base64\");\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64.\n * @param {Uint8Array} uint8Array The data to encode.\n * @return {string} The unpadded base64.\n */\nexport function encodeUnpaddedBase64(uint8Array: ArrayBuffer | Uint8Array): string {\n return encodeBase64(uint8Array).replace(/=+$/g, '');\n}\n\n/**\n * Decode a base64 string to a typed array of uint8.\n * @param {string} base64 The base64 to decode.\n * @return {Uint8Array} The decoded data.\n */\nexport function decodeBase64(base64: string): Uint8Array {\n return Buffer.from(base64, \"base64\");\n}\n",
"/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport bs58 from 'bs58';\n\n// picked arbitrarily but to try & avoid clashing with any bitcoin ones\n// (which are also base58 encoded, but bitcoin's involve a lot more hashing)\nconst OLM_RECOVERY_KEY_PREFIX = [0x8B, 0x01];\n\nexport function encodeRecoveryKey(key: ArrayLike<number>): string {\n const buf = new Buffer(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1);\n buf.set(OLM_RECOVERY_KEY_PREFIX, 0);\n buf.set(key, OLM_RECOVERY_KEY_PREFIX.length);\n\n let parity = 0;\n for (let i = 0; i < buf.length - 1; ++i) {\n parity ^= buf[i];\n }\n buf[buf.length - 1] = parity;\n const base58key = bs58.encode(buf);\n\n return base58key.match(/.{1,4}/g).join(\" \");\n}\n\nexport function decodeRecoveryKey(recoveryKey: string): Uint8Array {\n const result = bs58.decode(recoveryKey.replace(/ /g, ''));\n\n let parity = 0;\n for (const b of result) {\n parity ^= b;\n }\n if (parity !== 0) {\n throw new Error(\"Incorrect parity\");\n }\n\n for (let i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) {\n if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) {\n throw new Error(\"Incorrect prefix\");\n }\n }\n\n if (\n result.length !==\n OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH + 1\n ) {\n throw new Error(\"Incorrect length\");\n }\n\n return Uint8Array.from(result.slice(\n OLM_RECOVERY_KEY_PREFIX.length,\n OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH,\n ));\n}\n",
"/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../../logger';\nimport * as utils from \"../../utils\";\n\nexport const VERSION = 10;\nconst PROFILE_TRANSACTIONS = false;\n\n/**\n * Implementation of a CryptoStore which is backed by an existing\n * IndexedDB connection. Generally you want IndexedDBCryptoStore\n * which connects to the database and defers to one of these.\n *\n * @implements {module:crypto/store/base~CryptoStore}\n */\nexport class Backend {\n /**\n * @param {IDBDatabase} db\n */\n constructor(db) {\n this._db = db;\n this._nextTxnId = 0;\n\n // make sure we close the db on `onversionchange` - otherwise\n // attempts to delete the database will block (and subsequent\n // attempts to re-create it will also block).\n db.onversionchange = (ev) => {\n logger.log(`versionchange for indexeddb ${this._dbName}: closing`);\n db.close();\n };\n }\n\n /**\n * Look for an existing outgoing room key request, and if none is found,\n * add a new one\n *\n * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request\n *\n * @returns {Promise} resolves to\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the\n * same instance as passed in, or the existing one.\n */\n getOrAddOutgoingRoomKeyRequest(request) {\n const requestBody = request.requestBody;\n\n return new Promise((resolve, reject) => {\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readwrite\");\n txn.onerror = reject;\n\n // first see if we already have an entry for this request.\n this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => {\n if (existing) {\n // this entry matches the request - return it.\n logger.log(\n `already have key request outstanding for ` +\n `${requestBody.room_id} / ${requestBody.session_id}: ` +\n `not sending another`,\n );\n resolve(existing);\n return;\n }\n\n // we got to the end of the list without finding a match\n // - add the new request.\n logger.log(\n `enqueueing key request for ${requestBody.room_id} / ` +\n requestBody.session_id,\n );\n txn.oncomplete = () => {resolve(request);};\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n store.add(request);\n });\n });\n }\n\n /**\n * Look for an existing room key request\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * existing request to look for\n *\n * @return {Promise} resolves to the matching\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * not found\n */\n getOutgoingRoomKeyRequest(requestBody) {\n return new Promise((resolve, reject) => {\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n txn.onerror = reject;\n\n this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => {\n resolve(existing);\n });\n });\n }\n\n /**\n * look for an existing room key request in the db\n *\n * @private\n * @param {IDBTransaction} txn database transaction\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * existing request to look for\n * @param {Function} callback function to call with the results of the\n * search. Either passed a matching\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * not found.\n */\n _getOutgoingRoomKeyRequest(txn, requestBody, callback) {\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n\n const idx = store.index(\"session\");\n const cursorReq = idx.openCursor([\n requestBody.room_id,\n requestBody.session_id,\n ]);\n\n cursorReq.onsuccess = (ev) => {\n const cursor = ev.target.result;\n if (!cursor) {\n // no match found\n callback(null);\n return;\n }\n\n const existing = cursor.value;\n\n if (utils.deepCompare(existing.requestBody, requestBody)) {\n // got a match\n callback(existing);\n return;\n }\n\n // look at the next entry in the index\n cursor.continue();\n };\n }\n\n /**\n * Look for room key requests by state\n *\n * @param {Array<Number>} wantedStates list of acceptable states\n *\n * @return {Promise} resolves to the a\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * there are no pending requests in those states. If there are multiple\n * requests in those states, an arbitrary one is chosen.\n */\n getOutgoingRoomKeyRequestByState(wantedStates) {\n if (wantedStates.length === 0) {\n return Promise.resolve(null);\n }\n\n // this is a bit tortuous because we need to make sure we do the lookup\n // in a single transaction, to avoid having a race with the insertion\n // code.\n\n // index into the wantedStates array\n let stateIndex = 0;\n let result;\n\n function onsuccess(ev) {\n const cursor = ev.target.result;\n if (cursor) {\n // got a match\n result = cursor.value;\n return;\n }\n\n // try the next state in the list\n stateIndex++;\n if (stateIndex >= wantedStates.length) {\n // no matches\n return;\n }\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = ev.target.source.openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n }\n\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = store.index(\"state\").openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n\n return promiseifyTxn(txn).then(() => result);\n }\n\n /**\n *\n * @param {Number} wantedState\n * @return {Promise<Array<*>>} All elements in a given state\n */\n getAllOutgoingRoomKeyRequestsByState(wantedState) {\n return new Promise((resolve, reject) => {\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n const index = store.index(\"state\");\n const request = index.getAll(wantedState);\n\n request.onsuccess = (ev) => resolve(ev.target.result);\n request.onerror = (ev) => reject(ev.target.error);\n });\n }\n\n getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) {\n let stateIndex = 0;\n const results = [];\n\n function onsuccess(ev) {\n const cursor = ev.target.result;\n if (cursor) {\n const keyReq = cursor.value;\n if (keyReq.recipients.includes({ userId, deviceId })) {\n results.push(keyReq);\n }\n cursor.continue();\n } else {\n // try the next state in the list\n stateIndex++;\n if (stateIndex >= wantedStates.length) {\n // no matches\n return;\n }\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = ev.target.source.openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n }\n }\n\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = store.index(\"state\").openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n\n return promiseifyTxn(txn).then(() => results);\n }\n\n /**\n * Look for an existing room key request by id and state, and update it if\n * found\n *\n * @param {string} requestId ID of request to update\n * @param {number} expectedState state we expect to find the request in\n * @param {Object} updates name/value map of updates to apply\n *\n * @returns {Promise} resolves to\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}\n * updated request, or null if no matching row was found\n */\n updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {\n let result = null;\n\n function onsuccess(ev) {\n const cursor = ev.target.result;\n if (!cursor) {\n return;\n }\n const data = cursor.value;\n if (data.state != expectedState) {\n logger.warn(\n `Cannot update room key request from ${expectedState} ` +\n `as it was already updated to ${data.state}`,\n );\n return;\n }\n Object.assign(data, updates);\n cursor.update(data);\n result = data;\n }\n\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readwrite\");\n const cursorReq = txn.objectStore(\"outgoingRoomKeyRequests\")\n .openCursor(requestId);\n cursorReq.onsuccess = onsuccess;\n return promiseifyTxn(txn).then(() => result);\n }\n\n /**\n * Look for an existing room key request by id and state, and delete it if\n * found\n *\n * @param {string} requestId ID of request to update\n * @param {number} expectedState state we expect to find the request in\n *\n * @returns {Promise} resolves once the operation is completed\n */\n deleteOutgoingRoomKeyRequest(requestId, expectedState) {\n const txn = this._db.transaction(\"outgoingRoomKeyRequests\", \"readwrite\");\n const cursorReq = txn.objectStore(\"outgoingRoomKeyRequests\")\n .openCursor(requestId);\n cursorReq.onsuccess = (ev) => {\n const cursor = ev.target.result;\n if (!cursor) {\n return;\n }\n const data = cursor.value;\n if (data.state != expectedState) {\n logger.warn(\n `Cannot delete room key request in state ${data.state} `\n + `(expected ${expectedState})`,\n );\n return;\n }\n cursor.delete();\n };\n return promiseifyTxn(txn);\n }\n\n // Olm Account\n\n getAccount(txn, func) {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function() {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n storeAccount(txn, newData) {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(newData, \"-\");\n }\n\n getCrossSigningKeys(txn, func) {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"crossSigningKeys\");\n getReq.onsuccess = function() {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n getSecretStorePrivateKey(txn, func, type) {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(`ssss_cache:${type}`);\n getReq.onsuccess = function() {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n storeCrossSigningKeys(txn, keys) {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(keys, \"crossSigningKeys\");\n }\n\n storeSecretStorePrivateKey(txn, type, key) {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(key, `ssss_cache:${type}`);\n }\n\n // Olm Sessions\n\n countEndToEndSessions(txn, func) {\n const objectStore = txn.objectStore(\"sessions\");\n const countReq = objectStore.count();\n countReq.onsuccess = function() {\n try {\n func(countReq.result);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n getEndToEndSessions(deviceKey, txn, func) {\n const objectStore = txn.objectStore(\"sessions\");\n const idx = objectStore.index(\"deviceKey\");\n const getReq = idx.openCursor(deviceKey);\n const results = {};\n getReq.onsuccess = function() {\n const cursor = getReq.result;\n if (cursor) {\n results[cursor.value.sessionId] = {\n session: cursor.value.session,\n lastReceivedMessageTs: cursor.value.lastReceivedMessageTs,\n };\n cursor.continue();\n } else {\n try {\n func(results);\n } catch (e) {\n abortWithException(txn, e);\n }\n }\n };\n }\n\n getEndToEndSession(deviceKey, sessionId, txn, func) {\n const objectStore = txn.objectStore(\"sessions\");\n const getReq = objectStore.get([deviceKey, sessionId]);\n getReq.onsuccess = function() {\n try {\n if (getReq.result) {\n func({\n session: getReq.result.session,\n lastReceivedMessageTs: getReq.result.lastReceivedMessageTs,\n });\n } else {\n func(null);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n getAllEndToEndSessions(txn, func) {\n const objectStore = txn.objectStore(\"sessions\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function() {\n try {\n const cursor = getReq.result;\n if (cursor) {\n func(cursor.value);\n cursor.continue();\n } else {\n func(null);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {\n const objectStore = txn.objectStore(\"sessions\");\n objectStore.put({\n deviceKey,\n sessionId,\n session: sessionInfo.session,\n lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs,\n });\n }\n\n async storeEndToEndSessionProblem(deviceKey, type, fixed) {\n const txn = this._db.transaction(\"session_problems\", \"readwrite\");\n const objectStore = txn.objectStore(\"session_problems\");\n objectStore.put({\n deviceKey,\n type,\n fixed,\n time: Date.now(),\n });\n return promiseifyTxn(txn);\n }\n\n async getEndToEndSessionProblem(deviceKey, timestamp) {\n let result;\n const txn = this._db.transaction(\"session_problems\", \"readwrite\");\n const objectStore = txn.objectStore(\"session_problems\");\n const index = objectStore.index(\"deviceKey\");\n const req = index.getAll(deviceKey);\n req.onsuccess = (event) => {\n const problems = req.result;\n if (!problems.length) {\n result = null;\n return;\n }\n problems.sort((a, b) => {\n return a.time - b.time;\n });\n const lastProblem = problems[problems.length - 1];\n for (const problem of problems) {\n if (problem.time > timestamp) {\n result = Object.assign({}, problem, { fixed: lastProblem.fixed });\n return;\n }\n }\n if (lastProblem.fixed) {\n result = null;\n } else {\n result = lastProblem;\n }\n };\n await promiseifyTxn(txn);\n return result;\n }\n\n // FIXME: we should probably prune this when devices get deleted\n async filterOutNotifiedErrorDevices(devices) {\n const txn = this._db.transaction(\"notified_error_devices\", \"readwrite\");\n const objectStore = txn.objectStore(\"notified_error_devices\");\n\n const ret = [];\n\n await Promise.all(devices.map((device) => {\n return new Promise((resolve) => {\n const { userId, deviceInfo } = device;\n const getReq = objectStore.get([userId, deviceInfo.deviceId]);\n getReq.onsuccess = function() {\n if (!getReq.result) {\n objectStore.put({ userId, deviceId: deviceInfo.deviceId });\n ret.push(device);\n }\n resolve();\n };\n });\n }));\n\n return ret;\n }\n\n // Inbound group sessions\n\n getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {\n let session = false;\n let withheld = false;\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.get([senderCurve25519Key, sessionId]);\n getReq.onsuccess = function() {\n try {\n if (getReq.result) {\n session = getReq.result.session;\n } else {\n session = null;\n }\n if (withheld !== false) {\n func(session, withheld);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n\n const withheldObjectStore = txn.objectStore(\"inbound_group_sessions_withheld\");\n const withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]);\n withheldGetReq.onsuccess = function() {\n try {\n if (withheldGetReq.result) {\n withheld = withheldGetReq.result.session;\n } else {\n withheld = null;\n }\n if (session !== false) {\n func(session, withheld);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n getAllEndToEndInboundGroupSessions(txn, func) {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function() {\n const cursor = getReq.result;\n if (cursor) {\n try {\n func({\n senderKey: cursor.value.senderCurve25519Key,\n sessionId: cursor.value.sessionId,\n sessionData: cursor.value.session,\n });\n } catch (e) {\n abortWithException(txn, e);\n }\n cursor.continue();\n } else {\n try {\n func(null);\n } catch (e) {\n abortWithException(txn, e);\n }\n }\n };\n }\n\n addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const addReq = objectStore.add({\n senderCurve25519Key, sessionId, session: sessionData,\n });\n addReq.onerror = (ev) => {\n if (addReq.error.name === 'ConstraintError') {\n // This stops the error from triggering the txn's onerror\n ev.stopPropagation();\n // ...and this stops it from aborting the transaction\n ev.preventDefault();\n logger.log(\n \"Ignoring duplicate inbound group session: \" +\n senderCurve25519Key + \" / \" + sessionId,\n );\n } else {\n abortWithException(txn, new Error(\n \"Failed to add inbound group session: \" + addReq.error,\n ));\n }\n };\n }\n\n storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n objectStore.put({\n senderCurve25519Key, sessionId, session: sessionData,\n });\n }\n\n storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key, sessionId, sessionData, txn,\n ) {\n const objectStore = txn.objectStore(\"inbound_group_sessions_withheld\");\n objectStore.put({\n senderCurve25519Key, sessionId, session: sessionData,\n });\n }\n\n getEndToEndDeviceData(txn, func) {\n const objectStore = txn.objectStore(\"device_data\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function() {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n storeEndToEndDeviceData(deviceData, txn) {\n const objectStore = txn.objectStore(\"device_data\");\n objectStore.put(deviceData, \"-\");\n }\n\n storeEndToEndRoom(roomId, roomInfo, txn) {\n const objectStore = txn.objectStore(\"rooms\");\n objectStore.put(roomInfo, roomId);\n }\n\n getEndToEndRooms(txn, func) {\n const rooms = {};\n const objectStore = txn.objectStore(\"rooms\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function() {\n const cursor = getReq.result;\n if (cursor) {\n rooms[cursor.key] = cursor.value;\n cursor.continue();\n } else {\n try {\n func(rooms);\n } catch (e) {\n abortWithException(txn, e);\n }\n }\n };\n }\n\n // session backups\n\n getSessionsNeedingBackup(limit) {\n return new Promise((resolve, reject) => {\n const sessions = [];\n\n const txn = this._db.transaction(\n [\"sessions_needing_backup\", \"inbound_group_sessions\"],\n \"readonly\",\n );\n txn.onerror = reject;\n txn.oncomplete = function() {\n resolve(sessions);\n };\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n const sessionStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function() {\n const cursor = getReq.result;\n if (cursor) {\n const sessionGetReq = sessionStore.get(cursor.key);\n sessionGetReq.onsuccess = function() {\n sessions.push({\n senderKey: sessionGetReq.result.senderCurve25519Key,\n sessionId: sessionGetReq.result.sessionId,\n sessionData: sessionGetReq.result.session,\n });\n };\n if (!limit || sessions.length < limit) {\n cursor.continue();\n }\n }\n };\n });\n }\n\n countSessionsNeedingBackup(txn) {\n if (!txn) {\n txn = this._db.transaction(\"sessions_needing_backup\", \"readonly\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n return new Promise((resolve, reject) => {\n const req = objectStore.count();\n req.onerror = reject;\n req.onsuccess = () => resolve(req.result);\n });\n }\n\n unmarkSessionsNeedingBackup(sessions, txn) {\n if (!txn) {\n txn = this._db.transaction(\"sessions_needing_backup\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n return Promise.all(sessions.map((session) => {\n return new Promise((resolve, reject) => {\n const req = objectStore.delete([session.senderKey, session.sessionId]);\n req.onsuccess = resolve;\n req.onerror = reject;\n });\n }));\n }\n\n markSessionsNeedingBackup(sessions, txn) {\n if (!txn) {\n txn = this._db.transaction(\"sessions_needing_backup\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n return Promise.all(sessions.map((session) => {\n return new Promise((resolve, reject) => {\n const req = objectStore.put({\n senderCurve25519Key: session.senderKey,\n sessionId: session.sessionId,\n });\n req.onsuccess = resolve;\n req.onerror = reject;\n });\n }));\n }\n\n addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) {\n if (!txn) {\n txn = this._db.transaction(\n \"shared_history_inbound_group_sessions\", \"readwrite\",\n );\n }\n const objectStore = txn.objectStore(\"shared_history_inbound_group_sessions\");\n const req = objectStore.get([roomId]);\n req.onsuccess = () => {\n const { sessions } = req.result || { sessions: [] };\n sessions.push([senderKey, sessionId]);\n objectStore.put({ roomId, sessions });\n };\n }\n\n getSharedHistoryInboundGroupSessions(roomId, txn) {\n if (!txn) {\n txn = this._db.transaction(\n \"shared_history_inbound_group_sessions\", \"readonly\",\n );\n }\n const objectStore = txn.objectStore(\"shared_history_inbound_group_sessions\");\n const req = objectStore.get([roomId]);\n return new Promise((resolve, reject) => {\n req.onsuccess = () => {\n const { sessions } = req.result || { sessions: [] };\n resolve(sessions);\n };\n req.onerror = reject;\n });\n }\n\n doTxn(mode, stores, func, log = logger) {\n let startTime;\n let description;\n if (PROFILE_TRANSACTIONS) {\n const txnId = this._nextTxnId++;\n startTime = Date.now();\n description = `${mode} crypto store transaction ${txnId} in ${stores}`;\n log.debug(`Starting ${description}`);\n }\n const txn = this._db.transaction(stores, mode);\n const promise = promiseifyTxn(txn);\n const result = func(txn);\n if (PROFILE_TRANSACTIONS) {\n promise.then(() => {\n const elapsedTime = Date.now() - startTime;\n log.debug(`Finished ${description}, took ${elapsedTime} ms`);\n }, () => {\n const elapsedTime = Date.now() - startTime;\n log.error(`Failed ${description}, took ${elapsedTime} ms`);\n });\n }\n return promise.then(() => {\n return result;\n });\n }\n}\n\nexport function upgradeDatabase(db, oldVersion) {\n logger.log(\n `Upgrading IndexedDBCryptoStore from version ${oldVersion}`\n + ` to ${VERSION}`,\n );\n if (oldVersion < 1) { // The database did not previously exist.\n createDatabase(db);\n }\n if (oldVersion < 2) {\n db.createObjectStore(\"account\");\n }\n if (oldVersion < 3) {\n const sessionsStore = db.createObjectStore(\"sessions\", {\n keyPath: [\"deviceKey\", \"sessionId\"],\n });\n sessionsStore.createIndex(\"deviceKey\", \"deviceKey\");\n }\n if (oldVersion < 4) {\n db.createObjectStore(\"inbound_group_sessions\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n }\n if (oldVersion < 5) {\n db.createObjectStore(\"device_data\");\n }\n if (oldVersion < 6) {\n db.createObjectStore(\"rooms\");\n }\n if (oldVersion < 7) {\n db.createObjectStore(\"sessions_needing_backup\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n }\n if (oldVersion < 8) {\n db.createObjectStore(\"inbound_group_sessions_withheld\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n }\n if (oldVersion < 9) {\n const problemsStore = db.createObjectStore(\"session_problems\", {\n keyPath: [\"deviceKey\", \"time\"],\n });\n problemsStore.createIndex(\"deviceKey\", \"deviceKey\");\n\n db.createObjectStore(\"notified_error_devices\", {\n keyPath: [\"userId\", \"deviceId\"],\n });\n }\n if (oldVersion < 10) {\n db.createObjectStore(\"shared_history_inbound_group_sessions\", {\n keyPath: [\"roomId\"],\n });\n }\n // Expand as needed.\n}\n\nfunction createDatabase(db) {\n const outgoingRoomKeyRequestsStore =\n db.createObjectStore(\"outgoingRoomKeyRequests\", { keyPath: \"requestId\" });\n\n // we assume that the RoomKeyRequestBody will have room_id and session_id\n // properties, to make the index efficient.\n outgoingRoomKeyRequestsStore.createIndex(\"session\",\n [\"requestBody.room_id\", \"requestBody.session_id\"],\n );\n\n outgoingRoomKeyRequestsStore.createIndex(\"state\", \"state\");\n}\n\n/*\n * Aborts a transaction with a given exception\n * The transaction promise will be rejected with this exception.\n */\nfunction abortWithException(txn, e) {\n // We cheekily stick our exception onto the transaction object here\n // We could alternatively make the thing we pass back to the app\n // an object containing the transaction and exception.\n txn._mx_abortexception = e;\n try {\n txn.abort();\n } catch (e) {\n // sometimes we won't be able to abort the transaction\n // (ie. if it's aborted or completed)\n }\n}\n\nfunction promiseifyTxn(txn) {\n return new Promise((resolve, reject) => {\n txn.oncomplete = () => {\n if (txn._mx_abortexception !== undefined) {\n reject(txn._mx_abortexception);\n }\n resolve();\n };\n txn.onerror = (event) => {\n if (txn._mx_abortexception !== undefined) {\n reject(txn._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(event.target.error);\n }\n };\n txn.onabort = (event) => {\n if (txn._mx_abortexception !== undefined) {\n reject(txn._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(event.target.error);\n }\n };\n });\n}\n",
"/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../../logger';\nimport { LocalStorageCryptoStore } from './localStorage-crypto-store';\nimport { MemoryCryptoStore } from './memory-crypto-store';\nimport * as IndexedDBCryptoStoreBackend from './indexeddb-crypto-store-backend';\nimport { InvalidCryptoStoreError } from '../../errors';\nimport * as IndexedDBHelpers from \"../../indexeddb-helpers\";\n\n/**\n * Internal module. indexeddb storage for e2e.\n *\n * @module\n */\n\n/**\n * An implementation of CryptoStore, which is normally backed by an indexeddb,\n * but with fallback to MemoryCryptoStore.\n *\n * @implements {module:crypto/store/base~CryptoStore}\n */\nexport class IndexedDBCryptoStore {\n /**\n * Create a new IndexedDBCryptoStore\n *\n * @param {IDBFactory} indexedDB global indexedDB instance\n * @param {string} dbName name of db to connect to\n */\n constructor(indexedDB, dbName) {\n this._indexedDB = indexedDB;\n this._dbName = dbName;\n this._backendPromise = null;\n this._backend = null;\n }\n\n static exists(indexedDB, dbName) {\n return IndexedDBHelpers.exists(indexedDB, dbName);\n }\n\n /**\n * Ensure the database exists and is up-to-date, or fall back to\n * a local storage or in-memory store.\n *\n * This must be called before the store can be used.\n *\n * @return {Promise} resolves to either an IndexedDBCryptoStoreBackend.Backend,\n * or a MemoryCryptoStore\n */\n startup() {\n if (this._backendPromise) {\n return this._backendPromise;\n }\n\n this._backendPromise = new Promise((resolve, reject) => {\n if (!this._indexedDB) {\n reject(new Error('no indexeddb support available'));\n return;\n }\n\n logger.log(`connecting to indexeddb ${this._dbName}`);\n\n const req = this._indexedDB.open(\n this._dbName, IndexedDBCryptoStoreBackend.VERSION,\n );\n\n req.onupgradeneeded = (ev) => {\n const db = ev.target.result;\n const oldVersion = ev.oldVersion;\n IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion);\n };\n\n req.onblocked = () => {\n logger.log(\n `can't yet open IndexedDBCryptoStore because it is open elsewhere`,\n );\n };\n\n req.onerror = (ev) => {\n logger.log(\"Error connecting to indexeddb\", ev);\n reject(ev.target.error);\n };\n\n req.onsuccess = (r) => {\n const db = r.target.result;\n\n logger.log(`connected to indexeddb ${this._dbName}`);\n resolve(new IndexedDBCryptoStoreBackend.Backend(db));\n };\n }).then((backend) => {\n // Edge has IndexedDB but doesn't support compund keys which we use fairly extensively.\n // Try a dummy query which will fail if the browser doesn't support compund keys, so\n // we can fall back to a different backend.\n return backend.doTxn(\n 'readonly',\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ],\n (txn) => {\n backend.getEndToEndInboundGroupSession('', '', txn, () => {});\n }).then(() => {\n return backend;\n },\n );\n }).catch((e) => {\n if (e.name === 'VersionError') {\n logger.warn(\"Crypto DB is too new for us to use!\", e);\n // don't fall back to a different store: the user has crypto data\n // in this db so we should use it or nothing at all.\n throw new InvalidCryptoStoreError(InvalidCryptoStoreError.TOO_NEW);\n }\n logger.warn(\n `unable to connect to indexeddb ${this._dbName}` +\n `: falling back to localStorage store: ${e}`,\n );\n\n try {\n return new LocalStorageCryptoStore(global.localStorage);\n } catch (e) {\n logger.warn(\n `unable to open localStorage: falling back to in-memory store: ${e}`,\n );\n return new MemoryCryptoStore();\n }\n }).then(backend => {\n this._backend = backend;\n });\n\n return this._backendPromise;\n }\n\n /**\n * Delete all data from this store.\n *\n * @returns {Promise} resolves when the store has been cleared.\n */\n deleteAllData() {\n return new Promise((resolve, reject) => {\n if (!this._indexedDB) {\n reject(new Error('no indexeddb support available'));\n return;\n }\n\n logger.log(`Removing indexeddb instance: ${this._dbName}`);\n const req = this._indexedDB.deleteDatabase(this._dbName);\n\n req.onblocked = () => {\n logger.log(\n `can't yet delete IndexedDBCryptoStore because it is open elsewhere`,\n );\n };\n\n req.onerror = (ev) => {\n logger.log(\"Error deleting data from indexeddb\", ev);\n reject(ev.target.error);\n };\n\n req.onsuccess = () => {\n logger.log(`Removed indexeddb instance: ${this._dbName}`);\n resolve();\n };\n }).catch((e) => {\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that people can\n // still use the app.\n logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`);\n });\n }\n\n /**\n * Look for an existing outgoing room key request, and if none is found,\n * add a new one\n *\n * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request\n *\n * @returns {Promise} resolves to\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the\n * same instance as passed in, or the existing one.\n */\n getOrAddOutgoingRoomKeyRequest(request) {\n return this._backend.getOrAddOutgoingRoomKeyRequest(request);\n }\n\n /**\n * Look for an existing room key request\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * existing request to look for\n *\n * @return {Promise} resolves to the matching\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * not found\n */\n getOutgoingRoomKeyRequest(requestBody) {\n return this._backend.getOutgoingRoomKeyRequest(requestBody);\n }\n\n /**\n * Look for room key requests by state\n *\n * @param {Array<Number>} wantedStates list of acceptable states\n *\n * @return {Promise} resolves to the a\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * there are no pending requests in those states. If there are multiple\n * requests in those states, an arbitrary one is chosen.\n */\n getOutgoingRoomKeyRequestByState(wantedStates) {\n return this._backend.getOutgoingRoomKeyRequestByState(wantedStates);\n }\n\n /**\n * Look for room key requests by state \n * unlike above, return a list of all entries in one state.\n *\n * @param {Number} wantedState\n * @return {Promise<Array<*>>} Returns an array of requests in the given state\n */\n getAllOutgoingRoomKeyRequestsByState(wantedState) {\n return this._backend.getAllOutgoingRoomKeyRequestsByState(wantedState);\n }\n\n /**\n * Look for room key requests by target device and state\n *\n * @param {string} userId Target user ID\n * @param {string} deviceId Target device ID\n * @param {Array<Number>} wantedStates list of acceptable states\n *\n * @return {Promise} resolves to a list of all the\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}\n */\n getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) {\n return this._backend.getOutgoingRoomKeyRequestsByTarget(\n userId, deviceId, wantedStates,\n );\n }\n\n /**\n * Look for an existing room key request by id and state, and update it if\n * found\n *\n * @param {string} requestId ID of request to update\n * @param {number} expectedState state we expect to find the request in\n * @param {Object} updates name/value map of updates to apply\n *\n * @returns {Promise} resolves to\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}\n * updated request, or null if no matching row was found\n */\n updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {\n return this._backend.updateOutgoingRoomKeyRequest(\n requestId, expectedState, updates,\n );\n }\n\n /**\n * Look for an existing room key request by id and state, and delete it if\n * found\n *\n * @param {string} requestId ID of request to update\n * @param {number} expectedState state we expect to find the request in\n *\n * @returns {Promise} resolves once the operation is completed\n */\n deleteOutgoingRoomKeyRequest(requestId, expectedState) {\n return this._backend.deleteOutgoingRoomKeyRequest(requestId, expectedState);\n }\n\n // Olm Account\n\n /*\n * Get the account pickle from the store.\n * This requires an active transaction. See doTxn().\n *\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(string)} func Called with the account pickle\n */\n getAccount(txn, func) {\n this._backend.getAccount(txn, func);\n }\n\n /**\n * Write the account pickle to the store.\n * This requires an active transaction. See doTxn().\n *\n * @param {*} txn An active transaction. See doTxn().\n * @param {string} newData The new account pickle to store.\n */\n storeAccount(txn, newData) {\n this._backend.storeAccount(txn, newData);\n }\n\n /**\n * Get the public part of the cross-signing keys (eg. self-signing key,\n * user signing key).\n *\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(string)} func Called with the account keys object:\n * { key_type: base64 encoded seed } where key type = user_signing_key_seed or self_signing_key_seed\n */\n getCrossSigningKeys(txn, func) {\n this._backend.getCrossSigningKeys(txn, func);\n }\n\n /**\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(string)} func Called with the private key\n * @param {string} type A key type\n */\n getSecretStorePrivateKey(txn, func, type) {\n this._backend.getSecretStorePrivateKey(txn, func, type);\n }\n\n /**\n * Write the cross-signing keys back to the store\n *\n * @param {*} txn An active transaction. See doTxn().\n * @param {string} keys keys object as getCrossSigningKeys()\n */\n storeCrossSigningKeys(txn, keys) {\n this._backend.storeCrossSigningKeys(txn, keys);\n }\n\n /**\n * Write the cross-signing private keys back to the store\n *\n * @param {*} txn An active transaction. See doTxn().\n * @param {string} type The type of cross-signing private key to store\n * @param {string} key keys object as getCrossSigningKeys()\n */\n storeSecretStorePrivateKey(txn, type, key) {\n this._backend.storeSecretStorePrivateKey(txn, type, key);\n }\n\n // Olm sessions\n\n /**\n * Returns the number of end-to-end sessions in the store\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(int)} func Called with the count of sessions\n */\n countEndToEndSessions(txn, func) {\n this._backend.countEndToEndSessions(txn, func);\n }\n\n /**\n * Retrieve a specific end-to-end session between the logged-in user\n * and another device.\n * @param {string} deviceKey The public key of the other device.\n * @param {string} sessionId The ID of the session to retrieve\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(object)} func Called with A map from sessionId\n * to session information object with 'session' key being the\n * Base64 end-to-end session and lastReceivedMessageTs being the\n * timestamp in milliseconds at which the session last received\n * a message.\n */\n getEndToEndSession(deviceKey, sessionId, txn, func) {\n this._backend.getEndToEndSession(deviceKey, sessionId, txn, func);\n }\n\n /**\n * Retrieve the end-to-end sessions between the logged-in user and another\n * device.\n * @param {string} deviceKey The public key of the other device.\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(object)} func Called with A map from sessionId\n * to session information object with 'session' key being the\n * Base64 end-to-end session and lastReceivedMessageTs being the\n * timestamp in milliseconds at which the session last received\n * a message.\n */\n getEndToEndSessions(deviceKey, txn, func) {\n this._backend.getEndToEndSessions(deviceKey, txn, func);\n }\n\n /**\n * Retrieve all end-to-end sessions\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(object)} func Called one for each session with\n * an object with, deviceKey, lastReceivedMessageTs, sessionId\n * and session keys.\n */\n getAllEndToEndSessions(txn, func) {\n this._backend.getAllEndToEndSessions(txn, func);\n }\n\n /**\n * Store a session between the logged-in user and another device\n * @param {string} deviceKey The public key of the other device.\n * @param {string} sessionId The ID for this end-to-end session.\n * @param {string} sessionInfo Session information object\n * @param {*} txn An active transaction. See doTxn().\n */\n storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {\n this._backend.storeEndToEndSession(\n deviceKey, sessionId, sessionInfo, txn,\n );\n }\n\n storeEndToEndSessionProblem(deviceKey, type, fixed) {\n return this._backend.storeEndToEndSessionProblem(deviceKey, type, fixed);\n }\n\n getEndToEndSessionProblem(deviceKey, timestamp) {\n return this._backend.getEndToEndSessionProblem(deviceKey, timestamp);\n }\n\n filterOutNotifiedErrorDevices(devices) {\n return this._backend.filterOutNotifiedErrorDevices(devices);\n }\n\n // Inbound group sessions\n\n /**\n * Retrieve the end-to-end inbound group session for a given\n * server key and session ID\n * @param {string} senderCurve25519Key The sender's curve 25519 key\n * @param {string} sessionId The ID of the session\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(object)} func Called with A map from sessionId\n * to Base64 end-to-end session.\n */\n getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {\n this._backend.getEndToEndInboundGroupSession(\n senderCurve25519Key, sessionId, txn, func,\n );\n }\n\n /**\n * Fetches all inbound group sessions in the store\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(object)} func Called once for each group session\n * in the store with an object having keys {senderKey, sessionId,\n * sessionData}, then once with null to indicate the end of the list.\n */\n getAllEndToEndInboundGroupSessions(txn, func) {\n this._backend.getAllEndToEndInboundGroupSessions(txn, func);\n }\n\n /**\n * Adds an end-to-end inbound group session to the store.\n * If there already exists an inbound group session with the same\n * senderCurve25519Key and sessionID, the session will not be added.\n * @param {string} senderCurve25519Key The sender's curve 25519 key\n * @param {string} sessionId The ID of the session\n * @param {object} sessionData The session data structure\n * @param {*} txn An active transaction. See doTxn().\n */\n addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n this._backend.addEndToEndInboundGroupSession(\n senderCurve25519Key, sessionId, sessionData, txn,\n );\n }\n\n /**\n * Writes an end-to-end inbound group session to the store.\n * If there already exists an inbound group session with the same\n * senderCurve25519Key and sessionID, it will be overwritten.\n * @param {string} senderCurve25519Key The sender's curve 25519 key\n * @param {string} sessionId The ID of the session\n * @param {object} sessionData The session data structure\n * @param {*} txn An active transaction. See doTxn().\n */\n storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n this._backend.storeEndToEndInboundGroupSession(\n senderCurve25519Key, sessionId, sessionData, txn,\n );\n }\n\n storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key, sessionId, sessionData, txn,\n ) {\n this._backend.storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key, sessionId, sessionData, txn,\n );\n }\n\n // End-to-end device tracking\n\n /**\n * Store the state of all tracked devices\n * This contains devices for each user, a tracking state for each user\n * and a sync token matching the point in time the snapshot represents.\n * These all need to be written out in full each time such that the snapshot\n * is always consistent, so they are stored in one object.\n *\n * @param {Object} deviceData\n * @param {*} txn An active transaction. See doTxn().\n */\n storeEndToEndDeviceData(deviceData, txn) {\n this._backend.storeEndToEndDeviceData(deviceData, txn);\n }\n\n /**\n * Get the state of all tracked devices\n *\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(Object)} func Function called with the\n * device data\n */\n getEndToEndDeviceData(txn, func) {\n this._backend.getEndToEndDeviceData(txn, func);\n }\n\n // End to End Rooms\n\n /**\n * Store the end-to-end state for a room.\n * @param {string} roomId The room's ID.\n * @param {object} roomInfo The end-to-end info for the room.\n * @param {*} txn An active transaction. See doTxn().\n */\n storeEndToEndRoom(roomId, roomInfo, txn) {\n this._backend.storeEndToEndRoom(roomId, roomInfo, txn);\n }\n\n /**\n * Get an object of roomId->roomInfo for all e2e rooms in the store\n * @param {*} txn An active transaction. See doTxn().\n * @param {function(Object)} func Function called with the end to end encrypted rooms\n */\n getEndToEndRooms(txn, func) {\n this._backend.getEndToEndRooms(txn, func);\n }\n\n // session backups\n\n /**\n * Get the inbound group sessions that need to be backed up.\n * @param {integer} limit The maximum number of sessions to retrieve. 0\n * for no limit.\n * @returns {Promise} resolves to an array of inbound group sessions\n */\n getSessionsNeedingBackup(limit) {\n return this._backend.getSessionsNeedingBackup(limit);\n }\n\n /**\n * Count the inbound group sessions that need to be backed up.\n * @param {*} txn An active transaction. See doTxn(). (optional)\n * @returns {Promise} resolves to the number of sessions\n */\n countSessionsNeedingBackup(txn) {\n return this._backend.countSessionsNeedingBackup(txn);\n }\n\n /**\n * Unmark sessions as needing to be backed up.\n * @param {Array<object>} sessions The sessions that need to be backed up.\n * @param {*} txn An active transaction. See doTxn(). (optional)\n * @returns {Promise} resolves when the sessions are unmarked\n */\n unmarkSessionsNeedingBackup(sessions, txn) {\n return this._backend.unmarkSessionsNeedingBackup(sessions, txn);\n }\n\n /**\n * Mark sessions as needing to be backed up.\n * @param {Array<object>} sessions The sessions that need to be backed up.\n * @param {*} txn An active transaction. See doTxn(). (optional)\n * @returns {Promise} resolves when the sessions are marked\n */\n markSessionsNeedingBackup(sessions, txn) {\n return this._backend.markSessionsNeedingBackup(sessions, txn);\n }\n\n /**\n * Add a shared-history group session for a room.\n * @param {string} roomId The room that the key belongs to\n * @param {string} senderKey The sender's curve 25519 key\n * @param {string} sessionId The ID of the session\n * @param {*} txn An active transaction. See doTxn(). (optional)\n */\n addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) {\n this._backend.addSharedHistoryInboundGroupSession(\n roomId, senderKey, sessionId, txn,\n );\n }\n\n /**\n * Get the shared-history group session for a room.\n * @param {string} roomId The room that the key belongs to\n * @param {*} txn An active transaction. See doTxn(). (optional)\n * @returns {Promise} Resolves to an array of [senderKey, sessionId]\n */\n getSharedHistoryInboundGroupSessions(roomId, txn) {\n return this._backend.getSharedHistoryInboundGroupSessions(roomId, txn);\n }\n\n /**\n * Perform a transaction on the crypto store. Any store methods\n * that require a transaction (txn) object to be passed in may\n * only be called within a callback of either this function or\n * one of the store functions operating on the same transaction.\n *\n * @param {string} mode 'readwrite' if you need to call setter\n * functions with this transaction. Otherwise, 'readonly'.\n * @param {string[]} stores List IndexedDBCryptoStore.STORE_*\n * options representing all types of object that will be\n * accessed or written to with this transaction.\n * @param {function(*)} func Function called with the\n * transaction object: an opaque object that should be passed\n * to store functions.\n * @param {Logger} [log] A possibly customised log\n * @return {Promise} Promise that resolves with the result of the `func`\n * when the transaction is complete. If the backend is\n * async (ie. the indexeddb backend) any of the callback\n * functions throwing an exception will cause this promise to\n * reject with that exception. On synchronous backends, the\n * exception will propagate to the caller of the getFoo method.\n */\n doTxn(mode, stores, func, log) {\n return this._backend.doTxn(mode, stores, func, log);\n }\n}\n\nIndexedDBCryptoStore.STORE_ACCOUNT = 'account';\nIndexedDBCryptoStore.STORE_SESSIONS = 'sessions';\nIndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS = 'inbound_group_sessions';\nIndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD\n = 'inbound_group_sessions_withheld';\nIndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS\n = 'shared_history_inbound_group_sessions';\nIndexedDBCryptoStore.STORE_DEVICE_DATA = 'device_data';\nIndexedDBCryptoStore.STORE_ROOMS = 'rooms';\nIndexedDBCryptoStore.STORE_BACKUP = 'sessions_needing_backup';\n",
"/*\nCopyright 2017, 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../../logger';\nimport { MemoryCryptoStore } from './memory-crypto-store';\n\n/**\n * Internal module. Partial localStorage backed storage for e2e.\n * This is not a full crypto store, just the in-memory store with\n * some things backed by localStorage. It exists because indexedDB\n * is broken in Firefox private mode or set to, \"will not remember\n * history\".\n *\n * @module\n */\n\nconst E2E_PREFIX = \"crypto.\";\nconst KEY_END_TO_END_ACCOUNT = E2E_PREFIX + \"account\";\nconst KEY_CROSS_SIGNING_KEYS = E2E_PREFIX + \"cross_signing_keys\";\nconst KEY_NOTIFIED_ERROR_DEVICES = E2E_PREFIX + \"notified_error_devices\";\nconst KEY_DEVICE_DATA = E2E_PREFIX + \"device_data\";\nconst KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + \"inboundgroupsessions/\";\nconst KEY_INBOUND_SESSION_WITHHELD_PREFIX = E2E_PREFIX + \"inboundgroupsessions.withheld/\";\nconst KEY_ROOMS_PREFIX = E2E_PREFIX + \"rooms/\";\nconst KEY_SESSIONS_NEEDING_BACKUP = E2E_PREFIX + \"sessionsneedingbackup\";\n\nfunction keyEndToEndSessions(deviceKey) {\n return E2E_PREFIX + \"sessions/\" + deviceKey;\n}\n\nfunction keyEndToEndSessionProblems(deviceKey) {\n return E2E_PREFIX + \"session.problems/\" + deviceKey;\n}\n\nfunction keyEndToEndInboundGroupSession(senderKey, sessionId) {\n return KEY_INBOUND_SESSION_PREFIX + senderKey + \"/\" + sessionId;\n}\n\nfunction keyEndToEndInboundGroupSessionWithheld(senderKey, sessionId) {\n return KEY_INBOUND_SESSION_WITHHELD_PREFIX + senderKey + \"/\" + sessionId;\n}\n\nfunction keyEndToEndRoomsPrefix(roomId) {\n return KEY_ROOMS_PREFIX + roomId;\n}\n\n/**\n * @implements {module:crypto/store/base~CryptoStore}\n */\nexport class LocalStorageCryptoStore extends MemoryCryptoStore {\n constructor(webStore) {\n super();\n this.store = webStore;\n }\n\n static exists(webStore) {\n const length = webStore.length;\n for (let i = 0; i < length; i++) {\n if (webStore.key(i).startsWith(E2E_PREFIX)) {\n return true;\n }\n }\n return false;\n }\n\n // Olm Sessions\n\n countEndToEndSessions(txn, func) {\n let count = 0;\n for (let i = 0; i < this.store.length; ++i) {\n if (this.store.key(i).startsWith(keyEndToEndSessions(''))) ++count;\n }\n func(count);\n }\n\n _getEndToEndSessions(deviceKey, txn, func) {\n const sessions = getJsonItem(this.store, keyEndToEndSessions(deviceKey));\n const fixedSessions = {};\n\n // fix up any old sessions to be objects rather than just the base64 pickle\n for (const [sid, val] of Object.entries(sessions || {})) {\n if (typeof val === 'string') {\n fixedSessions[sid] = {\n session: val,\n };\n } else {\n fixedSessions[sid] = val;\n }\n }\n\n return fixedSessions;\n }\n\n getEndToEndSession(deviceKey, sessionId, txn, func) {\n const sessions = this._getEndToEndSessions(deviceKey);\n func(sessions[sessionId] || {});\n }\n\n getEndToEndSessions(deviceKey, txn, func) {\n func(this._getEndToEndSessions(deviceKey) || {});\n }\n\n getAllEndToEndSessions(txn, func) {\n for (let i = 0; i < this.store.length; ++i) {\n if (this.store.key(i).startsWith(keyEndToEndSessions(''))) {\n const deviceKey = this.store.key(i).split('/')[1];\n for (const sess of Object.values(this._getEndToEndSessions(deviceKey))) {\n func(sess);\n }\n }\n }\n }\n\n storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {\n const sessions = this._getEndToEndSessions(deviceKey) || {};\n sessions[sessionId] = sessionInfo;\n setJsonItem(\n this.store, keyEndToEndSessions(deviceKey), sessions,\n );\n }\n\n async storeEndToEndSessionProblem(deviceKey, type, fixed) {\n const key = keyEndToEndSessionProblems(deviceKey);\n const problems = getJsonItem(this.store, key) || [];\n problems.push({ type, fixed, time: Date.now() });\n problems.sort((a, b) => {\n return a.time - b.time;\n });\n setJsonItem(this.store, key, problems);\n }\n\n async getEndToEndSessionProblem(deviceKey, timestamp) {\n const key = keyEndToEndSessionProblems(deviceKey);\n const problems = getJsonItem(this.store, key) || [];\n if (!problems.length) {\n return null;\n }\n const lastProblem = problems[problems.length - 1];\n for (const problem of problems) {\n if (problem.time > timestamp) {\n return Object.assign({}, problem, { fixed: lastProblem.fixed });\n }\n }\n if (lastProblem.fixed) {\n return null;\n } else {\n return lastProblem;\n }\n }\n\n async filterOutNotifiedErrorDevices(devices) {\n const notifiedErrorDevices =\n getJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES) || {};\n const ret = [];\n\n for (const device of devices) {\n const { userId, deviceInfo } = device;\n if (userId in notifiedErrorDevices) {\n if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {\n ret.push(device);\n notifiedErrorDevices[userId][deviceInfo.deviceId] = true;\n }\n } else {\n ret.push(device);\n notifiedErrorDevices[userId] = { [deviceInfo.deviceId]: true };\n }\n }\n\n setJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES, notifiedErrorDevices);\n\n return ret;\n }\n\n // Inbound Group Sessions\n\n getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {\n func(\n getJsonItem(\n this.store,\n keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId),\n ),\n getJsonItem(\n this.store,\n keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId),\n ),\n );\n }\n\n getAllEndToEndInboundGroupSessions(txn, func) {\n for (let i = 0; i < this.store.length; ++i) {\n const key = this.store.key(i);\n if (key.startsWith(KEY_INBOUND_SESSION_PREFIX)) {\n // we can't use split, as the components we are trying to split out\n // might themselves contain '/' characters. We rely on the\n // senderKey being a (32-byte) curve25519 key, base64-encoded\n // (hence 43 characters long).\n\n func({\n senderKey: key.substr(KEY_INBOUND_SESSION_PREFIX.length, 43),\n sessionId: key.substr(KEY_INBOUND_SESSION_PREFIX.length + 44),\n sessionData: getJsonItem(this.store, key),\n });\n }\n }\n func(null);\n }\n\n addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n const existing = getJsonItem(\n this.store,\n keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId),\n );\n if (!existing) {\n this.storeEndToEndInboundGroupSession(\n senderCurve25519Key, sessionId, sessionData, txn,\n );\n }\n }\n\n storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n setJsonItem(\n this.store,\n keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId),\n sessionData,\n );\n }\n\n storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key, sessionId, sessionData, txn,\n ) {\n setJsonItem(\n this.store,\n keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId),\n sessionData,\n );\n }\n\n getEndToEndDeviceData(txn, func) {\n func(getJsonItem(\n this.store, KEY_DEVICE_DATA,\n ));\n }\n\n storeEndToEndDeviceData(deviceData, txn) {\n setJsonItem(\n this.store, KEY_DEVICE_DATA, deviceData,\n );\n }\n\n storeEndToEndRoom(roomId, roomInfo, txn) {\n setJsonItem(\n this.store, keyEndToEndRoomsPrefix(roomId), roomInfo,\n );\n }\n\n getEndToEndRooms(txn, func) {\n const result = {};\n const prefix = keyEndToEndRoomsPrefix('');\n\n for (let i = 0; i < this.store.length; ++i) {\n const key = this.store.key(i);\n if (key.startsWith(prefix)) {\n const roomId = key.substr(prefix.length);\n result[roomId] = getJsonItem(this.store, key);\n }\n }\n func(result);\n }\n\n getSessionsNeedingBackup(limit) {\n const sessionsNeedingBackup\n = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n const sessions = [];\n\n for (const session in sessionsNeedingBackup) {\n if (Object.prototype.hasOwnProperty.call(sessionsNeedingBackup, session)) {\n // see getAllEndToEndInboundGroupSessions for the magic number explanations\n const senderKey = session.substr(0, 43);\n const sessionId = session.substr(44);\n this.getEndToEndInboundGroupSession(\n senderKey, sessionId, null,\n (sessionData) => {\n sessions.push({\n senderKey: senderKey,\n sessionId: sessionId,\n sessionData: sessionData,\n });\n },\n );\n if (limit && session.length >= limit) {\n break;\n }\n }\n }\n return Promise.resolve(sessions);\n }\n\n countSessionsNeedingBackup() {\n const sessionsNeedingBackup\n = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n return Promise.resolve(Object.keys(sessionsNeedingBackup).length);\n }\n\n unmarkSessionsNeedingBackup(sessions) {\n const sessionsNeedingBackup\n = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n for (const session of sessions) {\n delete sessionsNeedingBackup[session.senderKey + '/' + session.sessionId];\n }\n setJsonItem(\n this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup,\n );\n return Promise.resolve();\n }\n\n markSessionsNeedingBackup(sessions) {\n const sessionsNeedingBackup\n = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n for (const session of sessions) {\n sessionsNeedingBackup[session.senderKey + '/' + session.sessionId] = true;\n }\n setJsonItem(\n this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup,\n );\n return Promise.resolve();\n }\n\n /**\n * Delete all data from this store.\n *\n * @returns {Promise} Promise which resolves when the store has been cleared.\n */\n deleteAllData() {\n this.store.removeItem(KEY_END_TO_END_ACCOUNT);\n return Promise.resolve();\n }\n\n // Olm account\n\n getAccount(txn, func) {\n const account = getJsonItem(this.store, KEY_END_TO_END_ACCOUNT);\n func(account);\n }\n\n storeAccount(txn, newData) {\n setJsonItem(\n this.store, KEY_END_TO_END_ACCOUNT, newData,\n );\n }\n\n getCrossSigningKeys(txn, func) {\n const keys = getJsonItem(this.store, KEY_CROSS_SIGNING_KEYS);\n func(keys);\n }\n\n getSecretStorePrivateKey(txn, func, type) {\n const key = getJsonItem(this.store, E2E_PREFIX + `ssss_cache.${type}`);\n func(key);\n }\n\n storeCrossSigningKeys(txn, keys) {\n setJsonItem(\n this.store, KEY_CROSS_SIGNING_KEYS, keys,\n );\n }\n\n storeSecretStorePrivateKey(txn, type, key) {\n setJsonItem(\n this.store, E2E_PREFIX + `ssss_cache.${type}`, key,\n );\n }\n\n doTxn(mode, stores, func) {\n return Promise.resolve(func(null));\n }\n}\n\nfunction getJsonItem(store, key) {\n try {\n // if the key is absent, store.getItem() returns null, and\n // JSON.parse(null) === null, so this returns null.\n return JSON.parse(store.getItem(key));\n } catch (e) {\n logger.log(\"Error: Failed to get key %s: %s\", key, e.stack || e);\n logger.log(e.stack);\n }\n return null;\n}\n\nfunction setJsonItem(store, key, val) {\n store.setItem(key, JSON.stringify(val));\n}\n",
"/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../../logger';\nimport * as utils from \"../../utils\";\n\n/**\n * Internal module. in-memory storage for e2e.\n *\n * @module\n */\n\n/**\n * @implements {module:crypto/store/base~CryptoStore}\n */\nexport class MemoryCryptoStore {\n constructor() {\n this._outgoingRoomKeyRequests = [];\n this._account = null;\n this._crossSigningKeys = null;\n this._privateKeys = {};\n this._backupKeys = {};\n\n // Map of {devicekey -> {sessionId -> session pickle}}\n this._sessions = {};\n // Map of {devicekey -> array of problems}\n this._sessionProblems = {};\n // Map of {userId -> deviceId -> true}\n this._notifiedErrorDevices = {};\n // Map of {senderCurve25519Key+'/'+sessionId -> session data object}\n this._inboundGroupSessions = {};\n this._inboundGroupSessionsWithheld = {};\n // Opaque device data object\n this._deviceData = null;\n // roomId -> Opaque roomInfo object\n this._rooms = {};\n // Set of {senderCurve25519Key+'/'+sessionId}\n this._sessionsNeedingBackup = {};\n // roomId -> array of [senderKey, sessionId]\n this._sharedHistoryInboundGroupSessions = {};\n }\n\n /**\n * Ensure the database exists and is up-to-date.\n *\n * This must be called before the store can be used.\n *\n * @return {Promise} resolves to the store.\n */\n async startup() {\n // No startup work to do for the memory store.\n return this;\n }\n\n /**\n * Delete all data from this store.\n *\n * @returns {Promise} Promise which resolves when the store has been cleared.\n */\n deleteAllData() {\n return Promise.resolve();\n }\n\n /**\n * Look for an existing outgoing room key request, and if none is found,\n * add a new one\n *\n * @param {module:crypto/store/base~OutgoingRoomKeyRequest} request\n *\n * @returns {Promise} resolves to\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the\n * same instance as passed in, or the existing one.\n */\n getOrAddOutgoingRoomKeyRequest(request) {\n const requestBody = request.requestBody;\n\n return utils.promiseTry(() => {\n // first see if we already have an entry for this request.\n const existing = this._getOutgoingRoomKeyRequest(requestBody);\n\n if (existing) {\n // this entry matches the request - return it.\n logger.log(\n `already have key request outstanding for ` +\n `${requestBody.room_id} / ${requestBody.session_id}: ` +\n `not sending another`,\n );\n return existing;\n }\n\n // we got to the end of the list without finding a match\n // - add the new request.\n logger.log(\n `enqueueing key request for ${requestBody.room_id} / ` +\n requestBody.session_id,\n );\n this._outgoingRoomKeyRequests.push(request);\n return request;\n });\n }\n\n /**\n * Look for an existing room key request\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * existing request to look for\n *\n * @return {Promise} resolves to the matching\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * not found\n */\n getOutgoingRoomKeyRequest(requestBody) {\n return Promise.resolve(this._getOutgoingRoomKeyRequest(requestBody));\n }\n\n /**\n * Looks for existing room key request, and returns the result synchronously.\n *\n * @internal\n *\n * @param {module:crypto~RoomKeyRequestBody} requestBody\n * existing request to look for\n *\n * @return {module:crypto/store/base~OutgoingRoomKeyRequest?}\n * the matching request, or null if not found\n */\n _getOutgoingRoomKeyRequest(requestBody) {\n for (const existing of this._outgoingRoomKeyRequests) {\n if (utils.deepCompare(existing.requestBody, requestBody)) {\n return existing;\n }\n }\n return null;\n }\n\n /**\n * Look for room key requests by state\n *\n * @param {Array<Number>} wantedStates list of acceptable states\n *\n * @return {Promise} resolves to the a\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if\n * there are no pending requests in those states\n */\n getOutgoingRoomKeyRequestByState(wantedStates) {\n for (const req of this._outgoingRoomKeyRequests) {\n for (const state of wantedStates) {\n if (req.state === state) {\n return Promise.resolve(req);\n }\n }\n }\n return Promise.resolve(null);\n }\n\n /**\n *\n * @param {Number} wantedState\n * @return {Promise<Array<*>>} All OutgoingRoomKeyRequests in state\n */\n getAllOutgoingRoomKeyRequestsByState(wantedState) {\n return Promise.resolve(\n this._outgoingRoomKeyRequests.filter(\n (r) => r.state == wantedState,\n ),\n );\n }\n\n getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) {\n const results = [];\n\n for (const req of this._outgoingRoomKeyRequests) {\n for (const state of wantedStates) {\n if (req.state === state && req.recipients.includes({ userId, deviceId })) {\n results.push(req);\n }\n }\n }\n return Promise.resolve(results);\n }\n\n /**\n * Look for an existing room key request by id and state, and update it if\n * found\n *\n * @param {string} requestId ID of request to update\n * @param {number} expectedState state we expect to find the request in\n * @param {Object} updates name/value map of updates to apply\n *\n * @returns {Promise} resolves to\n * {@link module:crypto/store/base~OutgoingRoomKeyRequest}\n * updated request, or null if no matching row was found\n */\n updateOutgoingRoomKeyRequest(requestId, expectedState, updates) {\n for (const req of this._outgoingRoomKeyRequests) {\n if (req.requestId !== requestId) {\n continue;\n }\n\n if (req.state != expectedState) {\n logger.warn(\n `Cannot update room key request from ${expectedState} ` +\n `as it was already updated to ${req.state}`,\n );\n return Promise.resolve(null);\n }\n Object.assign(req, updates);\n return Promise.resolve(req);\n }\n\n return Promise.resolve(null);\n }\n\n /**\n * Look for an existing room key request by id and state, and delete it if\n * found\n *\n * @param {string} requestId ID of request to update\n * @param {number} expectedState state we expect to find the request in\n *\n * @returns {Promise} resolves once the operation is completed\n */\n deleteOutgoingRoomKeyRequest(requestId, expectedState) {\n for (let i = 0; i < this._outgoingRoomKeyRequests.length; i++) {\n const req = this._outgoingRoomKeyRequests[i];\n\n if (req.requestId !== requestId) {\n continue;\n }\n\n if (req.state != expectedState) {\n logger.warn(\n `Cannot delete room key request in state ${req.state} `\n + `(expected ${expectedState})`,\n );\n return Promise.resolve(null);\n }\n\n this._outgoingRoomKeyRequests.splice(i, 1);\n return Promise.resolve(req);\n }\n\n return Promise.resolve(null);\n }\n\n // Olm Account\n\n getAccount(txn, func) {\n func(this._account);\n }\n\n storeAccount(txn, newData) {\n this._account = newData;\n }\n\n getCrossSigningKeys(txn, func) {\n func(this._crossSigningKeys);\n }\n\n getSecretStorePrivateKey(txn, func, type) {\n const result = this._privateKeys[type];\n return func(result || null);\n }\n\n storeCrossSigningKeys(txn, keys) {\n this._crossSigningKeys = keys;\n }\n\n storeSecretStorePrivateKey(txn, type, key) {\n this._privateKeys[type] = key;\n }\n\n // Olm Sessions\n\n countEndToEndSessions(txn, func) {\n return Object.keys(this._sessions).length;\n }\n\n getEndToEndSession(deviceKey, sessionId, txn, func) {\n const deviceSessions = this._sessions[deviceKey] || {};\n func(deviceSessions[sessionId] || null);\n }\n\n getEndToEndSessions(deviceKey, txn, func) {\n func(this._sessions[deviceKey] || {});\n }\n\n getAllEndToEndSessions(txn, func) {\n Object.entries(this._sessions).forEach(([deviceKey, deviceSessions]) => {\n Object.entries(deviceSessions).forEach(([sessionId, session]) => {\n func({\n ...session,\n deviceKey,\n sessionId,\n });\n });\n });\n }\n\n storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) {\n let deviceSessions = this._sessions[deviceKey];\n if (deviceSessions === undefined) {\n deviceSessions = {};\n this._sessions[deviceKey] = deviceSessions;\n }\n deviceSessions[sessionId] = sessionInfo;\n }\n\n async storeEndToEndSessionProblem(deviceKey, type, fixed) {\n const problems = this._sessionProblems[deviceKey]\n = this._sessionProblems[deviceKey] || [];\n problems.push({ type, fixed, time: Date.now() });\n problems.sort((a, b) => {\n return a.time - b.time;\n });\n }\n\n async getEndToEndSessionProblem(deviceKey, timestamp) {\n const problems = this._sessionProblems[deviceKey] || [];\n if (!problems.length) {\n return null;\n }\n const lastProblem = problems[problems.length - 1];\n for (const problem of problems) {\n if (problem.time > timestamp) {\n return Object.assign({}, problem, { fixed: lastProblem.fixed });\n }\n }\n if (lastProblem.fixed) {\n return null;\n } else {\n return lastProblem;\n }\n }\n\n async filterOutNotifiedErrorDevices(devices) {\n const notifiedErrorDevices = this._notifiedErrorDevices;\n const ret = [];\n\n for (const device of devices) {\n const { userId, deviceInfo } = device;\n if (userId in notifiedErrorDevices) {\n if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {\n ret.push(device);\n notifiedErrorDevices[userId][deviceInfo.deviceId] = true;\n }\n } else {\n ret.push(device);\n notifiedErrorDevices[userId] = { [deviceInfo.deviceId]: true };\n }\n }\n\n return ret;\n }\n\n // Inbound Group Sessions\n\n getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) {\n const k = senderCurve25519Key+'/'+sessionId;\n func(\n this._inboundGroupSessions[k] || null,\n this._inboundGroupSessionsWithheld[k] || null,\n );\n }\n\n getAllEndToEndInboundGroupSessions(txn, func) {\n for (const key of Object.keys(this._inboundGroupSessions)) {\n // we can't use split, as the components we are trying to split out\n // might themselves contain '/' characters. We rely on the\n // senderKey being a (32-byte) curve25519 key, base64-encoded\n // (hence 43 characters long).\n\n func({\n senderKey: key.substr(0, 43),\n sessionId: key.substr(44),\n sessionData: this._inboundGroupSessions[key],\n });\n }\n func(null);\n }\n\n addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n const k = senderCurve25519Key+'/'+sessionId;\n if (this._inboundGroupSessions[k] === undefined) {\n this._inboundGroupSessions[k] = sessionData;\n }\n }\n\n storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) {\n this._inboundGroupSessions[senderCurve25519Key+'/'+sessionId] = sessionData;\n }\n\n storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key, sessionId, sessionData, txn,\n ) {\n const k = senderCurve25519Key+'/'+sessionId;\n this._inboundGroupSessionsWithheld[k] = sessionData;\n }\n\n // Device Data\n\n getEndToEndDeviceData(txn, func) {\n func(this._deviceData);\n }\n\n storeEndToEndDeviceData(deviceData, txn) {\n this._deviceData = deviceData;\n }\n\n // E2E rooms\n\n storeEndToEndRoom(roomId, roomInfo, txn) {\n this._rooms[roomId] = roomInfo;\n }\n\n getEndToEndRooms(txn, func) {\n func(this._rooms);\n }\n\n getSessionsNeedingBackup(limit) {\n const sessions = [];\n for (const session in this._sessionsNeedingBackup) {\n if (this._inboundGroupSessions[session]) {\n sessions.push({\n senderKey: session.substr(0, 43),\n sessionId: session.substr(44),\n sessionData: this._inboundGroupSessions[session],\n });\n if (limit && session.length >= limit) {\n break;\n }\n }\n }\n return Promise.resolve(sessions);\n }\n\n countSessionsNeedingBackup() {\n return Promise.resolve(Object.keys(this._sessionsNeedingBackup).length);\n }\n\n unmarkSessionsNeedingBackup(sessions) {\n for (const session of sessions) {\n const sessionKey = session.senderKey + '/' + session.sessionId;\n delete this._sessionsNeedingBackup[sessionKey];\n }\n return Promise.resolve();\n }\n\n markSessionsNeedingBackup(sessions) {\n for (const session of sessions) {\n const sessionKey = session.senderKey + '/' + session.sessionId;\n this._sessionsNeedingBackup[sessionKey] = true;\n }\n return Promise.resolve();\n }\n\n addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId) {\n const sessions = this._sharedHistoryInboundGroupSessions[roomId] || [];\n sessions.push([senderKey, sessionId]);\n this._sharedHistoryInboundGroupSessions[roomId] = sessions;\n }\n\n getSharedHistoryInboundGroupSessions(roomId) {\n return Promise.resolve(this._sharedHistoryInboundGroupSessions[roomId] || []);\n }\n\n // Session key backups\n\n doTxn(mode, stores, func) {\n return Promise.resolve(func(null));\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Base class for verification methods.\n * @module crypto/verification/Base\n */\n\nimport { MatrixEvent } from '../../models/event';\nimport { EventEmitter } from 'events';\nimport { logger } from '../../logger';\nimport { DeviceInfo } from '../deviceinfo';\nimport { newTimeoutError } from \"./Error\";\nimport { requestKeysDuringVerification } from \"../CrossSigning\";\n\nconst timeoutException = new Error(\"Verification timed out\");\n\nexport class SwitchStartEventError extends Error {\n constructor(startEvent) {\n super();\n this.startEvent = startEvent;\n }\n}\n\nexport class VerificationBase extends EventEmitter {\n /**\n * Base class for verification methods.\n *\n * <p>Once a verifier object is created, the verification can be started by\n * calling the verify() method, which will return a promise that will\n * resolve when the verification is completed, or reject if it could not\n * complete.</p>\n *\n * <p>Subclasses must have a NAME class property.</p>\n *\n * @class\n *\n * @param {Object} channel the verification channel to send verification messages over.\n * TODO: Channel types\n *\n * @param {MatrixClient} baseApis base matrix api interface\n *\n * @param {string} userId the user ID that is being verified\n *\n * @param {string} deviceId the device ID that is being verified\n *\n * @param {object} [startEvent] the m.key.verification.start event that\n * initiated this verification, if any\n *\n * @param {object} [request] the key verification request object related to\n * this verification, if any\n */\n constructor(channel, baseApis, userId, deviceId, startEvent, request) {\n super();\n this._channel = channel;\n this._baseApis = baseApis;\n this.userId = userId;\n this.deviceId = deviceId;\n this.startEvent = startEvent;\n this.request = request;\n\n this.cancelled = false;\n this._done = false;\n this._promise = null;\n this._transactionTimeoutTimer = null;\n }\n\n get initiatedByMe() {\n // if there is no start event yet,\n // we probably want to send it,\n // which happens if we initiate\n if (!this.startEvent) {\n return true;\n }\n const sender = this.startEvent.getSender();\n const content = this.startEvent.getContent();\n return sender === this._baseApis.getUserId() &&\n content.from_device === this._baseApis.getDeviceId();\n }\n\n _resetTimer() {\n logger.info(\"Refreshing/starting the verification transaction timeout timer\");\n if (this._transactionTimeoutTimer !== null) {\n clearTimeout(this._transactionTimeoutTimer);\n }\n this._transactionTimeoutTimer = setTimeout(() => {\n if (!this._done && !this.cancelled) {\n logger.info(\"Triggering verification timeout\");\n this.cancel(timeoutException);\n }\n }, 10 * 60 * 1000); // 10 minutes\n }\n\n _endTimer() {\n if (this._transactionTimeoutTimer !== null) {\n clearTimeout(this._transactionTimeoutTimer);\n this._transactionTimeoutTimer = null;\n }\n }\n\n _send(type, uncompletedContent) {\n return this._channel.send(type, uncompletedContent);\n }\n\n _waitForEvent(type) {\n if (this._done) {\n return Promise.reject(new Error(\"Verification is already done\"));\n }\n const existingEvent = this.request.getEventFromOtherParty(type);\n if (existingEvent) {\n return Promise.resolve(existingEvent);\n }\n\n this._expectedEvent = type;\n return new Promise((resolve, reject) => {\n this._resolveEvent = resolve;\n this._rejectEvent = reject;\n });\n }\n\n canSwitchStartEvent() {\n return false;\n }\n\n switchStartEvent(event) {\n if (this.canSwitchStartEvent(event)) {\n logger.log(\"Verification Base: switching verification start event\",\n { restartingFlow: !!this._rejectEvent });\n if (this._rejectEvent) {\n const reject = this._rejectEvent;\n this._rejectEvent = undefined;\n reject(new SwitchStartEventError(event));\n } else {\n this.startEvent = event;\n }\n }\n }\n\n handleEvent(e) {\n if (this._done) {\n return;\n } else if (e.getType() === this._expectedEvent) {\n // if we receive an expected m.key.verification.done, then just\n // ignore it, since we don't need to do anything about it\n if (this._expectedEvent !== \"m.key.verification.done\") {\n this._expectedEvent = undefined;\n this._rejectEvent = undefined;\n this._resetTimer();\n this._resolveEvent(e);\n }\n } else if (e.getType() === \"m.key.verification.cancel\") {\n const reject = this._reject;\n this._reject = undefined;\n // there is only promise to reject if verify has been called\n if (reject) {\n const content = e.getContent();\n const { reason, code } = content;\n reject(new Error(`Other side cancelled verification ` +\n `because ${reason} (${code})`));\n }\n } else if (this._expectedEvent) {\n // only cancel if there is an event expected.\n // if there is no event expected, it means verify() wasn't called\n // and we're just replaying the timeline events when syncing\n // after a refresh when the events haven't been stored in the cache yet.\n const exception = new Error(\n \"Unexpected message: expecting \" + this._expectedEvent\n + \" but got \" + e.getType(),\n );\n this._expectedEvent = undefined;\n if (this._rejectEvent) {\n const reject = this._rejectEvent;\n this._rejectEvent = undefined;\n reject(exception);\n }\n this.cancel(exception);\n }\n }\n\n done() {\n this._endTimer(); // always kill the activity timer\n if (!this._done) {\n this.request.onVerifierFinished();\n this._resolve();\n return requestKeysDuringVerification(this._baseApis, this.userId, this.deviceId);\n }\n }\n\n cancel(e) {\n this._endTimer(); // always kill the activity timer\n if (!this._done) {\n this.cancelled = true;\n this.request.onVerifierCancelled();\n if (this.userId && this.deviceId) {\n // send a cancellation to the other user (if it wasn't\n // cancelled by the other user)\n if (e === timeoutException) {\n const timeoutEvent = newTimeoutError();\n this._send(timeoutEvent.getType(), timeoutEvent.getContent());\n } else if (e instanceof MatrixEvent) {\n const sender = e.getSender();\n if (sender !== this.userId) {\n const content = e.getContent();\n if (e.getType() === \"m.key.verification.cancel\") {\n content.code = content.code || \"m.unknown\";\n content.reason = content.reason || content.body\n || \"Unknown reason\";\n this._send(\"m.key.verification.cancel\", content);\n } else {\n this._send(\"m.key.verification.cancel\", {\n code: \"m.unknown\",\n reason: content.body || \"Unknown reason\",\n });\n }\n }\n } else {\n this._send(\"m.key.verification.cancel\", {\n code: \"m.unknown\",\n reason: e.toString(),\n });\n }\n }\n if (this._promise !== null) {\n // when we cancel without a promise, we end up with a promise\n // but no reject function. If cancel is called again, we'd error.\n if (this._reject) this._reject(e);\n } else {\n // FIXME: this causes an \"Uncaught promise\" console message\n // if nothing ends up chaining this promise.\n this._promise = Promise.reject(e);\n }\n // Also emit a 'cancel' event that the app can listen for to detect cancellation\n // before calling verify()\n this.emit('cancel', e);\n }\n }\n\n /**\n * Begin the key verification\n *\n * @returns {Promise} Promise which resolves when the verification has\n * completed.\n */\n verify() {\n if (this._promise) return this._promise;\n\n this._promise = new Promise((resolve, reject) => {\n this._resolve = (...args) => {\n this._done = true;\n this._endTimer();\n resolve(...args);\n };\n this._reject = (...args) => {\n this._done = true;\n this._endTimer();\n reject(...args);\n };\n });\n if (this._doVerification && !this._started) {\n this._started = true;\n this._resetTimer(); // restart the timeout\n Promise.resolve(this._doVerification())\n .then(this.done.bind(this), this.cancel.bind(this));\n }\n return this._promise;\n }\n\n async _verifyKeys(userId, keys, verifier) {\n // we try to verify all the keys that we're told about, but we might\n // not know about all of them, so keep track of the keys that we know\n // about, and ignore the rest\n const verifiedDevices = [];\n\n for (const [keyId, keyInfo] of Object.entries(keys)) {\n const deviceId = keyId.split(':', 2)[1];\n const device = this._baseApis.getStoredDevice(userId, deviceId);\n if (device) {\n await verifier(keyId, device, keyInfo);\n verifiedDevices.push(deviceId);\n } else {\n const crossSigningInfo = this._baseApis.crypto.deviceList\n .getStoredCrossSigningForUser(userId);\n if (crossSigningInfo && crossSigningInfo.getId() === deviceId) {\n await verifier(keyId, DeviceInfo.fromStorage({\n keys: {\n [keyId]: deviceId,\n },\n }, deviceId), keyInfo);\n verifiedDevices.push(deviceId);\n } else {\n logger.warn(\n `verification: Could not find device ${deviceId} to verify`,\n );\n }\n }\n }\n\n // if none of the keys could be verified, then error because the app\n // should be informed about that\n if (!verifiedDevices.length) {\n throw new Error(\"No devices could be verified\");\n }\n\n logger.info(\n \"Verification completed! Marking devices verified: \",\n verifiedDevices,\n );\n // TODO: There should probably be a batch version of this, otherwise it's going\n // to upload each signature in a separate API call which is silly because the\n // API supports as many signatures as you like.\n for (const deviceId of verifiedDevices) {\n await this._baseApis.setDeviceVerified(userId, deviceId);\n }\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Error messages.\n *\n * @module crypto/verification/Error\n */\n\nimport { MatrixEvent } from \"../../models/event\";\n\nexport function newVerificationError(code, reason, extradata) {\n const content = Object.assign({}, { code, reason }, extradata);\n return new MatrixEvent({\n type: \"m.key.verification.cancel\",\n content,\n });\n}\n\nexport function errorFactory(code, reason) {\n return function(extradata) {\n return newVerificationError(code, reason, extradata);\n };\n}\n\n/**\n * The verification was cancelled by the user.\n */\nexport const newUserCancelledError = errorFactory(\"m.user\", \"Cancelled by user\");\n\n/**\n * The verification timed out.\n */\nexport const newTimeoutError = errorFactory(\"m.timeout\", \"Timed out\");\n\n/**\n * The transaction is unknown.\n */\nexport const newUnknownTransactionError = errorFactory(\n \"m.unknown_transaction\", \"Unknown transaction\",\n);\n\n/**\n * An unknown method was selected.\n */\nexport const newUnknownMethodError = errorFactory(\"m.unknown_method\", \"Unknown method\");\n\n/**\n * An unexpected message was sent.\n */\nexport const newUnexpectedMessageError = errorFactory(\n \"m.unexpected_message\", \"Unexpected message\",\n);\n\n/**\n * The key does not match.\n */\nexport const newKeyMismatchError = errorFactory(\n \"m.key_mismatch\", \"Key mismatch\",\n);\n\n/**\n * The user does not match.\n */\nexport const newUserMismatchError = errorFactory(\"m.user_error\", \"User mismatch\");\n\n/**\n * An invalid message was sent.\n */\nexport const newInvalidMessageError = errorFactory(\n \"m.invalid_message\", \"Invalid message\",\n);\n\nexport function errorFromEvent(event) {\n const content = event.getContent();\n if (content) {\n const { code, reason } = content;\n return { code, reason };\n } else {\n return { code: \"Unknown error\", reason: \"m.unknown\" };\n }\n}\n",
"/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Verification method that is illegal to have (cannot possibly\n * do verification with this method).\n * @module crypto/verification/IllegalMethod\n */\n\nimport { VerificationBase as Base } from \"./Base\";\n\n/**\n * @class crypto/verification/IllegalMethod/IllegalMethod\n * @extends {module:crypto/verification/Base}\n */\nexport class IllegalMethod extends Base {\n static factory(...args) {\n return new IllegalMethod(...args);\n }\n\n static get NAME() {\n // Typically the name will be something else, but to complete\n // the contract we offer a default one here.\n return \"org.matrix.illegal_method\";\n }\n\n async _doVerification() {\n throw new Error(\"Verification is not possible with this method\");\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * QR code key verification.\n * @module crypto/verification/QRCode\n */\n\nimport { VerificationBase as Base } from \"./Base\";\nimport {\n newKeyMismatchError,\n newUserCancelledError,\n} from './Error';\nimport { encodeUnpaddedBase64, decodeBase64 } from \"../olmlib\";\nimport { logger } from '../../logger';\n\nexport const SHOW_QR_CODE_METHOD = \"m.qr_code.show.v1\";\nexport const SCAN_QR_CODE_METHOD = \"m.qr_code.scan.v1\";\n\n/**\n * @class crypto/verification/QRCode/ReciprocateQRCode\n * @extends {module:crypto/verification/Base}\n */\nexport class ReciprocateQRCode extends Base {\n static factory(...args) {\n return new ReciprocateQRCode(...args);\n }\n\n static get NAME() {\n return \"m.reciprocate.v1\";\n }\n\n async _doVerification() {\n if (!this.startEvent) {\n // TODO: Support scanning QR codes\n throw new Error(\"It is not currently possible to start verification\" +\n \"with this method yet.\");\n }\n\n const { qrCodeData } = this.request;\n // 1. check the secret\n if (this.startEvent.getContent()['secret'] !== qrCodeData.encodedSharedSecret) {\n throw newKeyMismatchError();\n }\n\n // 2. ask if other user shows shield as well\n await new Promise((resolve, reject) => {\n this.reciprocateQREvent = {\n confirm: resolve,\n cancel: () => reject(newUserCancelledError()),\n };\n this.emit(\"show_reciprocate_qr\", this.reciprocateQREvent);\n });\n\n // 3. determine key to sign / mark as trusted\n const keys = {};\n\n switch (qrCodeData.mode) {\n case MODE_VERIFY_OTHER_USER: {\n // add master key to keys to be signed, only if we're not doing self-verification\n const masterKey = qrCodeData.otherUserMasterKey;\n keys[`ed25519:${masterKey}`] = masterKey;\n break;\n }\n case MODE_VERIFY_SELF_TRUSTED: {\n const deviceId = this.request.targetDevice.deviceId;\n keys[`ed25519:${deviceId}`] = qrCodeData.otherDeviceKey;\n break;\n }\n case MODE_VERIFY_SELF_UNTRUSTED: {\n const masterKey = qrCodeData.myMasterKey;\n keys[`ed25519:${masterKey}`] = masterKey;\n break;\n }\n }\n\n // 4. sign the key (or mark own MSK as verified in case of MODE_VERIFY_SELF_TRUSTED)\n await this._verifyKeys(this.userId, keys, (keyId, device, keyInfo) => {\n // make sure the device has the expected keys\n const targetKey = keys[keyId];\n if (!targetKey) throw newKeyMismatchError();\n\n if (keyInfo !== targetKey) {\n logger.error(\"key ID from key info does not match\");\n throw newKeyMismatchError();\n }\n for (const deviceKeyId in device.keys) {\n if (!deviceKeyId.startsWith(\"ed25519\")) continue;\n const deviceTargetKey = keys[deviceKeyId];\n if (!deviceTargetKey) throw newKeyMismatchError();\n if (device.keys[deviceKeyId] !== deviceTargetKey) {\n logger.error(\"master key does not match\");\n throw newKeyMismatchError();\n }\n }\n });\n }\n}\n\nconst CODE_VERSION = 0x02; // the version of binary QR codes we support\nconst BINARY_PREFIX = \"MATRIX\"; // ASCII, used to prefix the binary format\nconst MODE_VERIFY_OTHER_USER = 0x00; // Verifying someone who isn't us\nconst MODE_VERIFY_SELF_TRUSTED = 0x01; // We trust the master key\nconst MODE_VERIFY_SELF_UNTRUSTED = 0x02; // We do not trust the master key\n\nexport class QRCodeData {\n constructor(\n mode, sharedSecret, otherUserMasterKey,\n otherDeviceKey, myMasterKey, buffer,\n ) {\n this._sharedSecret = sharedSecret;\n this._mode = mode;\n this._otherUserMasterKey = otherUserMasterKey;\n this._otherDeviceKey = otherDeviceKey;\n this._myMasterKey = myMasterKey;\n this._buffer = buffer;\n }\n\n static async create(request, client) {\n const sharedSecret = QRCodeData._generateSharedSecret();\n const mode = QRCodeData._determineMode(request, client);\n let otherUserMasterKey = null;\n let otherDeviceKey = null;\n let myMasterKey = null;\n if (mode === MODE_VERIFY_OTHER_USER) {\n const otherUserCrossSigningInfo =\n client.getStoredCrossSigningForUser(request.otherUserId);\n otherUserMasterKey = otherUserCrossSigningInfo.getId(\"master\");\n } else if (mode === MODE_VERIFY_SELF_TRUSTED) {\n otherDeviceKey = await QRCodeData._getOtherDeviceKey(request, client);\n } else if (mode === MODE_VERIFY_SELF_UNTRUSTED) {\n const myUserId = client.getUserId();\n const myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId);\n myMasterKey = myCrossSigningInfo.getId(\"master\");\n }\n const qrData = QRCodeData._generateQrData(\n request, client, mode,\n sharedSecret,\n otherUserMasterKey,\n otherDeviceKey,\n myMasterKey,\n );\n const buffer = QRCodeData._generateBuffer(qrData);\n return new QRCodeData(mode, sharedSecret,\n otherUserMasterKey, otherDeviceKey, myMasterKey, buffer);\n }\n\n get buffer() {\n return this._buffer;\n }\n\n get mode() {\n return this._mode;\n }\n\n /**\n * only set when mode is MODE_VERIFY_SELF_TRUSTED\n * @return {string} device key of other party at time of generating QR code\n */\n get otherDeviceKey() {\n return this._otherDeviceKey;\n }\n\n /**\n * only set when mode is MODE_VERIFY_OTHER_USER\n * @return {string} master key of other party at time of generating QR code\n */\n get otherUserMasterKey() {\n return this._otherUserMasterKey;\n }\n\n /**\n * only set when mode is MODE_VERIFY_SELF_UNTRUSTED\n * @return {string} own master key at time of generating QR code\n */\n get myMasterKey() {\n return this._myMasterKey;\n }\n\n /**\n * The unpadded base64 encoded shared secret.\n */\n get encodedSharedSecret() {\n return this._sharedSecret;\n }\n\n static _generateSharedSecret() {\n const secretBytes = new Uint8Array(11);\n global.crypto.getRandomValues(secretBytes);\n return encodeUnpaddedBase64(secretBytes);\n }\n\n static async _getOtherDeviceKey(request, client) {\n const myUserId = client.getUserId();\n const otherDevice = request.targetDevice;\n const otherDeviceId = otherDevice ? otherDevice.deviceId : null;\n const device = client.getStoredDevice(myUserId, otherDeviceId);\n if (!device) {\n throw new Error(\"could not find device \" + otherDeviceId);\n }\n const key = device.getFingerprint();\n return key;\n }\n\n static _determineMode(request, client) {\n const myUserId = client.getUserId();\n const otherUserId = request.otherUserId;\n\n let mode = MODE_VERIFY_OTHER_USER;\n if (myUserId === otherUserId) {\n // Mode changes depending on whether or not we trust the master cross signing key\n const myTrust = client.checkUserTrust(myUserId);\n if (myTrust.isCrossSigningVerified()) {\n mode = MODE_VERIFY_SELF_TRUSTED;\n } else {\n mode = MODE_VERIFY_SELF_UNTRUSTED;\n }\n }\n return mode;\n }\n\n static _generateQrData(request, client, mode,\n encodedSharedSecret, otherUserMasterKey,\n otherDeviceKey, myMasterKey,\n ) {\n const myUserId = client.getUserId();\n const transactionId = request.channel.transactionId;\n const qrData = {\n prefix: BINARY_PREFIX,\n version: CODE_VERSION,\n mode,\n transactionId,\n firstKeyB64: '', // worked out shortly\n secondKeyB64: '', // worked out shortly\n secretB64: encodedSharedSecret,\n };\n\n const myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId);\n\n if (mode === MODE_VERIFY_OTHER_USER) {\n // First key is our master cross signing key\n qrData.firstKeyB64 = myCrossSigningInfo.getId(\"master\");\n // Second key is the other user's master cross signing key\n qrData.secondKeyB64 = otherUserMasterKey;\n } else if (mode === MODE_VERIFY_SELF_TRUSTED) {\n // First key is our master cross signing key\n qrData.firstKeyB64 = myCrossSigningInfo.getId(\"master\");\n qrData.secondKeyB64 = otherDeviceKey;\n } else if (mode === MODE_VERIFY_SELF_UNTRUSTED) {\n // First key is our device's key\n qrData.firstKeyB64 = client.getDeviceEd25519Key();\n // Second key is what we think our master cross signing key is\n qrData.secondKeyB64 = myMasterKey;\n }\n return qrData;\n }\n\n static _generateBuffer(qrData) {\n let buf = Buffer.alloc(0); // we'll concat our way through life\n\n const appendByte = (b) => {\n const tmpBuf = Buffer.from([b]);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n const appendInt = (i) => {\n const tmpBuf = Buffer.alloc(2);\n tmpBuf.writeInt16BE(i, 0);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n const appendStr = (s, enc, withLengthPrefix = true) => {\n const tmpBuf = Buffer.from(s, enc);\n if (withLengthPrefix) appendInt(tmpBuf.byteLength);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n const appendEncBase64 = (b64) => {\n const b = decodeBase64(b64);\n const tmpBuf = Buffer.from(b);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n\n // Actually build the buffer for the QR code\n appendStr(qrData.prefix, \"ascii\", false);\n appendByte(qrData.version);\n appendByte(qrData.mode);\n appendStr(qrData.transactionId, \"utf-8\");\n appendEncBase64(qrData.firstKeyB64);\n appendEncBase64(qrData.secondKeyB64);\n appendEncBase64(qrData.secretB64);\n\n return buf;\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Short Authentication String (SAS) verification.\n * @module crypto/verification/SAS\n */\n\nimport { VerificationBase as Base, SwitchStartEventError } from \"./Base\";\nimport anotherjson from 'another-json';\nimport {\n errorFactory,\n newInvalidMessageError,\n newKeyMismatchError,\n newUnknownMethodError,\n newUserCancelledError,\n} from './Error';\nimport { logger } from '../../logger';\n\nconst START_TYPE = \"m.key.verification.start\";\n\nconst EVENTS = [\n \"m.key.verification.accept\",\n \"m.key.verification.key\",\n \"m.key.verification.mac\",\n];\n\nlet olmutil;\n\nconst newMismatchedSASError = errorFactory(\n \"m.mismatched_sas\", \"Mismatched short authentication string\",\n);\n\nconst newMismatchedCommitmentError = errorFactory(\n \"m.mismatched_commitment\", \"Mismatched commitment\",\n);\n\nfunction generateDecimalSas(sasBytes) {\n /**\n * +--------+--------+--------+--------+--------+\n * | Byte 0 | Byte 1 | Byte 2 | Byte 3 | Byte 4 |\n * +--------+--------+--------+--------+--------+\n * bits: 87654321 87654321 87654321 87654321 87654321\n * \\____________/\\_____________/\\____________/\n * 1st number 2nd number 3rd number\n */\n return [\n (sasBytes[0] << 5 | sasBytes[1] >> 3) + 1000,\n ((sasBytes[1] & 0x7) << 10 | sasBytes[2] << 2 | sasBytes[3] >> 6) + 1000,\n ((sasBytes[3] & 0x3f) << 7 | sasBytes[4] >> 1) + 1000,\n ];\n}\n\nconst emojiMapping = [\n [\"🐶\", \"dog\"], // 0\n [\"🐱\", \"cat\"], // 1\n [\"🦁\", \"lion\"], // 2\n [\"🐎\", \"horse\"], // 3\n [\"🦄\", \"unicorn\"], // 4\n [\"🐷\", \"pig\"], // 5\n [\"🐘\", \"elephant\"], // 6\n [\"🐰\", \"rabbit\"], // 7\n [\"🐼\", \"panda\"], // 8\n [\"🐓\", \"rooster\"], // 9\n [\"🐧\", \"penguin\"], // 10\n [\"🐢\", \"turtle\"], // 11\n [\"🐟\", \"fish\"], // 12\n [\"🐙\", \"octopus\"], // 13\n [\"🦋\", \"butterfly\"], // 14\n [\"🌷\", \"flower\"], // 15\n [\"🌳\", \"tree\"], // 16\n [\"🌵\", \"cactus\"], // 17\n [\"🍄\", \"mushroom\"], // 18\n [\"🌏\", \"globe\"], // 19\n [\"🌙\", \"moon\"], // 20\n [\"☁️\", \"cloud\"], // 21\n [\"🔥\", \"fire\"], // 22\n [\"🍌\", \"banana\"], // 23\n [\"🍎\", \"apple\"], // 24\n [\"🍓\", \"strawberry\"], // 25\n [\"🌽\", \"corn\"], // 26\n [\"🍕\", \"pizza\"], // 27\n [\"🎂\", \"cake\"], // 28\n [\"❤️\", \"heart\"], // 29\n [\"🙂\", \"smiley\"], // 30\n [\"🤖\", \"robot\"], // 31\n [\"🎩\", \"hat\"], // 32\n [\"👓\", \"glasses\"], // 33\n [\"🔧\", \"spanner\"], // 34\n [\"🎅\", \"santa\"], // 35\n [\"👍\", \"thumbs up\"], // 36\n [\"☂️\", \"umbrella\"], // 37\n [\"⌛\", \"hourglass\"], // 38\n [\"⏰\", \"clock\"], // 39\n [\"🎁\", \"gift\"], // 40\n [\"💡\", \"light bulb\"], // 41\n [\"📕\", \"book\"], // 42\n [\"✏️\", \"pencil\"], // 43\n [\"📎\", \"paperclip\"], // 44\n [\"✂️\", \"scissors\"], // 45\n [\"🔒\", \"lock\"], // 46\n [\"🔑\", \"key\"], // 47\n [\"🔨\", \"hammer\"], // 48\n [\"☎️\", \"telephone\"], // 49\n [\"🏁\", \"flag\"], // 50\n [\"🚂\", \"train\"], // 51\n [\"🚲\", \"bicycle\"], // 52\n [\"✈️\", \"aeroplane\"], // 53\n [\"🚀\", \"rocket\"], // 54\n [\"🏆\", \"trophy\"], // 55\n [\"⚽\", \"ball\"], // 56\n [\"🎸\", \"guitar\"], // 57\n [\"🎺\", \"trumpet\"], // 58\n [\"🔔\", \"bell\"], // 59\n [\"⚓️\", \"anchor\"], // 60\n [\"🎧\", \"headphones\"], // 61\n [\"📁\", \"folder\"], // 62\n [\"📌\", \"pin\"], // 63\n];\n\nfunction generateEmojiSas(sasBytes) {\n const emojis = [\n // just like base64 encoding\n sasBytes[0] >> 2,\n (sasBytes[0] & 0x3) << 4 | sasBytes[1] >> 4,\n (sasBytes[1] & 0xf) << 2 | sasBytes[2] >> 6,\n sasBytes[2] & 0x3f,\n sasBytes[3] >> 2,\n (sasBytes[3] & 0x3) << 4 | sasBytes[4] >> 4,\n (sasBytes[4] & 0xf) << 2 | sasBytes[5] >> 6,\n ];\n\n return emojis.map((num) => emojiMapping[num]);\n}\n\nconst sasGenerators = {\n decimal: generateDecimalSas,\n emoji: generateEmojiSas,\n};\n\nfunction generateSas(sasBytes, methods) {\n const sas = {};\n for (const method of methods) {\n if (method in sasGenerators) {\n sas[method] = sasGenerators[method](sasBytes);\n }\n }\n return sas;\n}\n\nconst macMethods = {\n \"hkdf-hmac-sha256\": \"calculate_mac\",\n \"hmac-sha256\": \"calculate_mac_long_kdf\",\n};\n\nfunction calculateMAC(olmSAS, method) {\n return function(...args) {\n const macFunction = olmSAS[macMethods[method]];\n const mac = macFunction.apply(olmSAS, args);\n logger.log(\"SAS calculateMAC:\", method, args, mac);\n return mac;\n };\n}\n\nconst calculateKeyAgreement = {\n \"curve25519-hkdf-sha256\": function(sas, olmSAS, bytes) {\n const ourInfo = `${sas._baseApis.getUserId()}|${sas._baseApis.deviceId}|`\n + `${sas.ourSASPubKey}|`;\n const theirInfo = `${sas.userId}|${sas.deviceId}|${sas.theirSASPubKey}|`;\n const sasInfo =\n \"MATRIX_KEY_VERIFICATION_SAS|\"\n + (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo)\n + sas._channel.transactionId;\n return olmSAS.generate_bytes(sasInfo, bytes);\n },\n \"curve25519\": function(sas, olmSAS, bytes) {\n const ourInfo = `${sas._baseApis.getUserId()}${sas._baseApis.deviceId}`;\n const theirInfo = `${sas.userId}${sas.deviceId}`;\n const sasInfo =\n \"MATRIX_KEY_VERIFICATION_SAS\"\n + (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo)\n + sas._channel.transactionId;\n return olmSAS.generate_bytes(sasInfo, bytes);\n },\n};\n\n/* lists of algorithms/methods that are supported. The key agreement, hashes,\n * and MAC lists should be sorted in order of preference (most preferred\n * first).\n */\nconst KEY_AGREEMENT_LIST = [\"curve25519-hkdf-sha256\", \"curve25519\"];\nconst HASHES_LIST = [\"sha256\"];\nconst MAC_LIST = [\"hkdf-hmac-sha256\", \"hmac-sha256\"];\nconst SAS_LIST = Object.keys(sasGenerators);\n\nconst KEY_AGREEMENT_SET = new Set(KEY_AGREEMENT_LIST);\nconst HASHES_SET = new Set(HASHES_LIST);\nconst MAC_SET = new Set(MAC_LIST);\nconst SAS_SET = new Set(SAS_LIST);\n\nfunction intersection(anArray, aSet) {\n return anArray instanceof Array ? anArray.filter(x => aSet.has(x)) : [];\n}\n\n/**\n * @alias module:crypto/verification/SAS\n * @extends {module:crypto/verification/Base}\n */\nexport class SAS extends Base {\n static get NAME() {\n return \"m.sas.v1\";\n }\n\n get events() {\n return EVENTS;\n }\n\n async _doVerification() {\n await global.Olm.init();\n olmutil = olmutil || new global.Olm.Utility();\n\n // make sure user's keys are downloaded\n await this._baseApis.downloadKeys([this.userId]);\n\n let retry = false;\n do {\n try {\n if (this.initiatedByMe) {\n return await this._doSendVerification();\n } else {\n return await this._doRespondVerification();\n }\n } catch (err) {\n if (err instanceof SwitchStartEventError) {\n // this changes what initiatedByMe returns\n this.startEvent = err.startEvent;\n retry = true;\n } else {\n throw err;\n }\n }\n } while (retry);\n }\n\n canSwitchStartEvent(event) {\n if (event.getType() !== START_TYPE) {\n return false;\n }\n const content = event.getContent();\n return content && content.method === SAS.NAME &&\n this._waitingForAccept;\n }\n\n async _sendStart() {\n const startContent = this._channel.completeContent(START_TYPE, {\n method: SAS.NAME,\n from_device: this._baseApis.deviceId,\n key_agreement_protocols: KEY_AGREEMENT_LIST,\n hashes: HASHES_LIST,\n message_authentication_codes: MAC_LIST,\n // FIXME: allow app to specify what SAS methods can be used\n short_authentication_string: SAS_LIST,\n });\n await this._channel.sendCompleted(START_TYPE, startContent);\n return startContent;\n }\n\n async _doSendVerification() {\n this._waitingForAccept = true;\n let startContent;\n if (this.startEvent) {\n startContent = this._channel.completedContentFromEvent(this.startEvent);\n } else {\n startContent = await this._sendStart();\n }\n\n // we might have switched to a different start event,\n // but was we didn't call _waitForEvent there was no\n // call that could throw yet. So check manually that\n // we're still on the initiator side\n if (!this.initiatedByMe) {\n throw new SwitchStartEventError(this.startEvent);\n }\n\n let e;\n try {\n e = await this._waitForEvent(\"m.key.verification.accept\");\n } finally {\n this._waitingForAccept = false;\n }\n let content = e.getContent();\n const sasMethods\n = intersection(content.short_authentication_string, SAS_SET);\n if (!(KEY_AGREEMENT_SET.has(content.key_agreement_protocol)\n && HASHES_SET.has(content.hash)\n && MAC_SET.has(content.message_authentication_code)\n && sasMethods.length)) {\n throw newUnknownMethodError();\n }\n if (typeof content.commitment !== \"string\") {\n throw newInvalidMessageError();\n }\n const keyAgreement = content.key_agreement_protocol;\n const macMethod = content.message_authentication_code;\n const hashCommitment = content.commitment;\n const olmSAS = new global.Olm.SAS();\n try {\n this.ourSASPubKey = olmSAS.get_pubkey();\n await this._send(\"m.key.verification.key\", {\n key: this.ourSASPubKey,\n });\n\n e = await this._waitForEvent(\"m.key.verification.key\");\n // FIXME: make sure event is properly formed\n content = e.getContent();\n const commitmentStr = content.key + anotherjson.stringify(startContent);\n // TODO: use selected hash function (when we support multiple)\n if (olmutil.sha256(commitmentStr) !== hashCommitment) {\n throw newMismatchedCommitmentError();\n }\n this.theirSASPubKey = content.key;\n olmSAS.set_their_key(content.key);\n\n const sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);\n const verifySAS = new Promise((resolve, reject) => {\n this.sasEvent = {\n sas: generateSas(sasBytes, sasMethods),\n confirm: async () => {\n try {\n await this._sendMAC(olmSAS, macMethod);\n resolve();\n } catch (err) {\n reject(err);\n }\n },\n cancel: () => reject(newUserCancelledError()),\n mismatch: () => reject(newMismatchedSASError()),\n };\n this.emit(\"show_sas\", this.sasEvent);\n });\n\n [e] = await Promise.all([\n this._waitForEvent(\"m.key.verification.mac\")\n .then((e) => {\n // we don't expect any more messages from the other\n // party, and they may send a m.key.verification.done\n // when they're done on their end\n this._expectedEvent = \"m.key.verification.done\";\n return e;\n }),\n verifySAS,\n ]);\n content = e.getContent();\n await this._checkMAC(olmSAS, content, macMethod);\n } finally {\n olmSAS.free();\n }\n }\n\n async _doRespondVerification() {\n // as m.related_to is not included in the encrypted content in e2e rooms,\n // we need to make sure it is added\n let content = this._channel.completedContentFromEvent(this.startEvent);\n\n // Note: we intersect using our pre-made lists, rather than the sets,\n // so that the result will be in our order of preference. Then\n // fetching the first element from the array will give our preferred\n // method out of the ones offered by the other party.\n const keyAgreement\n = intersection(\n KEY_AGREEMENT_LIST, new Set(content.key_agreement_protocols),\n )[0];\n const hashMethod\n = intersection(HASHES_LIST, new Set(content.hashes))[0];\n const macMethod\n = intersection(MAC_LIST, new Set(content.message_authentication_codes))[0];\n // FIXME: allow app to specify what SAS methods can be used\n const sasMethods\n = intersection(content.short_authentication_string, SAS_SET);\n if (!(keyAgreement !== undefined\n && hashMethod !== undefined\n && macMethod !== undefined\n && sasMethods.length)) {\n throw newUnknownMethodError();\n }\n\n const olmSAS = new global.Olm.SAS();\n try {\n const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(content);\n await this._send(\"m.key.verification.accept\", {\n key_agreement_protocol: keyAgreement,\n hash: hashMethod,\n message_authentication_code: macMethod,\n short_authentication_string: sasMethods,\n // TODO: use selected hash function (when we support multiple)\n commitment: olmutil.sha256(commitmentStr),\n });\n\n let e = await this._waitForEvent(\"m.key.verification.key\");\n // FIXME: make sure event is properly formed\n content = e.getContent();\n this.theirSASPubKey = content.key;\n olmSAS.set_their_key(content.key);\n this.ourSASPubKey = olmSAS.get_pubkey();\n await this._send(\"m.key.verification.key\", {\n key: this.ourSASPubKey,\n });\n\n const sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);\n const verifySAS = new Promise((resolve, reject) => {\n this.sasEvent = {\n sas: generateSas(sasBytes, sasMethods),\n confirm: async () => {\n try {\n await this._sendMAC(olmSAS, macMethod);\n resolve();\n } catch (err) {\n reject(err);\n }\n },\n cancel: () => reject(newUserCancelledError()),\n mismatch: () => reject(newMismatchedSASError()),\n };\n this.emit(\"show_sas\", this.sasEvent);\n });\n\n [e] = await Promise.all([\n this._waitForEvent(\"m.key.verification.mac\")\n .then((e) => {\n // we don't expect any more messages from the other\n // party, and they may send a m.key.verification.done\n // when they're done on their end\n this._expectedEvent = \"m.key.verification.done\";\n return e;\n }),\n verifySAS,\n ]);\n content = e.getContent();\n await this._checkMAC(olmSAS, content, macMethod);\n } finally {\n olmSAS.free();\n }\n }\n\n _sendMAC(olmSAS, method) {\n const mac = {};\n const keyList = [];\n const baseInfo = \"MATRIX_KEY_VERIFICATION_MAC\"\n + this._baseApis.getUserId() + this._baseApis.deviceId\n + this.userId + this.deviceId\n + this._channel.transactionId;\n\n const deviceKeyId = `ed25519:${this._baseApis.deviceId}`;\n mac[deviceKeyId] = calculateMAC(olmSAS, method)(\n this._baseApis.getDeviceEd25519Key(),\n baseInfo + deviceKeyId,\n );\n keyList.push(deviceKeyId);\n\n const crossSigningId = this._baseApis.getCrossSigningId();\n if (crossSigningId) {\n const crossSigningKeyId = `ed25519:${crossSigningId}`;\n mac[crossSigningKeyId] = calculateMAC(olmSAS, method)(\n crossSigningId,\n baseInfo + crossSigningKeyId,\n );\n keyList.push(crossSigningKeyId);\n }\n\n const keys = calculateMAC(olmSAS, method)(\n keyList.sort().join(\",\"),\n baseInfo + \"KEY_IDS\",\n );\n return this._send(\"m.key.verification.mac\", { mac, keys });\n }\n\n async _checkMAC(olmSAS, content, method) {\n const baseInfo = \"MATRIX_KEY_VERIFICATION_MAC\"\n + this.userId + this.deviceId\n + this._baseApis.getUserId() + this._baseApis.deviceId\n + this._channel.transactionId;\n\n if (content.keys !== calculateMAC(olmSAS, method)(\n Object.keys(content.mac).sort().join(\",\"),\n baseInfo + \"KEY_IDS\",\n )) {\n throw newKeyMismatchError();\n }\n\n await this._verifyKeys(this.userId, content.mac, (keyId, device, keyInfo) => {\n if (keyInfo !== calculateMAC(olmSAS, method)(\n device.keys[keyId],\n baseInfo + keyId,\n )) {\n throw newKeyMismatchError();\n }\n });\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n VerificationRequest,\n REQUEST_TYPE,\n READY_TYPE,\n START_TYPE,\n} from \"./VerificationRequest\";\nimport { logger } from '../../../logger';\n\nconst MESSAGE_TYPE = \"m.room.message\";\nconst M_REFERENCE = \"m.reference\";\nconst M_RELATES_TO = \"m.relates_to\";\n\n/**\n * A key verification channel that sends verification events in the timeline of a room.\n * Uses the event id of the initial m.key.verification.request event as a transaction id.\n */\nexport class InRoomChannel {\n /**\n * @param {MatrixClient} client the matrix client, to send messages with and get current user & device from.\n * @param {string} roomId id of the room where verification events should be posted in, should be a DM with the given user.\n * @param {string} userId id of user that the verification request is directed at, should be present in the room.\n */\n constructor(client, roomId, userId = null) {\n this._client = client;\n this._roomId = roomId;\n this.userId = userId;\n this._requestEventId = null;\n }\n\n get receiveStartFromOtherDevices() {\n return true;\n }\n\n get roomId() {\n return this._roomId;\n }\n\n /** The transaction id generated/used by this verification channel */\n get transactionId() {\n return this._requestEventId;\n }\n\n static getOtherPartyUserId(event, client) {\n const type = InRoomChannel.getEventType(event);\n if (type !== REQUEST_TYPE) {\n return;\n }\n const ownUserId = client.getUserId();\n const sender = event.getSender();\n const content = event.getContent();\n const receiver = content.to;\n\n if (sender === ownUserId) {\n return receiver;\n } else if (receiver === ownUserId) {\n return sender;\n }\n }\n\n /**\n * @param {MatrixEvent} event the event to get the timestamp of\n * @return {number} the timestamp when the event was sent\n */\n getTimestamp(event) {\n return event.getTs();\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param {string} type the event type to check\n * @returns {bool} boolean flag\n */\n static canCreateRequest(type) {\n return type === REQUEST_TYPE;\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param {MatrixEvent} event the event\n * @returns {string} the transaction id\n */\n static getTransactionId(event) {\n if (InRoomChannel.getEventType(event) === REQUEST_TYPE) {\n return event.getId();\n } else {\n const relation = event.getRelation();\n if (relation && relation.rel_type === M_REFERENCE) {\n return relation.event_id;\n }\n }\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param {MatrixEvent} event the event to validate\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(event, client) {\n const txnId = InRoomChannel.getTransactionId(event);\n if (typeof txnId !== \"string\" || txnId.length === 0) {\n return false;\n }\n const type = InRoomChannel.getEventType(event);\n const content = event.getContent();\n\n // from here on we're fairly sure that this is supposed to be\n // part of a verification request, so be noisy when rejecting something\n if (type === REQUEST_TYPE) {\n if (!content || typeof content.to !== \"string\" || !content.to.length) {\n logger.log(\"InRoomChannel: validateEvent: \" +\n \"no valid to \" + (content && content.to));\n return false;\n }\n\n // ignore requests that are not direct to or sent by the syncing user\n if (!InRoomChannel.getOtherPartyUserId(event, client)) {\n logger.log(\"InRoomChannel: validateEvent: \" +\n `not directed to or sent by me: ${event.getSender()}` +\n `, ${content && content.to}`);\n return false;\n }\n }\n\n return VerificationRequest.validateEvent(type, event, client);\n }\n\n /**\n * As m.key.verification.request events are as m.room.message events with the InRoomChannel\n * to have a fallback message in non-supporting clients, we map the real event type\n * to the symbolic one to keep things in unison with ToDeviceChannel\n * @param {MatrixEvent} event the event to get the type of\n * @returns {string} the \"symbolic\" event type\n */\n static getEventType(event) {\n const type = event.getType();\n if (type === MESSAGE_TYPE) {\n const content = event.getContent();\n if (content) {\n const { msgtype } = content;\n if (msgtype === REQUEST_TYPE) {\n return REQUEST_TYPE;\n }\n }\n }\n if (type && type !== REQUEST_TYPE) {\n return type;\n } else {\n return \"\";\n }\n }\n\n /**\n * Changes the state of the channel, request, and verifier in response to a key verification event.\n * @param {MatrixEvent} event to handle\n * @param {VerificationRequest} request the request to forward handling to\n * @param {bool} isLiveEvent whether this is an even received through sync or not\n * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent.\n */\n async handleEvent(event, request, isLiveEvent) {\n // prevent processing the same event multiple times, as under\n // some circumstances Room.timeline can get emitted twice for the same event\n if (request.hasEventId(event.getId())) {\n return;\n }\n const type = InRoomChannel.getEventType(event);\n // do validations that need state (roomId, userId),\n // ignore if invalid\n\n if (event.getRoomId() !== this._roomId) {\n return;\n }\n // set userId if not set already\n if (this.userId === null) {\n const userId = InRoomChannel.getOtherPartyUserId(event, this._client);\n if (userId) {\n this.userId = userId;\n }\n }\n // ignore events not sent by us or the other party\n const ownUserId = this._client.getUserId();\n const sender = event.getSender();\n if (this.userId !== null) {\n if (sender !== ownUserId && sender !== this.userId) {\n logger.log(`InRoomChannel: ignoring verification event from ` +\n `non-participating sender ${sender}`);\n return;\n }\n }\n if (this._requestEventId === null) {\n this._requestEventId = InRoomChannel.getTransactionId(event);\n }\n\n const isRemoteEcho = !!event.getUnsigned().transaction_id;\n const isSentByUs = event.getSender() === this._client.getUserId();\n\n return await request.handleEvent(\n type, event, isLiveEvent, isRemoteEcho, isSentByUs);\n }\n\n /**\n * Adds the transaction id (relation) back to a received event\n * so it has the same format as returned by `completeContent` before sending.\n * The relation can not appear on the event content because of encryption,\n * relations are excluded from encryption.\n * @param {MatrixEvent} event the received event\n * @returns {Object} the content object with the relation added again\n */\n completedContentFromEvent(event) {\n // ensure m.related_to is included in e2ee rooms\n // as the field is excluded from encryption\n const content = Object.assign({}, event.getContent());\n content[M_RELATES_TO] = event.getRelation();\n return content;\n }\n /**\n * Add all the fields to content needed for sending it over this channel.\n * This is public so verification methods (SAS uses this) can get the exact\n * content that will be sent independent of the used channel,\n * as they need to calculate the hash of it.\n * @param {string} type the event type\n * @param {object} content the (incomplete) content\n * @returns {object} the complete content, as it will be sent.\n */\n completeContent(type, content) {\n content = Object.assign({}, content);\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n content.from_device = this._client.getDeviceId();\n }\n if (type === REQUEST_TYPE) {\n // type is mapped to m.room.message in the send method\n content = {\n body: this._client.getUserId() + \" is requesting to verify \" +\n \"your key, but your client does not support in-chat key \" +\n \"verification. You will need to use legacy key \" +\n \"verification to verify keys.\",\n msgtype: REQUEST_TYPE,\n to: this.userId,\n from_device: content.from_device,\n methods: content.methods,\n };\n } else {\n content[M_RELATES_TO] = {\n rel_type: M_REFERENCE,\n event_id: this.transactionId,\n };\n }\n return content;\n }\n\n /**\n * Send an event over the channel with the content not having gone through `completeContent`.\n * @param {string} type the event type\n * @param {object} uncompletedContent the (incomplete) content\n * @returns {Promise} the promise of the request\n */\n send(type, uncompletedContent) {\n const content = this.completeContent(type, uncompletedContent);\n return this.sendCompleted(type, content);\n }\n\n /**\n * Send an event over the channel with the content having gone through `completeContent` already.\n * @param {string} type the event type\n * @param {object} content\n * @returns {Promise} the promise of the request\n */\n async sendCompleted(type, content) {\n let sendType = type;\n if (type === REQUEST_TYPE) {\n sendType = MESSAGE_TYPE;\n }\n const response = await this._client.sendEvent(this._roomId, sendType, content);\n if (type === REQUEST_TYPE) {\n this._requestEventId = response.event_id;\n }\n }\n}\n\nexport class InRoomRequests {\n constructor() {\n this._requestsByRoomId = new Map();\n }\n\n getRequest(event) {\n const roomId = event.getRoomId();\n const txnId = InRoomChannel.getTransactionId(event);\n return this._getRequestByTxnId(roomId, txnId);\n }\n\n getRequestByChannel(channel) {\n return this._getRequestByTxnId(channel.roomId, channel.transactionId);\n }\n\n _getRequestByTxnId(roomId, txnId) {\n const requestsByTxnId = this._requestsByRoomId.get(roomId);\n if (requestsByTxnId) {\n return requestsByTxnId.get(txnId);\n }\n }\n\n setRequest(event, request) {\n this._setRequest(\n event.getRoomId(),\n InRoomChannel.getTransactionId(event),\n request,\n );\n }\n\n setRequestByChannel(channel, request) {\n this._setRequest(channel.roomId, channel.transactionId, request);\n }\n\n _setRequest(roomId, txnId, request) {\n let requestsByTxnId = this._requestsByRoomId.get(roomId);\n if (!requestsByTxnId) {\n requestsByTxnId = new Map();\n this._requestsByRoomId.set(roomId, requestsByTxnId);\n }\n requestsByTxnId.set(txnId, request);\n }\n\n removeRequest(event) {\n const roomId = event.getRoomId();\n const requestsByTxnId = this._requestsByRoomId.get(roomId);\n if (requestsByTxnId) {\n requestsByTxnId.delete(InRoomChannel.getTransactionId(event));\n if (requestsByTxnId.size === 0) {\n this._requestsByRoomId.delete(roomId);\n }\n }\n }\n\n findRequestInProgress(roomId) {\n const requestsByTxnId = this._requestsByRoomId.get(roomId);\n if (requestsByTxnId) {\n for (const request of requestsByTxnId.values()) {\n if (request.pending) {\n return request;\n }\n }\n }\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { randomString } from '../../../randomstring';\nimport { logger } from '../../../logger';\nimport {\n CANCEL_TYPE,\n PHASE_STARTED,\n PHASE_READY,\n REQUEST_TYPE,\n READY_TYPE,\n START_TYPE,\n VerificationRequest,\n} from \"./VerificationRequest\";\nimport { errorFromEvent, newUnexpectedMessageError } from \"../Error\";\nimport { MatrixEvent } from \"../../../models/event\";\n\n/**\n * A key verification channel that sends verification events over to_device messages.\n * Generates its own transaction ids.\n */\nexport class ToDeviceChannel {\n // userId and devices of user we're about to verify\n constructor(client, userId, devices, transactionId = null, deviceId = null) {\n this._client = client;\n this.userId = userId;\n this._devices = devices;\n this.transactionId = transactionId;\n this._deviceId = deviceId;\n }\n\n isToDevices(devices) {\n if (devices.length === this._devices.length) {\n for (const device of devices) {\n const d = this._devices.find(d => d.deviceId === device.deviceId);\n if (!d) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n get deviceId() {\n return this._deviceId;\n }\n\n static getEventType(event) {\n return event.getType();\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param {MatrixEvent} event the event\n * @returns {string} the transaction id\n */\n static getTransactionId(event) {\n const content = event.getContent();\n return content && content.transaction_id;\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param {string} type the event type to check\n * @returns {bool} boolean flag\n */\n static canCreateRequest(type) {\n return type === REQUEST_TYPE || type === START_TYPE;\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param {MatrixEvent} event the event to validate\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(event, client) {\n if (event.isCancelled()) {\n logger.warn(\"Ignoring flagged verification request from \"\n + event.getSender());\n return false;\n }\n const content = event.getContent();\n if (!content) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no content\");\n return false;\n }\n\n if (!content.transaction_id) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no transaction_id\");\n return false;\n }\n\n const type = event.getType();\n\n if (type === REQUEST_TYPE) {\n if (!Number.isFinite(content.timestamp)) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no timestamp\");\n return false;\n }\n if (event.getSender() === client.getUserId() &&\n content.from_device == client.getDeviceId()\n ) {\n // ignore requests from ourselves, because it doesn't make sense for a\n // device to verify itself\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: from own device\");\n return false;\n }\n }\n\n return VerificationRequest.validateEvent(type, event, client);\n }\n\n /**\n * @param {MatrixEvent} event the event to get the timestamp of\n * @return {number} the timestamp when the event was sent\n */\n getTimestamp(event) {\n const content = event.getContent();\n return content && content.timestamp;\n }\n\n /**\n * Changes the state of the channel, request, and verifier in response to a key verification event.\n * @param {MatrixEvent} event to handle\n * @param {VerificationRequest} request the request to forward handling to\n * @param {bool} isLiveEvent whether this is an even received through sync or not\n * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent.\n */\n async handleEvent(event, request, isLiveEvent) {\n const type = event.getType();\n const content = event.getContent();\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n if (!this.transactionId) {\n this.transactionId = content.transaction_id;\n }\n const deviceId = content.from_device;\n // adopt deviceId if not set before and valid\n if (!this._deviceId && this._devices.includes(deviceId)) {\n this._deviceId = deviceId;\n }\n // if no device id or different from addopted one, cancel with sender\n if (!this._deviceId || this._deviceId !== deviceId) {\n // also check that message came from the device we sent the request to earlier on\n // and do send a cancel message to that device\n // (but don't cancel the request for the device we should be talking to)\n const cancelContent =\n this.completeContent(errorFromEvent(newUnexpectedMessageError()));\n return this._sendToDevices(CANCEL_TYPE, cancelContent, [deviceId]);\n }\n }\n const wasStarted = request.phase === PHASE_STARTED ||\n request.phase === PHASE_READY;\n\n await request.handleEvent(event.getType(), event, isLiveEvent, false, false);\n\n const isStarted = request.phase === PHASE_STARTED ||\n request.phase === PHASE_READY;\n\n const isAcceptingEvent = type === START_TYPE || type === READY_TYPE;\n // the request has picked a ready or start event, tell the other devices about it\n if (isAcceptingEvent && !wasStarted && isStarted && this._deviceId) {\n const nonChosenDevices = this._devices.filter(\n d => d !== this._deviceId && d !== this._client.getDeviceId(),\n );\n if (nonChosenDevices.length) {\n const message = this.completeContent({\n code: \"m.accepted\",\n reason: \"Verification request accepted by another device\",\n });\n await this._sendToDevices(CANCEL_TYPE, message, nonChosenDevices);\n }\n }\n }\n\n /**\n * See {InRoomChannel.completedContentFromEvent} why this is needed.\n * @param {MatrixEvent} event the received event\n * @returns {Object} the content object\n */\n completedContentFromEvent(event) {\n return event.getContent();\n }\n\n /**\n * Add all the fields to content needed for sending it over this channel.\n * This is public so verification methods (SAS uses this) can get the exact\n * content that will be sent independent of the used channel,\n * as they need to calculate the hash of it.\n * @param {string} type the event type\n * @param {object} content the (incomplete) content\n * @returns {object} the complete content, as it will be sent.\n */\n completeContent(type, content) {\n // make a copy\n content = Object.assign({}, content);\n if (this.transactionId) {\n content.transaction_id = this.transactionId;\n }\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n content.from_device = this._client.getDeviceId();\n }\n if (type === REQUEST_TYPE) {\n content.timestamp = Date.now();\n }\n return content;\n }\n\n /**\n * Send an event over the channel with the content not having gone through `completeContent`.\n * @param {string} type the event type\n * @param {object} uncompletedContent the (incomplete) content\n * @returns {Promise} the promise of the request\n */\n send(type, uncompletedContent = {}) {\n // create transaction id when sending request\n if ((type === REQUEST_TYPE || type === START_TYPE) && !this.transactionId) {\n this.transactionId = ToDeviceChannel.makeTransactionId();\n }\n const content = this.completeContent(type, uncompletedContent);\n return this.sendCompleted(type, content);\n }\n\n /**\n * Send an event over the channel with the content having gone through `completeContent` already.\n * @param {string} type the event type\n * @param {object} content\n * @returns {Promise} the promise of the request\n */\n async sendCompleted(type, content) {\n let result;\n if (type === REQUEST_TYPE) {\n result = await this._sendToDevices(type, content, this._devices);\n } else {\n result = await this._sendToDevices(type, content, [this._deviceId]);\n }\n // the VerificationRequest state machine requires remote echos of the event\n // the client sends itself, so we fake this for to_device messages\n const remoteEchoEvent = new MatrixEvent({\n sender: this._client.getUserId(),\n content,\n type,\n });\n await this._request.handleEvent(\n type,\n remoteEchoEvent,\n /*isLiveEvent=*/true,\n /*isRemoteEcho=*/true,\n /*isSentByUs=*/true,\n );\n return result;\n }\n\n _sendToDevices(type, content, devices) {\n if (devices.length) {\n const msgMap = {};\n for (const deviceId of devices) {\n msgMap[deviceId] = content;\n }\n\n return this._client.sendToDevice(type, { [this.userId]: msgMap });\n } else {\n return Promise.resolve();\n }\n }\n\n /**\n * Allow Crypto module to create and know the transaction id before the .start event gets sent.\n * @returns {string} the transaction id\n */\n static makeTransactionId() {\n return randomString(32);\n }\n}\n\nexport class ToDeviceRequests {\n constructor() {\n this._requestsByUserId = new Map();\n }\n\n getRequest(event) {\n return this.getRequestBySenderAndTxnId(\n event.getSender(),\n ToDeviceChannel.getTransactionId(event),\n );\n }\n\n getRequestByChannel(channel) {\n return this.getRequestBySenderAndTxnId(channel.userId, channel.transactionId);\n }\n\n getRequestBySenderAndTxnId(sender, txnId) {\n const requestsByTxnId = this._requestsByUserId.get(sender);\n if (requestsByTxnId) {\n return requestsByTxnId.get(txnId);\n }\n }\n\n setRequest(event, request) {\n this.setRequestBySenderAndTxnId(\n event.getSender(),\n ToDeviceChannel.getTransactionId(event),\n request,\n );\n }\n\n setRequestByChannel(channel, request) {\n this.setRequestBySenderAndTxnId(channel.userId, channel.transactionId, request);\n }\n\n setRequestBySenderAndTxnId(sender, txnId, request) {\n let requestsByTxnId = this._requestsByUserId.get(sender);\n if (!requestsByTxnId) {\n requestsByTxnId = new Map();\n this._requestsByUserId.set(sender, requestsByTxnId);\n }\n requestsByTxnId.set(txnId, request);\n }\n\n removeRequest(event) {\n const userId = event.getSender();\n const requestsByTxnId = this._requestsByUserId.get(userId);\n if (requestsByTxnId) {\n requestsByTxnId.delete(ToDeviceChannel.getTransactionId(event));\n if (requestsByTxnId.size === 0) {\n this._requestsByUserId.delete(userId);\n }\n }\n }\n\n findRequestInProgress(userId, devices) {\n const requestsByTxnId = this._requestsByUserId.get(userId);\n if (requestsByTxnId) {\n for (const request of requestsByTxnId.values()) {\n if (request.pending && request.channel.isToDevices(devices)) {\n return request;\n }\n }\n }\n }\n\n getRequestsInProgress(userId) {\n const requestsByTxnId = this._requestsByUserId.get(userId);\n if (requestsByTxnId) {\n return Array.from(requestsByTxnId.values()).filter(r => r.pending);\n }\n return [];\n }\n}\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../../../logger';\nimport { EventEmitter } from 'events';\nimport {\n errorFactory,\n errorFromEvent,\n newUnexpectedMessageError,\n newUnknownMethodError,\n} from \"../Error\";\nimport { QRCodeData, SCAN_QR_CODE_METHOD } from \"../QRCode\";\n\n// How long after the event's timestamp that the request times out\nconst TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes\n\n// How long after we receive the event that the request times out\nconst TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes\n\n// to avoid almost expired verification notifications\n// from showing a notification and almost immediately\n// disappearing, also ignore verification requests that\n// are this amount of time away from expiring.\nconst VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds\n\nexport const EVENT_PREFIX = \"m.key.verification.\";\nexport const REQUEST_TYPE = EVENT_PREFIX + \"request\";\nexport const START_TYPE = EVENT_PREFIX + \"start\";\nexport const CANCEL_TYPE = EVENT_PREFIX + \"cancel\";\nexport const DONE_TYPE = EVENT_PREFIX + \"done\";\nexport const READY_TYPE = EVENT_PREFIX + \"ready\";\n\nexport const PHASE_UNSENT = 1;\nexport const PHASE_REQUESTED = 2;\nexport const PHASE_READY = 3;\nexport const PHASE_STARTED = 4;\nexport const PHASE_CANCELLED = 5;\nexport const PHASE_DONE = 6;\n\n/**\n * State machine for verification requests.\n * Things that differ based on what channel is used to\n * send and receive verification events are put in `InRoomChannel` or `ToDeviceChannel`.\n * @event \"change\" whenever the state of the request object has changed.\n */\nexport class VerificationRequest extends EventEmitter {\n constructor(channel, verificationMethods, client) {\n super();\n this.channel = channel;\n this.channel._request = this;\n this._verificationMethods = verificationMethods;\n this._client = client;\n this._commonMethods = [];\n this._setPhase(PHASE_UNSENT, false);\n this._eventsByUs = new Map();\n this._eventsByThem = new Map();\n this._observeOnly = false;\n this._timeoutTimer = null;\n this._accepting = false;\n this._declining = false;\n this._verifierHasFinished = false;\n this._cancelled = false;\n this._chosenMethod = null;\n // we keep a copy of the QR Code data (including other user master key) around\n // for QR reciprocate verification, to protect against\n // cross-signing identity reset between the .ready and .start event\n // and signing the wrong key after .start\n this._qrCodeData = null;\n\n // The timestamp when we received the request event from the other side\n this._requestReceivedAt = null;\n }\n\n /**\n * Stateless validation logic not specific to the channel.\n * Invoked by the same static method in either channel.\n * @param {string} type the \"symbolic\" event type, as returned by the `getEventType` function on the channel.\n * @param {MatrixEvent} event the event to validate. Don't call getType() on it but use the `type` parameter instead.\n * @param {MatrixClient} client the client to get the current user and device id from\n * @returns {bool} whether the event is valid and should be passed to handleEvent\n */\n static validateEvent(type, event, client) {\n const content = event.getContent();\n\n if (!type || !type.startsWith(EVENT_PREFIX)) {\n return false;\n }\n\n // from here on we're fairly sure that this is supposed to be\n // part of a verification request, so be noisy when rejecting something\n if (!content) {\n logger.log(\"VerificationRequest: validateEvent: no content\");\n return false;\n }\n\n if (type === REQUEST_TYPE || type === READY_TYPE) {\n if (!Array.isArray(content.methods)) {\n logger.log(\"VerificationRequest: validateEvent: \" +\n \"fail because methods\");\n return false;\n }\n }\n\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n if (typeof content.from_device !== \"string\" ||\n content.from_device.length === 0\n ) {\n logger.log(\"VerificationRequest: validateEvent: \"+\n \"fail because from_device\");\n return false;\n }\n }\n\n return true;\n }\n\n get invalid() {\n return this.phase === PHASE_UNSENT;\n }\n\n /** returns whether the phase is PHASE_REQUESTED */\n get requested() {\n return this.phase === PHASE_REQUESTED;\n }\n\n /** returns whether the phase is PHASE_CANCELLED */\n get cancelled() {\n return this.phase === PHASE_CANCELLED;\n }\n\n /** returns whether the phase is PHASE_READY */\n get ready() {\n return this.phase === PHASE_READY;\n }\n\n /** returns whether the phase is PHASE_STARTED */\n get started() {\n return this.phase === PHASE_STARTED;\n }\n\n /** returns whether the phase is PHASE_DONE */\n get done() {\n return this.phase === PHASE_DONE;\n }\n\n /** once the phase is PHASE_STARTED (and !initiatedByMe) or PHASE_READY: common methods supported by both sides */\n get methods() {\n return this._commonMethods;\n }\n\n /** the method picked in the .start event */\n get chosenMethod() {\n return this._chosenMethod;\n }\n\n calculateEventTimeout(event) {\n let effectiveExpiresAt = this.channel.getTimestamp(event)\n + TIMEOUT_FROM_EVENT_TS;\n\n if (this._requestReceivedAt && !this.initiatedByMe &&\n this.phase <= PHASE_REQUESTED\n ) {\n const expiresAtByReceipt = this._requestReceivedAt\n + TIMEOUT_FROM_EVENT_RECEIPT;\n effectiveExpiresAt = Math.min(effectiveExpiresAt, expiresAtByReceipt);\n }\n\n return Math.max(0, effectiveExpiresAt - Date.now());\n }\n\n /** The current remaining amount of ms before the request should be automatically cancelled */\n get timeout() {\n const requestEvent = this._getEventByEither(REQUEST_TYPE);\n if (requestEvent) {\n return this.calculateEventTimeout(requestEvent);\n }\n return 0;\n }\n\n /**\n * The key verification request event.\n * @returns {MatrixEvent} The request event, or falsey if not found.\n */\n get requestEvent() {\n return this._getEventByEither(REQUEST_TYPE);\n }\n\n /** current phase of the request. Some properties might only be defined in a current phase. */\n get phase() {\n return this._phase;\n }\n\n /** The verifier to do the actual verification, once the method has been established. Only defined when the `phase` is PHASE_STARTED. */\n get verifier() {\n return this._verifier;\n }\n\n get canAccept() {\n return this.phase < PHASE_READY && !this._accepting && !this._declining;\n }\n\n get accepting() {\n return this._accepting;\n }\n\n get declining() {\n return this._declining;\n }\n\n /** whether this request has sent it's initial event and needs more events to complete */\n get pending() {\n return !this.observeOnly &&\n this._phase !== PHASE_DONE &&\n this._phase !== PHASE_CANCELLED;\n }\n\n /** Only set after a .ready if the other party can scan a QR code */\n get qrCodeData() {\n return this._qrCodeData;\n }\n\n /** Checks whether the other party supports a given verification method.\n * This is useful when setting up the QR code UI, as it is somewhat asymmetrical:\n * if the other party supports SCAN_QR, we should show a QR code in the UI, and vice versa.\n * For methods that need to be supported by both ends, use the `methods` property.\n * @param {string} method the method to check\n * @param {boolean} force to check even if the phase is not ready or started yet, internal usage\n * @return {bool} whether or not the other party said the supported the method */\n otherPartySupportsMethod(method, force = false) {\n if (!force && !this.ready && !this.started) {\n return false;\n }\n const theirMethodEvent = this._eventsByThem.get(REQUEST_TYPE) ||\n this._eventsByThem.get(READY_TYPE);\n if (!theirMethodEvent) {\n // if we started straight away with .start event,\n // we are assuming that the other side will support the\n // chosen method, so return true for that.\n if (this.started && this.initiatedByMe) {\n const myStartEvent = this._eventsByUs.get(START_TYPE);\n const content = myStartEvent && myStartEvent.getContent();\n const myStartMethod = content && content.method;\n return method == myStartMethod;\n }\n return false;\n }\n const content = theirMethodEvent.getContent();\n if (!content) {\n return false;\n }\n const { methods } = content;\n if (!Array.isArray(methods)) {\n return false;\n }\n\n return methods.includes(method);\n }\n\n /** Whether this request was initiated by the syncing user.\n * For InRoomChannel, this is who sent the .request event.\n * For ToDeviceChannel, this is who sent the .start event\n */\n get initiatedByMe() {\n // event created by us but no remote echo has been received yet\n const noEventsYet = (this._eventsByUs.size + this._eventsByThem.size) === 0;\n if (this._phase === PHASE_UNSENT && noEventsYet) {\n return true;\n }\n const hasMyRequest = this._eventsByUs.has(REQUEST_TYPE);\n const hasTheirRequest = this._eventsByThem.has(REQUEST_TYPE);\n if (hasMyRequest && !hasTheirRequest) {\n return true;\n }\n if (!hasMyRequest && hasTheirRequest) {\n return false;\n }\n const hasMyStart = this._eventsByUs.has(START_TYPE);\n const hasTheirStart = this._eventsByThem.has(START_TYPE);\n if (hasMyStart && !hasTheirStart) {\n return true;\n }\n return false;\n }\n\n /** The id of the user that initiated the request */\n get requestingUserId() {\n if (this.initiatedByMe) {\n return this._client.getUserId();\n } else {\n return this.otherUserId;\n }\n }\n\n /** The id of the user that (will) receive(d) the request */\n get receivingUserId() {\n if (this.initiatedByMe) {\n return this.otherUserId;\n } else {\n return this._client.getUserId();\n }\n }\n\n /** The user id of the other party in this request */\n get otherUserId() {\n return this.channel.userId;\n }\n\n get isSelfVerification() {\n return this._client.getUserId() === this.otherUserId;\n }\n\n /**\n * The id of the user that cancelled the request,\n * only defined when phase is PHASE_CANCELLED\n */\n get cancellingUserId() {\n const myCancel = this._eventsByUs.get(CANCEL_TYPE);\n const theirCancel = this._eventsByThem.get(CANCEL_TYPE);\n\n if (myCancel && (!theirCancel || myCancel.getId() < theirCancel.getId())) {\n return myCancel.getSender();\n }\n if (theirCancel) {\n return theirCancel.getSender();\n }\n return undefined;\n }\n\n /**\n * The cancellation code e.g m.user which is responsible for cancelling this verification\n */\n get cancellationCode() {\n const ev = this._getEventByEither(CANCEL_TYPE);\n return ev ? ev.getContent().code : null;\n }\n\n get observeOnly() {\n return this._observeOnly;\n }\n\n /**\n * Gets which device the verification should be started with\n * given the events sent so far in the verification. This is the\n * same algorithm used to determine which device to send the\n * verification to when no specific device is specified.\n * @returns {{userId: *, deviceId: *}} The device information\n */\n get targetDevice() {\n const theirFirstEvent =\n this._eventsByThem.get(REQUEST_TYPE) ||\n this._eventsByThem.get(READY_TYPE) ||\n this._eventsByThem.get(START_TYPE);\n const theirFirstContent = theirFirstEvent.getContent();\n const fromDevice = theirFirstContent.from_device;\n return {\n userId: this.otherUserId,\n deviceId: fromDevice,\n };\n }\n\n /* Start the key verification, creating a verifier and sending a .start event.\n * If no previous events have been sent, pass in `targetDevice` to set who to direct this request to.\n * @param {string} method the name of the verification method to use.\n * @param {string?} targetDevice.userId the id of the user to direct this request to\n * @param {string?} targetDevice.deviceId the id of the device to direct this request to\n * @returns {VerifierBase} the verifier of the given method\n */\n beginKeyVerification(method, targetDevice = null) {\n // need to allow also when unsent in case of to_device\n if (!this.observeOnly && !this._verifier) {\n const validStartPhase =\n this.phase === PHASE_REQUESTED ||\n this.phase === PHASE_READY ||\n (this.phase === PHASE_UNSENT &&\n this.channel.constructor.canCreateRequest(START_TYPE));\n if (validStartPhase) {\n // when called on a request that was initiated with .request event\n // check the method is supported by both sides\n if (this._commonMethods.length && !this._commonMethods.includes(method)) {\n throw newUnknownMethodError();\n }\n this._verifier = this._createVerifier(method, null, targetDevice);\n if (!this._verifier) {\n throw newUnknownMethodError();\n }\n this._chosenMethod = method;\n }\n }\n return this._verifier;\n }\n\n /**\n * sends the initial .request event.\n * @returns {Promise} resolves when the event has been sent.\n */\n async sendRequest() {\n if (!this.observeOnly && this._phase === PHASE_UNSENT) {\n const methods = [...this._verificationMethods.keys()];\n await this.channel.send(REQUEST_TYPE, { methods });\n }\n }\n\n /**\n * Cancels the request, sending a cancellation to the other party\n * @param {string?} error.reason the error reason to send the cancellation with\n * @param {string?} error.code the error code to send the cancellation with\n * @returns {Promise} resolves when the event has been sent.\n */\n async cancel({ reason = \"User declined\", code = \"m.user\" } = {}) {\n if (!this.observeOnly && this._phase !== PHASE_CANCELLED) {\n this._declining = true;\n this.emit(\"change\");\n if (this._verifier) {\n return this._verifier.cancel(errorFactory(code, reason)());\n } else {\n this._cancellingUserId = this._client.getUserId();\n await this.channel.send(CANCEL_TYPE, { code, reason });\n }\n }\n }\n\n /**\n * Accepts the request, sending a .ready event to the other party\n * @returns {Promise} resolves when the event has been sent.\n */\n async accept() {\n if (!this.observeOnly && this.phase === PHASE_REQUESTED && !this.initiatedByMe) {\n const methods = [...this._verificationMethods.keys()];\n this._accepting = true;\n this.emit(\"change\");\n await this.channel.send(READY_TYPE, { methods });\n }\n }\n\n /**\n * Can be used to listen for state changes until the callback returns true.\n * @param {Function} fn callback to evaluate whether the request is in the desired state.\n * Takes the request as an argument.\n * @returns {Promise} that resolves once the callback returns true\n * @throws {Error} when the request is cancelled\n */\n waitFor(fn) {\n return new Promise((resolve, reject) => {\n const check = () => {\n let handled = false;\n if (fn(this)) {\n resolve(this);\n handled = true;\n } else if (this.cancelled) {\n reject(new Error(\"cancelled\"));\n handled = true;\n }\n if (handled) {\n this.off(\"change\", check);\n }\n return handled;\n };\n if (!check()) {\n this.on(\"change\", check);\n }\n });\n }\n\n _setPhase(phase, notify = true) {\n this._phase = phase;\n if (notify) {\n this.emit(\"change\");\n }\n }\n\n _getEventByEither(type) {\n return this._eventsByThem.get(type) || this._eventsByUs.get(type);\n }\n\n _getEventBy(type, byThem) {\n if (byThem) {\n return this._eventsByThem.get(type);\n } else {\n return this._eventsByUs.get(type);\n }\n }\n\n _calculatePhaseTransitions() {\n const transitions = [{ phase: PHASE_UNSENT }];\n const phase = () => transitions[transitions.length - 1].phase;\n\n // always pass by .request first to be sure channel.userId has been set\n const hasRequestByThem = this._eventsByThem.has(REQUEST_TYPE);\n const requestEvent = this._getEventBy(REQUEST_TYPE, hasRequestByThem);\n if (requestEvent) {\n transitions.push({ phase: PHASE_REQUESTED, event: requestEvent });\n }\n\n const readyEvent =\n requestEvent && this._getEventBy(READY_TYPE, !hasRequestByThem);\n if (readyEvent && phase() === PHASE_REQUESTED) {\n transitions.push({ phase: PHASE_READY, event: readyEvent });\n }\n\n let startEvent;\n if (readyEvent || !requestEvent) {\n const theirStartEvent = this._eventsByThem.get(START_TYPE);\n const ourStartEvent = this._eventsByUs.get(START_TYPE);\n // any party can send .start after a .ready or unsent\n if (theirStartEvent && ourStartEvent) {\n startEvent = theirStartEvent.getSender() < ourStartEvent.getSender() ?\n theirStartEvent : ourStartEvent;\n } else {\n startEvent = theirStartEvent ? theirStartEvent : ourStartEvent;\n }\n } else {\n startEvent = this._getEventBy(START_TYPE, !hasRequestByThem);\n }\n if (startEvent) {\n const fromRequestPhase = phase() === PHASE_REQUESTED &&\n requestEvent.getSender() !== startEvent.getSender();\n const fromUnsentPhase = phase() === PHASE_UNSENT &&\n this.channel.constructor.canCreateRequest(START_TYPE);\n if (fromRequestPhase || phase() === PHASE_READY || fromUnsentPhase) {\n transitions.push({ phase: PHASE_STARTED, event: startEvent });\n }\n }\n\n const ourDoneEvent = this._eventsByUs.get(DONE_TYPE);\n if (this._verifierHasFinished || (ourDoneEvent && phase() === PHASE_STARTED)) {\n transitions.push({ phase: PHASE_DONE });\n }\n\n const cancelEvent = this._getEventByEither(CANCEL_TYPE);\n if ((this._cancelled || cancelEvent) && phase() !== PHASE_DONE) {\n transitions.push({ phase: PHASE_CANCELLED, event: cancelEvent });\n return transitions;\n }\n\n return transitions;\n }\n\n _transitionToPhase(transition) {\n const { phase, event } = transition;\n // get common methods\n if (phase === PHASE_REQUESTED || phase === PHASE_READY) {\n if (!this._wasSentByOwnDevice(event)) {\n const content = event.getContent();\n this._commonMethods =\n content.methods.filter(m => this._verificationMethods.has(m));\n }\n }\n // detect if we're not a party in the request, and we should just observe\n if (!this.observeOnly) {\n // if requested or accepted by one of my other devices\n if (phase === PHASE_REQUESTED ||\n phase === PHASE_STARTED ||\n phase === PHASE_READY\n ) {\n if (\n this.channel.receiveStartFromOtherDevices &&\n this._wasSentByOwnUser(event) &&\n !this._wasSentByOwnDevice(event)\n ) {\n this._observeOnly = true;\n }\n }\n }\n // create verifier\n if (phase === PHASE_STARTED) {\n const { method } = event.getContent();\n if (!this._verifier && !this.observeOnly) {\n this._verifier = this._createVerifier(method, event);\n if (!this._verifier) {\n this.cancel({\n code: \"m.unknown_method\",\n reason: `Unknown method: ${method}`,\n });\n } else {\n this._chosenMethod = method;\n }\n }\n }\n }\n\n _applyPhaseTransitions() {\n const transitions = this._calculatePhaseTransitions();\n const existingIdx = transitions.findIndex(t => t.phase === this.phase);\n // trim off phases we already went through, if any\n const newTransitions = transitions.slice(existingIdx + 1);\n // transition to all new phases\n for (const transition of newTransitions) {\n this._transitionToPhase(transition);\n }\n return newTransitions;\n }\n\n _isWinningStartRace(newEvent) {\n if (newEvent.getType() !== START_TYPE) {\n return false;\n }\n const oldEvent = this._verifier.startEvent;\n\n let oldRaceIdentifier;\n if (this.isSelfVerification) {\n // if the verifier does not have a startEvent,\n // it is because it's still sending and we are on the initator side\n // we know we are sending a .start event because we already\n // have a verifier (checked in calling method)\n if (oldEvent) {\n const oldContent = oldEvent.getContent();\n oldRaceIdentifier = oldContent && oldContent.from_device;\n } else {\n oldRaceIdentifier = this._client.getDeviceId();\n }\n } else {\n if (oldEvent) {\n oldRaceIdentifier = oldEvent.getSender();\n } else {\n oldRaceIdentifier = this._client.getUserId();\n }\n }\n\n let newRaceIdentifier;\n if (this.isSelfVerification) {\n const newContent = newEvent.getContent();\n newRaceIdentifier = newContent && newContent.from_device;\n } else {\n newRaceIdentifier = newEvent.getSender();\n }\n return newRaceIdentifier < oldRaceIdentifier;\n }\n\n hasEventId(eventId) {\n for (const event of this._eventsByUs.values()) {\n if (event.getId() === eventId) {\n return true;\n }\n }\n for (const event of this._eventsByThem.values()) {\n if (event.getId() === eventId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Changes the state of the request and verifier in response to a key verification event.\n * @param {string} type the \"symbolic\" event type, as returned by the `getEventType` function on the channel.\n * @param {MatrixEvent} event the event to handle. Don't call getType() on it but use the `type` parameter instead.\n * @param {bool} isLiveEvent whether this is an even received through sync or not\n * @param {bool} isRemoteEcho whether this is the remote echo of an event sent by the same device\n * @param {bool} isSentByUs whether this event is sent by a party that can accept and/or observe the request like one of our peers.\n * For InRoomChannel this means any device for the syncing user. For ToDeviceChannel, just the syncing device.\n * @returns {Promise} a promise that resolves when any requests as an anwser to the passed-in event are sent.\n */\n async handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs) {\n // if reached phase cancelled or done, ignore anything else that comes\n if (this.done || this.cancelled) {\n return;\n }\n const wasObserveOnly = this._observeOnly;\n\n this._adjustObserveOnly(event, isLiveEvent);\n\n if (!this.observeOnly && !isRemoteEcho) {\n if (await this._cancelOnError(type, event)) {\n return;\n }\n }\n\n // This assumes verification won't need to send an event with\n // the same type for the same party twice.\n // This is true for QR and SAS verification, and was\n // added here to prevent verification getting cancelled\n // when the server duplicates an event (https://github.com/matrix-org/synapse/issues/3365)\n const isDuplicateEvent = isSentByUs ?\n this._eventsByUs.has(type) :\n this._eventsByThem.has(type);\n if (isDuplicateEvent) {\n return;\n }\n\n const oldPhase = this.phase;\n this._addEvent(type, event, isSentByUs);\n\n // this will create if needed the verifier so needs to happen before calling it\n const newTransitions = this._applyPhaseTransitions();\n try {\n // only pass events from the other side to the verifier,\n // no remote echos of our own events\n if (this._verifier && !this.observeOnly) {\n const newEventWinsRace = this._isWinningStartRace(event);\n if (this._verifier.canSwitchStartEvent(event) && newEventWinsRace) {\n this._verifier.switchStartEvent(event);\n } else if (!isRemoteEcho) {\n if (type === CANCEL_TYPE || (this._verifier.events\n && this._verifier.events.includes(type))) {\n this._verifier.handleEvent(event);\n }\n }\n }\n\n if (newTransitions.length) {\n // create QRCodeData if the other side can scan\n // important this happens before emitting a phase change,\n // so listeners can rely on it being there already\n // We only do this for live events because it is important that\n // we sign the keys that were in the QR code, and not the keys\n // we happen to have at some later point in time.\n if (isLiveEvent && newTransitions.some(t => t.phase === PHASE_READY)) {\n const shouldGenerateQrCode =\n this.otherPartySupportsMethod(SCAN_QR_CODE_METHOD, true);\n if (shouldGenerateQrCode) {\n this._qrCodeData = await QRCodeData.create(this, this._client);\n }\n }\n\n const lastTransition = newTransitions[newTransitions.length - 1];\n const { phase } = lastTransition;\n\n this._setupTimeout(phase);\n // set phase as last thing as this emits the \"change\" event\n this._setPhase(phase);\n } else if (this._observeOnly !== wasObserveOnly) {\n this.emit(\"change\");\n }\n } finally {\n // log events we processed so we can see from rageshakes what events were added to a request\n logger.log(`Verification request ${this.channel.transactionId}: ` +\n `${type} event with id:${event.getId()}, ` +\n `content:${JSON.stringify(event.getContent())} ` +\n `deviceId:${this.channel.deviceId}, ` +\n `sender:${event.getSender()}, isSentByUs:${isSentByUs}, ` +\n `isLiveEvent:${isLiveEvent}, isRemoteEcho:${isRemoteEcho}, ` +\n `phase:${oldPhase}=>${this.phase}, ` +\n `observeOnly:${wasObserveOnly}=>${this._observeOnly}`);\n }\n }\n\n _setupTimeout(phase) {\n const shouldTimeout = !this._timeoutTimer && !this.observeOnly &&\n phase === PHASE_REQUESTED;\n\n if (shouldTimeout) {\n this._timeoutTimer = setTimeout(this._cancelOnTimeout, this.timeout);\n }\n if (this._timeoutTimer) {\n const shouldClear = phase === PHASE_STARTED ||\n phase === PHASE_READY ||\n phase === PHASE_DONE ||\n phase === PHASE_CANCELLED;\n if (shouldClear) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = null;\n }\n }\n }\n\n _cancelOnTimeout = () => {\n try {\n if (this.initiatedByMe) {\n this.cancel({\n reason: \"Other party didn't accept in time\",\n code: \"m.timeout\",\n });\n } else {\n this.cancel({\n reason: \"User didn't accept in time\",\n code: \"m.timeout\",\n });\n }\n } catch (err) {\n logger.error(\"Error while cancelling verification request\", err);\n }\n };\n\n async _cancelOnError(type, event) {\n if (type === START_TYPE) {\n const method = event.getContent().method;\n if (!this._verificationMethods.has(method)) {\n await this.cancel(errorFromEvent(newUnknownMethodError()));\n return true;\n }\n }\n\n const isUnexpectedRequest = type === REQUEST_TYPE && this.phase !== PHASE_UNSENT;\n const isUnexpectedReady = type === READY_TYPE && this.phase !== PHASE_REQUESTED;\n // only if phase has passed from PHASE_UNSENT should we cancel, because events\n // are allowed to come in in any order (at least with InRoomChannel). So we only know\n // we're dealing with a valid request we should participate in once we've moved to PHASE_REQUESTED\n // before that, we could be looking at somebody elses verification request and we just\n // happen to be in the room\n if (this.phase !== PHASE_UNSENT && (isUnexpectedRequest || isUnexpectedReady)) {\n logger.warn(`Cancelling, unexpected ${type} verification ` +\n `event from ${event.getSender()}`);\n const reason = `Unexpected ${type} event in phase ${this.phase}`;\n await this.cancel(errorFromEvent(newUnexpectedMessageError({ reason })));\n return true;\n }\n return false;\n }\n\n _adjustObserveOnly(event, isLiveEvent) {\n // don't send out events for historical requests\n if (!isLiveEvent) {\n this._observeOnly = true;\n }\n if (this.calculateEventTimeout(event) < VERIFICATION_REQUEST_MARGIN) {\n this._observeOnly = true;\n }\n }\n\n _addEvent(type, event, isSentByUs) {\n if (isSentByUs) {\n this._eventsByUs.set(type, event);\n } else {\n this._eventsByThem.set(type, event);\n }\n\n // once we know the userId of the other party (from the .request event)\n // see if any event by anyone else crept into this._eventsByThem\n if (type === REQUEST_TYPE) {\n for (const [type, event] of this._eventsByThem.entries()) {\n if (event.getSender() !== this.otherUserId) {\n this._eventsByThem.delete(type);\n }\n }\n // also remember when we received the request event\n this._requestReceivedAt = Date.now();\n }\n }\n\n _createVerifier(method, startEvent = null, targetDevice = null) {\n if (!targetDevice) {\n targetDevice = this.targetDevice;\n }\n const { userId, deviceId } = targetDevice;\n\n const VerifierCtor = this._verificationMethods.get(method);\n if (!VerifierCtor) {\n logger.warn(\"could not find verifier constructor for method\", method);\n return;\n }\n return new VerifierCtor(\n this.channel,\n this._client,\n userId,\n deviceId,\n startEvent,\n this,\n );\n }\n\n _wasSentByOwnUser(event) {\n return event.getSender() === this._client.getUserId();\n }\n\n // only for .request, .ready or .start\n _wasSentByOwnDevice(event) {\n if (!this._wasSentByOwnUser(event)) {\n return false;\n }\n const content = event.getContent();\n if (!content || content.from_device !== this._client.getDeviceId()) {\n return false;\n }\n return true;\n }\n\n onVerifierCancelled() {\n this._cancelled = true;\n // move to cancelled phase\n const newTransitions = this._applyPhaseTransitions();\n if (newTransitions.length) {\n this._setPhase(newTransitions[newTransitions.length - 1].phase);\n }\n }\n\n onVerifierFinished() {\n this.channel.send(\"m.key.verification.done\", {});\n this._verifierHasFinished = true;\n // move to .done phase\n const newTransitions = this._applyPhaseTransitions();\n if (newTransitions.length) {\n this._setPhase(newTransitions[newTransitions.length - 1].phase);\n }\n }\n\n getEventFromOtherParty(type) {\n return this._eventsByThem.get(type);\n }\n}\n",
"// can't just do InvalidStoreError extends Error\n// because of http://babeljs.io/docs/usage/caveats/#classes\nexport function InvalidStoreError(reason, value) {\n const message = `Store is invalid because ${reason}, ` +\n `please stop the client, delete all data and start the client again`;\n const instance = Reflect.construct(Error, [message]);\n Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));\n instance.reason = reason;\n instance.value = value;\n return instance;\n}\n\nInvalidStoreError.TOGGLED_LAZY_LOADING = \"TOGGLED_LAZY_LOADING\";\n\nInvalidStoreError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: Error,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n});\nReflect.setPrototypeOf(InvalidStoreError, Error);\n\nexport function InvalidCryptoStoreError(reason) {\n const message = `Crypto store is invalid because ${reason}, ` +\n `please stop the client, delete all data and start the client again`;\n const instance = Reflect.construct(Error, [message]);\n Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));\n instance.reason = reason;\n instance.name = 'InvalidCryptoStoreError';\n return instance;\n}\n\nInvalidCryptoStoreError.TOO_NEW = \"TOO_NEW\";\n\nInvalidCryptoStoreError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: Error,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n});\nReflect.setPrototypeOf(InvalidCryptoStoreError, Error);\n\nexport class KeySignatureUploadError extends Error {\n constructor(message, value) {\n super(message);\n this.value = value;\n }\n}\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"./client\";\nimport { MatrixEvent } from \"./models/event\";\n\nexport type EventMapper = (obj: any) => MatrixEvent;\n\nexport interface MapperOpts {\n preventReEmit?: boolean;\n decrypt?: boolean;\n}\n\nexport function eventMapperFor(client: MatrixClient, options: MapperOpts): EventMapper {\n const preventReEmit = Boolean(options.preventReEmit);\n const decrypt = options.decrypt !== false;\n\n function mapper(plainOldJsObject) {\n const event = new MatrixEvent(plainOldJsObject);\n if (event.isEncrypted()) {\n if (!preventReEmit) {\n client.reEmitter.reEmit(event, [\n \"Event.decrypted\",\n ]);\n }\n if (decrypt) {\n client.decryptEventIfNeeded(event);\n }\n }\n if (!preventReEmit) {\n client.reEmitter.reEmit(event, [\"Event.replaced\"]);\n }\n return event;\n }\n\n return mapper;\n}\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n * @module filter-component\n */\n\n/**\n * Checks if a value matches a given field value, which may be a * terminated\n * wildcard pattern.\n * @param {String} actualValue The value to be compared\n * @param {String} filterValue The filter pattern to be compared\n * @return {boolean} true if the actualValue matches the filterValue\n */\nfunction matchesWildcard(actualValue: string, filterValue: string): boolean {\n if (filterValue.endsWith(\"*\")) {\n const typePrefix = filterValue.slice(0, -1);\n return actualValue.substr(0, typePrefix.length) === typePrefix;\n } else {\n return actualValue === filterValue;\n }\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterComponent {\n types?: string[];\n not_types?: string[];\n rooms?: string[];\n not_rooms?: string[];\n senders?: string[];\n not_senders?: string[];\n contains_url?: boolean;\n limit?: number;\n}\n/* eslint-enable camelcase */\n\n/**\n * FilterComponent is a section of a Filter definition which defines the\n * types, rooms, senders filters etc to be applied to a particular type of resource.\n * This is all ported over from synapse's Filter object.\n *\n * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as\n * 'Filters' are referred to as 'FilterCollections'.\n *\n * @constructor\n * @param {Object} filterJson the definition of this filter JSON, e.g. { 'contains_url': true }\n */\nexport class FilterComponent {\n constructor(private filterJson: IFilterComponent) {}\n\n /**\n * Checks with the filter component matches the given event\n * @param {MatrixEvent} event event to be checked against the filter\n * @return {boolean} true if the event matches the filter\n */\n public check(event: MatrixEvent): boolean {\n return this.checkFields(\n event.getRoomId(),\n event.getSender(),\n event.getType(),\n event.getContent() ? event.getContent().url !== undefined : false,\n );\n }\n\n /**\n * Converts the filter component into the form expected over the wire\n */\n public toJSON(): object {\n return {\n types: this.filterJson.types || null,\n not_types: this.filterJson.not_types || [],\n rooms: this.filterJson.rooms || null,\n not_rooms: this.filterJson.not_rooms || [],\n senders: this.filterJson.senders || null,\n not_senders: this.filterJson.not_senders || [],\n contains_url: this.filterJson.contains_url || null,\n };\n }\n\n /**\n * Checks whether the filter component matches the given event fields.\n * @param {String} roomId the roomId for the event being checked\n * @param {String} sender the sender of the event being checked\n * @param {String} eventType the type of the event being checked\n * @param {boolean} containsUrl whether the event contains a content.url field\n * @return {boolean} true if the event fields match the filter\n */\n private checkFields(roomId: string, sender: string, eventType: string, containsUrl: boolean): boolean {\n const literalKeys = {\n \"rooms\": function(v: string): boolean {\n return roomId === v;\n },\n \"senders\": function(v: string): boolean {\n return sender === v;\n },\n \"types\": function(v: string): boolean {\n return matchesWildcard(eventType, v);\n },\n };\n\n for (let n = 0; n < Object.keys(literalKeys).length; n++) {\n const name = Object.keys(literalKeys)[n];\n const matchFunc = literalKeys[name];\n const notName = \"not_\" + name;\n const disallowedValues: string[] = this.filterJson[notName];\n if (disallowedValues?.some(matchFunc)) {\n return false;\n }\n\n const allowedValues: string[] = this.filterJson[name];\n if (allowedValues && !allowedValues.some(matchFunc)) {\n return false;\n }\n }\n\n const containsUrlFilter = this.filterJson.contains_url;\n if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Filters a list of events down to those which match this filter component\n * @param {MatrixEvent[]} events Events to be checked against the filter component\n * @return {MatrixEvent[]} events which matched the filter component\n */\n filter(events: MatrixEvent[]): MatrixEvent[] {\n return events.filter(this.check, this);\n }\n\n /**\n * Returns the limit field for a given filter component, providing a default of\n * 10 if none is otherwise specified. Cargo-culted from Synapse.\n * @return {Number} the limit for this filter component.\n */\n limit(): number {\n return this.filterJson.limit !== undefined ? this.filterJson.limit : 10;\n }\n}\n",
"/*\nCopyright 2015 - 2021 Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module filter\n */\n\nimport { FilterComponent, IFilterComponent } from \"./filter-component\";\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n * @param {Object} obj\n * @param {string} keyNesting\n * @param {*} val\n */\nfunction setProp(obj: object, keyNesting: string, val: any) {\n const nestedKeys = keyNesting.split(\".\");\n let currentObj = obj;\n for (let i = 0; i < (nestedKeys.length - 1); i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\ninterface IFilterDefinition {\n event_fields?: string[];\n event_format?: \"client\" | \"federation\";\n presence?: IFilterComponent;\n account_data?: IFilterComponent;\n room?: IRoomFilter;\n}\n\ninterface IRoomEventFilter extends IFilterComponent {\n lazy_load_members?: boolean;\n include_redundant_members?: boolean;\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n/* eslint-enable camelcase */\n\n/**\n * Construct a new Filter.\n * @constructor\n * @param {string} userId The user ID for this filter.\n * @param {string=} filterId The filter ID if known.\n * @prop {string} userId The user ID of the filter\n * @prop {?string} filterId The filter ID\n */\nexport class Filter {\n static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n * @static\n * @param {string} userId\n * @param {string} filterId\n * @param {Object} jsonObj\n * @return {Filter}\n */\n static fromJson(userId: string, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter: FilterComponent;\n private roomTimelineFilter: FilterComponent;\n\n constructor(public readonly userId: string, public filterId?: string) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @return {?string} The filter ID\n */\n getFilterId(): string | null {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @return {Object} The filter definition\n */\n getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param {Object} definition The filter definition\n */\n setDefinition(definition: IFilterDefinition) {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filter\n const roomFilterFields: IRoomFilter = {};\n if (roomFilterJson) {\n if (roomFilterJson.rooms) {\n roomFilterFields.rooms = roomFilterJson.rooms;\n }\n if (roomFilterJson.rooms) {\n roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n }\n }\n\n this.roomFilter = new FilterComponent(roomFilterFields);\n this.roomTimelineFilter = new FilterComponent(roomFilterJson?.timeline || {});\n\n // don't bother porting this from synapse yet:\n // this._room_state_filter =\n // new FilterComponent(roomFilterJson.state || {});\n // this._room_ephemeral_filter =\n // new FilterComponent(roomFilterJson.ephemeral || {});\n // this._room_account_data_filter =\n // new FilterComponent(roomFilterJson.account_data || {});\n // this._presence_filter =\n // new FilterComponent(definition.presence || {});\n // this._account_data_filter =\n // new FilterComponent(definition.account_data || {});\n }\n\n /**\n * Get the room.timeline filter component of the filter\n * @return {FilterComponent} room timeline filter component\n */\n getRoomTimelineFilterComponent(): FilterComponent {\n return this.roomTimelineFilter;\n }\n\n /**\n * Filter the list of events based on whether they are allowed in a timeline\n * based on this filter\n * @param {MatrixEvent[]} events the list of events being filtered\n * @return {MatrixEvent[]} the list of events which match the filter\n */\n filterRoomTimeline(events: MatrixEvent[]): MatrixEvent[] {\n return this.roomTimelineFilter.filter(this.roomFilter.filter(events));\n }\n\n /**\n * Set the max number of events to return for each room's timeline.\n * @param {Number} limit The max number of events to return for each room.\n */\n setTimelineLimit(limit: number) {\n setProp(this.definition, \"room.timeline.limit\", limit);\n }\n\n setLazyLoadMembers(enabled: boolean) {\n setProp(this.definition, \"room.state.lazy_load_members\", !!enabled);\n }\n\n /**\n * Control whether left rooms should be included in responses.\n * @param {boolean} includeLeave True to make rooms the user has left appear\n * in responses.\n */\n setIncludeLeaveRooms(includeLeave: boolean) {\n setProp(this.definition, \"room.include_leave\", includeLeave);\n }\n}\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n * @module http-api\n */\n\nimport { parse as parseContentType } from \"content-type\";\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\n\n// we use our own implementation of setTimeout, so that if we get suspended in\n// the middle of a /sync, we cancel the sync as soon as we awake, rather than\n// waiting for the delay to elapse.\nimport * as callbacks from \"./realtime-callbacks\";\n\n/*\nTODO:\n- CS: complete register function (doing stages)\n- Identity server: linkEmail, authEmail, bindEmail, lookup3pid\n*/\n\n/**\n * A constant representing the URI path for release 0 of the Client-Server HTTP API.\n */\nexport const PREFIX_R0 = \"/_matrix/client/r0\";\n\n/**\n * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n */\nexport const PREFIX_UNSTABLE = \"/_matrix/client/unstable\";\n\n/**\n * URI path for v1 of the the identity API\n * @deprecated Use v2.\n */\nexport const PREFIX_IDENTITY_V1 = \"/_matrix/identity/api/v1\";\n\n/**\n * URI path for the v2 identity API\n */\nexport const PREFIX_IDENTITY_V2 = \"/_matrix/identity/v2\";\n\n/**\n * URI path for the media repo API\n */\nexport const PREFIX_MEDIA_R0 = \"/_matrix/media/r0\";\n\n/**\n * Construct a MatrixHttpApi.\n * @constructor\n * @param {EventEmitter} event_emitter The event emitter to use for emitting events\n * @param {Object} opts The options to use for this HTTP API.\n * @param {string} opts.baseUrl Required. The base client-server URL e.g.\n * 'http://localhost:8008'.\n * @param {Function} opts.request Required. The function to call for HTTP\n * requests. This function must look like function(opts, callback){ ... }.\n * @param {string} opts.prefix Required. The matrix client prefix to use, e.g.\n * '/_matrix/client/r0'. See PREFIX_R0 and PREFIX_UNSTABLE for constants.\n *\n * @param {boolean} opts.onlyData True to return only the 'data' component of the\n * response (e.g. the parsed HTTP body). If false, requests will return an\n * object with the properties <tt>code</tt>, <tt>headers</tt> and <tt>data</tt>.\n *\n * @param {string} opts.accessToken The access_token to send with requests. Can be\n * null to not send an access token.\n * @param {Object=} opts.extraParams Optional. Extra query parameters to send on\n * requests.\n * @param {Number=} opts.localTimeoutMs The default maximum amount of time to wait\n * before timing out the request. If not specified, there is no timeout.\n * @param {boolean} [opts.useAuthorizationHeader = false] Set to true to use\n * Authorization header instead of query param to send the access token to the server.\n */\nexport function MatrixHttpApi(event_emitter, opts) {\n utils.checkObjectHasKeys(opts, [\"baseUrl\", \"request\", \"prefix\"]);\n opts.onlyData = opts.onlyData || false;\n this.event_emitter = event_emitter;\n this.opts = opts;\n this.useAuthorizationHeader = Boolean(opts.useAuthorizationHeader);\n this.uploads = [];\n}\n\nMatrixHttpApi.prototype = {\n /**\n * Sets the baase URL for the identity server\n * @param {string} url The new base url\n */\n setIdBaseUrl: function(url) {\n this.opts.idBaseUrl = url;\n },\n\n /**\n * Get the content repository url with query parameters.\n * @return {Object} An object with a 'base', 'path' and 'params' for base URL,\n * path and query parameters respectively.\n */\n getContentUri: function() {\n const params = {\n access_token: this.opts.accessToken,\n };\n return {\n base: this.opts.baseUrl,\n path: \"/_matrix/media/r0/upload\",\n params: params,\n };\n },\n\n /**\n * Upload content to the Home Server\n *\n * @param {object} file The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a Buffer, String or ReadStream.\n *\n * @param {object} opts options object\n *\n * @param {string=} opts.name Name to give the file on the server. Defaults\n * to <tt>file.name</tt>.\n *\n * @param {boolean=} opts.includeFilename if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n *\n * @param {string=} opts.type Content-type for the upload. Defaults to\n * <tt>file.type</tt>, or <tt>applicaton/octet-stream</tt>.\n *\n * @param {boolean=} opts.rawResponse Return the raw body, rather than\n * parsing the JSON. Defaults to false (except on node.js, where it\n * defaults to true for backwards compatibility).\n *\n * @param {boolean=} opts.onlyContentUri Just return the content URI,\n * rather than the whole body. Defaults to false (except on browsers,\n * where it defaults to true for backwards compatibility). Ignored if\n * opts.rawResponse is true.\n *\n * @param {Function=} opts.callback Deprecated. Optional. The callback to\n * invoke on success/failure. See the promise return values for more\n * information.\n *\n * @param {Function=} opts.progressHandler Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n *\n * @return {Promise} Resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n uploadContent: function(file, opts) {\n if (utils.isFunction(opts)) {\n // opts used to be callback\n opts = {\n callback: opts,\n };\n } else if (opts === undefined) {\n opts = {};\n }\n\n // default opts.includeFilename to true (ignoring falsey values)\n const includeFilename = opts.includeFilename !== false;\n\n // if the file doesn't have a mime type, use a default since\n // the HS errors if we don't supply one.\n const contentType = opts.type || file.type || 'application/octet-stream';\n const fileName = opts.name || file.name;\n\n // We used to recommend setting file.stream to the thing to upload on\n // Node.js. As of 2019-06-11, this is still in widespread use in various\n // clients, so we should preserve this for simple objects used in\n // Node.js. File API objects (via either the File or Blob interfaces) in\n // the browser now define a `stream` method, which leads to trouble\n // here, so we also check the type of `stream`.\n let body = file;\n if (body.stream && typeof body.stream !== \"function\") {\n logger.warn(\n \"Using `file.stream` as the content to upload. Future \" +\n \"versions of the js-sdk will change this to expect `file` to \" +\n \"be the content directly.\",\n );\n body = body.stream;\n }\n\n // backwards-compatibility hacks where we used to do different things\n // between browser and node.\n let rawResponse = opts.rawResponse;\n if (rawResponse === undefined) {\n if (global.XMLHttpRequest) {\n rawResponse = false;\n } else {\n logger.warn(\n \"Returning the raw JSON from uploadContent(). Future \" +\n \"versions of the js-sdk will change this default, to \" +\n \"return the parsed object. Set opts.rawResponse=false \" +\n \"to change this behaviour now.\",\n );\n rawResponse = true;\n }\n }\n\n let onlyContentUri = opts.onlyContentUri;\n if (!rawResponse && onlyContentUri === undefined) {\n if (global.XMLHttpRequest) {\n logger.warn(\n \"Returning only the content-uri from uploadContent(). \" +\n \"Future versions of the js-sdk will change this \" +\n \"default, to return the whole response object. Set \" +\n \"opts.onlyContentUri=false to change this behaviour now.\",\n );\n onlyContentUri = true;\n } else {\n onlyContentUri = false;\n }\n }\n\n // browser-request doesn't support File objects because it deep-copies\n // the options using JSON.parse(JSON.stringify(options)). Instead of\n // loading the whole file into memory as a string and letting\n // browser-request base64 encode and then decode it again, we just\n // use XMLHttpRequest directly.\n // (browser-request doesn't support progress either, which is also kind\n // of important here)\n\n const upload = { loaded: 0, total: 0 };\n let promise;\n\n // XMLHttpRequest doesn't parse JSON for us. request normally does, but\n // we're setting opts.json=false so that it doesn't JSON-encode the\n // request, which also means it doesn't JSON-decode the response. Either\n // way, we have to JSON-parse the response ourselves.\n let bodyParser = null;\n if (!rawResponse) {\n bodyParser = function(rawBody) {\n let body = JSON.parse(rawBody);\n if (onlyContentUri) {\n body = body.content_uri;\n if (body === undefined) {\n throw Error('Bad response');\n }\n }\n return body;\n };\n }\n\n if (global.XMLHttpRequest) {\n const defer = utils.defer();\n const xhr = new global.XMLHttpRequest();\n upload.xhr = xhr;\n const cb = requestCallback(defer, opts.callback, this.opts.onlyData);\n\n const timeout_fn = function() {\n xhr.abort();\n cb(new Error('Timeout'));\n };\n\n // set an initial timeout of 30s; we'll advance it each time we get\n // a progress notification\n xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);\n\n xhr.onreadystatechange = function() {\n let resp;\n switch (xhr.readyState) {\n case global.XMLHttpRequest.DONE:\n callbacks.clearTimeout(xhr.timeout_timer);\n try {\n if (xhr.status === 0) {\n throw new AbortError();\n }\n if (!xhr.responseText) {\n throw new Error('No response body.');\n }\n resp = xhr.responseText;\n if (bodyParser) {\n resp = bodyParser(resp);\n }\n } catch (err) {\n err.http_status = xhr.status;\n cb(err);\n return;\n }\n cb(undefined, xhr, resp);\n break;\n }\n };\n xhr.upload.addEventListener(\"progress\", function(ev) {\n callbacks.clearTimeout(xhr.timeout_timer);\n upload.loaded = ev.loaded;\n upload.total = ev.total;\n xhr.timeout_timer = callbacks.setTimeout(timeout_fn, 30000);\n if (opts.progressHandler) {\n opts.progressHandler({\n loaded: ev.loaded,\n total: ev.total,\n });\n }\n });\n let url = this.opts.baseUrl + \"/_matrix/media/r0/upload\";\n\n const queryArgs = [];\n\n if (includeFilename && fileName) {\n queryArgs.push(\"filename=\" + encodeURIComponent(fileName));\n }\n\n if (!this.useAuthorizationHeader) {\n queryArgs.push(\"access_token=\"\n + encodeURIComponent(this.opts.accessToken));\n }\n\n if (queryArgs.length > 0) {\n url += \"?\" + queryArgs.join(\"&\");\n }\n\n xhr.open(\"POST\", url);\n if (this.useAuthorizationHeader) {\n xhr.setRequestHeader(\"Authorization\", \"Bearer \" + this.opts.accessToken);\n }\n xhr.setRequestHeader(\"Content-Type\", contentType);\n xhr.send(body);\n promise = defer.promise;\n\n // dirty hack (as per _request) to allow the upload to be cancelled.\n promise.abort = xhr.abort.bind(xhr);\n } else {\n const queryParams = {};\n\n if (includeFilename && fileName) {\n queryParams.filename = fileName;\n }\n\n promise = this.authedRequest(\n opts.callback, \"POST\", \"/upload\", queryParams, body, {\n prefix: \"/_matrix/media/r0\",\n headers: { \"Content-Type\": contentType },\n json: false,\n bodyParser: bodyParser,\n },\n );\n }\n\n const self = this;\n\n // remove the upload from the list on completion\n const promise0 = promise.finally(function() {\n for (let i = 0; i < self.uploads.length; ++i) {\n if (self.uploads[i] === upload) {\n self.uploads.splice(i, 1);\n return;\n }\n }\n });\n\n // copy our dirty abort() method to the new promise\n promise0.abort = promise.abort;\n\n upload.promise = promise0;\n this.uploads.push(upload);\n\n return promise0;\n },\n\n cancelUpload: function(promise) {\n if (promise.abort) {\n promise.abort();\n return true;\n }\n return false;\n },\n\n getCurrentUploads: function() {\n return this.uploads;\n },\n\n idServerRequest: function(\n callback,\n method,\n path,\n params,\n prefix,\n accessToken,\n ) {\n if (!this.opts.idBaseUrl) {\n throw new Error(\"No Identity Server base URL set\");\n }\n\n const fullUri = this.opts.idBaseUrl + prefix + path;\n\n if (callback !== undefined && !utils.isFunction(callback)) {\n throw Error(\n \"Expected callback to be a function but got \" + typeof callback,\n );\n }\n\n const opts = {\n uri: fullUri,\n method: method,\n withCredentials: false,\n json: true, // we want a JSON response if we can\n _matrix_opts: this.opts,\n headers: {},\n };\n if (method === 'GET') {\n opts.qs = params;\n } else if (typeof params === \"object\") {\n opts.json = params;\n }\n if (accessToken) {\n opts.headers['Authorization'] = `Bearer ${accessToken}`;\n }\n\n const defer = utils.defer();\n this.opts.request(\n opts,\n requestCallback(defer, callback, this.opts.onlyData),\n );\n return defer.promise;\n },\n\n /**\n * Perform an authorised request to the homeserver.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param {Object=} queryParams A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param {Object} [data] The HTTP JSON body.\n *\n * @param {Object|Number=} opts additional options. If a number is specified,\n * this is treated as `opts.localTimeoutMs`.\n *\n * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n *\n * @param {sting=} opts.prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n *\n * @param {Object=} opts.headers map of additional request headers\n *\n * @return {Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n authedRequest: function(callback, method, path, queryParams, data, opts) {\n if (!queryParams) {\n queryParams = {};\n }\n if (this.useAuthorizationHeader) {\n if (isFinite(opts)) {\n // opts used to be localTimeoutMs\n opts = {\n localTimeoutMs: opts,\n };\n }\n if (!opts) {\n opts = {};\n }\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = \"Bearer \" + this.opts.accessToken;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else {\n if (!queryParams.access_token) {\n queryParams.access_token = this.opts.accessToken;\n }\n }\n\n const requestPromise = this.request(\n callback, method, path, queryParams, data, opts,\n );\n\n const self = this;\n requestPromise.catch(function(err) {\n if (err.errcode == 'M_UNKNOWN_TOKEN') {\n self.event_emitter.emit(\"Session.logged_out\", err);\n } else if (err.errcode == 'M_CONSENT_NOT_GIVEN') {\n self.event_emitter.emit(\n \"no_consent\",\n err.message,\n err.data.consent_uri,\n );\n }\n });\n\n // return the original promise, otherwise tests break due to it having to\n // go around the event loop one more time to process the result of the request\n return requestPromise;\n },\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param {Object=} queryParams A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param {Object} [data] The HTTP JSON body.\n *\n * @param {Object=} opts additional options\n *\n * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n *\n * @param {sting=} opts.prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n *\n * @param {Object=} opts.headers map of additional request headers\n *\n * @return {Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n request: function(callback, method, path, queryParams, data, opts) {\n opts = opts || {};\n const prefix = opts.prefix !== undefined ? opts.prefix : this.opts.prefix;\n const fullUri = this.opts.baseUrl + prefix + path;\n\n return this.requestOtherUrl(\n callback, method, fullUri, queryParams, data, opts,\n );\n },\n\n /**\n * Perform a request to an arbitrary URL.\n * @param {Function} callback Optional. The callback to invoke on\n * success/failure. See the promise return values for more information.\n * @param {string} method The HTTP method e.g. \"GET\".\n * @param {string} uri The HTTP URI\n *\n * @param {Object=} queryParams A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param {Object} [data] The HTTP JSON body.\n *\n * @param {Object=} opts additional options\n *\n * @param {Number=} opts.localTimeoutMs The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n *\n * @param {sting=} opts.prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n *\n * @param {Object=} opts.headers map of additional request headers\n *\n * @return {Promise} Resolves to <code>{data: {Object},\n * headers: {Object}, code: {Number}}</code>.\n * If <code>onlyData</code> is set, this will resolve to the <code>data</code>\n * object only.\n * @return {module:http-api.MatrixError} Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n requestOtherUrl: function(callback, method, uri, queryParams, data,\n opts) {\n if (opts === undefined || opts === null) {\n opts = {};\n } else if (isFinite(opts)) {\n // opts used to be localTimeoutMs\n opts = {\n localTimeoutMs: opts,\n };\n }\n\n return this._request(\n callback, method, uri, queryParams, data, opts,\n );\n },\n\n /**\n * Form and return a homeserver request URL based on the given path\n * params and prefix.\n * @param {string} path The HTTP path <b>after</b> the supplied prefix e.g.\n * \"/createRoom\".\n * @param {Object} queryParams A dict of query params (these will NOT be\n * urlencoded).\n * @param {string} prefix The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\".\n * @return {string} URL\n */\n getUrl: function(path, queryParams, prefix) {\n let queryString = \"\";\n if (queryParams) {\n queryString = \"?\" + utils.encodeParams(queryParams);\n }\n return this.opts.baseUrl + prefix + path + queryString;\n },\n\n /**\n * @private\n *\n * @param {function} callback\n * @param {string} method\n * @param {string} uri\n * @param {object} queryParams\n * @param {object|string} data\n * @param {object=} opts\n *\n * @param {boolean} [opts.json =true] Json-encode data before sending, and\n * decode response on receipt. (We will still json-decode error\n * responses, even if this is false.)\n *\n * @param {object=} opts.headers extra request headers\n *\n * @param {number=} opts.localTimeoutMs client-side timeout for the\n * request. Default timeout if falsy.\n *\n * @param {function=} opts.bodyParser function to parse the body of the\n * response before passing it to the promise and callback.\n *\n * @return {Promise} a promise which resolves to either the\n * response object (if this.opts.onlyData is truthy), or the parsed\n * body. Rejects\n */\n _request: function(callback, method, uri, queryParams, data, opts) {\n if (callback !== undefined && !utils.isFunction(callback)) {\n throw Error(\n \"Expected callback to be a function but got \" + typeof callback,\n );\n }\n opts = opts || {};\n\n const self = this;\n if (this.opts.extraParams) {\n queryParams = {\n ...queryParams,\n ...this.opts.extraParams,\n };\n }\n\n const headers = utils.extend({}, opts.headers || {});\n const json = opts.json === undefined ? true : opts.json;\n let bodyParser = opts.bodyParser;\n\n // we handle the json encoding/decoding here, because request and\n // browser-request make a mess of it. Specifically, they attempt to\n // json-decode plain-text error responses, which in turn means that the\n // actual error gets swallowed by a SyntaxError.\n\n if (json) {\n if (data) {\n data = JSON.stringify(data);\n headers['content-type'] = 'application/json';\n }\n\n if (!headers['accept']) {\n headers['accept'] = 'application/json';\n }\n\n if (bodyParser === undefined) {\n bodyParser = function(rawBody) {\n return JSON.parse(rawBody);\n };\n }\n }\n\n const defer = utils.defer();\n\n let timeoutId;\n let timedOut = false;\n let req;\n const localTimeoutMs = opts.localTimeoutMs || this.opts.localTimeoutMs;\n\n const resetTimeout = () => {\n if (localTimeoutMs) {\n if (timeoutId) {\n callbacks.clearTimeout(timeoutId);\n }\n timeoutId = callbacks.setTimeout(function() {\n timedOut = true;\n if (req && req.abort) {\n req.abort();\n }\n defer.reject(new MatrixError({\n error: \"Locally timed out waiting for a response\",\n errcode: \"ORG.MATRIX.JSSDK_TIMEOUT\",\n timeout: localTimeoutMs,\n }));\n }, localTimeoutMs);\n }\n };\n resetTimeout();\n\n const reqPromise = defer.promise;\n\n try {\n req = this.opts.request(\n {\n uri: uri,\n method: method,\n withCredentials: false,\n qs: queryParams,\n qsStringifyOptions: opts.qsStringifyOptions,\n useQuerystring: true,\n body: data,\n json: false,\n timeout: localTimeoutMs,\n headers: headers || {},\n _matrix_opts: this.opts,\n },\n function(err, response, body) {\n if (localTimeoutMs) {\n callbacks.clearTimeout(timeoutId);\n if (timedOut) {\n return; // already rejected promise\n }\n }\n\n const handlerFn = requestCallback(\n defer, callback, self.opts.onlyData,\n bodyParser,\n );\n handlerFn(err, response, body);\n },\n );\n if (req) {\n // This will only work in a browser, where opts.request is the\n // `browser-request` import. Currently `request` does not support progress\n // updates - see https://github.com/request/request/pull/2346.\n // `browser-request` returns an XHRHttpRequest which exposes `onprogress`\n if ('onprogress' in req) {\n req.onprogress = (e) => {\n // Prevent the timeout from rejecting the deferred promise if progress is\n // seen with the request\n resetTimeout();\n };\n }\n\n // FIXME: This is EVIL, but I can't think of a better way to expose\n // abort() operations on underlying HTTP requests :(\n if (req.abort) reqPromise.abort = req.abort.bind(req);\n }\n } catch (ex) {\n defer.reject(ex);\n if (callback) {\n callback(ex);\n }\n }\n return reqPromise;\n },\n};\n\n/*\n * Returns a callback that can be invoked by an HTTP request on completion,\n * that will either resolve or reject the given defer as well as invoke the\n * given userDefinedCallback (if any).\n *\n * HTTP errors are transformed into javascript errors and the deferred is rejected.\n *\n * If bodyParser is given, it is used to transform the body of the successful\n * responses before passing to the defer/callback.\n *\n * If onlyData is true, the defer/callback is invoked with the body of the\n * response, otherwise the result object (with `code` and `data` fields)\n *\n */\nconst requestCallback = function(\n defer, userDefinedCallback, onlyData,\n bodyParser,\n) {\n userDefinedCallback = userDefinedCallback || function() {};\n\n return function(err, response, body) {\n if (err) {\n // the unit tests use matrix-mock-request, which throw the string \"aborted\" when aborting a request.\n // See https://github.com/matrix-org/matrix-mock-request/blob/3276d0263a561b5b8326b47bae720578a2c7473a/src/index.js#L48\n const aborted = err.name === \"AbortError\" || err === \"aborted\";\n if (!aborted && !(err instanceof MatrixError)) {\n // browser-request just throws normal Error objects,\n // not `TypeError`s like fetch does. So just assume any\n // error is due to the connection.\n err = new ConnectionError(\"request failed\", err);\n }\n }\n if (!err) {\n try {\n const httpStatus = response.status || response.statusCode; // XMLHttpRequest vs http.IncomingMessage\n if (httpStatus >= 400) {\n err = parseErrorResponse(response, body);\n } else if (bodyParser) {\n body = bodyParser(body);\n }\n } catch (e) {\n err = new Error(`Error parsing server response: ${e}`);\n }\n }\n\n if (err) {\n defer.reject(err);\n userDefinedCallback(err);\n } else {\n const res = {\n code: response.status || response.statusCode, // XMLHttpRequest vs http.IncomingMessage\n\n // XXX: why do we bother with this? it doesn't work for\n // XMLHttpRequest, so clearly we don't use it.\n headers: response.headers,\n data: body,\n };\n defer.resolve(onlyData ? body : res);\n userDefinedCallback(null, onlyData ? body : res);\n }\n };\n};\n\n/**\n * Attempt to turn an HTTP error response into a Javascript Error.\n *\n * If it is a JSON response, we will parse it into a MatrixError. Otherwise\n * we return a generic Error.\n *\n * @param {XMLHttpRequest|http.IncomingMessage} response response object\n * @param {String} body raw body of the response\n * @returns {Error}\n */\nfunction parseErrorResponse(response, body) {\n const httpStatus = response.status || response.statusCode; // XMLHttpRequest vs http.IncomingMessage\n const contentType = getResponseContentType(response);\n\n let err;\n if (contentType) {\n if (contentType.type === 'application/json') {\n const jsonBody = typeof(body) === 'object' ? body : JSON.parse(body);\n err = new MatrixError(jsonBody);\n } else if (contentType.type === 'text/plain') {\n err = new Error(`Server returned ${httpStatus} error: ${body}`);\n }\n }\n\n if (!err) {\n err = new Error(`Server returned ${httpStatus} error`);\n }\n err.httpStatus = httpStatus;\n return err;\n}\n\n/**\n * extract the Content-Type header from the response object, and\n * parse it to a `{type, parameters}` object.\n *\n * returns null if no content-type header could be found.\n *\n * @param {XMLHttpRequest|http.IncomingMessage} response response object\n * @returns {{type: String, parameters: Object}?} parsed content-type header, or null if not found\n */\nfunction getResponseContentType(response) {\n let contentType;\n if (response.getResponseHeader) {\n // XMLHttpRequest provides getResponseHeader\n contentType = response.getResponseHeader(\"Content-Type\");\n } else if (response.headers) {\n // request provides http.IncomingMessage which has a message.headers map\n contentType = response.headers['content-type'] || null;\n }\n\n if (!contentType) {\n return null;\n }\n\n try {\n return parseContentType(contentType);\n } catch (e) {\n throw new Error(`Error parsing Content-Type '${contentType}': ${e}`);\n }\n}\n\n/**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @constructor\n * @param {Object} errorJson The Matrix error JSON returned from the homeserver.\n * @prop {string} errcode The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n * @prop {string} name Same as MatrixError.errcode but with a default unknown string.\n * @prop {string} message The Matrix 'error' value, e.g. \"Missing token.\"\n * @prop {Object} data The raw Matrix error JSON used to construct this object.\n * @prop {integer} httpStatus The numeric HTTP status code given\n */\nexport class MatrixError extends Error {\n constructor(errorJson) {\n errorJson = errorJson || {};\n super(`MatrixError: ${errorJson.errcode}`);\n this.errcode = errorJson.errcode;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.message = errorJson.error || \"Unknown message\";\n this.data = errorJson;\n }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n * @constructor\n */\nexport class ConnectionError extends Error {\n constructor(message, cause = undefined) {\n super(message + (cause ? `: ${cause.message}` : \"\"));\n this._cause = cause;\n }\n\n get name() {\n return \"ConnectionError\";\n }\n\n get cause() {\n return this._cause;\n }\n}\n\nexport class AbortError extends Error {\n constructor() {\n super(\"Operation aborted\");\n }\n\n get name() {\n return \"AbortError\";\n }\n}\n\n/**\n * Retries a network operation run in a callback.\n * @param {number} maxAttempts maximum attempts to try\n * @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.\n * @return {any} the result of the network operation\n * @throws {ConnectionError} If after maxAttempts the callback still throws ConnectionError\n */\nexport async function retryNetworkOperation(maxAttempts, callback) {\n let attempts = 0;\n let lastConnectionError = null;\n while (attempts < maxAttempts) {\n try {\n if (attempts > 0) {\n const timeout = 1000 * Math.pow(2, attempts);\n logger.log(`network operation failed ${attempts} times,` +\n ` retrying in ${timeout}ms...`);\n await new Promise(r => setTimeout(r, timeout));\n }\n return await callback();\n } catch (err) {\n if (err instanceof ConnectionError) {\n attempts += 1;\n lastConnectionError = err;\n } else {\n throw err;\n }\n }\n }\n throw lastConnectionError;\n}\n",
"/*\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Check if an IndexedDB database exists. The only way to do so is to try opening it, so\n * we do that and then delete it did not exist before.\n *\n * @param {Object} indexedDB The `indexedDB` interface\n * @param {string} dbName The database name to test for\n * @returns {boolean} Whether the database exists\n */\nexport function exists(indexedDB, dbName) {\n return new Promise((resolve, reject) => {\n let exists = true;\n const req = indexedDB.open(dbName);\n req.onupgradeneeded = () => {\n // Since we did not provide an explicit version when opening, this event\n // should only fire if the DB did not exist before at any version.\n exists = false;\n };\n req.onblocked = () => reject();\n req.onsuccess = () => {\n const db = req.result;\n db.close();\n if (!exists) {\n // The DB did not exist before, but has been created as part of this\n // existence check. Delete it now to restore previous state. Delete can\n // actually take a while to complete in some browsers, so don't wait for\n // it. This won't block future open calls that a store might issue next to\n // properly set up the DB.\n indexedDB.deleteDatabase(dbName);\n }\n resolve(exists);\n };\n req.onerror = ev => reject(ev.target.error);\n });\n}\n",
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module interactive-auth */\n\nimport url from \"url\";\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n * <p>Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n * <p>Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @constructor\n * @alias module:interactive-auth\n *\n * @param {object} opts options object\n *\n * @param {object} opts.matrixClient A matrix client to use for the auth process\n *\n * @param {object?} opts.authData error response from the last request. If\n * null, a request will be made with no auth before starting.\n *\n * @param {function(object?): Promise} opts.doRequest\n * called with the new auth dict to submit the request. Also passes a\n * second deprecated arg which is a flag set to true if this request\n * is a background request. The busyChanged callback should be used\n * instead of the backfround flag. Should return a promise which resolves\n * to the successful response or rejects with a MatrixError.\n *\n * @param {function(bool): Promise} opts.busyChanged\n * called whenever the interactive auth logic becomes busy submitting\n * information provided by the user or finsihes. After this has been\n * called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n *\n * @param {function(string, object?)} opts.stateUpdated\n * called when the status of the UI auth changes, ie. when the state of\n * an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object\n * which is either an error or an informational object specific to the\n * login type. If the 'errcode' key is defined, the object is an error,\n * and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n *\n * @param {object?} opts.inputs Inputs provided by the user and used by different\n * stages of the auto process. The inputs provided will affect what flow is chosen.\n *\n * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow\n * using email verification will be chosen.\n *\n * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives\n * the country that opts.phoneNumber should be resolved relative to.\n *\n * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow\n * using phone number validation will be chosen.\n *\n * @param {string?} opts.sessionId If resuming an existing interactive auth session,\n * the sessionId of that session.\n *\n * @param {string?} opts.clientSecret If resuming an existing interactive auth session,\n * the client secret for that session\n *\n * @param {string?} opts.emailSid If returning from having completed m.login.email.identity\n * auth, the sid for the email verification session.\n *\n * @param {function?} opts.requestEmailToken A function that takes the email address (string),\n * clientSecret (string), attempt number (int) and sessionId (string) and calls the\n * relevant requestToken function and returns the promise returned by that function.\n * If the resulting promise rejects, the rejection will propagate through to the\n * attemptAuth promise.\n *\n */\nexport function InteractiveAuth(opts) {\n this._matrixClient = opts.matrixClient;\n this._data = opts.authData || {};\n this._requestCallback = opts.doRequest;\n this._busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compat\n this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this._resolveFunc = null;\n this._rejectFunc = null;\n this._inputs = opts.inputs || {};\n this._requestEmailTokenCallback = opts.requestEmailToken;\n\n if (opts.sessionId) this._data.session = opts.sessionId;\n this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();\n this._emailSid = opts.emailSid;\n if (this._emailSid === undefined) this._emailSid = null;\n this._requestingEmailToken = false;\n\n this._chosenFlow = null;\n this._currentStage = null;\n\n // if we are currently trying to submit an auth dict (which includes polling)\n // the promise the will resolve/reject when it completes\n this._submitPromise = null;\n}\n\nInteractiveAuth.prototype = {\n /**\n * begin the authentication process.\n *\n * @return {Promise} which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n attemptAuth: function() {\n // This promise will be quite long-lived and will resolve when the\n // request is authenticated and completes successfully.\n return new Promise((resolve, reject) => {\n this._resolveFunc = resolve;\n this._rejectFunc = reject;\n\n const hasFlows = this._data && this._data.flows;\n\n // if we have no flows, try a request to acquire the flows\n if (!hasFlows) {\n if (this._busyChangedCallback) this._busyChangedCallback(true);\n // use the existing sessionid, if one is present.\n let auth = null;\n if (this._data.session) {\n auth = {\n session: this._data.session,\n };\n }\n this._doRequest(auth).finally(() => {\n if (this._busyChangedCallback) this._busyChangedCallback(false);\n });\n } else {\n this._startNextAuthStage();\n }\n });\n },\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n poll: async function() {\n if (!this._data.session) return;\n // likewise don't poll if there is no auth session in progress\n if (!this._resolveFunc) return;\n // if we currently have a request in flight, there's no point making\n // another just to check what the status is\n if (this._submitPromise) return;\n\n let authDict = {};\n if (this._currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this._emailSid) {\n const creds = {\n sid: this._emailSid,\n client_secret: this._clientSecret,\n };\n if (await this._matrixClient.doesServerRequireIdServerParam()) {\n const idServerParsedUrl = url.parse(\n this._matrixClient.getIdentityServerUrl(),\n );\n creds.id_server = idServerParsedUrl.host;\n }\n authDict = {\n type: EMAIL_STAGE_TYPE,\n // TODO: Remove `threepid_creds` once servers support proper UIA\n // See https://github.com/matrix-org/synapse/issues/5665\n // See https://github.com/matrix-org/matrix-doc/issues/2220\n threepid_creds: creds,\n threepidCreds: creds,\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n },\n\n /**\n * get the auth session ID\n *\n * @return {string} session id\n */\n getSessionId: function() {\n return this._data ? this._data.session : undefined;\n },\n\n /**\n * get the client secret used for validation sessions\n * with the ID server.\n *\n * @return {string} client secret\n */\n getClientSecret: function() {\n return this._clientSecret;\n },\n\n /**\n * get the server params for a given stage\n *\n * @param {string} loginType login type for the stage\n * @return {object?} any parameters from the server for this stage\n */\n getStageParams: function(loginType) {\n let params = {};\n if (this._data && this._data.params) {\n params = this._data.params;\n }\n return params[loginType];\n },\n\n getChosenFlow() {\n return this._chosenFlow;\n },\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param {object} authData new auth dict to send to the server. Should\n * include a `type` propterty denoting the login type, as well as any\n * other params for that stage.\n * @param {bool} background If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n submitAuthDict: async function(authData, background) {\n if (!this._resolveFunc) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n if (!background && this._busyChangedCallback) {\n this._busyChangedCallback(true);\n }\n\n // if we're currently trying a request, wait for it to finish\n // as otherwise we can get multiple 200 responses which can mean\n // things like multiple logins for register requests.\n // (but discard any expections as we only care when its done,\n // not whether it worked or not)\n while (this._submitPromise) {\n try {\n await this._submitPromise;\n } catch (e) {\n }\n }\n\n // use the sessionid from the last request, if one is present.\n let auth;\n if (this._data.session) {\n auth = {\n session: this._data.session,\n };\n utils.extend(auth, authData);\n } else {\n auth = authData;\n }\n\n try {\n // NB. the 'background' flag is deprecated by the busyChanged\n // callback and is here for backwards compat\n this._submitPromise = this._doRequest(auth, background);\n await this._submitPromise;\n } finally {\n this._submitPromise = null;\n if (!background && this._busyChangedCallback) {\n this._busyChangedCallback(false);\n }\n }\n },\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns {string} The sid of the email auth session\n */\n getEmailSid: function() {\n return this._emailSid;\n },\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param {string} sid The sid for the email validation session\n */\n setEmailSid: function(sid) {\n this._emailSid = sid;\n },\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @private\n * @param {object?} auth new auth dict, including session id\n * @param {bool?} background If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n _doRequest: async function(auth, background) {\n try {\n const result = await this._requestCallback(auth, background);\n this._resolveFunc(result);\n this._resolveFunc = null;\n this._rejectFunc = null;\n } catch (error) {\n // sometimes UI auth errors don't come with flows\n const errorFlows = error.data ? error.data.flows : null;\n const haveFlows = this._data.flows || Boolean(errorFlows);\n if (error.httpStatus !== 401 || !error.data || !haveFlows) {\n // doesn't look like an interactive-auth failure.\n if (!background) {\n this._rejectFunc(error);\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n logger.log(\n \"Background poll request failed doing UI auth: ignoring\",\n error,\n );\n }\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (!error.data.flows && !error.data.completed && !error.data.session) {\n error.data.flows = this._data.flows;\n error.data.completed = this._data.completed;\n error.data.session = this._data.session;\n }\n this._data = error.data;\n try {\n this._startNextAuthStage();\n } catch (e) {\n this._rejectFunc(e);\n this._resolveFunc = null;\n this._rejectFunc = null;\n }\n\n if (\n !this._emailSid &&\n !this._requestingEmailToken &&\n this._chosenFlow.stages.includes('m.login.email.identity')\n ) {\n // If we've picked a flow with email auth, we send the email\n // now because we want the request to fail as soon as possible\n // if the email address is not valid (ie. already taken or not\n // registered, depending on what the operation is).\n this._requestingEmailToken = true;\n try {\n const requestTokenResult = await this._requestEmailTokenCallback(\n this._inputs.emailAddress,\n this._clientSecret,\n 1, // TODO: Multiple send attempts?\n this._data.session,\n );\n this._emailSid = requestTokenResult.sid;\n // NB. promise is not resolved here - at some point, doRequest\n // will be called again and if the user has jumped through all\n // the hoops correctly, auth will be complete and the request\n // will succeed.\n // Also, we should expose the fact that this request has compledted\n // so clients can know that the email has actually been sent.\n } catch (e) {\n // we failed to request an email token, so fail the request.\n // This could be due to the email already beeing registered\n // (or not being registered, depending on what we're trying\n // to do) or it could be a network failure. Either way, pass\n // the failure up as the user can't complete auth if we can't\n // send the email, for whatever reason.\n this._rejectFunc(e);\n this._resolveFunc = null;\n this._rejectFunc = null;\n } finally {\n this._requestingEmailToken = false;\n }\n }\n }\n },\n\n /**\n * Pick the next stage and call the callback\n *\n * @private\n * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n _startNextAuthStage: function() {\n const nextStage = this._chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this._currentStage = nextStage;\n\n if (nextStage === 'm.login.dummy') {\n this.submitAuthDict({\n type: 'm.login.dummy',\n });\n return;\n }\n\n if (this._data && this._data.errcode || this._data.error) {\n this._stateUpdatedCallback(nextStage, {\n errcode: this._data.errcode || \"\",\n error: this._data.error || \"\",\n });\n return;\n }\n\n const stageStatus = {};\n if (nextStage == EMAIL_STAGE_TYPE) {\n stageStatus.emailSid = this._emailSid;\n }\n this._stateUpdatedCallback(nextStage, stageStatus);\n },\n\n /**\n * Pick the next auth stage\n *\n * @private\n * @return {string?} login type\n * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n _chooseStage: function() {\n if (this._chosenFlow === null) {\n this._chosenFlow = this._chooseFlow();\n }\n logger.log(\"Active flow => %s\", JSON.stringify(this._chosenFlow));\n const nextStage = this._firstUncompletedStage(this._chosenFlow);\n logger.log(\"Next stage: %s\", nextStage);\n return nextStage;\n },\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likley to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @private\n * @return {object} flow\n * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n _chooseFlow: function() {\n const flows = this._data.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);\n const haveMsisdn = (\n Boolean(this._inputs.phoneCountry) &&\n Boolean(this._inputs.phoneNumber)\n );\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n const err = new Error(\"No appropriate authentication flow found\");\n err.name = 'NoAuthFlowFoundError';\n err.required_stages = [];\n if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);\n err.available_flows = flows;\n throw err;\n },\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @private\n * @param {object} flow\n * @return {string} login type\n */\n _firstUncompletedStage: function(flow) {\n const completed = (this._data || {}).completed || [];\n for (let i = 0; i < flow.stages.length; ++i) {\n const stageType = flow.stages[i];\n if (completed.indexOf(stageType) === -1) {\n return stageType;\n }\n }\n },\n};\n\n",
"/*\nCopyright 2018 André Jaenisch\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module logger\n */\n\nimport log, { Logger } from \"loglevel\";\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nlog.methodFactory = function(methodName, logLevel, loggerName) {\n return function(...args) {\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n const supportedByConsole = methodName === \"error\" ||\n methodName === \"warn\" ||\n methodName === \"trace\" ||\n methodName === \"info\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n */\nexport const logger: PrefixedLogger = log.getLogger(DEFAULT_NAMESPACE);\nlogger.setLevel(log.levels.DEBUG);\n\ninterface PrefixedLogger extends Logger {\n withPrefix?: (prefix: string) => PrefixedLogger;\n prefix?: string;\n}\n\nfunction extendLogger(logger: PrefixedLogger) {\n logger.withPrefix = function(prefix: string): PrefixedLogger {\n const existingPrefix = this.prefix || \"\";\n return getPrefixedLogger(existingPrefix + prefix);\n };\n}\n\nextendLogger(logger);\n\nfunction getPrefixedLogger(prefix): PrefixedLogger {\n const prefixLogger: PrefixedLogger = log.getLogger(`${DEFAULT_NAMESPACE}-${prefix}`);\n if (prefixLogger.prefix !== prefix) {\n // Only do this setup work the first time through, as loggers are saved by name.\n extendLogger(prefixLogger);\n prefixLogger.prefix = prefix;\n prefixLogger.setLevel(log.levels.DEBUG);\n }\n return prefixLogger;\n}\n",
"/*\nCopyright 2015-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MemoryCryptoStore } from \"./crypto/store/memory-crypto-store\";\nimport { MemoryStore } from \"./store/memory\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { MatrixClient } from \"./client\";\nimport { ICreateClientOpts } from \"./client\";\nimport { DeviceTrustLevel } from \"./crypto/CrossSigning\";\nimport { ISecretStorageKeyInfo } from \"./crypto/api\";\n\nexport * from \"./client\";\nexport * from \"./http-api\";\nexport * from \"./autodiscovery\";\nexport * from \"./sync-accumulator\";\nexport * from \"./errors\";\nexport * from \"./models/event\";\nexport * from \"./models/room\";\nexport * from \"./models/group\";\nexport * from \"./models/event-timeline\";\nexport * from \"./models/event-timeline-set\";\nexport * from \"./models/room-member\";\nexport * from \"./models/room-state\";\nexport * from \"./models/user\";\nexport * from \"./scheduler\";\nexport * from \"./filter\";\nexport * from \"./timeline-window\";\nexport * from \"./interactive-auth\";\nexport * from \"./service-types\";\nexport * from \"./store/memory\";\nexport * from \"./store/indexeddb\";\nexport * from \"./store/session/webstorage\";\nexport * from \"./crypto/store/memory-crypto-store\";\nexport * from \"./crypto/store/indexeddb-crypto-store\";\nexport * from \"./content-repo\";\nexport * as ContentHelpers from \"./content-helpers\";\nexport {\n createNewMatrixCall,\n setAudioInput as setMatrixCallAudioInput,\n setVideoInput as setMatrixCallVideoInput,\n} from \"./webrtc/call\";\n\n// expose the underlying request object so different environments can use\n// different request libs (e.g. request or browser-request)\nlet requestInstance;\n\n/**\n * The function used to perform HTTP requests. Only use this if you want to\n * use a different HTTP library, e.g. Angular's <code>$http</code>. This should\n * be set prior to calling {@link createClient}.\n * @param {requestFunction} r The request function to use.\n */\nexport function request(r) {\n requestInstance = r;\n}\n\n/**\n * Return the currently-set request function.\n * @return {requestFunction} The current request function.\n */\nexport function getRequest() {\n return requestInstance;\n}\n\n/**\n * Apply wrapping code around the request function. The wrapper function is\n * installed as the new request handler, and when invoked it is passed the\n * previous value, along with the options and callback arguments.\n * @param {requestWrapperFunction} wrapper The wrapping function.\n */\nexport function wrapRequest(wrapper) {\n const origRequest = requestInstance;\n requestInstance = function(options, callback) {\n return wrapper(origRequest, options, callback);\n };\n}\n\nlet cryptoStoreFactory = () => new MemoryCryptoStore;\n\n/**\n * Configure a different factory to be used for creating crypto stores\n *\n * @param {Function} fac a function which will return a new\n * {@link module:crypto.store.base~CryptoStore}.\n */\nexport function setCryptoStoreFactory(fac) {\n cryptoStoreFactory = fac;\n}\n\nexport interface ICryptoCallbacks {\n getCrossSigningKey?: (keyType: string, pubKey: string) => Promise<Uint8Array>;\n saveCrossSigningKeys?: (keys: Record<string, Uint8Array>) => void;\n shouldUpgradeDeviceVerifications?: (\n users: Record<string, any>\n ) => Promise<string[]>;\n getSecretStorageKey?: (\n keys: {keys: Record<string, ISecretStorageKeyInfo>}, name: string\n ) => Promise<[string, Uint8Array] | null>;\n cacheSecretStorageKey?: (\n keyId: string, keyInfo: ISecretStorageKeyInfo, key: Uint8Array\n ) => void;\n onSecretRequested?: (\n userId: string, deviceId: string,\n requestId: string, secretName: string, deviceTrust: DeviceTrustLevel\n ) => Promise<string>;\n getDehydrationKey?: (\n keyInfo: ISecretStorageKeyInfo,\n checkFunc: (Uint8Array) => void,\n ) => Promise<Uint8Array>;\n getBackupKey?: () => Promise<Uint8Array>;\n}\n\n/**\n * Construct a Matrix Client. Similar to {@link module:client.MatrixClient}\n * except that the 'request', 'store' and 'scheduler' dependencies are satisfied.\n * @param {(Object|string)} opts The configuration options for this client. If\n * this is a string, it is assumed to be the base URL. These configuration\n * options will be passed directly to {@link module:client.MatrixClient}.\n * @param {Object} opts.store If not set, defaults to\n * {@link module:store/memory.MemoryStore}.\n * @param {Object} opts.scheduler If not set, defaults to\n * {@link module:scheduler~MatrixScheduler}.\n * @param {requestFunction} opts.request If not set, defaults to the function\n * supplied to {@link request} which defaults to the request module from NPM.\n *\n * @param {module:crypto.store.base~CryptoStore=} opts.cryptoStore\n * crypto store implementation. Calls the factory supplied to\n * {@link setCryptoStoreFactory} if unspecified; or if no factory has been\n * specified, uses a default implementation (indexeddb in the browser,\n * in-memory otherwise).\n *\n * @return {MatrixClient} A new matrix client.\n * @see {@link module:client.MatrixClient} for the full list of options for\n * <code>opts</code>.\n */\nexport function createClient(opts: ICreateClientOpts | string) {\n if (typeof opts === \"string\") {\n opts = {\n \"baseUrl\": opts as string,\n };\n }\n opts.request = opts.request || requestInstance;\n opts.store = opts.store || new MemoryStore({\n localStorage: global.localStorage,\n });\n opts.scheduler = opts.scheduler || new MatrixScheduler();\n opts.cryptoStore = opts.cryptoStore || cryptoStoreFactory();\n return new MatrixClient(opts);\n}\n\n/**\n * The request function interface for performing HTTP requests. This matches the\n * API for the {@link https://github.com/request/request#requestoptions-callback|\n * request NPM module}. The SDK will attempt to call this function in order to\n * perform an HTTP request.\n * @callback requestFunction\n * @param {Object} opts The options for this HTTP request.\n * @param {string} opts.uri The complete URI.\n * @param {string} opts.method The HTTP method.\n * @param {Object} opts.qs The query parameters to append to the URI.\n * @param {Object} opts.body The JSON-serializable object.\n * @param {boolean} opts.json True if this is a JSON request.\n * @param {Object} opts._matrix_opts The underlying options set for\n * {@link MatrixHttpApi}.\n * @param {requestCallback} callback The request callback.\n */\n\n/**\n * A wrapper for the request function interface.\n * @callback requestWrapperFunction\n * @param {requestFunction} origRequest The underlying request function being\n * wrapped\n * @param {Object} opts The options for this HTTP request, given in the same\n * form as {@link requestFunction}.\n * @param {requestCallback} callback The request callback.\n */\n\n/**\n * The request callback interface for performing HTTP requests. This matches the\n * API for the {@link https://github.com/request/request#requestoptions-callback|\n * request NPM module}. The SDK will implement a callback which meets this\n * interface in order to handle the HTTP response.\n * @callback requestCallback\n * @param {Error} err The error if one occurred, else falsey.\n * @param {Object} response The HTTP response which consists of\n * <code>{statusCode: {Number}, headers: {Object}}</code>\n * @param {Object} body The parsed HTTP response body.\n */\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { IEncryptedFile, UNSTABLE_MSC3089_BRANCH } from \"../@types/event\";\nimport { MatrixEvent } from \"./event\";\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference\n * to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089Branch {\n public constructor(private client: MatrixClient, public readonly indexEvent: MatrixEvent) {\n // Nothing to do\n }\n\n /**\n * The file ID.\n */\n public get id(): string {\n return this.indexEvent.getStateKey();\n }\n\n /**\n * Whether this branch is active/valid.\n */\n public get isActive(): boolean {\n return this.indexEvent.getContent()[\"active\"] === true;\n }\n\n private get roomId(): string {\n return this.indexEvent.getRoomId();\n }\n\n /**\n * Deletes the file from the tree.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async delete(): Promise<void> {\n await this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {}, this.id);\n await this.client.redactEvent(this.roomId, this.id);\n\n // TODO: Delete edit history as well\n }\n\n /**\n * Gets the name for this file.\n * @returns {string} The name, or \"Unnamed File\" if unknown.\n */\n public getName(): string {\n return this.indexEvent.getContent()['name'] || \"Unnamed File\";\n }\n\n /**\n * Sets the name for this file.\n * @param {string} name The new name for this file.\n * @returns {Promise<void>} Resolves when complete.\n */\n public setName(name: string): Promise<void> {\n return this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {\n ...this.indexEvent.getContent(),\n name: name,\n }, this.id);\n }\n\n /**\n * Gets information about the file needed to download it.\n * @returns {Promise<{info: IEncryptedFile, httpUrl: string}>} Information about the file.\n */\n public async getFileInfo(): Promise<{ info: IEncryptedFile, httpUrl: string }> {\n const room = this.client.getRoom(this.roomId);\n if (!room) throw new Error(\"Unknown room\");\n\n const timeline = await this.client.getEventTimeline(room.getUnfilteredTimelineSet(), this.id);\n if (!timeline) throw new Error(\"Failed to get timeline for room event\");\n\n const event = timeline.getEvents().find(e => e.getId() === this.id);\n if (!event) throw new Error(\"Failed to find event\");\n\n // Sometimes the event context doesn't decrypt for us, so do that.\n await this.client.decryptEventIfNeeded(event, { emit: false, isRetry: false });\n\n const file = event.getContent()['file'];\n const httpUrl = this.client.mxcUrlToHttp(file['url']);\n\n return { info: file, httpUrl: httpUrl };\n }\n}\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { EventType, IEncryptedFile, MsgType, UNSTABLE_MSC3089_BRANCH, UNSTABLE_MSC3089_LEAF } from \"../@types/event\";\nimport { Room } from \"./room\";\nimport { logger } from \"../logger\";\nimport { MatrixEvent } from \"./event\";\nimport {\n averageBetweenStrings,\n DEFAULT_ALPHABET,\n lexicographicCompare,\n nextString,\n prevString,\n simpleRetryOperation,\n} from \"../utils\";\nimport { MSC3089Branch } from \"./MSC3089Branch\";\nimport promiseRetry from \"p-retry\";\nimport { isRoomSharedHistory } from \"../crypto/algorithms/megolm\";\n\n/**\n * The recommended defaults for a tree space's power levels. Note that this\n * is UNSTABLE and subject to breaking changes without notice.\n */\nexport const DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {\n // Owner\n invite: 100,\n kick: 100,\n ban: 100,\n\n // Editor\n redact: 50,\n state_default: 50,\n events_default: 50,\n\n // Viewer\n users_default: 0,\n\n // Mixed\n events: {\n [EventType.RoomPowerLevels]: 100,\n [EventType.RoomHistoryVisibility]: 100,\n [EventType.RoomTombstone]: 100,\n [EventType.RoomEncryption]: 100,\n [EventType.RoomName]: 50,\n [EventType.RoomMessage]: 50,\n [EventType.RoomMessageEncrypted]: 50,\n [EventType.Sticker]: 50,\n },\n\n users: {}, // defined by calling code\n};\n\n/**\n * Ease-of-use representation for power levels represented as simple roles.\n * Note that this is UNSTABLE and subject to breaking changes without notice.\n */\nexport enum TreePermissions {\n Viewer = \"viewer\", // Default\n Editor = \"editor\", // \"Moderator\" or ~PL50\n Owner = \"owner\", // \"Admin\" or PL100\n}\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)\n * file tree Space. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089TreeSpace {\n public readonly room: Room;\n\n public constructor(private client: MatrixClient, public readonly roomId: string) {\n this.room = this.client.getRoom(this.roomId);\n\n if (!this.room) throw new Error(\"Unknown room\");\n }\n\n /**\n * Syntactic sugar for room ID of the Space.\n */\n public get id(): string {\n return this.roomId;\n }\n\n /**\n * Whether or not this is a top level space.\n */\n public get isTopLevel(): boolean {\n // XXX: This is absolutely not how you find out if the space is top level\n // but is safe for a managed usecase like we offer in the SDK.\n const parentEvents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n if (!parentEvents?.length) return true;\n return parentEvents.every(e => !e.getContent()?.['via']);\n }\n\n /**\n * Sets the name of the tree space.\n * @param {string} name The new name for the space.\n * @returns {Promise<void>} Resolves when complete.\n */\n public setName(name: string): Promise<void> {\n return this.client.sendStateEvent(this.roomId, EventType.RoomName, { name }, \"\");\n }\n\n /**\n * Invites a user to the tree space. They will be given the default Viewer\n * permission level unless specified elsewhere.\n * @param {string} userId The user ID to invite.\n * @param {boolean} andSubspaces True (default) to invite the user to all\n * directories/subspaces too, recursively.\n * @param {boolean} shareHistoryKeys True (default) to share encryption keys\n * with the invited user. This will allow them to decrypt the events (files)\n * in the tree. Keys will not be shared if the room is lacking appropriate\n * history visibility (by default, history visibility is \"shared\" in trees,\n * which is an appropriate visibility for these purposes).\n * @returns {Promise<void>} Resolves when complete.\n */\n public async invite(userId: string, andSubspaces = true, shareHistoryKeys = true): Promise<void> {\n const promises: Promise<void>[] = [this.retryInvite(userId)];\n if (andSubspaces) {\n promises.push(...this.getDirectories().map(d => d.invite(userId, andSubspaces, shareHistoryKeys)));\n }\n return Promise.all(promises).then(() => {\n // Note: key sharing is default on because for file trees it is relatively important that the invite\n // target can actually decrypt the files. The implied use case is that by inviting a user to the tree\n // it means the sender would like the receiver to view/download the files contained within, much like\n // sharing a folder in other circles.\n if (shareHistoryKeys && isRoomSharedHistory(this.room)) {\n // noinspection JSIgnoredPromiseFromCall - we aren't concerned as much if this fails.\n this.client.sendSharedHistoryKeys(this.roomId, [userId]);\n }\n });\n }\n\n private retryInvite(userId: string): Promise<void> {\n return simpleRetryOperation(async () => {\n await this.client.invite(this.roomId, userId).catch(e => {\n // We don't want to retry permission errors forever...\n if (e?.errcode === \"M_FORBIDDEN\") {\n throw new promiseRetry.AbortError(e);\n }\n throw e;\n });\n });\n }\n\n /**\n * Sets the permissions of a user to the given role. Note that if setting a user\n * to Owner then they will NOT be able to be demoted. If the user does not have\n * permission to change the power level of the target, an error will be thrown.\n * @param {string} userId The user ID to change the role of.\n * @param {TreePermissions} role The role to assign.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async setPermissions(userId: string, role: TreePermissions): Promise<void> {\n const currentPls = this.room.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n if (Array.isArray(currentPls)) throw new Error(\"Unexpected return type for power levels\");\n\n const pls = currentPls.getContent() || {};\n const viewLevel = pls['users_default'] || 0;\n const editLevel = pls['events_default'] || 50;\n const adminLevel = pls['events']?.[EventType.RoomPowerLevels] || 100;\n\n const users = pls['users'] || {};\n switch (role) {\n case TreePermissions.Viewer:\n users[userId] = viewLevel;\n break;\n case TreePermissions.Editor:\n users[userId] = editLevel;\n break;\n case TreePermissions.Owner:\n users[userId] = adminLevel;\n break;\n default:\n throw new Error(\"Invalid role: \" + role);\n }\n pls['users'] = users;\n\n return this.client.sendStateEvent(this.roomId, EventType.RoomPowerLevels, pls, \"\");\n }\n\n /**\n * Creates a directory under this tree space, represented as another tree space.\n * @param {string} name The name for the directory.\n * @returns {Promise<MSC3089TreeSpace>} Resolves to the created directory.\n */\n public async createDirectory(name: string): Promise<MSC3089TreeSpace> {\n const directory = await this.client.unstableCreateFileTree(name);\n\n await this.client.sendStateEvent(this.roomId, EventType.SpaceChild, {\n via: [this.client.getDomain()],\n }, directory.roomId);\n\n await this.client.sendStateEvent(directory.roomId, EventType.SpaceParent, {\n via: [this.client.getDomain()],\n }, this.roomId);\n\n return directory;\n }\n\n /**\n * Gets a list of all known immediate subdirectories to this tree space.\n * @returns {MSC3089TreeSpace[]} The tree spaces (directories). May be empty, but not null.\n */\n public getDirectories(): MSC3089TreeSpace[] {\n const trees: MSC3089TreeSpace[] = [];\n const children = this.room.currentState.getStateEvents(EventType.SpaceChild);\n for (const child of children) {\n try {\n const tree = this.client.unstableGetFileTreeSpace(child.getStateKey());\n if (tree) trees.push(tree);\n } catch (e) {\n logger.warn(\"Unable to create tree space instance for listing. Are we joined?\", e);\n }\n }\n return trees;\n }\n\n /**\n * Gets a subdirectory of a given ID under this tree space. Note that this will not recurse\n * into children and instead only look one level deep.\n * @param {string} roomId The room ID (directory ID) to find.\n * @returns {MSC3089TreeSpace} The directory, or falsy if not found.\n */\n public getDirectory(roomId: string): MSC3089TreeSpace {\n return this.getDirectories().find(r => r.roomId === roomId);\n }\n\n /**\n * Deletes the tree, kicking all members and deleting **all subdirectories**.\n * @returns {Promise<void>} Resolves when complete.\n */\n public async delete(): Promise<void> {\n const subdirectories = this.getDirectories();\n for (const dir of subdirectories) {\n await dir.delete();\n }\n\n const kickMemberships = [\"invite\", \"knock\", \"join\"];\n const members = this.room.currentState.getStateEvents(EventType.RoomMember);\n for (const member of members) {\n const isNotUs = member.getStateKey() !== this.client.getUserId();\n if (isNotUs && kickMemberships.includes(member.getContent()['membership'])) {\n await this.client.kick(this.roomId, member.getStateKey(), \"Room deleted\");\n }\n }\n\n await this.client.leave(this.roomId);\n }\n\n private getOrderedChildren(children: MatrixEvent[]): { roomId: string, order: string }[] {\n const ordered: { roomId: string, order: string }[] = children\n .map(c => ({ roomId: c.getStateKey(), order: c.getContent()['order'] }));\n ordered.sort((a, b) => {\n if (a.order && !b.order) {\n return -1;\n } else if (!a.order && b.order) {\n return 1;\n } else if (!a.order && !b.order) {\n const roomA = this.client.getRoom(a.roomId);\n const roomB = this.client.getRoom(b.roomId);\n if (!roomA || !roomB) { // just don't bother trying to do more partial sorting\n return lexicographicCompare(a.roomId, b.roomId);\n }\n\n const createTsA = roomA.currentState.getStateEvents(EventType.RoomCreate, \"\")?.getTs() ?? 0;\n const createTsB = roomB.currentState.getStateEvents(EventType.RoomCreate, \"\")?.getTs() ?? 0;\n if (createTsA === createTsB) {\n return lexicographicCompare(a.roomId, b.roomId);\n }\n return createTsA - createTsB;\n } else { // both not-null orders\n return lexicographicCompare(a.order, b.order);\n }\n });\n return ordered;\n }\n\n private getParentRoom(): Room {\n const parents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n const parent = parents[0]; // XXX: Wild assumption\n if (!parent) throw new Error(\"Expected to have a parent in a non-top level space\");\n\n // XXX: We are assuming the parent is a valid tree space.\n // We probably don't need to validate the parent room state for this usecase though.\n const parentRoom = this.client.getRoom(parent.getStateKey());\n if (!parentRoom) throw new Error(\"Unable to locate room for parent\");\n\n return parentRoom;\n }\n\n /**\n * Gets the current order index for this directory. Note that if this is the top level space\n * then -1 will be returned.\n * @returns {number} The order index of this space.\n */\n public getOrder(): number {\n if (this.isTopLevel) return -1;\n\n const parentRoom = this.getParentRoom();\n const children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);\n const ordered = this.getOrderedChildren(children);\n\n return ordered.findIndex(c => c.roomId === this.roomId);\n }\n\n /**\n * Sets the order index for this directory within its parent. Note that if this is a top level\n * space then an error will be thrown. -1 can be used to move the child to the start, and numbers\n * larger than the number of children can be used to move the child to the end.\n * @param {number} index The new order index for this space.\n * @returns {Promise<void>} Resolves when complete.\n * @throws Throws if this is a top level space.\n */\n public async setOrder(index: number): Promise<void> {\n if (this.isTopLevel) throw new Error(\"Cannot set order of top level spaces currently\");\n\n const parentRoom = this.getParentRoom();\n const children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);\n const ordered = this.getOrderedChildren(children);\n index = Math.max(Math.min(index, ordered.length - 1), 0);\n\n const currentIndex = this.getOrder();\n const movingUp = currentIndex < index;\n if (movingUp && index === (ordered.length - 1)) {\n index--;\n } else if (!movingUp && index === 0) {\n index++;\n }\n\n const prev = ordered[movingUp ? index : (index - 1)];\n const next = ordered[movingUp ? (index + 1) : index];\n\n let newOrder = DEFAULT_ALPHABET[0];\n let ensureBeforeIsSane = false;\n if (!prev) {\n // Move to front\n if (next?.order) {\n newOrder = prevString(next.order);\n }\n } else if (index === (ordered.length - 1)) {\n // Move to back\n if (next?.order) {\n newOrder = nextString(next.order);\n }\n } else {\n // Move somewhere in the middle\n const startOrder = prev?.order;\n const endOrder = next?.order;\n if (startOrder && endOrder) {\n if (startOrder === endOrder) {\n // Error case: just move +1 to break out of awful math\n newOrder = nextString(startOrder);\n } else {\n newOrder = averageBetweenStrings(startOrder, endOrder);\n }\n } else {\n if (startOrder) {\n // We're at the end (endOrder is null, so no explicit order)\n newOrder = nextString(startOrder);\n } else if (endOrder) {\n // We're at the start (startOrder is null, so nothing before us)\n newOrder = prevString(endOrder);\n } else {\n // Both points are unknown. We're likely in a range where all the children\n // don't have particular order values, so we may need to update them too.\n // The other possibility is there's only us as a child, but we should have\n // shown up in the other states.\n ensureBeforeIsSane = true;\n }\n }\n }\n\n if (ensureBeforeIsSane) {\n // We were asked by the order algorithm to prepare the moving space for a landing\n // in the undefined order part of the order array, which means we need to update the\n // spaces that come before it with a stable order value.\n let lastOrder: string;\n for (let i = 0; i <= index; i++) {\n const target = ordered[i];\n if (i === 0) {\n lastOrder = target.order;\n }\n if (!target.order) {\n // XXX: We should be creating gaps to avoid conflicts\n lastOrder = lastOrder ? nextString(lastOrder) : DEFAULT_ALPHABET[0];\n const currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, target.roomId);\n const content = currentChild?.getContent() ?? { via: [this.client.getDomain()] };\n await this.client.sendStateEvent(parentRoom.roomId, EventType.SpaceChild, {\n ...content,\n order: lastOrder,\n }, target.roomId);\n } else {\n lastOrder = target.order;\n }\n }\n newOrder = nextString(lastOrder);\n }\n\n // TODO: Deal with order conflicts by reordering\n\n // Now we can finally update our own order state\n const currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, this.roomId);\n const content = currentChild?.getContent() ?? { via: [this.client.getDomain()] };\n await this.client.sendStateEvent(parentRoom.roomId, EventType.SpaceChild, {\n ...content,\n\n // TODO: Safely constrain to 50 character limit required by spaces.\n order: newOrder,\n }, this.roomId);\n }\n\n /**\n * Creates (uploads) a new file to this tree. The file must have already been encrypted for the room.\n * @param {string} name The name of the file.\n * @param {ArrayBuffer} encryptedContents The encrypted contents.\n * @param {Partial<IEncryptedFile>} info The encrypted file information.\n * @returns {Promise<void>} Resolves when uploaded.\n */\n public async createFile(\n name: string,\n encryptedContents: ArrayBuffer, info: Partial<IEncryptedFile>,\n ): Promise<void> {\n const mxc = await this.client.uploadContent(new Blob([encryptedContents]), {\n includeFilename: false,\n onlyContentUri: true,\n });\n info.url = mxc;\n\n const res = await this.client.sendMessage(this.roomId, {\n msgtype: MsgType.File,\n body: name,\n url: mxc,\n file: info,\n [UNSTABLE_MSC3089_LEAF.name]: {},\n });\n\n await this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {\n active: true,\n name: name,\n }, res['event_id']);\n }\n\n /**\n * Retrieves a file from the tree.\n * @param {string} fileEventId The event ID of the file.\n * @returns {MSC3089Branch} The file, or falsy if not found.\n */\n public getFile(fileEventId: string): MSC3089Branch {\n const branch = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name, fileEventId);\n return branch ? new MSC3089Branch(this.client, branch) : null;\n }\n\n /**\n * Gets an array of all known files for the tree.\n * @returns {MSC3089Branch[]} The known files. May be empty, but not null.\n */\n public listFiles(): MSC3089Branch[] {\n const branches = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name) ?? [];\n return branches.map(e => new MSC3089Branch(this.client, e)).filter(b => b.isActive);\n }\n}\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"./event\";\nimport { Direction } from \"./event-timeline\";\n\n/**\n * @module models/event-context\n */\nexport class EventContext {\n private timeline: MatrixEvent[];\n private ourEventIndex = 0;\n private paginateTokens: Record<Direction, string | null> = {\n [Direction.Backward]: null,\n [Direction.Forward]: null,\n };\n\n /**\n * Construct a new EventContext\n *\n * An eventcontext is used for circumstances such as search results, when we\n * have a particular event of interest, and a bunch of events before and after\n * it.\n *\n * It also stores pagination tokens for going backwards and forwards in the\n * timeline.\n *\n * @param {MatrixEvent} ourEvent the event at the centre of this context\n *\n * @constructor\n */\n constructor(ourEvent: MatrixEvent) {\n this.timeline = [ourEvent];\n }\n\n /**\n * Get the main event of interest\n *\n * This is a convenience function for getTimeline()[getOurEventIndex()].\n *\n * @return {MatrixEvent} The event at the centre of this context.\n */\n public getEvent(): MatrixEvent {\n return this.timeline[this.ourEventIndex];\n }\n\n /**\n * Get the list of events in this context\n *\n * @return {Array} An array of MatrixEvents\n */\n public getTimeline(): MatrixEvent[] {\n return this.timeline;\n }\n\n /**\n * Get the index in the timeline of our event\n *\n * @return {Number}\n */\n public getOurEventIndex(): number {\n return this.ourEventIndex;\n }\n\n /**\n * Get a pagination token.\n *\n * @param {boolean} backwards true to get the pagination token for going\n * backwards in time\n * @return {string}\n */\n public getPaginateToken(backwards = false): string {\n return this.paginateTokens[backwards ? Direction.Backward : Direction.Forward];\n }\n\n /**\n * Set a pagination token.\n *\n * Generally this will be used only by the matrix js sdk.\n *\n * @param {string} token pagination token\n * @param {boolean} backwards true to set the pagination token for going\n * backwards in time\n */\n public setPaginateToken(token: string, backwards = false): void {\n this.paginateTokens[backwards ? Direction.Backward : Direction.Forward] = token;\n }\n\n /**\n * Add more events to the timeline\n *\n * @param {Array} events new events, in timeline order\n * @param {boolean} atStart true to insert new events at the start\n */\n public addEvents(events: MatrixEvent[], atStart = false): void {\n // TODO: should we share logic with Room.addEventsToTimeline?\n // Should Room even use EventContext?\n\n if (atStart) {\n this.timeline = events.concat(this.timeline);\n this.ourEventIndex += events.length;\n } else {\n this.timeline = this.timeline.concat(events);\n }\n }\n}\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/event-timeline-set\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { EventTimeline } from \"./event-timeline\";\nimport { EventStatus, MatrixEvent } from \"./event\";\nimport { logger } from '../logger';\nimport { Relations } from './relations';\nimport { Room } from \"./room\";\nimport { Filter } from \"../filter\";\nimport { EventType, RelationType } from \"../@types/event\";\n\n// var DEBUG = false;\nconst DEBUG = true;\n\nlet debuglog;\nif (DEBUG) {\n // using bind means that we get to keep useful line numbers in the console\n debuglog = logger.log.bind(logger);\n} else {\n debuglog = function() {};\n}\n\ninterface IOpts {\n timelineSupport?: boolean;\n filter?: Filter;\n unstableClientRelationAggregation?: boolean;\n}\n\nexport class EventTimelineSet extends EventEmitter {\n private readonly timelineSupport: boolean;\n private unstableClientRelationAggregation: boolean;\n private liveTimeline: EventTimeline;\n private timelines: EventTimeline[];\n private _eventIdToTimeline: Record<string, EventTimeline>;\n private filter?: Filter;\n private relations: Record<string, Record<string, Record<RelationType, Relations>>>;\n\n /**\n * Construct a set of EventTimeline objects, typically on behalf of a given\n * room. A room may have multiple EventTimelineSets for different levels\n * of filtering. The global notification list is also an EventTimelineSet, but\n * lacks a room.\n *\n * <p>This is an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline (if appropriate).\n * It also tracks forward and backward pagination tokens, as well as containing\n * links to the next timeline in the sequence.\n *\n * <p>There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n * <p>In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @constructor\n * @param {?Room} room\n * Room for this timelineSet. May be null for non-room cases, such as the\n * notification timeline.\n * @param {Object} opts Options inherited from Room.\n *\n * @param {boolean} [opts.timelineSupport = false]\n * Set to true to enable improved timeline support.\n * @param {Object} [opts.filter = null]\n * The filter object, if any, for this timelineSet.\n * @param {boolean} [opts.unstableClientRelationAggregation = false]\n * Optional. Set to true to enable client-side aggregation of event relations\n * via `getRelationsForEvent`.\n * This feature is currently unstable and the API may change without notice.\n */\n constructor(public readonly room: Room, opts: IOpts) {\n super();\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n this.liveTimeline = new EventTimeline(this);\n this.unstableClientRelationAggregation = !!opts.unstableClientRelationAggregation;\n\n // just a list - *not* ordered.\n this.timelines = [this.liveTimeline];\n this._eventIdToTimeline = {};\n\n this.filter = opts.filter;\n\n if (this.unstableClientRelationAggregation) {\n // A tree of objects to access a set of relations for an event, as in:\n // this.relations[relatesToEventId][relationType][relationEventType]\n this.relations = {};\n }\n }\n\n /**\n * Get all the timelines in this set\n * @return {module:models/event-timeline~EventTimeline[]} the timelines in this set\n */\n public getTimelines(): EventTimeline[] {\n return this.timelines;\n }\n\n /**\n * Get the filter object this timeline set is filtered on, if any\n * @return {?Filter} the optional filter for this timelineSet\n */\n public getFilter(): Filter | undefined {\n return this.filter;\n }\n\n /**\n * Set the filter object this timeline set is filtered on\n * (passed to the server when paginating via /messages).\n * @param {Filter} filter the filter for this timelineSet\n */\n public setFilter(filter?: Filter): void {\n this.filter = filter;\n }\n\n /**\n * Get the list of pending sent events for this timelineSet's room, filtered\n * by the timelineSet's filter if appropriate.\n *\n * @return {module:models/event.MatrixEvent[]} A list of the sent events\n * waiting for remote echo.\n *\n * @throws If <code>opts.pendingEventOrdering</code> was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (!this.room) {\n return [];\n }\n\n if (this.filter) {\n return this.filter.filterRoomTimeline(this.room.getPendingEvents());\n } else {\n return this.room.getPendingEvents();\n }\n }\n\n /**\n * Get the live timeline for this room.\n *\n * @return {module:models/event-timeline~EventTimeline} live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.liveTimeline;\n }\n\n /**\n * Return the timeline (if any) this event is in.\n * @param {String} eventId the eventId being sought\n * @return {module:models/event-timeline~EventTimeline} timeline\n */\n public eventIdToTimeline(eventId: string): EventTimeline {\n return this._eventIdToTimeline[eventId];\n }\n\n /**\n * Track a new event as if it were in the same timeline as an old event,\n * replacing it.\n * @param {String} oldEventId event ID of the original event\n * @param {String} newEventId event ID of the replacement event\n */\n public replaceEventId(oldEventId: string, newEventId: string): void {\n const existingTimeline = this._eventIdToTimeline[oldEventId];\n if (existingTimeline) {\n delete this._eventIdToTimeline[oldEventId];\n this._eventIdToTimeline[newEventId] = existingTimeline;\n }\n }\n\n /**\n * Reset the live timeline, and start a new one.\n *\n * <p>This is used when /sync returns a 'limited' timeline.\n *\n * @param {string=} backPaginationToken token for back-paginating the new timeline\n * @param {string=} forwardPaginationToken token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset.\n *\n * @fires module:client~MatrixClient#event:\"Room.timelineReset\"\n */\n public resetLiveTimeline(backPaginationToken: string, forwardPaginationToken?: string): void {\n // Each EventTimeline has RoomState objects tracking the state at the start\n // and end of that timeline. The copies at the end of the live timeline are\n // special because they will have listeners attached to monitor changes to\n // the current room state, so we move this RoomState from the end of the\n // current live timeline to the end of the new one and, if necessary,\n // replace it with a newly created one. We also make a copy for the start\n // of the new timeline.\n\n // if timeline support is disabled, forget about the old timelines\n const resetAllTimelines = !this.timelineSupport || !forwardPaginationToken;\n\n const oldTimeline = this.liveTimeline;\n const newTimeline = resetAllTimelines ?\n oldTimeline.forkLive(EventTimeline.FORWARDS) :\n oldTimeline.fork(EventTimeline.FORWARDS);\n\n if (resetAllTimelines) {\n this.timelines = [newTimeline];\n this._eventIdToTimeline = {};\n } else {\n this.timelines.push(newTimeline);\n }\n\n if (forwardPaginationToken) {\n // Now set the forward pagination token on the old live timeline\n // so it can be forward-paginated.\n oldTimeline.setPaginationToken(\n forwardPaginationToken, EventTimeline.FORWARDS,\n );\n }\n\n // make sure we set the pagination token before firing timelineReset,\n // otherwise clients which start back-paginating will fail, and then get\n // stuck without realising that they *can* back-paginate.\n newTimeline.setPaginationToken(backPaginationToken, EventTimeline.BACKWARDS);\n\n // Now we can swap the live timeline to the new one.\n this.liveTimeline = newTimeline;\n this.emit(\"Room.timelineReset\", this.room, this, resetAllTimelines);\n }\n\n /**\n * Get the timeline which contains the given event, if any\n *\n * @param {string} eventId event ID to look for\n * @return {?module:models/event-timeline~EventTimeline} timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId: string): EventTimeline | null {\n const res = this._eventIdToTimeline[eventId];\n return (res === undefined) ? null : res;\n }\n\n /**\n * Get an event which is stored in our timelines\n *\n * @param {string} eventId event ID to look for\n * @return {?module:models/event~MatrixEvent} the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n const tl = this.getTimelineForEvent(eventId);\n if (!tl) {\n return undefined;\n }\n return tl.getEvents().find(function(ev) {\n return ev.getId() == eventId;\n });\n }\n\n /**\n * Add a new timeline to this timeline list\n *\n * @return {module:models/event-timeline~EventTimeline} newly-created timeline\n */\n public addTimeline(): EventTimeline {\n if (!this.timelineSupport) {\n throw new Error(\"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable\" +\n \" it.\");\n }\n\n const timeline = new EventTimeline(this);\n this.timelines.push(timeline);\n return timeline;\n }\n\n /**\n * Add events to a timeline\n *\n * <p>Will fire \"Room.timeline\" for each event added.\n *\n * @param {MatrixEvent[]} events A list of events to add.\n *\n * @param {boolean} toStartOfTimeline True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the <b>last</b> element of 'events'.\n *\n * @param {module:models/event-timeline~EventTimeline} timeline timeline to\n * add events to.\n *\n * @param {string=} paginationToken token for the next batch of events\n *\n * @fires module:client~MatrixClient#event:\"Room.timeline\"\n *\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken: string,\n ): void {\n if (!timeline) {\n throw new Error(\n \"'timeline' not specified for EventTimelineSet.addEventsToTimeline\",\n );\n }\n\n if (!toStartOfTimeline && timeline == this.liveTimeline) {\n throw new Error(\n \"EventTimelineSet.addEventsToTimeline cannot be used for adding events to \" +\n \"the live timeline - use Room.addLiveEvents instead\",\n );\n }\n\n if (this.filter) {\n events = this.filter.filterRoomTimeline(events);\n if (!events.length) {\n return;\n }\n }\n\n const direction = toStartOfTimeline ? EventTimeline.BACKWARDS :\n EventTimeline.FORWARDS;\n const inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS :\n EventTimeline.BACKWARDS;\n\n // Adding events to timelines can be quite complicated. The following\n // illustrates some of the corner-cases.\n //\n // Let's say we start by knowing about four timelines. timeline3 and\n // timeline4 are neighbours:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M] [P] [S] <------> [T]\n //\n // Now we paginate timeline1, and get the following events from the server:\n // [M, N, P, R, S, T, U].\n //\n // 1. First, we ignore event M, since we already know about it.\n //\n // 2. Next, we append N to timeline 1.\n //\n // 3. Next, we don't add event P, since we already know about it,\n // but we do link together the timelines. We now have:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P] [S] <------> [T]\n //\n // 4. Now we add event R to timeline2:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P, R] [S] <------> [T]\n //\n // Note that we have switched the timeline we are working on from\n // timeline1 to timeline2.\n //\n // 5. We ignore event S, but again join the timelines:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P, R] <---> [S] <------> [T]\n //\n // 6. We ignore event T, and the timelines are already joined, so there\n // is nothing to do.\n //\n // 7. Finally, we add event U to timeline4:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P, R] <---> [S] <------> [T, U]\n //\n // The important thing to note in the above is what happened when we\n // already knew about a given event:\n //\n // - if it was appropriate, we joined up the timelines (steps 3, 5).\n // - in any case, we started adding further events to the timeline which\n // contained the event we knew about (steps 3, 5, 6).\n //\n //\n // So much for adding events to the timeline. But what do we want to do\n // with the pagination token?\n //\n // In the case above, we will be given a pagination token which tells us how to\n // get events beyond 'U' - in this case, it makes sense to store this\n // against timeline4. But what if timeline4 already had 'U' and beyond? in\n // that case, our best bet is to throw away the pagination token we were\n // given and stick with whatever token timeline4 had previously. In short,\n // we want to only store the pagination token if the last event we receive\n // is one we didn't previously know about.\n //\n // We make an exception for this if it turns out that we already knew about\n // *all* of the events, and we weren't able to join up any timelines. When\n // that happens, it means our existing pagination token is faulty, since it\n // is only telling us what we already know. Rather than repeatedly\n // paginating with the same token, we might as well use the new pagination\n // token in the hope that we eventually work our way out of the mess.\n\n let didUpdate = false;\n let lastEventWasNew = false;\n for (let i = 0; i < events.length; i++) {\n const event = events[i];\n const eventId = event.getId();\n\n const existingTimeline = this._eventIdToTimeline[eventId];\n\n if (!existingTimeline) {\n // we don't know about this event yet. Just add it to the timeline.\n this.addEventToTimeline(event, timeline, toStartOfTimeline);\n lastEventWasNew = true;\n didUpdate = true;\n continue;\n }\n\n lastEventWasNew = false;\n\n if (existingTimeline == timeline) {\n debuglog(\"Event \" + eventId + \" already in timeline \" + timeline);\n continue;\n }\n\n const neighbour = timeline.getNeighbouringTimeline(direction);\n if (neighbour) {\n // this timeline already has a neighbour in the relevant direction;\n // let's assume the timelines are already correctly linked up, and\n // skip over to it.\n //\n // there's probably some edge-case here where we end up with an\n // event which is in a timeline a way down the chain, and there is\n // a break in the chain somewhere. But I can't really imagine how\n // that would happen, so I'm going to ignore it for now.\n //\n if (existingTimeline == neighbour) {\n debuglog(\"Event \" + eventId + \" in neighbouring timeline - \" +\n \"switching to \" + existingTimeline);\n } else {\n debuglog(\"Event \" + eventId + \" already in a different \" +\n \"timeline \" + existingTimeline);\n }\n timeline = existingTimeline;\n continue;\n }\n\n // time to join the timelines.\n logger.info(\"Already have timeline for \" + eventId +\n \" - joining timeline \" + timeline + \" to \" +\n existingTimeline);\n\n // Variables to keep the line length limited below.\n const existingIsLive = existingTimeline === this.liveTimeline;\n const timelineIsLive = timeline === this.liveTimeline;\n\n const backwardsIsLive = direction === EventTimeline.BACKWARDS && existingIsLive;\n const forwardsIsLive = direction === EventTimeline.FORWARDS && timelineIsLive;\n\n if (backwardsIsLive || forwardsIsLive) {\n // The live timeline should never be spliced into a non-live position.\n // We use independent logging to better discover the problem at a glance.\n if (backwardsIsLive) {\n logger.warn(\n \"Refusing to set a preceding existingTimeLine on our \" +\n \"timeline as the existingTimeLine is live (\" + existingTimeline + \")\",\n );\n }\n if (forwardsIsLive) {\n logger.warn(\n \"Refusing to set our preceding timeline on a existingTimeLine \" +\n \"as our timeline is live (\" + timeline + \")\",\n );\n }\n continue; // abort splicing - try next event\n }\n\n timeline.setNeighbouringTimeline(existingTimeline, direction);\n existingTimeline.setNeighbouringTimeline(timeline, inverseDirection);\n\n timeline = existingTimeline;\n didUpdate = true;\n }\n\n // see above - if the last event was new to us, or if we didn't find any\n // new information, we update the pagination token for whatever\n // timeline we ended up on.\n if (lastEventWasNew || !didUpdate) {\n if (direction === EventTimeline.FORWARDS && timeline === this.liveTimeline) {\n logger.warn({ lastEventWasNew, didUpdate }); // for debugging\n logger.warn(\n `Refusing to set forwards pagination token of live timeline ` +\n `${timeline} to ${paginationToken}`,\n );\n return;\n }\n timeline.setPaginationToken(paginationToken, direction);\n }\n }\n\n /**\n * Add an event to the end of this live timeline.\n *\n * @param {MatrixEvent} event Event to be added\n * @param {string?} duplicateStrategy 'ignore' or 'replace'\n * @param {boolean} fromCache whether the sync response came from cache\n */\n public addLiveEvent(event: MatrixEvent, duplicateStrategy?: \"ignore\" | \"replace\", fromCache = false): void {\n if (this.filter) {\n const events = this.filter.filterRoomTimeline([event]);\n if (!events.length) {\n return;\n }\n }\n\n const timeline = this._eventIdToTimeline[event.getId()];\n if (timeline) {\n if (duplicateStrategy === \"replace\") {\n debuglog(\"EventTimelineSet.addLiveEvent: replacing duplicate event \" +\n event.getId());\n const tlEvents = timeline.getEvents();\n for (let j = 0; j < tlEvents.length; j++) {\n if (tlEvents[j].getId() === event.getId()) {\n // still need to set the right metadata on this event\n EventTimeline.setEventMetadata(\n event,\n timeline.getState(EventTimeline.FORWARDS),\n false,\n );\n tlEvents[j] = event;\n\n // XXX: we need to fire an event when this happens.\n break;\n }\n }\n } else {\n debuglog(\"EventTimelineSet.addLiveEvent: ignoring duplicate event \" +\n event.getId());\n }\n return;\n }\n\n this.addEventToTimeline(event, this.liveTimeline, false, fromCache);\n }\n\n /**\n * Add event to the given timeline, and emit Room.timeline. Assumes\n * we have already checked we don't know about this event.\n *\n * Will fire \"Room.timeline\" for each event added.\n *\n * @param {MatrixEvent} event\n * @param {EventTimeline} timeline\n * @param {boolean} toStartOfTimeline\n * @param {boolean} fromCache whether the sync response came from cache\n *\n * @fires module:client~MatrixClient#event:\"Room.timeline\"\n */\n public addEventToTimeline(\n event: MatrixEvent,\n timeline: EventTimeline,\n toStartOfTimeline: boolean,\n fromCache = false,\n ) {\n const eventId = event.getId();\n timeline.addEvent(event, toStartOfTimeline);\n this._eventIdToTimeline[eventId] = timeline;\n\n this.setRelationsTarget(event);\n this.aggregateRelations(event);\n\n const data = {\n timeline: timeline,\n liveEvent: !toStartOfTimeline && timeline == this.liveTimeline && !fromCache,\n };\n this.emit(\"Room.timeline\", event, this.room,\n Boolean(toStartOfTimeline), false, data);\n }\n\n /**\n * Replaces event with ID oldEventId with one with newEventId, if oldEventId is\n * recognised. Otherwise, add to the live timeline. Used to handle remote echos.\n *\n * @param {MatrixEvent} localEvent the new event to be added to the timeline\n * @param {String} oldEventId the ID of the original event\n * @param {boolean} newEventId the ID of the replacement event\n *\n * @fires module:client~MatrixClient#event:\"Room.timeline\"\n */\n public handleRemoteEcho(\n localEvent: MatrixEvent,\n oldEventId: string,\n newEventId: string,\n ): void {\n // XXX: why don't we infer newEventId from localEvent?\n const existingTimeline = this._eventIdToTimeline[oldEventId];\n if (existingTimeline) {\n delete this._eventIdToTimeline[oldEventId];\n this._eventIdToTimeline[newEventId] = existingTimeline;\n } else {\n if (this.filter) {\n if (this.filter.filterRoomTimeline([localEvent]).length) {\n this.addEventToTimeline(localEvent, this.liveTimeline, false);\n }\n } else {\n this.addEventToTimeline(localEvent, this.liveTimeline, false);\n }\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param {String} eventId The id of the event to remove\n *\n * @return {?MatrixEvent} the removed event, or null if the event was not found\n * in this room.\n */\n public removeEvent(eventId: string): MatrixEvent | null {\n const timeline = this._eventIdToTimeline[eventId];\n if (!timeline) {\n return null;\n }\n\n const removed = timeline.removeEvent(eventId);\n if (removed) {\n delete this._eventIdToTimeline[eventId];\n const data = {\n timeline: timeline,\n };\n this.emit(\"Room.timeline\", removed, this.room, undefined, true, data);\n }\n return removed;\n }\n\n /**\n * Determine where two events appear in the timeline relative to one another\n *\n * @param {string} eventId1 The id of the first event\n * @param {string} eventId2 The id of the second event\n\n * @return {?number} a number less than zero if eventId1 precedes eventId2, and\n * greater than zero if eventId1 succeeds eventId2. zero if they are the\n * same event; null if we can't tell (either because we don't know about one\n * of the events, or because they are in separate timelines which don't join\n * up).\n */\n public compareEventOrdering(eventId1: string, eventId2: string): number | null {\n if (eventId1 == eventId2) {\n // optimise this case\n return 0;\n }\n\n const timeline1 = this._eventIdToTimeline[eventId1];\n const timeline2 = this._eventIdToTimeline[eventId2];\n\n if (timeline1 === undefined) {\n return null;\n }\n if (timeline2 === undefined) {\n return null;\n }\n\n if (timeline1 === timeline2) {\n // both events are in the same timeline - figure out their\n // relative indices\n let idx1;\n let idx2;\n const events = timeline1.getEvents();\n for (let idx = 0; idx < events.length &&\n (idx1 === undefined || idx2 === undefined); idx++) {\n const evId = events[idx].getId();\n if (evId == eventId1) {\n idx1 = idx;\n }\n if (evId == eventId2) {\n idx2 = idx;\n }\n }\n return idx1 - idx2;\n }\n\n // the events are in different timelines. Iterate through the\n // linkedlist to see which comes first.\n\n // first work forwards from timeline1\n let tl = timeline1;\n while (tl) {\n if (tl === timeline2) {\n // timeline1 is before timeline2\n return -1;\n }\n tl = tl.getNeighbouringTimeline(EventTimeline.FORWARDS);\n }\n\n // now try backwards from timeline1\n tl = timeline1;\n while (tl) {\n if (tl === timeline2) {\n // timeline2 is before timeline1\n return 1;\n }\n tl = tl.getNeighbouringTimeline(EventTimeline.BACKWARDS);\n }\n\n // the timelines are not contiguous.\n return null;\n }\n\n /**\n * Get a collection of relations to a given event in this timeline set.\n *\n * @param {String} eventId\n * The ID of the event that you'd like to access relation events for.\n * For example, with annotations, this would be the ID of the event being annotated.\n * @param {String} relationType\n * The type of relation involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param {String} eventType\n * The relation event's type, such as \"m.reaction\", etc.\n * @throws If <code>eventId</code>, <code>relationType</code> or <code>eventType</code>\n * are not valid.\n *\n * @returns {?Relations}\n * A container for relation events or undefined if there are no relation events for\n * the relationType.\n */\n public getRelationsForEvent(\n eventId: string,\n relationType: RelationType,\n eventType: EventType | string,\n ): Relations | undefined {\n if (!this.unstableClientRelationAggregation) {\n throw new Error(\"Client-side relation aggregation is disabled\");\n }\n\n if (!eventId || !relationType || !eventType) {\n throw new Error(\"Invalid arguments for `getRelationsForEvent`\");\n }\n\n // debuglog(\"Getting relations for: \", eventId, relationType, eventType);\n\n const relationsForEvent = this.relations[eventId] || {};\n const relationsWithRelType = relationsForEvent[relationType] || {};\n return relationsWithRelType[eventType];\n }\n\n /**\n * Set an event as the target event if any Relations exist for it already\n *\n * @param {MatrixEvent} event\n * The event to check as relation target.\n */\n public setRelationsTarget(event: MatrixEvent): void {\n if (!this.unstableClientRelationAggregation) {\n return;\n }\n\n const relationsForEvent = this.relations[event.getId()];\n if (!relationsForEvent) {\n return;\n }\n\n for (const relationsWithRelType of Object.values(relationsForEvent)) {\n for (const relationsWithEventType of Object.values(relationsWithRelType)) {\n relationsWithEventType.setTargetEvent(event);\n }\n }\n }\n\n /**\n * Add relation events to the relevant relation collection.\n *\n * @param {MatrixEvent} event\n * The new relation event to be aggregated.\n */\n public aggregateRelations(event: MatrixEvent): void {\n if (!this.unstableClientRelationAggregation) {\n return;\n }\n\n if (event.isRedacted() || event.status === EventStatus.CANCELLED) {\n return;\n }\n\n // If the event is currently encrypted, wait until it has been decrypted.\n if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n event.once(\"Event.decrypted\", () => {\n this.aggregateRelations(event);\n });\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n return;\n }\n\n const relatesToEventId = relation.event_id;\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n // debuglog(\"Aggregating relation: \", event.getId(), eventType, relation);\n\n let relationsForEvent: Record<string, Partial<Record<string, Relations>>> = this.relations[relatesToEventId];\n if (!relationsForEvent) {\n relationsForEvent = this.relations[relatesToEventId] = {};\n }\n let relationsWithRelType = relationsForEvent[relationType];\n if (!relationsWithRelType) {\n relationsWithRelType = relationsForEvent[relationType] = {};\n }\n let relationsWithEventType = relationsWithRelType[eventType];\n\n let relatesToEvent;\n if (!relationsWithEventType) {\n relationsWithEventType = relationsWithRelType[eventType] = new Relations(\n relationType,\n eventType,\n this.room,\n );\n relatesToEvent = this.findEventById(relatesToEventId) || this.room.getPendingEvent(relatesToEventId);\n if (relatesToEvent) {\n relationsWithEventType.setTargetEvent(relatesToEvent);\n }\n }\n\n relationsWithEventType.addEvent(event);\n }\n}\n\n/**\n * Fires whenever the timeline in a room is updated.\n * @event module:client~MatrixClient#\"Room.timeline\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {?Room} room The room, if any, whose timeline was updated.\n * @param {boolean} toStartOfTimeline True if this event was added to the start\n * @param {boolean} removed True if this event has just been removed from the timeline\n * (beginning; oldest) of the timeline e.g. due to pagination.\n *\n * @param {object} data more data about the event\n *\n * @param {module:models/event-timeline.EventTimeline} data.timeline the timeline the\n * event was added to/removed from\n *\n * @param {boolean} data.liveEvent true if the event was a real-time event\n * added to the end of the live timeline\n *\n * @example\n * matrixClient.on(\"Room.timeline\",\n * function(event, room, toStartOfTimeline, removed, data) {\n * if (!toStartOfTimeline && data.liveEvent) {\n * var messageToAppend = room.timeline.[room.timeline.length - 1];\n * }\n * });\n */\n\n/**\n * Fires whenever the live timeline in a room is reset.\n *\n * When we get a 'limited' sync (for example, after a network outage), we reset\n * the live timeline to be empty before adding the recent events to the new\n * timeline. This event is fired after the timeline is reset, and before the\n * new events are added.\n *\n * @event module:client~MatrixClient#\"Room.timelineReset\"\n * @param {Room} room The room whose live timeline was reset, if any\n * @param {EventTimelineSet} timelineSet timelineSet room whose live timeline was reset\n * @param {boolean} resetAllTimelines True if all timelines were reset.\n */\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/event-timeline\n */\n\nimport { RoomState } from \"./room-state\";\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { MatrixEvent } from \"./event\";\nimport { Filter } from \"../filter\";\nimport { EventType } from \"../@types/event\";\n\nexport enum Direction {\n Backward = \"b\",\n Forward = \"f\",\n}\n\nexport class EventTimeline {\n /**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the start of the timeline, or backwards in time.\n */\n static BACKWARDS = Direction.Backward;\n\n /**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the end of the timeline, or forwards in time.\n */\n static FORWARDS = Direction.Forward;\n\n /**\n * Static helper method to set sender and target properties\n *\n * @param {MatrixEvent} event the event whose metadata is to be set\n * @param {RoomState} stateContext the room state to be queried\n * @param {boolean} toStartOfTimeline if true the event's forwardLooking flag is set false\n */\n static setEventMetadata(event: MatrixEvent, stateContext: RoomState, toStartOfTimeline: boolean): void {\n // We always check if the event doesn't already have the property. We do\n // this to avoid overriding non-sentinel members by sentinel ones when\n // adding the event to a filtered timeline\n if (!event.sender) {\n event.sender = stateContext.getSentinelMember(event.getSender());\n }\n if (!event.target && event.getType() === EventType.RoomMember) {\n event.target = stateContext.getSentinelMember(event.getStateKey());\n }\n\n if (event.isState()) {\n // room state has no concept of 'old' or 'current', but we want the\n // room state to regress back to previous values if toStartOfTimeline\n // is set, which means inspecting prev_content if it exists. This\n // is done by toggling the forwardLooking flag.\n if (toStartOfTimeline) {\n event.forwardLooking = false;\n }\n }\n }\n\n private readonly roomId: string | null;\n private readonly name: string;\n private events: MatrixEvent[] = [];\n private baseIndex = 0;\n private startState: RoomState;\n private endState: RoomState;\n private prevTimeline?: EventTimeline;\n private nextTimeline?: EventTimeline;\n public paginationRequests: Record<Direction, Promise<boolean>> = {\n [Direction.Backward]: null,\n [Direction.Forward]: null,\n };\n\n /**\n * Construct a new EventTimeline\n *\n * <p>An EventTimeline represents a contiguous sequence of events in a room.\n *\n * <p>As well as keeping track of the events themselves, it stores the state of\n * the room at the beginning and end of the timeline, and pagination tokens for\n * going backwards and forwards in the timeline.\n *\n * <p>In order that clients can meaningfully maintain an index into a timeline,\n * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is\n * incremented when events are prepended to the timeline. The index of an event\n * relative to baseIndex therefore remains constant.\n *\n * <p>Once a timeline joins up with its neighbour, they are linked together into a\n * doubly-linked list.\n *\n * @param {EventTimelineSet} eventTimelineSet the set of timelines this is part of\n * @constructor\n */\n constructor(private readonly eventTimelineSet: EventTimelineSet) {\n this.roomId = eventTimelineSet.room?.roomId ?? null;\n this.startState = new RoomState(this.roomId);\n this.startState.paginationToken = null;\n this.endState = new RoomState(this.roomId);\n this.endState.paginationToken = null;\n\n this.prevTimeline = null;\n this.nextTimeline = null;\n\n // this is used by client.js\n this.paginationRequests = { 'b': null, 'f': null };\n\n this.name = this.roomId + \":\" + new Date().toISOString();\n }\n\n /**\n * Initialise the start and end state with the given events\n *\n * <p>This can only be called before any events are added.\n *\n * @param {MatrixEvent[]} stateEvents list of state events to initialise the\n * state with.\n * @throws {Error} if an attempt is made to call this after addEvent is called.\n */\n public initialiseState(stateEvents: MatrixEvent[]): void {\n if (this.events.length > 0) {\n throw new Error(\"Cannot initialise state after events are added\");\n }\n\n // We previously deep copied events here and used different copies in\n // the oldState and state events: this decision seems to date back\n // quite a way and was apparently made to fix a bug where modifications\n // made to the start state leaked through to the end state.\n // This really shouldn't be possible though: the events themselves should\n // not change. Duplicating the events uses a lot of extra memory,\n // so we now no longer do it. To assert that they really do never change,\n // freeze them! Note that we can't do this for events in general:\n // although it looks like the only things preventing us are the\n // 'status' flag, forwardLooking (which is only set once when adding to the\n // timeline) and possibly the sender (which seems like it should never be\n // reset but in practice causes a lot of the tests to break).\n for (const e of stateEvents) {\n Object.freeze(e);\n }\n\n this.startState.setStateEvents(stateEvents);\n this.endState.setStateEvents(stateEvents);\n }\n\n /**\n * Forks the (live) timeline, taking ownership of the existing directional state of this timeline.\n * All attached listeners will keep receiving state updates from the new live timeline state.\n * The end state of this timeline gets replaced with an independent copy of the current RoomState,\n * and will need a new pagination token if it ever needs to paginate forwards.\n\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {EventTimeline} the new timeline\n */\n public forkLive(direction: Direction): EventTimeline {\n const forkState = this.getState(direction);\n const timeline = new EventTimeline(this.eventTimelineSet);\n timeline.startState = forkState.clone();\n // Now clobber the end state of the new live timeline with that from the\n // previous live timeline. It will be identical except that we'll keep\n // using the same RoomMember objects for the 'live' set of members with any\n // listeners still attached\n timeline.endState = forkState;\n // Firstly, we just stole the current timeline's end state, so it needs a new one.\n // Make an immutable copy of the state so back pagination will get the correct sentinels.\n this.endState = forkState.clone();\n return timeline;\n }\n\n /**\n * Creates an independent timeline, inheriting the directional state from this timeline.\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {EventTimeline} the new timeline\n */\n public fork(direction: Direction): EventTimeline {\n const forkState = this.getState(direction);\n const timeline = new EventTimeline(this.eventTimelineSet);\n timeline.startState = forkState.clone();\n timeline.endState = forkState.clone();\n return timeline;\n }\n\n /**\n * Get the ID of the room for this timeline\n * @return {string} room ID\n */\n public getRoomId(): string {\n return this.roomId;\n }\n\n /**\n * Get the filter for this timeline's timelineSet (if any)\n * @return {Filter} filter\n */\n public getFilter(): Filter {\n return this.eventTimelineSet.getFilter();\n }\n\n /**\n * Get the timelineSet for this timeline\n * @return {EventTimelineSet} timelineSet\n */\n public getTimelineSet(): EventTimelineSet {\n return this.eventTimelineSet;\n }\n\n /**\n * Get the base index.\n *\n * <p>This is an index which is incremented when events are prepended to the\n * timeline. An individual event therefore stays at the same index in the array\n * relative to the base index (although note that a given event's index may\n * well be less than the base index, thus giving that event a negative relative\n * index).\n *\n * @return {number}\n */\n public getBaseIndex(): number {\n return this.baseIndex;\n }\n\n /**\n * Get the list of events in this context\n *\n * @return {MatrixEvent[]} An array of MatrixEvents\n */\n public getEvents(): MatrixEvent[] {\n return this.events;\n }\n\n /**\n * Get the room state at the start/end of the timeline\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @return {RoomState} state at the start/end of the timeline\n */\n public getState(direction: Direction): RoomState {\n if (direction == EventTimeline.BACKWARDS) {\n return this.startState;\n } else if (direction == EventTimeline.FORWARDS) {\n return this.endState;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n }\n\n /**\n * Get a pagination token\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to get the\n * pagination token for going forwards in time.\n *\n * @return {?string} pagination token\n */\n public getPaginationToken(direction: Direction): string | null {\n return this.getState(direction).paginationToken;\n }\n\n /**\n * Set a pagination token\n *\n * @param {?string} token pagination token\n *\n * @param {string} direction EventTimeline.BACKWARDS to set the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to set the\n * pagination token for going forwards in time.\n */\n public setPaginationToken(token: string, direction: Direction): void {\n this.getState(direction).paginationToken = token;\n }\n\n /**\n * Get the next timeline in the series\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the previous\n * timeline; EventTimeline.FORWARDS to get the next timeline.\n *\n * @return {?EventTimeline} previous or following timeline, if they have been\n * joined up.\n */\n public getNeighbouringTimeline(direction: Direction): EventTimeline {\n if (direction == EventTimeline.BACKWARDS) {\n return this.prevTimeline;\n } else if (direction == EventTimeline.FORWARDS) {\n return this.nextTimeline;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n }\n\n /**\n * Set the next timeline in the series\n *\n * @param {EventTimeline} neighbour previous/following timeline\n *\n * @param {string} direction EventTimeline.BACKWARDS to set the previous\n * timeline; EventTimeline.FORWARDS to set the next timeline.\n *\n * @throws {Error} if an attempt is made to set the neighbouring timeline when\n * it is already set.\n */\n public setNeighbouringTimeline(neighbour: EventTimeline, direction: Direction): void {\n if (this.getNeighbouringTimeline(direction)) {\n throw new Error(\"timeline already has a neighbouring timeline - \" +\n \"cannot reset neighbour (direction: \" + direction + \")\");\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n this.prevTimeline = neighbour;\n } else if (direction == EventTimeline.FORWARDS) {\n this.nextTimeline = neighbour;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n\n // make sure we don't try to paginate this timeline\n this.setPaginationToken(null, direction);\n }\n\n /**\n * Add a new event to the timeline, and update the state\n *\n * @param {MatrixEvent} event new event\n * @param {boolean} atStart true to insert new event at the start\n */\n public addEvent(event: MatrixEvent, atStart: boolean): void {\n const stateContext = atStart ? this.startState : this.endState;\n const timelineSet = this.getTimelineSet();\n\n if (timelineSet.room) {\n EventTimeline.setEventMetadata(event, stateContext, atStart);\n\n // modify state but only on unfiltered timelineSets\n if (\n event.isState() &&\n timelineSet.room.getUnfilteredTimelineSet() === timelineSet\n ) {\n stateContext.setStateEvents([event]);\n // it is possible that the act of setting the state event means we\n // can set more metadata (specifically sender/target props), so try\n // it again if the prop wasn't previously set. It may also mean that\n // the sender/target is updated (if the event set was a room member event)\n // so we want to use the *updated* member (new avatar/name) instead.\n //\n // However, we do NOT want to do this on member events if we're going\n // back in time, else we'll set the .sender value for BEFORE the given\n // member event, whereas we want to set the .sender value for the ACTUAL\n // member event itself.\n if (!event.sender || (event.getType() === \"m.room.member\" && !atStart)) {\n EventTimeline.setEventMetadata(event, stateContext, atStart);\n }\n }\n }\n\n let insertIndex;\n\n if (atStart) {\n insertIndex = 0;\n } else {\n insertIndex = this.events.length;\n }\n\n this.events.splice(insertIndex, 0, event); // insert element\n if (atStart) {\n this.baseIndex++;\n }\n }\n\n /**\n * Remove an event from the timeline\n *\n * @param {string} eventId ID of event to be removed\n * @return {?MatrixEvent} removed event, or null if not found\n */\n public removeEvent(eventId: string): MatrixEvent | null {\n for (let i = this.events.length - 1; i >= 0; i--) {\n const ev = this.events[i];\n if (ev.getId() == eventId) {\n this.events.splice(i, 1);\n if (i < this.baseIndex) {\n this.baseIndex--;\n }\n return ev;\n }\n }\n return null;\n }\n\n /**\n * Return a string to identify this timeline, for debugging\n *\n * @return {string} name for this timeline\n */\n public toString(): string {\n return this.name;\n }\n}\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n * @module models/event\n */\n\nimport { EventEmitter } from 'events';\n\nimport { logger } from '../logger';\nimport { VerificationRequest } from \"../crypto/verification/request/VerificationRequest\";\nimport { EventType, MsgType, RelationType } from \"../@types/event\";\nimport { Crypto } from \"../crypto\";\nimport { deepSortedObjectEntries } from \"../utils\";\nimport { RoomMember } from \"./room-member\";\n\n/**\n * Enum for event statuses.\n * @readonly\n * @enum {string}\n */\nexport enum EventStatus {\n /** The event was not sent and will no longer be retried. */\n NOT_SENT = \"not_sent\",\n\n /** The message is being encrypted */\n ENCRYPTING = \"encrypting\",\n\n /** The event is in the process of being sent. */\n SENDING = \"sending\",\n\n /** The event is in a queue waiting to be sent. */\n QUEUED = \"queued\",\n\n /** The event has been sent to the server, but we have not yet received the echo. */\n SENT = \"sent\",\n\n /** The event was cancelled before it was successfully sent. */\n CANCELLED = \"cancelled\",\n}\n\nconst interns: Record<string, string> = {};\nfunction intern(str: string): string {\n if (!interns[str]) {\n interns[str] = str;\n }\n return interns[str];\n}\n\n/* eslint-disable camelcase */\nexport interface IContent {\n [key: string]: any;\n msgtype?: MsgType | string;\n membership?: string;\n avatar_url?: string;\n displayname?: string;\n \"m.relates_to\"?: IEventRelation;\n}\n\ntype StrippedState = Required<Pick<IEvent, \"content\" | \"state_key\" | \"type\" | \"sender\">>;\n\nexport interface IUnsigned {\n age?: number;\n prev_sender?: string;\n prev_content?: IContent;\n redacted_because?: IEvent;\n transaction_id?: string;\n invite_room_state?: StrippedState[];\n}\n\nexport interface IEvent {\n event_id: string;\n type: string;\n content: IContent;\n sender: string;\n room_id: string;\n origin_server_ts: number;\n txn_id?: string;\n state_key?: string;\n membership?: string;\n unsigned: IUnsigned;\n redacts?: string;\n\n // v1 legacy fields\n user_id?: string;\n prev_content?: IContent;\n age?: number;\n}\n\ninterface IAggregatedRelation {\n origin_server_ts: number;\n event_id?: string;\n sender?: string;\n type?: string;\n count?: number;\n key?: string;\n}\n\ninterface IEventRelation {\n rel_type: RelationType | string;\n event_id: string;\n key?: string;\n}\n\ninterface IDecryptionResult {\n clearEvent: {\n room_id?: string;\n type: string;\n content: IContent;\n unsigned?: IUnsigned;\n };\n forwardingCurve25519KeyChain?: string[];\n senderCurve25519Key?: string;\n claimedEd25519Key?: string;\n untrusted?: boolean;\n}\n/* eslint-enable camelcase */\n\nexport interface IClearEvent {\n type: string;\n content: Omit<IContent, \"membership\" | \"avatar_url\" | \"displayname\" | \"m.relates_to\">;\n unsigned?: IUnsigned;\n}\n\ninterface IKeyRequestRecipient {\n userId: string;\n deviceId: \"*\" | string;\n}\n\nexport interface IDecryptOptions {\n emit?: boolean;\n isRetry?: boolean;\n}\n\nexport class MatrixEvent extends EventEmitter {\n private pushActions: object = null;\n private _replacingEvent: MatrixEvent = null;\n private _localRedactionEvent: MatrixEvent = null;\n private _isCancelled = false;\n private clearEvent: Partial<IClearEvent> = {};\n\n /* curve25519 key which we believe belongs to the sender of the event. See\n * getSenderKey()\n */\n private senderCurve25519Key: string = null;\n\n /* ed25519 key which the sender of this event (for olm) or the creator of\n * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n */\n private claimedEd25519Key: string = null;\n\n /* curve25519 keys of devices involved in telling us about the\n * senderCurve25519Key and claimedEd25519Key.\n * See getForwardingCurve25519KeyChain().\n */\n private forwardingCurve25519KeyChain: string[] = [];\n\n /* where the decryption key is untrusted\n */\n private untrusted: boolean = null;\n\n /* if we have a process decrypting this event, a Promise which resolves\n * when it is finished. Normally null.\n */\n private _decryptionPromise: Promise<void> = null;\n\n /* flag to indicate if we should retry decrypting this event after the\n * first attempt (eg, we have received new data which means that a second\n * attempt may succeed)\n */\n private retryDecryption = false;\n\n /* The txnId with which this event was sent if it was during this session,\n * allows for a unique ID which does not change when the event comes back down sync.\n */\n private txnId: string = null;\n\n /* Set an approximate timestamp for the event relative the local clock.\n * This will inherently be approximate because it doesn't take into account\n * the time between the server putting the 'age' field on the event as it sent\n * it to us and the time we're now constructing this event, but that's better\n * than assuming the local clock is in sync with the origin HS's clock.\n */\n private readonly localTimestamp: number;\n\n // XXX: these should be read-only\n public sender: RoomMember = null;\n public target: RoomMember = null;\n public status: EventStatus = null;\n public error = null;\n public forwardLooking = true;\n\n /* If the event is a `m.key.verification.request` (or to_device `m.key.verification.start`) event,\n * `Crypto` will set this the `VerificationRequest` for the event\n * so it can be easily accessed from the timeline.\n */\n public verificationRequest = null;\n\n /**\n * Construct a Matrix Event object\n * @constructor\n *\n * @param {Object} event The raw event to be wrapped in this DAO\n *\n * @prop {Object} event The raw (possibly encrypted) event. <b>Do not access\n * this property</b> directly unless you absolutely have to. Prefer the getter\n * methods defined on this class. Using the getter methods shields your app\n * from changes to event JSON between Matrix versions.\n *\n * @prop {RoomMember} sender The room member who sent this event, or null e.g.\n * this is a presence event. This is only guaranteed to be set for events that\n * appear in a timeline, ie. do not guarantee that it will be set on state\n * events.\n * @prop {RoomMember} target The room member who is the target of this event, e.g.\n * the invitee, the person being banned, etc.\n * @prop {EventStatus} status The sending status of the event.\n * @prop {Error} error most recent error associated with sending the event, if any\n * @prop {boolean} forwardLooking True if this event is 'forward looking', meaning\n * that getDirectionalContent() will return event.content and not event.prev_content.\n * Default: true. <strong>This property is experimental and may change.</strong>\n */\n constructor(public event: Partial<IEvent> = {}) {\n super();\n\n // intern the values of matrix events to force share strings and reduce the\n // amount of needless string duplication. This can save moderate amounts of\n // memory (~10% on a 350MB heap).\n // 'membership' at the event level (rather than the content level) is a legacy\n // field that Element never otherwise looks at, but it will still take up a lot\n // of space if we don't intern it.\n [\"state_key\", \"type\", \"sender\", \"room_id\", \"membership\"].forEach((prop) => {\n if (typeof event[prop] !== \"string\") return;\n event[prop] = intern(event[prop]);\n });\n\n [\"membership\", \"avatar_url\", \"displayname\"].forEach((prop) => {\n if (typeof event.content?.[prop] !== \"string\") return;\n event.content[prop] = intern(event.content[prop]);\n });\n\n [\"rel_type\"].forEach((prop) => {\n if (typeof event.content?.[\"m.relates_to\"]?.[prop] !== \"string\") return;\n event.content[\"m.relates_to\"][prop] = intern(event.content[\"m.relates_to\"][prop]);\n });\n\n this.txnId = event.txn_id || null;\n this.localTimestamp = Date.now() - this.getAge();\n }\n\n /**\n * Get the event_id for this event.\n * @return {string} The event ID, e.g. <code>$143350589368169JsLZx:localhost\n * </code>\n */\n public getId(): string {\n return this.event.event_id;\n }\n\n /**\n * Get the user_id for this event.\n * @return {string} The user ID, e.g. <code>@alice:matrix.org</code>\n */\n public getSender(): string {\n return this.event.sender || this.event.user_id; // v2 / v1\n }\n\n /**\n * Get the (decrypted, if necessary) type of event.\n *\n * @return {string} The event type, e.g. <code>m.room.message</code>\n */\n public getType(): EventType | string {\n return this.clearEvent.type || this.event.type;\n }\n\n /**\n * Get the (possibly encrypted) type of the event that will be sent to the\n * homeserver.\n *\n * @return {string} The event type.\n */\n public getWireType(): EventType | string {\n return this.event.type;\n }\n\n /**\n * Get the room_id for this event. This will return <code>undefined</code>\n * for <code>m.presence</code> events.\n * @return {string} The room ID, e.g. <code>!cURbafjkfsMDVwdRDQ:matrix.org\n * </code>\n */\n public getRoomId(): string {\n return this.event.room_id;\n }\n\n /**\n * Get the timestamp of this event.\n * @return {Number} The event timestamp, e.g. <code>1433502692297</code>\n */\n public getTs(): number {\n return this.event.origin_server_ts;\n }\n\n /**\n * Get the timestamp of this event, as a Date object.\n * @return {Date} The event date, e.g. <code>new Date(1433502692297)</code>\n */\n public getDate(): Date | null {\n return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;\n }\n\n /**\n * Get the (decrypted, if necessary) event content JSON, even if the event\n * was replaced by another event.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n public getOriginalContent<T = IContent>(): T {\n if (this._localRedactionEvent) {\n return {} as T;\n }\n return (this.clearEvent.content || this.event.content || {}) as T;\n }\n\n /**\n * Get the (decrypted, if necessary) event content JSON,\n * or the content from the replacing event, if any.\n * See `makeReplaced`.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n public getContent<T = IContent>(): T {\n if (this._localRedactionEvent) {\n return {} as T;\n } else if (this._replacingEvent) {\n return this._replacingEvent.getContent()[\"m.new_content\"] || {};\n } else {\n return this.getOriginalContent();\n }\n }\n\n /**\n * Get the (possibly encrypted) event content JSON that will be sent to the\n * homeserver.\n *\n * @return {Object} The event content JSON, or an empty object.\n */\n public getWireContent(): IContent {\n return this.event.content || {};\n }\n\n /**\n * Get the previous event content JSON. This will only return something for\n * state events which exist in the timeline.\n * @return {Object} The previous event content JSON, or an empty object.\n */\n public getPrevContent(): IContent {\n // v2 then v1 then default\n return this.getUnsigned().prev_content || this.event.prev_content || {};\n }\n\n /**\n * Get either 'content' or 'prev_content' depending on if this event is\n * 'forward-looking' or not. This can be modified via event.forwardLooking.\n * In practice, this means we get the chronologically earlier content value\n * for this event (this method should surely be called getEarlierContent)\n * <strong>This method is experimental and may change.</strong>\n * @return {Object} event.content if this event is forward-looking, else\n * event.prev_content.\n */\n public getDirectionalContent(): IContent {\n return this.forwardLooking ? this.getContent() : this.getPrevContent();\n }\n\n /**\n * Get the age of this event. This represents the age of the event when the\n * event arrived at the device, and not the age of the event when this\n * function was called.\n * @return {Number} The age of this event in milliseconds.\n */\n public getAge(): number {\n return this.getUnsigned().age || this.event.age; // v2 / v1\n }\n\n /**\n * Get the age of the event when this function was called.\n * This is the 'age' field adjusted according to how long this client has\n * had the event.\n * @return {Number} The age of this event in milliseconds.\n */\n public getLocalAge(): number {\n return Date.now() - this.localTimestamp;\n }\n\n /**\n * Get the event state_key if it has one. This will return <code>undefined\n * </code> for message events.\n * @return {string} The event's <code>state_key</code>.\n */\n public getStateKey(): string | undefined {\n return this.event.state_key;\n }\n\n /**\n * Check if this event is a state event.\n * @return {boolean} True if this is a state event.\n */\n public isState(): boolean {\n return this.event.state_key !== undefined;\n }\n\n /**\n * Replace the content of this event with encrypted versions.\n * (This is used when sending an event; it should not be used by applications).\n *\n * @internal\n *\n * @param {string} cryptoType type of the encrypted event - typically\n * <tt>\"m.room.encrypted\"</tt>\n *\n * @param {object} cryptoContent raw 'content' for the encrypted event.\n *\n * @param {string} senderCurve25519Key curve25519 key to record for the\n * sender of this event.\n * See {@link module:models/event.MatrixEvent#getSenderKey}.\n *\n * @param {string} claimedEd25519Key claimed ed25519 key to record for the\n * sender if this event.\n * See {@link module:models/event.MatrixEvent#getClaimedEd25519Key}\n */\n public makeEncrypted(\n cryptoType: string,\n cryptoContent: object,\n senderCurve25519Key: string,\n claimedEd25519Key: string,\n ): void {\n // keep the plain-text data for 'view source'\n this.clearEvent = {\n type: this.event.type,\n content: this.event.content,\n };\n this.event.type = cryptoType;\n this.event.content = cryptoContent;\n this.senderCurve25519Key = senderCurve25519Key;\n this.claimedEd25519Key = claimedEd25519Key;\n }\n\n /**\n * Check if this event is currently being decrypted.\n *\n * @return {boolean} True if this event is currently being decrypted, else false.\n */\n public isBeingDecrypted(): boolean {\n return this._decryptionPromise != null;\n }\n\n public getDecryptionPromise(): Promise<void> {\n return this._decryptionPromise;\n }\n\n /**\n * Check if this event is an encrypted event which we failed to decrypt\n *\n * (This implies that we might retry decryption at some point in the future)\n *\n * @return {boolean} True if this event is an encrypted event which we\n * couldn't decrypt.\n */\n public isDecryptionFailure(): boolean {\n return this.clearEvent?.content?.msgtype === \"m.bad.encrypted\";\n }\n\n public shouldAttemptDecryption() {\n return this.isEncrypted() && !this.isBeingDecrypted() && this.getClearContent() === null;\n }\n\n /**\n * Start the process of trying to decrypt this event.\n *\n * (This is used within the SDK: it isn't intended for use by applications)\n *\n * @internal\n *\n * @param {module:crypto} crypto crypto module\n * @param {object} options\n * @param {boolean} options.isRetry True if this is a retry (enables more logging)\n * @param {boolean} options.emit Emits \"event.decrypted\" if set to true\n *\n * @returns {Promise} promise which resolves (to undefined) when the decryption\n * attempt is completed.\n */\n public async attemptDecryption(crypto: Crypto, options: IDecryptOptions = {}): Promise<void> {\n // For backwards compatibility purposes\n // The function signature used to be attemptDecryption(crypto, isRetry)\n if (typeof options === \"boolean\") {\n options = {\n isRetry: options,\n };\n }\n\n // start with a couple of sanity checks.\n if (!this.isEncrypted()) {\n throw new Error(\"Attempt to decrypt event which isn't encrypted\");\n }\n\n if (\n this.clearEvent && this.clearEvent.content &&\n this.clearEvent.content.msgtype !== \"m.bad.encrypted\"\n ) {\n // we may want to just ignore this? let's start with rejecting it.\n throw new Error(\n \"Attempt to decrypt event which has already been decrypted\",\n );\n }\n\n // if we already have a decryption attempt in progress, then it may\n // fail because it was using outdated info. We now have reason to\n // succeed where it failed before, but we don't want to have multiple\n // attempts going at the same time, so just set a flag that says we have\n // new info.\n //\n if (this._decryptionPromise) {\n logger.log(\n `Event ${this.getId()} already being decrypted; queueing a retry`,\n );\n this.retryDecryption = true;\n return this._decryptionPromise;\n }\n\n this._decryptionPromise = this.decryptionLoop(crypto, options);\n return this._decryptionPromise;\n }\n\n /**\n * Cancel any room key request for this event and resend another.\n *\n * @param {module:crypto} crypto crypto module\n * @param {string} userId the user who received this event\n *\n * @returns {Promise} a promise that resolves when the request is queued\n */\n public cancelAndResendKeyRequest(crypto: Crypto, userId: string): Promise<void> {\n const wireContent = this.getWireContent();\n return crypto.requestRoomKey({\n algorithm: wireContent.algorithm,\n room_id: this.getRoomId(),\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key,\n }, this.getKeyRequestRecipients(userId), true);\n }\n\n /**\n * Calculate the recipients for keyshare requests.\n *\n * @param {string} userId the user who received this event.\n *\n * @returns {Array} array of recipients\n */\n public getKeyRequestRecipients(userId: string): IKeyRequestRecipient[] {\n // send the request to all of our own devices, and the\n // original sending device if it wasn't us.\n const wireContent = this.getWireContent();\n const recipients = [{\n userId, deviceId: '*',\n }];\n const sender = this.getSender();\n if (sender !== userId) {\n recipients.push({\n userId: sender, deviceId: wireContent.device_id,\n });\n }\n return recipients;\n }\n\n private async decryptionLoop(crypto: Crypto, options: IDecryptOptions = {}): Promise<void> {\n // make sure that this method never runs completely synchronously.\n // (doing so would mean that we would clear _decryptionPromise *before*\n // it is set in attemptDecryption - and hence end up with a stuck\n // `_decryptionPromise`).\n await Promise.resolve();\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n this.retryDecryption = false;\n\n let res;\n let err;\n try {\n if (!crypto) {\n res = this.badEncryptedMessage(\"Encryption not enabled\");\n } else {\n res = await crypto.decryptEvent(this);\n if (options.isRetry === true) {\n logger.info(`Decrypted event on retry (id=${this.getId()})`);\n }\n }\n } catch (e) {\n if (e.name !== \"DecryptionError\") {\n // not a decryption error: log the whole exception as an error\n // (and don't bother with a retry)\n const re = options.isRetry ? 're' : '';\n logger.error(\n `Error ${re}decrypting event ` +\n `(id=${this.getId()}): ${e.stack || e}`,\n );\n this._decryptionPromise = null;\n this.retryDecryption = false;\n return;\n }\n\n err = e;\n\n // see if we have a retry queued.\n //\n // NB: make sure to keep this check in the same tick of the\n // event loop as `_decryptionPromise = null` below - otherwise we\n // risk a race:\n //\n // * A: we check retryDecryption here and see that it is\n // false\n // * B: we get a second call to attemptDecryption, which sees\n // that _decryptionPromise is set so sets\n // retryDecryption\n // * A: we continue below, clear _decryptionPromise, and\n // never do the retry.\n //\n if (this.retryDecryption) {\n // decryption error, but we have a retry queued.\n logger.log(\n `Got error decrypting event (id=${this.getId()}: ` +\n `${e}), but retrying`,\n );\n continue;\n }\n\n // decryption error, no retries queued. Warn about the error and\n // set it to m.bad.encrypted.\n logger.warn(\n `Error decrypting event (id=${this.getId()}): ${e.detailedString}`,\n );\n\n res = this.badEncryptedMessage(e.message);\n }\n\n // at this point, we've either successfully decrypted the event, or have given up\n // (and set res to a 'badEncryptedMessage'). Either way, we can now set the\n // cleartext of the event and raise Event.decrypted.\n //\n // make sure we clear '_decryptionPromise' before sending the 'Event.decrypted' event,\n // otherwise the app will be confused to see `isBeingDecrypted` still set when\n // there isn't an `Event.decrypted` on the way.\n //\n // see also notes on retryDecryption above.\n //\n this._decryptionPromise = null;\n this.retryDecryption = false;\n this.setClearData(res);\n\n // Before we emit the event, clear the push actions so that they can be recalculated\n // by relevant code. We do this because the clear event has now changed, making it\n // so that existing rules can be re-run over the applicable properties. Stuff like\n // highlighting when the user's name is mentioned rely on this happening. We also want\n // to set the push actions before emitting so that any notification listeners don't\n // pick up the wrong contents.\n this.setPushActions(null);\n\n if (options.emit !== false) {\n this.emit(\"Event.decrypted\", this, err);\n }\n\n return;\n }\n }\n\n private badEncryptedMessage(reason: string): IDecryptionResult {\n return {\n clearEvent: {\n type: \"m.room.message\",\n content: {\n msgtype: \"m.bad.encrypted\",\n body: \"** Unable to decrypt: \" + reason + \" **\",\n },\n },\n };\n }\n\n /**\n * Update the cleartext data on this event.\n *\n * (This is used after decrypting an event; it should not be used by applications).\n *\n * @internal\n *\n * @fires module:models/event.MatrixEvent#\"Event.decrypted\"\n *\n * @param {module:crypto~EventDecryptionResult} decryptionResult\n * the decryption result, including the plaintext and some key info\n */\n private setClearData(decryptionResult: IDecryptionResult): void {\n this.clearEvent = decryptionResult.clearEvent;\n this.senderCurve25519Key =\n decryptionResult.senderCurve25519Key || null;\n this.claimedEd25519Key =\n decryptionResult.claimedEd25519Key || null;\n this.forwardingCurve25519KeyChain =\n decryptionResult.forwardingCurve25519KeyChain || [];\n this.untrusted = decryptionResult.untrusted || false;\n }\n\n /**\n * Gets the cleartext content for this event. If the event is not encrypted,\n * or encryption has not been completed, this will return null.\n *\n * @returns {Object} The cleartext (decrypted) content for the event\n */\n public getClearContent(): IContent | null {\n const ev = this.clearEvent;\n return ev && ev.content ? ev.content : null;\n }\n\n /**\n * Check if the event is encrypted.\n * @return {boolean} True if this event is encrypted.\n */\n public isEncrypted(): boolean {\n return !this.isState() && this.event.type === \"m.room.encrypted\";\n }\n\n /**\n * The curve25519 key for the device that we think sent this event\n *\n * For an Olm-encrypted event, this is inferred directly from the DH\n * exchange at the start of the session: the curve25519 key is involved in\n * the DH exchange, so only a device which holds the private part of that\n * key can establish such a session.\n *\n * For a megolm-encrypted event, it is inferred from the Olm message which\n * established the megolm session\n *\n * @return {string}\n */\n public getSenderKey(): string | null {\n return this.senderCurve25519Key;\n }\n\n /**\n * The additional keys the sender of this encrypted event claims to possess.\n *\n * Just a wrapper for #getClaimedEd25519Key (q.v.)\n *\n * @return {Object<string, string>}\n */\n public getKeysClaimed(): Record<\"ed25519\", string> {\n return {\n ed25519: this.claimedEd25519Key,\n };\n }\n\n /**\n * Get the ed25519 the sender of this event claims to own.\n *\n * For Olm messages, this claim is encoded directly in the plaintext of the\n * event itself. For megolm messages, it is implied by the m.room_key event\n * which established the megolm session.\n *\n * Until we download the device list of the sender, it's just a claim: the\n * device list gives a proof that the owner of the curve25519 key used for\n * this event (and returned by #getSenderKey) also owns the ed25519 key by\n * signing the public curve25519 key with the ed25519 key.\n *\n * In general, applications should not use this method directly, but should\n * instead use MatrixClient.getEventSenderDeviceInfo.\n *\n * @return {string}\n */\n public getClaimedEd25519Key(): string | null {\n return this.claimedEd25519Key;\n }\n\n /**\n * Get the curve25519 keys of the devices which were involved in telling us\n * about the claimedEd25519Key and sender curve25519 key.\n *\n * Normally this will be empty, but in the case of a forwarded megolm\n * session, the sender keys are sent to us by another device (the forwarding\n * device), which we need to trust to do this. In that case, the result will\n * be a list consisting of one entry.\n *\n * If the device that sent us the key (A) got it from another device which\n * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on.\n *\n * @return {string[]} base64-encoded curve25519 keys, from oldest to newest.\n */\n public getForwardingCurve25519KeyChain(): string[] {\n return this.forwardingCurve25519KeyChain;\n }\n\n /**\n * Whether the decryption key was obtained from an untrusted source. If so,\n * we cannot verify the authenticity of the message.\n *\n * @return {boolean}\n */\n public isKeySourceUntrusted(): boolean {\n return this.untrusted;\n }\n\n public getUnsigned(): IUnsigned {\n return this.event.unsigned || {};\n }\n\n public unmarkLocallyRedacted(): boolean {\n const value = this._localRedactionEvent;\n this._localRedactionEvent = null;\n if (this.event.unsigned) {\n this.event.unsigned.redacted_because = null;\n }\n return !!value;\n }\n\n public markLocallyRedacted(redactionEvent: MatrixEvent): void {\n if (this._localRedactionEvent) return;\n this.emit(\"Event.beforeRedaction\", this, redactionEvent);\n this._localRedactionEvent = redactionEvent;\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redactionEvent.event as IEvent;\n }\n\n /**\n * Update the content of an event in the same way it would be by the server\n * if it were redacted before it was sent to us\n *\n * @param {module:models/event.MatrixEvent} redactionEvent\n * event causing the redaction\n */\n public makeRedacted(redactionEvent: MatrixEvent): void {\n // quick sanity-check\n if (!redactionEvent.event) {\n throw new Error(\"invalid redactionEvent in makeRedacted\");\n }\n\n this._localRedactionEvent = null;\n\n this.emit(\"Event.beforeRedaction\", this, redactionEvent);\n\n this._replacingEvent = null;\n // we attempt to replicate what we would see from the server if\n // the event had been redacted before we saw it.\n //\n // The server removes (most of) the content of the event, and adds a\n // \"redacted_because\" key to the unsigned section containing the\n // redacted event.\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redactionEvent.event as IEvent;\n\n let key;\n for (key in this.event) {\n if (!this.event.hasOwnProperty(key)) {\n continue;\n }\n if (!REDACT_KEEP_KEYS.has(key)) {\n delete this.event[key];\n }\n }\n\n const keeps = REDACT_KEEP_CONTENT_MAP[this.getType()] || {};\n const content = this.getContent();\n for (key in content) {\n if (!content.hasOwnProperty(key)) {\n continue;\n }\n if (!keeps[key]) {\n delete content[key];\n }\n }\n }\n\n /**\n * Check if this event has been redacted\n *\n * @return {boolean} True if this event has been redacted\n */\n public isRedacted(): boolean {\n return Boolean(this.getUnsigned().redacted_because);\n }\n\n /**\n * Check if this event is a redaction of another event\n *\n * @return {boolean} True if this event is a redaction\n */\n public isRedaction(): boolean {\n return this.getType() === \"m.room.redaction\";\n }\n\n /**\n * Get the (decrypted, if necessary) redaction event JSON\n * if event was redacted\n *\n * @returns {object} The redaction event JSON, or an empty object\n */\n public getRedactionEvent(): object | null {\n if (!this.isRedacted()) return null;\n\n if (this.clearEvent.unsigned) {\n return this.clearEvent.unsigned.redacted_because;\n } else if (this.event.unsigned.redacted_because) {\n return this.event.unsigned.redacted_because;\n } else {\n return {};\n }\n }\n\n /**\n * Get the push actions, if known, for this event\n *\n * @return {?Object} push actions\n */\n public getPushActions(): object | null {\n return this.pushActions;\n }\n\n /**\n * Set the push actions for this event.\n *\n * @param {Object} pushActions push actions\n */\n public setPushActions(pushActions: object): void {\n this.pushActions = pushActions;\n }\n\n /**\n * Replace the `event` property and recalculate any properties based on it.\n * @param {Object} event the object to assign to the `event` property\n */\n public handleRemoteEcho(event: object): void {\n const oldUnsigned = this.getUnsigned();\n const oldId = this.getId();\n this.event = event;\n // if this event was redacted before it was sent, it's locally marked as redacted.\n // At this point, we've received the remote echo for the event, but not yet for\n // the redaction that we are sending ourselves. Preserve the locally redacted\n // state by copying over redacted_because so we don't get a flash of\n // redacted, not-redacted, redacted as remote echos come in\n if (oldUnsigned.redacted_because) {\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = oldUnsigned.redacted_because;\n }\n // successfully sent.\n this.setStatus(null);\n if (this.getId() !== oldId) {\n // emit the event if it changed\n this.emit(\"Event.localEventIdReplaced\", this);\n }\n }\n\n /**\n * Whether the event is in any phase of sending, send failure, waiting for\n * remote echo, etc.\n *\n * @return {boolean}\n */\n public isSending(): boolean {\n return !!this.status;\n }\n\n /**\n * Update the event's sending status and emit an event as well.\n *\n * @param {String} status The new status\n */\n public setStatus(status: EventStatus): void {\n this.status = status;\n this.emit(\"Event.status\", this, status);\n }\n\n public replaceLocalEventId(eventId: string): void {\n this.event.event_id = eventId;\n this.emit(\"Event.localEventIdReplaced\", this);\n }\n\n /**\n * Get whether the event is a relation event, and of a given type if\n * `relType` is passed in.\n *\n * @param {string?} relType if given, checks that the relation is of the\n * given type\n * @return {boolean}\n */\n public isRelation(relType: string = undefined): boolean {\n // Relation info is lifted out of the encrypted content when sent to\n // encrypted rooms, so we have to check `getWireContent` for this.\n const content = this.getWireContent();\n const relation = content && content[\"m.relates_to\"];\n return relation && relation.rel_type && relation.event_id &&\n ((relType && relation.rel_type === relType) || !relType);\n }\n\n /**\n * Get relation info for the event, if any.\n *\n * @return {Object}\n */\n public getRelation(): IEventRelation | null {\n if (!this.isRelation()) {\n return null;\n }\n return this.getWireContent()[\"m.relates_to\"];\n }\n\n /**\n * Set an event that replaces the content of this event, through an m.replace relation.\n *\n * @fires module:models/event.MatrixEvent#\"Event.replaced\"\n *\n * @param {MatrixEvent?} newEvent the event with the replacing content, if any.\n */\n public makeReplaced(newEvent?: MatrixEvent): void {\n // don't allow redacted events to be replaced.\n // if newEvent is null we allow to go through though,\n // as with local redaction, the replacing event might get\n // cancelled, which should be reflected on the target event.\n if (this.isRedacted() && newEvent) {\n return;\n }\n if (this._replacingEvent !== newEvent) {\n this._replacingEvent = newEvent;\n this.emit(\"Event.replaced\", this);\n }\n }\n\n /**\n * Returns the status of any associated edit or redaction\n * (not for reactions/annotations as their local echo doesn't affect the original event),\n * or else the status of the event.\n *\n * @return {EventStatus}\n */\n public getAssociatedStatus(): EventStatus | undefined {\n if (this._replacingEvent) {\n return this._replacingEvent.status;\n } else if (this._localRedactionEvent) {\n return this._localRedactionEvent.status;\n }\n return this.status;\n }\n\n public getServerAggregatedRelation(relType: RelationType): IAggregatedRelation {\n const relations = this.getUnsigned()[\"m.relations\"];\n if (relations) {\n return relations[relType];\n }\n }\n\n /**\n * Returns the event ID of the event replacing the content of this event, if any.\n *\n * @return {string?}\n */\n public replacingEventId(): string | undefined {\n const replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);\n if (replaceRelation) {\n return replaceRelation.event_id;\n } else if (this._replacingEvent) {\n return this._replacingEvent.getId();\n }\n }\n\n /**\n * Returns the event replacing the content of this event, if any.\n * Replacements are aggregated on the server, so this would only\n * return an event in case it came down the sync, or for local echo of edits.\n *\n * @return {MatrixEvent?}\n */\n public replacingEvent(): MatrixEvent | undefined {\n return this._replacingEvent;\n }\n\n /**\n * Returns the origin_server_ts of the event replacing the content of this event, if any.\n *\n * @return {Date?}\n */\n public replacingEventDate(): Date | undefined {\n const replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);\n if (replaceRelation) {\n const ts = replaceRelation.origin_server_ts;\n if (Number.isFinite(ts)) {\n return new Date(ts);\n }\n } else if (this._replacingEvent) {\n return this._replacingEvent.getDate();\n }\n }\n\n /**\n * Returns the event that wants to redact this event, but hasn't been sent yet.\n * @return {MatrixEvent} the event\n */\n public localRedactionEvent(): MatrixEvent | undefined {\n return this._localRedactionEvent;\n }\n\n /**\n * For relations and redactions, returns the event_id this event is referring to.\n *\n * @return {string?}\n */\n public getAssociatedId(): string | undefined {\n const relation = this.getRelation();\n if (relation) {\n return relation.event_id;\n } else if (this.isRedaction()) {\n return this.event.redacts;\n }\n }\n\n /**\n * Checks if this event is associated with another event. See `getAssociatedId`.\n *\n * @return {boolean}\n */\n public hasAssocation(): boolean {\n return !!this.getAssociatedId();\n }\n\n /**\n * Update the related id with a new one.\n *\n * Used to replace a local id with remote one before sending\n * an event with a related id.\n *\n * @param {string} eventId the new event id\n */\n public updateAssociatedId(eventId: string): void {\n const relation = this.getRelation();\n if (relation) {\n relation.event_id = eventId;\n } else if (this.isRedaction()) {\n this.event.redacts = eventId;\n }\n }\n\n /**\n * Flags an event as cancelled due to future conditions. For example, a verification\n * request event in the same sync transaction may be flagged as cancelled to warn\n * listeners that a cancellation event is coming down the same pipe shortly.\n * @param {boolean} cancelled Whether the event is to be cancelled or not.\n */\n public flagCancelled(cancelled = true): void {\n this._isCancelled = cancelled;\n }\n\n /**\n * Gets whether or not the event is flagged as cancelled. See flagCancelled() for\n * more information.\n * @returns {boolean} True if the event is cancelled, false otherwise.\n */\n isCancelled(): boolean {\n return this._isCancelled;\n }\n\n /**\n * Get a copy/snapshot of this event. The returned copy will be loosely linked\n * back to this instance, though will have \"frozen\" event information. Other\n * properties of this MatrixEvent instance will be copied verbatim, which can\n * mean they are in reference to this instance despite being on the copy too.\n * The reference the snapshot uses does not change, however members aside from\n * the underlying event will not be deeply cloned, thus may be mutated internally.\n * For example, the sender profile will be copied over at snapshot time, and\n * the sender profile internally may mutate without notice to the consumer.\n *\n * This is meant to be used to snapshot the event details themselves, not the\n * features (such as sender) surrounding the event.\n * @returns {MatrixEvent} A snapshot of this event.\n */\n toSnapshot(): MatrixEvent {\n const ev = new MatrixEvent(JSON.parse(JSON.stringify(this.event)));\n for (const [p, v] of Object.entries(this)) {\n if (p !== \"event\") { // exclude the thing we just cloned\n ev[p] = v;\n }\n }\n return ev;\n }\n\n /**\n * Determines if this event is equivalent to the given event. This only checks\n * the event object itself, not the other properties of the event. Intended for\n * use with toSnapshot() to identify events changing.\n * @param {MatrixEvent} otherEvent The other event to check against.\n * @returns {boolean} True if the events are the same, false otherwise.\n */\n isEquivalentTo(otherEvent: MatrixEvent): boolean {\n if (!otherEvent) return false;\n if (otherEvent === this) return true;\n const myProps = deepSortedObjectEntries(this.event);\n const theirProps = deepSortedObjectEntries(otherEvent.event);\n return JSON.stringify(myProps) === JSON.stringify(theirProps);\n }\n\n /**\n * Summarise the event as JSON for debugging. If encrypted, include both the\n * decrypted and encrypted view of the event. This is named `toJSON` for use\n * with `JSON.stringify` which checks objects for functions named `toJSON`\n * and will call them to customise the output if they are defined.\n *\n * @return {Object}\n */\n public toJSON(): object {\n const event: any = {\n type: this.getType(),\n sender: this.getSender(),\n content: this.getContent(),\n event_id: this.getId(),\n origin_server_ts: this.getTs(),\n unsigned: this.getUnsigned(),\n room_id: this.getRoomId(),\n };\n\n // if this is a redaction then attach the redacts key\n if (this.isRedaction()) {\n event.redacts = this.event.redacts;\n }\n\n if (!this.isEncrypted()) {\n return event;\n }\n\n return {\n decrypted: event,\n encrypted: this.event,\n };\n }\n\n public setVerificationRequest(request: VerificationRequest): void {\n this.verificationRequest = request;\n }\n\n public setTxnId(txnId: string): void {\n this.txnId = txnId;\n }\n\n public getTxnId(): string | undefined {\n return this.txnId;\n }\n}\n\n/* REDACT_KEEP_KEYS gives the keys we keep when an event is redacted\n *\n * This is specified here:\n * http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions\n *\n * Also:\n * - We keep 'unsigned' since that is created by the local server\n * - We keep user_id for backwards-compat with v1\n */\nconst REDACT_KEEP_KEYS = new Set([\n 'event_id', 'type', 'room_id', 'user_id', 'sender', 'state_key', 'prev_state',\n 'content', 'unsigned', 'origin_server_ts',\n]);\n\n// a map from event type to the .content keys we keep when an event is redacted\nconst REDACT_KEEP_CONTENT_MAP = {\n 'm.room.member': { 'membership': 1 },\n 'm.room.create': { 'creator': 1 },\n 'm.room.join_rules': { 'join_rule': 1 },\n 'm.room.power_levels': {\n 'ban': 1, 'events': 1, 'events_default': 1,\n 'kick': 1, 'redact': 1, 'state_default': 1,\n 'users': 1, 'users_default': 1,\n },\n 'm.room.aliases': { 'aliases': 1 },\n};\n\n/**\n * Fires when an event is decrypted\n *\n * @event module:models/event.MatrixEvent#\"Event.decrypted\"\n *\n * @param {module:models/event.MatrixEvent} event\n * The matrix event which has been decrypted\n * @param {module:crypto/algorithms/base.DecryptionError?} err\n * The error that occurred during decryption, or `undefined` if no\n * error occurred.\n */\n",
"/*\nCopyright 2017 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/group\n */\n\nimport * as utils from \"../utils\";\nimport { EventEmitter } from \"events\";\n\n/**\n * Construct a new Group.\n *\n * @param {string} groupId The ID of this group.\n *\n * @prop {string} groupId The ID of this group.\n * @prop {string} name The human-readable display name for this group.\n * @prop {string} avatarUrl The mxc URL for this group's avatar.\n * @prop {string} myMembership The logged in user's membership of this group\n * @prop {Object} inviter Infomation about the user who invited the logged in user\n * to the group, if myMembership is 'invite'.\n * @prop {string} inviter.userId The user ID of the inviter\n */\nexport function Group(groupId) {\n this.groupId = groupId;\n this.name = null;\n this.avatarUrl = null;\n this.myMembership = null;\n this.inviter = null;\n}\nutils.inherits(Group, EventEmitter);\n\nGroup.prototype.setProfile = function(name, avatarUrl) {\n if (this.name === name && this.avatarUrl === avatarUrl) return;\n\n this.name = name || this.groupId;\n this.avatarUrl = avatarUrl;\n\n this.emit(\"Group.profile\", this);\n};\n\nGroup.prototype.setMyMembership = function(membership) {\n if (this.myMembership === membership) return;\n\n this.myMembership = membership;\n\n this.emit(\"Group.myMembership\", this);\n};\n\n/**\n * Sets the 'inviter' property. This does not emit an event (the inviter\n * will only change when the user is revited / reinvited to a room),\n * so set this before setting myMembership.\n * @param {Object} inviter Infomation about who invited us to the room\n */\nGroup.prototype.setInviter = function(inviter) {\n this.inviter = inviter;\n};\n\n/**\n * Fires whenever a group's profile information is updated.\n * This means the 'name' and 'avatarUrl' properties.\n * @event module:client~MatrixClient#\"Group.profile\"\n * @param {Group} group The group whose profile was updated.\n * @example\n * matrixClient.on(\"Group.profile\", function(group){\n * var name = group.name;\n * });\n */\n\n/**\n * Fires whenever the logged in user's membership status of\n * the group is updated.\n * @event module:client~MatrixClient#\"Group.myMembership\"\n * @param {Group} group The group in which the user's membership changed\n * @example\n * matrixClient.on(\"Group.myMembership\", function(group){\n * var myMembership = group.myMembership;\n * });\n */\n",
"/*\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventEmitter } from 'events';\n\nimport { EventStatus, MatrixEvent } from './event';\nimport { Room } from './room';\nimport { logger } from '../logger';\nimport { RelationType } from \"../@types/event\";\n\n/**\n * A container for relation events that supports easy access to common ways of\n * aggregating such events. Each instance holds events that of a single relation\n * type and event type. All of the events also relate to the same original event.\n *\n * The typical way to get one of these containers is via\n * EventTimelineSet#getRelationsForEvent.\n */\nexport class Relations extends EventEmitter {\n private relationEventIds = new Set<string>();\n private relations = new Set<MatrixEvent>();\n private annotationsByKey: Record<string, Set<MatrixEvent>> = {};\n private annotationsBySender: Record<string, Set<MatrixEvent>> = {};\n private sortedAnnotationsByKey: [string, Set<MatrixEvent>][] = [];\n private targetEvent: MatrixEvent = null;\n private creationEmitted = false;\n\n /**\n * @param {RelationType} relationType\n * The type of relation involved, such as \"m.annotation\", \"m.reference\",\n * \"m.replace\", etc.\n * @param {String} eventType\n * The relation event's type, such as \"m.reaction\", etc.\n * @param {?Room} room\n * Room for this container. May be null for non-room cases, such as the\n * notification timeline.\n */\n constructor(\n public readonly relationType: RelationType | string,\n public readonly eventType: string,\n private readonly room: Room,\n ) {\n super();\n }\n\n /**\n * Add relation events to this collection.\n *\n * @param {MatrixEvent} event\n * The new relation event to be added.\n */\n public async addEvent(event: MatrixEvent) {\n if (this.relationEventIds.has(event.getId())) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || this.eventType !== eventType) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n // If the event is in the process of being sent, listen for cancellation\n // so we can remove the event from the collection.\n if (event.isSending()) {\n event.on(\"Event.status\", this.onEventStatus);\n }\n\n this.relations.add(event);\n this.relationEventIds.add(event.getId());\n\n if (this.relationType === RelationType.Annotation) {\n this.addAnnotationToAggregation(event);\n } else if (this.relationType === RelationType.Replace && this.targetEvent) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement);\n }\n\n event.on(\"Event.beforeRedaction\", this.onBeforeRedaction);\n\n this.emit(\"Relations.add\", event);\n\n this.maybeEmitCreated();\n }\n\n /**\n * Remove relation event from this collection.\n *\n * @param {MatrixEvent} event\n * The relation event to remove.\n */\n private async removeEvent(event: MatrixEvent) {\n if (!this.relations.has(event)) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || this.eventType !== eventType) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n this.relations.delete(event);\n\n if (this.relationType === RelationType.Annotation) {\n this.removeAnnotationFromAggregation(event);\n } else if (this.relationType === RelationType.Replace && this.targetEvent) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement);\n }\n\n this.emit(\"Relations.remove\", event);\n }\n\n /**\n * Listens for event status changes to remove cancelled events.\n *\n * @param {MatrixEvent} event The event whose status has changed\n * @param {EventStatus} status The new status\n */\n private onEventStatus = (event: MatrixEvent, status: EventStatus) => {\n if (!event.isSending()) {\n // Sending is done, so we don't need to listen anymore\n event.removeListener(\"Event.status\", this.onEventStatus);\n return;\n }\n if (status !== EventStatus.CANCELLED) {\n return;\n }\n // Event was cancelled, remove from the collection\n event.removeListener(\"Event.status\", this.onEventStatus);\n this.removeEvent(event);\n };\n\n /**\n * Get all relation events in this collection.\n *\n * These are currently in the order of insertion to this collection, which\n * won't match timeline order in the case of scrollback.\n * TODO: Tweak `addEvent` to insert correctly for scrollback.\n *\n * @return {Array}\n * Relation events in insertion order.\n */\n public getRelations() {\n return [...this.relations];\n }\n\n private addAnnotationToAggregation(event: MatrixEvent) {\n const { key } = event.getRelation();\n if (!key) {\n return;\n }\n\n let eventsForKey = this.annotationsByKey[key];\n if (!eventsForKey) {\n eventsForKey = this.annotationsByKey[key] = new Set();\n this.sortedAnnotationsByKey.push([key, eventsForKey]);\n }\n // Add the new event to the set for this key\n eventsForKey.add(event);\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n\n const sender = event.getSender();\n let eventsFromSender = this.annotationsBySender[sender];\n if (!eventsFromSender) {\n eventsFromSender = this.annotationsBySender[sender] = new Set();\n }\n // Add the new event to the set for this sender\n eventsFromSender.add(event);\n }\n\n private removeAnnotationFromAggregation(event: MatrixEvent) {\n const { key } = event.getRelation();\n if (!key) {\n return;\n }\n\n const eventsForKey = this.annotationsByKey[key];\n if (eventsForKey) {\n eventsForKey.delete(event);\n\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n }\n\n const sender = event.getSender();\n const eventsFromSender = this.annotationsBySender[sender];\n if (eventsFromSender) {\n eventsFromSender.delete(event);\n }\n }\n\n /**\n * For relations that have been redacted, we want to remove them from\n * aggregation data sets and emit an update event.\n *\n * To do so, we listen for `Event.beforeRedaction`, which happens:\n * - after the server accepted the redaction and remote echoed back to us\n * - before the original event has been marked redacted in the client\n *\n * @param {MatrixEvent} redactedEvent\n * The original relation event that is about to be redacted.\n */\n private onBeforeRedaction = async (redactedEvent: MatrixEvent) => {\n if (!this.relations.has(redactedEvent)) {\n return;\n }\n\n this.relations.delete(redactedEvent);\n\n if (this.relationType === RelationType.Annotation) {\n // Remove the redacted annotation from aggregation by key\n this.removeAnnotationFromAggregation(redactedEvent);\n } else if (this.relationType === RelationType.Replace && this.targetEvent) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement);\n }\n\n redactedEvent.removeListener(\"Event.beforeRedaction\", this.onBeforeRedaction);\n\n this.emit(\"Relations.redaction\", redactedEvent);\n };\n\n /**\n * Get all events in this collection grouped by key and sorted by descending\n * event count in each group.\n *\n * This is currently only supported for the annotation relation type.\n *\n * @return {Array}\n * An array of [key, events] pairs sorted by descending event count.\n * The events are stored in a Set (which preserves insertion order).\n */\n public getSortedAnnotationsByKey() {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.sortedAnnotationsByKey;\n }\n\n /**\n * Get all events in this collection grouped by sender.\n *\n * This is currently only supported for the annotation relation type.\n *\n * @return {Object}\n * An object with each relation sender as a key and the matching Set of\n * events for that sender as a value.\n */\n public getAnnotationsBySender() {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.annotationsBySender;\n }\n\n /**\n * Returns the most recent (and allowed) m.replace relation, if any.\n *\n * This is currently only supported for the m.replace relation type,\n * once the target event is known, see `addEvent`.\n *\n * @return {MatrixEvent?}\n */\n public async getLastReplacement(): Promise<MatrixEvent | null> {\n if (this.relationType !== RelationType.Replace) {\n // Aggregating on last only makes sense for this relation type\n return null;\n }\n if (!this.targetEvent) {\n // Don't know which replacements to accept yet.\n // This method shouldn't be called before the original\n // event is known anyway.\n return null;\n }\n\n // the all-knowning server tells us that the event at some point had\n // this timestamp for its replacement, so any following replacement should definitely not be less\n const replaceRelation = this.targetEvent.getServerAggregatedRelation(RelationType.Replace);\n const minTs = replaceRelation && replaceRelation.origin_server_ts;\n\n const lastReplacement = this.getRelations().reduce((last, event) => {\n if (event.getSender() !== this.targetEvent.getSender()) {\n return last;\n }\n if (minTs && minTs > event.getTs()) {\n return last;\n }\n if (last && last.getTs() > event.getTs()) {\n return last;\n }\n return event;\n }, null);\n\n if (lastReplacement?.shouldAttemptDecryption()) {\n await lastReplacement.attemptDecryption(this.room.client.crypto);\n } else if (lastReplacement?.isBeingDecrypted()) {\n await lastReplacement.getDecryptionPromise();\n }\n\n return lastReplacement;\n }\n\n /*\n * @param {MatrixEvent} targetEvent the event the relations are related to.\n */\n public async setTargetEvent(event: MatrixEvent) {\n if (this.targetEvent) {\n return;\n }\n this.targetEvent = event;\n\n if (this.relationType === RelationType.Replace) {\n const replacement = await this.getLastReplacement();\n // this is the initial update, so only call it if we already have something\n // to not emit Event.replaced needlessly\n if (replacement) {\n this.targetEvent.makeReplaced(replacement);\n }\n }\n\n this.maybeEmitCreated();\n }\n\n private maybeEmitCreated() {\n if (this.creationEmitted) {\n return;\n }\n // Only emit we're \"created\" once we have a target event instance _and_\n // at least one related event.\n if (!this.targetEvent || !this.relations.size) {\n return;\n }\n this.creationEmitted = true;\n this.targetEvent.emit(\"Event.relationsCreated\", this.relationType, this.eventType);\n }\n}\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room-member\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { User } from \"./user\";\nimport { MatrixEvent } from \"./event\";\nimport { RoomState } from \"./room-state\";\n\nexport class RoomMember extends EventEmitter {\n private _isOutOfBand = false;\n private _modified: number;\n public _requestedProfileInfo: boolean; // used by sync.ts\n\n // XXX these should be read-only\n public typing = false;\n public name: string;\n public rawDisplayName: string;\n public powerLevel = 0;\n public powerLevelNorm = 0;\n public user?: User = null;\n public membership: string = null;\n public disambiguate = false;\n public events: {\n member?: MatrixEvent;\n } = {\n member: null,\n };\n\n /**\n * Construct a new room member.\n *\n * @constructor\n * @alias module:models/room-member\n *\n * @param {string} roomId The room ID of the member.\n * @param {string} userId The user ID of the member.\n * @prop {string} roomId The room ID for this member.\n * @prop {string} userId The user ID of this member.\n * @prop {boolean} typing True if the room member is currently typing.\n * @prop {string} name The human-readable name for this room member. This will be\n * disambiguated with a suffix of \" (@user_id:matrix.org)\" if another member shares the\n * same displayname.\n * @prop {string} rawDisplayName The ambiguous displayname of this room member.\n * @prop {Number} powerLevel The power level for this room member.\n * @prop {Number} powerLevelNorm The normalised power level (0-100) for this\n * room member.\n * @prop {User} user The User object for this room member, if one exists.\n * @prop {string} membership The membership state for this room member e.g. 'join'.\n * @prop {Object} events The events describing this RoomMember.\n * @prop {MatrixEvent} events.member The m.room.member event for this RoomMember.\n * @prop {boolean} disambiguate True if the member's name is disambiguated.\n */\n constructor(public readonly roomId: string, public readonly userId: string) {\n super();\n\n this.name = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Mark the member as coming from a channel that is not sync\n */\n public markOutOfBand(): void {\n this._isOutOfBand = true;\n }\n\n /**\n * @return {boolean} does the member come from a channel that is not sync?\n * This is used to store the member seperately\n * from the sync state so it available across browser sessions.\n */\n public isOutOfBand(): boolean {\n return this._isOutOfBand;\n }\n\n /**\n * Update this room member's membership event. May fire \"RoomMember.name\" if\n * this event updates this member's name.\n * @param {MatrixEvent} event The <code>m.room.member</code> event\n * @param {RoomState} roomState Optional. The room state to take into account\n * when calculating (e.g. for disambiguating users with the same name).\n * @fires module:client~MatrixClient#event:\"RoomMember.name\"\n * @fires module:client~MatrixClient#event:\"RoomMember.membership\"\n */\n public setMembershipEvent(event: MatrixEvent, roomState: RoomState): void {\n const displayName = event.getDirectionalContent().displayname;\n\n if (event.getType() !== \"m.room.member\") {\n return;\n }\n\n this._isOutOfBand = false;\n\n this.events.member = event;\n\n const oldMembership = this.membership;\n this.membership = event.getDirectionalContent().membership;\n\n this.disambiguate = shouldDisambiguate(\n this.userId,\n displayName,\n roomState,\n );\n\n const oldName = this.name;\n this.name = calculateDisplayName(\n this.userId,\n displayName,\n roomState,\n this.disambiguate,\n );\n\n this.rawDisplayName = event.getDirectionalContent().displayname || this.userId;\n if (oldMembership !== this.membership) {\n this.updateModifiedTime();\n this.emit(\"RoomMember.membership\", event, this, oldMembership);\n }\n if (oldName !== this.name) {\n this.updateModifiedTime();\n this.emit(\"RoomMember.name\", event, this, oldName);\n }\n }\n\n /**\n * Update this room member's power level event. May fire\n * \"RoomMember.powerLevel\" if this event updates this member's power levels.\n * @param {MatrixEvent} powerLevelEvent The <code>m.room.power_levels</code>\n * event\n * @fires module:client~MatrixClient#event:\"RoomMember.powerLevel\"\n */\n public setPowerLevelEvent(powerLevelEvent: MatrixEvent): void {\n if (powerLevelEvent.getType() !== \"m.room.power_levels\") {\n return;\n }\n\n const evContent = powerLevelEvent.getDirectionalContent();\n\n let maxLevel = evContent.users_default || 0;\n const users = evContent.users || {};\n Object.values(users).forEach(function(lvl: number) {\n maxLevel = Math.max(maxLevel, lvl);\n });\n const oldPowerLevel = this.powerLevel;\n const oldPowerLevelNorm = this.powerLevelNorm;\n\n if (users[this.userId] !== undefined && Number.isInteger(users[this.userId])) {\n this.powerLevel = users[this.userId];\n } else if (evContent.users_default !== undefined) {\n this.powerLevel = evContent.users_default;\n } else {\n this.powerLevel = 0;\n }\n this.powerLevelNorm = 0;\n if (maxLevel > 0) {\n this.powerLevelNorm = (this.powerLevel * 100) / maxLevel;\n }\n\n // emit for changes in powerLevelNorm as well (since the app will need to\n // redraw everyone's level if the max has changed)\n if (oldPowerLevel !== this.powerLevel || oldPowerLevelNorm !== this.powerLevelNorm) {\n this.updateModifiedTime();\n this.emit(\"RoomMember.powerLevel\", powerLevelEvent, this);\n }\n }\n\n /**\n * Update this room member's typing event. May fire \"RoomMember.typing\" if\n * this event changes this member's typing state.\n * @param {MatrixEvent} event The typing event\n * @fires module:client~MatrixClient#event:\"RoomMember.typing\"\n */\n public setTypingEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.typing\") {\n return;\n }\n const oldTyping = this.typing;\n this.typing = false;\n const typingList = event.getContent().user_ids;\n if (!Array.isArray(typingList)) {\n // malformed event :/ bail early. TODO: whine?\n return;\n }\n if (typingList.indexOf(this.userId) !== -1) {\n this.typing = true;\n }\n if (oldTyping !== this.typing) {\n this.updateModifiedTime();\n this.emit(\"RoomMember.typing\", event, this);\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime() {\n this._modified = Date.now();\n }\n\n /**\n * Get the timestamp when this RoomMember was last updated. This timestamp is\n * updated when properties on this RoomMember are updated.\n * It is updated <i>before</i> firing events.\n * @return {number} The timestamp\n */\n public getLastModifiedTime(): number {\n return this._modified;\n }\n\n public isKicked(): boolean {\n return this.membership === \"leave\" &&\n this.events.member.getSender() !== this.events.member.getStateKey();\n }\n\n /**\n * If this member was invited with the is_direct flag set, return\n * the user that invited this member\n * @return {string} user id of the inviter\n */\n public getDMInviter(): string {\n // when not available because that room state hasn't been loaded in,\n // we don't really know, but more likely to not be a direct chat\n if (this.events.member) {\n // TODO: persist the is_direct flag on the member as more member events\n // come in caused by displayName changes.\n\n // the is_direct flag is set on the invite member event.\n // This is copied on the prev_content section of the join member event\n // when the invite is accepted.\n\n const memberEvent = this.events.member;\n let memberContent = memberEvent.getContent();\n let inviteSender = memberEvent.getSender();\n\n if (memberContent.membership === \"join\") {\n memberContent = memberEvent.getPrevContent();\n inviteSender = memberEvent.getUnsigned().prev_sender;\n }\n\n if (memberContent.membership === \"invite\" && memberContent.is_direct) {\n return inviteSender;\n }\n }\n }\n\n /**\n * Get the avatar URL for a room member.\n * @param {string} baseUrl The base homeserver URL See\n * {@link module:client~MatrixClient#getHomeserverUrl}.\n * @param {Number} width The desired width of the thumbnail.\n * @param {Number} height The desired height of the thumbnail.\n * @param {string} resizeMethod The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param {Boolean} allowDefault (optional) Passing false causes this method to\n * return null if the user has no avatar image. Otherwise, a default image URL\n * will be returned. Default: true. (Deprecated)\n * @param {Boolean} allowDirectLinks (optional) If true, the avatar URL will be\n * returned even if it is a direct hyperlink rather than a matrix content URL.\n * If false, any non-matrix content URLs will be ignored. Setting this option to\n * true will expose URLs that, if fetched, will leak information about the user\n * to anyone who they share a room with.\n * @return {?string} the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: string,\n allowDefault = true,\n allowDirectLinks: boolean,\n ): string | null {\n const rawUrl = this.getMxcAvatarUrl();\n\n if (!rawUrl && !allowDefault) {\n return null;\n }\n const httpUrl = getHttpUriForMxc(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks);\n if (httpUrl) {\n return httpUrl;\n }\n return null;\n }\n\n /**\n * get the mxc avatar url, either from a state event, or from a lazily loaded member\n * @return {string} the mxc avatar url\n */\n public getMxcAvatarUrl(): string | null {\n if (this.events.member) {\n return this.events.member.getDirectionalContent().avatar_url;\n } else if (this.user) {\n return this.user.avatarUrl;\n }\n return null;\n }\n}\n\nconst MXID_PATTERN = /@.+:.+/;\nconst LTR_RTL_PATTERN = /[\\u200E\\u200F\\u202A-\\u202F]/;\n\nfunction shouldDisambiguate(selfUserId: string, displayName: string, roomState: RoomState): boolean {\n if (!displayName || displayName === selfUserId) return false;\n\n // First check if the displayname is something we consider truthy\n // after stripping it of zero width characters and padding spaces\n if (!utils.removeHiddenChars(displayName)) return false;\n\n if (!roomState) return false;\n\n // Next check if the name contains something that look like a mxid\n // If it does, it may be someone trying to impersonate someone else\n // Show full mxid in this case\n if (MXID_PATTERN.test(displayName)) return true;\n\n // Also show mxid if the display name contains any LTR/RTL characters as these\n // make it very difficult for us to find similar *looking* display names\n // E.g \"Mark\" could be cloned by writing \"kraM\" but in RTL.\n if (LTR_RTL_PATTERN.test(displayName)) return true;\n\n // Also show mxid if there are other people with the same or similar\n // displayname, after hidden character removal.\n const userIds = roomState.getUserIdsWithDisplayName(displayName);\n if (userIds.some((u) => u !== selfUserId)) return true;\n\n return false;\n}\n\nfunction calculateDisplayName(\n selfUserId: string,\n displayName: string,\n roomState: RoomState,\n disambiguate: boolean,\n): string {\n if (disambiguate) return displayName + \" (\" + selfUserId + \")\";\n\n if (!displayName || displayName === selfUserId) return selfUserId;\n\n // First check if the displayname is something we consider truthy\n // after stripping it of zero width characters and padding spaces\n if (!utils.removeHiddenChars(displayName)) return selfUserId;\n\n return displayName;\n}\n\n/**\n * Fires whenever any room member's name changes.\n * @event module:client~MatrixClient#\"RoomMember.name\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomMember} member The member whose RoomMember.name changed.\n * @param {string?} oldName The previous name. Null if the member didn't have a\n * name previously.\n * @example\n * matrixClient.on(\"RoomMember.name\", function(event, member){\n * var newName = member.name;\n * });\n */\n\n/**\n * Fires whenever any room member's membership state changes.\n * @event module:client~MatrixClient#\"RoomMember.membership\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomMember} member The member whose RoomMember.membership changed.\n * @param {string?} oldMembership The previous membership state. Null if it's a\n * new member.\n * @example\n * matrixClient.on(\"RoomMember.membership\", function(event, member, oldMembership){\n * var newState = member.membership;\n * });\n */\n\n/**\n * Fires whenever any room member's typing state changes.\n * @event module:client~MatrixClient#\"RoomMember.typing\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomMember} member The member whose RoomMember.typing changed.\n * @example\n * matrixClient.on(\"RoomMember.typing\", function(event, member){\n * var isTyping = member.typing;\n * });\n */\n\n/**\n * Fires whenever any room member's power level changes.\n * @event module:client~MatrixClient#\"RoomMember.powerLevel\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomMember} member The member whose RoomMember.powerLevel changed.\n * @example\n * matrixClient.on(\"RoomMember.powerLevel\", function(event, member){\n * var newPowerLevel = member.powerLevel;\n * var newNormPowerLevel = member.powerLevelNorm;\n * });\n */\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room-state\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { RoomMember } from \"./room-member\";\nimport { logger } from '../logger';\nimport * as utils from \"../utils\";\nimport { EventType } from \"../@types/event\";\nimport { MatrixEvent } from \"./event\";\nimport { MatrixClient } from \"../client\";\n\n// possible statuses for out-of-band member loading\nenum OobStatus {\n NotStarted,\n InProgress,\n Finished,\n}\n\nexport class RoomState extends EventEmitter {\n private sentinels: Record<string, RoomMember> = {}; // userId: RoomMember\n // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)\n private displayNameToUserIds: Record<string, string[]> = {};\n private userIdsToDisplayNames: Record<string, string> = {};\n private tokenToInvite: Record<string, MatrixEvent> = {}; // 3pid invite state_key to m.room.member invite\n private joinedMemberCount: number = null; // cache of the number of joined members\n // joined members count from summary api\n // once set, we know the server supports the summary api\n // and we should only trust that\n // we could also only trust that before OOB members\n // are loaded but doesn't seem worth the hassle atm\n private summaryJoinedMemberCount: number = null;\n // same for invited member count\n private invitedMemberCount: number = null;\n private summaryInvitedMemberCount: number = null;\n private modified: number;\n\n // XXX: Should be read-only\n public members: Record<string, RoomMember> = {}; // userId: RoomMember\n public events = new Map<string, Map<string, MatrixEvent>>(); // Map<eventType, Map<stateKey, MatrixEvent>>\n public paginationToken: string = null;\n\n /**\n * Construct room state.\n *\n * Room State represents the state of the room at a given point.\n * It can be mutated by adding state events to it.\n * There are two types of room member associated with a state event:\n * normal member objects (accessed via getMember/getMembers) which mutate\n * with the state to represent the current state of that room/user, eg.\n * the object returned by getMember('@bob:example.com') will mutate to\n * get a different display name if Bob later changes his display name\n * in the room.\n * There are also 'sentinel' members (accessed via getSentinelMember).\n * These also represent the state of room members at the point in time\n * represented by the RoomState object, but unlike objects from getMember,\n * sentinel objects will always represent the room state as at the time\n * getSentinelMember was called, so if Bob subsequently changes his display\n * name, a room member object previously acquired with getSentinelMember\n * will still have his old display name. Calling getSentinelMember again\n * after the display name change will return a new RoomMember object\n * with Bob's new display name.\n *\n * @constructor\n * @param {?string} roomId Optional. The ID of the room which has this state.\n * If none is specified it just tracks paginationTokens, useful for notifTimelineSet\n * @param {?object} oobMemberFlags Optional. The state of loading out of bound members.\n * As the timeline might get reset while they are loading, this state needs to be inherited\n * and shared when the room state is cloned for the new timeline.\n * This should only be passed from clone.\n * @prop {Object.<string, RoomMember>} members The room member dictionary, keyed\n * on the user's ID.\n * @prop {Object.<string, Object.<string, MatrixEvent>>} events The state\n * events dictionary, keyed on the event type and then the state_key value.\n * @prop {string} paginationToken The pagination token for this state.\n */\n constructor(public readonly roomId: string, private oobMemberFlags = { status: OobStatus.NotStarted }) {\n super();\n this.updateModifiedTime();\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * @return {number} The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n if (this.summaryJoinedMemberCount !== null) {\n return this.summaryJoinedMemberCount;\n }\n if (this.joinedMemberCount === null) {\n this.joinedMemberCount = this.getMembers().reduce((count, m) => {\n return m.membership === 'join' ? count + 1 : count;\n }, 0);\n }\n return this.joinedMemberCount;\n }\n\n /**\n * Set the joined member count explicitly (like from summary part of the sync response)\n * @param {number} count the amount of joined members\n */\n public setJoinedMemberCount(count: number): void {\n this.summaryJoinedMemberCount = count;\n }\n\n /**\n * Returns the number of invited members in this room\n * @return {number} The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n if (this.summaryInvitedMemberCount !== null) {\n return this.summaryInvitedMemberCount;\n }\n if (this.invitedMemberCount === null) {\n this.invitedMemberCount = this.getMembers().reduce((count, m) => {\n return m.membership === 'invite' ? count + 1 : count;\n }, 0);\n }\n return this.invitedMemberCount;\n }\n\n /**\n * Set the amount of invited members in this room\n * @param {number} count the amount of invited members\n */\n public setInvitedMemberCount(count: number): void {\n this.summaryInvitedMemberCount = count;\n }\n\n /**\n * Get all RoomMembers in this room.\n * @return {Array<RoomMember>} A list of RoomMembers.\n */\n public getMembers(): RoomMember[] {\n return Object.values(this.members);\n }\n\n /**\n * Get all RoomMembers in this room, excluding the user IDs provided.\n * @param {Array<string>} excludedIds The user IDs to exclude.\n * @return {Array<RoomMember>} A list of RoomMembers.\n */\n public getMembersExcept(excludedIds: string[]): RoomMember[] {\n return this.getMembers().filter((m) => !excludedIds.includes(m.userId));\n }\n\n /**\n * Get a room member by their user ID.\n * @param {string} userId The room member's user ID.\n * @return {RoomMember} The member or null if they do not exist.\n */\n public getMember(userId: string): RoomMember | null {\n return this.members[userId] || null;\n }\n\n /**\n * Get a room member whose properties will not change with this room state. You\n * typically want this if you want to attach a RoomMember to a MatrixEvent which\n * may no longer be represented correctly by Room.currentState or Room.oldState.\n * The term 'sentinel' refers to the fact that this RoomMember is an unchanging\n * guardian for state at this particular point in time.\n * @param {string} userId The room member's user ID.\n * @return {RoomMember} The member or null if they do not exist.\n */\n public getSentinelMember(userId: string): RoomMember | null {\n if (!userId) return null;\n let sentinel = this.sentinels[userId];\n\n if (sentinel === undefined) {\n sentinel = new RoomMember(this.roomId, userId);\n const member = this.members[userId];\n if (member) {\n sentinel.setMembershipEvent(member.events.member, this);\n }\n this.sentinels[userId] = sentinel;\n }\n return sentinel;\n }\n\n /**\n * Get state events from the state of the room.\n * @param {string} eventType The event type of the state event.\n * @param {string} stateKey Optional. The state_key of the state event. If\n * this is <code>undefined</code> then all matching state events will be\n * returned.\n * @return {MatrixEvent[]|MatrixEvent} A list of events if state_key was\n * <code>undefined</code>, else a single event (or null if no match found).\n */\n public getStateEvents(eventType: string): MatrixEvent[];\n public getStateEvents(eventType: string, stateKey: string): MatrixEvent;\n public getStateEvents(eventType: string, stateKey?: string) {\n if (!this.events.has(eventType)) {\n // no match\n return stateKey === undefined ? [] : null;\n }\n if (stateKey === undefined) { // return all values\n return Array.from(this.events.get(eventType).values());\n }\n const event = this.events.get(eventType).get(stateKey);\n return event ? event : null;\n }\n\n /**\n * Creates a copy of this room state so that mutations to either won't affect the other.\n * @return {RoomState} the copy of the room state\n */\n public clone(): RoomState {\n const copy = new RoomState(this.roomId, this.oobMemberFlags);\n\n // Ugly hack: because setStateEvents will mark\n // members as susperseding future out of bound members\n // if loading is in progress (through oobMemberFlags)\n // since these are not new members, we're merely copying them\n // set the status to not started\n // after copying, we set back the status\n const status = this.oobMemberFlags.status;\n this.oobMemberFlags.status = OobStatus.NotStarted;\n\n Array.from(this.events.values()).forEach((eventsByStateKey) => {\n copy.setStateEvents(Array.from(eventsByStateKey.values()));\n });\n\n // Ugly hack: see above\n this.oobMemberFlags.status = status;\n\n if (this.summaryInvitedMemberCount !== null) {\n copy.setInvitedMemberCount(this.getInvitedMemberCount());\n }\n if (this.summaryJoinedMemberCount !== null) {\n copy.setJoinedMemberCount(this.getJoinedMemberCount());\n }\n\n // copy out of band flags if needed\n if (this.oobMemberFlags.status == OobStatus.Finished) {\n // copy markOutOfBand flags\n this.getMembers().forEach((member) => {\n if (member.isOutOfBand()) {\n const copyMember = copy.getMember(member.userId);\n copyMember.markOutOfBand();\n }\n });\n }\n\n return copy;\n }\n\n /**\n * Add previously unknown state events.\n * When lazy loading members while back-paginating,\n * the relevant room state for the timeline chunk at the end\n * of the chunk can be set with this method.\n * @param {MatrixEvent[]} events state events to prepend\n */\n public setUnknownStateEvents(events: MatrixEvent[]): void {\n const unknownStateEvents = events.filter((event) => {\n return !this.events.has(event.getType()) ||\n !this.events.get(event.getType()).has(event.getStateKey());\n });\n\n this.setStateEvents(unknownStateEvents);\n }\n\n /**\n * Add an array of one or more state MatrixEvents, overwriting\n * any existing state with the same {type, stateKey} tuple. Will fire\n * \"RoomState.events\" for every event added. May fire \"RoomState.members\"\n * if there are <code>m.room.member</code> events.\n * @param {MatrixEvent[]} stateEvents a list of state events for this room.\n * @fires module:client~MatrixClient#event:\"RoomState.members\"\n * @fires module:client~MatrixClient#event:\"RoomState.newMember\"\n * @fires module:client~MatrixClient#event:\"RoomState.events\"\n */\n public setStateEvents(stateEvents: MatrixEvent[]) {\n this.updateModifiedTime();\n\n // update the core event dict\n stateEvents.forEach((event) => {\n if (event.getRoomId() !== this.roomId) {\n return;\n }\n if (!event.isState()) {\n return;\n }\n\n const lastStateEvent = this.getStateEventMatching(event);\n this.setStateEvent(event);\n if (event.getType() === EventType.RoomMember) {\n this.updateDisplayNameCache(event.getStateKey(), event.getContent().displayname);\n this.updateThirdPartyTokenCache(event);\n }\n this.emit(\"RoomState.events\", event, this, lastStateEvent);\n });\n\n // update higher level data structures. This needs to be done AFTER the\n // core event dict as these structures may depend on other state events in\n // the given array (e.g. disambiguating display names in one go to do both\n // clashing names rather than progressively which only catches 1 of them).\n stateEvents.forEach((event) => {\n if (event.getRoomId() !== this.roomId) {\n return;\n }\n if (!event.isState()) {\n return;\n }\n\n if (event.getType() === EventType.RoomMember) {\n const userId = event.getStateKey();\n\n // leave events apparently elide the displayname or avatar_url,\n // so let's fake one up so that we don't leak user ids\n // into the timeline\n if (event.getContent().membership === \"leave\" ||\n event.getContent().membership === \"ban\") {\n event.getContent().avatar_url =\n event.getContent().avatar_url ||\n event.getPrevContent().avatar_url;\n event.getContent().displayname =\n event.getContent().displayname ||\n event.getPrevContent().displayname;\n }\n\n const member = this.getOrCreateMember(userId, event);\n member.setMembershipEvent(event, this);\n\n this.updateMember(member);\n this.emit(\"RoomState.members\", event, this, member);\n } else if (event.getType() === EventType.RoomPowerLevels) {\n // events with unknown state keys should be ignored\n // and should not aggregate onto members power levels\n if (event.getStateKey() !== \"\") {\n return;\n }\n const members = Object.values(this.members);\n members.forEach((member) => {\n // We only propagate `RoomState.members` event if the\n // power levels has been changed\n // large room suffer from large re-rendering especially when not needed\n const oldLastModified = member.getLastModifiedTime();\n member.setPowerLevelEvent(event);\n if (oldLastModified !== member.getLastModifiedTime()) {\n this.emit(\"RoomState.members\", event, this, member);\n }\n });\n\n // assume all our sentinels are now out-of-date\n this.sentinels = {};\n }\n });\n }\n\n /**\n * Looks up a member by the given userId, and if it doesn't exist,\n * create it and emit the `RoomState.newMember` event.\n * This method makes sure the member is added to the members dictionary\n * before emitting, as this is done from setStateEvents and setOutOfBandMember.\n * @param {string} userId the id of the user to look up\n * @param {MatrixEvent} event the membership event for the (new) member. Used to emit.\n * @fires module:client~MatrixClient#event:\"RoomState.newMember\"\n * @returns {RoomMember} the member, existing or newly created.\n */\n private getOrCreateMember(userId: string, event: MatrixEvent): RoomMember {\n let member = this.members[userId];\n if (!member) {\n member = new RoomMember(this.roomId, userId);\n // add member to members before emitting any events,\n // as event handlers often lookup the member\n this.members[userId] = member;\n this.emit(\"RoomState.newMember\", event, this, member);\n }\n return member;\n }\n\n private setStateEvent(event: MatrixEvent): void {\n if (!this.events.has(event.getType())) {\n this.events.set(event.getType(), new Map());\n }\n this.events.get(event.getType()).set(event.getStateKey(), event);\n }\n\n private getStateEventMatching(event: MatrixEvent): MatrixEvent | null {\n if (!this.events.has(event.getType())) return null;\n return this.events.get(event.getType()).get(event.getStateKey());\n }\n\n private updateMember(member: RoomMember): void {\n // this member may have a power level already, so set it.\n const pwrLvlEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n if (pwrLvlEvent) {\n member.setPowerLevelEvent(pwrLvlEvent);\n }\n\n // blow away the sentinel which is now outdated\n delete this.sentinels[member.userId];\n\n this.members[member.userId] = member;\n this.joinedMemberCount = null;\n this.invitedMemberCount = null;\n }\n\n /**\n * Get the out-of-band members loading state, whether loading is needed or not.\n * Note that loading might be in progress and hence isn't needed.\n * @return {boolean} whether or not the members of this room need to be loaded\n */\n public needsOutOfBandMembers(): boolean {\n return this.oobMemberFlags.status === OobStatus.NotStarted;\n }\n\n /**\n * Mark this room state as waiting for out-of-band members,\n * ensuring it doesn't ask for them to be requested again\n * through needsOutOfBandMembers\n */\n public markOutOfBandMembersStarted(): void {\n if (this.oobMemberFlags.status !== OobStatus.NotStarted) {\n return;\n }\n this.oobMemberFlags.status = OobStatus.InProgress;\n }\n\n /**\n * Mark this room state as having failed to fetch out-of-band members\n */\n public markOutOfBandMembersFailed(): void {\n if (this.oobMemberFlags.status !== OobStatus.InProgress) {\n return;\n }\n this.oobMemberFlags.status = OobStatus.NotStarted;\n }\n\n /**\n * Clears the loaded out-of-band members\n */\n public clearOutOfBandMembers(): void {\n let count = 0;\n Object.keys(this.members).forEach((userId) => {\n const member = this.members[userId];\n if (member.isOutOfBand()) {\n ++count;\n delete this.members[userId];\n }\n });\n logger.log(`LL: RoomState removed ${count} members...`);\n this.oobMemberFlags.status = OobStatus.NotStarted;\n }\n\n /**\n * Sets the loaded out-of-band members.\n * @param {MatrixEvent[]} stateEvents array of membership state events\n */\n public setOutOfBandMembers(stateEvents: MatrixEvent[]): void {\n logger.log(`LL: RoomState about to set ${stateEvents.length} OOB members ...`);\n if (this.oobMemberFlags.status !== OobStatus.InProgress) {\n return;\n }\n logger.log(`LL: RoomState put in finished state ...`);\n this.oobMemberFlags.status = OobStatus.Finished;\n stateEvents.forEach((e) => this.setOutOfBandMember(e));\n }\n\n /**\n * Sets a single out of band member, used by both setOutOfBandMembers and clone\n * @param {MatrixEvent} stateEvent membership state event\n */\n private setOutOfBandMember(stateEvent: MatrixEvent): void {\n if (stateEvent.getType() !== EventType.RoomMember) {\n return;\n }\n const userId = stateEvent.getStateKey();\n const existingMember = this.getMember(userId);\n // never replace members received as part of the sync\n if (existingMember && !existingMember.isOutOfBand()) {\n return;\n }\n\n const member = this.getOrCreateMember(userId, stateEvent);\n member.setMembershipEvent(stateEvent, this);\n // needed to know which members need to be stored seperately\n // as they are not part of the sync accumulator\n // this is cleared by setMembershipEvent so when it's updated through /sync\n member.markOutOfBand();\n\n this.updateDisplayNameCache(member.userId, member.name);\n\n this.setStateEvent(stateEvent);\n this.updateMember(member);\n this.emit(\"RoomState.members\", stateEvent, this, member);\n }\n\n /**\n * Set the current typing event for this room.\n * @param {MatrixEvent} event The typing event\n */\n public setTypingEvent(event: MatrixEvent): void {\n Object.values(this.members).forEach(function(member) {\n member.setTypingEvent(event);\n });\n }\n\n /**\n * Get the m.room.member event which has the given third party invite token.\n *\n * @param {string} token The token\n * @return {?MatrixEvent} The m.room.member event or null\n */\n public getInviteForThreePidToken(token: string): MatrixEvent | null {\n return this.tokenToInvite[token] || null;\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this room state was last updated. This timestamp is\n * updated when this object has received new state events.\n * @return {number} The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get user IDs with the specified or similar display names.\n * @param {string} displayName The display name to get user IDs from.\n * @return {string[]} An array of user IDs or an empty array.\n */\n public getUserIdsWithDisplayName(displayName: string): string[] {\n return this.displayNameToUserIds[utils.removeHiddenChars(displayName)] || [];\n }\n\n /**\n * Returns true if userId is in room, event is not redacted and either sender of\n * mxEvent or has power level sufficient to redact events other than their own.\n * @param {MatrixEvent} mxEvent The event to test permission for\n * @param {string} userId The user ID of the user to test permission for\n * @return {boolean} true if the given used ID can redact given event\n */\n public maySendRedactionForEvent(mxEvent: MatrixEvent, userId: string): boolean {\n const member = this.getMember(userId);\n if (!member || member.membership === 'leave') return false;\n\n if (mxEvent.status || mxEvent.isRedacted()) return false;\n\n // The user may have been the sender, but they can't redact their own message\n // if redactions are blocked.\n const canRedact = this.maySendEvent(EventType.RoomRedaction, userId);\n if (mxEvent.getSender() === userId) return canRedact;\n\n return this.hasSufficientPowerLevelFor('redact', member.powerLevel);\n }\n\n /**\n * Returns true if the given power level is sufficient for action\n * @param {string} action The type of power level to check\n * @param {number} powerLevel The power level of the member\n * @return {boolean} true if the given power level is sufficient\n */\n private hasSufficientPowerLevelFor(action: string, powerLevel: number): boolean {\n const powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n\n let powerLevels = {};\n if (powerLevelsEvent) {\n powerLevels = powerLevelsEvent.getContent();\n }\n\n let requiredLevel = 50;\n if (utils.isNumber(powerLevels[action])) {\n requiredLevel = powerLevels[action];\n }\n\n return powerLevel >= requiredLevel;\n }\n\n /**\n * Short-form for maySendEvent('m.room.message', userId)\n * @param {string} userId The user ID of the user to test permission for\n * @return {boolean} true if the given user ID should be permitted to send\n * message events into the given room.\n */\n public maySendMessage(userId: string): boolean {\n return this.maySendEventOfType(EventType.RoomMessage, userId, false);\n }\n\n /**\n * Returns true if the given user ID has permission to send a normal\n * event of type `eventType` into this room.\n * @param {string} eventType The type of event to test\n * @param {string} userId The user ID of the user to test permission for\n * @return {boolean} true if the given user ID should be permitted to send\n * the given type of event into this room,\n * according to the room's state.\n */\n public maySendEvent(eventType: EventType | string, userId: string): boolean {\n return this.maySendEventOfType(eventType, userId, false);\n }\n\n /**\n * Returns true if the given MatrixClient has permission to send a state\n * event of type `stateEventType` into this room.\n * @param {string} stateEventType The type of state events to test\n * @param {MatrixClient} cli The client to test permission for\n * @return {boolean} true if the given client should be permitted to send\n * the given type of state event into this room,\n * according to the room's state.\n */\n public mayClientSendStateEvent(stateEventType: EventType | string, cli: MatrixClient): boolean {\n if (cli.isGuest()) {\n return false;\n }\n return this.maySendStateEvent(stateEventType, cli.credentials.userId);\n }\n\n /**\n * Returns true if the given user ID has permission to send a state\n * event of type `stateEventType` into this room.\n * @param {string} stateEventType The type of state events to test\n * @param {string} userId The user ID of the user to test permission for\n * @return {boolean} true if the given user ID should be permitted to send\n * the given type of state event into this room,\n * according to the room's state.\n */\n public maySendStateEvent(stateEventType: EventType | string, userId: string): boolean {\n return this.maySendEventOfType(stateEventType, userId, true);\n }\n\n /**\n * Returns true if the given user ID has permission to send a normal or state\n * event of type `eventType` into this room.\n * @param {string} eventType The type of event to test\n * @param {string} userId The user ID of the user to test permission for\n * @param {boolean} state If true, tests if the user may send a state\n event of this type. Otherwise tests whether\n they may send a regular event.\n * @return {boolean} true if the given user ID should be permitted to send\n * the given type of event into this room,\n * according to the room's state.\n */\n private maySendEventOfType(eventType: EventType | string, userId: string, state: boolean): boolean {\n const powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, '');\n\n let powerLevels;\n let eventsLevels = {};\n\n let stateDefault = 0;\n let eventsDefault = 0;\n let powerLevel = 0;\n if (powerLevelsEvent) {\n powerLevels = powerLevelsEvent.getContent();\n eventsLevels = powerLevels.events || {};\n\n if (Number.isSafeInteger(powerLevels.state_default)) {\n stateDefault = powerLevels.state_default;\n } else {\n stateDefault = 50;\n }\n\n const userPowerLevel = powerLevels.users && powerLevels.users[userId];\n if (Number.isSafeInteger(userPowerLevel)) {\n powerLevel = userPowerLevel;\n } else if (Number.isSafeInteger(powerLevels.users_default)) {\n powerLevel = powerLevels.users_default;\n }\n\n if (Number.isSafeInteger(powerLevels.events_default)) {\n eventsDefault = powerLevels.events_default;\n }\n }\n\n let requiredLevel = state ? stateDefault : eventsDefault;\n if (Number.isSafeInteger(eventsLevels[eventType])) {\n requiredLevel = eventsLevels[eventType];\n }\n return powerLevel >= requiredLevel;\n }\n\n /**\n * Returns true if the given user ID has permission to trigger notification\n * of type `notifLevelKey`\n * @param {string} notifLevelKey The level of notification to test (eg. 'room')\n * @param {string} userId The user ID of the user to test permission for\n * @return {boolean} true if the given user ID has permission to trigger a\n * notification of this type.\n */\n public mayTriggerNotifOfType(notifLevelKey: string, userId: string): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n\n const powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, '');\n\n let notifLevel = 50;\n if (\n powerLevelsEvent &&\n powerLevelsEvent.getContent() &&\n powerLevelsEvent.getContent().notifications &&\n utils.isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])\n ) {\n notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey];\n }\n\n return member.powerLevel >= notifLevel;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns {string} the join_rule applied to this room\n */\n public getJoinRule(): string {\n const joinRuleEvent = this.getStateEvents(EventType.RoomJoinRules, \"\");\n const joinRuleContent = joinRuleEvent ? joinRuleEvent.getContent() : {};\n return joinRuleContent[\"join_rule\"] || \"invite\";\n }\n\n private updateThirdPartyTokenCache(memberEvent: MatrixEvent): void {\n if (!memberEvent.getContent().third_party_invite) {\n return;\n }\n const token = (memberEvent.getContent().third_party_invite.signed || {}).token;\n if (!token) {\n return;\n }\n const threePidInvite = this.getStateEvents(EventType.RoomThirdPartyInvite, token);\n if (!threePidInvite) {\n return;\n }\n this.tokenToInvite[token] = memberEvent;\n }\n\n private updateDisplayNameCache(userId: string, displayName: string): void {\n const oldName = this.userIdsToDisplayNames[userId];\n delete this.userIdsToDisplayNames[userId];\n if (oldName) {\n // Remove the old name from the cache.\n // We clobber the user_id > name lookup but the name -> [user_id] lookup\n // means we need to remove that user ID from that array rather than nuking\n // the lot.\n const strippedOldName = utils.removeHiddenChars(oldName);\n\n const existingUserIds = this.displayNameToUserIds[strippedOldName];\n if (existingUserIds) {\n // remove this user ID from this array\n const filteredUserIDs = existingUserIds.filter((id) => id !== userId);\n this.displayNameToUserIds[strippedOldName] = filteredUserIDs;\n }\n }\n\n this.userIdsToDisplayNames[userId] = displayName;\n\n const strippedDisplayname = displayName && utils.removeHiddenChars(displayName);\n // an empty stripped displayname (undefined/'') will be set to MXID in room-member.js\n if (strippedDisplayname) {\n if (!this.displayNameToUserIds[strippedDisplayname]) {\n this.displayNameToUserIds[strippedDisplayname] = [];\n }\n this.displayNameToUserIds[strippedDisplayname].push(userId);\n }\n }\n}\n\n/**\n * Fires whenever the event dictionary in room state is updated.\n * @event module:client~MatrixClient#\"RoomState.events\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomState} state The room state whose RoomState.events dictionary\n * was updated.\n * @param {MatrixEvent} prevEvent The event being replaced by the new state, if\n * known. Note that this can differ from `getPrevContent()` on the new state event\n * as this is the store's view of the last state, not the previous state provided\n * by the server.\n * @example\n * matrixClient.on(\"RoomState.events\", function(event, state, prevEvent){\n * var newStateEvent = event;\n * });\n */\n\n/**\n * Fires whenever a member in the members dictionary is updated in any way.\n * @event module:client~MatrixClient#\"RoomState.members\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomState} state The room state whose RoomState.members dictionary\n * was updated.\n * @param {RoomMember} member The room member that was updated.\n * @example\n * matrixClient.on(\"RoomState.members\", function(event, state, member){\n * var newMembershipState = member.membership;\n * });\n */\n\n/**\n * Fires whenever a member is added to the members dictionary. The RoomMember\n * will not be fully populated yet (e.g. no membership state) but will already\n * be available in the members dictionary.\n * @event module:client~MatrixClient#\"RoomState.newMember\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {RoomState} state The room state whose RoomState.members dictionary\n * was updated with a new entry.\n * @param {RoomMember} member The room member that was added.\n * @example\n * matrixClient.on(\"RoomState.newMember\", function(event, state, member){\n * // add event listeners on 'member'\n * });\n */\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room-summary\n */\n\nexport interface IRoomSummary {\n \"m.heroes\": string[];\n \"m.joined_member_count\": number;\n \"m.invited_member_count\": number;\n}\n\ninterface IInfo {\n title: string;\n desc?: string;\n numMembers?: number;\n aliases?: string[];\n timestamp?: number;\n}\n\n/**\n * Construct a new Room Summary. A summary can be used for display on a recent\n * list, without having to load the entire room list into memory.\n * @constructor\n * @param {string} roomId Required. The ID of this room.\n * @param {Object} info Optional. The summary info. Additional keys are supported.\n * @param {string} info.title The title of the room (e.g. <code>m.room.name</code>)\n * @param {string} info.desc The description of the room (e.g.\n * <code>m.room.topic</code>)\n * @param {Number} info.numMembers The number of joined users.\n * @param {string[]} info.aliases The list of aliases for this room.\n * @param {Number} info.timestamp The timestamp for this room.\n */\nexport class RoomSummary {\n constructor(public readonly roomId: string, info?: IInfo) {}\n}\n\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/room\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { EventTimeline } from \"./event-timeline\";\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { normalize } from \"../utils\";\nimport { EventStatus, MatrixEvent } from \"./event\";\nimport { RoomMember } from \"./room-member\";\nimport { IRoomSummary, RoomSummary } from \"./room-summary\";\nimport { logger } from '../logger';\nimport { ReEmitter } from '../ReEmitter';\nimport { EventType, RoomCreateTypeField, RoomType } from \"../@types/event\";\nimport { IRoomVersionsCapability, MatrixClient, RoomVersionStability } from \"../client\";\nimport { ResizeMethod } from \"../@types/partials\";\nimport { Filter } from \"../filter\";\nimport { RoomState } from \"./room-state\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nconst KNOWN_SAFE_ROOM_VERSION = '6';\nconst SAFE_ROOM_VERSIONS = ['1', '2', '3', '4', '5', '6'];\n\nfunction synthesizeReceipt(userId: string, event: MatrixEvent, receiptType: string): MatrixEvent {\n // console.log(\"synthesizing receipt for \"+event.getId());\n // This is really ugly because JS has no way to express an object literal\n // where the name of a key comes from an expression\n const fakeReceipt = {\n content: {},\n type: \"m.receipt\",\n room_id: event.getRoomId(),\n };\n fakeReceipt.content[event.getId()] = {};\n fakeReceipt.content[event.getId()][receiptType] = {};\n fakeReceipt.content[event.getId()][receiptType][userId] = {\n ts: event.getTs(),\n };\n return new MatrixEvent(fakeReceipt);\n}\n\ninterface IOpts {\n storageToken?: string;\n pendingEventOrdering?: \"chronological\" | \"detached\";\n timelineSupport?: boolean;\n unstableClientRelationAggregation?: boolean;\n lazyLoadMembers?: boolean;\n}\n\nexport interface IRecommendedVersion {\n version: string;\n needsUpgrade: boolean;\n urgent: boolean;\n}\n\ninterface IReceipt {\n ts: number;\n}\n\ninterface IWrappedReceipt {\n eventId: string;\n data: IReceipt;\n}\n\ninterface ICachedReceipt {\n type: string;\n userId: string;\n data: IReceipt;\n}\n\ntype ReceiptCache = Record<string, ICachedReceipt[]>;\n\ninterface IReceiptContent {\n [eventId: string]: {\n [type: string]: {\n [userId: string]: IReceipt;\n };\n };\n}\n\ntype Receipts = Record<string, Record<string, IWrappedReceipt>>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport class Room extends EventEmitter {\n private readonly reEmitter: ReEmitter;\n private txnToEvent: Record<string, MatrixEvent> = {}; // Pending in-flight requests { string: MatrixEvent }\n // receipts should clobber based on receipt_type and user_id pairs hence\n // the form of this structure. This is sub-optimal for the exposed APIs\n // which pass in an event ID and get back some receipts, so we also store\n // a pre-cached list for this purpose.\n private receipts: Receipts = {}; // { receipt_type: { user_id: IReceipt } }\n private receiptCacheByEventId: ReceiptCache = {}; // { event_id: IReceipt2[] }\n // only receipts that came from the server, not synthesized ones\n private realReceipts: Receipts = {};\n private notificationCounts: Partial<Record<NotificationCountType, number>> = {};\n private readonly timelineSets: EventTimelineSet[];\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnverifiedDevices: boolean = null;\n private selfMembership: string = null;\n private summaryHeroes: string[] = null;\n // flags to stop logspam about missing m.room.create events\n private getTypeWarning = false;\n private getVersionWarning = false;\n private membersPromise?: Promise<boolean>;\n\n // XXX: These should be read-only\n public name: string;\n public normalizedName: string;\n public tags: Record<string, Record<string, any>> = {}; // $tagName: { $metadata: $value }\n public accountData: Record<string, MatrixEvent> = {}; // $eventType: $event\n public summary: RoomSummary = null;\n public readonly storageToken?: string;\n // legacy fields\n public timeline: MatrixEvent[];\n public oldState: RoomState;\n public currentState: RoomState;\n\n /**\n * Construct a new Room.\n *\n * <p>For a room, we store an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline. It also tracks\n * forward and backward pagination tokens, as well as containing links to the\n * next timeline in the sequence.\n *\n * <p>There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n * <p>In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @constructor\n * @alias module:models/room\n * @param {string} roomId Required. The ID of this room.\n * @param {MatrixClient} client Required. The client, used to lazy load members.\n * @param {string} myUserId Required. The ID of the syncing user.\n * @param {Object=} opts Configuration options\n * @param {*} opts.storageToken Optional. The token which a data store can use\n * to remember the state of the room. What this means is dependent on the store\n * implementation.\n *\n * @param {String=} opts.pendingEventOrdering Controls where pending messages\n * appear in a room's timeline. If \"<b>chronological</b>\", messages will appear\n * in the timeline when the call to <code>sendEvent</code> was made. If\n * \"<b>detached</b>\", pending messages will appear in a separate list,\n * accessible via {@link module:models/room#getPendingEvents}. Default:\n * \"chronological\".\n * @param {boolean} [opts.timelineSupport = false] Set to true to enable improved\n * timeline support.\n * @param {boolean} [opts.unstableClientRelationAggregation = false]\n * Optional. Set to true to enable client-side aggregation of event relations\n * via `EventTimelineSet#getRelationsForEvent`.\n * This feature is currently unstable and the API may change without notice.\n *\n * @prop {string} roomId The ID of this room.\n * @prop {string} name The human-readable display name for this room.\n * @prop {string} normalizedName The un-homoglyphed name for this room.\n * @prop {Array<MatrixEvent>} timeline The live event timeline for this room,\n * with the oldest event at index 0. Present for backwards compatibility -\n * prefer getLiveTimeline().getEvents().\n * @prop {object} tags Dict of room tags; the keys are the tag name and the values\n * are any metadata associated with the tag - e.g. { \"fav\" : { order: 1 } }\n * @prop {object} accountData Dict of per-room account_data events; the keys are the\n * event type and the values are the events.\n * @prop {RoomState} oldState The state of the room at the time of the oldest\n * event in the live timeline. Present for backwards compatibility -\n * prefer getLiveTimeline().getState(EventTimeline.BACKWARDS).\n * @prop {RoomState} currentState The state of the room at the time of the\n * newest event in the timeline. Present for backwards compatibility -\n * prefer getLiveTimeline().getState(EventTimeline.FORWARDS).\n * @prop {RoomSummary} summary The room summary.\n * @prop {*} storageToken A token which a data store can use to remember\n * the state of the room.\n */\n constructor(\n public readonly roomId: string,\n public readonly client: MatrixClient,\n public readonly myUserId: string,\n private readonly opts: IOpts = {},\n ) {\n super();\n // In some cases, we add listeners for every displayed Matrix event, so it's\n // common to have quite a few more than the default limit.\n this.setMaxListeners(100);\n this.reEmitter = new ReEmitter(this);\n\n opts.pendingEventOrdering = opts.pendingEventOrdering || \"chronological\";\n if ([\"chronological\", \"detached\"].indexOf(opts.pendingEventOrdering) === -1) {\n throw new Error(\n \"opts.pendingEventOrdering MUST be either 'chronological' or \" +\n \"'detached'. Got: '\" + opts.pendingEventOrdering + \"'\",\n );\n }\n\n this.name = roomId;\n\n // all our per-room timeline sets. the first one is the unfiltered ones;\n // the subsequent ones are the filtered ones in no particular order.\n this.timelineSets = [new EventTimelineSet(this, opts)];\n this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [\"Room.timeline\", \"Room.timelineReset\"]);\n\n this.fixUpLegacyTimelineFields();\n\n if (this.opts.pendingEventOrdering == \"detached\") {\n this.pendingEventList = [];\n const serializedPendingEventList = client.sessionStore.store.getItem(pendingEventsKey(this.roomId));\n if (serializedPendingEventList) {\n JSON.parse(serializedPendingEventList)\n .forEach(async serializedEvent => {\n const event = new MatrixEvent(serializedEvent);\n if (event.getType() === EventType.RoomMessageEncrypted) {\n await event.attemptDecryption(this.client.crypto);\n }\n event.setStatus(EventStatus.NOT_SENT);\n this.addPendingEvent(event, event.getTxnId());\n });\n }\n }\n\n // awaited by getEncryptionTargetMembers while room members are loading\n if (!this.opts.lazyLoadMembers) {\n this.membersPromise = Promise.resolve(false);\n } else {\n this.membersPromise = null;\n }\n }\n\n /**\n * Bulk decrypt critical events in a room\n *\n * Critical events represents the minimal set of events to decrypt\n * for a typical UI to function properly\n *\n * - Last event of every room (to generate likely message preview)\n * - All events up to the read receipt (to calculate an accurate notification count)\n *\n * @returns {Promise} Signals when all events have been decrypted\n */\n public decryptCriticalEvents(): Promise<void> {\n const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId(), true);\n const events = this.getLiveTimeline().getEvents();\n const readReceiptTimelineIndex = events.findIndex(matrixEvent => {\n return matrixEvent.event.event_id === readReceiptEventId;\n });\n\n const decryptionPromises = events\n .slice(readReceiptTimelineIndex)\n .filter(event => event.shouldAttemptDecryption())\n .reverse()\n .map(event => event.attemptDecryption(this.client.crypto, { isRetry: true }));\n\n return Promise.allSettled(decryptionPromises) as unknown as Promise<void>;\n }\n\n /**\n * Bulk decrypt events in a room\n *\n * @returns {Promise} Signals when all events have been decrypted\n */\n public decryptAllEvents(): Promise<void> {\n const decryptionPromises = this\n .getUnfilteredTimelineSet()\n .getLiveTimeline()\n .getEvents()\n .filter(event => event.shouldAttemptDecryption())\n .reverse()\n .map(event => event.attemptDecryption(this.client.crypto, { isRetry: true }));\n\n return Promise.allSettled(decryptionPromises) as unknown as Promise<void>;\n }\n\n /**\n * Gets the version of the room\n * @returns {string} The version of the room, or null if it could not be determined\n */\n public getVersion(): string | null {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getVersionWarning) {\n logger.warn(\"[getVersion] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getVersionWarning = true;\n }\n return '1';\n }\n const ver = createEvent.getContent()['room_version'];\n if (ver === undefined) return '1';\n return ver;\n }\n\n /**\n * Determines whether this room needs to be upgraded to a new version\n * @returns {string?} What version the room should be upgraded to, or null if\n * the room does not require upgrading at this time.\n * @deprecated Use #getRecommendedVersion() instead\n */\n public shouldUpgradeToVersion(): string | null {\n // TODO: Remove this function.\n // This makes assumptions about which versions are safe, and can easily\n // be wrong. Instead, people are encouraged to use getRecommendedVersion\n // which determines a safer value. This function doesn't use that function\n // because this is not async-capable, and to avoid breaking the contract\n // we're deprecating this.\n\n if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) {\n return KNOWN_SAFE_ROOM_VERSION;\n }\n\n return null;\n }\n\n /**\n * Determines the recommended room version for the room. This returns an\n * object with 3 properties: <code>version</code> as the new version the\n * room should be upgraded to (may be the same as the current version);\n * <code>needsUpgrade</code> to indicate if the room actually can be\n * upgraded (ie: does the current version not match?); and <code>urgent</code>\n * to indicate if the new version patches a vulnerability in a previous\n * version.\n * @returns {Promise<{version: string, needsUpgrade: boolean, urgent: boolean}>}\n * Resolves to the version the room should be upgraded to.\n */\n public async getRecommendedVersion(): Promise<IRecommendedVersion> {\n const capabilities = await this.client.getCapabilities();\n let versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n versionCap = {\n default: KNOWN_SAFE_ROOM_VERSION,\n available: {},\n };\n for (const safeVer of SAFE_ROOM_VERSIONS) {\n versionCap.available[safeVer] = RoomVersionStability.Stable;\n }\n }\n\n let result = this.checkVersionAgainstCapability(versionCap);\n if (result.urgent && result.needsUpgrade) {\n // Something doesn't feel right: we shouldn't need to update\n // because the version we're on should be in the protocol's\n // namespace. This usually means that the server was updated\n // before the client was, making us think the newest possible\n // room version is not stable. As a solution, we'll refresh\n // the capability we're using to determine this.\n logger.warn(\n \"Refreshing room version capability because the server looks \" +\n \"to be supporting a newer room version we don't know about.\",\n );\n\n const caps = await this.client.getCapabilities(true);\n versionCap = caps[\"m.room_versions\"];\n if (!versionCap) {\n logger.warn(\"No room version capability - assuming upgrade required.\");\n return result;\n } else {\n result = this.checkVersionAgainstCapability(versionCap);\n }\n }\n\n return result;\n }\n\n private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {\n const currentVersion = this.getVersion();\n logger.log(`[${this.roomId}] Current version: ${currentVersion}`);\n logger.log(`[${this.roomId}] Version capability: `, versionCap);\n\n const result = {\n version: currentVersion,\n needsUpgrade: false,\n urgent: false,\n };\n\n // If the room is on the default version then nothing needs to change\n if (currentVersion === versionCap.default) return result;\n\n const stableVersions = Object.keys(versionCap.available)\n .filter((v) => versionCap.available[v] === 'stable');\n\n // Check if the room is on an unstable version. We determine urgency based\n // off the version being in the Matrix spec namespace or not (if the version\n // is in the current namespace and unstable, the room is probably vulnerable).\n if (!stableVersions.includes(currentVersion)) {\n result.version = versionCap.default;\n result.needsUpgrade = true;\n result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);\n if (result.urgent) {\n logger.warn(`URGENT upgrade required on ${this.roomId}`);\n } else {\n logger.warn(`Non-urgent upgrade required on ${this.roomId}`);\n }\n return result;\n }\n\n // The room is on a stable, but non-default, version by this point.\n // No upgrade needed.\n return result;\n }\n\n /**\n * Determines whether the given user is permitted to perform a room upgrade\n * @param {String} userId The ID of the user to test against\n * @returns {boolean} True if the given user is permitted to upgrade the room\n */\n public userMayUpgradeRoom(userId: string): boolean {\n return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);\n }\n\n /**\n * Get the list of pending sent events for this room\n *\n * @return {module:models/event.MatrixEvent[]} A list of the sent events\n * waiting for remote echo.\n *\n * @throws If <code>opts.pendingEventOrdering</code> was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (this.opts.pendingEventOrdering !== \"detached\") {\n throw new Error(\n \"Cannot call getPendingEvents with pendingEventOrdering == \" +\n this.opts.pendingEventOrdering);\n }\n\n return this.pendingEventList;\n }\n\n /**\n * Removes a pending event for this room\n *\n * @param {string} eventId\n * @return {boolean} True if an element was removed.\n */\n public removePendingEvent(eventId: string): boolean {\n if (this.opts.pendingEventOrdering !== \"detached\") {\n throw new Error(\n \"Cannot call removePendingEvent with pendingEventOrdering == \" +\n this.opts.pendingEventOrdering);\n }\n\n const removed = utils.removeElement(\n this.pendingEventList,\n function(ev) {\n return ev.getId() == eventId;\n }, false,\n );\n\n this.savePendingEvents();\n\n return removed;\n }\n\n /**\n * Check whether the pending event list contains a given event by ID.\n * If pending event ordering is not \"detached\" then this returns false.\n *\n * @param {string} eventId The event ID to check for.\n * @return {boolean}\n */\n public hasPendingEvent(eventId: string): boolean {\n if (this.opts.pendingEventOrdering !== \"detached\") {\n return false;\n }\n\n return this.pendingEventList.some(event => event.getId() === eventId);\n }\n\n /**\n * Get a specific event from the pending event list, if configured, null otherwise.\n *\n * @param {string} eventId The event ID to check for.\n * @return {MatrixEvent}\n */\n public getPendingEvent(eventId: string): MatrixEvent | null {\n if (this.opts.pendingEventOrdering !== \"detached\") {\n return null;\n }\n\n return this.pendingEventList.find(event => event.getId() === eventId);\n }\n\n /**\n * Get the live unfiltered timeline for this room.\n *\n * @return {module:models/event-timeline~EventTimeline} live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().getLiveTimeline();\n }\n\n /**\n * Get the timestamp of the last message in the room\n *\n * @return {number} the timestamp of the last message in the room\n */\n public getLastActiveTimestamp(): number {\n const timeline = this.getLiveTimeline();\n const events = timeline.getEvents();\n if (events.length) {\n const lastEvent = events[events.length - 1];\n return lastEvent.getTs();\n } else {\n return Number.MIN_SAFE_INTEGER;\n }\n }\n\n /**\n * @return {string} the membership type (join | leave | invite) for the logged in user\n */\n public getMyMembership(): string {\n return this.selfMembership;\n }\n\n /**\n * If this room is a DM we're invited to,\n * try to find out who invited us\n * @return {string} user id of the inviter\n */\n public getDMInviter(): string {\n if (this.myUserId) {\n const me = this.getMember(this.myUserId);\n if (me) {\n return me.getDMInviter();\n }\n }\n if (this.selfMembership === \"invite\") {\n // fall back to summary information\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount == 2 && this.summaryHeroes.length) {\n return this.summaryHeroes[0];\n }\n }\n }\n\n /**\n * Assuming this room is a DM room, tries to guess with which user.\n * @return {string} user id of the other member (could be syncing user)\n */\n public guessDMUserId(): string {\n const me = this.getMember(this.myUserId);\n if (me) {\n const inviterId = me.getDMInviter();\n if (inviterId) {\n return inviterId;\n }\n }\n // remember, we're assuming this room is a DM,\n // so returning the first member we find should be fine\n const hasHeroes = Array.isArray(this.summaryHeroes) &&\n this.summaryHeroes.length;\n if (hasHeroes) {\n return this.summaryHeroes[0];\n }\n const members = this.currentState.getMembers();\n const anyMember = members.find((m) => m.userId !== this.myUserId);\n if (anyMember) {\n return anyMember.userId;\n }\n // it really seems like I'm the only user in the room\n // so I probably created a room with just me in it\n // and marked it as a DM. Ok then\n return this.myUserId;\n }\n\n public getAvatarFallbackMember(): RoomMember {\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount > 2) {\n return;\n }\n const hasHeroes = Array.isArray(this.summaryHeroes) &&\n this.summaryHeroes.length;\n if (hasHeroes) {\n const availableMember = this.summaryHeroes.map((userId) => {\n return this.getMember(userId);\n }).find((member) => !!member);\n if (availableMember) {\n return availableMember;\n }\n }\n const members = this.currentState.getMembers();\n // could be different than memberCount\n // as this includes left members\n if (members.length <= 2) {\n const availableMember = members.find((m) => {\n return m.userId !== this.myUserId;\n });\n if (availableMember) {\n return availableMember;\n }\n }\n // if all else fails, try falling back to a user,\n // and create a one-off member for it\n if (hasHeroes) {\n const availableUser = this.summaryHeroes.map((userId) => {\n return this.client.getUser(userId);\n }).find((user) => !!user);\n if (availableUser) {\n const member = new RoomMember(\n this.roomId, availableUser.userId);\n member.user = availableUser;\n return member;\n }\n }\n }\n\n /**\n * Sets the membership this room was received as during sync\n * @param {string} membership join | leave | invite\n */\n public updateMyMembership(membership: string): void {\n const prevMembership = this.selfMembership;\n this.selfMembership = membership;\n if (prevMembership !== membership) {\n if (membership === \"leave\") {\n this.cleanupAfterLeaving();\n }\n this.emit(\"Room.myMembership\", this, membership, prevMembership);\n }\n }\n\n private async loadMembersFromServer(): Promise<object[]> {\n const lastSyncToken = this.client.store.getSyncToken();\n const queryString = utils.encodeParams({\n not_membership: \"leave\",\n at: lastSyncToken,\n });\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString,\n { $roomId: this.roomId });\n const http = this.client.http;\n const response = await http.authedRequest(undefined, \"GET\", path);\n return response.chunk;\n }\n\n private async loadMembers(): Promise<{ memberEvents: MatrixEvent[], fromServer: boolean }> {\n // were the members loaded from the server?\n let fromServer = false;\n let rawMembersEvents =\n await this.client.store.getOutOfBandMembers(this.roomId);\n if (rawMembersEvents === null) {\n fromServer = true;\n rawMembersEvents = await this.loadMembersFromServer();\n logger.log(`LL: got ${rawMembersEvents.length} ` +\n `members from server for room ${this.roomId}`);\n }\n const memberEvents = rawMembersEvents.map(this.client.getEventMapper());\n return { memberEvents, fromServer };\n }\n\n /**\n * Preloads the member list in case lazy loading\n * of memberships is in use. Can be called multiple times,\n * it will only preload once.\n * @return {Promise} when preloading is done and\n * accessing the members on the room will take\n * all members in the room into account\n */\n public loadMembersIfNeeded(): Promise<boolean> {\n if (this.membersPromise) {\n return this.membersPromise;\n }\n\n // mark the state so that incoming messages while\n // the request is in flight get marked as superseding\n // the OOB members\n this.currentState.markOutOfBandMembersStarted();\n\n const inMemoryUpdate = this.loadMembers().then((result) => {\n this.currentState.setOutOfBandMembers(result.memberEvents);\n // now the members are loaded, start to track the e2e devices if needed\n if (this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId)) {\n this.client.crypto.trackRoomDevices(this.roomId);\n }\n return result.fromServer;\n }).catch((err) => {\n // allow retries on fail\n this.membersPromise = null;\n this.currentState.markOutOfBandMembersFailed();\n throw err;\n });\n // update members in storage, but don't wait for it\n inMemoryUpdate.then((fromServer) => {\n if (fromServer) {\n const oobMembers = this.currentState.getMembers()\n .filter((m) => m.isOutOfBand())\n .map((m) => m.events.member.event);\n logger.log(`LL: telling store to write ${oobMembers.length}`\n + ` members for room ${this.roomId}`);\n const store = this.client.store;\n return store.setOutOfBandMembers(this.roomId, oobMembers)\n // swallow any IDB error as we don't want to fail\n // because of this\n .catch((err) => {\n logger.log(\"LL: storing OOB room members failed, oh well\",\n err);\n });\n }\n }).catch((err) => {\n // as this is not awaited anywhere,\n // at least show the error in the console\n logger.error(err);\n });\n\n this.membersPromise = inMemoryUpdate;\n\n return this.membersPromise;\n }\n\n /**\n * Removes the lazily loaded members from storage if needed\n */\n public async clearLoadedMembersIfNeeded(): Promise<void> {\n if (this.opts.lazyLoadMembers && this.membersPromise) {\n await this.loadMembersIfNeeded();\n await this.client.store.clearOutOfBandMembers(this.roomId);\n this.currentState.clearOutOfBandMembers();\n this.membersPromise = null;\n }\n }\n\n /**\n * called when sync receives this room in the leave section\n * to do cleanup after leaving a room. Possibly called multiple times.\n */\n private cleanupAfterLeaving(): void {\n this.clearLoadedMembersIfNeeded().catch((err) => {\n logger.error(`error after clearing loaded members from ` +\n `room ${this.roomId} after leaving`);\n logger.log(err);\n });\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline.\n *\n * @param {string=} backPaginationToken token for back-paginating the new timeline\n * @param {string=} forwardPaginationToken token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public resetLiveTimeline(backPaginationToken: string, forwardPaginationToken: string): void {\n for (let i = 0; i < this.timelineSets.length; i++) {\n this.timelineSets[i].resetLiveTimeline(\n backPaginationToken, forwardPaginationToken,\n );\n }\n\n this.fixUpLegacyTimelineFields();\n }\n\n /**\n * Fix up this.timeline, this.oldState and this.currentState\n *\n * @private\n */\n private fixUpLegacyTimelineFields(): void {\n // maintain this.timeline as a reference to the live timeline,\n // and this.oldState and this.currentState as references to the\n // state at the start and end of that timeline. These are more\n // for backwards-compatibility than anything else.\n this.timeline = this.getLiveTimeline().getEvents();\n this.oldState = this.getLiveTimeline()\n .getState(EventTimeline.BACKWARDS);\n this.currentState = this.getLiveTimeline()\n .getState(EventTimeline.FORWARDS);\n }\n\n /**\n * Returns whether there are any devices in the room that are unverified\n *\n * Note: Callers should first check if crypto is enabled on this device. If it is\n * disabled, then we aren't tracking room devices at all, so we can't answer this, and an\n * error will be thrown.\n *\n * @return {boolean} the result\n */\n public async hasUnverifiedDevices(): Promise<boolean> {\n if (!this.client.isRoomEncrypted(this.roomId)) {\n return false;\n }\n const e2eMembers = await this.getEncryptionTargetMembers();\n for (const member of e2eMembers) {\n const devices = this.client.getStoredDevicesForUser(member.userId);\n if (devices.some((device) => device.isUnverified())) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the timeline sets for this room.\n * @return {EventTimelineSet[]} array of timeline sets for this room\n */\n public getTimelineSets(): EventTimelineSet[] {\n return this.timelineSets;\n }\n\n /**\n * Helper to return the main unfiltered timeline set for this room\n * @return {EventTimelineSet} room's unfiltered timeline set\n */\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSets[0];\n }\n\n /**\n * Get the timeline which contains the given event from the unfiltered set, if any\n *\n * @param {string} eventId event ID to look for\n * @return {?module:models/event-timeline~EventTimeline} timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId: string): EventTimeline {\n return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);\n }\n\n /**\n * Add a new timeline to this room's unfiltered timeline set\n *\n * @return {module:models/event-timeline~EventTimeline} newly-created timeline\n */\n public addTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().addTimeline();\n }\n\n /**\n * Get an event which is stored in our unfiltered timeline set\n *\n * @param {string} eventId event ID to look for\n * @return {?module:models/event.MatrixEvent} the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n return this.getUnfilteredTimelineSet().findEventById(eventId);\n }\n\n /**\n * Get one of the notification counts for this room\n * @param {String} type The type of notification count to get. default: 'total'\n * @return {Number} The notification count, or undefined if there is no count\n * for this type.\n */\n public getUnreadNotificationCount(type = NotificationCountType.Total): number | undefined {\n return this.notificationCounts[type];\n }\n\n /**\n * Set one of the notification counts for this room\n * @param {String} type The type of notification count to set.\n * @param {Number} count The new count\n */\n public setUnreadNotificationCount(type: NotificationCountType, count: number): void {\n this.notificationCounts[type] = count;\n }\n\n public setSummary(summary: IRoomSummary): void {\n const heroes = summary[\"m.heroes\"];\n const joinedCount = summary[\"m.joined_member_count\"];\n const invitedCount = summary[\"m.invited_member_count\"];\n if (Number.isInteger(joinedCount)) {\n this.currentState.setJoinedMemberCount(joinedCount);\n }\n if (Number.isInteger(invitedCount)) {\n this.currentState.setInvitedMemberCount(invitedCount);\n }\n if (Array.isArray(heroes)) {\n // be cautious about trusting server values,\n // and make sure heroes doesn't contain our own id\n // just to be sure\n this.summaryHeroes = heroes.filter((userId) => {\n return userId !== this.myUserId;\n });\n }\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @param {Boolean} value true to blacklist unverified devices, null\n * to use the global value for this room.\n */\n public setBlacklistUnverifiedDevices(value: boolean): void {\n this.blacklistUnverifiedDevices = value;\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @return {Boolean} true if blacklisting unverified devices, null\n * if the global value should be used for this room.\n */\n public getBlacklistUnverifiedDevices(): boolean {\n return this.blacklistUnverifiedDevices;\n }\n\n /**\n * Get the avatar URL for a room if one was set.\n * @param {String} baseUrl The homeserver base URL. See\n * {@link module:client~MatrixClient#getHomeserverUrl}.\n * @param {Number} width The desired width of the thumbnail.\n * @param {Number} height The desired height of the thumbnail.\n * @param {string} resizeMethod The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param {boolean} allowDefault True to allow an identicon for this room if an\n * avatar URL wasn't explicitly set. Default: true. (Deprecated)\n * @return {?string} the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: ResizeMethod,\n allowDefault = true,\n ): string | null {\n const roomAvatarEvent = this.currentState.getStateEvents(EventType.RoomAvatar, \"\");\n if (!roomAvatarEvent && !allowDefault) {\n return null;\n }\n\n const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;\n if (mainUrl) {\n return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod);\n }\n\n return null;\n }\n\n /**\n * Get the mxc avatar url for the room, if one was set.\n * @return {string} the mxc avatar url or falsy\n */\n public getMxcAvatarUrl(): string | null {\n return this.currentState.getStateEvents(EventType.RoomAvatar, \"\")?.getContent()?.url || null;\n }\n\n /**\n * Get the aliases this room has according to the room's state\n * The aliases returned by this function may not necessarily\n * still point to this room.\n * @return {array} The room's alias as an array of strings\n */\n public getAliases(): string[] {\n const aliasStrings = [];\n\n const aliasEvents = this.currentState.getStateEvents(EventType.RoomAliases);\n if (aliasEvents) {\n for (let i = 0; i < aliasEvents.length; ++i) {\n const aliasEvent = aliasEvents[i];\n if (Array.isArray(aliasEvent.getContent().aliases)) {\n const filteredAliases = aliasEvent.getContent().aliases.filter(a => {\n if (typeof(a) !== \"string\") return false;\n if (a[0] !== '#') return false;\n if (!a.endsWith(`:${aliasEvent.getStateKey()}`)) return false;\n\n // It's probably valid by here.\n return true;\n });\n Array.prototype.push.apply(aliasStrings, filteredAliases);\n }\n }\n }\n return aliasStrings;\n }\n\n /**\n * Get this room's canonical alias\n * The alias returned by this function may not necessarily\n * still point to this room.\n * @return {?string} The room's canonical alias, or null if there is none\n */\n public getCanonicalAlias(): string | null {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alias || null;\n }\n return null;\n }\n\n /**\n * Get this room's alternative aliases\n * @return {array} The room's alternative aliases, or an empty array\n */\n public getAltAliases(): string[] {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alt_aliases || [];\n }\n return [];\n }\n\n /**\n * Add events to a timeline\n *\n * <p>Will fire \"Room.timeline\" for each event added.\n *\n * @param {MatrixEvent[]} events A list of events to add.\n *\n * @param {boolean} toStartOfTimeline True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the <b>last</b> element of 'events'.\n *\n * @param {module:models/event-timeline~EventTimeline} timeline timeline to\n * add events to.\n *\n * @param {string=} paginationToken token for the next batch of events\n *\n * @fires module:client~MatrixClient#event:\"Room.timeline\"\n *\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken?: string,\n ): void {\n timeline.getTimelineSet().addEventsToTimeline(\n events, toStartOfTimeline,\n timeline, paginationToken,\n );\n }\n\n /**\n * Get a member from the current room state.\n * @param {string} userId The user ID of the member.\n * @return {RoomMember} The member or <code>null</code>.\n */\n public getMember(userId: string): RoomMember | null {\n return this.currentState.getMember(userId);\n }\n\n /**\n * Get all currently loaded members from the current\n * room state.\n * @returns {RoomMember[]} Room members\n */\n public getMembers(): RoomMember[] {\n return this.currentState.getMembers();\n }\n\n /**\n * Get a list of members whose membership state is \"join\".\n * @return {RoomMember[]} A list of currently joined members.\n */\n public getJoinedMembers(): RoomMember[] {\n return this.getMembersWithMembership(\"join\");\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * This is a wrapper around the method of the same name in roomState, returning\n * its result for the room's current state.\n * @return {number} The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n return this.currentState.getJoinedMemberCount();\n }\n\n /**\n * Returns the number of invited members in this room\n * @return {number} The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n return this.currentState.getInvitedMemberCount();\n }\n\n /**\n * Returns the number of invited + joined members in this room\n * @return {number} The number of members in this room whose membership is 'invite' or 'join'\n */\n public getInvitedAndJoinedMemberCount(): number {\n return this.getInvitedMemberCount() + this.getJoinedMemberCount();\n }\n\n /**\n * Get a list of members with given membership state.\n * @param {string} membership The membership state.\n * @return {RoomMember[]} A list of members with the given membership state.\n */\n public getMembersWithMembership(membership: string): RoomMember[] {\n return this.currentState.getMembers().filter(function(m) {\n return m.membership === membership;\n });\n }\n\n /**\n * Get a list of members we should be encrypting for in this room\n * @return {Promise<RoomMember[]>} A list of members who\n * we should encrypt messages for in this room.\n */\n public async getEncryptionTargetMembers(): Promise<RoomMember[]> {\n await this.loadMembersIfNeeded();\n let members = this.getMembersWithMembership(\"join\");\n if (this.shouldEncryptForInvitedMembers()) {\n members = members.concat(this.getMembersWithMembership(\"invite\"));\n }\n return members;\n }\n\n /**\n * Determine whether we should encrypt messages for invited users in this room\n * @return {boolean} if we should encrypt messages for invited users\n */\n public shouldEncryptForInvitedMembers(): boolean {\n const ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n return ev?.getContent()?.history_visibility !== \"joined\";\n }\n\n /**\n * Get the default room name (i.e. what a given user would see if the\n * room had no m.room.name)\n * @param {string} userId The userId from whose perspective we want\n * to calculate the default name\n * @return {string} The default room name\n */\n public getDefaultRoomName(userId: string): string {\n return this.calculateRoomName(userId, true);\n }\n\n /**\n * Check if the given user_id has the given membership state.\n * @param {string} userId The user ID to check.\n * @param {string} membership The membership e.g. <code>'join'</code>\n * @return {boolean} True if this user_id has the given membership state.\n */\n public hasMembershipState(userId: string, membership: string): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n return member.membership === membership;\n }\n\n /**\n * Add a timelineSet for this room with the given filter\n * @param {Filter} filter The filter to be applied to this timelineSet\n * @return {EventTimelineSet} The timelineSet\n */\n public getOrCreateFilteredTimelineSet(filter: Filter): EventTimelineSet {\n if (this.filteredTimelineSets[filter.filterId]) {\n return this.filteredTimelineSets[filter.filterId];\n }\n const opts = Object.assign({ filter: filter }, this.opts);\n const timelineSet = new EventTimelineSet(this, opts);\n this.reEmitter.reEmit(timelineSet, [\"Room.timeline\", \"Room.timelineReset\"]);\n this.filteredTimelineSets[filter.filterId] = timelineSet;\n this.timelineSets.push(timelineSet);\n\n // populate up the new timelineSet with filtered events from our live\n // unfiltered timeline.\n //\n // XXX: This is risky as our timeline\n // may have grown huge and so take a long time to filter.\n // see https://github.com/vector-im/vector-web/issues/2109\n\n const unfilteredLiveTimeline = this.getLiveTimeline();\n\n unfilteredLiveTimeline.getEvents().forEach(function(event) {\n timelineSet.addLiveEvent(event);\n });\n\n // find the earliest unfiltered timeline\n let timeline = unfilteredLiveTimeline;\n while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS);\n }\n\n timelineSet.getLiveTimeline().setPaginationToken(\n timeline.getPaginationToken(EventTimeline.BACKWARDS),\n EventTimeline.BACKWARDS,\n );\n\n // alternatively, we could try to do something like this to try and re-paginate\n // in the filtered events from nothing, but Mark says it's an abuse of the API\n // to do so:\n //\n // timelineSet.resetLiveTimeline(\n // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)\n // );\n\n return timelineSet;\n }\n\n /**\n * Forget the timelineSet for this room with the given filter\n *\n * @param {Filter} filter the filter whose timelineSet is to be forgotten\n */\n public removeFilteredTimelineSet(filter: Filter): void {\n const timelineSet = this.filteredTimelineSets[filter.filterId];\n delete this.filteredTimelineSets[filter.filterId];\n const i = this.timelineSets.indexOf(timelineSet);\n if (i > -1) {\n this.timelineSets.splice(i, 1);\n }\n }\n\n /**\n * Add an event to the end of this room's live timelines. Will fire\n * \"Room.timeline\".\n *\n * @param {MatrixEvent} event Event to be added\n * @param {string?} duplicateStrategy 'ignore' or 'replace'\n * @param {boolean} fromCache whether the sync response came from cache\n * @fires module:client~MatrixClient#event:\"Room.timeline\"\n * @private\n */\n private addLiveEvent(event: MatrixEvent, duplicateStrategy?: \"ignore\" | \"replace\", fromCache = false): void {\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n\n // if we know about this event, redact its contents now.\n const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n if (redactedEvent) {\n redactedEvent.makeRedacted(event);\n\n // If this is in the current state, replace it with the redacted version\n if (redactedEvent.getStateKey()) {\n const currentStateEvent = this.currentState.getStateEvents(\n redactedEvent.getType(),\n redactedEvent.getStateKey(),\n );\n if (currentStateEvent.getId() === redactedEvent.getId()) {\n this.currentState.setStateEvents([redactedEvent]);\n }\n }\n\n this.emit(\"Room.redaction\", event, this);\n\n // TODO: we stash user displaynames (among other things) in\n // RoomMember objects which are then attached to other events\n // (in the sender and target fields). We should get those\n // RoomMember objects to update themselves when the events that\n // they are based on are changed.\n }\n\n // FIXME: apply redactions to notification list\n\n // NB: We continue to add the redaction event to the timeline so\n // clients can say \"so and so redacted an event\" if they wish to. Also\n // this may be needed to trigger an update.\n }\n\n if (event.getUnsigned().transaction_id) {\n const existingEvent = this.txnToEvent[event.getUnsigned().transaction_id];\n if (existingEvent) {\n // remote echo of an event we sent earlier\n this.handleRemoteEcho(event, existingEvent);\n return;\n }\n }\n\n // add to our timeline sets\n for (let i = 0; i < this.timelineSets.length; i++) {\n this.timelineSets[i].addLiveEvent(event, duplicateStrategy, fromCache);\n }\n\n // synthesize and inject implicit read receipts\n // Done after adding the event because otherwise the app would get a read receipt\n // pointing to an event that wasn't yet in the timeline\n // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.\n if (event.sender && event.getType() !== EventType.RoomRedaction) {\n this.addReceipt(synthesizeReceipt(\n event.sender.userId, event, \"m.read\",\n ), true);\n\n // Any live events from a user could be taken as implicit\n // presence information: evidence that they are currently active.\n // ...except in a world where we use 'user.currentlyActive' to reduce\n // presence spam, this isn't very useful - we'll get a transition when\n // they are no longer currently active anyway. So don't bother to\n // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.\n }\n }\n\n /**\n * Add a pending outgoing event to this room.\n *\n * <p>The event is added to either the pendingEventList, or the live timeline,\n * depending on the setting of opts.pendingEventOrdering.\n *\n * <p>This is an internal method, intended for use by MatrixClient.\n *\n * @param {module:models/event.MatrixEvent} event The event to add.\n *\n * @param {string} txnId Transaction id for this outgoing event\n *\n * @fires module:client~MatrixClient#event:\"Room.localEchoUpdated\"\n *\n * @throws if the event doesn't have status SENDING, or we aren't given a\n * unique transaction id.\n */\n public addPendingEvent(event: MatrixEvent, txnId: string): void {\n if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {\n throw new Error(\"addPendingEvent called on an event with status \" +\n event.status);\n }\n\n if (this.txnToEvent[txnId]) {\n throw new Error(\"addPendingEvent called on an event with known txnId \" +\n txnId);\n }\n\n // call setEventMetadata to set up event.sender etc\n // as event is shared over all timelineSets, we set up its metadata based\n // on the unfiltered timelineSet.\n EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS), false);\n\n this.txnToEvent[txnId] = event;\n\n if (this.opts.pendingEventOrdering == \"detached\") {\n if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {\n logger.warn(\"Setting event as NOT_SENT due to messages in the same state\");\n event.setStatus(EventStatus.NOT_SENT);\n }\n this.pendingEventList.push(event);\n this.savePendingEvents();\n if (event.isRelation()) {\n // For pending events, add them to the relations collection immediately.\n // (The alternate case below already covers this as part of adding to\n // the timeline set.)\n this.aggregateNonLiveRelation(event);\n }\n\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n let redactedEvent = this.pendingEventList &&\n this.pendingEventList.find(e => e.getId() === redactId);\n if (!redactedEvent) {\n redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n }\n if (redactedEvent) {\n redactedEvent.markLocallyRedacted(event);\n this.emit(\"Room.redaction\", event, this);\n }\n }\n } else {\n for (let i = 0; i < this.timelineSets.length; i++) {\n const timelineSet = this.timelineSets[i];\n if (timelineSet.getFilter()) {\n if (timelineSet.getFilter().filterRoomTimeline([event]).length) {\n timelineSet.addEventToTimeline(event,\n timelineSet.getLiveTimeline(), false);\n }\n } else {\n timelineSet.addEventToTimeline(event,\n timelineSet.getLiveTimeline(), false);\n }\n }\n }\n\n this.emit(\"Room.localEchoUpdated\", event, this, null, null);\n }\n\n /**\n * Persists all pending events to local storage\n *\n * If the current room is encrypted only encrypted events will be persisted\n * all messages that are not yet encrypted will be discarded\n *\n * This is because the flow of EVENT_STATUS transition is\n * queued => sending => encrypting => sending => sent\n *\n * Steps 3 and 4 are skipped for unencrypted room.\n * It is better to discard an unencrypted message rather than persisting\n * it locally for everyone to read\n */\n private savePendingEvents(): void {\n if (this.pendingEventList) {\n const pendingEvents = this.pendingEventList.map(event => {\n return {\n ...event.event,\n txn_id: event.getTxnId(),\n };\n }).filter(event => {\n // Filter out the unencrypted messages if the room is encrypted\n const isEventEncrypted = event.type === EventType.RoomMessageEncrypted;\n const isRoomEncrypted = this.client.isRoomEncrypted(this.roomId);\n return isEventEncrypted || !isRoomEncrypted;\n });\n\n const { store } = this.client.sessionStore;\n if (this.pendingEventList.length > 0) {\n store.setItem(\n pendingEventsKey(this.roomId),\n JSON.stringify(pendingEvents),\n );\n } else {\n store.removeItem(pendingEventsKey(this.roomId));\n }\n }\n }\n\n /**\n * Used to aggregate the local echo for a relation, and also\n * for re-applying a relation after it's redaction has been cancelled,\n * as the local echo for the redaction of the relation would have\n * un-aggregated the relation. Note that this is different from regular messages,\n * which are just kept detached for their local echo.\n *\n * Also note that live events are aggregated in the live EventTimelineSet.\n * @param {module:models/event.MatrixEvent} event the relation event that needs to be aggregated.\n */\n private aggregateNonLiveRelation(event: MatrixEvent): void {\n // TODO: We should consider whether this means it would be a better\n // design to lift the relations handling up to the room instead.\n for (let i = 0; i < this.timelineSets.length; i++) {\n const timelineSet = this.timelineSets[i];\n if (timelineSet.getFilter()) {\n if (timelineSet.getFilter().filterRoomTimeline([event]).length) {\n timelineSet.aggregateRelations(event);\n }\n } else {\n timelineSet.aggregateRelations(event);\n }\n }\n }\n\n /**\n * Deal with the echo of a message we sent.\n *\n * <p>We move the event to the live timeline if it isn't there already, and\n * update it.\n *\n * @param {module:models/event.MatrixEvent} remoteEvent The event received from\n * /sync\n * @param {module:models/event.MatrixEvent} localEvent The local echo, which\n * should be either in the pendingEventList or the timeline.\n *\n * @fires module:client~MatrixClient#event:\"Room.localEchoUpdated\"\n * @private\n */\n private handleRemoteEcho(remoteEvent: MatrixEvent, localEvent: MatrixEvent): void {\n const oldEventId = localEvent.getId();\n const newEventId = remoteEvent.getId();\n const oldStatus = localEvent.status;\n\n logger.debug(\n `Got remote echo for event ${oldEventId} -> ${newEventId} ` +\n `old status ${oldStatus}`,\n );\n\n // no longer pending\n delete this.txnToEvent[remoteEvent.getUnsigned().transaction_id];\n\n // if it's in the pending list, remove it\n if (this.pendingEventList) {\n this.removePendingEvent(oldEventId);\n }\n\n // replace the event source (this will preserve the plaintext payload if\n // any, which is good, because we don't want to try decoding it again).\n localEvent.handleRemoteEcho(remoteEvent.event);\n\n for (let i = 0; i < this.timelineSets.length; i++) {\n const timelineSet = this.timelineSets[i];\n\n // if it's already in the timeline, update the timeline map. If it's not, add it.\n timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n }\n\n this.emit(\"Room.localEchoUpdated\", localEvent, this,\n oldEventId, oldStatus);\n }\n\n /**\n * Update the status / event id on a pending event, to reflect its transmission\n * progress.\n *\n * <p>This is an internal method.\n *\n * @param {MatrixEvent} event local echo event\n * @param {EventStatus} newStatus status to assign\n * @param {string} newEventId new event id to assign. Ignored unless\n * newStatus == EventStatus.SENT.\n * @fires module:client~MatrixClient#event:\"Room.localEchoUpdated\"\n */\n public updatePendingEvent(event: MatrixEvent, newStatus: EventStatus, newEventId?: string): void {\n logger.log(\n `setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +\n `event ID ${event.getId()} -> ${newEventId}`,\n );\n\n // if the message was sent, we expect an event id\n if (newStatus == EventStatus.SENT && !newEventId) {\n throw new Error(\"updatePendingEvent called with status=SENT, \" +\n \"but no new event id\");\n }\n\n // SENT races against /sync, so we have to special-case it.\n if (newStatus == EventStatus.SENT) {\n const timeline = this.getUnfilteredTimelineSet().eventIdToTimeline(newEventId);\n if (timeline) {\n // we've already received the event via the event stream.\n // nothing more to do here.\n return;\n }\n }\n\n const oldStatus = event.status;\n const oldEventId = event.getId();\n\n if (!oldStatus) {\n throw new Error(\"updatePendingEventStatus called on an event which is \" +\n \"not a local echo.\");\n }\n\n const allowed = ALLOWED_TRANSITIONS[oldStatus];\n if (!allowed || allowed.indexOf(newStatus) < 0) {\n throw new Error(\"Invalid EventStatus transition \" + oldStatus + \"->\" +\n newStatus);\n }\n\n event.setStatus(newStatus);\n\n if (newStatus == EventStatus.SENT) {\n // update the event id\n event.replaceLocalEventId(newEventId);\n\n // if the event was already in the timeline (which will be the case if\n // opts.pendingEventOrdering==chronological), we need to update the\n // timeline map.\n for (let i = 0; i < this.timelineSets.length; i++) {\n this.timelineSets[i].replaceEventId(oldEventId, newEventId);\n }\n } else if (newStatus == EventStatus.CANCELLED) {\n // remove it from the pending event list, or the timeline.\n if (this.pendingEventList) {\n const idx = this.pendingEventList.findIndex(ev => ev.getId() === oldEventId);\n if (idx !== -1) {\n const [removedEvent] = this.pendingEventList.splice(idx, 1);\n if (removedEvent.isRedaction()) {\n this.revertRedactionLocalEcho(removedEvent);\n }\n }\n }\n this.removeEvent(oldEventId);\n }\n this.savePendingEvents();\n\n this.emit(\"Room.localEchoUpdated\", event, this, oldEventId, oldStatus);\n }\n\n private revertRedactionLocalEcho(redactionEvent: MatrixEvent): void {\n const redactId = redactionEvent.event.redacts;\n if (!redactId) {\n return;\n }\n const redactedEvent = this.getUnfilteredTimelineSet()\n .findEventById(redactId);\n if (redactedEvent) {\n redactedEvent.unmarkLocallyRedacted();\n // re-render after undoing redaction\n this.emit(\"Room.redactionCancelled\", redactionEvent, this);\n // reapply relation now redaction failed\n if (redactedEvent.isRelation()) {\n this.aggregateNonLiveRelation(redactedEvent);\n }\n }\n }\n\n /**\n * Add some events to this room. This can include state events, message\n * events and typing notifications. These events are treated as \"live\" so\n * they will go to the end of the timeline.\n *\n * @param {MatrixEvent[]} events A list of events to add.\n *\n * @param {string} duplicateStrategy Optional. Applies to events in the\n * timeline only. If this is 'replace' then if a duplicate is encountered, the\n * event passed to this function will replace the existing event in the\n * timeline. If this is not specified, or is 'ignore', then the event passed to\n * this function will be ignored entirely, preserving the existing event in the\n * timeline. Events are identical based on their event ID <b>only</b>.\n *\n * @param {boolean} fromCache whether the sync response came from cache\n * @throws If <code>duplicateStrategy</code> is not falsey, 'replace' or 'ignore'.\n */\n public addLiveEvents(events: MatrixEvent[], duplicateStrategy?: \"replace\" | \"ignore\", fromCache = false): void {\n let i;\n if (duplicateStrategy && [\"replace\", \"ignore\"].indexOf(duplicateStrategy) === -1) {\n throw new Error(\"duplicateStrategy MUST be either 'replace' or 'ignore'\");\n }\n\n // sanity check that the live timeline is still live\n for (i = 0; i < this.timelineSets.length; i++) {\n const liveTimeline = this.timelineSets[i].getLiveTimeline();\n if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {\n throw new Error(\n \"live timeline \" + i + \" is no longer live - it has a pagination token \" +\n \"(\" + liveTimeline.getPaginationToken(EventTimeline.FORWARDS) + \")\",\n );\n }\n if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {\n throw new Error(\n \"live timeline \" + i + \" is no longer live - \" +\n \"it has a neighbouring timeline\",\n );\n }\n }\n\n for (i = 0; i < events.length; i++) {\n // TODO: We should have a filter to say \"only add state event\n // types X Y Z to the timeline\".\n this.addLiveEvent(events[i], duplicateStrategy, fromCache);\n }\n }\n\n /**\n * Adds/handles ephemeral events such as typing notifications and read receipts.\n * @param {MatrixEvent[]} events A list of events to process\n */\n public addEphemeralEvents(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === 'm.typing') {\n this.currentState.setTypingEvent(event);\n } else if (event.getType() === 'm.receipt') {\n this.addReceipt(event);\n } // else ignore - life is too short for us to care about these events\n }\n }\n\n /**\n * Removes events from this room.\n * @param {String[]} eventIds A list of eventIds to remove.\n */\n public removeEvents(eventIds: string[]): void {\n for (let i = 0; i < eventIds.length; ++i) {\n this.removeEvent(eventIds[i]);\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param {String} eventId The id of the event to remove\n *\n * @return {boolean} true if the event was removed from any of the room's timeline sets\n */\n public removeEvent(eventId: string): boolean {\n let removedAny = false;\n for (let i = 0; i < this.timelineSets.length; i++) {\n const removed = this.timelineSets[i].removeEvent(eventId);\n if (removed) {\n if (removed.isRedaction()) {\n this.revertRedactionLocalEcho(removed);\n }\n removedAny = true;\n }\n }\n return removedAny;\n }\n\n /**\n * Recalculate various aspects of the room, including the room name and\n * room summary. Call this any time the room's current state is modified.\n * May fire \"Room.name\" if the room name is updated.\n * @fires module:client~MatrixClient#event:\"Room.name\"\n */\n public recalculate(): void {\n // set fake stripped state events if this is an invite room so logic remains\n // consistent elsewhere.\n const membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);\n if (membershipEvent && membershipEvent.getContent().membership === \"invite\") {\n const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];\n strippedStateEvents.forEach((strippedEvent) => {\n const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);\n if (!existingEvent) {\n // set the fake stripped event instead\n this.currentState.setStateEvents([new MatrixEvent({\n type: strippedEvent.type,\n state_key: strippedEvent.state_key,\n content: strippedEvent.content,\n event_id: \"$fake\" + Date.now(),\n room_id: this.roomId,\n user_id: this.myUserId, // technically a lie\n })]);\n }\n });\n }\n\n const oldName = this.name;\n this.name = this.calculateRoomName(this.myUserId);\n this.normalizedName = normalize(this.name);\n this.summary = new RoomSummary(this.roomId, {\n title: this.name,\n });\n\n if (oldName !== this.name) {\n this.emit(\"Room.name\", this);\n }\n }\n\n /**\n * Get a list of user IDs who have <b>read up to</b> the given event.\n * @param {MatrixEvent} event the event to get read receipts for.\n * @return {String[]} A list of user IDs.\n */\n public getUsersReadUpTo(event: MatrixEvent): string[] {\n return this.getReceiptsForEvent(event).filter(function(receipt) {\n return receipt.type === \"m.read\";\n }).map(function(receipt) {\n return receipt.userId;\n });\n }\n\n /**\n * Get the ID of the event that a given user has read up to, or null if we\n * have received no read receipts from them.\n * @param {String} userId The user ID to get read receipt event ID for\n * @param {Boolean} ignoreSynthesized If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @return {String} ID of the latest event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized = false): string | null {\n let receipts = this.receipts;\n if (ignoreSynthesized) {\n receipts = this.realReceipts;\n }\n\n if (\n receipts[\"m.read\"] === undefined ||\n receipts[\"m.read\"][userId] === undefined\n ) {\n return null;\n }\n\n return receipts[\"m.read\"][userId].eventId;\n }\n\n /**\n * Determines if the given user has read a particular event ID with the known\n * history of the room. This is not a definitive check as it relies only on\n * what is available to the room at the time of execution.\n * @param {String} userId The user ID to check the read state of.\n * @param {String} eventId The event ID to check if the user read.\n * @returns {Boolean} True if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n const readUpToId = this.getEventReadUpTo(userId, false);\n if (readUpToId === eventId) return true;\n\n if (this.timeline.length\n && this.timeline[this.timeline.length - 1].getSender()\n && this.timeline[this.timeline.length - 1].getSender() === userId) {\n // It doesn't matter where the event is in the timeline, the user has read\n // it because they've sent the latest event.\n return true;\n }\n\n for (let i = this.timeline.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n\n // If we encounter the target event first, the user hasn't read it\n // however if we encounter the readUpToId first then the user has read\n // it. These rules apply because we're iterating bottom-up.\n if (ev.getId() === eventId) return false;\n if (ev.getId() === readUpToId) return true;\n }\n\n // We don't know if the user has read it, so assume not.\n return false;\n }\n\n /**\n * Get a list of receipts for the given event.\n * @param {MatrixEvent} event the event to get receipts for\n * @return {Object[]} A list of receipts with a userId, type and data keys or\n * an empty list.\n */\n public getReceiptsForEvent(event: MatrixEvent): ICachedReceipt[] {\n return this.receiptCacheByEventId[event.getId()] || [];\n }\n\n /**\n * Add a receipt event to the room.\n * @param {MatrixEvent} event The m.receipt event.\n * @param {Boolean} fake True if this event is implicit\n */\n public addReceipt(event: MatrixEvent, fake = false): void {\n if (!fake) {\n this.addReceiptsToStructure(event, this.realReceipts);\n // we don't bother caching real receipts by event ID\n // as there's nothing that would read it.\n }\n this.addReceiptsToStructure(event, this.receipts);\n this.receiptCacheByEventId = this.buildReceiptCache(this.receipts);\n\n // send events after we've regenerated the cache, otherwise things that\n // listened for the event would read from a stale cache\n this.emit(\"Room.receipt\", event, this);\n }\n\n /**\n * Add a receipt event to the room.\n * @param {MatrixEvent} event The m.receipt event.\n * @param {Object} receipts The object to add receipts to\n */\n private addReceiptsToStructure(event: MatrixEvent, receipts: Receipts): void {\n const content = event.getContent<IReceiptContent>();\n Object.keys(content).forEach((eventId) => {\n Object.keys(content[eventId]).forEach((receiptType) => {\n Object.keys(content[eventId][receiptType]).forEach((userId) => {\n const receipt = content[eventId][receiptType][userId];\n\n if (!receipts[receiptType]) {\n receipts[receiptType] = {};\n }\n\n const existingReceipt = receipts[receiptType][userId];\n\n if (!existingReceipt) {\n receipts[receiptType][userId] = {} as IWrappedReceipt;\n } else {\n // we only want to add this receipt if we think it is later\n // than the one we already have. (This is managed\n // server-side, but because we synthesize RRs locally we\n // have to do it here too.)\n const ordering = this.getUnfilteredTimelineSet().compareEventOrdering(\n existingReceipt.eventId, eventId);\n if (ordering !== null && ordering >= 0) {\n return;\n }\n }\n\n receipts[receiptType][userId] = {\n eventId: eventId,\n data: receipt,\n };\n });\n });\n });\n }\n\n /**\n * Build and return a map of receipts by event ID\n * @param {Object} receipts A map of receipts\n * @return {Object} Map of receipts by event ID\n */\n private buildReceiptCache(receipts: Receipts): ReceiptCache {\n const receiptCacheByEventId = {};\n Object.keys(receipts).forEach(function(receiptType) {\n Object.keys(receipts[receiptType]).forEach(function(userId) {\n const receipt = receipts[receiptType][userId];\n if (!receiptCacheByEventId[receipt.eventId]) {\n receiptCacheByEventId[receipt.eventId] = [];\n }\n receiptCacheByEventId[receipt.eventId].push({\n userId: userId,\n type: receiptType,\n data: receipt.data,\n });\n });\n });\n return receiptCacheByEventId;\n }\n\n /**\n * Add a temporary local-echo receipt to the room to reflect in the\n * client the fact that we've sent one.\n * @param {string} userId The user ID if the receipt sender\n * @param {MatrixEvent} e The event that is to be acknowledged\n * @param {string} receiptType The type of receipt\n */\n public addLocalEchoReceipt(userId: string, e: MatrixEvent, receiptType: string): void {\n this.addReceipt(synthesizeReceipt(userId, e, receiptType), true);\n }\n\n /**\n * Update the room-tag event for the room. The previous one is overwritten.\n * @param {MatrixEvent} event the m.tag event\n */\n public addTags(event: MatrixEvent): void {\n // event content looks like:\n // content: {\n // tags: {\n // $tagName: { $metadata: $value },\n // $tagName: { $metadata: $value },\n // }\n // }\n\n // XXX: do we need to deep copy here?\n this.tags = event.getContent().tags || {};\n\n // XXX: we could do a deep-comparison to see if the tags have really\n // changed - but do we want to bother?\n this.emit(\"Room.tags\", event, this);\n }\n\n /**\n * Update the account_data events for this room, overwriting events of the same type.\n * @param {Array<MatrixEvent>} events an array of account_data events to add\n */\n public addAccountData(events: MatrixEvent[]): void {\n for (let i = 0; i < events.length; i++) {\n const event = events[i];\n if (event.getType() === \"m.tag\") {\n this.addTags(event);\n }\n const lastEvent = this.accountData[event.getType()];\n this.accountData[event.getType()] = event;\n this.emit(\"Room.accountData\", event, this, lastEvent);\n }\n }\n\n /**\n * Access account_data event of given event type for this room\n * @param {string} type the type of account_data event to be accessed\n * @return {?MatrixEvent} the account_data event in question\n */\n public getAccountData(type: EventType | string): MatrixEvent | undefined {\n return this.accountData[type];\n }\n\n /**\n * Returns whether the syncing user has permission to send a message in the room\n * @return {boolean} true if the user should be permitted to send\n * message events into the room.\n */\n public maySendMessage(): boolean {\n return this.getMyMembership() === 'join' &&\n this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId);\n }\n\n /**\n * Returns whether the given user has permissions to issue an invite for this room.\n * @param {string} userId the ID of the Matrix user to check permissions for\n * @returns {boolean} true if the user should be permitted to issue invites for this room.\n */\n public canInvite(userId: string): boolean {\n let canInvite = this.getMyMembership() === \"join\";\n const powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();\n const me = this.getMember(userId);\n if (powerLevels && me && powerLevels.invite > me.powerLevel) {\n canInvite = false;\n }\n return canInvite;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns {string} the join_rule applied to this room\n */\n public getJoinRule(): string {\n return this.currentState.getJoinRule();\n }\n\n /**\n * Returns the type of the room from the `m.room.create` event content or undefined if none is set\n * @returns {?string} the type of the room. Currently only RoomType.Space is known.\n */\n public getType(): RoomType | string | undefined {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getTypeWarning) {\n logger.warn(\"[getType] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getTypeWarning = true;\n }\n return undefined;\n }\n return createEvent.getContent()[RoomCreateTypeField];\n }\n\n /**\n * Returns whether the room is a space-room as defined by MSC1772.\n * @returns {boolean} true if the room's type is RoomType.Space\n */\n public isSpaceRoom(): boolean {\n return this.getType() === RoomType.Space;\n }\n\n /**\n * This is an internal method. Calculates the name of the room from the current\n * room state.\n * @param {string} userId The client's user ID. Used to filter room members\n * correctly.\n * @param {boolean} ignoreRoomNameEvent Return the implicit room name that we'd see if there\n * was no m.room.name event.\n * @return {string} The calculated room name.\n */\n private calculateRoomName(userId: string, ignoreRoomNameEvent = false): string {\n if (!ignoreRoomNameEvent) {\n // check for an alias, if any. for now, assume first alias is the\n // official one.\n const mRoomName = this.currentState.getStateEvents(EventType.RoomName, \"\");\n if (mRoomName && mRoomName.getContent() && mRoomName.getContent().name) {\n return mRoomName.getContent().name;\n }\n }\n\n let alias = this.getCanonicalAlias();\n\n if (!alias) {\n const aliases = this.getAltAliases();\n\n if (aliases.length) {\n alias = aliases[0];\n }\n }\n if (alias) {\n return alias;\n }\n\n const joinedMemberCount = this.currentState.getJoinedMemberCount();\n const invitedMemberCount = this.currentState.getInvitedMemberCount();\n // -1 because these numbers include the syncing user\n const inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;\n\n // get members that are NOT ourselves and are actually in the room.\n let otherNames = null;\n if (this.summaryHeroes) {\n // if we have a summary, the member state events\n // should be in the room state\n otherNames = this.summaryHeroes.map((userId) => {\n const member = this.getMember(userId);\n return member ? member.name : userId;\n });\n } else {\n let otherMembers = this.currentState.getMembers().filter((m) => {\n return m.userId !== userId &&\n (m.membership === \"invite\" || m.membership === \"join\");\n });\n // make sure members have stable order\n otherMembers.sort((a, b) => a.userId.localeCompare(b.userId));\n // only 5 first members, immitate summaryHeroes\n otherMembers = otherMembers.slice(0, 5);\n otherNames = otherMembers.map((m) => m.name);\n }\n\n if (inviteJoinCount) {\n return memberNamesToRoomName(otherNames, inviteJoinCount);\n }\n\n const myMembership = this.getMyMembership();\n // if I have created a room and invited people throuh\n // 3rd party invites\n if (myMembership == 'join') {\n const thirdPartyInvites =\n this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);\n\n if (thirdPartyInvites && thirdPartyInvites.length) {\n const thirdPartyNames = thirdPartyInvites.map((i) => {\n return i.getContent().display_name;\n });\n\n return `Inviting ${memberNamesToRoomName(thirdPartyNames)}`;\n }\n }\n // let's try to figure out who was here before\n let leftNames = otherNames;\n // if we didn't have heroes, try finding them in the room state\n if (!leftNames.length) {\n leftNames = this.currentState.getMembers().filter((m) => {\n return m.userId !== userId &&\n m.membership !== \"invite\" &&\n m.membership !== \"join\";\n }).map((m) => m.name);\n }\n if (leftNames.length) {\n return `Empty room (was ${memberNamesToRoomName(leftNames)})`;\n } else {\n return \"Empty room\";\n }\n }\n}\n\n/**\n * @param {string} roomId ID of the current room\n * @returns {string} Storage key to retrieve pending events\n */\nfunction pendingEventsKey(roomId: string): string {\n return `mx_pending_events_${roomId}`;\n}\n\n/* a map from current event status to a list of allowed next statuses\n */\nconst ALLOWED_TRANSITIONS = {};\n\nALLOWED_TRANSITIONS[EventStatus.ENCRYPTING] = [\n EventStatus.SENDING,\n EventStatus.NOT_SENT,\n];\n\nALLOWED_TRANSITIONS[EventStatus.SENDING] = [\n EventStatus.ENCRYPTING,\n EventStatus.QUEUED,\n EventStatus.NOT_SENT,\n EventStatus.SENT,\n];\n\nALLOWED_TRANSITIONS[EventStatus.QUEUED] =\n [EventStatus.SENDING, EventStatus.CANCELLED];\n\nALLOWED_TRANSITIONS[EventStatus.SENT] =\n [];\n\nALLOWED_TRANSITIONS[EventStatus.NOT_SENT] =\n [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED];\n\nALLOWED_TRANSITIONS[EventStatus.CANCELLED] =\n [];\n\n// TODO i18n\nfunction memberNamesToRoomName(names: string[], count = (names.length + 1)) {\n const countWithoutMe = count - 1;\n if (!names.length) {\n return \"Empty room\";\n } else if (names.length === 1 && countWithoutMe <= 1) {\n return names[0];\n } else if (names.length === 2 && countWithoutMe <= 2) {\n return `${names[0]} and ${names[1]}`;\n } else {\n const plural = countWithoutMe > 1;\n if (plural) {\n return `${names[0]} and ${countWithoutMe} others`;\n } else {\n return `${names[0]} and 1 other`;\n }\n }\n}\n\n/**\n * Fires when an event we had previously received is redacted.\n *\n * (Note this is *not* fired when the redaction happens before we receive the\n * event).\n *\n * @event module:client~MatrixClient#\"Room.redaction\"\n * @param {MatrixEvent} event The matrix redaction event\n * @param {Room} room The room containing the redacted event\n */\n\n/**\n * Fires when an event that was previously redacted isn't anymore.\n * This happens when the redaction couldn't be sent and\n * was subsequently cancelled by the user. Redactions have a local echo\n * which is undone in this scenario.\n *\n * @event module:client~MatrixClient#\"Room.redactionCancelled\"\n * @param {MatrixEvent} event The matrix redaction event that was cancelled.\n * @param {Room} room The room containing the unredacted event\n */\n\n/**\n * Fires whenever the name of a room is updated.\n * @event module:client~MatrixClient#\"Room.name\"\n * @param {Room} room The room whose Room.name was updated.\n * @example\n * matrixClient.on(\"Room.name\", function(room){\n * var newName = room.name;\n * });\n */\n\n/**\n * Fires whenever a receipt is received for a room\n * @event module:client~MatrixClient#\"Room.receipt\"\n * @param {event} event The receipt event\n * @param {Room} room The room whose receipts was updated.\n * @example\n * matrixClient.on(\"Room.receipt\", function(event, room){\n * var receiptContent = event.getContent();\n * });\n */\n\n/**\n * Fires whenever a room's tags are updated.\n * @event module:client~MatrixClient#\"Room.tags\"\n * @param {event} event The tags event\n * @param {Room} room The room whose Room.tags was updated.\n * @example\n * matrixClient.on(\"Room.tags\", function(event, room){\n * var newTags = event.getContent().tags;\n * if (newTags[\"favourite\"]) showStar(room);\n * });\n */\n\n/**\n * Fires whenever a room's account_data is updated.\n * @event module:client~MatrixClient#\"Room.accountData\"\n * @param {event} event The account_data event\n * @param {Room} room The room whose account_data was updated.\n * @param {MatrixEvent} prevEvent The event being replaced by\n * the new account data, if known.\n * @example\n * matrixClient.on(\"Room.accountData\", function(event, room, oldEvent){\n * if (event.getType() === \"m.room.colorscheme\") {\n * applyColorScheme(event.getContents());\n * }\n * });\n */\n\n/**\n * Fires when the status of a transmitted event is updated.\n *\n * <p>When an event is first transmitted, a temporary copy of the event is\n * inserted into the timeline, with a temporary event id, and a status of\n * 'SENDING'.\n *\n * <p>Once the echo comes back from the server, the content of the event\n * (MatrixEvent.event) is replaced by the complete event from the homeserver,\n * thus updating its event id, as well as server-generated fields such as the\n * timestamp. Its status is set to null.\n *\n * <p>Once the /send request completes, if the remote echo has not already\n * arrived, the event is updated with a new event id and the status is set to\n * 'SENT'. The server-generated fields are of course not updated yet.\n *\n * <p>If the /send fails, In this case, the event's status is set to\n * 'NOT_SENT'. If it is later resent, the process starts again, setting the\n * status to 'SENDING'. Alternatively, the message may be cancelled, which\n * removes the event from the room, and sets the status to 'CANCELLED'.\n *\n * <p>This event is raised to reflect each of the transitions above.\n *\n * @event module:client~MatrixClient#\"Room.localEchoUpdated\"\n *\n * @param {MatrixEvent} event The matrix event which has been updated\n *\n * @param {Room} room The room containing the redacted event\n *\n * @param {string} oldEventId The previous event id (the temporary event id,\n * except when updating a successfully-sent event when its echo arrives)\n *\n * @param {EventStatus} oldStatus The previous event status.\n */\n\n/**\n * Fires when the logged in user's membership in the room is updated.\n *\n * @event module:models/room~Room#\"Room.myMembership\"\n * @param {Room} room The room in which the membership has been updated\n * @param {string} membership The new membership value\n * @param {string} prevMembership The previous membership value\n */\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/search-result\n */\n\nimport { EventContext } from \"./event-context\";\n\n/**\n * Construct a new SearchResult\n *\n * @param {number} rank where this SearchResult ranks in the results\n * @param {event-context.EventContext} eventContext the matching event and its\n * context\n *\n * @constructor\n */\nexport function SearchResult(rank, eventContext) {\n this.rank = rank;\n this.context = eventContext;\n}\n\n/**\n * Create a SearchResponse from the response to /search\n * @static\n * @param {Object} jsonObj\n * @param {function} eventMapper\n * @return {SearchResult}\n */\n\nSearchResult.fromJson = function(jsonObj, eventMapper) {\n const jsonContext = jsonObj.context || {};\n const events_before = jsonContext.events_before || [];\n const events_after = jsonContext.events_after || [];\n\n const context = new EventContext(eventMapper(jsonObj.result));\n\n context.setPaginateToken(jsonContext.start, true);\n context.addEvents(events_before.map(eventMapper), true);\n context.addEvents(events_after.map(eventMapper), false);\n context.setPaginateToken(jsonContext.end, false);\n\n return new SearchResult(jsonObj.rank, context);\n};\n\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module models/user\n */\n\nimport { EventEmitter } from \"events\";\n\nimport { MatrixEvent } from \"./event\";\n\nexport class User extends EventEmitter {\n // eslint-disable-next-line camelcase\n private modified: number;\n\n // XXX these should be read-only\n public displayName: string;\n public rawDisplayName: string;\n public avatarUrl: string;\n public presenceStatusMsg: string = null;\n public presence = \"offline\";\n public lastActiveAgo = 0;\n public lastPresenceTs = 0;\n public currentlyActive = false;\n public events: {\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {\n presence: null,\n profile: null,\n };\n // eslint-disable-next-line camelcase\n public unstable_statusMessage = \"\";\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra\n * information associated with it.\n * @constructor\n * @param {string} userId Required. The ID of this user.\n * @prop {string} userId The ID of the user.\n * @prop {Object} info The info object supplied in the constructor.\n * @prop {string} displayName The 'displayname' of the user if known.\n * @prop {string} avatarUrl The 'avatar_url' of the user if known.\n * @prop {string} presence The presence enum if known.\n * @prop {string} presenceStatusMsg The presence status message if known.\n * @prop {Number} lastActiveAgo The time elapsed in ms since the user interacted\n * proactively with the server, or we saw a message from the user\n * @prop {Number} lastPresenceTs Timestamp (ms since the epoch) for when we last\n * received presence data for this user. We can subtract\n * lastActiveAgo from this to approximate an absolute value for\n * when a user was last active.\n * @prop {Boolean} currentlyActive Whether we should consider lastActiveAgo to be\n * an approximation and that the user should be seen as active 'now'\n * @prop {string} unstable_statusMessage The status message for the user, if known. This is\n * different from the presenceStatusMsg in that this is not tied to\n * the user's presence, and should be represented differently.\n * @prop {Object} events The events describing this user.\n * @prop {MatrixEvent} events.presence The m.presence event for this user.\n */\n constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.avatarUrl = null;\n this.updateModifiedTime();\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param {MatrixEvent} event The <code>m.presence</code> event.\n * @fires module:client~MatrixClient#event:\"User.presence\"\n * @fires module:client~MatrixClient#event:\"User.displayName\"\n * @fires module:client~MatrixClient#event:\"User.avatarUrl\"\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(\"User.presence\");\n }\n if (event.getContent().avatar_url &&\n event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(\"User.avatarUrl\");\n }\n if (event.getContent().displayname &&\n event.getContent().displayname !== this.displayName) {\n eventsToFire.push(\"User.displayName\");\n }\n if (event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive) {\n eventsToFire.push(\"User.currentlyActive\");\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(\"User.lastPresenceTs\");\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent().status_msg;\n }\n if (event.getContent().displayname) {\n this.displayName = event.getContent().displayname;\n }\n if (event.getContent().avatar_url) {\n this.avatarUrl = event.getContent().avatar_url;\n }\n this.lastActiveAgo = event.getContent().last_active_ago;\n this.lastPresenceTs = Date.now();\n this.currentlyActive = event.getContent().currently_active;\n\n this.updateModifiedTime();\n\n for (let i = 0; i < eventsToFire.length; i++) {\n this.emit(eventsToFire[i], event, this);\n }\n }\n\n /**\n * Manually set this user's display name. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param {string} name The new display name.\n */\n public setDisplayName(name: string): void {\n const oldName = this.displayName;\n if (typeof name === \"string\") {\n this.displayName = name;\n } else {\n this.displayName = undefined;\n }\n if (name !== oldName) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Manually set this user's non-disambiguated display name. No event is emitted\n * in response to this as there is no underlying MatrixEvent to emit with.\n * @param {string} name The new display name.\n */\n public setRawDisplayName(name: string): void {\n if (typeof name === \"string\") {\n this.rawDisplayName = name;\n } else {\n this.rawDisplayName = undefined;\n }\n }\n\n /**\n * Manually set this user's avatar URL. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param {string} url The new avatar URL.\n */\n public setAvatarUrl(url: string): void {\n const oldUrl = this.avatarUrl;\n this.avatarUrl = url;\n if (url !== oldUrl) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this User was last updated. This timestamp is\n * updated when this User receives a new Presence event which has updated a\n * property on this object. It is updated <i>before</i> firing events.\n * @return {number} The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get the absolute timestamp when this User was last known active on the server.\n * It is *NOT* accurate if this.currentlyActive is true.\n * @return {number} The timestamp\n */\n public getLastActiveTs(): number {\n return this.lastPresenceTs - this.lastActiveAgo;\n }\n\n /**\n * Manually set the user's status message.\n * @param {MatrixEvent} event The <code>im.vector.user_status</code> event.\n * @fires module:client~MatrixClient#event:\"User.unstable_statusMessage\"\n */\n // eslint-disable-next-line camelcase\n public unstable_updateStatusMessage(event: MatrixEvent): void {\n if (!event.getContent()) this.unstable_statusMessage = \"\";\n else this.unstable_statusMessage = event.getContent()[\"status\"];\n this.updateModifiedTime();\n this.emit(\"User.unstable_statusMessage\", this);\n }\n}\n\n/**\n * Fires whenever any user's lastPresenceTs changes,\n * ie. whenever any presence event is received for a user.\n * @event module:client~MatrixClient#\"User.lastPresenceTs\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {User} user The user whose User.lastPresenceTs changed.\n * @example\n * matrixClient.on(\"User.lastPresenceTs\", function(event, user){\n * var newlastPresenceTs = user.lastPresenceTs;\n * });\n */\n\n/**\n * Fires whenever any user's presence changes.\n * @event module:client~MatrixClient#\"User.presence\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {User} user The user whose User.presence changed.\n * @example\n * matrixClient.on(\"User.presence\", function(event, user){\n * var newPresence = user.presence;\n * });\n */\n\n/**\n * Fires whenever any user's currentlyActive changes.\n * @event module:client~MatrixClient#\"User.currentlyActive\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {User} user The user whose User.currentlyActive changed.\n * @example\n * matrixClient.on(\"User.currentlyActive\", function(event, user){\n * var newCurrentlyActive = user.currentlyActive;\n * });\n */\n\n/**\n * Fires whenever any user's display name changes.\n * @event module:client~MatrixClient#\"User.displayName\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {User} user The user whose User.displayName changed.\n * @example\n * matrixClient.on(\"User.displayName\", function(event, user){\n * var newName = user.displayName;\n * });\n */\n\n/**\n * Fires whenever any user's avatar URL changes.\n * @event module:client~MatrixClient#\"User.avatarUrl\"\n * @param {MatrixEvent} event The matrix event which caused this event to fire.\n * @param {User} user The user whose User.avatarUrl changed.\n * @example\n * matrixClient.on(\"User.avatarUrl\", function(event, user){\n * var newUrl = user.avatarUrl;\n * });\n */\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils\";\nimport { logger } from './logger';\n\n/**\n * @module pushprocessor\n */\n\nconst RULEKINDS_IN_ORDER = ['override', 'content', 'room', 'sender', 'underride'];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES = [\n {\n // For homeservers which don't support MSC1930 yet\n rule_id: \".m.rule.tombstone\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: \"event_match\",\n key: \"type\",\n pattern: \"m.room.tombstone\",\n },\n {\n kind: \"event_match\",\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [\n \"notify\",\n {\n set_tweak: \"highlight\",\n value: true,\n },\n ],\n },\n {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: \"event_match\",\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [\n \"dont_notify\",\n ],\n },\n];\n\n/**\n * Construct a Push Processor.\n * @constructor\n * @param {Object} client The Matrix client object to use\n */\nexport function PushProcessor(client) {\n const cachedGlobToRegex = {\n // $glob: RegExp,\n };\n\n const matchingRuleFromKindSet = (ev, kindset) => {\n for (let ruleKindIndex = 0;\n ruleKindIndex < RULEKINDS_IN_ORDER.length;\n ++ruleKindIndex) {\n const kind = RULEKINDS_IN_ORDER[ruleKindIndex];\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (let ruleIndex = 0; ruleIndex < ruleset.length; ++ruleIndex) {\n const rule = ruleset[ruleIndex];\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n rule.kind = kind;\n return rule;\n }\n }\n }\n return null;\n };\n\n const templateRuleToRaw = function(kind, tprule) {\n const rawrule = {\n 'rule_id': tprule.rule_id,\n 'actions': tprule.actions,\n 'conditions': [],\n };\n switch (kind) {\n case 'underride':\n case 'override':\n rawrule.conditions = tprule.conditions;\n break;\n case 'room':\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'room_id',\n 'value': tprule.rule_id,\n });\n break;\n case 'sender':\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'user_id',\n 'value': tprule.rule_id,\n });\n break;\n case 'content':\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions.push({\n 'kind': 'event_match',\n 'key': 'content.body',\n 'pattern': tprule.pattern,\n });\n break;\n }\n return rawrule;\n };\n\n const eventFulfillsCondition = function(cond, ev) {\n const condition_functions = {\n \"event_match\": eventFulfillsEventMatchCondition,\n \"contains_display_name\": eventFulfillsDisplayNameCondition,\n \"room_member_count\": eventFulfillsRoomMemberCountCondition,\n \"sender_notification_permission\": eventFulfillsSenderNotifPermCondition,\n };\n if (condition_functions[cond.kind]) {\n return condition_functions[cond.kind](cond, ev);\n }\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n };\n\n const eventFulfillsSenderNotifPermCondition = function(cond, ev) {\n const notifLevelKey = cond['key'];\n if (!notifLevelKey) {\n return false;\n }\n\n const room = client.getRoom(ev.getRoomId());\n if (!room || !room.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender());\n };\n\n const eventFulfillsRoomMemberCountCondition = function(cond, ev) {\n if (!cond.is) {\n return false;\n }\n\n const room = client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n const memberCount = room.currentState.getJoinedMemberCount();\n\n const m = cond.is.match(/^([=<>]*)([0-9]*)$/);\n if (!m) {\n return false;\n }\n const ineq = m[1];\n const rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case '':\n case '==':\n return memberCount == rhs;\n case '<':\n return memberCount < rhs;\n case '>':\n return memberCount > rhs;\n case '<=':\n return memberCount <= rhs;\n case '>=':\n return memberCount >= rhs;\n default:\n return false;\n }\n };\n\n const eventFulfillsDisplayNameCondition = function(cond, ev) {\n let content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent();\n }\n if (!content || !content.body || typeof content.body != 'string') {\n return false;\n }\n\n const room = client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members ||\n !room.currentState.getMember(client.credentials.userId)) {\n return false;\n }\n\n const displayName = room.currentState.getMember(client.credentials.userId).name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n const pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", 'i');\n return content.body.search(pat) > -1;\n };\n\n const eventFulfillsEventMatchCondition = function(cond, ev) {\n if (!cond.key) {\n return false;\n }\n\n const val = valueForDottedKey(cond.key, ev);\n if (typeof val !== 'string') {\n return false;\n }\n\n if (cond.value) {\n return cond.value === val;\n }\n\n if (typeof cond.pattern !== 'string') {\n return false;\n }\n\n let regex;\n\n if (cond.key == 'content.body') {\n regex = createCachedRegex('(^|\\\\W)', cond.pattern, '(\\\\W|$)');\n } else {\n regex = createCachedRegex('^', cond.pattern, '$');\n }\n\n return !!val.match(regex);\n };\n\n const createCachedRegex = function(prefix, glob, suffix) {\n if (cachedGlobToRegex[glob]) {\n return cachedGlobToRegex[glob];\n }\n cachedGlobToRegex[glob] = new RegExp(\n prefix + globToRegexp(glob) + suffix,\n 'i', // Case insensitive\n );\n return cachedGlobToRegex[glob];\n };\n\n const valueForDottedKey = function(key, ev) {\n const parts = key.split('.');\n let val;\n\n // special-case the first component to deal with encrypted messages\n const firstPart = parts[0];\n if (firstPart === 'content') {\n val = ev.getContent();\n parts.shift();\n } else if (firstPart === 'type') {\n val = ev.getType();\n parts.shift();\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n while (parts.length > 0) {\n const thisPart = parts.shift();\n if (isNullOrUndefined(val[thisPart])) {\n return null;\n }\n val = val[thisPart];\n }\n return val;\n };\n\n const matchingRuleForEventWithRulesets = function(ev, rulesets) {\n if (!rulesets) {\n return null;\n }\n if (ev.getSender() === client.credentials.userId) {\n return null;\n }\n\n return matchingRuleFromKindSet(ev, rulesets.global);\n };\n\n const pushActionsForEventAndRulesets = function(ev, rulesets) {\n const rule = matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {};\n }\n\n const actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = (rule.kind == 'content');\n }\n\n return actionObj;\n };\n\n this.ruleMatchesEvent = function(rule, ev) {\n let ret = true;\n for (let i = 0; i < rule.conditions.length; ++i) {\n const cond = rule.conditions[i];\n ret &= eventFulfillsCondition(cond, ev);\n }\n //console.log(\"Rule \"+rule.rule_id+(ret ? \" matches\" : \" doesn't match\"));\n return ret;\n };\n\n /**\n * Get the user's push actions for the given event\n *\n * @param {module:models/event.MatrixEvent} ev\n *\n * @return {PushAction}\n */\n this.actionsForEvent = function(ev) {\n return pushActionsForEventAndRulesets(ev, client.pushRules);\n };\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param {string} ruleId The ID of the rule to search for\n * @return {object} The push rule, or null if no such rule was found\n */\n this.getPushRuleById = function(ruleId) {\n for (const scope of ['global']) {\n if (client.pushRules[scope] === undefined) continue;\n\n for (const kind of RULEKINDS_IN_ORDER) {\n if (client.pushRules[scope][kind] === undefined) continue;\n\n for (const rule of client.pushRules[scope][kind]) {\n if (rule.rule_id === ruleId) return rule;\n }\n }\n }\n return null;\n };\n}\n\n/**\n * Convert a list of actions into a object with the actions as keys and their values\n * eg. [ 'notify', { set_tweak: 'sound', value: 'default' } ]\n * becomes { notify: true, tweaks: { sound: 'default' } }\n * @param {array} actionlist The actions list\n *\n * @return {object} A object with key 'notify' (true or false) and an object of actions\n */\nPushProcessor.actionListToActionsObject = function(actionlist) {\n const actionobj = { 'notify': false, 'tweaks': {} };\n for (let i = 0; i < actionlist.length; ++i) {\n const action = actionlist[i];\n if (action === 'notify') {\n actionobj.notify = true;\n } else if (typeof action === 'object') {\n if (action.value === undefined) {\n action.value = true;\n }\n actionobj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionobj;\n};\n\n/**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n * @param {object} incomingRules The client's existing push rules\n * @returns {object} The rewritten rules\n */\nPushProcessor.rewriteDefaultRules = function(incomingRules) {\n let newRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {};\n if (!newRules.global) newRules.global = {};\n if (!newRules.global.override) newRules.global.override = [];\n\n // Merge the client-level defaults with the ones from the server\n const globalOverrides = newRules.global.override;\n for (const override of DEFAULT_OVERRIDE_RULES) {\n const existingRule = globalOverrides\n .find((r) => r.rule_id === override.rule_id);\n\n if (existingRule) {\n // Copy over the actions, default, and conditions. Don't touch the user's\n // preference.\n existingRule.default = override.default;\n existingRule.conditions = override.conditions;\n existingRule.actions = override.actions;\n } else {\n // Add the rule\n const ruleId = override.rule_id;\n logger.warn(`Adding default global override for ${ruleId}`);\n globalOverrides.push(override);\n }\n }\n\n return newRules;\n};\n\n/**\n * @typedef {Object} PushAction\n * @type {Object}\n * @property {boolean} notify Whether this event should notify the user or not.\n * @property {Object} tweaks How this event should be notified.\n * @property {boolean} tweaks.highlight Whether this event should be highlighted\n * on the UI.\n * @property {boolean} tweaks.sound Whether this notification should produce a\n * noise.\n */\n\n",
"/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nconst LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\nconst UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst DIGITS = \"0123456789\";\n\nexport function randomString(len: number): string {\n return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\nexport function randomLowercaseString(len: number): string {\n return randomStringFrom(len, LOWERCASE);\n}\n\nexport function randomUppercaseString(len: number): string {\n return randomStringFrom(len, UPPERCASE);\n}\n\nfunction randomStringFrom(len: number, chars: string): string {\n let ret = \"\";\n\n for (let i = 0; i < len; ++i) {\n ret += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n\n return ret;\n}\n",
"/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* A re-implementation of the javascript callback functions (setTimeout,\n * clearTimeout; setInterval and clearInterval are not yet implemented) which\n * try to improve handling of large clock jumps (as seen when\n * suspending/resuming the system).\n *\n * In particular, if a timeout would have fired while the system was suspended,\n * it will instead fire as soon as possible after resume.\n */\n\nimport { logger } from './logger';\n\n// we schedule a callback at least this often, to check if we've missed out on\n// some wall-clock time due to being suspended.\nconst TIMER_CHECK_PERIOD_MS = 1000;\n\n// counter, for making up ids to return from setTimeout\nlet _count = 0;\n\n// the key for our callback with the real global.setTimeout\nlet _realCallbackKey;\n\n// a sorted list of the callbacks to be run.\n// each is an object with keys [runAt, func, params, key].\nconst _callbackList = [];\n\n// var debuglog = logger.log.bind(logger);\nconst debuglog = function() {};\n\n/**\n * Replace the function used by this module to get the current time.\n *\n * Intended for use by the unit tests.\n *\n * @param {function} [f] function which should return a millisecond counter\n *\n * @internal\n */\nexport function setNow(f) {\n _now = f || Date.now;\n}\nlet _now = Date.now;\n\n/**\n * reimplementation of window.setTimeout, which will call the callback if\n * the wallclock time goes past the deadline.\n *\n * @param {function} func callback to be called after a delay\n * @param {Number} delayMs number of milliseconds to delay by\n *\n * @return {Number} an identifier for this callback, which may be passed into\n * clearTimeout later.\n */\nexport function setTimeout(func, delayMs) {\n delayMs = delayMs || 0;\n if (delayMs < 0) {\n delayMs = 0;\n }\n\n const params = Array.prototype.slice.call(arguments, 2);\n const runAt = _now() + delayMs;\n const key = _count++;\n debuglog(\"setTimeout: scheduling cb\", key, \"at\", runAt,\n \"(delay\", delayMs, \")\");\n const data = {\n runAt: runAt,\n func: func,\n params: params,\n key: key,\n };\n\n // figure out where it goes in the list\n const idx = binarySearch(\n _callbackList, function(el) {\n return el.runAt - runAt;\n },\n );\n\n _callbackList.splice(idx, 0, data);\n _scheduleRealCallback();\n\n return key;\n}\n\n/**\n * reimplementation of window.clearTimeout, which mirrors setTimeout\n *\n * @param {Number} key result from an earlier setTimeout call\n */\nexport function clearTimeout(key) {\n if (_callbackList.length === 0) {\n return;\n }\n\n // remove the element from the list\n let i;\n for (i = 0; i < _callbackList.length; i++) {\n const cb = _callbackList[i];\n if (cb.key == key) {\n _callbackList.splice(i, 1);\n break;\n }\n }\n\n // iff it was the first one in the list, reschedule our callback.\n if (i === 0) {\n _scheduleRealCallback();\n }\n}\n\n// use the real global.setTimeout to schedule a callback to _runCallbacks.\nfunction _scheduleRealCallback() {\n if (_realCallbackKey) {\n global.clearTimeout(_realCallbackKey);\n }\n\n const first = _callbackList[0];\n\n if (!first) {\n debuglog(\"_scheduleRealCallback: no more callbacks, not rescheduling\");\n return;\n }\n\n const now = _now();\n const delayMs = Math.min(first.runAt - now, TIMER_CHECK_PERIOD_MS);\n\n debuglog(\"_scheduleRealCallback: now:\", now, \"delay:\", delayMs);\n _realCallbackKey = global.setTimeout(_runCallbacks, delayMs);\n}\n\nfunction _runCallbacks() {\n let cb;\n const now = _now();\n debuglog(\"_runCallbacks: now:\", now);\n\n // get the list of things to call\n const callbacksToRun = [];\n while (true) {\n const first = _callbackList[0];\n if (!first || first.runAt > now) {\n break;\n }\n cb = _callbackList.shift();\n debuglog(\"_runCallbacks: popping\", cb.key);\n callbacksToRun.push(cb);\n }\n\n // reschedule the real callback before running our functions, to\n // keep the codepaths the same whether or not our functions\n // register their own setTimeouts.\n _scheduleRealCallback();\n\n for (let i = 0; i < callbacksToRun.length; i++) {\n cb = callbacksToRun[i];\n try {\n cb.func.apply(global, cb.params);\n } catch (e) {\n logger.error(\"Uncaught exception in callback function\",\n e.stack || e);\n }\n }\n}\n\n/* search in a sorted array.\n *\n * returns the index of the last element for which func returns\n * greater than zero, or array.length if no such element exists.\n */\nfunction binarySearch(array, func) {\n // min is inclusive, max exclusive.\n let min = 0;\n let max = array.length;\n\n while (min < max) {\n const mid = (min + max) >> 1;\n const res = func(array[mid]);\n if (res > 0) {\n // the element at 'mid' is too big; set it as the new max.\n max = mid;\n } else {\n // the element at 'mid' is too small. 'min' is inclusive, so +1.\n min = mid + 1;\n }\n }\n // presumably, min==max now.\n return min;\n}\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module which manages queuing, scheduling and retrying\n * of requests.\n * @module scheduler\n */\nimport * as utils from \"./utils\";\nimport { logger } from './logger';\n\nconst DEBUG = false; // set true to enable console logging.\n\n/**\n * Construct a scheduler for Matrix. Requires\n * {@link module:scheduler~MatrixScheduler#setProcessFunction} to be provided\n * with a way of processing events.\n * @constructor\n * @param {module:scheduler~retryAlgorithm} retryAlgorithm Optional. The retry\n * algorithm to apply when determining when to try to send an event again.\n * Defaults to {@link module:scheduler~MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.\n * @param {module:scheduler~queueAlgorithm} queueAlgorithm Optional. The queuing\n * algorithm to apply when determining which events should be sent before the\n * given event. Defaults to {@link module:scheduler~MatrixScheduler.QUEUE_MESSAGES}.\n */\nexport function MatrixScheduler(retryAlgorithm, queueAlgorithm) {\n this.retryAlgorithm = retryAlgorithm || MatrixScheduler.RETRY_BACKOFF_RATELIMIT;\n this.queueAlgorithm = queueAlgorithm || MatrixScheduler.QUEUE_MESSAGES;\n this._queues = {\n // queueName: [{\n // event: MatrixEvent, // event to send\n // defer: Deferred, // defer to resolve/reject at the END of the retries\n // attempts: Number // number of times we've called processFn\n // }, ...]\n };\n this._activeQueues = [];\n this._procFn = null;\n}\n\n/**\n * Retrieve a queue based on an event. The event provided does not need to be in\n * the queue.\n * @param {MatrixEvent} event An event to get the queue for.\n * @return {?Array<MatrixEvent>} A shallow copy of events in the queue or null.\n * Modifying this array will not modify the list itself. Modifying events in\n * this array <i>will</i> modify the underlying event in the queue.\n * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.\n */\nMatrixScheduler.prototype.getQueueForEvent = function(event) {\n const name = this.queueAlgorithm(event);\n if (!name || !this._queues[name]) {\n return null;\n }\n return this._queues[name].map(function(obj) {\n return obj.event;\n });\n};\n\n/**\n * Remove this event from the queue. The event is equal to another event if they\n * have the same ID returned from event.getId().\n * @param {MatrixEvent} event The event to remove.\n * @return {boolean} True if this event was removed.\n */\nMatrixScheduler.prototype.removeEventFromQueue = function(event) {\n const name = this.queueAlgorithm(event);\n if (!name || !this._queues[name]) {\n return false;\n }\n let removed = false;\n utils.removeElement(this._queues[name], function(element) {\n if (element.event.getId() === event.getId()) {\n // XXX we should probably reject the promise?\n // https://github.com/matrix-org/matrix-js-sdk/issues/496\n removed = true;\n return true;\n }\n });\n return removed;\n};\n\n/**\n * Set the process function. Required for events in the queue to be processed.\n * If set after events have been added to the queue, this will immediately start\n * processing them.\n * @param {module:scheduler~processFn} fn The function that can process events\n * in the queue.\n */\nMatrixScheduler.prototype.setProcessFunction = function(fn) {\n this._procFn = fn;\n _startProcessingQueues(this);\n};\n\n/**\n * Queue an event if it is required and start processing queues.\n * @param {MatrixEvent} event The event that may be queued.\n * @return {?Promise} A promise if the event was queued, which will be\n * resolved or rejected in due time, else null.\n */\nMatrixScheduler.prototype.queueEvent = function(event) {\n const queueName = this.queueAlgorithm(event);\n if (!queueName) {\n return null;\n }\n // add the event to the queue and make a deferred for it.\n if (!this._queues[queueName]) {\n this._queues[queueName] = [];\n }\n const defer = utils.defer();\n this._queues[queueName].push({\n event: event,\n defer: defer,\n attempts: 0,\n });\n debuglog(\n \"Queue algorithm dumped event %s into queue '%s'\",\n event.getId(), queueName,\n );\n _startProcessingQueues(this);\n return defer.promise;\n};\n\n/**\n * Retries events up to 4 times using exponential backoff. This produces wait\n * times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the\n * failure was due to a rate limited request, the time specified in the error is\n * waited before being retried.\n * @param {MatrixEvent} event\n * @param {Number} attempts\n * @param {MatrixError} err\n * @return {Number}\n * @see module:scheduler~retryAlgorithm\n */\nMatrixScheduler.RETRY_BACKOFF_RATELIMIT = function(event, attempts, err) {\n if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) {\n // client error; no amount of retrying with save you now.\n return -1;\n }\n // we ship with browser-request which returns { cors: rejected } when trying\n // with no connection, so if we match that, give up since they have no conn.\n if (err.cors === \"rejected\") {\n return -1;\n }\n\n // if event that we are trying to send is too large in any way then retrying won't help\n if (err.name === \"M_TOO_LARGE\") {\n return -1;\n }\n\n if (err.name === \"M_LIMIT_EXCEEDED\") {\n const waitTime = err.data.retry_after_ms;\n if (waitTime > 0) {\n return waitTime;\n }\n }\n if (attempts > 4) {\n return -1; // give up\n }\n return (1000 * Math.pow(2, attempts));\n};\n\n/**\n * Queues <code>m.room.message</code> events and lets other events continue\n * concurrently.\n * @param {MatrixEvent} event\n * @return {string}\n * @see module:scheduler~queueAlgorithm\n */\nMatrixScheduler.QUEUE_MESSAGES = function(event) {\n // enqueue messages or events that associate with another event (redactions and relations)\n if (event.getType() === \"m.room.message\" || event.hasAssocation()) {\n // put these events in the 'message' queue.\n return \"message\";\n }\n // allow all other events continue concurrently.\n return null;\n};\n\nfunction _startProcessingQueues(scheduler) {\n if (!scheduler._procFn) {\n return;\n }\n // for each inactive queue with events in them\n Object.keys(scheduler._queues)\n .filter(function(queueName) {\n return scheduler._activeQueues.indexOf(queueName) === -1 &&\n scheduler._queues[queueName].length > 0;\n })\n .forEach(function(queueName) {\n // mark the queue as active\n scheduler._activeQueues.push(queueName);\n // begin processing the head of the queue\n debuglog(\"Spinning up queue: '%s'\", queueName);\n _processQueue(scheduler, queueName);\n });\n}\n\nfunction _processQueue(scheduler, queueName) {\n // get head of queue\n const obj = _peekNextEvent(scheduler, queueName);\n if (!obj) {\n // queue is empty. Mark as inactive and stop recursing.\n const index = scheduler._activeQueues.indexOf(queueName);\n if (index >= 0) {\n scheduler._activeQueues.splice(index, 1);\n }\n debuglog(\"Stopping queue '%s' as it is now empty\", queueName);\n return;\n }\n debuglog(\n \"Queue '%s' has %s pending events\",\n queueName, scheduler._queues[queueName].length,\n );\n // fire the process function and if it resolves, resolve the deferred. Else\n // invoke the retry algorithm.\n\n // First wait for a resolved promise, so the resolve handlers for\n // the deferred of the previously sent event can run.\n // This way enqueued relations/redactions to enqueued events can receive\n // the remove id of their target before being sent.\n Promise.resolve().then(() => {\n return scheduler._procFn(obj.event);\n }).then(function(res) {\n // remove this from the queue\n _removeNextEvent(scheduler, queueName);\n debuglog(\"Queue '%s' sent event %s\", queueName, obj.event.getId());\n obj.defer.resolve(res);\n // keep processing\n _processQueue(scheduler, queueName);\n }, function(err) {\n obj.attempts += 1;\n // ask the retry algorithm when/if we should try again\n const waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);\n debuglog(\n \"retry(%s) err=%s event_id=%s waitTime=%s\",\n obj.attempts, err, obj.event.getId(), waitTimeMs,\n );\n if (waitTimeMs === -1) { // give up (you quitter!)\n debuglog(\n \"Queue '%s' giving up on event %s\", queueName, obj.event.getId(),\n );\n // remove this from the queue\n _removeNextEvent(scheduler, queueName);\n obj.defer.reject(err);\n // process next event\n _processQueue(scheduler, queueName);\n } else {\n setTimeout(function() {\n _processQueue(scheduler, queueName);\n }, waitTimeMs);\n }\n });\n}\n\nfunction _peekNextEvent(scheduler, queueName) {\n const queue = scheduler._queues[queueName];\n if (!Array.isArray(queue)) {\n return null;\n }\n return queue[0];\n}\n\nfunction _removeNextEvent(scheduler, queueName) {\n const queue = scheduler._queues[queueName];\n if (!Array.isArray(queue)) {\n return null;\n }\n return queue.shift();\n}\n\nfunction debuglog() {\n if (DEBUG) {\n logger.log(...arguments);\n }\n}\n\n/**\n * The retry algorithm to apply when retrying events. To stop retrying, return\n * <code>-1</code>. If this event was part of a queue, it will be removed from\n * the queue.\n * @callback retryAlgorithm\n * @param {MatrixEvent} event The event being retried.\n * @param {Number} attempts The number of failed attempts. This will always be\n * >= 1.\n * @param {MatrixError} err The most recent error message received when trying\n * to send this event.\n * @return {Number} The number of milliseconds to wait before trying again. If\n * this is 0, the request will be immediately retried. If this is\n * <code>-1</code>, the event will be marked as\n * {@link module:models/event.EventStatus.NOT_SENT} and will not be retried.\n */\n\n/**\n * The queuing algorithm to apply to events. This function must be idempotent as\n * it may be called multiple times with the same event. All queues created are\n * serviced in a FIFO manner. To send the event ASAP, return <code>null</code>\n * which will not put this event in a queue. Events that fail to send that form\n * part of a queue will be removed from the queue and the next event in the\n * queue will be sent.\n * @callback queueAlgorithm\n * @param {MatrixEvent} event The event to be sent.\n * @return {string} The name of the queue to put the event into. If a queue with\n * this name does not exist, it will be created. If this is <code>null</code>,\n * the event is not put into a queue and will be sent concurrently.\n */\n\n /**\n * The function to invoke to process (send) events in the queue.\n * @callback processFn\n * @param {MatrixEvent} event The event to send.\n * @return {Promise} Resolved/rejected depending on the outcome of the request.\n */\n\n",
"/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum SERVICE_TYPES {\n IS = 'SERVICE_TYPE_IS', // An Identity Service\n IM = 'SERVICE_TYPE_IM', // An Integration Manager\n}\n",
"/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { SyncAccumulator } from \"../sync-accumulator\";\nimport * as utils from \"../utils\";\nimport * as IndexedDBHelpers from \"../indexeddb-helpers\";\nimport { logger } from '../logger';\n\nconst VERSION = 3;\n\nfunction createDatabase(db) {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", { keyPath: [\"userId\"] });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", { keyPath: [\"type\"] });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", { keyPath: [\"clobber\"] });\n}\n\nfunction upgradeSchemaV2(db) {\n const oobMembersStore = db.createObjectStore(\n \"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"],\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n}\n\nfunction upgradeSchemaV3(db) {\n db.createObjectStore(\"client_options\",\n { keyPath: [\"clobber\"] });\n}\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param {ObjectStore|Index} store The store to perform openCursor on.\n * @param {IDBKeyRange=} keyRange Optional key range to apply on the cursor.\n * @param {Function} resultMapper A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @return {Promise<T[]>} Resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery(store, keyRange, resultMapper) {\n const query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n const results = [];\n query.onerror = (event) => {\n reject(new Error(\"Query failed: \" + event.target.errorCode));\n };\n // collect results\n query.onsuccess = (event) => {\n const cursor = event.target.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\n\nfunction txnAsPromise(txn) {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function(event) {\n resolve(event);\n };\n txn.onerror = function(event) {\n reject(event.target.error);\n };\n });\n}\n\nfunction reqAsEventPromise(req) {\n return new Promise((resolve, reject) => {\n req.onsuccess = function(event) {\n resolve(event);\n };\n req.onerror = function(event) {\n reject(event.target.error);\n };\n });\n}\n\nfunction reqAsPromise(req) {\n return new Promise((resolve, reject) => {\n req.onsuccess = () => resolve(req);\n req.onerror = (err) => reject(err);\n });\n}\n\nfunction reqAsCursorPromise(req) {\n return reqAsEventPromise(req).then((event) => event.target.result);\n}\n\n/**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * <code>connect()</code> before this store can be used.\n * @constructor\n * @param {Object} indexedDBInterface The Indexed DB interface e.g\n * <code>window.indexedDB</code>\n * @param {string=} dbName Optional database name. The same name must be used\n * to open the same database.\n */\nexport function LocalIndexedDBStoreBackend(\n indexedDBInterface, dbName,\n) {\n this.indexedDB = indexedDBInterface;\n this._dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n this.db = null;\n this._disconnected = true;\n this._syncAccumulator = new SyncAccumulator();\n this._isNewlyCreated = false;\n}\n\nLocalIndexedDBStoreBackend.exists = function(indexedDB, dbName) {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return IndexedDBHelpers.exists(indexedDB, dbName);\n};\n\nLocalIndexedDBStoreBackend.prototype = {\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @return {Promise} Resolves if successfully connected.\n */\n connect: function() {\n if (!this._disconnected) {\n logger.log(\n `LocalIndexedDBStoreBackend.connect: already connected or connecting`,\n );\n return Promise.resolve();\n }\n\n this._disconnected = false;\n\n logger.log(\n `LocalIndexedDBStoreBackend.connect: connecting...`,\n );\n const req = this.indexedDB.open(this._dbName, VERSION);\n req.onupgradeneeded = (ev) => {\n const db = ev.target.result;\n const oldVersion = ev.oldVersion;\n logger.log(\n `LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`,\n );\n if (oldVersion < 1) { // The database did not previously exist.\n this._isNewlyCreated = true;\n createDatabase(db);\n }\n if (oldVersion < 2) {\n upgradeSchemaV2(db);\n }\n if (oldVersion < 3) {\n upgradeSchemaV3(db);\n }\n // Expand as needed.\n };\n\n req.onblocked = () => {\n logger.log(\n `can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`,\n );\n };\n\n logger.log(\n `LocalIndexedDBStoreBackend.connect: awaiting connection...`,\n );\n return reqAsEventPromise(req).then((ev) => {\n logger.log(\n `LocalIndexedDBStoreBackend.connect: connected`,\n );\n this.db = ev.target.result;\n\n // add a poorly-named listener for when deleteDatabase is called\n // so we can close our db connections.\n this.db.onversionchange = () => {\n this.db.close();\n };\n\n return this._init();\n });\n },\n /** @return {bool} whether or not the database was newly created in this session. */\n isNewlyCreated: function() {\n return Promise.resolve(this._isNewlyCreated);\n },\n\n /**\n * Having connected, load initial data from the database and prepare for use\n * @return {Promise} Resolves on success\n */\n _init: function() {\n return Promise.all([\n this._loadAccountData(),\n this._loadSyncData(),\n ]).then(([accountData, syncData]) => {\n logger.log(\n `LocalIndexedDBStoreBackend: loaded initial data`,\n );\n this._syncAccumulator.accumulate({\n next_batch: syncData.nextBatch,\n rooms: syncData.roomsData,\n groups: syncData.groupsData,\n account_data: {\n events: accountData,\n },\n }, true);\n });\n },\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @param {string} roomId\n * @returns {Promise<event[]>} the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns {null} in case the members for this room haven't been stored yet\n */\n getOutOfBandMembers: function(roomId) {\n return new Promise((resolve, reject) =>{\n const tx = this.db.transaction([\"oob_membership_events\"], \"readonly\");\n const store = tx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const range = IDBKeyRange.only(roomId);\n const request = roomIndex.openCursor(range);\n\n const membershipEvents = [];\n // did we encounter the oob_written marker object\n // amongst the results? That means OOB member\n // loading already happened for this room\n // but there were no members to persist as they\n // were all known already\n let oobWritten = false;\n\n request.onsuccess = (event) => {\n const cursor = event.target.result;\n if (!cursor) {\n // Unknown room\n if (!membershipEvents.length && !oobWritten) {\n return resolve(null);\n }\n return resolve(membershipEvents);\n }\n const record = cursor.value;\n if (record.oob_written) {\n oobWritten = true;\n } else {\n membershipEvents.push(record);\n }\n cursor.continue();\n };\n request.onerror = (err) => {\n reject(err);\n };\n }).then((events) => {\n logger.log(`LL: got ${events && events.length}` +\n ` membershipEvents from storage for room ${roomId} ...`);\n return events;\n });\n },\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param {string} roomId\n * @param {event[]} membershipEvents the membership events to store\n */\n setOutOfBandMembers: async function(roomId, membershipEvents) {\n logger.log(`LL: backend about to store ${membershipEvents.length}` +\n ` members for ${roomId}`);\n const tx = this.db.transaction([\"oob_membership_events\"], \"readwrite\");\n const store = tx.objectStore(\"oob_membership_events\");\n membershipEvents.forEach((e) => {\n store.put(e);\n });\n // aside from all the events, we also write a marker object to the store\n // to mark the fact that OOB members have been written for this room.\n // It's possible that 0 members need to be written as all where previously know\n // but we still need to know whether to return null or [] from getOutOfBandMembers\n // where null means out of band members haven't been stored yet for this room\n const markerObject = {\n room_id: roomId,\n oob_written: true,\n state_key: 0,\n };\n store.put(markerObject);\n await txnAsPromise(tx);\n logger.log(`LL: backend done storing for ${roomId}!`);\n },\n\n clearOutOfBandMembers: async function(roomId) {\n // the approach to delete all members for a room\n // is to get the min and max state key from the index\n // for that room, and then delete between those\n // keys in the store.\n // this should be way faster than deleting every member\n // individually for a large room.\n const readTx = this.db.transaction(\n [\"oob_membership_events\"],\n \"readonly\");\n const store = readTx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const roomRange = IDBKeyRange.only(roomId);\n\n const minStateKeyProm = reqAsCursorPromise(\n roomIndex.openKeyCursor(roomRange, \"next\"),\n ).then((cursor) => cursor && cursor.primaryKey[1]);\n const maxStateKeyProm = reqAsCursorPromise(\n roomIndex.openKeyCursor(roomRange, \"prev\"),\n ).then((cursor) => cursor && cursor.primaryKey[1]);\n const [minStateKey, maxStateKey] = await Promise.all(\n [minStateKeyProm, maxStateKeyProm]);\n\n const writeTx = this.db.transaction(\n [\"oob_membership_events\"],\n \"readwrite\");\n const writeStore = writeTx.objectStore(\"oob_membership_events\");\n const membersKeyRange = IDBKeyRange.bound(\n [roomId, minStateKey],\n [roomId, maxStateKey],\n );\n\n logger.log(`LL: Deleting all users + marker in storage for ` +\n `room ${roomId}, with key range:`,\n [roomId, minStateKey], [roomId, maxStateKey]);\n await reqAsPromise(writeStore.delete(membersKeyRange));\n },\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts.\n * @return {Promise} Resolved when the database is cleared.\n */\n clearDatabase: function() {\n return new Promise((resolve, reject) => {\n logger.log(`Removing indexeddb instance: ${this._dbName}`);\n const req = this.indexedDB.deleteDatabase(this._dbName);\n\n req.onblocked = () => {\n logger.log(\n `can't yet delete indexeddb ${this._dbName}` +\n ` because it is open elsewhere`,\n );\n };\n\n req.onerror = (ev) => {\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that we can still\n // use the app.\n logger.warn(\n `unable to delete js-sdk store indexeddb: ${ev.target.error}`,\n );\n resolve();\n };\n\n req.onsuccess = () => {\n logger.log(`Removed indexeddb instance: ${this._dbName}`);\n resolve();\n };\n });\n },\n\n /**\n * @param {boolean=} copy If false, the data returned is from internal\n * buffers and must not be mutated. Otherwise, a copy is made before\n * returning such that the data can be safely mutated. Default: true.\n *\n * @return {Promise} Resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n getSavedSync: function(copy) {\n if (copy === undefined) copy = true;\n\n const data = this._syncAccumulator.getJSON();\n if (!data.nextBatch) return Promise.resolve(null);\n if (copy) {\n // We must deep copy the stored data so that the /sync processing code doesn't\n // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n return Promise.resolve(utils.deepCopy(data));\n } else {\n return Promise.resolve(data);\n }\n },\n\n getNextBatchToken: function() {\n return Promise.resolve(this._syncAccumulator.getNextBatchToken());\n },\n\n setSyncData: function(syncData) {\n return Promise.resolve().then(() => {\n this._syncAccumulator.accumulate(syncData);\n });\n },\n\n syncToDatabase: function(userTuples) {\n const syncData = this._syncAccumulator.getJSON(true);\n\n return Promise.all([\n this._persistUserPresenceEvents(userTuples),\n this._persistAccountData(syncData.accountData),\n this._persistSyncData(\n syncData.nextBatch, syncData.roomsData, syncData.groupsData,\n ),\n ]);\n },\n\n /**\n * Persist rooms /sync data along with the next batch token.\n * @param {string} nextBatch The next_batch /sync value.\n * @param {Object} roomsData The 'rooms' /sync data from a SyncAccumulator\n * @param {Object} groupsData The 'groups' /sync data from a SyncAccumulator\n * @return {Promise} Resolves if the data was persisted.\n */\n _persistSyncData: function(nextBatch, roomsData, groupsData) {\n logger.log(\"Persisting sync data up to\", nextBatch);\n return utils.promiseTry(() => {\n const txn = this.db.transaction([\"sync\"], \"readwrite\");\n const store = txn.objectStore(\"sync\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n nextBatch: nextBatch,\n roomsData: roomsData,\n groupsData: groupsData,\n }); // put == UPSERT\n return txnAsPromise(txn);\n });\n },\n\n /**\n * Persist a list of account data events. Events with the same 'type' will\n * be replaced.\n * @param {Object[]} accountData An array of raw user-scoped account data events\n * @return {Promise} Resolves if the events were persisted.\n */\n _persistAccountData: function(accountData) {\n return utils.promiseTry(() => {\n const txn = this.db.transaction([\"accountData\"], \"readwrite\");\n const store = txn.objectStore(\"accountData\");\n for (let i = 0; i < accountData.length; i++) {\n store.put(accountData[i]); // put == UPSERT\n }\n return txnAsPromise(txn);\n });\n },\n\n /**\n * Persist a list of [user id, presence event] they are for.\n * Users with the same 'userId' will be replaced.\n * Presence events should be the event in its raw form (not the Event\n * object)\n * @param {Object[]} tuples An array of [userid, event] tuples\n * @return {Promise} Resolves if the users were persisted.\n */\n _persistUserPresenceEvents: function(tuples) {\n return utils.promiseTry(() => {\n const txn = this.db.transaction([\"users\"], \"readwrite\");\n const store = txn.objectStore(\"users\");\n for (const tuple of tuples) {\n store.put({\n userId: tuple[0],\n event: tuple[1],\n }); // put == UPSERT\n }\n return txnAsPromise(txn);\n });\n },\n\n /**\n * Load all user presence events from the database. This is not cached.\n * FIXME: It would probably be more sensible to store the events in the\n * sync.\n * @return {Promise<Object[]>} A list of presence events in their raw form.\n */\n getUserPresenceEvents: function() {\n return utils.promiseTry(() => {\n const txn = this.db.transaction([\"users\"], \"readonly\");\n const store = txn.objectStore(\"users\");\n return selectQuery(store, undefined, (cursor) => {\n return [cursor.value.userId, cursor.value.event];\n });\n });\n },\n\n /**\n * Load all the account data events from the database. This is not cached.\n * @return {Promise<Object[]>} A list of raw global account events.\n */\n _loadAccountData: function() {\n logger.log(\n `LocalIndexedDBStoreBackend: loading account data...`,\n );\n return utils.promiseTry(() => {\n const txn = this.db.transaction([\"accountData\"], \"readonly\");\n const store = txn.objectStore(\"accountData\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((result) => {\n logger.log(\n `LocalIndexedDBStoreBackend: loaded account data`,\n );\n return result;\n });\n });\n },\n\n /**\n * Load the sync data from the database.\n * @return {Promise<Object>} An object with \"roomsData\" and \"nextBatch\" keys.\n */\n _loadSyncData: function() {\n logger.log(\n `LocalIndexedDBStoreBackend: loading sync data...`,\n );\n return utils.promiseTry(() => {\n const txn = this.db.transaction([\"sync\"], \"readonly\");\n const store = txn.objectStore(\"sync\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((results) => {\n logger.log(\n `LocalIndexedDBStoreBackend: loaded sync data`,\n );\n if (results.length > 1) {\n logger.warn(\"loadSyncData: More than 1 sync row found.\");\n }\n return (results.length > 0 ? results[0] : {});\n });\n });\n },\n\n getClientOptions: function() {\n return Promise.resolve().then(() => {\n const txn = this.db.transaction([\"client_options\"], \"readonly\");\n const store = txn.objectStore(\"client_options\");\n return selectQuery(store, undefined, (cursor) => {\n if (cursor.value && cursor.value && cursor.value.options) {\n return cursor.value.options;\n }\n }).then((results) => results[0]);\n });\n },\n\n storeClientOptions: async function(options) {\n const txn = this.db.transaction([\"client_options\"], \"readwrite\");\n const store = txn.objectStore(\"client_options\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n options: options,\n }); // put == UPSERT\n await txnAsPromise(txn);\n },\n};\n",
"/*\nCopyright 2017 Vector Creations Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from '../logger';\nimport { defer } from '../utils';\n\n/**\n * An IndexedDB store backend where the actual backend sits in a web\n * worker.\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * <code>connect()</code> before this store can be used.\n * @constructor\n * @param {string} workerScript URL to the worker script\n * @param {string=} dbName Optional database name. The same name must be used\n * to open the same database.\n * @param {Object} workerApi The web worker compatible interface object\n */\nexport function RemoteIndexedDBStoreBackend(\n workerScript, dbName, workerApi,\n) {\n this._workerScript = workerScript;\n this._dbName = dbName;\n this._workerApi = workerApi;\n this._worker = null;\n this._nextSeq = 0;\n // The currently in-flight requests to the actual backend\n this._inFlight = {\n // seq: promise,\n };\n // Once we start connecting, we keep the promise and re-use it\n // if we try to connect again\n this._startPromise = null;\n}\n\nRemoteIndexedDBStoreBackend.prototype = {\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @return {Promise} Resolves if successfully connected.\n */\n connect: function() {\n return this._ensureStarted().then(() => this._doCmd('connect'));\n },\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts.\n * @return {Promise} Resolved when the database is cleared.\n */\n clearDatabase: function() {\n return this._ensureStarted().then(() => this._doCmd('clearDatabase'));\n },\n /** @return {Promise<bool>} whether or not the database was newly created in this session. */\n isNewlyCreated: function() {\n return this._doCmd('isNewlyCreated');\n },\n /**\n * @return {Promise} Resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n getSavedSync: function() {\n return this._doCmd('getSavedSync');\n },\n\n getNextBatchToken: function() {\n return this._doCmd('getNextBatchToken');\n },\n\n setSyncData: function(syncData) {\n return this._doCmd('setSyncData', [syncData]);\n },\n\n syncToDatabase: function(users) {\n return this._doCmd('syncToDatabase', [users]);\n },\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @param {string} roomId\n * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns {null} in case the members for this room haven't been stored yet\n */\n getOutOfBandMembers: function(roomId) {\n return this._doCmd('getOutOfBandMembers', [roomId]);\n },\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param {string} roomId\n * @param {event[]} membershipEvents the membership events to store\n * @returns {Promise} when all members have been stored\n */\n setOutOfBandMembers: function(roomId, membershipEvents) {\n return this._doCmd('setOutOfBandMembers', [roomId, membershipEvents]);\n },\n\n clearOutOfBandMembers: function(roomId) {\n return this._doCmd('clearOutOfBandMembers', [roomId]);\n },\n\n getClientOptions: function() {\n return this._doCmd('getClientOptions');\n },\n\n storeClientOptions: function(options) {\n return this._doCmd('storeClientOptions', [options]);\n },\n\n /**\n * Load all user presence events from the database. This is not cached.\n * @return {Promise<Object[]>} A list of presence events in their raw form.\n */\n getUserPresenceEvents: function() {\n return this._doCmd('getUserPresenceEvents');\n },\n\n _ensureStarted: function() {\n if (this._startPromise === null) {\n this._worker = new this._workerApi(this._workerScript);\n this._worker.onmessage = this._onWorkerMessage.bind(this);\n\n // tell the worker the db name.\n this._startPromise = this._doCmd('_setupWorker', [this._dbName]).then(() => {\n logger.log(\"IndexedDB worker is ready\");\n });\n }\n return this._startPromise;\n },\n\n _doCmd: function(cmd, args) {\n // wrap in a q so if the postMessage throws,\n // the promise automatically gets rejected\n return Promise.resolve().then(() => {\n const seq = this._nextSeq++;\n const def = defer();\n\n this._inFlight[seq] = def;\n\n this._worker.postMessage({\n command: cmd,\n seq: seq,\n args: args,\n });\n\n return def.promise;\n });\n },\n\n _onWorkerMessage: function(ev) {\n const msg = ev.data;\n\n if (msg.command == 'cmd_success' || msg.command == 'cmd_fail') {\n if (msg.seq === undefined) {\n logger.error(\"Got reply from worker with no seq\");\n return;\n }\n\n const def = this._inFlight[msg.seq];\n if (def === undefined) {\n logger.error(\"Got reply for unknown seq \" + msg.seq);\n return;\n }\n delete this._inFlight[msg.seq];\n\n if (msg.command == 'cmd_success') {\n def.resolve(msg.result);\n } else {\n const error = new Error(msg.error.message);\n error.name = msg.error.name;\n def.reject(error);\n }\n } else {\n logger.warn(\"Unrecognised message from worker: \" + msg);\n }\n },\n};\n",
"/*\nCopyright 2017 - 2021 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* eslint-disable @babel/no-invalid-this */\n\nimport { EventEmitter } from 'events';\n\nimport { MemoryStore, IOpts as IBaseOpts } from \"./memory\";\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend.js\";\nimport { RemoteIndexedDBStoreBackend } from \"./indexeddb-remote-backend.js\";\nimport { User } from \"../models/user\";\nimport { MatrixEvent } from \"../models/event\";\nimport { logger } from '../logger';\nimport { ISavedSync } from \"./index\";\n\n/**\n * This is an internal module. See {@link IndexedDBStore} for the public class.\n * @module store/indexeddb\n */\n\n// If this value is too small we'll be writing very often which will cause\n// noticeable stop-the-world pauses. If this value is too big we'll be writing\n// so infrequently that the /sync size gets bigger on reload. Writing more\n// often does not affect the length of the pause since the entire /sync\n// response is persisted each time.\nconst WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes\n\ninterface IOpts extends IBaseOpts {\n indexedDB: IDBFactory;\n dbName?: string;\n workerScript?: string;\n workerApi?: typeof Worker;\n}\n\nexport class IndexedDBStore extends MemoryStore {\n static exists(indexedDB: IDBFactory, dbName: string): boolean {\n return LocalIndexedDBStoreBackend.exists(indexedDB, dbName);\n }\n\n // TODO these should conform to one interface\n public readonly backend: LocalIndexedDBStoreBackend | RemoteIndexedDBStoreBackend;\n\n private startedUp = false;\n private syncTs = 0;\n // Records the last-modified-time of each user at the last point we saved\n // the database, such that we can derive the set if users that have been\n // modified since we last saved.\n private userModifiedMap: Record<string, number> = {}; // user_id : timestamp\n private emitter = new EventEmitter();\n\n /**\n * Construct a new Indexed Database store, which extends MemoryStore.\n *\n * This store functions like a MemoryStore except it periodically persists\n * the contents of the store to an IndexedDB backend.\n *\n * All data is still kept in-memory but can be loaded from disk by calling\n * <code>startup()</code>. This can make startup times quicker as a complete\n * sync from the server is not required. This does not reduce memory usage as all\n * the data is eagerly fetched when <code>startup()</code> is called.\n * <pre>\n * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage };\n * let store = new IndexedDBStore(opts);\n * await store.startup(); // load from indexed db\n * let client = sdk.createClient({\n * store: store,\n * });\n * client.startClient();\n * client.on(\"sync\", function(state, prevState, data) {\n * if (state === \"PREPARED\") {\n * console.log(\"Started up, now with go faster stripes!\");\n * }\n * });\n * </pre>\n *\n * @constructor\n * @extends MemoryStore\n * @param {Object} opts Options object.\n * @param {Object} opts.indexedDB The Indexed DB interface e.g.\n * <code>window.indexedDB</code>\n * @param {string=} opts.dbName Optional database name. The same name must be used\n * to open the same database.\n * @param {string=} opts.workerScript Optional URL to a script to invoke a web\n * worker with to run IndexedDB queries on the web worker. The IndexedDbStoreWorker\n * class is provided for this purpose and requires the application to provide a\n * trivial wrapper script around it.\n * @param {Object=} opts.workerApi The webWorker API object. If omitted, the global Worker\n * object will be used if it exists.\n * @prop {IndexedDBStoreBackend} backend The backend instance. Call through to\n * this API if you need to perform specific indexeddb actions like deleting the\n * database.\n */\n constructor(opts: IOpts) {\n super(opts);\n\n if (!opts.indexedDB) {\n throw new Error('Missing required option: indexedDB');\n }\n\n if (opts.workerScript) {\n // try & find a webworker-compatible API\n let workerApi = opts.workerApi;\n if (!workerApi) {\n // default to the global Worker object (which is where it in a browser)\n workerApi = global.Worker;\n }\n this.backend = new RemoteIndexedDBStoreBackend(\n opts.workerScript, opts.dbName, workerApi,\n );\n } else {\n this.backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);\n }\n }\n\n public on = this.emitter.on.bind(this.emitter);\n\n /**\n * @return {Promise} Resolved when loaded from indexed db.\n */\n public startup(): Promise<void> {\n if (this.startedUp) {\n logger.log(`IndexedDBStore.startup: already started`);\n return Promise.resolve();\n }\n\n logger.log(`IndexedDBStore.startup: connecting to backend`);\n return this.backend.connect().then(() => {\n logger.log(`IndexedDBStore.startup: loading presence events`);\n return this.backend.getUserPresenceEvents();\n }).then((userPresenceEvents) => {\n logger.log(`IndexedDBStore.startup: processing presence events`);\n userPresenceEvents.forEach(([userId, rawEvent]) => {\n const u = new User(userId);\n if (rawEvent) {\n u.setPresenceEvent(new MatrixEvent(rawEvent));\n }\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n this.storeUser(u);\n });\n });\n }\n\n /**\n * @return {Promise} Resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync = this.degradable((): Promise<ISavedSync> => {\n return this.backend.getSavedSync();\n }, \"getSavedSync\");\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated = this.degradable((): Promise<boolean> => {\n return this.backend.isNewlyCreated();\n }, \"isNewlyCreated\");\n\n /**\n * @return {Promise} If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken = this.degradable((): Promise<string | null> => {\n return this.backend.getNextBatchToken();\n }, \"getSavedSyncToken\");\n\n /**\n * Delete all data from this store.\n * @return {Promise} Resolves if the data was deleted from the database.\n */\n public deleteAllData = this.degradable((): Promise<void> => {\n super.deleteAllData();\n return this.backend.clearDatabase().then(() => {\n logger.log(\"Deleted indexeddb data.\");\n }, (err) => {\n logger.error(`Failed to delete indexeddb data: ${err}`);\n throw err;\n });\n });\n\n /**\n * Whether this store would like to save its data\n * Note that obviously whether the store wants to save or\n * not could change between calling this function and calling\n * save().\n *\n * @return {boolean} True if calling save() will actually save\n * (at the time this function is called).\n */\n public wantsSave(): boolean {\n const now = Date.now();\n return now - this.syncTs > WRITE_DELAY_MS;\n }\n\n /**\n * Possibly write data to the database.\n *\n * @param {boolean} force True to force a save to happen\n * @return {Promise} Promise resolves after the write completes\n * (or immediately if no write is performed)\n */\n public save(force = false): Promise<void> {\n if (force || this.wantsSave()) {\n return this.reallySave();\n }\n return Promise.resolve();\n }\n\n private reallySave = this.degradable((): Promise<void> => {\n this.syncTs = Date.now(); // set now to guard against multi-writes\n\n // work out changed users (this doesn't handle deletions but you\n // can't 'delete' users as they are just presence events).\n const userTuples = [];\n for (const u of this.getUsers()) {\n if (this.userModifiedMap[u.userId] === u.getLastModifiedTime()) continue;\n if (!u.events.presence) continue;\n\n userTuples.push([u.userId, u.events.presence.event]);\n\n // note that we've saved this version of the user\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n }\n\n return this.backend.syncToDatabase(userTuples);\n });\n\n public setSyncData = this.degradable((syncData: object): Promise<void> => {\n return this.backend.setSyncData(syncData);\n }, \"setSyncData\");\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @param {string} roomId\n * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns {null} in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers = this.degradable((roomId: string): Promise<MatrixEvent[]> => {\n return this.backend.getOutOfBandMembers(roomId);\n }, \"getOutOfBandMembers\");\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param {string} roomId\n * @param {event[]} membershipEvents the membership events to store\n * @returns {Promise} when all members have been stored\n */\n public setOutOfBandMembers = this.degradable((roomId: string, membershipEvents: MatrixEvent[]): Promise<void> => {\n super.setOutOfBandMembers(roomId, membershipEvents);\n return this.backend.setOutOfBandMembers(roomId, membershipEvents);\n }, \"setOutOfBandMembers\");\n\n public clearOutOfBandMembers = this.degradable((roomId: string) => {\n super.clearOutOfBandMembers(roomId);\n return this.backend.clearOutOfBandMembers(roomId);\n }, \"clearOutOfBandMembers\");\n\n public getClientOptions = this.degradable((): Promise<object> => {\n return this.backend.getClientOptions();\n }, \"getClientOptions\");\n\n public storeClientOptions = this.degradable((options: object): Promise<void> => {\n super.storeClientOptions(options);\n return this.backend.storeClientOptions(options);\n }, \"storeClientOptions\");\n\n /**\n * All member functions of `IndexedDBStore` that access the backend use this wrapper to\n * watch for failures after initial store startup, including `QuotaExceededError` as\n * free disk space changes, etc.\n *\n * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore`\n * in place so that the current operation and all future ones are in-memory only.\n *\n * @param {Function} func The degradable work to do.\n * @param {String} fallback The method name for fallback.\n * @returns {Function} A wrapped member function.\n */\n private degradable<A extends Array<any>, R = void>(\n func: DegradableFn<A, R>,\n fallback?: string,\n ): DegradableFn<A, R> {\n const fallbackFn = super[fallback];\n\n return async (...args) => {\n try {\n return func.call(this, ...args);\n } catch (e) {\n logger.error(\"IndexedDBStore failure, degrading to MemoryStore\", e);\n this.emitter.emit(\"degraded\", e);\n try {\n // We try to delete IndexedDB after degrading since this store is only a\n // cache (the app will still function correctly without the data).\n // It's possible that deleting repair IndexedDB for the next app load,\n // potentially by making a little more space available.\n logger.log(\"IndexedDBStore trying to delete degraded data\");\n await this.backend.clearDatabase();\n logger.log(\"IndexedDBStore delete after degrading succeeded\");\n } catch (e) {\n logger.warn(\"IndexedDBStore delete after degrading failed\", e);\n }\n // Degrade the store from being an instance of `IndexedDBStore` to instead be\n // an instance of `MemoryStore` so that future API calls use the memory path\n // directly and skip IndexedDB entirely. This should be safe as\n // `IndexedDBStore` already extends from `MemoryStore`, so we are making the\n // store become its parent type in a way. The mutator methods of\n // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are\n // not overridden at all).\n if (fallbackFn) {\n return fallbackFn(...args);\n }\n }\n };\n }\n}\n\ntype DegradableFn<A extends Array<any>, T> = (...args: A) => Promise<T>;\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MemoryStore} for the public class.\n * @module store/memory\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Group } from \"../models/group\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { MatrixEvent } from \"../models/event\";\nimport { RoomState } from \"../models/room-state\";\nimport { RoomMember } from \"../models/room-member\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\n\nfunction isValidFilterId(filterId: string): boolean {\n const isValidStr = typeof filterId === \"string\" &&\n !!filterId &&\n filterId !== \"undefined\" && // exclude these as we've serialized undefined in localStorage before\n filterId !== \"null\";\n\n return isValidStr || typeof filterId === \"number\";\n}\n\nexport interface IOpts {\n localStorage?: Storage;\n}\n\n/**\n * Construct a new in-memory data store for the Matrix Client.\n * @constructor\n * @param {Object=} opts Config options\n * @param {LocalStorage} opts.localStorage The local storage instance to persist\n * some forms of data such as tokens. Rooms will NOT be stored.\n */\nexport class MemoryStore implements IStore {\n private rooms: Record<string, Room> = {}; // roomId: Room\n private groups: Record<string, Group> = {}; // groupId: Group\n private users: Record<string, User> = {}; // userId: User\n private syncToken: string = null;\n // userId: {\n // filterId: Filter\n // }\n private filters: Record<string, Record<string, Filter>> = {};\n private accountData: Record<string, MatrixEvent> = {}; // type : content\n private readonly localStorage: Storage;\n private oobMembers: Record<string, MatrixEvent[]> = {}; // roomId: [member events]\n private clientOptions = {};\n\n constructor(opts: IOpts = {}) {\n this.localStorage = opts.localStorage;\n }\n\n /**\n * Retrieve the token to stream from.\n * @return {string} The token or null.\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /** @return {Promise<boolean>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Set the token to stream from.\n * @param {string} token The token to stream from.\n */\n public setSyncToken(token: string) {\n this.syncToken = token;\n }\n\n /**\n * Store the given room.\n * @param {Group} group The group to be stored\n */\n public storeGroup(group: Group) {\n this.groups[group.groupId] = group;\n }\n\n /**\n * Retrieve a group by its group ID.\n * @param {string} groupId The group ID.\n * @return {Group} The group or null.\n */\n public getGroup(groupId: string): Group | null {\n return this.groups[groupId] || null;\n }\n\n /**\n * Retrieve all known groups.\n * @return {Group[]} A list of groups, which may be empty.\n */\n public getGroups(): Group[] {\n return Object.values(this.groups);\n }\n\n /**\n * Store the given room.\n * @param {Room} room The room to be stored. All properties must be stored.\n */\n public storeRoom(room: Room) {\n this.rooms[room.roomId] = room;\n // add listeners for room member changes so we can keep the room member\n // map up-to-date.\n room.currentState.on(\"RoomState.members\", this.onRoomMember);\n // add existing members\n room.currentState.getMembers().forEach((m) => {\n this.onRoomMember(null, room.currentState, m);\n });\n }\n\n /**\n * Called when a room member in a room being tracked by this store has been\n * updated.\n * @param {MatrixEvent} event\n * @param {RoomState} state\n * @param {RoomMember} member\n */\n private onRoomMember = (event: MatrixEvent, state: RoomState, member: RoomMember) => {\n if (member.membership === \"invite\") {\n // We do NOT add invited members because people love to typo user IDs\n // which would then show up in these lists (!)\n return;\n }\n\n const user = this.users[member.userId] || new User(member.userId);\n if (member.name) {\n user.setDisplayName(member.name);\n if (member.events.member) {\n user.setRawDisplayName(\n member.events.member.getDirectionalContent().displayname,\n );\n }\n }\n if (member.events.member && member.events.member.getContent().avatar_url) {\n user.setAvatarUrl(member.events.member.getContent().avatar_url);\n }\n this.users[user.userId] = user;\n };\n\n /**\n * Retrieve a room by its' room ID.\n * @param {string} roomId The room ID.\n * @return {Room} The room or null.\n */\n public getRoom(roomId: string): Room | null {\n return this.rooms[roomId] || null;\n }\n\n /**\n * Retrieve all known rooms.\n * @return {Room[]} A list of rooms, which may be empty.\n */\n public getRooms(): Room[] {\n return Object.values(this.rooms);\n }\n\n /**\n * Permanently delete a room.\n * @param {string} roomId\n */\n public removeRoom(roomId: string): void {\n if (this.rooms[roomId]) {\n this.rooms[roomId].removeListener(\"RoomState.members\", this.onRoomMember);\n }\n delete this.rooms[roomId];\n }\n\n /**\n * Retrieve a summary of all the rooms.\n * @return {RoomSummary[]} A summary of each room.\n */\n public getRoomSummaries(): RoomSummary[] {\n return Object.values(this.rooms).map(function(room) {\n return room.summary;\n });\n }\n\n /**\n * Store a User.\n * @param {User} user The user to store.\n */\n public storeUser(user: User): void {\n this.users[user.userId] = user;\n }\n\n /**\n * Retrieve a User by its' user ID.\n * @param {string} userId The user ID.\n * @return {User} The user or null.\n */\n public getUser(userId: string): User | null {\n return this.users[userId] || null;\n }\n\n /**\n * Retrieve all known users.\n * @return {User[]} A list of users, which may be empty.\n */\n public getUsers(): User[] {\n return Object.values(this.users);\n }\n\n /**\n * Retrieve scrollback for this room.\n * @param {Room} room The matrix room\n * @param {integer} limit The max number of old events to retrieve.\n * @return {Array<Object>} An array of objects which will be at most 'limit'\n * length and at least 0. The objects are the raw event JSON.\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room. The events have already been added to the timeline\n * @param {Room} room The room to store events for.\n * @param {Array<MatrixEvent>} events The events to store.\n * @param {string} token The token associated with these events.\n * @param {boolean} toStart True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string, toStart: boolean) {\n // no-op because they've already been added to the room instance.\n }\n\n /**\n * Store a filter.\n * @param {Filter} filter\n */\n public storeFilter(filter: Filter): void {\n if (!filter) {\n return;\n }\n if (!this.filters[filter.userId]) {\n this.filters[filter.userId] = {};\n }\n this.filters[filter.userId][filter.filterId] = filter;\n }\n\n /**\n * Retrieve a filter.\n * @param {string} userId\n * @param {string} filterId\n * @return {?Filter} A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n if (!this.filters[userId] || !this.filters[userId][filterId]) {\n return null;\n }\n return this.filters[userId][filterId];\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param {string} filterName The filter name.\n * @return {?string} The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n if (!this.localStorage) {\n return null;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n // XXX Storage.getItem doesn't throw ...\n // or are we using something different\n // than window.localStorage in some cases\n // that does throw?\n // that would be very naughty\n try {\n const value = this.localStorage.getItem(key);\n if (isValidFilterId(value)) {\n return value;\n }\n } catch (e) {}\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n * @param {string} filterName\n * @param {string} filterId\n */\n public setFilterIdByName(filterName: string, filterId: string) {\n if (!this.localStorage) {\n return;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n try {\n if (isValidFilterId(filterId)) {\n this.localStorage.setItem(key, filterId);\n } else {\n this.localStorage.removeItem(key);\n }\n } catch (e) {}\n }\n\n /**\n * Store user-scoped account data events.\n * N.B. that account data only allows a single event per type, so multiple\n * events with the same type will replace each other.\n * @param {Array<MatrixEvent>} events The events to store.\n */\n public storeAccountDataEvents(events: MatrixEvent[]): void {\n events.forEach((event) => {\n this.accountData[event.getType()] = event;\n });\n }\n\n /**\n * Get account data event by event type\n * @param {string} eventType The event type being queried\n * @return {?MatrixEvent} the user account_data event of given type, if any\n */\n public getAccountData(eventType: EventType | string): MatrixEvent | undefined {\n return this.accountData[eventType];\n }\n\n /**\n * setSyncData does nothing as there is no backing data store.\n *\n * @param {Object} syncData The sync data\n * @return {Promise} An immediately resolved promise.\n */\n public setSyncData(syncData: object): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * We never want to save becase we have nothing to save to.\n *\n * @return {boolean} If the store wants to save\n */\n public wantsSave(): boolean {\n return false;\n }\n\n /**\n * Save does nothing as there is no backing data store.\n * @param {bool} force True to force a save (but the memory\n * store still can't save anything)\n */\n public save(force: boolean): void {}\n\n /**\n * Startup does nothing as this store doesn't require starting up.\n * @return {Promise} An immediately resolved promise.\n */\n public startup(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * @return {Promise} Resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise<ISavedSync> {\n return Promise.resolve(null);\n }\n\n /**\n * @return {Promise} If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken(): Promise<string | null> {\n return Promise.resolve(null);\n }\n\n /**\n * Delete all data from this store.\n * @return {Promise} An immediately resolved promise.\n */\n public deleteAllData(): Promise<void> {\n this.rooms = {\n // roomId: Room\n };\n this.users = {\n // userId: User\n };\n this.syncToken = null;\n this.filters = {\n // userId: {\n // filterId: Filter\n // }\n };\n this.accountData = {\n // type : content\n };\n return Promise.resolve();\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @param {string} roomId\n * @returns {event[]} the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns {null} in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise<MatrixEvent[] | null> {\n return Promise.resolve(this.oobMembers[roomId] || null);\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param {string} roomId\n * @param {event[]} membershipEvents the membership events to store\n * @returns {Promise} when all members have been stored\n */\n public setOutOfBandMembers(roomId: string, membershipEvents: MatrixEvent[]): Promise<void> {\n this.oobMembers[roomId] = membershipEvents;\n return Promise.resolve();\n }\n\n public clearOutOfBandMembers(roomId: string): Promise<void> {\n this.oobMembers = {};\n return Promise.resolve();\n }\n\n public getClientOptions(): Promise<object> {\n return Promise.resolve(this.clientOptions);\n }\n\n public storeClientOptions(options: object): Promise<void> {\n this.clientOptions = Object.assign({}, options);\n return Promise.resolve();\n }\n}\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @module store/session/webstorage\n */\n\nimport * as utils from \"../../utils\";\nimport { logger } from '../../logger';\n\nconst DEBUG = false; // set true to enable console logging.\nconst E2E_PREFIX = \"session.e2e.\";\n\n/**\n * Construct a web storage session store, capable of storing account keys,\n * session keys and access tokens.\n * @constructor\n * @param {WebStorage} webStore A web storage implementation, e.g.\n * 'window.localStorage' or 'window.sessionStorage' or a custom implementation.\n * @throws if the supplied 'store' does not meet the Storage interface of the\n * WebStorage API.\n */\nexport function WebStorageSessionStore(webStore) {\n this.store = webStore;\n if (!utils.isFunction(webStore.getItem) ||\n !utils.isFunction(webStore.setItem) ||\n !utils.isFunction(webStore.removeItem) ||\n !utils.isFunction(webStore.key) ||\n typeof(webStore.length) !== 'number'\n ) {\n throw new Error(\n \"Supplied webStore does not meet the WebStorage API interface\",\n );\n }\n}\n\nWebStorageSessionStore.prototype = {\n /**\n * Remove the stored end to end account for the logged-in user.\n */\n removeEndToEndAccount: function() {\n this.store.removeItem(KEY_END_TO_END_ACCOUNT);\n },\n\n /**\n * Load the end to end account for the logged-in user.\n * Note that the end-to-end account is now stored in the\n * crypto store rather than here: this remains here so\n * old sessions can be migrated out of the session store.\n * @return {?string} Base64 encoded account.\n */\n getEndToEndAccount: function() {\n return this.store.getItem(KEY_END_TO_END_ACCOUNT);\n },\n\n /**\n * Retrieves the known devices for all users.\n * @return {object} A map from user ID to map of device ID to keys for the device.\n */\n getAllEndToEndDevices: function() {\n const prefix = keyEndToEndDevicesForUser('');\n const devices = {};\n for (let i = 0; i < this.store.length; ++i) {\n const key = this.store.key(i);\n const userId = key.substr(prefix.length);\n if (key.startsWith(prefix)) devices[userId] = getJsonItem(this.store, key);\n }\n return devices;\n },\n\n getEndToEndDeviceTrackingStatus: function() {\n return getJsonItem(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS);\n },\n\n /**\n * Get the sync token corresponding to the device list.\n *\n * @return {String?} token\n */\n getEndToEndDeviceSyncToken: function() {\n return getJsonItem(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN);\n },\n\n /**\n * Removes all end to end device data from the store\n */\n removeEndToEndDeviceData: function() {\n removeByPrefix(this.store, keyEndToEndDevicesForUser(''));\n removeByPrefix(this.store, KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS);\n removeByPrefix(this.store, KEY_END_TO_END_DEVICE_SYNC_TOKEN);\n },\n\n /**\n * Retrieve the end-to-end sessions between the logged-in user and another\n * device.\n * @param {string} deviceKey The public key of the other device.\n * @return {object} A map from sessionId to Base64 end-to-end session.\n */\n getEndToEndSessions: function(deviceKey) {\n return getJsonItem(this.store, keyEndToEndSessions(deviceKey));\n },\n\n /**\n * Retrieve all end-to-end sessions between the logged-in user and other\n * devices.\n * @return {object} A map of {deviceKey -> {sessionId -> session pickle}}\n */\n getAllEndToEndSessions: function() {\n const deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions(''));\n const results = {};\n for (const k of deviceKeys) {\n const unprefixedKey = k.substr(keyEndToEndSessions('').length);\n results[unprefixedKey] = getJsonItem(this.store, k);\n }\n return results;\n },\n\n /**\n * Remove all end-to-end sessions from the store\n * This is used after migrating sessions awat from the sessions store.\n */\n removeAllEndToEndSessions: function() {\n removeByPrefix(this.store, keyEndToEndSessions(''));\n },\n\n /**\n * Retrieve a list of all known inbound group sessions\n *\n * @return {{senderKey: string, sessionId: string}}\n */\n getAllEndToEndInboundGroupSessionKeys: function() {\n const prefix = E2E_PREFIX + 'inboundgroupsessions/';\n const result = [];\n for (let i = 0; i < this.store.length; i++) {\n const key = this.store.key(i);\n if (!key.startsWith(prefix)) {\n continue;\n }\n // we can't use split, as the components we are trying to split out\n // might themselves contain '/' characters. We rely on the\n // senderKey being a (32-byte) curve25519 key, base64-encoded\n // (hence 43 characters long).\n\n result.push({\n senderKey: key.substr(prefix.length, 43),\n sessionId: key.substr(prefix.length + 44),\n });\n }\n return result;\n },\n\n getEndToEndInboundGroupSession: function(senderKey, sessionId) {\n const key = keyEndToEndInboundGroupSession(senderKey, sessionId);\n return this.store.getItem(key);\n },\n\n removeAllEndToEndInboundGroupSessions: function() {\n removeByPrefix(this.store, E2E_PREFIX + 'inboundgroupsessions/');\n },\n\n /**\n * Get the end-to-end state for all rooms\n * @return {object} roomId -> object with the end-to-end info for the room.\n */\n getAllEndToEndRooms: function() {\n const roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom(''));\n const results = {};\n for (const k of roomKeys) {\n const unprefixedKey = k.substr(keyEndToEndRoom('').length);\n results[unprefixedKey] = getJsonItem(this.store, k);\n }\n return results;\n },\n\n removeAllEndToEndRooms: function() {\n removeByPrefix(this.store, keyEndToEndRoom(''));\n },\n\n setLocalTrustedBackupPubKey: function(pubkey) {\n this.store.setItem(KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY, pubkey);\n },\n\n // XXX: This store is deprecated really, but added this as a temporary\n // thing until cross-signing lands.\n getLocalTrustedBackupPubKey: function() {\n return this.store.getItem(KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY);\n },\n};\n\nconst KEY_END_TO_END_ACCOUNT = E2E_PREFIX + \"account\";\nconst KEY_END_TO_END_DEVICE_SYNC_TOKEN = E2E_PREFIX + \"device_sync_token\";\nconst KEY_END_TO_END_DEVICE_LIST_TRACKING_STATUS = E2E_PREFIX + \"device_tracking\";\nconst KEY_END_TO_END_TRUSTED_BACKUP_PUBKEY = E2E_PREFIX + \"trusted_backup_pubkey\";\n\nfunction keyEndToEndDevicesForUser(userId) {\n return E2E_PREFIX + \"devices/\" + userId;\n}\n\nfunction keyEndToEndSessions(deviceKey) {\n return E2E_PREFIX + \"sessions/\" + deviceKey;\n}\n\nfunction keyEndToEndInboundGroupSession(senderKey, sessionId) {\n return E2E_PREFIX + \"inboundgroupsessions/\" + senderKey + \"/\" + sessionId;\n}\n\nfunction keyEndToEndRoom(roomId) {\n return E2E_PREFIX + \"rooms/\" + roomId;\n}\n\nfunction getJsonItem(store, key) {\n try {\n // if the key is absent, store.getItem() returns null, and\n // JSON.parse(null) === null, so this returns null.\n return JSON.parse(store.getItem(key));\n } catch (e) {\n debuglog(\"Failed to get key %s: %s\", key, e);\n debuglog(e.stack);\n }\n return null;\n}\n\nfunction getKeysWithPrefix(store, prefix) {\n const results = [];\n for (let i = 0; i < store.length; ++i) {\n const key = store.key(i);\n if (key.startsWith(prefix)) results.push(key);\n }\n return results;\n}\n\nfunction removeByPrefix(store, prefix) {\n const toRemove = [];\n for (let i = 0; i < store.length; ++i) {\n const key = store.key(i);\n if (key.startsWith(prefix)) toRemove.push(key);\n }\n for (const key of toRemove) {\n store.removeItem(key);\n }\n}\n\nfunction debuglog() {\n if (DEBUG) {\n logger.log(...arguments);\n }\n}\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n * @module store/stub\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Group } from \"../models/group\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { MatrixEvent } from \"../models/event\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\n\n/**\n * Construct a stub store. This does no-ops on most store methods.\n * @constructor\n */\nexport class StubStore implements IStore {\n private fromToken: string = null;\n\n /** @return {Promise<bool>} whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n /**\n * Get the sync token.\n * @return {string}\n */\n public getSyncToken(): string | null {\n return this.fromToken;\n }\n\n /**\n * Set the sync token.\n * @param {string} token\n */\n public setSyncToken(token: string) {\n this.fromToken = token;\n }\n\n /**\n * No-op.\n * @param {Group} group\n */\n public storeGroup(group: Group) {}\n\n /**\n * No-op.\n * @param {string} groupId\n * @return {null}\n */\n public getGroup(groupId: string): Group | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getGroups(): Group[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {Room} room\n */\n public storeRoom(room: Room) {}\n\n /**\n * No-op.\n * @param {string} roomId\n * @return {null}\n */\n public getRoom(roomId: string): Room | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getRooms(): Room[] {\n return [];\n }\n\n /**\n * Permanently delete a room.\n * @param {string} roomId\n */\n public removeRoom(roomId: string) {\n return;\n }\n\n /**\n * No-op.\n * @return {Array} An empty array.\n */\n public getRoomSummaries(): RoomSummary[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {User} user\n */\n public storeUser(user: User) {}\n\n /**\n * No-op.\n * @param {string} userId\n * @return {null}\n */\n public getUser(userId: string): User | null {\n return null;\n }\n\n /**\n * No-op.\n * @return {User[]}\n */\n public getUsers(): User[] {\n return [];\n }\n\n /**\n * No-op.\n * @param {Room} room\n * @param {integer} limit\n * @return {Array}\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room.\n * @param {Room} room The room to store events for.\n * @param {Array<MatrixEvent>} events The events to store.\n * @param {string} token The token associated with these events.\n * @param {boolean} toStart True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string, toStart: boolean) {}\n\n /**\n * Store a filter.\n * @param {Filter} filter\n */\n public storeFilter(filter: Filter) {}\n\n /**\n * Retrieve a filter.\n * @param {string} userId\n * @param {string} filterId\n * @return {?Filter} A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param {string} filterName The filter name.\n * @return {?string} The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n * @param {string} filterName\n * @param {string} filterId\n */\n public setFilterIdByName(filterName: string, filterId: string) {}\n\n /**\n * Store user-scoped account data events\n * @param {Array<MatrixEvent>} events The events to store.\n */\n public storeAccountDataEvents(events: MatrixEvent[]) {}\n\n /**\n * Get account data event by event type\n * @param {string} eventType The event type being queried\n */\n public getAccountData(eventType: EventType | string): MatrixEvent | undefined {\n return undefined;\n }\n\n /**\n * setSyncData does nothing as there is no backing data store.\n *\n * @param {Object} syncData The sync data\n * @return {Promise} An immediately resolved promise.\n */\n public setSyncData(syncData: object): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * We never want to save because we have nothing to save to.\n *\n * @return {boolean} If the store wants to save\n */\n public wantsSave(): boolean {\n return false;\n }\n\n /**\n * Save does nothing as there is no backing data store.\n */\n public save() {}\n\n /**\n * Startup does nothing.\n * @return {Promise} An immediately resolved promise.\n */\n public startup(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * @return {Promise} Resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise<ISavedSync> {\n return Promise.resolve(null);\n }\n\n /**\n * @return {Promise} If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken(): Promise<string | null> {\n return Promise.resolve(null);\n }\n\n /**\n * Delete all data from this store. Does nothing since this store\n * doesn't store anything.\n * @return {Promise} An immediately resolved promise.\n */\n public deleteAllData(): Promise<void> {\n return Promise.resolve();\n }\n\n public getOutOfBandMembers(): Promise<MatrixEvent[]> {\n return Promise.resolve(null);\n }\n\n public setOutOfBandMembers(roomId: string, membershipEvents: MatrixEvent[]): Promise<void> {\n return Promise.resolve();\n }\n\n public clearOutOfBandMembers(): Promise<void> {\n return Promise.resolve();\n }\n\n public getClientOptions(): Promise<object> {\n return Promise.resolve({});\n }\n\n public storeClientOptions(options: object): Promise<void> {\n return Promise.resolve();\n }\n}\n",
"/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link SyncAccumulator} for the public class.\n * @module sync-accumulator\n */\n\nimport { logger } from './logger';\nimport { deepCopy } from \"./utils\";\nimport { IContent, IUnsigned } from \"./models/event\";\nimport { IRoomSummary } from \"./models/room-summary\";\nimport { EventType } from \"./@types/event\";\n\ninterface IOpts {\n maxTimelineEntries?: number;\n}\n\nexport interface IMinimalEvent {\n content: IContent;\n type: EventType | string;\n}\n\nexport interface IEphemeral {\n events: IMinimalEvent[];\n}\n\n/* eslint-disable camelcase */\ninterface IUnreadNotificationCounts {\n highlight_count: number;\n notification_count: number;\n}\n\nexport interface IRoomEvent extends IMinimalEvent {\n event_id: string;\n sender: string;\n origin_server_ts: number;\n unsigned?: IUnsigned;\n /** @deprecated - legacy field */\n age?: number;\n}\n\nexport interface IStateEvent extends IRoomEvent {\n prev_content?: IContent;\n state_key: string;\n}\n\ninterface IState {\n events: IStateEvent[];\n}\n\nexport interface ITimeline {\n events: Array<IRoomEvent | IStateEvent>;\n limited: boolean;\n prev_batch: string;\n}\n\nexport interface IJoinedRoom {\n summary: IRoomSummary;\n state: IState;\n timeline: ITimeline;\n ephemeral: IEphemeral;\n account_data: IAccountData;\n unread_notifications: IUnreadNotificationCounts;\n}\n\nexport interface IStrippedState {\n content: IContent;\n state_key: string;\n type: EventType | string;\n sender: string;\n}\n\nexport interface IInviteState {\n events: IStrippedState[];\n}\n\nexport interface IInvitedRoom {\n invite_state: IInviteState;\n}\n\nexport interface ILeftRoom {\n state: IState;\n timeline: ITimeline;\n account_data: IAccountData;\n}\n\nexport interface IRooms {\n [Category.Join]: Record<string, IJoinedRoom>;\n [Category.Invite]: Record<string, IInvitedRoom>;\n [Category.Leave]: Record<string, ILeftRoom>;\n}\n\ninterface IPresence {\n events: IMinimalEvent[];\n}\n\ninterface IAccountData {\n events: IMinimalEvent[];\n}\n\ninterface IToDeviceEvent {\n content: IContent;\n sender: string;\n type: string;\n}\n\ninterface IToDevice {\n events: IToDeviceEvent[];\n}\n\ninterface IDeviceLists {\n changed: string[];\n left: string[];\n}\n\nexport interface IGroups {\n [Category.Join]: object;\n [Category.Invite]: object;\n [Category.Leave]: object;\n}\n\nexport interface ISyncResponse {\n next_batch: string;\n rooms: IRooms;\n presence?: IPresence;\n account_data: IAccountData;\n to_device?: IToDevice;\n device_lists?: IDeviceLists;\n device_one_time_keys_count?: Record<string, number>;\n\n groups: IGroups; // unspecced\n}\n/* eslint-enable camelcase */\n\nexport enum Category {\n Invite = \"invite\",\n Leave = \"leave\",\n Join = \"join\",\n}\n\ninterface IRoom {\n _currentState: { [eventType: string]: { [stateKey: string]: IStateEvent } };\n _timeline: {\n event: IRoomEvent | IStateEvent;\n token: string | null;\n }[];\n _summary: Partial<IRoomSummary>;\n _accountData: { [eventType: string]: IMinimalEvent };\n _unreadNotifications: Partial<IUnreadNotificationCounts>;\n _readReceipts: {\n [userId: string]: {\n data: IMinimalEvent;\n eventId: string;\n };\n };\n}\n\n/**\n * The purpose of this class is to accumulate /sync responses such that a\n * complete \"initial\" JSON response can be returned which accurately represents\n * the sum total of the /sync responses accumulated to date. It only handles\n * room data: that is, everything under the \"rooms\" top-level key.\n *\n * This class is used when persisting room data so a complete /sync response can\n * be loaded from disk and incremental syncs can be performed on the server,\n * rather than asking the server to do an initial sync on startup.\n */\nexport class SyncAccumulator {\n private accountData: Record<string, IMinimalEvent> = {}; // $event_type: Object\n private inviteRooms: Record<string, IInvitedRoom> = {}; // $roomId: { ... sync 'invite' json data ... }\n private joinRooms: { [roomId: string]: IRoom } = {};\n // the /sync token which corresponds to the last time rooms were\n // accumulated. We remember this so that any caller can obtain a\n // coherent /sync response and know at what point they should be\n // streaming from without losing events.\n private nextBatch: string = null;\n\n // { ('invite'|'join'|'leave'): $groupId: { ... sync 'group' data } }\n private groups: Record<Category, object> = {\n invite: {},\n join: {},\n leave: {},\n };\n\n /**\n * @param {Object} opts\n * @param {Number=} opts.maxTimelineEntries The ideal maximum number of\n * timeline entries to keep in the sync response. This is best-effort, as\n * clients do not always have a back-pagination token for each event, so\n * it's possible there may be slightly *less* than this value. There will\n * never be more. This cannot be 0 or else it makes it impossible to scroll\n * back in a room. Default: 50.\n */\n constructor(private readonly opts: IOpts = {}) {\n this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50;\n }\n\n public accumulate(syncResponse: ISyncResponse, fromDatabase = false): void {\n this.accumulateRooms(syncResponse, fromDatabase);\n this.accumulateGroups(syncResponse);\n this.accumulateAccountData(syncResponse);\n this.nextBatch = syncResponse.next_batch;\n }\n\n private accumulateAccountData(syncResponse: ISyncResponse): void {\n if (!syncResponse.account_data || !syncResponse.account_data.events) {\n return;\n }\n // Clobbers based on event type.\n syncResponse.account_data.events.forEach((e) => {\n this.accountData[e.type] = e;\n });\n }\n\n /**\n * Accumulate incremental /sync room data.\n * @param {Object} syncResponse the complete /sync JSON\n * @param {boolean} fromDatabase True if the sync response is one saved to the database\n */\n private accumulateRooms(syncResponse: ISyncResponse, fromDatabase = false): void {\n if (!syncResponse.rooms) {\n return;\n }\n if (syncResponse.rooms.invite) {\n Object.keys(syncResponse.rooms.invite).forEach((roomId) => {\n this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.join) {\n Object.keys(syncResponse.rooms.join).forEach((roomId) => {\n this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.leave) {\n Object.keys(syncResponse.rooms.leave).forEach((roomId) => {\n this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase);\n });\n }\n }\n\n private accumulateRoom(roomId: string, category: Category.Invite, data: IInvitedRoom, fromDatabase: boolean): void;\n private accumulateRoom(roomId: string, category: Category.Join, data: IJoinedRoom, fromDatabase: boolean): void;\n private accumulateRoom(roomId: string, category: Category.Leave, data: ILeftRoom, fromDatabase: boolean): void;\n private accumulateRoom(roomId: string, category: Category, data: any, fromDatabase = false): void {\n // Valid /sync state transitions\n // +--------+ <======+ 1: Accept an invite\n // +== | INVITE | | (5) 2: Leave a room\n // | +--------+ =====+ | 3: Join a public room previously\n // |(1) (4) | | left (handle as if new room)\n // V (2) V | 4: Reject an invite\n // +------+ ========> +--------+ 5: Invite to a room previously\n // | JOIN | (3) | LEAVE* | left (handle as if new room)\n // +------+ <======== +--------+\n //\n // * equivalent to \"no state\"\n switch (category) {\n case Category.Invite: // (5)\n this.accumulateInviteState(roomId, data as IInvitedRoom);\n break;\n\n case Category.Join:\n if (this.inviteRooms[roomId]) { // (1)\n // was previously invite, now join. We expect /sync to give\n // the entire state and timeline on 'join', so delete previous\n // invite state\n delete this.inviteRooms[roomId];\n }\n // (3)\n this.accumulateJoinState(roomId, data as IJoinedRoom, fromDatabase);\n break;\n\n case Category.Leave:\n if (this.inviteRooms[roomId]) { // (4)\n delete this.inviteRooms[roomId];\n } else { // (2)\n delete this.joinRooms[roomId];\n }\n break;\n\n default:\n logger.error(\"Unknown cateogory: \", category);\n }\n }\n\n private accumulateInviteState(roomId: string, data: IInvitedRoom): void {\n if (!data.invite_state || !data.invite_state.events) { // no new data\n return;\n }\n if (!this.inviteRooms[roomId]) {\n this.inviteRooms[roomId] = {\n invite_state: data.invite_state,\n };\n return;\n }\n // accumulate extra keys for invite->invite transitions\n // clobber based on event type / state key\n // We expect invite_state to be small, so just loop over the events\n const currentData = this.inviteRooms[roomId];\n data.invite_state.events.forEach((e) => {\n let hasAdded = false;\n for (let i = 0; i < currentData.invite_state.events.length; i++) {\n const current = currentData.invite_state.events[i];\n if (current.type === e.type && current.state_key == e.state_key) {\n currentData.invite_state.events[i] = e; // update\n hasAdded = true;\n }\n }\n if (!hasAdded) {\n currentData.invite_state.events.push(e);\n }\n });\n }\n\n // Accumulate timeline and state events in a room.\n private accumulateJoinState(roomId: string, data: IJoinedRoom, fromDatabase = false): void {\n // We expect this function to be called a lot (every /sync) so we want\n // this to be fast. /sync stores events in an array but we often want\n // to clobber based on type/state_key. Rather than convert arrays to\n // maps all the time, just keep private maps which contain\n // the actual current accumulated sync state, and array-ify it when\n // getJSON() is called.\n\n // State resolution:\n // The 'state' key is the delta from the previous sync (or start of time\n // if no token was supplied), to the START of the timeline. To obtain\n // the current state, we need to \"roll forward\" state by reading the\n // timeline. We want to store the current state so we can drop events\n // out the end of the timeline based on opts.maxTimelineEntries.\n //\n // 'state' 'timeline' current state\n // |-------x<======================>x\n // T I M E\n //\n // When getJSON() is called, we 'roll back' the current state by the\n // number of entries in the timeline to work out what 'state' should be.\n\n // Back-pagination:\n // On an initial /sync, the server provides a back-pagination token for\n // the start of the timeline. When /sync deltas come down, they also\n // include back-pagination tokens for the start of the timeline. This\n // means not all events in the timeline have back-pagination tokens, as\n // it is only the ones at the START of the timeline which have them.\n // In order for us to have a valid timeline (and back-pagination token\n // to match), we need to make sure that when we remove old timeline\n // events, that we roll forward to an event which has a back-pagination\n // token. This means we can't keep a strict sliding-window based on\n // opts.maxTimelineEntries, and we may have a few less. We should never\n // have more though, provided that the /sync limit is less than or equal\n // to opts.maxTimelineEntries.\n\n if (!this.joinRooms[roomId]) {\n // Create truly empty objects so event types of 'hasOwnProperty' and co\n // don't cause this code to break.\n this.joinRooms[roomId] = {\n _currentState: Object.create(null),\n _timeline: [],\n _accountData: Object.create(null),\n _unreadNotifications: {},\n _summary: {},\n _readReceipts: {},\n };\n }\n const currentData = this.joinRooms[roomId];\n\n if (data.account_data && data.account_data.events) {\n // clobber based on type\n data.account_data.events.forEach((e) => {\n currentData._accountData[e.type] = e;\n });\n }\n\n // these probably clobber, spec is unclear.\n if (data.unread_notifications) {\n currentData._unreadNotifications = data.unread_notifications;\n }\n if (data.summary) {\n const HEROES_KEY = \"m.heroes\";\n const INVITED_COUNT_KEY = \"m.invited_member_count\";\n const JOINED_COUNT_KEY = \"m.joined_member_count\";\n\n const acc = currentData._summary;\n const sum = data.summary;\n acc[HEROES_KEY] = sum[HEROES_KEY] || acc[HEROES_KEY];\n acc[JOINED_COUNT_KEY] = sum[JOINED_COUNT_KEY] || acc[JOINED_COUNT_KEY];\n acc[INVITED_COUNT_KEY] = sum[INVITED_COUNT_KEY] || acc[INVITED_COUNT_KEY];\n }\n\n if (data.ephemeral && data.ephemeral.events) {\n data.ephemeral.events.forEach((e) => {\n // We purposefully do not persist m.typing events.\n // Technically you could refresh a browser before the timer on a\n // typing event is up, so it'll look like you aren't typing when\n // you really still are. However, the alternative is worse. If\n // we do persist typing events, it will look like people are\n // typing forever until someone really does start typing (which\n // will prompt Synapse to send down an actual m.typing event to\n // clobber the one we persisted).\n if (e.type !== \"m.receipt\" || !e.content) {\n // This means we'll drop unknown ephemeral events but that\n // seems okay.\n return;\n }\n // Handle m.receipt events. They clobber based on:\n // (user_id, receipt_type)\n // but they are keyed in the event as:\n // content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n // so store them in the former so we can accumulate receipt deltas\n // quickly and efficiently (we expect a lot of them). Fold the\n // receipt type into the key name since we only have 1 at the\n // moment (m.read) and nested JSON objects are slower and more\n // of a hassle to work with. We'll inflate this back out when\n // getJSON() is called.\n Object.keys(e.content).forEach((eventId) => {\n if (!e.content[eventId][\"m.read\"]) {\n return;\n }\n Object.keys(e.content[eventId][\"m.read\"]).forEach((userId) => {\n // clobber on user ID\n currentData._readReceipts[userId] = {\n data: e.content[eventId][\"m.read\"][userId],\n eventId: eventId,\n };\n });\n });\n });\n }\n\n // if we got a limited sync, we need to remove all timeline entries or else\n // we will have gaps in the timeline.\n if (data.timeline && data.timeline.limited) {\n currentData._timeline = [];\n }\n\n // Work out the current state. The deltas need to be applied in the order:\n // - existing state which didn't come down /sync.\n // - State events under the 'state' key.\n // - State events in the 'timeline'.\n if (data.state && data.state.events) {\n data.state.events.forEach((e) => {\n setState(currentData._currentState, e);\n });\n }\n if (data.timeline && data.timeline.events) {\n data.timeline.events.forEach((e, index) => {\n // this nops if 'e' isn't a state event\n setState(currentData._currentState, e);\n // append the event to the timeline. The back-pagination token\n // corresponds to the first event in the timeline\n let transformedEvent: IRoomEvent & { _localTs?: number };\n if (!fromDatabase) {\n transformedEvent = Object.assign({}, e);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n const age = e.unsigned ? e.unsigned.age : e.age;\n if (age !== undefined) transformedEvent._localTs = Date.now() - age;\n } else {\n transformedEvent = e;\n }\n\n currentData._timeline.push({\n event: transformedEvent,\n token: index === 0 ? data.timeline.prev_batch : null,\n });\n });\n }\n\n // attempt to prune the timeline by jumping between events which have\n // pagination tokens.\n if (currentData._timeline.length > this.opts.maxTimelineEntries) {\n const startIndex = (\n currentData._timeline.length - this.opts.maxTimelineEntries\n );\n for (let i = startIndex; i < currentData._timeline.length; i++) {\n if (currentData._timeline[i].token) {\n // keep all events after this, including this one\n currentData._timeline = currentData._timeline.slice(\n i, currentData._timeline.length,\n );\n break;\n }\n }\n }\n }\n\n /**\n * Accumulate incremental /sync group data.\n * @param {Object} syncResponse the complete /sync JSON\n */\n private accumulateGroups(syncResponse: ISyncResponse): void {\n if (!syncResponse.groups) {\n return;\n }\n if (syncResponse.groups.invite) {\n Object.keys(syncResponse.groups.invite).forEach((groupId) => {\n this.accumulateGroup(groupId, Category.Invite, syncResponse.groups.invite[groupId]);\n });\n }\n if (syncResponse.groups.join) {\n Object.keys(syncResponse.groups.join).forEach((groupId) => {\n this.accumulateGroup(groupId, Category.Join, syncResponse.groups.join[groupId]);\n });\n }\n if (syncResponse.groups.leave) {\n Object.keys(syncResponse.groups.leave).forEach((groupId) => {\n this.accumulateGroup(groupId, Category.Leave, syncResponse.groups.leave[groupId]);\n });\n }\n }\n\n private accumulateGroup(groupId: string, category: Category, data: object): void {\n for (const cat of [Category.Invite, Category.Leave, Category.Join]) {\n delete this.groups[cat][groupId];\n }\n this.groups[category][groupId] = data;\n }\n\n /**\n * Return everything under the 'rooms' key from a /sync response which\n * represents all room data that should be stored. This should be paired\n * with the sync token which represents the most recent /sync response\n * provided to accumulate().\n * @param {boolean} forDatabase True to generate a sync to be saved to storage\n * @return {Object} An object with a \"nextBatch\", \"roomsData\" and \"accountData\"\n * keys.\n * The \"nextBatch\" key is a string which represents at what point in the\n * /sync stream the accumulator reached. This token should be used when\n * restarting a /sync stream at startup. Failure to do so can lead to missing\n * events. The \"roomsData\" key is an Object which represents the entire\n * /sync response from the 'rooms' key onwards. The \"accountData\" key is\n * a list of raw events which represent global account data.\n */\n public getJSON(forDatabase = false): object {\n const data = {\n join: {},\n invite: {},\n // always empty. This is set by /sync when a room was previously\n // in 'invite' or 'join'. On fresh startup, the client won't know\n // about any previous room being in 'invite' or 'join' so we can\n // just omit mentioning it at all, even if it has previously come\n // down /sync.\n // The notable exception is when a client is kicked or banned:\n // we may want to hold onto that room so the client can clearly see\n // why their room has disappeared. We don't persist it though because\n // it is unclear *when* we can safely remove the room from the DB.\n // Instead, we assume that if you're loading from the DB, you've\n // refreshed the page, which means you've seen the kick/ban already.\n leave: {},\n };\n Object.keys(this.inviteRooms).forEach((roomId) => {\n data.invite[roomId] = this.inviteRooms[roomId];\n });\n Object.keys(this.joinRooms).forEach((roomId) => {\n const roomData = this.joinRooms[roomId];\n const roomJson = {\n ephemeral: { events: [] },\n account_data: { events: [] },\n state: { events: [] },\n timeline: {\n events: [],\n prev_batch: null,\n },\n unread_notifications: roomData._unreadNotifications,\n summary: roomData._summary,\n };\n // Add account data\n Object.keys(roomData._accountData).forEach((evType) => {\n roomJson.account_data.events.push(roomData._accountData[evType]);\n });\n\n // Add receipt data\n const receiptEvent = {\n type: \"m.receipt\",\n room_id: roomId,\n content: {\n // $event_id: { \"m.read\": { $user_id: $json } }\n },\n };\n Object.keys(roomData._readReceipts).forEach((userId) => {\n const receiptData = roomData._readReceipts[userId];\n if (!receiptEvent.content[receiptData.eventId]) {\n receiptEvent.content[receiptData.eventId] = {\n \"m.read\": {},\n };\n }\n receiptEvent.content[receiptData.eventId][\"m.read\"][userId] = (\n receiptData.data\n );\n });\n // add only if we have some receipt data\n if (Object.keys(receiptEvent.content).length > 0) {\n roomJson.ephemeral.events.push(receiptEvent);\n }\n\n // Add timeline data\n roomData._timeline.forEach((msgData) => {\n if (!roomJson.timeline.prev_batch) {\n // the first event we add to the timeline MUST match up to\n // the prev_batch token.\n if (!msgData.token) {\n return; // this shouldn't happen as we prune constantly.\n }\n roomJson.timeline.prev_batch = msgData.token;\n }\n\n let transformedEvent: (IRoomEvent | IStateEvent) & { _localTs?: number };\n if (!forDatabase && msgData.event[\"_localTs\"]) {\n // This means we have to copy each event so we can fix it up to\n // set a correct 'age' parameter whilst keeping the local timestamp\n // on our stored event. If this turns out to be a bottleneck, it could\n // be optimised either by doing this in the main process after the data\n // has been structured-cloned to go between the worker & main process,\n // or special-casing data from saved syncs to read the local timestamp\n // directly rather than turning it into age to then immediately be\n // transformed back again into a local timestamp.\n transformedEvent = Object.assign({}, msgData.event);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n delete transformedEvent._localTs;\n transformedEvent.unsigned = transformedEvent.unsigned || {};\n transformedEvent.unsigned.age = Date.now() - msgData.event[\"_localTs\"];\n } else {\n transformedEvent = msgData.event;\n }\n roomJson.timeline.events.push(transformedEvent);\n });\n\n // Add state data: roll back current state to the start of timeline,\n // by \"reverse clobbering\" from the end of the timeline to the start.\n // Convert maps back into arrays.\n const rollBackState = Object.create(null);\n for (let i = roomJson.timeline.events.length - 1; i >=0; i--) {\n const timelineEvent = roomJson.timeline.events[i];\n if (timelineEvent.state_key === null ||\n timelineEvent.state_key === undefined) {\n continue; // not a state event\n }\n // since we're going back in time, we need to use the previous\n // state value else we'll break causality. We don't have the\n // complete previous state event, so we need to create one.\n const prevStateEvent = deepCopy(timelineEvent);\n if (prevStateEvent.unsigned) {\n if (prevStateEvent.unsigned.prev_content) {\n prevStateEvent.content = prevStateEvent.unsigned.prev_content;\n }\n if (prevStateEvent.unsigned.prev_sender) {\n prevStateEvent.sender = prevStateEvent.unsigned.prev_sender;\n }\n }\n setState(rollBackState, prevStateEvent);\n }\n Object.keys(roomData._currentState).forEach((evType) => {\n Object.keys(roomData._currentState[evType]).forEach((stateKey) => {\n let ev = roomData._currentState[evType][stateKey];\n if (rollBackState[evType] && rollBackState[evType][stateKey]) {\n // use the reverse clobbered event instead.\n ev = rollBackState[evType][stateKey];\n }\n roomJson.state.events.push(ev);\n });\n });\n data.join[roomId] = roomJson;\n });\n\n // Add account data\n const accData = [];\n Object.keys(this.accountData).forEach((evType) => {\n accData.push(this.accountData[evType]);\n });\n\n return {\n nextBatch: this.nextBatch,\n roomsData: data,\n groupsData: this.groups,\n accountData: accData,\n };\n }\n\n public getNextBatchToken(): string {\n return this.nextBatch;\n }\n}\n\nfunction setState(eventMap: Record<string, Record<string, IStateEvent>>, event: IRoomEvent | IStateEvent): void {\n if ((event as IStateEvent).state_key === null || (event as IStateEvent).state_key === undefined || !event.type) {\n return;\n }\n if (!eventMap[event.type]) {\n eventMap[event.type] = Object.create(null);\n }\n eventMap[event.type][(event as IStateEvent).state_key] = event as IStateEvent;\n}\n",
"/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// TODO: Merge this with sync.js once converted\n\nexport enum SyncState {\n Error = \"ERROR\",\n Prepared = \"PREPARED\",\n Stopped = \"STOPPED\",\n Syncing = \"SYNCING\",\n Catchup = \"CATCHUP\",\n Reconnecting = \"RECONNECTING\",\n}\n",
"/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { User } from \"./models/user\";\nimport { NotificationCountType, Room } from \"./models/room\";\nimport { Group } from \"./models/group\";\nimport * as utils from \"./utils\";\nimport { IDeferred } from \"./utils\";\nimport { Filter } from \"./filter\";\nimport { EventTimeline } from \"./models/event-timeline\";\nimport { PushProcessor } from \"./pushprocessor\";\nimport { logger } from './logger';\nimport { InvalidStoreError } from './errors';\nimport { IStoredClientOpts, MatrixClient, PendingEventOrdering } from \"./client\";\nimport { SyncState } from \"./sync.api\";\nimport {\n Category,\n IInvitedRoom,\n IInviteState,\n IJoinedRoom,\n ILeftRoom,\n IStateEvent,\n IRoomEvent,\n IStrippedState,\n ISyncResponse,\n ITimeline,\n IEphemeral,\n IMinimalEvent,\n} from \"./sync-accumulator\";\nimport { MatrixEvent } from \"./models/event\";\nimport { MatrixError } from \"./http-api\";\nimport { ISavedSync } from \"./store\";\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nfunction getFilterName(userId: string, suffix?: string): string {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return \"FILTER_SYNC_\" + userId + (suffix ? \"_\" + suffix : \"\");\n}\n\nfunction debuglog(...params) {\n if (!DEBUG) {\n return;\n }\n logger.log(...params);\n}\n\ninterface ISyncOptions {\n filterId?: string;\n hasSyncedBefore?: boolean;\n}\n\nexport interface ISyncStateData {\n error?: Error;\n oldSyncToken?: string;\n nextSyncToken?: string;\n catchingUp?: boolean;\n fromCache?: boolean;\n}\n\ninterface ISyncParams {\n filter?: string;\n timeout: number;\n since?: string;\n // eslint-disable-next-line camelcase\n full_state?: boolean;\n // eslint-disable-next-line camelcase\n set_presence?: \"offline\" | \"online\" | \"unavailable\";\n _cacheBuster?: string | number; // not part of the API itself\n}\n\n// http-api mangles an abort method onto its promises\ninterface IRequestPromise<T> extends Promise<T> {\n abort(): void;\n}\n\ntype WrappedRoom<T> = T & {\n room: Room;\n isBrandNewRoom: boolean;\n};\n\n/**\n * <b>Internal class - unstable.</b>\n * Construct an entity which is able to sync with a homeserver.\n * @constructor\n * @param {MatrixClient} client The matrix client instance to use.\n * @param {Object} opts Config options\n * @param {module:crypto=} opts.crypto Crypto manager\n * @param {Function=} opts.canResetEntireTimeline A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n * Default: returns false.\n * @param {Boolean=} opts.disablePresence True to perform syncing without automatically\n * updating presence.\n */\nexport class SyncApi {\n private _peekRoom: Room = null;\n private currentSyncRequest: IRequestPromise<ISyncResponse> = null;\n private syncState: SyncState = null;\n private syncStateData: ISyncStateData = null; // additional data (eg. error object for failed sync)\n private catchingUp = false;\n private running = false;\n private keepAliveTimer: NodeJS.Timeout = null;\n private connectionReturnedDefer: IDeferred<boolean> = null;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n private failedSyncCount = 0; // Number of consecutive failed /sync requests\n private storeIsInvalid = false; // flag set if the store needs to be cleared before we can start\n\n constructor(private readonly client: MatrixClient, private readonly opts: Partial<IStoredClientOpts> = {}) {\n this.opts.initialSyncLimit = this.opts.initialSyncLimit ?? 8;\n this.opts.resolveInvitesToProfiles = this.opts.resolveInvitesToProfiles || false;\n this.opts.pollTimeout = this.opts.pollTimeout || (30 * 1000);\n this.opts.pendingEventOrdering = this.opts.pendingEventOrdering || PendingEventOrdering.Chronological;\n\n if (!opts.canResetEntireTimeline) {\n opts.canResetEntireTimeline = (roomId: string) => {\n return false;\n };\n }\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet(),\n [\"Room.timeline\", \"Room.timelineReset\"]);\n }\n }\n\n /**\n * @param {string} roomId\n * @return {Room}\n */\n public createRoom(roomId: string): Room {\n const client = this.client;\n const {\n timelineSupport,\n unstableClientRelationAggregation,\n } = client;\n const room = new Room(roomId, client, client.getUserId(), {\n lazyLoadMembers: this.opts.lazyLoadMembers,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n timelineSupport,\n unstableClientRelationAggregation,\n });\n client.reEmitter.reEmit(room, [\"Room.name\", \"Room.timeline\",\n \"Room.redaction\",\n \"Room.redactionCancelled\",\n \"Room.receipt\", \"Room.tags\",\n \"Room.timelineReset\",\n \"Room.localEchoUpdated\",\n \"Room.accountData\",\n \"Room.myMembership\",\n \"Room.replaceEvent\",\n ]);\n this.registerStateListeners(room);\n return room;\n }\n\n /**\n * @param {string} groupId\n * @return {Group}\n */\n public createGroup(groupId: string): Group {\n const client = this.client;\n const group = new Group(groupId);\n client.reEmitter.reEmit(group, [\"Group.profile\", \"Group.myMembership\"]);\n client.store.storeGroup(group);\n return group;\n }\n\n /**\n * @param {Room} room\n * @private\n */\n private registerStateListeners(room: Room): void {\n const client = this.client;\n // we need to also re-emit room state and room member events, so hook it up\n // to the client now. We need to add a listener for RoomState.members in\n // order to hook them correctly. (TODO: find a better way?)\n client.reEmitter.reEmit(room.currentState, [\n \"RoomState.events\", \"RoomState.members\", \"RoomState.newMember\",\n ]);\n room.currentState.on(\"RoomState.newMember\", function(event, state, member) {\n member.user = client.getUser(member.userId);\n client.reEmitter.reEmit(\n member,\n [\n \"RoomMember.name\", \"RoomMember.typing\", \"RoomMember.powerLevel\",\n \"RoomMember.membership\",\n ],\n );\n });\n }\n\n /**\n * @param {Room} room\n * @private\n */\n private deregisterStateListeners(room: Room): void {\n // could do with a better way of achieving this.\n room.currentState.removeAllListeners(\"RoomState.events\");\n room.currentState.removeAllListeners(\"RoomState.members\");\n room.currentState.removeAllListeners(\"RoomState.newMember\");\n }\n\n /**\n * Sync rooms the user has left.\n * @return {Promise} Resolved when they've been added to the store.\n */\n public syncLeftRooms() {\n const client = this.client;\n\n // grab a filter with limit=1 and include_leave=true\n const filter = new Filter(this.client.credentials.userId);\n filter.setTimelineLimit(1);\n filter.setIncludeLeaveRooms(true);\n\n const localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;\n const qps: ISyncParams = {\n timeout: 0, // don't want to block since this is a single isolated req\n };\n\n return client.getOrCreateFilter(\n getFilterName(client.credentials.userId, \"LEFT_ROOMS\"), filter,\n ).then(function(filterId) {\n qps.filter = filterId;\n return client.http.authedRequest(\n undefined, \"GET\", \"/sync\", qps, undefined, localTimeoutMs,\n );\n }).then((data) => {\n let leaveRooms = [];\n if (data.rooms && data.rooms.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n const rooms = [];\n leaveRooms.forEach((leaveObj) => {\n const room = leaveObj.room;\n rooms.push(room);\n if (!leaveObj.isBrandNewRoom) {\n // the intention behind syncLeftRooms is to add in rooms which were\n // *omitted* from the initial /sync. Rooms the user were joined to\n // but then left whilst the app is running will appear in this list\n // and we do not want to bother with them since they will have the\n // current state already (and may get dupe messages if we add\n // yet more timeline events!), so skip them.\n // NB: When we persist rooms to localStorage this will be more\n // complicated...\n return;\n }\n leaveObj.timeline = leaveObj.timeline || {};\n const timelineEvents =\n this.mapSyncEventsFormat(leaveObj.timeline, room);\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch,\n EventTimeline.BACKWARDS);\n\n this.processRoomEvents(room, stateEvents, timelineEvents);\n\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n\n this.processEventsForNotifs(room, timelineEvents);\n });\n return rooms;\n });\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param {string} roomId The room ID to peek into.\n * @return {Promise} A promise which resolves once the room has been added to the\n * store.\n */\n public peek(roomId: string): Promise<Room> {\n if (this._peekRoom && this._peekRoom.roomId === roomId) {\n return Promise.resolve(this._peekRoom);\n }\n\n const client = this.client;\n this._peekRoom = this.createRoom(roomId);\n return this.client.roomInitialSync(roomId, 20).then((response) => {\n // make sure things are init'd\n response.messages = response.messages || {};\n response.messages.chunk = response.messages.chunk || [];\n response.state = response.state || [];\n\n // FIXME: Mostly duplicated from processRoomEvents but not entirely\n // because \"state\" in this API is at the BEGINNING of the chunk\n const oldStateEvents = utils.deepCopy(response.state)\n .map(client.getEventMapper());\n const stateEvents = response.state.map(client.getEventMapper());\n const messages = response.messages.chunk.map(client.getEventMapper());\n\n // XXX: copypasted from /sync until we kill off this\n // minging v1 API stuff)\n // handle presence events (User objects)\n if (response.presence && Array.isArray(response.presence)) {\n response.presence.map(client.getEventMapper()).forEach(\n function(presenceEvent) {\n let user = client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(client, presenceEvent.getContent().user_id);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(\"event\", presenceEvent);\n });\n }\n\n // set the pagination token before adding the events in case people\n // fire off pagination requests in response to the Room.timeline\n // events.\n if (response.messages.start) {\n this._peekRoom.oldState.paginationToken = response.messages.start;\n }\n\n // set the state of the room to as it was after the timeline executes\n this._peekRoom.oldState.setStateEvents(oldStateEvents);\n this._peekRoom.currentState.setStateEvents(stateEvents);\n\n this.resolveInvites(this._peekRoom);\n this._peekRoom.recalculate();\n\n // roll backwards to diverge old state. addEventsToTimeline\n // will overwrite the pagination token, so make sure it overwrites\n // it with the right thing.\n this._peekRoom.addEventsToTimeline(messages.reverse(), true,\n this._peekRoom.getLiveTimeline(),\n response.messages.start);\n\n client.store.storeRoom(this._peekRoom);\n client.emit(\"Room\", this._peekRoom);\n\n this.peekPoll(this._peekRoom);\n return this._peekRoom;\n });\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n this._peekRoom = null;\n }\n\n /**\n * Do a peek room poll.\n * @param {Room} peekRoom\n * @param {string?} token from= token\n */\n private peekPoll(peekRoom: Room, token?: string): void {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n\n // FIXME: gut wrenching; hard-coded timeout values\n this.client.http.authedRequest(undefined, \"GET\", \"/events\", {\n room_id: peekRoom.roomId,\n timeout: 30 * 1000,\n from: token,\n }, undefined, 50 * 1000).then((res) => {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n // We have a problem that we get presence both from /events and /sync\n // however, /sync only returns presence for users in rooms\n // you're actually joined to.\n // in order to be sure to get presence for all of the users in the\n // peeked room, we handle presence explicitly here. This may result\n // in duplicate presence events firing for some users, which is a\n // performance drain, but such is life.\n // XXX: copypasted from /sync until we can kill this minging v1 stuff.\n\n res.chunk.filter(function(e) {\n return e.type === \"m.presence\";\n }).map(this.client.getEventMapper()).forEach((presenceEvent) => {\n let user = this.client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(this.client, presenceEvent.getContent().user_id);\n user.setPresenceEvent(presenceEvent);\n this.client.store.storeUser(user);\n }\n this.client.emit(\"event\", presenceEvent);\n });\n\n // strip out events which aren't for the given room_id (e.g presence)\n // and also ephemeral events (which we're assuming is anything without\n // and event ID because the /events API doesn't separate them).\n const events = res.chunk.filter(function(e) {\n return e.room_id === peekRoom.roomId && e.event_id;\n }).map(this.client.getEventMapper());\n\n peekRoom.addLiveEvents(events);\n this.peekPoll(peekRoom, res.end);\n }, (err) => {\n logger.error(\"[%s] Peek poll failed: %s\", peekRoom.roomId, err);\n setTimeout(() => {\n this.peekPoll(peekRoom, token);\n }, 30 * 1000);\n });\n }\n\n /**\n * Returns the current state of this sync object\n * @see module:client~MatrixClient#event:\"sync\"\n * @return {?String}\n */\n public getSyncState(): SyncState {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n * @return {?Object}\n */\n public getSyncStateData(): ISyncStateData {\n return this.syncStateData;\n }\n\n public async recoverFromSyncStartupError(savedSyncPromise: Promise<void>, err: Error): Promise<void> {\n // Wait for the saved sync to complete - we send the pushrules and filter requests\n // before the saved sync has finished so they can run in parallel, but only process\n // the results after the saved sync is done. Equivalently, we wait for it to finish\n // before reporting failures from these functions.\n await savedSyncPromise;\n const keepaliveProm = this.startKeepAlives();\n this.updateSyncState(SyncState.Error, { error: err });\n await keepaliveProm;\n }\n\n /**\n * Is the lazy loading option different than in previous session?\n * @param {boolean} lazyLoadMembers current options for lazy loading\n * @return {boolean} whether or not the option has changed compared to the previous session */\n private async wasLazyLoadingToggled(lazyLoadMembers = false): Promise<boolean> {\n // assume it was turned off before\n // if we don't know any better\n let lazyLoadMembersBefore = false;\n const isStoreNewlyCreated = await this.client.store.isNewlyCreated();\n if (!isStoreNewlyCreated) {\n const prevClientOptions = await this.client.store.getClientOptions();\n if (prevClientOptions) {\n lazyLoadMembersBefore = !!prevClientOptions.lazyLoadMembers;\n }\n return lazyLoadMembersBefore !== lazyLoadMembers;\n }\n return false;\n }\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n return true;\n }\n return false;\n }\n\n /**\n * Main entry point\n */\n public sync(): void {\n const client = this.client;\n\n this.running = true;\n\n if (global.window && global.window.addEventListener) {\n global.window.addEventListener(\"online\", this.onOnline, false);\n }\n\n let savedSyncPromise = Promise.resolve();\n let savedSyncToken = null;\n\n // We need to do one-off checks before we can begin the /sync loop.\n // These are:\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n // 2) We need to get/create a filter which we can use for /sync.\n // 3) We need to check the lazy loading option matches what was used in the\n // stored sync. If it doesn't, we can't use the stored sync.\n\n const getPushRules = async () => {\n try {\n debuglog(\"Getting push rules...\");\n const result = await client.getPushRules();\n debuglog(\"Got push rules\");\n\n client.pushRules = result;\n } catch (err) {\n logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(err)) return;\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying push rules...\");\n await this.recoverFromSyncStartupError(savedSyncPromise, err);\n getPushRules();\n return;\n }\n checkLazyLoadStatus(); // advance to the next stage\n };\n\n const buildDefaultFilter = () => {\n const filter = new Filter(client.credentials.userId);\n filter.setTimelineLimit(this.opts.initialSyncLimit);\n return filter;\n };\n\n const checkLazyLoadStatus = async () => {\n debuglog(\"Checking lazy load status...\");\n if (this.opts.lazyLoadMembers && client.isGuest()) {\n this.opts.lazyLoadMembers = false;\n }\n if (this.opts.lazyLoadMembers) {\n debuglog(\"Checking server lazy load support...\");\n const supported = await client.doesServerSupportLazyLoading();\n if (supported) {\n debuglog(\"Enabling lazy load on sync filter...\");\n if (!this.opts.filter) {\n this.opts.filter = buildDefaultFilter();\n }\n this.opts.filter.setLazyLoadMembers(true);\n } else {\n debuglog(\"LL: lazy loading requested but not supported \" +\n \"by server, so disabling\");\n this.opts.lazyLoadMembers = false;\n }\n }\n // need to vape the store when enabling LL and wasn't enabled before\n debuglog(\"Checking whether lazy loading has changed in store...\");\n const shouldClear = await this.wasLazyLoadingToggled(this.opts.lazyLoadMembers);\n if (shouldClear) {\n this.storeIsInvalid = true;\n const reason = InvalidStoreError.TOGGLED_LAZY_LOADING;\n const error = new InvalidStoreError(reason, !!this.opts.lazyLoadMembers);\n this.updateSyncState(SyncState.Error, { error });\n // bail out of the sync loop now: the app needs to respond to this error.\n // we leave the state as 'ERROR' which isn't great since this normally means\n // we're retrying. The client must be stopped before clearing the stores anyway\n // so the app should stop the client, clear the store and start it again.\n logger.warn(\"InvalidStoreError: store is not usable: stopping sync.\");\n return;\n }\n if (this.opts.lazyLoadMembers && this.opts.crypto) {\n this.opts.crypto.enableLazyLoading();\n }\n try {\n debuglog(\"Storing client options...\");\n await this.client.storeClientOptions();\n debuglog(\"Stored client options\");\n } catch (err) {\n logger.error(\"Storing client options failed\", err);\n throw err;\n }\n\n getFilter(); // Now get the filter and start syncing\n };\n\n const getFilter = async () => {\n debuglog(\"Getting filter...\");\n let filter;\n if (this.opts.filter) {\n filter = this.opts.filter;\n } else {\n filter = buildDefaultFilter();\n }\n\n let filterId;\n try {\n filterId = await client.getOrCreateFilter(getFilterName(client.credentials.userId), filter);\n } catch (err) {\n logger.error(\"Getting filter failed\", err);\n if (this.shouldAbortSync(err)) return;\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying filter...\");\n await this.recoverFromSyncStartupError(savedSyncPromise, err);\n getFilter();\n return;\n }\n // reset the notifications timeline to prepare it to paginate from\n // the current point in time.\n // The right solution would be to tie /sync pagination tokens into\n // /notifications API somehow.\n client.resetNotifTimelineSet();\n\n if (this.currentSyncRequest === null) {\n // Send this first sync request here so we can then wait for the saved\n // sync data to finish processing before we process the results of this one.\n debuglog(\"Sending first sync request...\");\n this.currentSyncRequest = this.doSyncRequest({ filterId }, savedSyncToken);\n }\n\n // Now wait for the saved sync to finish...\n debuglog(\"Waiting for saved sync before starting sync processing...\");\n await savedSyncPromise;\n this._sync({ filterId });\n };\n\n if (client.isGuest()) {\n // no push rules for guests, no access to POST filter for guests.\n this._sync({});\n } else {\n // Pull the saved sync token out first, before the worker starts sending\n // all the sync data which could take a while. This will let us send our\n // first incremental sync request before we've processed our saved data.\n debuglog(\"Getting saved sync token...\");\n savedSyncPromise = client.store.getSavedSyncToken().then((tok) => {\n debuglog(\"Got saved sync token\");\n savedSyncToken = tok;\n debuglog(\"Getting saved sync...\");\n return client.store.getSavedSync();\n }).then((savedSync) => {\n debuglog(`Got reply from saved sync, exists? ${!!savedSync}`);\n if (savedSync) {\n return this.syncFromCache(savedSync);\n }\n }).catch(err => {\n logger.error(\"Getting saved sync failed\", err);\n });\n // Now start the first incremental sync request: this can also\n // take a while so if we set it going now, we can wait for it\n // to finish while we process our saved sync data.\n getPushRules();\n }\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n debuglog(\"SyncApi.stop\");\n if (global.window) {\n global.window.removeEventListener(\"online\", this.onOnline, false);\n }\n this.running = false;\n if (this.currentSyncRequest) {\n this.currentSyncRequest.abort();\n }\n if (this.keepAliveTimer) {\n clearTimeout(this.keepAliveTimer);\n this.keepAliveTimer = null;\n }\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * @return {boolean} True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n if (!this.connectionReturnedDefer) {\n return false;\n }\n this.startKeepAlives(0);\n return true;\n }\n /**\n * Process a single set of cached sync data.\n * @param {Object} savedSync a saved sync that was persisted by a store. This\n * should have been acquired via client.store.getSavedSync().\n */\n private async syncFromCache(savedSync: ISavedSync): Promise<void> {\n debuglog(\"sync(): not doing HTTP hit, instead returning stored /sync data\");\n\n const nextSyncToken = savedSync.nextBatch;\n\n // Set sync token for future incremental syncing\n this.client.store.setSyncToken(nextSyncToken);\n\n // No previous sync, set old token to null\n const syncEventData = {\n oldSyncToken: null,\n nextSyncToken,\n catchingUp: false,\n fromCache: true,\n };\n\n const data: ISyncResponse = {\n next_batch: nextSyncToken,\n rooms: savedSync.roomsData,\n groups: savedSync.groupsData,\n account_data: {\n events: savedSync.accountData,\n },\n };\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n logger.error(\"Error processing cached sync\", e.stack || e);\n }\n\n // Don't emit a prepared if we've bailed because the store is invalid:\n // in this case the client will not be usable until stopped & restarted\n // so this would be useless and misleading.\n if (!this.storeIsInvalid) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n }\n }\n\n /**\n * Invoke me to do /sync calls\n * @param {Object} syncOptions\n * @param {string} syncOptions.filterId\n * @param {boolean} syncOptions.hasSyncedBefore\n */\n private async _sync(syncOptions: ISyncOptions): Promise<void> {\n const client = this.client;\n\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting.\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = null;\n }\n this.updateSyncState(SyncState.Stopped);\n return;\n }\n\n const syncToken = client.store.getSyncToken();\n\n let data;\n try {\n //debuglog('Starting sync since=' + syncToken);\n if (this.currentSyncRequest === null) {\n this.currentSyncRequest = this.doSyncRequest(syncOptions, syncToken);\n }\n data = await this.currentSyncRequest;\n } catch (e) {\n this.onSyncError(e, syncOptions);\n return;\n } finally {\n this.currentSyncRequest = null;\n }\n\n //debuglog('Completed sync, next_batch=' + data.next_batch);\n\n // set the sync token NOW *before* processing the events. We do this so\n // if something barfs on an event we can skip it rather than constantly\n // polling with the same token.\n client.store.setSyncToken(data.next_batch);\n\n // Reset after a successful sync\n this.failedSyncCount = 0;\n\n await client.store.setSyncData(data);\n\n const syncEventData = {\n oldSyncToken: syncToken,\n nextSyncToken: data.next_batch,\n catchingUp: this.catchingUp,\n };\n\n if (this.opts.crypto) {\n // tell the crypto module we're about to process a sync\n // response\n await this.opts.crypto.onSyncWillProcess(syncEventData);\n }\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n // log the exception with stack if we have it, else fall back\n // to the plain description\n logger.error(\"Caught /sync error\", e.stack || e);\n\n // Emit the exception for client handling\n this.client.emit(\"sync.unexpectedError\", e);\n }\n\n // update this as it may have changed\n syncEventData.catchingUp = this.catchingUp;\n\n // emit synced events\n if (!syncOptions.hasSyncedBefore) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n syncOptions.hasSyncedBefore = true;\n }\n\n // tell the crypto module to do its processing. It may block (to do a\n // /keys/changes request).\n if (this.opts.crypto) {\n await this.opts.crypto.onSyncCompleted(syncEventData);\n }\n\n // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates\n this.updateSyncState(SyncState.Syncing, syncEventData);\n\n if (client.store.wantsSave()) {\n // We always save the device list (if it's dirty) before saving the sync data:\n // this means we know the saved device list data is at least as fresh as the\n // stored sync data which means we don't have to worry that we may have missed\n // device changes. We can also skip the delay since we're not calling this very\n // frequently (and we don't really want to delay the sync for it).\n if (this.opts.crypto) {\n await this.opts.crypto.saveDeviceList(0);\n }\n\n // tell databases that everything is now in a consistent state and can be saved.\n client.store.save();\n }\n\n // Begin next sync\n this._sync(syncOptions);\n }\n\n private doSyncRequest(syncOptions: ISyncOptions, syncToken: string): IRequestPromise<ISyncResponse> {\n const qps = this.getSyncParams(syncOptions, syncToken);\n return this.client.http.authedRequest(\n undefined, \"GET\", \"/sync\", qps, undefined,\n qps.timeout + BUFFER_PERIOD_MS,\n );\n }\n\n private getSyncParams(syncOptions: ISyncOptions, syncToken: string): ISyncParams {\n let pollTimeout = this.opts.pollTimeout;\n\n if (this.getSyncState() !== 'SYNCING' || this.catchingUp) {\n // unless we are happily syncing already, we want the server to return\n // as quickly as possible, even if there are no events queued. This\n // serves two purposes:\n //\n // * When the connection dies, we want to know asap when it comes back,\n // so that we can hide the error from the user. (We don't want to\n // have to wait for an event or a timeout).\n //\n // * We want to know if the server has any to_device messages queued up\n // for us. We do that by calling it with a zero timeout until it\n // doesn't give us any more to_device messages.\n this.catchingUp = true;\n pollTimeout = 0;\n }\n\n let filterId = syncOptions.filterId;\n if (this.client.isGuest() && !filterId) {\n filterId = this.getGuestFilter();\n }\n\n const qps: ISyncParams = {\n filter: filterId,\n timeout: pollTimeout,\n };\n\n if (this.opts.disablePresence) {\n qps.set_presence = \"offline\";\n }\n\n if (syncToken) {\n qps.since = syncToken;\n } else {\n // use a cachebuster for initialsyncs, to make sure that\n // we don't get a stale sync\n // (https://github.com/vector-im/vector-web/issues/1354)\n qps._cacheBuster = Date.now();\n }\n\n if (this.getSyncState() == 'ERROR' || this.getSyncState() == 'RECONNECTING') {\n // we think the connection is dead. If it comes back up, we won't know\n // about it till /sync returns. If the timeout= is high, this could\n // be a long time. Set it to 0 when doing retries so we don't have to wait\n // for an event or a timeout before emiting the SYNCING event.\n qps.timeout = 0;\n }\n\n return qps;\n }\n\n private onSyncError(err: Error, syncOptions: ISyncOptions): void {\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = null;\n }\n this.updateSyncState(SyncState.Stopped);\n return;\n }\n\n logger.error(\"/sync error %s\", err);\n logger.error(err);\n\n if (this.shouldAbortSync(err)) {\n return;\n }\n\n this.failedSyncCount++;\n logger.log('Number of consecutive failed sync requests:', this.failedSyncCount);\n\n debuglog(\"Starting keep-alive\");\n // Note that we do *not* mark the sync connection as\n // lost yet: we only do this if a keepalive poke\n // fails, since long lived HTTP connections will\n // go away sometimes and we shouldn't treat this as\n // erroneous. We set the state to 'reconnecting'\n // instead, so that clients can observe this state\n // if they wish.\n this.startKeepAlives().then((connDidFail) => {\n // Only emit CATCHUP if we detected a connectivity error: if we didn't,\n // it's quite likely the sync will fail again for the same reason and we\n // want to stay in ERROR rather than keep flip-flopping between ERROR\n // and CATCHUP.\n if (connDidFail && this.getSyncState() === SyncState.Error) {\n this.updateSyncState(SyncState.Catchup, {\n oldSyncToken: null,\n nextSyncToken: null,\n catchingUp: true,\n });\n }\n this._sync(syncOptions);\n });\n\n this.currentSyncRequest = null;\n // Transition from RECONNECTING to ERROR after a given number of failed syncs\n this.updateSyncState(\n this.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ?\n SyncState.Error : SyncState.Reconnecting,\n { error: err },\n );\n }\n\n /**\n * Process data returned from a sync response and propagate it\n * into the model objects\n *\n * @param {Object} syncEventData Object containing sync tokens associated with this sync\n * @param {Object} data The response from /sync\n */\n private async processSyncResponse(syncEventData: ISyncStateData, data: ISyncResponse): Promise<void> {\n const client = this.client;\n\n // data looks like:\n // {\n // next_batch: $token,\n // presence: { events: [] },\n // account_data: { events: [] },\n // device_lists: { changed: [\"@user:server\", ... ]},\n // to_device: { events: [] },\n // device_one_time_keys_count: { signed_curve25519: 42 },\n // rooms: {\n // invite: {\n // $roomid: {\n // invite_state: { events: [] }\n // }\n // },\n // join: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token, limited: true },\n // ephemeral: { events: [] },\n // summary: {\n // m.heroes: [ $user_id ],\n // m.joined_member_count: $count,\n // m.invited_member_count: $count\n // },\n // account_data: { events: [] },\n // unread_notifications: {\n // highlight_count: 0,\n // notification_count: 0,\n // }\n // }\n // },\n // leave: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token }\n // }\n // }\n // },\n // groups: {\n // invite: {\n // $groupId: {\n // inviter: $inviter,\n // profile: {\n // avatar_url: $avatarUrl,\n // name: $groupName,\n // },\n // },\n // },\n // join: {},\n // leave: {},\n // },\n // }\n\n // TODO-arch:\n // - Each event we pass through needs to be emitted via 'event', can we\n // do this in one place?\n // - The isBrandNewRoom boilerplate is boilerplatey.\n\n // handle presence events (User objects)\n if (data.presence && Array.isArray(data.presence.events)) {\n data.presence.events.map(client.getEventMapper()).forEach(\n function(presenceEvent) {\n let user = client.store.getUser(presenceEvent.getSender());\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(client, presenceEvent.getSender());\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(\"event\", presenceEvent);\n });\n }\n\n // handle non-room account_data\n if (data.account_data && Array.isArray(data.account_data.events)) {\n const events = data.account_data.events.map(client.getEventMapper());\n const prevEventsMap = events.reduce((m, c) => {\n m[c.getId()] = client.store.getAccountData(c.getType());\n return m;\n }, {});\n client.store.storeAccountDataEvents(events);\n events.forEach(\n function(accountDataEvent) {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === 'm.push_rules') {\n const rules = accountDataEvent.getContent();\n client.pushRules = PushProcessor.rewriteDefaultRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getId()];\n client.emit(\"accountData\", accountDataEvent, prevEvent);\n return accountDataEvent;\n },\n );\n }\n\n // handle to-device events\n if (data.to_device && Array.isArray(data.to_device.events) &&\n data.to_device.events.length > 0\n ) {\n const cancelledKeyVerificationTxns = [];\n data.to_device.events\n .map(client.getEventMapper())\n .map((toDeviceEvent) => { // map is a cheap inline forEach\n // We want to flag m.key.verification.start events as cancelled\n // if there's an accompanying m.key.verification.cancel event, so\n // we pull out the transaction IDs from the cancellation events\n // so we can flag the verification events as cancelled in the loop\n // below.\n if (toDeviceEvent.getType() === \"m.key.verification.cancel\") {\n const txnId = toDeviceEvent.getContent()['transaction_id'];\n if (txnId) {\n cancelledKeyVerificationTxns.push(txnId);\n }\n }\n\n // as mentioned above, .map is a cheap inline forEach, so return\n // the unmodified event.\n return toDeviceEvent;\n })\n .forEach(\n function(toDeviceEvent) {\n const content = toDeviceEvent.getContent();\n if (\n toDeviceEvent.getType() == \"m.room.message\" &&\n content.msgtype == \"m.bad.encrypted\"\n ) {\n // the mapper already logged a warning.\n logger.log(\n 'Ignoring undecryptable to-device event from ' +\n toDeviceEvent.getSender(),\n );\n return;\n }\n\n if (toDeviceEvent.getType() === \"m.key.verification.start\"\n || toDeviceEvent.getType() === \"m.key.verification.request\") {\n const txnId = content['transaction_id'];\n if (cancelledKeyVerificationTxns.includes(txnId)) {\n toDeviceEvent.flagCancelled();\n }\n }\n\n client.emit(\"toDeviceEvent\", toDeviceEvent);\n },\n );\n } else {\n // no more to-device events: we can stop polling with a short timeout.\n this.catchingUp = false;\n }\n\n if (data.groups) {\n if (data.groups.invite) {\n this.processGroupSyncEntry(data.groups.invite, Category.Invite);\n }\n\n if (data.groups.join) {\n this.processGroupSyncEntry(data.groups.join, Category.Join);\n }\n\n if (data.groups.leave) {\n this.processGroupSyncEntry(data.groups.leave, Category.Leave);\n }\n }\n\n // the returned json structure is a bit crap, so make it into a\n // nicer form (array) after applying sanity to make sure we don't fail\n // on missing keys (on the off chance)\n let inviteRooms: WrappedRoom<IInvitedRoom>[] = [];\n let joinRooms: WrappedRoom<IJoinedRoom>[] = [];\n let leaveRooms: WrappedRoom<ILeftRoom>[] = [];\n\n if (data.rooms) {\n if (data.rooms.invite) {\n inviteRooms = this.mapSyncResponseToRoomArray(data.rooms.invite);\n }\n if (data.rooms.join) {\n joinRooms = this.mapSyncResponseToRoomArray(data.rooms.join);\n }\n if (data.rooms.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n }\n\n this.notifEvents = [];\n\n // Handle invites\n inviteRooms.forEach((inviteObj) => {\n const room = inviteObj.room;\n const stateEvents = this.mapSyncEventsFormat(inviteObj.invite_state, room);\n\n this.processRoomEvents(room, stateEvents);\n if (inviteObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n }\n stateEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n room.updateMyMembership(\"invite\");\n });\n\n // Handle joins\n await utils.promiseMapSeries(joinRooms, async (joinObj) => {\n const room = joinObj.room;\n const stateEvents = this.mapSyncEventsFormat(joinObj.state, room);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n const timelineEvents = this.mapSyncEventsFormat(joinObj.timeline, room, false);\n const ephemeralEvents = this.mapSyncEventsFormat(joinObj.ephemeral);\n const accountDataEvents = this.mapSyncEventsFormat(joinObj.account_data);\n\n const encrypted = client.isRoomEncrypted(room.roomId);\n // we do this first so it's correct when any of the events fire\n if (joinObj.unread_notifications) {\n room.setUnreadNotificationCount(\n NotificationCountType.Total,\n joinObj.unread_notifications.notification_count,\n );\n\n // We track unread notifications ourselves in encrypted rooms, so don't\n // bother setting it here. We trust our calculations better than the\n // server's for this case, and therefore will assume that our non-zero\n // count is accurate.\n if (!encrypted\n || (encrypted && room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0)) {\n room.setUnreadNotificationCount(\n NotificationCountType.Highlight,\n joinObj.unread_notifications.highlight_count,\n );\n }\n }\n\n joinObj.timeline = joinObj.timeline || {} as ITimeline;\n\n if (joinObj.isBrandNewRoom) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(\n joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n } else if (joinObj.timeline.limited) {\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const eventId = timelineEvents[i].getId();\n if (room.getTimelineForEvent(eventId)) {\n debuglog(\"Already have event \" + eventId + \" in limited \" +\n \"sync - not resetting\");\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n timelineEvents.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n\n break;\n }\n }\n\n if (limited) {\n this.deregisterStateListeners(room);\n room.resetLiveTimeline(\n joinObj.timeline.prev_batch,\n this.opts.canResetEntireTimeline(room.roomId) ?\n null : syncEventData.oldSyncToken,\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n client.resetNotifTimelineSet();\n\n this.registerStateListeners(room);\n }\n }\n\n this.processRoomEvents(room, stateEvents, timelineEvents, syncEventData.fromCache);\n\n // set summary after processing events,\n // because it will trigger a name calculation\n // which needs the room state to be up to date\n if (joinObj.summary) {\n room.setSummary(joinObj.summary);\n }\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // we deliberately don't add accountData to the timeline\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (joinObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n }\n\n this.processEventsForNotifs(room, timelineEvents);\n\n const processRoomEvent = async (e) => {\n client.emit(\"event\", e);\n if (e.isState() && e.getType() == \"m.room.encryption\" && this.opts.crypto) {\n await this.opts.crypto.onCryptoEvent(e);\n }\n if (e.isState() && e.getType() === \"im.vector.user_status\") {\n let user = client.store.getUser(e.getStateKey());\n if (user) {\n user.unstable_updateStatusMessage(e);\n } else {\n user = createNewUser(client, e.getStateKey());\n user.unstable_updateStatusMessage(e);\n client.store.storeUser(user);\n }\n }\n };\n\n await utils.promiseMapSeries(stateEvents, processRoomEvent);\n await utils.promiseMapSeries(timelineEvents, processRoomEvent);\n ephemeralEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n accountDataEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n\n room.updateMyMembership(\"join\");\n\n // Decrypt only the last message in all rooms to make sure we can generate a preview\n // And decrypt all events after the recorded read receipt to ensure an accurate\n // notification count\n room.decryptCriticalEvents();\n });\n\n // Handle leaves (e.g. kicked rooms)\n leaveRooms.forEach((leaveObj) => {\n const room = leaveObj.room;\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n const timelineEvents = this.mapSyncEventsFormat(leaveObj.timeline, room);\n const accountDataEvents = this.mapSyncEventsFormat(leaveObj.account_data);\n\n this.processRoomEvents(room, stateEvents, timelineEvents);\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (leaveObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n }\n\n this.processEventsForNotifs(room, timelineEvents);\n\n stateEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n timelineEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n accountDataEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n\n room.updateMyMembership(\"leave\");\n });\n\n // update the notification timeline, if appropriate.\n // we only do this for live events, as otherwise we can't order them sanely\n // in the timeline relative to ones paginated in by /notifications.\n // XXX: we could fix this by making EventTimeline support chronological\n // ordering... but it doesn't, right now.\n if (syncEventData.oldSyncToken && this.notifEvents.length) {\n this.notifEvents.sort(function(a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach(function(event) {\n client.getNotifTimelineSet().addLiveEvent(event);\n });\n }\n\n // Handle device list updates\n if (data.device_lists) {\n if (this.opts.crypto) {\n await this.opts.crypto.handleDeviceListChanges(syncEventData, data.device_lists);\n } else {\n // FIXME if we *don't* have a crypto module, we still need to\n // invalidate the device lists. But that would require a\n // substantial bit of rework :/.\n }\n }\n\n // Handle one_time_keys_count\n if (this.opts.crypto && data.device_one_time_keys_count) {\n const currentCount = data.device_one_time_keys_count.signed_curve25519 || 0;\n this.opts.crypto.updateOneTimeKeyCount(currentCount);\n }\n if (this.opts.crypto && data[\"org.matrix.msc2732.device_unused_fallback_key_types\"]) {\n // The presence of device_unused_fallback_key_types indicates that the\n // server supports fallback keys. If there's no unused\n // signed_curve25519 fallback key we need a new one.\n const unusedFallbackKeys = data[\"org.matrix.msc2732.device_unused_fallback_key_types\"];\n this.opts.crypto.setNeedsNewFallback(\n unusedFallbackKeys instanceof Array &&\n !unusedFallbackKeys.includes(\"signed_curve25519\"),\n );\n }\n }\n\n /**\n * Starts polling the connectivity check endpoint\n * @param {number} delay How long to delay until the first poll.\n * defaults to a short, randomised interval (to prevent\n * tightlooping if /versions succeeds but /sync etc. fail).\n * @return {promise} which resolves once the connection returns\n */\n private startKeepAlives(delay?: number): Promise<boolean> {\n if (delay === undefined) {\n delay = 2000 + Math.floor(Math.random() * 5000);\n }\n\n if (this.keepAliveTimer !== null) {\n clearTimeout(this.keepAliveTimer);\n }\n if (delay > 0) {\n this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);\n } else {\n this.pokeKeepAlive();\n }\n if (!this.connectionReturnedDefer) {\n this.connectionReturnedDefer = utils.defer();\n }\n return this.connectionReturnedDefer.promise;\n }\n\n /**\n * Make a dummy call to /_matrix/client/versions, to see if the HS is\n * reachable.\n *\n * On failure, schedules a call back to itself. On success, resolves\n * this.connectionReturnedDefer.\n *\n * @param {boolean} connDidFail True if a connectivity failure has been detected. Optional.\n */\n private pokeKeepAlive(connDidFail = false): void {\n const success = () => {\n clearTimeout(this.keepAliveTimer);\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.resolve(connDidFail);\n this.connectionReturnedDefer = null;\n }\n };\n\n this.client.http.request(\n undefined, // callback\n \"GET\", \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: '',\n localTimeoutMs: 15 * 1000,\n },\n ).then(() => {\n success();\n }, (err) => {\n if (err.httpStatus == 400 || err.httpStatus == 404) {\n // treat this as a success because the server probably just doesn't\n // support /versions: point is, we're getting a response.\n // We wait a short time though, just in case somehow the server\n // is in a mode where it 400s /versions responses and sync etc.\n // responses fail, this will mean we don't hammer in a loop.\n this.keepAliveTimer = setTimeout(success, 2000);\n } else {\n connDidFail = true;\n this.keepAliveTimer = setTimeout(\n this.pokeKeepAlive.bind(this, connDidFail),\n 5000 + Math.floor(Math.random() * 5000),\n );\n // A keepalive has failed, so we emit the\n // error state (whether or not this is the\n // first failure).\n // Note we do this after setting the timer:\n // this lets the unit tests advance the mock\n // clock when they get the error.\n this.updateSyncState(SyncState.Error, { error: err });\n }\n });\n }\n\n /**\n * @param {Object} groupsSection Groups section object, eg. response.groups.invite\n * @param {string} sectionName Which section this is ('invite', 'join' or 'leave')\n */\n private processGroupSyncEntry(groupsSection: object, sectionName: Category) {\n // Processes entries from 'groups' section of the sync stream\n for (const groupId of Object.keys(groupsSection)) {\n const groupInfo = groupsSection[groupId];\n let group = this.client.store.getGroup(groupId);\n const isBrandNew = group === null;\n if (group === null) {\n group = this.createGroup(groupId);\n }\n if (groupInfo.profile) {\n group.setProfile(\n groupInfo.profile.name, groupInfo.profile.avatar_url,\n );\n }\n if (groupInfo.inviter) {\n group.setInviter({ userId: groupInfo.inviter });\n }\n group.setMyMembership(sectionName);\n if (isBrandNew) {\n // Now we've filled in all the fields, emit the Group event\n this.client.emit(\"Group\", group);\n }\n }\n }\n\n /**\n * @param {Object} obj\n * @return {Object[]}\n */\n private mapSyncResponseToRoomArray<T extends ILeftRoom | IJoinedRoom | IInvitedRoom>(\n obj: Record<string, T>,\n ): Array<WrappedRoom<T>> {\n // Maps { roomid: {stuff}, roomid: {stuff} }\n // to\n // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]\n const client = this.client;\n return Object.keys(obj).map((roomId) => {\n const arrObj = obj[roomId] as T & { room: Room, isBrandNewRoom: boolean };\n let room = client.store.getRoom(roomId);\n let isBrandNewRoom = false;\n if (!room) {\n room = this.createRoom(roomId);\n isBrandNewRoom = true;\n }\n arrObj.room = room;\n arrObj.isBrandNewRoom = isBrandNewRoom;\n return arrObj;\n });\n }\n\n /**\n * @param {Object} obj\n * @param {Room} room\n * @param {boolean} decrypt\n * @return {MatrixEvent[]}\n */\n private mapSyncEventsFormat(\n obj: IInviteState | ITimeline | IEphemeral,\n room?: Room,\n decrypt = true,\n ): MatrixEvent[] {\n if (!obj || !Array.isArray(obj.events)) {\n return [];\n }\n const mapper = this.client.getEventMapper({ decrypt });\n return (obj.events as Array<IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent>).map(function(e) {\n if (room) {\n e[\"room_id\"] = room.roomId;\n }\n return mapper(e);\n });\n }\n\n /**\n * @param {Room} room\n */\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(\"invite\").forEach(function(member) {\n if (member._requestedProfileInfo) return;\n member._requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(function(info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member;\n if (inviteEvent.getContent().membership !== \"invite\") {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n }, function(err) {\n // OH WELL.\n });\n });\n }\n\n /**\n * @param {Room} room\n * @param {MatrixEvent[]} stateEventList A list of state events. This is the state\n * at the *START* of the timeline list if it is supplied.\n * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index\n * @param {boolean} fromCache whether the sync response came from cache\n * is earlier in time. Higher index is later.\n */\n private processRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList?: MatrixEvent[],\n fromCache = false,\n ): void {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList);\n }\n\n this.resolveInvites(room);\n\n // recalculate the room name at this point as adding events to the timeline\n // may make notifications appear which should have the right name.\n // XXX: This looks suspect: we'll end up recalculating the room once here\n // and then again after adding events (processSyncResponse calls it after\n // calling us) even if no state events were added. It also means that if\n // one of the room events in timelineEventList is something that needs\n // a recalculation (like m.room.name) we won't recalculate until we've\n // finished adding all the events, which will cause the notification to have\n // the old room name rather than the new one.\n room.recalculate();\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList || []);\n room.currentState.setStateEvents(stateEventList || []);\n }\n // execute the timeline events. This will continue to diverge the current state\n // if the timeline has any state events in it.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n room.addLiveEvents(timelineEventList || [], null, fromCache);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param {Room} room\n * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private processEventsForNotifs(room: Room, timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (this.client.getNotifTimelineSet()) {\n for (let i = 0; i < timelineEventList.length; i++) {\n const pushActions = this.client.getPushActionsForEvent(timelineEventList[i]);\n if (pushActions && pushActions.notify &&\n pushActions.tweaks && pushActions.tweaks.highlight) {\n this.notifEvents.push(timelineEventList[i]);\n }\n }\n }\n }\n\n /**\n * @return {string}\n */\n private getGuestFilter(): string {\n // Dev note: This used to be conditional to return a filter of 20 events maximum, but\n // the condition never went to the other branch. This is now hardcoded.\n return \"{}\";\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param {String} newState The new state string\n * @param {Object} data Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(\"sync\", this.syncState, old, data);\n }\n\n /**\n * Event handler for the 'online' event\n * This event is generally unreliable and precise behaviour\n * varies between browsers, so we poll for connectivity too,\n * but this might help us reconnect a little faster.\n */\n private onOnline = (): void => {\n debuglog(\"Browser thinks we are back online\");\n this.startKeepAlives(0);\n };\n}\n\nfunction createNewUser(client: MatrixClient, userId: string): User {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n \"User.avatarUrl\", \"User.displayName\", \"User.presence\",\n \"User.currentlyActive\", \"User.lastPresenceTs\",\n ]);\n return user;\n}\n\n",
"/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** @module timeline-window */\n\nimport { Direction, EventTimeline } from './models/event-timeline';\nimport { logger } from './logger';\nimport { MatrixClient } from \"./client\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n * @private\n */\nconst DEBUG = false;\n\n/**\n * @private\n */\nconst debuglog = DEBUG ? logger.log.bind(logger) : function() {};\n\n/**\n * the number of times we ask the server for more events before giving up\n *\n * @private\n */\nconst DEFAULT_PAGINATE_LOOP_LIMIT = 5;\n\ninterface IOpts {\n windowLimit?: number;\n}\n\nexport class TimelineWindow {\n private readonly windowLimit: number;\n // these will be TimelineIndex objects; they delineate the 'start' and\n // 'end' of the window.\n //\n // start.index is inclusive; end.index is exclusive.\n private start?: TimelineIndex = null;\n private end?: TimelineIndex = null;\n private eventCount = 0;\n\n /**\n * Construct a TimelineWindow.\n *\n * <p>This abstracts the separate timelines in a Matrix {@link\n * module:models/room|Room} into a single iterable thing. It keeps track of\n * the start and endpoints of the window, which can be advanced with the help\n * of pagination requests.\n *\n * <p>Before the window is useful, it must be initialised by calling {@link\n * module:timeline-window~TimelineWindow#load|load}.\n *\n * <p>Note that the window will not automatically extend itself when new events\n * are received from /sync; you should arrange to call {@link\n * module:timeline-window~TimelineWindow#paginate|paginate} on {@link\n * module:client~MatrixClient.event:\"Room.timeline\"|Room.timeline} events.\n *\n * @param {MatrixClient} client MatrixClient to be used for context/pagination\n * requests.\n *\n * @param {EventTimelineSet} timelineSet The timelineSet to track\n *\n * @param {Object} [opts] Configuration options for this window\n *\n * @param {number} [opts.windowLimit = 1000] maximum number of events to keep\n * in the window. If more events are retrieved via pagination requests,\n * excess events will be dropped from the other end of the window.\n *\n * @constructor\n */\n constructor(\n private readonly client: MatrixClient,\n private readonly timelineSet: EventTimelineSet,\n opts: IOpts = {},\n ) {\n this.windowLimit = opts.windowLimit || 1000;\n }\n\n /**\n * Initialise the window to point at a given event, or the live timeline\n *\n * @param {string} [initialEventId] If given, the window will contain the\n * given event\n * @param {number} [initialWindowSize = 20] Size of the initial window\n *\n * @return {Promise}\n */\n public load(initialEventId: string, initialWindowSize = 20): Promise<any> {\n // given an EventTimeline, find the event we were looking for, and initialise our\n // fields so that the event in question is in the middle of the window.\n const initFields = (timeline: EventTimeline) => {\n let eventIndex;\n\n const events = timeline.getEvents();\n\n if (!initialEventId) {\n // we were looking for the live timeline: initialise to the end\n eventIndex = events.length;\n } else {\n for (let i = 0; i < events.length; i++) {\n if (events[i].getId() == initialEventId) {\n eventIndex = i;\n break;\n }\n }\n\n if (eventIndex === undefined) {\n throw new Error(\"getEventTimeline result didn't include requested event\");\n }\n }\n\n const endIndex = Math.min(events.length,\n eventIndex + Math.ceil(initialWindowSize / 2));\n const startIndex = Math.max(0, endIndex - initialWindowSize);\n this.start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());\n this.end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());\n this.eventCount = endIndex - startIndex;\n };\n\n // We avoid delaying the resolution of the promise by a reactor tick if\n // we already have the data we need, which is important to keep room-switching\n // feeling snappy.\n //\n if (initialEventId) {\n const timeline = this.timelineSet.getTimelineForEvent(initialEventId);\n if (timeline) {\n // hot-path optimization to save a reactor tick by replicating the sync check getTimelineForEvent does.\n initFields(timeline);\n return Promise.resolve(timeline);\n }\n\n const prom = this.client.getEventTimeline(this.timelineSet, initialEventId);\n return prom.then(initFields);\n } else {\n const tl = this.timelineSet.getLiveTimeline();\n initFields(tl);\n return Promise.resolve();\n }\n }\n\n /**\n * Get the TimelineIndex of the window in the given direction.\n *\n * @param {string} direction EventTimeline.BACKWARDS to get the TimelineIndex\n * at the start of the window; EventTimeline.FORWARDS to get the TimelineIndex at\n * the end.\n *\n * @return {TimelineIndex} The requested timeline index if one exists, null\n * otherwise.\n */\n public getTimelineIndex(direction: Direction): TimelineIndex {\n if (direction == EventTimeline.BACKWARDS) {\n return this.start;\n } else if (direction == EventTimeline.FORWARDS) {\n return this.end;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n }\n\n /**\n * Try to extend the window using events that are already in the underlying\n * TimelineIndex.\n *\n * @param {string} direction EventTimeline.BACKWARDS to try extending it\n * backwards; EventTimeline.FORWARDS to try extending it forwards.\n * @param {number} size number of events to try to extend by.\n *\n * @return {boolean} true if the window was extended, false otherwise.\n */\n public extend(direction: Direction, size: number): boolean {\n const tl = this.getTimelineIndex(direction);\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return false;\n }\n\n const count = (direction == EventTimeline.BACKWARDS) ?\n tl.retreat(size) : tl.advance(size);\n\n if (count) {\n this.eventCount += count;\n debuglog(\"TimelineWindow: increased cap by \" + count +\n \" (now \" + this.eventCount + \")\");\n // remove some events from the other end, if necessary\n const excess = this.eventCount - this.windowLimit;\n if (excess > 0) {\n this.unpaginate(excess, direction != EventTimeline.BACKWARDS);\n }\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if this window can be extended\n *\n * <p>This returns true if we either have more events, or if we have a\n * pagination token which means we can paginate in that direction. It does not\n * necessarily mean that there are more events available in that direction at\n * this time.\n *\n * @param {string} direction EventTimeline.BACKWARDS to check if we can\n * paginate backwards; EventTimeline.FORWARDS to check if we can go forwards\n *\n * @return {boolean} true if we can paginate in the given direction\n */\n public canPaginate(direction: Direction): boolean {\n const tl = this.getTimelineIndex(direction);\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return false;\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n if (tl.index > tl.minIndex()) {\n return true;\n }\n } else {\n if (tl.index < tl.maxIndex()) {\n return true;\n }\n }\n\n return Boolean(tl.timeline.getNeighbouringTimeline(direction) ||\n tl.timeline.getPaginationToken(direction));\n }\n\n /**\n * Attempt to extend the window\n *\n * @param {string} direction EventTimeline.BACKWARDS to extend the window\n * backwards (towards older events); EventTimeline.FORWARDS to go forwards.\n *\n * @param {number} size number of events to try to extend by. If fewer than this\n * number are immediately available, then we return immediately rather than\n * making an API call.\n *\n * @param {boolean} [makeRequest = true] whether we should make API calls to\n * fetch further events if we don't have any at all. (This has no effect if\n * the room already knows about additional events in the relevant direction,\n * even if there are fewer than 'size' of them, as we will just return those\n * we already know about.)\n *\n * @param {number} [requestLimit = 5] limit for the number of API requests we\n * should make.\n *\n * @return {Promise} Resolves to a boolean which is true if more events\n * were successfully retrieved.\n */\n public paginate(\n direction: Direction,\n size: number,\n makeRequest = true,\n requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT,\n ): Promise<boolean> {\n // Either wind back the message cap (if there are enough events in the\n // timeline to do so), or fire off a pagination request.\n const tl = this.getTimelineIndex(direction);\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return Promise.resolve(false);\n }\n\n if (tl.pendingPaginate) {\n return tl.pendingPaginate;\n }\n\n // try moving the cap\n if (this.extend(direction, size)) {\n return Promise.resolve(true);\n }\n\n if (!makeRequest || requestLimit === 0) {\n // todo: should we return something different to indicate that there\n // might be more events out there, but we haven't found them yet?\n return Promise.resolve(false);\n }\n\n // try making a pagination request\n const token = tl.timeline.getPaginationToken(direction);\n if (!token) {\n debuglog(\"TimelineWindow: no token\");\n return Promise.resolve(false);\n }\n\n debuglog(\"TimelineWindow: starting request\");\n\n const prom = this.client.paginateEventTimeline(tl.timeline, {\n backwards: direction == EventTimeline.BACKWARDS,\n limit: size,\n }).finally(function() {\n tl.pendingPaginate = null;\n }).then((r) => {\n debuglog(\"TimelineWindow: request completed with result \" + r);\n if (!r) {\n // end of timeline\n return false;\n }\n\n // recurse to advance the index into the results.\n //\n // If we don't get any new events, we want to make sure we keep asking\n // the server for events for as long as we have a valid pagination\n // token. In particular, we want to know if we've actually hit the\n // start of the timeline, or if we just happened to know about all of\n // the events thanks to https://matrix.org/jira/browse/SYN-645.\n //\n // On the other hand, we necessarily want to wait forever for the\n // server to make its mind up about whether there are other events,\n // because it gives a bad user experience\n // (https://github.com/vector-im/vector-web/issues/1204).\n return this.paginate(direction, size, true, requestLimit - 1);\n });\n tl.pendingPaginate = prom;\n return prom;\n }\n\n /**\n * Remove `delta` events from the start or end of the timeline.\n *\n * @param {number} delta number of events to remove from the timeline\n * @param {boolean} startOfTimeline if events should be removed from the start\n * of the timeline.\n */\n public unpaginate(delta: number, startOfTimeline: boolean): void {\n const tl = startOfTimeline ? this.start : this.end;\n\n // sanity-check the delta\n if (delta > this.eventCount || delta < 0) {\n throw new Error(\"Attemting to unpaginate \" + delta + \" events, but \" +\n \"only have \" + this.eventCount + \" in the timeline\");\n }\n\n while (delta > 0) {\n const count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta);\n if (count <= 0) {\n // sadness. This shouldn't be possible.\n throw new Error(\n \"Unable to unpaginate any further, but still have \" +\n this.eventCount + \" events\");\n }\n\n delta -= count;\n this.eventCount -= count;\n debuglog(\"TimelineWindow.unpaginate: dropped \" + count +\n \" (now \" + this.eventCount + \")\");\n }\n }\n\n /**\n * Get a list of the events currently in the window\n *\n * @return {MatrixEvent[]} the events in the window\n */\n public getEvents(): MatrixEvent[] {\n if (!this.start) {\n // not yet loaded\n return [];\n }\n\n const result = [];\n\n // iterate through each timeline between this.start and this.end\n // (inclusive).\n let timeline = this.start.timeline;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const events = timeline.getEvents();\n\n // For the first timeline in the chain, we want to start at\n // this.start.index. For the last timeline in the chain, we want to\n // stop before this.end.index. Otherwise, we want to copy all of the\n // events in the timeline.\n //\n // (Note that both this.start.index and this.end.index are relative\n // to their respective timelines' BaseIndex).\n //\n let startIndex = 0;\n let endIndex = events.length;\n if (timeline === this.start.timeline) {\n startIndex = this.start.index + timeline.getBaseIndex();\n }\n if (timeline === this.end.timeline) {\n endIndex = this.end.index + timeline.getBaseIndex();\n }\n\n for (let i = startIndex; i < endIndex; i++) {\n result.push(events[i]);\n }\n\n // if we're not done, iterate to the next timeline.\n if (timeline === this.end.timeline) {\n break;\n } else {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.FORWARDS);\n }\n }\n\n return result;\n }\n}\n\n/**\n * a thing which contains a timeline reference, and an index into it.\n *\n * @constructor\n * @param {EventTimeline} timeline\n * @param {number} index\n * @private\n */\nexport class TimelineIndex {\n public pendingPaginate?: Promise<boolean>;\n\n // index: the indexes are relative to BaseIndex, so could well be negative.\n constructor(public timeline: EventTimeline, public index: number) {}\n\n /**\n * @return {number} the minimum possible value for the index in the current\n * timeline\n */\n public minIndex(): number {\n return this.timeline.getBaseIndex() * -1;\n }\n\n /**\n * @return {number} the maximum possible value for the index in the current\n * timeline (exclusive - ie, it actually returns one more than the index\n * of the last element).\n */\n public maxIndex(): number {\n return this.timeline.getEvents().length - this.timeline.getBaseIndex();\n }\n\n /**\n * Try move the index forward, or into the neighbouring timeline\n *\n * @param {number} delta number of events to advance by\n * @return {number} number of events successfully advanced by\n */\n public advance(delta: number): number {\n if (!delta) {\n return 0;\n }\n\n // first try moving the index in the current timeline. See if there is room\n // to do so.\n let cappedDelta;\n if (delta < 0) {\n // we want to wind the index backwards.\n //\n // (this.minIndex() - this.index) is a negative number whose magnitude\n // is the amount of room we have to wind back the index in the current\n // timeline. We cap delta to this quantity.\n cappedDelta = Math.max(delta, this.minIndex() - this.index);\n if (cappedDelta < 0) {\n this.index += cappedDelta;\n return cappedDelta;\n }\n } else {\n // we want to wind the index forwards.\n //\n // (this.maxIndex() - this.index) is a (positive) number whose magnitude\n // is the amount of room we have to wind forward the index in the current\n // timeline. We cap delta to this quantity.\n cappedDelta = Math.min(delta, this.maxIndex() - this.index);\n if (cappedDelta > 0) {\n this.index += cappedDelta;\n return cappedDelta;\n }\n }\n\n // the index is already at the start/end of the current timeline.\n //\n // next see if there is a neighbouring timeline to switch to.\n const neighbour = this.timeline.getNeighbouringTimeline(\n delta < 0 ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS);\n if (neighbour) {\n this.timeline = neighbour;\n if (delta < 0) {\n this.index = this.maxIndex();\n } else {\n this.index = this.minIndex();\n }\n\n debuglog(\"paginate: switched to new neighbour\");\n\n // recurse, using the next timeline\n return this.advance(delta);\n }\n\n return 0;\n }\n\n /**\n * Try move the index backwards, or into the neighbouring timeline\n *\n * @param {number} delta number of events to retreat by\n * @return {number} number of events successfully retreated by\n */\n public retreat(delta: number): number {\n return this.advance(delta * -1) * -1;\n }\n}\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n * @module utils\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport type NodeCrypto from \"crypto\";\n\n/**\n * Encode a dictionary of query parameters.\n * @param {Object} params A dict of key/values to encode e.g.\n * {\"foo\": \"bar\", \"baz\": \"taz\"}\n * @return {string} The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params: Record<string, string>): string {\n let qs = \"\";\n for (const key in params) {\n if (!params.hasOwnProperty(key)) {\n continue;\n }\n qs += \"&\" + encodeURIComponent(key) + \"=\" +\n encodeURIComponent(params[key]);\n }\n return qs.substring(1);\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param {string} pathTemplate The path with template variables e.g. '/foo/$bar'.\n * @param {Object} variables The key/value pairs to replace the template\n * variables with. E.g. { \"$bar\": \"baz\" }.\n * @return {string} The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate: string,\n variables: Record<string, string>): string {\n for (const key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n pathTemplate = pathTemplate.replace(\n key, encodeURIComponent(variables[key]),\n );\n }\n return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param {Array} array The array.\n * @param {Function} fn Function to execute on each value in the array, with the\n * function signature <code>fn(element, index, array)</code>. Return true to\n * remove this element and break.\n * @param {boolean} reverse True to search in reverse order.\n * @return {boolean} True if an element was removed.\n */\nexport function removeElement<T>(\n array: T[],\n fn: (t: T, i?: number, a?: T[]) => boolean,\n reverse?: boolean,\n) {\n let i;\n let removed;\n if (reverse) {\n for (i = array.length - 1; i >= 0; i--) {\n if (fn(array[i], i, array)) {\n removed = array[i];\n array.splice(i, 1);\n return removed;\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (fn(array[i], i, array)) {\n removed = array[i];\n array.splice(i, 1);\n return removed;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param {*} value The thing to check.\n * @return {boolean} True if it is a function.\n */\nexport function isFunction(value: any) {\n return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param {Object} obj The object to check.\n * @param {string[]} keys The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj: object, keys_: string[]) {\n for (let i = 0; i < keys_.length; i++) {\n if (!obj.hasOwnProperty(keys_[i])) {\n throw new Error(\"Missing required key: \" + keys_[i]);\n }\n }\n}\n\n/**\n * Checks that the given object has no extra keys other than the specified ones.\n * @param {Object} obj The object to check.\n * @param {string[]} allowedKeys The list of allowed key names.\n * @throws If there are extra keys.\n */\nexport function checkObjectHasNoAdditionalKeys(obj: object, allowedKeys: string[]): void {\n for (const key in obj) {\n if (!obj.hasOwnProperty(key)) {\n continue;\n }\n if (allowedKeys.indexOf(key) === -1) {\n throw new Error(\"Unknown key: \" + key);\n }\n }\n}\n\n/**\n * Deep copy the given object. The object MUST NOT have circular references and\n * MUST NOT have functions.\n * @param {Object} obj The object to deep copy.\n * @return {Object} A copy of the object without any references to the original.\n */\nexport function deepCopy<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj));\n}\n\n/**\n * Compare two objects for equality. The objects MUST NOT have circular references.\n *\n * @param {Object} x The first object to compare.\n * @param {Object} y The second object to compare.\n *\n * @return {boolean} true if the two objects are equal\n */\nexport function deepCompare(x: any, y: any): boolean {\n // Inspired by\n // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249\n\n // Compare primitives and functions.\n // Also check if both arguments link to the same object.\n if (x === y) {\n return true;\n }\n\n if (typeof x !== typeof y) {\n return false;\n }\n\n // special-case NaN (since NaN !== NaN)\n if (typeof x === 'number' && isNaN(x) && isNaN(y)) {\n return true;\n }\n\n // special-case null (since typeof null == 'object', but null.constructor\n // throws)\n if (x === null || y === null) {\n return x === y;\n }\n\n // everything else is either an unequal primitive, or an object\n if (!(x instanceof Object)) {\n return false;\n }\n\n // check they are the same type of object\n if (x.constructor !== y.constructor || x.prototype !== y.prototype) {\n return false;\n }\n\n // special-casing for some special types of object\n if (x instanceof RegExp || x instanceof Date) {\n return x.toString() === y.toString();\n }\n\n // the object algorithm works for Array, but it's sub-optimal.\n if (x instanceof Array) {\n if (x.length !== y.length) {\n return false;\n }\n\n for (let i = 0; i < x.length; i++) {\n if (!deepCompare(x[i], y[i])) {\n return false;\n }\n }\n } else {\n // disable jshint \"The body of a for in should be wrapped in an if\n // statement\"\n /* jshint -W089 */\n\n // check that all of y's direct keys are in x\n let p;\n for (p in y) {\n if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {\n return false;\n }\n }\n\n // finally, compare each of x's keys with y\n for (p in y) { // eslint-disable-line guard-for-in\n if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {\n return false;\n }\n if (!deepCompare(x[p], y[p])) {\n return false;\n }\n }\n }\n /* jshint +W089 */\n return true;\n}\n\n// Dev note: This returns a tuple, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703\n/**\n * Creates an array of object properties/values (entries) then\n * sorts the result by key, recursively. The input object must\n * ensure it does not have loops. If the input is not an object\n * then it will be returned as-is.\n * @param {*} obj The object to get entries of\n * @returns {Array} The entries, sorted by key.\n */\nexport function deepSortedObjectEntries(obj: any): [string, any][] {\n if (typeof(obj) !== \"object\") return obj;\n\n // Apparently these are object types...\n if (obj === null || obj === undefined || Array.isArray(obj)) return obj;\n\n const pairs: [string, any][] = [];\n for (const [k, v] of Object.entries(obj)) {\n pairs.push([k, deepSortedObjectEntries(v)]);\n }\n\n // lexicographicCompare is faster than localeCompare, so let's use that.\n pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));\n\n return pairs;\n}\n\n/**\n * Copy properties from one object to another.\n *\n * All enumerable properties, included inherited ones, are copied.\n *\n * This is approximately equivalent to ES6's Object.assign, except\n * that the latter doesn't copy inherited properties.\n *\n * @param {Object} target The object that will receive new properties\n * @param {...Object} source Objects from which to copy properties\n *\n * @return {Object} target\n */\nexport function extend(...restParams) {\n const target = restParams[0] || {};\n for (let i = 1; i < restParams.length; i++) {\n const source = restParams[i];\n if (!source) continue;\n for (const propName in source) { // eslint-disable-line guard-for-in\n target[propName] = source[propName];\n }\n }\n return target;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another. This is a\n * port of the Node.js implementation with an Object.create polyfill.\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexport function inherits(ctor: Function, superCtor: Function) {\n // Add util.inherits from Node.js\n // Source:\n // https://github.com/joyent/node/blob/master/lib/util.js\n // Copyright Joyent, Inc. and other Node contributors.\n //\n // Permission is hereby granted, free of charge, to any person obtaining a\n // copy of this software and associated documentation files (the\n // \"Software\"), to deal in the Software without restriction, including\n // without limitation the rights to use, copy, modify, merge, publish,\n // distribute, sublicense, and/or sell copies of the Software, and to permit\n // persons to whom the Software is furnished to do so, subject to the\n // following conditions:\n //\n // The above copyright notice and this permission notice shall be included\n // in all copies or substantial portions of the Software.\n //\n // THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n // USE OR OTHER DEALINGS IN THE SOFTWARE.\n (ctor as any).super_ = superCtor;\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n });\n}\n\n/**\n * Polyfills inheritance for prototypes by allowing different kinds of\n * super types. Typically prototypes would use `SuperType.call(this, params)`\n * though this doesn't always work in some environments - this function\n * falls back to using `Object.assign()` to clone a constructed copy\n * of the super type onto `thisArg`.\n * @param {any} thisArg The child instance. Modified in place.\n * @param {any} SuperType The type to act as a super instance\n * @param {any} params Arguments to supply to the super type's constructor\n */\nexport function polyfillSuper(thisArg: any, SuperType: any, ...params: any[]) {\n try {\n SuperType.call(thisArg, ...params);\n } catch (e) {\n // fall back to Object.assign to just clone the thing\n const fakeSuper = new SuperType(...params);\n Object.assign(thisArg, fakeSuper);\n }\n}\n\n/**\n * Returns whether the given value is a finite number without type-coercion\n *\n * @param {*} value the value to test\n * @return {boolean} whether or not value is a finite number without type-coercion\n */\nexport function isNumber(value: any): boolean {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Removes zero width chars, diacritics and whitespace from the string\n * Also applies an unhomoglyph on the string, to prevent similar looking chars\n * @param {string} str the string to remove hidden characters from\n * @return {string} a string with the hidden characters removed\n */\nexport function removeHiddenChars(str: string): string {\n if (typeof str === \"string\") {\n return unhomoglyph(str.normalize('NFD').replace(removeHiddenCharsRegex, ''));\n }\n return \"\";\n}\n\nexport function normalize(str: string): string {\n // Note: we have to match the filter with the removeHiddenChars() because the\n // function strips spaces and other characters (M becomes RN for example, in lowercase).\n return removeHiddenChars(str.toLowerCase())\n // Strip all punctuation\n .replace(/[\\\\'!\"#$%&()*+,\\-./:;<=>?@[\\]^_`{|}~\\u2000-\\u206f\\u2e00-\\u2e7f]/g, \"\")\n // We also doubly convert to lowercase to work around oddities of the library.\n .toLowerCase();\n}\n\n// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.\n// Includes:\n// various width spaces U+2000 - U+200D\n// LTR and RTL marks U+200E and U+200F\n// LTR/RTL and other directional formatting marks U+202A - U+202F\n// Combining characters U+0300 - U+036F\n// Zero width no-break space (BOM) U+FEFF\n// eslint-disable-next-line no-misleading-character-class\nconst removeHiddenCharsRegex = /[\\u2000-\\u200F\\u202A-\\u202F\\u0300-\\u036f\\uFEFF\\s]/g;\n\nexport function escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function globToRegexp(glob: string, extended: any): string {\n extended = typeof(extended) === 'boolean' ? extended : true;\n // From\n // https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132\n // Because micromatch is about 130KB with dependencies,\n // and minimatch is not much better.\n let pat = escapeRegExp(glob);\n pat = pat.replace(/\\\\\\*/g, '.*');\n pat = pat.replace(/\\?/g, '.');\n if (extended) {\n pat = pat.replace(/\\\\\\[(!|)(.*)\\\\]/g, function(match, p1, p2, offset, string) {\n const first = p1 && '^' || '';\n const second = p2.replace(/\\\\-/, '-');\n return '[' + first + second + ']';\n });\n }\n return pat;\n}\n\nexport function ensureNoTrailingSlash(url: string): string {\n if (url && url.endsWith(\"/\")) {\n return url.substr(0, url.length - 1);\n } else {\n return url;\n }\n}\n\n// Returns a promise which resolves with a given value after the given number of ms\nexport function sleep<T>(ms: number, value?: T): Promise<T> {\n return new Promise((resolve => {\n setTimeout(resolve, ms, value);\n }));\n}\n\nexport function isNullOrUndefined(val: any): boolean {\n return val === null || val === undefined;\n}\n\nexport interface IDeferred<T> {\n resolve: (value: T) => void;\n reject: (reason?: any) => void;\n promise: Promise<T>;\n}\n\n// Returns a Deferred\nexport function defer<T>(): IDeferred<T> {\n let resolve;\n let reject;\n\n const promise = new Promise<T>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n\n return { resolve, reject, promise };\n}\n\nexport async function promiseMapSeries<T>(\n promises: T[],\n fn: (t: T) => void,\n): Promise<void> {\n for (const o of promises) {\n await fn(await o);\n }\n}\n\nexport function promiseTry<T>(fn: () => T): Promise<T> {\n return new Promise((resolve) => resolve(fn()));\n}\n\n// Creates and awaits all promises, running no more than `chunkSize` at the same time\nexport async function chunkPromises<T>(fns: (() => Promise<T>)[], chunkSize: number): Promise<T[]> {\n const results: T[] = [];\n for (let i = 0; i < fns.length; i += chunkSize) {\n results.push(...(await Promise.all(fns.slice(i, i + chunkSize).map(fn => fn()))));\n }\n return results;\n}\n\n/**\n * Retries the function until it succeeds or is interrupted. The given function must return\n * a promise which throws/rejects on error, otherwise the retry will assume the request\n * succeeded. The promise chain returned will contain the successful promise. The given function\n * should always return a new promise.\n * @param {Function} promiseFn The function to call to get a fresh promise instance. Takes an\n * attempt count as an argument, for logging/debugging purposes.\n * @returns {Promise<T>} The promise for the retried operation.\n */\nexport function simpleRetryOperation<T>(promiseFn: (attempt: number) => Promise<T>): Promise<T> {\n return promiseRetry((attempt: number) => {\n return promiseFn(attempt);\n }, {\n forever: true,\n factor: 2,\n minTimeout: 3000, // ms\n maxTimeout: 15000, // ms\n });\n}\n\n// We need to be able to access the Node.js crypto library from within the\n// Matrix SDK without needing to `require(\"crypto\")`, which will fail in\n// browsers. So `index.ts` will call `setCrypto` to store it, and when we need\n// it, we can call `getCrypto`.\nlet crypto: typeof NodeCrypto;\n\nexport function setCrypto(c: typeof NodeCrypto) {\n crypto = c;\n}\n\nexport function getCrypto(): typeof NodeCrypto {\n return crypto;\n}\n\n// String averaging inspired by https://stackoverflow.com/a/2510816\n// Dev note: We make the alphabet a string because it's easier to write syntactically\n// than arrays. Thankfully, strings implement the useful parts of the Array interface\n// anyhow.\n\n/**\n * The default alphabet used by string averaging in this SDK. This matches\n * all usefully printable ASCII characters (0x20-0x7E, inclusive).\n */\nexport const DEFAULT_ALPHABET = (() => {\n let str = \"\";\n for (let c = 0x20; c <= 0x7E; c++) {\n str += String.fromCharCode(c);\n }\n return str;\n})();\n\n/**\n * Pads a string using the given alphabet as a base. The returned string will be\n * padded at the end with the first character in the alphabet.\n *\n * This is intended for use with string averaging.\n * @param {string} s The string to pad.\n * @param {number} n The length to pad to.\n * @param {string} alphabet The alphabet to use as a single string.\n * @returns {string} The padded string.\n */\nexport function alphabetPad(s: string, n: number, alphabet = DEFAULT_ALPHABET): string {\n return s.padEnd(n, alphabet[0]);\n}\n\n/**\n * Converts a baseN number to a string, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param {bigint} n The baseN number.\n * @param {string} alphabet The alphabet to use as a single string.\n * @returns {string} The baseN number encoded as a string from the alphabet.\n */\nexport function baseToString(n: bigint, alphabet = DEFAULT_ALPHABET): string {\n // Developer note: the stringToBase() function offsets the character set by 1 so that repeated\n // characters (ie: \"aaaaaa\" in a..z) don't come out as zero. We have to reverse this here as\n // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun\n // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a\n // sane state. This also means we have to do rollover detection: see below.\n\n const len = BigInt(alphabet.length);\n if (n <= len) {\n return alphabet[Number(n) - 1] ?? \"\";\n }\n\n let d = n / len;\n let r = Number(n % len) - 1;\n\n // Rollover detection: if the remainder is negative, it means that the string needs\n // to roll over by 1 character downwards (ie: in a..z, the previous to \"aaa\" would be\n // \"zz\").\n if (r < 0) {\n d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`.\n r = Number(len) - 1;\n }\n\n return baseToString(d, alphabet) + alphabet[r];\n}\n\n/**\n * Converts a string to a baseN number, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param {string} s The string to convert to a number.\n * @param {string} alphabet The alphabet to use as a single string.\n * @returns {bigint} The baseN number.\n */\nexport function stringToBase(s: string, alphabet = DEFAULT_ALPHABET): bigint {\n const len = BigInt(alphabet.length);\n\n // In our conversion to baseN we do a couple performance optimizations to avoid using\n // excess CPU and such. To create baseN numbers, the input string needs to be reversed\n // so the exponents stack up appropriately, as the last character in the unreversed\n // string has less impact than the first character (in \"abc\" the A is a lot more important\n // for lexicographic sorts). We also do a trick with the character codes to optimize the\n // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know\n // that the alphabet and (theoretically) the input string are constrained on character sets\n // and thus can do simple subtraction to end up with the same result.\n\n // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot\n // rely on Math.pow() (for example) to be capable of handling our insane numbers.\n\n let result = BigInt(0);\n for (let i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {\n const charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);\n\n // We add 1 to the char index to offset the whole numbering scheme. We unpack this in\n // the baseToString() function.\n result += BigInt(1 + charIndex) * (len ** j);\n }\n return result;\n}\n\n/**\n * Averages two strings, returning the midpoint between them. This is accomplished by\n * converting both to baseN numbers (where N is the alphabet's length) then averaging\n * those before re-encoding as a string.\n * @param {string} a The first string.\n * @param {string} b The second string.\n * @param {string} alphabet The alphabet to use as a single string.\n * @returns {string} The midpoint between the strings, as a string.\n */\nexport function averageBetweenStrings(a: string, b: string, alphabet = DEFAULT_ALPHABET): string {\n const padN = Math.max(a.length, b.length);\n const baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);\n const baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);\n const avg = (baseA + baseB) / BigInt(2);\n\n // Detect integer division conflicts. This happens when two numbers are divided too close so\n // we lose a .5 precision. We need to add a padding character in these cases.\n if (avg === baseA || avg == baseB) {\n return baseToString(avg, alphabet) + alphabet[0];\n }\n\n return baseToString(avg, alphabet);\n}\n\n/**\n * Finds the next string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then adding 1 before\n * converting back to a string.\n * @param {string} s The string to start at.\n * @param {string} alphabet The alphabet to use as a single string.\n * @returns {string} The string which follows the input string.\n */\nexport function nextString(s: string, alphabet = DEFAULT_ALPHABET): string {\n return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);\n}\n\n/**\n * Finds the previous string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then subtracting 1 before\n * converting back to a string.\n * @param {string} s The string to start at.\n * @param {string} alphabet The alphabet to use as a single string.\n * @returns {string} The string which precedes the input string.\n */\nexport function prevString(s: string, alphabet = DEFAULT_ALPHABET): string {\n return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);\n}\n\n/**\n * Compares strings lexicographically as a sort-safe function.\n * @param {string} a The first (reference) string.\n * @param {string} b The second (compare) string.\n * @returns {number} Negative if the reference string is before the compare string;\n * positive if the reference string is after; and zero if equal.\n */\nexport function lexicographicCompare(a: string, b: string): number {\n // Dev note: this exists because I'm sad that you can use math operators on strings, so I've\n // hidden the operation in this function.\n return (a < b) ? -1 : ((a === b) ? 0 : 1);\n}\n",
"/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link createNewMatrixCall} for the public API.\n * @module webrtc/call\n */\n\nimport { logger } from '../logger';\nimport { EventEmitter } from 'events';\nimport * as utils from '../utils';\nimport { MatrixEvent } from '../models/event';\nimport { EventType } from '../@types/event';\nimport { RoomMember } from '../models/room-member';\nimport { randomString } from '../randomstring';\nimport {\n MCallReplacesEvent,\n MCallAnswer,\n MCallOfferNegotiate,\n CallCapabilities,\n SDPStreamMetadataPurpose,\n} from './callEventTypes';\nimport { CallFeed } from './callFeed';\n\n// events: hangup, error(err), replaced(call), state(state, oldState)\n\n/**\n * Fires whenever an error occurs when call.js encounters an issue with setting up the call.\n * <p>\n * The error given will have a code equal to either `MatrixCall.ERR_LOCAL_OFFER_FAILED` or\n * `MatrixCall.ERR_NO_USER_MEDIA`. `ERR_LOCAL_OFFER_FAILED` is emitted when the local client\n * fails to create an offer. `ERR_NO_USER_MEDIA` is emitted when the user has denied access\n * to their audio/video hardware.\n *\n * @event module:webrtc/call~MatrixCall#\"error\"\n * @param {Error} err The error raised by MatrixCall.\n * @example\n * matrixCall.on(\"error\", function(err){\n * console.error(err.code, err);\n * });\n */\n\ninterface CallOpts {\n roomId?: string;\n invitee?: string;\n client?: any; // Fix when client is TSified\n forceTURN?: boolean;\n turnServers?: Array<TurnServer>;\n}\n\ninterface TurnServer {\n urls: Array<string>;\n username?: string;\n password?: string;\n ttl?: number;\n}\n\ninterface AssertedIdentity {\n id: string;\n displayName: string;\n}\n\nexport enum CallState {\n Fledgling = 'fledgling',\n InviteSent = 'invite_sent',\n WaitLocalMedia = 'wait_local_media',\n CreateOffer = 'create_offer',\n CreateAnswer = 'create_answer',\n Connecting = 'connecting',\n Connected = 'connected',\n Ringing = 'ringing',\n Ended = 'ended',\n}\n\nexport enum CallType {\n Voice = 'voice',\n Video = 'video',\n}\n\nexport enum CallDirection {\n Inbound = 'inbound',\n Outbound = 'outbound',\n}\n\nexport enum CallParty {\n Local = 'local',\n Remote = 'remote',\n}\n\nexport enum CallEvent {\n Hangup = 'hangup',\n State = 'state',\n Error = 'error',\n Replaced = 'replaced',\n\n // The value of isLocalOnHold() has changed\n LocalHoldUnhold = 'local_hold_unhold',\n // The value of isRemoteOnHold() has changed\n RemoteHoldUnhold = 'remote_hold_unhold',\n // backwards compat alias for LocalHoldUnhold: remove in a major version bump\n HoldUnhold = 'hold_unhold',\n // Feeds have changed\n FeedsChanged = 'feeds_changed',\n\n AssertedIdentityChanged = 'asserted_identity_changed',\n}\n\nexport enum CallErrorCode {\n /** The user chose to end the call */\n UserHangup = 'user_hangup',\n\n /** An error code when the local client failed to create an offer. */\n LocalOfferFailed = 'local_offer_failed',\n /**\n * An error code when there is no local mic/camera to use. This may be because\n * the hardware isn't plugged in, or the user has explicitly denied access.\n */\n NoUserMedia = 'no_user_media',\n\n /**\n * Error code used when a call event failed to send\n * because unknown devices were present in the room\n */\n UnknownDevices = 'unknown_devices',\n\n /**\n * Error code usewd when we fail to send the invite\n * for some reason other than there being unknown devices\n */\n SendInvite = 'send_invite',\n\n /**\n * An answer could not be created\n */\n CreateAnswer = 'create_answer',\n\n /**\n * Error code usewd when we fail to send the answer\n * for some reason other than there being unknown devices\n */\n SendAnswer = 'send_answer',\n\n /**\n * The session description from the other side could not be set\n */\n SetRemoteDescription = 'set_remote_description',\n\n /**\n * The session description from this side could not be set\n */\n SetLocalDescription = 'set_local_description',\n\n /**\n * A different device answered the call\n */\n AnsweredElsewhere = 'answered_elsewhere',\n\n /**\n * No media connection could be established to the other party\n */\n IceFailed = 'ice_failed',\n\n /**\n * The invite timed out whilst waiting for an answer\n */\n InviteTimeout = 'invite_timeout',\n\n /**\n * The call was replaced by another call\n */\n Replaced = 'replaced',\n\n /**\n * Signalling for the call could not be sent (other than the initial invite)\n */\n SignallingFailed = 'signalling_timeout',\n\n /**\n * The remote party is busy\n */\n UserBusy = 'user_busy',\n\n /**\n * We transferred the call off to somewhere else\n */\n Transfered = 'transferred',\n}\n\nexport enum ConstraintsType {\n Audio = \"audio\",\n Video = \"video\",\n}\n\n/**\n * The version field that we set in m.call.* events\n */\nconst VOIP_PROTO_VERSION = 1;\n\n/** The fallback ICE server to use for STUN or TURN protocols. */\nconst FALLBACK_ICE_SERVER = 'stun:turn.matrix.org';\n\n/** The length of time a call can be ringing for. */\nconst CALL_TIMEOUT_MS = 60000;\n\n/** Retrieves sources from desktopCapturer */\nexport function getDesktopCapturerSources(): Promise<Array<DesktopCapturerSource>> {\n const options: GetSourcesOptions = {\n thumbnailSize: {\n height: 176,\n width: 312,\n },\n types: [\n \"screen\",\n \"window\",\n ],\n };\n return window.electron.getDesktopCapturerSources(options);\n}\n\nexport class CallError extends Error {\n code: string;\n\n constructor(code: CallErrorCode, msg: string, err: Error) {\n // Stil ldon't think there's any way to have proper nested errors\n super(msg + \": \" + err);\n\n this.code = code;\n }\n}\n\nfunction genCallID(): string {\n return Date.now().toString() + randomString(16);\n}\n\n/**\n * Construct a new Matrix Call.\n * @constructor\n * @param {Object} opts Config options.\n * @param {string} opts.roomId The room ID for this call.\n * @param {Object} opts.webRtc The WebRTC globals from the browser.\n * @param {boolean} opts.forceTURN whether relay through TURN should be forced.\n * @param {Object} opts.URL The URL global.\n * @param {Array<Object>} opts.turnServers Optional. A list of TURN servers.\n * @param {MatrixClient} opts.client The Matrix Client instance to send events to.\n */\nexport class MatrixCall extends EventEmitter {\n roomId: string;\n invitee?: string;\n type: CallType;\n callId: string;\n state: CallState;\n hangupParty: CallParty;\n hangupReason: string;\n direction: CallDirection;\n ourPartyId: string;\n\n private client: any; // Fix when client is TSified\n private forceTURN: boolean;\n private turnServers: Array<TurnServer>;\n private candidateSendQueue: Array<RTCIceCandidate>;\n private candidateSendTries: number;\n private sentEndOfCandidates: boolean;\n private peerConn: RTCPeerConnection;\n private feeds: Array<CallFeed>;\n private screenSharingStream: MediaStream;\n private localAVStream: MediaStream;\n private inviteOrAnswerSent: boolean;\n private waitForLocalAVStream: boolean;\n private successor: MatrixCall;\n private opponentMember: RoomMember;\n private opponentVersion: number;\n // The party ID of the other side: undefined if we haven't chosen a partner\n // yet, null if we have but they didn't send a party ID.\n private opponentPartyId: string;\n private opponentCaps: CallCapabilities;\n private inviteTimeout: NodeJS.Timeout; // in the browser it's 'number'\n private iceDisconnectedTimeout: NodeJS.Timeout;\n\n // The logic of when & if a call is on hold is nontrivial and explained in is*OnHold\n // This flag represents whether we want the other party to be on hold\n private remoteOnHold;\n\n private micMuted;\n private vidMuted;\n\n // the stats for the call at the point it ended. We can't get these after we\n // tear the call down, so we just grab a snapshot before we stop the call.\n // The typescript definitions have this type as 'any' :(\n private callStatsAtEnd: any[];\n\n // Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example\n private makingOffer: boolean;\n private ignoreOffer: boolean;\n\n // If candidates arrive before we've picked an opponent (which, in particular,\n // will happen if the opponent sends candidates eagerly before the user answers\n // the call) we buffer them up here so we can then add the ones from the party we pick\n private remoteCandidateBuffer = new Map<string, RTCIceCandidate[]>();\n\n private remoteAssertedIdentity: AssertedIdentity;\n\n constructor(opts: CallOpts) {\n super();\n this.roomId = opts.roomId;\n this.invitee = opts.invitee;\n this.client = opts.client;\n this.type = null;\n this.forceTURN = opts.forceTURN;\n this.ourPartyId = this.client.deviceId;\n // Array of Objects with urls, username, credential keys\n this.turnServers = opts.turnServers || [];\n if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {\n this.turnServers.push({\n urls: [FALLBACK_ICE_SERVER],\n });\n }\n for (const server of this.turnServers) {\n utils.checkObjectHasKeys(server, [\"urls\"]);\n }\n\n this.callId = genCallID();\n this.state = CallState.Fledgling;\n\n // A queue for candidates waiting to go out.\n // We try to amalgamate candidates into a single candidate message where\n // possible\n this.candidateSendQueue = [];\n this.candidateSendTries = 0;\n\n this.sentEndOfCandidates = false;\n this.inviteOrAnswerSent = false;\n this.makingOffer = false;\n\n this.remoteOnHold = false;\n this.micMuted = false;\n this.vidMuted = false;\n\n this.feeds = [];\n }\n\n /**\n * Place a voice call to this room.\n * @throws If you have not specified a listener for 'error' events.\n */\n async placeVoiceCall() {\n logger.debug(\"placeVoiceCall\");\n this.checkForErrorListener();\n this.type = CallType.Voice;\n await this.placeCall(ConstraintsType.Audio);\n }\n\n /**\n * Place a video call to this room.\n * @throws If you have not specified a listener for 'error' events.\n */\n async placeVideoCall() {\n logger.debug(\"placeVideoCall\");\n this.checkForErrorListener();\n this.type = CallType.Video;\n await this.placeCall(ConstraintsType.Video);\n }\n\n /**\n * Place a screen-sharing call to this room. This includes audio.\n * <b>This method is EXPERIMENTAL and subject to change without warning. It\n * only works in Google Chrome and Firefox >= 44.</b>\n * @throws If you have not specified a listener for 'error' events.\n */\n async placeScreenSharingCall(selectDesktopCapturerSource?: () => Promise<DesktopCapturerSource>) {\n logger.debug(\"placeScreenSharingCall\");\n this.checkForErrorListener();\n try {\n const screenshareConstraints = await getScreenshareContraints(selectDesktopCapturerSource);\n if (!screenshareConstraints) {\n this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);\n return;\n }\n\n if (window.electron?.getDesktopCapturerSources) {\n // We are using Electron\n logger.debug(\"Getting screen stream using getUserMedia()...\");\n this.screenSharingStream = await navigator.mediaDevices.getUserMedia(screenshareConstraints);\n } else {\n // We are not using Electron\n logger.debug(\"Getting screen stream using getDisplayMedia()...\");\n this.screenSharingStream = await navigator.mediaDevices.getDisplayMedia(screenshareConstraints);\n }\n\n logger.debug(\"Got screen stream, requesting audio stream...\");\n this.placeCall(ConstraintsType.Audio);\n } catch (err) {\n this.emit(CallEvent.Error,\n new CallError(\n CallErrorCode.NoUserMedia,\n \"Failed to get screen-sharing stream: \", err,\n ),\n );\n this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);\n }\n this.type = CallType.Video;\n }\n\n public getOpponentMember() {\n return this.opponentMember;\n }\n\n public opponentCanBeTransferred() {\n return Boolean(this.opponentCaps && this.opponentCaps[\"m.call.transferee\"]);\n }\n\n public getRemoteAssertedIdentity(): AssertedIdentity {\n return this.remoteAssertedIdentity;\n }\n\n /**\n * Returns an array of all CallFeeds\n * @returns {Array<CallFeed>} CallFeeds\n */\n public getFeeds(): Array<CallFeed> {\n return this.feeds;\n }\n\n /**\n * Returns an array of all local CallFeeds\n * @returns {Array<CallFeed>} local CallFeeds\n */\n public getLocalFeeds(): Array<CallFeed> {\n return this.feeds.filter((feed) => feed.isLocal());\n }\n\n /**\n * Returns an array of all remote CallFeeds\n * @returns {Array<CallFeed>} remote CallFeeds\n */\n public getRemoteFeeds(): Array<CallFeed> {\n return this.feeds.filter((feed) => !feed.isLocal());\n }\n\n /**\n * Returns true if there are no incoming feeds,\n * otherwise returns false\n * @returns {boolean} no incoming feeds\n */\n public noIncomingFeeds(): boolean {\n return !this.feeds.some((feed) => !feed.isLocal());\n }\n\n private pushNewFeed(stream: MediaStream, userId: string, purpose: SDPStreamMetadataPurpose) {\n // Try to find a feed with the same stream id as the new stream,\n // if we find it replace the old stream with the new one\n const feed = this.feeds.find((feed) => feed.stream.id === stream.id);\n if (feed) {\n feed.setNewStream(stream);\n } else {\n this.feeds.push(new CallFeed(stream, userId, purpose, this.client, this.roomId));\n this.emit(CallEvent.FeedsChanged, this.feeds);\n }\n }\n\n private deleteAllFeeds() {\n this.feeds = [];\n this.emit(CallEvent.FeedsChanged, this.feeds);\n }\n\n // The typescript definitions have this type as 'any' :(\n public async getCurrentCallStats(): Promise<any[]> {\n if (this.callHasEnded()) {\n return this.callStatsAtEnd;\n }\n\n return this.collectCallStats();\n }\n\n private async collectCallStats(): Promise<any[]> {\n // This happens when the call fails before it starts.\n // For example when we fail to get capture sources\n if (!this.peerConn) return;\n\n const statsReport = await this.peerConn.getStats();\n const stats = [];\n for (const item of statsReport) {\n stats.push(item[1]);\n }\n\n return stats;\n }\n\n /**\n * Configure this call from an invite event. Used by MatrixClient.\n * @param {MatrixEvent} event The m.call.invite event\n */\n async initWithInvite(event: MatrixEvent) {\n const invite = event.getContent();\n this.direction = CallDirection.Inbound;\n\n // make sure we have valid turn creds. Unless something's gone wrong, it should\n // poll and keep the credentials valid so this should be instant.\n const haveTurnCreds = await this.client.checkTurnServers();\n if (!haveTurnCreds) {\n logger.warn(\"Failed to get TURN credentials! Proceeding with call anyway...\");\n }\n\n this.peerConn = this.createPeerConnection();\n // we must set the party ID before await-ing on anything: the call event\n // handler will start giving us more call events (eg. candidates) so if\n // we haven't set the party ID, we'll ignore them.\n this.chooseOpponent(event);\n try {\n await this.peerConn.setRemoteDescription(invite.offer);\n await this.addBufferedIceCandidates();\n } catch (e) {\n logger.debug(\"Failed to set remote description\", e);\n this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n return;\n }\n\n const remoteStream = this.feeds.find((feed) => !feed.isLocal())?.stream;\n\n // According to previous comments in this file, firefox at some point did not\n // add streams until media started ariving on them. Testing latest firefox\n // (81 at time of writing), this is no longer a problem, so let's do it the correct way.\n if (!remoteStream || remoteStream.getTracks().length === 0) {\n logger.error(\"No remote stream or no tracks after setting remote description!\");\n this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n return;\n }\n\n this.type = remoteStream.getTracks().some(t => t.kind === 'video') ? CallType.Video : CallType.Voice;\n\n this.setState(CallState.Ringing);\n\n if (event.getLocalAge()) {\n setTimeout(() => {\n if (this.state == CallState.Ringing) {\n logger.debug(\"Call invite has expired. Hanging up.\");\n this.hangupParty = CallParty.Remote; // effectively\n this.setState(CallState.Ended);\n this.stopAllMedia();\n if (this.peerConn.signalingState != 'closed') {\n this.peerConn.close();\n }\n this.emit(CallEvent.Hangup);\n }\n }, invite.lifetime - event.getLocalAge());\n }\n }\n\n /**\n * Configure this call from a hangup or reject event. Used by MatrixClient.\n * @param {MatrixEvent} event The m.call.hangup event\n */\n initWithHangup(event: MatrixEvent) {\n // perverse as it may seem, sometimes we want to instantiate a call with a\n // hangup message (because when getting the state of the room on load, events\n // come in reverse order and we want to remember that a call has been hung up)\n this.setState(CallState.Ended);\n }\n\n /**\n * Answer a call.\n */\n async answer() {\n if (this.inviteOrAnswerSent) {\n return;\n }\n\n logger.debug(`Answering call ${this.callId} of type ${this.type}`);\n\n if (!this.localAVStream && !this.waitForLocalAVStream) {\n this.setState(CallState.WaitLocalMedia);\n this.waitForLocalAVStream = true;\n\n try {\n let mediaStream: MediaStream;\n\n if (this.type === CallType.Voice) {\n mediaStream = await this.client.getLocalAudioStream();\n } else {\n mediaStream = await this.client.getLocalVideoStream();\n }\n\n this.waitForLocalAVStream = false;\n this.gotUserMediaForAnswer(mediaStream);\n } catch (e) {\n this.getUserMediaFailed(e);\n return;\n }\n } else if (this.localAVStream) {\n this.gotUserMediaForAnswer(this.localAVStream);\n } else if (this.waitForLocalAVStream) {\n this.setState(CallState.WaitLocalMedia);\n }\n }\n\n /**\n * Replace this call with a new call, e.g. for glare resolution. Used by\n * MatrixClient.\n * @param {MatrixCall} newCall The new call.\n */\n replacedBy(newCall: MatrixCall) {\n logger.debug(this.callId + \" being replaced by \" + newCall.callId);\n if (this.state === CallState.WaitLocalMedia) {\n logger.debug(\"Telling new call to wait for local media\");\n newCall.waitForLocalAVStream = true;\n } else if (this.state === CallState.CreateOffer) {\n logger.debug(\"Handing local stream to new call\");\n newCall.gotUserMediaForAnswer(this.localAVStream);\n delete(this.localAVStream);\n } else if (this.state === CallState.InviteSent) {\n logger.debug(\"Handing local stream to new call\");\n newCall.gotUserMediaForAnswer(this.localAVStream);\n delete(this.localAVStream);\n }\n this.successor = newCall;\n this.emit(CallEvent.Replaced, newCall);\n this.hangup(CallErrorCode.Replaced, true);\n }\n\n /**\n * Hangup a call.\n * @param {string} reason The reason why the call is being hung up.\n * @param {boolean} suppressEvent True to suppress emitting an event.\n */\n hangup(reason: CallErrorCode, suppressEvent: boolean) {\n if (this.callHasEnded()) return;\n\n logger.debug(\"Ending call \" + this.callId);\n this.terminate(CallParty.Local, reason, !suppressEvent);\n // We don't want to send hangup here if we didn't even get to sending an invite\n if (this.state === CallState.WaitLocalMedia) return;\n const content = {};\n // Continue to send no reason for user hangups temporarily, until\n // clients understand the user_hangup reason (voip v1)\n if (reason !== CallErrorCode.UserHangup) content['reason'] = reason;\n this.sendVoipEvent(EventType.CallHangup, content);\n }\n\n /**\n * Reject a call\n * This used to be done by calling hangup, but is a separate method and protocol\n * event as of MSC2746.\n */\n reject() {\n if (this.state !== CallState.Ringing) {\n throw Error(\"Call must be in 'ringing' state to reject!\");\n }\n\n if (this.opponentVersion < 1) {\n logger.info(\n `Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`,\n );\n this.hangup(CallErrorCode.UserHangup, true);\n return;\n }\n\n logger.debug(\"Rejecting call: \" + this.callId);\n this.terminate(CallParty.Local, CallErrorCode.UserHangup, true);\n this.sendVoipEvent(EventType.CallReject, {});\n }\n\n /**\n * Set whether our outbound video should be muted or not.\n * @param {boolean} muted True to mute the outbound video.\n */\n setLocalVideoMuted(muted: boolean) {\n this.vidMuted = muted;\n this.updateMuteStatus();\n }\n\n /**\n * Check if local video is muted.\n *\n * If there are multiple video tracks, <i>all</i> of the tracks need to be muted\n * for this to return true. This means if there are no video tracks, this will\n * return true.\n * @return {Boolean} True if the local preview video is muted, else false\n * (including if the call is not set up yet).\n */\n isLocalVideoMuted(): boolean {\n return this.vidMuted;\n }\n\n /**\n * Set whether the microphone should be muted or not.\n * @param {boolean} muted True to mute the mic.\n */\n setMicrophoneMuted(muted: boolean) {\n this.micMuted = muted;\n this.updateMuteStatus();\n }\n\n /**\n * Check if the microphone is muted.\n *\n * If there are multiple audio tracks, <i>all</i> of the tracks need to be muted\n * for this to return true. This means if there are no audio tracks, this will\n * return true.\n * @return {Boolean} True if the mic is muted, else false (including if the call\n * is not set up yet).\n */\n isMicrophoneMuted(): boolean {\n return this.micMuted;\n }\n\n /**\n * @returns true if we have put the party on the other side of the call on hold\n * (that is, we are signalling to them that we are not listening)\n */\n isRemoteOnHold(): boolean {\n return this.remoteOnHold;\n }\n\n setRemoteOnHold(onHold: boolean) {\n if (this.isRemoteOnHold() === onHold) return;\n this.remoteOnHold = onHold;\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n // We don't send hold music or anything so we're not actually\n // sending anything, but sendrecv is fairly standard for hold and\n // it makes it a lot easier to figure out who's put who on hold.\n tranceiver.direction = onHold ? 'sendonly' : 'sendrecv';\n }\n this.updateMuteStatus();\n\n this.emit(CallEvent.RemoteHoldUnhold, this.remoteOnHold);\n }\n\n /**\n * Indicates whether we are 'on hold' to the remote party (ie. if true,\n * they cannot hear us).\n * @returns true if the other party has put us on hold\n */\n isLocalOnHold(): boolean {\n if (this.state !== CallState.Connected) return false;\n\n let callOnHold = true;\n\n // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }\n\n /**\n * Sends a DTMF digit to the other party\n * @param digit The digit (nb. string - '#' and '*' are dtmf too)\n */\n sendDtmfDigit(digit: string) {\n for (const sender of this.peerConn.getSenders()) {\n if (sender.track.kind === 'audio' && sender.dtmf) {\n sender.dtmf.insertDTMF(digit);\n return;\n }\n }\n\n throw new Error(\"Unable to find a track to send DTMF on\");\n }\n\n private updateMuteStatus() {\n if (!this.localAVStream) {\n return;\n }\n\n const micShouldBeMuted = this.micMuted || this.remoteOnHold;\n setTracksEnabled(this.localAVStream.getAudioTracks(), !micShouldBeMuted);\n\n const vidShouldBeMuted = this.vidMuted || this.remoteOnHold;\n setTracksEnabled(this.localAVStream.getVideoTracks(), !vidShouldBeMuted);\n }\n\n /**\n * Internal\n * @param {Object} stream\n */\n private gotUserMediaForInvite = async (stream: MediaStream) => {\n if (this.successor) {\n this.successor.gotUserMediaForAnswer(stream);\n return;\n }\n if (this.callHasEnded()) {\n this.stopAllMedia();\n return;\n }\n this.localAVStream = stream;\n logger.info(\"Got local AV stream with id \" + this.localAVStream.id);\n\n this.setState(CallState.CreateOffer);\n\n logger.debug(\"gotUserMediaForInvite -> \" + this.type);\n\n if (this.screenSharingStream) {\n logger.debug(\n \"Setting screen sharing stream to the local video element\",\n );\n this.pushNewFeed(this.screenSharingStream, this.client.getUserId(), SDPStreamMetadataPurpose.Screenshare);\n } else {\n this.pushNewFeed(stream, this.client.getUserId(), SDPStreamMetadataPurpose.Usermedia);\n }\n\n // why do we enable audio (and only audio) tracks here? -- matthew\n setTracksEnabled(stream.getAudioTracks(), true);\n\n for (const audioTrack of stream.getAudioTracks()) {\n logger.info(\"Adding audio track with id \" + audioTrack.id);\n this.peerConn.addTrack(audioTrack, stream);\n }\n for (const videoTrack of (this.screenSharingStream || stream).getVideoTracks()) {\n logger.info(\"Adding video track with id \" + videoTrack.id);\n this.peerConn.addTrack(videoTrack, stream);\n }\n\n // Now we wait for the negotiationneeded event\n };\n\n private async sendAnswer() {\n const answerContent = {\n answer: {\n sdp: this.peerConn.localDescription.sdp,\n // type is now deprecated as of Matrix VoIP v1, but\n // required to still be sent for backwards compat\n type: this.peerConn.localDescription.type,\n },\n } as MCallAnswer;\n\n if (this.client.supportsCallTransfer) {\n answerContent.capabilities = {\n 'm.call.transferee': true,\n };\n }\n\n // We have just taken the local description from the peerconnection which will\n // contain all the local candidates added so far, so we can discard any candidates\n // we had queued up because they'll be in the answer.\n logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in answer`);\n this.candidateSendQueue = [];\n\n try {\n await this.sendVoipEvent(EventType.CallAnswer, answerContent);\n // If this isn't the first time we've tried to send the answer,\n // we may have candidates queued up, so send them now.\n this.inviteOrAnswerSent = true;\n } catch (error) {\n // We've failed to answer: back to the ringing state\n this.setState(CallState.Ringing);\n this.client.cancelPendingEvent(error.event);\n\n let code = CallErrorCode.SendAnswer;\n let message = \"Failed to send answer\";\n if (error.name == 'UnknownDeviceError') {\n code = CallErrorCode.UnknownDevices;\n message = \"Unknown devices present in the room\";\n }\n this.emit(CallEvent.Error, new CallError(code, message, error));\n throw error;\n }\n\n // error handler re-throws so this won't happen on error, but\n // we don't want the same error handling on the candidate queue\n this.sendCandidateQueue();\n }\n\n private gotUserMediaForAnswer = async (stream: MediaStream) => {\n if (this.callHasEnded()) {\n return;\n }\n\n this.pushNewFeed(stream, this.client.getUserId(), SDPStreamMetadataPurpose.Usermedia);\n\n this.localAVStream = stream;\n logger.info(\"Got local AV stream with id \" + this.localAVStream.id);\n setTracksEnabled(stream.getAudioTracks(), true);\n for (const track of stream.getTracks()) {\n this.peerConn.addTrack(track, stream);\n }\n\n this.setState(CallState.CreateAnswer);\n\n let myAnswer;\n try {\n myAnswer = await this.peerConn.createAnswer();\n } catch (err) {\n logger.debug(\"Failed to create answer: \", err);\n this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);\n return;\n }\n\n try {\n await this.peerConn.setLocalDescription(myAnswer);\n this.setState(CallState.Connecting);\n\n // Allow a short time for initial candidates to be gathered\n await new Promise(resolve => {\n setTimeout(resolve, 200);\n });\n\n this.sendAnswer();\n } catch (err) {\n logger.debug(\"Error setting local description!\", err);\n this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n return;\n }\n };\n\n /**\n * Internal\n * @param {Object} event\n */\n private gotLocalIceCandidate = (event: RTCPeerConnectionIceEvent) => {\n if (event.candidate) {\n logger.debug(\n \"Call \" + this.callId + \" got local ICE \" + event.candidate.sdpMid + \" candidate: \" +\n event.candidate.candidate,\n );\n\n if (this.callHasEnded()) return;\n\n // As with the offer, note we need to make a copy of this object, not\n // pass the original: that broke in Chrome ~m43.\n if (event.candidate.candidate !== '' || !this.sentEndOfCandidates) {\n this.queueCandidate(event.candidate);\n\n if (event.candidate.candidate === '') this.sentEndOfCandidates = true;\n }\n }\n };\n\n private onIceGatheringStateChange = (event: Event) => {\n logger.debug(\"ice gathering state changed to \" + this.peerConn.iceGatheringState);\n if (this.peerConn.iceGatheringState === 'complete' && !this.sentEndOfCandidates) {\n // If we didn't get an empty-string candidate to signal the end of candidates,\n // create one ourselves now gathering has finished.\n // We cast because the interface lists all the properties as required but we\n // only want to send 'candidate'\n // XXX: We probably want to send either sdpMid or sdpMLineIndex, as it's not strictly\n // correct to have a candidate that lacks both of these. We'd have to figure out what\n // previous candidates had been sent with and copy them.\n const c = {\n candidate: '',\n } as RTCIceCandidate;\n this.queueCandidate(c);\n this.sentEndOfCandidates = true;\n }\n };\n\n async onRemoteIceCandidatesReceived(ev: MatrixEvent) {\n if (this.callHasEnded()) {\n //debuglog(\"Ignoring remote ICE candidate because call has ended\");\n return;\n }\n\n const cands = ev.getContent().candidates;\n if (!cands) {\n logger.info(\"Ignoring candidates event with no candidates!\");\n return;\n }\n\n const fromPartyId = ev.getContent().version === 0 ? null : ev.getContent().party_id || null;\n\n if (this.opponentPartyId === undefined) {\n // we haven't picked an opponent yet so save the candidates\n logger.info(`Bufferring ${cands.length} candidates until we pick an opponent`);\n const bufferedCands = this.remoteCandidateBuffer.get(fromPartyId) || [];\n bufferedCands.push(...cands);\n this.remoteCandidateBuffer.set(fromPartyId, bufferedCands);\n return;\n }\n\n if (!this.partyIdMatches(ev.getContent())) {\n logger.info(\n `Ignoring candidates from party ID ${ev.getContent().party_id}: ` +\n `we have chosen party ID ${this.opponentPartyId}`,\n );\n\n return;\n }\n\n await this.addIceCandidates(cands);\n }\n\n /**\n * Used by MatrixClient.\n * @param {Object} msg\n */\n async onAnswerReceived(event: MatrixEvent) {\n logger.debug(`Got answer for call ID ${this.callId} from party ID ${event.getContent().party_id}`);\n\n if (this.callHasEnded()) {\n logger.debug(`Ignoring answer because call ID ${this.callId} has ended`);\n return;\n }\n\n if (this.opponentPartyId !== undefined) {\n logger.info(\n `Ignoring answer from party ID ${event.getContent().party_id}: ` +\n `we already have an answer/reject from ${this.opponentPartyId}`,\n );\n return;\n }\n\n this.chooseOpponent(event);\n await this.addBufferedIceCandidates();\n\n this.setState(CallState.Connecting);\n\n try {\n await this.peerConn.setRemoteDescription(event.getContent().answer);\n } catch (e) {\n logger.debug(\"Failed to set remote description\", e);\n this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n return;\n }\n\n // If the answer we selected has a party_id, send a select_answer event\n // We do this after setting the remote description since otherwise we'd block\n // call setup on it\n if (this.opponentPartyId !== null) {\n try {\n await this.sendVoipEvent(EventType.CallSelectAnswer, {\n selected_party_id: this.opponentPartyId,\n });\n } catch (err) {\n // This isn't fatal, and will just mean that if another party has raced to answer\n // the call, they won't know they got rejected, so we carry on & don't retry.\n logger.warn(\"Failed to send select_answer event\", err);\n }\n }\n }\n\n async onSelectAnswerReceived(event: MatrixEvent) {\n if (this.direction !== CallDirection.Inbound) {\n logger.warn(\"Got select_answer for an outbound call: ignoring\");\n return;\n }\n\n const selectedPartyId = event.getContent().selected_party_id;\n\n if (selectedPartyId === undefined || selectedPartyId === null) {\n logger.warn(\"Got nonsensical select_answer with null/undefined selected_party_id: ignoring\");\n return;\n }\n\n if (selectedPartyId !== this.ourPartyId) {\n logger.info(`Got select_answer for party ID ${selectedPartyId}: we are party ID ${this.ourPartyId}.`);\n // The other party has picked somebody else's answer\n this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n }\n }\n\n async onNegotiateReceived(event: MatrixEvent) {\n const description = event.getContent().description;\n if (!description || !description.sdp || !description.type) {\n logger.info(\"Ignoring invalid m.call.negotiate event\");\n return;\n }\n // Politeness always follows the direction of the call: in a glare situation,\n // we pick either the inbound or outbound call, so one side will always be\n // inbound and one outbound\n const polite = this.direction === CallDirection.Inbound;\n\n // Here we follow the perfect negotiation logic from\n // https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation\n const offerCollision = (\n (description.type === 'offer') &&\n (this.makingOffer || this.peerConn.signalingState != 'stable')\n );\n\n this.ignoreOffer = !polite && offerCollision;\n if (this.ignoreOffer) {\n logger.info(\"Ignoring colliding negotiate event because we're impolite\");\n return;\n }\n\n const prevLocalOnHold = this.isLocalOnHold();\n\n try {\n await this.peerConn.setRemoteDescription(description);\n\n if (description.type === 'offer') {\n const localDescription = await this.peerConn.createAnswer();\n await this.peerConn.setLocalDescription(localDescription);\n\n this.sendVoipEvent(EventType.CallNegotiate, {\n description: this.peerConn.localDescription,\n });\n }\n } catch (err) {\n logger.warn(\"Failed to complete negotiation\", err);\n }\n\n const newLocalOnHold = this.isLocalOnHold();\n if (prevLocalOnHold !== newLocalOnHold) {\n this.emit(CallEvent.LocalHoldUnhold, newLocalOnHold);\n // also this one for backwards compat\n this.emit(CallEvent.HoldUnhold, newLocalOnHold);\n }\n }\n\n async onAssertedIdentityReceived(event: MatrixEvent) {\n if (!event.getContent().asserted_identity) return;\n\n this.remoteAssertedIdentity = {\n id: event.getContent().asserted_identity.id,\n displayName: event.getContent().asserted_identity.display_name,\n };\n this.emit(CallEvent.AssertedIdentityChanged);\n }\n\n private callHasEnded(): boolean {\n // This exists as workaround to typescript trying to be clever and erroring\n // when putting if (this.state === CallState.Ended) return; twice in the same\n // function, even though that function is async.\n return this.state === CallState.Ended;\n }\n\n private gotLocalOffer = async (description: RTCSessionDescriptionInit) => {\n logger.debug(\"Created offer: \", description);\n\n if (this.callHasEnded()) {\n logger.debug(\"Ignoring newly created offer on call ID \" + this.callId +\n \" because the call has ended\");\n return;\n }\n\n try {\n await this.peerConn.setLocalDescription(description);\n } catch (err) {\n logger.debug(\"Error setting local description!\", err);\n this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n return;\n }\n\n if (this.peerConn.iceGatheringState === 'gathering') {\n // Allow a short time for initial candidates to be gathered\n await new Promise(resolve => {\n setTimeout(resolve, 200);\n });\n }\n\n if (this.callHasEnded()) return;\n\n const eventType = this.state === CallState.CreateOffer ? EventType.CallInvite : EventType.CallNegotiate;\n\n const content = {\n lifetime: CALL_TIMEOUT_MS,\n } as MCallOfferNegotiate;\n\n if (eventType === EventType.CallInvite && this.invitee) {\n content.invitee = this.invitee;\n }\n\n // clunky because TypeScript can't folow the types through if we use an expression as the key\n if (this.state === CallState.CreateOffer) {\n content.offer = this.peerConn.localDescription;\n } else {\n content.description = this.peerConn.localDescription;\n }\n\n if (this.client.supportsCallTransfer) {\n content.capabilities = {\n 'm.call.transferee': true,\n };\n }\n\n // Get rid of any candidates waiting to be sent: they'll be included in the local\n // description we just got and will send in the offer.\n logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in offer`);\n this.candidateSendQueue = [];\n\n try {\n await this.sendVoipEvent(eventType, content);\n } catch (error) {\n logger.error(\"Failed to send invite\", error);\n if (error.event) this.client.cancelPendingEvent(error.event);\n\n let code = CallErrorCode.SignallingFailed;\n let message = \"Signalling failed\";\n if (this.state === CallState.CreateOffer) {\n code = CallErrorCode.SendInvite;\n message = \"Failed to send invite\";\n }\n if (error.name == 'UnknownDeviceError') {\n code = CallErrorCode.UnknownDevices;\n message = \"Unknown devices present in the room\";\n }\n\n this.emit(CallEvent.Error, new CallError(code, message, error));\n this.terminate(CallParty.Local, code, false);\n\n // no need to carry on & send the candidate queue, but we also\n // don't want to rethrow the error\n return;\n }\n\n this.sendCandidateQueue();\n if (this.state === CallState.CreateOffer) {\n this.inviteOrAnswerSent = true;\n this.setState(CallState.InviteSent);\n this.inviteTimeout = setTimeout(() => {\n this.inviteTimeout = null;\n if (this.state === CallState.InviteSent) {\n this.hangup(CallErrorCode.InviteTimeout, false);\n }\n }, CALL_TIMEOUT_MS);\n }\n };\n\n private getLocalOfferFailed = (err: Error) => {\n logger.error(\"Failed to get local offer\", err);\n\n this.emit(\n CallEvent.Error,\n new CallError(\n CallErrorCode.LocalOfferFailed,\n \"Failed to get local offer!\", err,\n ),\n );\n this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);\n };\n\n private getUserMediaFailed = (err: Error) => {\n if (this.successor) {\n this.successor.getUserMediaFailed(err);\n return;\n }\n\n logger.warn(\"Failed to get user media - ending call\", err);\n\n this.emit(\n CallEvent.Error,\n new CallError(\n CallErrorCode.NoUserMedia,\n \"Couldn't start capturing media! Is your microphone set up and \" +\n \"does this app have permission?\", err,\n ),\n );\n this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);\n };\n\n onIceConnectionStateChanged = () => {\n if (this.callHasEnded()) {\n return; // because ICE can still complete as we're ending the call\n }\n logger.debug(\n \"Call ID \" + this.callId + \": ICE connection state changed to: \" + this.peerConn.iceConnectionState,\n );\n // ideally we'd consider the call to be connected when we get media but\n // chrome doesn't implement any of the 'onstarted' events yet\n if (this.peerConn.iceConnectionState == 'connected') {\n clearTimeout(this.iceDisconnectedTimeout);\n this.setState(CallState.Connected);\n } else if (this.peerConn.iceConnectionState == 'failed') {\n this.hangup(CallErrorCode.IceFailed, false);\n } else if (this.peerConn.iceConnectionState == 'disconnected') {\n this.iceDisconnectedTimeout = setTimeout(() => {\n this.hangup(CallErrorCode.IceFailed, false);\n }, 30 * 1000);\n }\n };\n\n private onSignallingStateChanged = () => {\n logger.debug(\n \"call \" + this.callId + \": Signalling state changed to: \" +\n this.peerConn.signalingState,\n );\n };\n\n private onTrack = (ev: RTCTrackEvent) => {\n if (ev.streams.length === 0) {\n logger.warn(`Streamless ${ev.track.kind} found: ignoring.`);\n return;\n }\n\n const oldRemoteStream = this.feeds.find((feed) => !feed.isLocal())?.stream;\n\n // If we already have a stream, check this track is from the same one\n // Note that we check by ID and always set the remote stream: Chrome appears\n // to make new stream objects when tranciever directionality is changed and the 'active'\n // status of streams change - Dave\n if (oldRemoteStream && ev.streams[0].id !== oldRemoteStream.id) {\n logger.warn(\n `Ignoring new stream ID ${ev.streams[0].id}: we already have stream ID ${oldRemoteStream.id}`,\n );\n return;\n }\n\n if (!oldRemoteStream) {\n logger.info(\"Got remote stream with id \" + ev.streams[0].id);\n }\n\n const newRemoteStream = ev.streams[0];\n\n logger.debug(`Track id ${ev.track.id} of kind ${ev.track.kind} added`);\n\n this.pushNewFeed(newRemoteStream, this.getOpponentMember().userId, SDPStreamMetadataPurpose.Usermedia);\n\n logger.info(\"playing remote. stream active? \" + newRemoteStream.active);\n };\n\n onNegotiationNeeded = async () => {\n logger.info(\"Negotation is needed!\");\n\n if (this.state !== CallState.CreateOffer && this.opponentVersion === 0) {\n logger.info(\"Opponent does not support renegotiation: ignoring negotiationneeded event\");\n return;\n }\n\n this.makingOffer = true;\n try {\n const myOffer = await this.peerConn.createOffer();\n await this.gotLocalOffer(myOffer);\n } catch (e) {\n this.getLocalOfferFailed(e);\n return;\n } finally {\n this.makingOffer = false;\n }\n };\n\n onHangupReceived = (msg) => {\n logger.debug(\"Hangup received for call ID \" + this.callId);\n\n // party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen\n // a partner yet but we're treating the hangup as a reject as per VoIP v0)\n if (this.partyIdMatches(msg) || this.state === CallState.Ringing) {\n // default reason is user_hangup\n this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n } else {\n logger.info(`Ignoring message from party ID ${msg.party_id}: our partner is ${this.opponentPartyId}`);\n }\n };\n\n onRejectReceived = (msg) => {\n logger.debug(\"Reject received for call ID \" + this.callId);\n\n // No need to check party_id for reject because if we'd received either\n // an answer or reject, we wouldn't be in state InviteSent\n\n const shouldTerminate = (\n // reject events also end the call if it's ringing: it's another of\n // our devices rejecting the call.\n ([CallState.InviteSent, CallState.Ringing].includes(this.state)) ||\n // also if we're in the init state and it's an inbound call, since\n // this means we just haven't entered the ringing state yet\n this.state === CallState.Fledgling && this.direction === CallDirection.Inbound\n );\n\n if (shouldTerminate) {\n this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n } else {\n logger.debug(`Call is in state: ${this.state}: ignoring reject`);\n }\n };\n\n onAnsweredElsewhere = (msg) => {\n logger.debug(\"Call ID \" + this.callId + \" answered elsewhere\");\n this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n };\n\n setState(state: CallState) {\n const oldState = this.state;\n this.state = state;\n this.emit(CallEvent.State, state, oldState);\n }\n\n /**\n * Internal\n * @param {string} eventType\n * @param {Object} content\n * @return {Promise}\n */\n private sendVoipEvent(eventType: string, content: object) {\n return this.client.sendEvent(this.roomId, eventType, Object.assign({}, content, {\n version: VOIP_PROTO_VERSION,\n call_id: this.callId,\n party_id: this.ourPartyId,\n }));\n }\n\n queueCandidate(content: RTCIceCandidate) {\n // Sends candidates with are sent in a special way because we try to amalgamate\n // them into one message\n this.candidateSendQueue.push(content);\n\n // Don't send the ICE candidates yet if the call is in the ringing state: this\n // means we tried to pick (ie. started generating candidates) and then failed to\n // send the answer and went back to the ringing state. Queue up the candidates\n // to send if we sucessfully send the answer.\n // Equally don't send if we haven't yet sent the answer because we can send the\n // first batch of candidates along with the answer\n if (this.state === CallState.Ringing || !this.inviteOrAnswerSent) return;\n\n // MSC2746 reccomends these values (can be quite long when calling because the\n // callee will need a while to answer the call)\n const delay = this.direction === CallDirection.Inbound ? 500 : 2000;\n\n if (this.candidateSendTries === 0) {\n setTimeout(() => {\n this.sendCandidateQueue();\n }, delay);\n }\n }\n\n /*\n * Transfers this call to another user\n */\n async transfer(targetUserId: string) {\n // Fetch the target user's global profile info: their room avatar / displayname\n // could be different in whatever room we shae with them.\n const profileInfo = await this.client.getProfileInfo(targetUserId);\n\n const replacementId = genCallID();\n\n const body = {\n replacement_id: genCallID(),\n target_user: {\n id: targetUserId,\n display_name: profileInfo.display_name,\n avatar_url: profileInfo.avatar_url,\n },\n create_call: replacementId,\n } as MCallReplacesEvent;\n\n await this.sendVoipEvent(EventType.CallReplaces, body);\n\n await this.terminate(CallParty.Local, CallErrorCode.Transfered, true);\n }\n\n /*\n * Transfers this call to the target call, effectively 'joining' the\n * two calls (so the remote parties on each call are connected together).\n */\n async transferToCall(transferTargetCall?: MatrixCall) {\n const targetProfileInfo = await this.client.getProfileInfo(transferTargetCall.getOpponentMember().userId);\n const transfereeProfileInfo = await this.client.getProfileInfo(this.getOpponentMember().userId);\n\n const newCallId = genCallID();\n\n const bodyToTransferTarget = {\n // the replacements on each side have their own ID, and it's distinct from the\n // ID of the new call (but we can use the same function to generate it)\n replacement_id: genCallID(),\n target_user: {\n id: this.getOpponentMember().userId,\n display_name: transfereeProfileInfo.display_name,\n avatar_url: transfereeProfileInfo.avatar_url,\n },\n await_call: newCallId,\n } as MCallReplacesEvent;\n\n await transferTargetCall.sendVoipEvent(EventType.CallReplaces, bodyToTransferTarget);\n\n const bodyToTransferee = {\n replacement_id: genCallID(),\n target_user: {\n id: transferTargetCall.getOpponentMember().userId,\n display_name: targetProfileInfo.display_name,\n avatar_url: targetProfileInfo.avatar_url,\n },\n create_call: newCallId,\n } as MCallReplacesEvent;\n\n await this.sendVoipEvent(EventType.CallReplaces, bodyToTransferee);\n\n await this.terminate(CallParty.Local, CallErrorCode.Replaced, true);\n await transferTargetCall.terminate(CallParty.Local, CallErrorCode.Transfered, true);\n }\n\n private async terminate(hangupParty: CallParty, hangupReason: CallErrorCode, shouldEmit: boolean) {\n if (this.callHasEnded()) return;\n\n this.callStatsAtEnd = await this.collectCallStats();\n\n if (this.inviteTimeout) {\n clearTimeout(this.inviteTimeout);\n this.inviteTimeout = null;\n }\n\n // Order is important here: first we stopAllMedia() and only then we can deleteAllFeeds()\n // We don't stop media if the call was replaced as we want to re-use streams in the successor\n if (hangupReason !== CallErrorCode.Replaced) this.stopAllMedia();\n this.deleteAllFeeds();\n\n this.hangupParty = hangupParty;\n this.hangupReason = hangupReason;\n this.setState(CallState.Ended);\n if (this.peerConn && this.peerConn.signalingState !== 'closed') {\n this.peerConn.close();\n }\n if (shouldEmit) {\n this.emit(CallEvent.Hangup, this);\n }\n }\n\n private stopAllMedia() {\n logger.debug(`stopAllMedia (stream=${this.localAVStream})`);\n\n for (const feed of this.feeds) {\n if (!feed.isLocal()) {\n for (const track of feed.stream.getTracks()) {\n track.stop();\n }\n }\n }\n }\n\n private checkForErrorListener() {\n if (this.listeners(\"error\").length === 0) {\n throw new Error(\n \"You MUST attach an error listener using call.on('error', function() {})\",\n );\n }\n }\n\n private async sendCandidateQueue() {\n if (this.candidateSendQueue.length === 0) {\n return;\n }\n\n const cands = this.candidateSendQueue;\n this.candidateSendQueue = [];\n ++this.candidateSendTries;\n const content = {\n candidates: cands,\n };\n logger.debug(\"Attempting to send \" + cands.length + \" candidates\");\n try {\n await this.sendVoipEvent(EventType.CallCandidates, content);\n } catch (error) {\n // don't retry this event: we'll send another one later as we might\n // have more candidates by then.\n if (error.event) this.client.cancelPendingEvent(error.event);\n\n // put all the candidates we failed to send back in the queue\n this.candidateSendQueue.push(...cands);\n\n if (this.candidateSendTries > 5) {\n logger.debug(\n \"Failed to send candidates on attempt \" + this.candidateSendTries +\n \". Giving up on this call.\", error,\n );\n\n const code = CallErrorCode.SignallingFailed;\n const message = \"Signalling failed\";\n\n this.emit(CallEvent.Error, new CallError(code, message, error));\n this.hangup(code, false);\n\n return;\n }\n\n const delayMs = 500 * Math.pow(2, this.candidateSendTries);\n ++this.candidateSendTries;\n logger.debug(\"Failed to send candidates. Retrying in \" + delayMs + \"ms\", error);\n setTimeout(() => {\n this.sendCandidateQueue();\n }, delayMs);\n }\n }\n\n private async placeCall(constraintsType: ConstraintsType) {\n // XXX Find a better way to do this\n this.client.callEventHandler.calls.set(this.callId, this);\n this.setState(CallState.WaitLocalMedia);\n this.direction = CallDirection.Outbound;\n\n // make sure we have valid turn creds. Unless something's gone wrong, it should\n // poll and keep the credentials valid so this should be instant.\n const haveTurnCreds = await this.client.checkTurnServers();\n if (!haveTurnCreds) {\n logger.warn(\"Failed to get TURN credentials! Proceeding with call anyway...\");\n }\n\n // create the peer connection now so it can be gathering candidates while we get user\n // media (assuming a candidate pool size is configured)\n this.peerConn = this.createPeerConnection();\n\n try {\n let mediaStream: MediaStream;\n\n if (constraintsType === ConstraintsType.Audio) {\n mediaStream = await this.client.getLocalAudioStream();\n } else {\n mediaStream = await this.client.getLocalVideoStream();\n }\n\n this.gotUserMediaForInvite(mediaStream);\n } catch (e) {\n this.getUserMediaFailed(e);\n return;\n }\n }\n\n private createPeerConnection(): RTCPeerConnection {\n const pc = new window.RTCPeerConnection({\n iceTransportPolicy: this.forceTURN ? 'relay' : undefined,\n iceServers: this.turnServers,\n iceCandidatePoolSize: this.client.iceCandidatePoolSize,\n });\n\n // 'connectionstatechange' would be better, but firefox doesn't implement that.\n pc.addEventListener('iceconnectionstatechange', this.onIceConnectionStateChanged);\n pc.addEventListener('signalingstatechange', this.onSignallingStateChanged);\n pc.addEventListener('icecandidate', this.gotLocalIceCandidate);\n pc.addEventListener('icegatheringstatechange', this.onIceGatheringStateChange);\n pc.addEventListener('track', this.onTrack);\n pc.addEventListener('negotiationneeded', this.onNegotiationNeeded);\n\n return pc;\n }\n\n private partyIdMatches(msg): boolean {\n // They must either match or both be absent (in which case opponentPartyId will be null)\n // Also we ignore party IDs on the invite/offer if the version is 0, so we must do the same\n // here and use null if the version is 0 (woe betide any opponent sending messages in the\n // same call with different versions)\n const msgPartyId = msg.version === 0 ? null : msg.party_id || null;\n return msgPartyId === this.opponentPartyId;\n }\n\n // Commits to an opponent for the call\n // ev: An invite or answer event\n private chooseOpponent(ev: MatrixEvent) {\n // I choo-choo-choose you\n const msg = ev.getContent();\n\n logger.debug(`Choosing party ID ${msg.party_id} for call ID ${this.callId}`);\n\n this.opponentVersion = msg.version;\n if (this.opponentVersion === 0) {\n // set to null to indicate that we've chosen an opponent, but because\n // they're v0 they have no party ID (even if they sent one, we're ignoring it)\n this.opponentPartyId = null;\n } else {\n // set to their party ID, or if they're naughty and didn't send one despite\n // not being v0, set it to null to indicate we picked an opponent with no\n // party ID\n this.opponentPartyId = msg.party_id || null;\n }\n this.opponentCaps = msg.capabilities || {};\n this.opponentMember = ev.sender;\n }\n\n private async addBufferedIceCandidates() {\n const bufferedCands = this.remoteCandidateBuffer.get(this.opponentPartyId);\n if (bufferedCands) {\n logger.info(`Adding ${bufferedCands.length} buffered candidates for opponent ${this.opponentPartyId}`);\n await this.addIceCandidates(bufferedCands);\n }\n this.remoteCandidateBuffer = null;\n }\n\n private async addIceCandidates(cands: RTCIceCandidate[]) {\n for (const cand of cands) {\n if (\n (cand.sdpMid === null || cand.sdpMid === undefined) &&\n (cand.sdpMLineIndex === null || cand.sdpMLineIndex === undefined)\n ) {\n logger.debug(\"Ignoring remote ICE candidate with no sdpMid or sdpMLineIndex\");\n continue;\n }\n logger.debug(\"Call \" + this.callId + \" got remote ICE \" + cand.sdpMid + \" candidate: \" + cand.candidate);\n try {\n await this.peerConn.addIceCandidate(cand);\n } catch (err) {\n if (!this.ignoreOffer) {\n logger.info(\"Failed to add remote ICE candidate\", err);\n }\n }\n }\n }\n}\n\nfunction setTracksEnabled(tracks: Array<MediaStreamTrack>, enabled: boolean) {\n for (let i = 0; i < tracks.length; i++) {\n tracks[i].enabled = enabled;\n }\n}\n\nexport function getUserMediaContraints(type: ConstraintsType) {\n const isWebkit = !!navigator.webkitGetUserMedia;\n\n switch (type) {\n case ConstraintsType.Audio: {\n return {\n audio: {\n deviceId: audioInput ? { ideal: audioInput } : undefined,\n },\n video: false,\n };\n }\n case ConstraintsType.Video: {\n return {\n audio: {\n deviceId: audioInput ? { ideal: audioInput } : undefined,\n }, video: {\n deviceId: videoInput ? { ideal: videoInput } : undefined,\n /* We want 640x360. Chrome will give it only if we ask exactly,\n FF refuses entirely if we ask exactly, so have to ask for ideal\n instead\n XXX: Is this still true?\n */\n width: isWebkit ? { exact: 640 } : { ideal: 640 },\n height: isWebkit ? { exact: 360 } : { ideal: 360 },\n },\n };\n }\n }\n}\n\nasync function getScreenshareContraints(selectDesktopCapturerSource?: () => Promise<DesktopCapturerSource>) {\n if (window.electron?.getDesktopCapturerSources && selectDesktopCapturerSource) {\n // We have access to getDesktopCapturerSources()\n logger.debug(\"Electron getDesktopCapturerSources() is available...\");\n const selectedSource = await selectDesktopCapturerSource();\n if (!selectedSource) return null;\n return {\n audio: false,\n video: {\n mandatory: {\n chromeMediaSource: \"desktop\",\n chromeMediaSourceId: selectedSource.id,\n },\n },\n };\n } else {\n // We do not have access to the Electron desktop capturer,\n // therefore we can assume we are on the web\n logger.debug(\"Electron desktopCapturer is not available...\");\n return {\n audio: false,\n video: true,\n };\n }\n}\n\nlet audioInput: string;\nlet videoInput: string;\n/**\n * Set an audio input device to use for MatrixCalls\n * @function\n * @param {string=} deviceId the identifier for the device\n * undefined treated as unset\n */\nexport function setAudioInput(deviceId: string) { audioInput = deviceId; }\n/**\n * Set a video input device to use for MatrixCalls\n * @function\n * @param {string=} deviceId the identifier for the device\n * undefined treated as unset\n */\nexport function setVideoInput(deviceId: string) { videoInput = deviceId; }\n\n/**\n * DEPRECATED\n * Use client.createCall()\n *\n * Create a new Matrix call for the browser.\n * @param {MatrixClient} client The client instance to use.\n * @param {string} roomId The room the call is in.\n * @param {Object?} options DEPRECATED optional options map.\n * @param {boolean} options.forceTURN DEPRECATED whether relay through TURN should be\n * forced. This option is deprecated - use opts.forceTURN when creating the matrix client\n * since it's only possible to set this option on outbound calls.\n * @return {MatrixCall} the call or null if the browser doesn't support calling.\n */\nexport function createNewMatrixCall(client: any, roomId: string, options?: CallOpts) {\n // typeof prevents Node from erroring on an undefined reference\n if (typeof(window) === 'undefined' || typeof(document) === 'undefined') {\n // NB. We don't log here as apps try to create a call object as a test for\n // whether calls are supported, so we shouldn't fill the logs up.\n return null;\n }\n\n // Firefox throws on so little as accessing the RTCPeerConnection when operating in\n // a secure mode. There's some information at https://bugzilla.mozilla.org/show_bug.cgi?id=1542616\n // though the concern is that the browser throwing a SecurityError will brick the\n // client creation process.\n try {\n const supported = Boolean(\n window.RTCPeerConnection || window.RTCSessionDescription ||\n window.RTCIceCandidate || navigator.mediaDevices,\n );\n if (!supported) {\n // Adds a lot of noise to test runs, so disable logging there.\n if (process.env.NODE_ENV !== \"test\") {\n logger.error(\"WebRTC is not supported in this browser / environment\");\n }\n return null;\n }\n } catch (e) {\n logger.error(\"Exception thrown when trying to access WebRTC\", e);\n return null;\n }\n\n const optionsForceTURN = options ? options.forceTURN : false;\n\n const opts = {\n client: client,\n roomId: roomId,\n invitee: options && options.invitee,\n turnServers: client.getTurnServers(),\n // call level options\n forceTURN: client.forceTURN || optionsForceTURN,\n };\n const call = new MatrixCall(opts);\n\n client.reEmitter.reEmit(call, Object.values(CallEvent));\n\n return call;\n}\n",
"/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from '../models/event';\nimport { logger } from '../logger';\nimport { createNewMatrixCall, MatrixCall, CallErrorCode, CallState, CallDirection } from './call';\nimport { EventType } from '../@types/event';\nimport { MatrixClient } from '../client';\n\n// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some\n// time to press the 'accept' button\nconst RING_GRACE_PERIOD = 3000;\n\nexport class CallEventHandler {\n client: MatrixClient;\n calls: Map<string, MatrixCall>;\n callEventBuffer: MatrixEvent[];\n candidateEventsByCall: Map<string, Array<MatrixEvent>>;\n\n constructor(client: MatrixClient) {\n this.client = client;\n this.calls = new Map<string, MatrixCall>();\n // The sync code always emits one event at a time, so it will patiently\n // wait for us to finish processing a call invite before delivering the\n // next event, even if that next event is a hangup. We therefore accumulate\n // all our call events and then process them on the 'sync' event, ie.\n // each time a sync has completed. This way, we can avoid emitting incoming\n // call events if we get both the invite and answer/hangup in the same sync.\n // This happens quite often, eg. replaying sync from storage, catchup sync\n // after loading and after we've been offline for a bit.\n this.callEventBuffer = [];\n this.candidateEventsByCall = new Map<string, Array<MatrixEvent>>();\n }\n\n public start() {\n this.client.on(\"sync\", this.evaluateEventBuffer);\n this.client.on(\"event\", this.onEvent);\n }\n\n public stop() {\n this.client.removeListener(\"sync\", this.evaluateEventBuffer);\n this.client.removeListener(\"event\", this.onEvent);\n }\n\n private evaluateEventBuffer = async () => {\n if (this.client.getSyncState() === \"SYNCING\") {\n await Promise.all(this.callEventBuffer.map(event => {\n this.client.decryptEventIfNeeded(event);\n }));\n\n const ignoreCallIds = new Set<String>();\n // inspect the buffer and mark all calls which have been answered\n // or hung up before passing them to the call event handler.\n for (const ev of this.callEventBuffer) {\n if (ev.getType() === EventType.CallAnswer ||\n ev.getType() === EventType.CallHangup) {\n ignoreCallIds.add(ev.getContent().call_id);\n }\n }\n // now loop through the buffer chronologically and inject them\n for (const e of this.callEventBuffer) {\n if (\n e.getType() === EventType.CallInvite &&\n ignoreCallIds.has(e.getContent().call_id)\n ) {\n // This call has previously been answered or hung up: ignore it\n continue;\n }\n try {\n this.handleCallEvent(e);\n } catch (e) {\n logger.error(\"Caught exception handling call event\", e);\n }\n }\n this.callEventBuffer = [];\n }\n };\n\n private onEvent = (event: MatrixEvent) => {\n this.client.decryptEventIfNeeded(event);\n // any call events or ones that might be once they're decrypted\n if (this.eventIsACall(event) || event.isBeingDecrypted()) {\n // queue up for processing once all events from this sync have been\n // processed (see above).\n this.callEventBuffer.push(event);\n }\n\n if (event.isBeingDecrypted() || event.isDecryptionFailure()) {\n // add an event listener for once the event is decrypted.\n event.once(\"Event.decrypted\", () => {\n if (!this.eventIsACall(event)) return;\n\n if (this.callEventBuffer.includes(event)) {\n // we were waiting for that event to decrypt, so recheck the buffer\n this.evaluateEventBuffer();\n } else {\n // This one wasn't buffered so just run the event handler for it\n // straight away\n try {\n this.handleCallEvent(event);\n } catch (e) {\n logger.error(\"Caught exception handling call event\", e);\n }\n }\n });\n }\n };\n\n private eventIsACall(event: MatrixEvent): boolean {\n const type = event.getType();\n /**\n * Unstable prefixes:\n * - org.matrix.call. : MSC3086 https://github.com/matrix-org/matrix-doc/pull/3086\n */\n return type.startsWith(\"m.call.\") || type.startsWith(\"org.matrix.call.\");\n }\n\n private handleCallEvent(event: MatrixEvent) {\n const content = event.getContent();\n let call = content.call_id ? this.calls.get(content.call_id) : undefined;\n //console.info(\"RECV %s content=%s\", event.getType(), JSON.stringify(content));\n\n if (event.getType() === EventType.CallInvite) {\n if (event.getSender() === this.client.credentials.userId) {\n return; // ignore invites you send\n }\n\n if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) {\n return; // expired call\n }\n\n if (call && call.state === CallState.Ended) {\n return; // stale/old invite event\n }\n if (call) {\n logger.log(\n `WARN: Already have a MatrixCall with id ${content.call_id} but got an ` +\n `invite. Clobbering.`,\n );\n }\n\n if (content.invitee && content.invitee !== this.client.getUserId()) {\n return; // This invite was meant for another user in the room\n }\n\n const timeUntilTurnCresExpire = this.client.getTurnServersExpiry() - Date.now();\n logger.info(\"Current turn creds expire in \" + timeUntilTurnCresExpire + \" ms\");\n call = createNewMatrixCall(this.client, event.getRoomId(), {\n forceTURN: this.client.forceTURN,\n });\n if (!call) {\n logger.log(\n \"Incoming call ID \" + content.call_id + \" but this client \" +\n \"doesn't support WebRTC\",\n );\n // don't hang up the call: there could be other clients\n // connected that do support WebRTC and declining the\n // the call on their behalf would be really annoying.\n return;\n }\n\n call.callId = content.call_id;\n const invitePromise = call.initWithInvite(event);\n this.calls.set(call.callId, call);\n\n // if we stashed candidate events for that call ID, play them back now\n if (this.candidateEventsByCall.get(call.callId)) {\n for (const ev of this.candidateEventsByCall.get(call.callId)) {\n call.onRemoteIceCandidatesReceived(ev);\n }\n }\n\n // Were we trying to call that user (room)?\n let existingCall;\n for (const thisCall of this.calls.values()) {\n const isCalling = [CallState.WaitLocalMedia, CallState.CreateOffer, CallState.InviteSent].includes(\n thisCall.state,\n );\n\n if (\n call.roomId === thisCall.roomId &&\n thisCall.direction === CallDirection.Outbound &&\n call.invitee === thisCall.invitee &&\n isCalling\n ) {\n existingCall = thisCall;\n break;\n }\n }\n\n if (existingCall) {\n // If we've only got to wait_local_media or create_offer and\n // we've got an invite, pick the incoming call because we know\n // we haven't sent our invite yet otherwise, pick whichever\n // call has the lowest call ID (by string comparison)\n if (existingCall.state === CallState.WaitLocalMedia ||\n existingCall.state === CallState.CreateOffer ||\n existingCall.callId > call.callId) {\n logger.log(\n \"Glare detected: answering incoming call \" + call.callId +\n \" and canceling outgoing call \" + existingCall.callId,\n );\n existingCall.replacedBy(call);\n call.answer();\n } else {\n logger.log(\n \"Glare detected: rejecting incoming call \" + call.callId +\n \" and keeping outgoing call \" + existingCall.callId,\n );\n call.hangup(CallErrorCode.Replaced, true);\n }\n } else {\n invitePromise.then(() => {\n this.client.emit(\"Call.incoming\", call);\n });\n }\n } else if (event.getType() === EventType.CallAnswer) {\n if (!call) {\n return;\n }\n if (event.getSender() === this.client.credentials.userId) {\n if (call.state === CallState.Ringing) {\n call.onAnsweredElsewhere(content);\n }\n } else {\n call.onAnswerReceived(event);\n }\n } else if (event.getType() === EventType.CallCandidates) {\n if (event.getSender() === this.client.credentials.userId) {\n return;\n }\n if (!call) {\n // store the candidates; we may get a call eventually.\n if (!this.candidateEventsByCall.has(content.call_id)) {\n this.candidateEventsByCall.set(content.call_id, []);\n }\n this.candidateEventsByCall.get(content.call_id).push(event);\n } else {\n call.onRemoteIceCandidatesReceived(event);\n }\n } else if ([EventType.CallHangup, EventType.CallReject].includes(event.getType() as EventType)) {\n // Note that we also observe our own hangups here so we can see\n // if we've already rejected a call that would otherwise be valid\n if (!call) {\n // if not live, store the fact that the call has ended because\n // we're probably getting events backwards so\n // the hangup will come before the invite\n call = createNewMatrixCall(this.client, event.getRoomId());\n if (call) {\n call.callId = content.call_id;\n call.initWithHangup(event);\n this.calls.set(content.call_id, call);\n }\n } else {\n if (call.state !== CallState.Ended) {\n if (event.getType() === EventType.CallHangup) {\n call.onHangupReceived(content);\n } else {\n call.onRejectReceived(content);\n }\n this.calls.delete(content.call_id);\n }\n }\n } else if (event.getType() === EventType.CallSelectAnswer) {\n if (!call) return;\n\n if (event.getContent().party_id === call.ourPartyId) {\n // Ignore remote echo\n return;\n }\n\n call.onSelectAnswerReceived(event);\n } else if (event.getType() === EventType.CallNegotiate) {\n if (!call) return;\n\n if (event.getContent().party_id === call.ourPartyId) {\n // Ignore remote echo\n return;\n }\n\n call.onNegotiateReceived(event);\n } else if (\n event.getType() === EventType.CallAssertedIdentity ||\n event.getType() === EventType.CallAssertedIdentityPrefix\n ) {\n if (!call) return;\n\n if (event.getContent().party_id === call.ourPartyId) {\n // Ignore remote echo (not that we send asserted identity, but still...)\n return;\n }\n\n call.onAssertedIdentityReceived(event);\n }\n }\n}\n",
"// allow camelcase as these are events type that go onto the wire\n/* eslint-disable camelcase */\n\nexport enum SDPStreamMetadataPurpose {\n Usermedia = \"m.usermedia\",\n Screenshare = \"m.screenshare\",\n}\n\ninterface CallOfferAnswer {\n type: string;\n sdp: string;\n}\n\nexport interface CallCapabilities {\n 'm.call.transferee': boolean;\n}\n\nexport interface MCallAnswer {\n answer: CallOfferAnswer;\n capabilities: CallCapabilities;\n}\n\nexport interface MCallOfferNegotiate {\n offer: CallOfferAnswer;\n description: CallOfferAnswer;\n lifetime: number;\n capabilities: CallCapabilities;\n invitee?: string;\n}\n\nexport interface MCallReplacesTarget {\n id: string;\n display_name: string;\n avatar_url: string;\n}\n\nexport interface MCallReplacesEvent {\n replacement_id: string;\n target_user: MCallReplacesTarget;\n create_call: string;\n await_call: string;\n target_room: string;\n}\n/* eslint-enable camelcase */\n",
"/*\nCopyright 2021 Šimon Brandner <simon.bra.ag@gmail.com>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport EventEmitter from \"events\";\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes\";\nimport { MatrixClient } from \"../client\";\nimport { RoomMember } from \"../models/room-member\";\n\nexport enum CallFeedEvent {\n NewStream = \"new_stream\",\n}\n\nexport class CallFeed extends EventEmitter {\n constructor(\n public stream: MediaStream,\n public userId: string,\n public purpose: SDPStreamMetadataPurpose,\n private client: MatrixClient,\n private roomId: string,\n ) {\n super();\n }\n\n /**\n * Returns callRoom member\n * @returns member of the callRoom\n */\n public getMember(): RoomMember {\n const callRoom = this.client.getRoom(this.roomId);\n return callRoom.getMember(this.userId);\n }\n\n /**\n * Returns true if CallFeed is local, otherwise returns false\n * @returns {boolean} is local?\n */\n public isLocal(): boolean {\n return this.userId === this.client.getUserId();\n }\n\n // TODO: The two following methods should be later replaced\n // by something that will also check if the remote is muted\n /**\n * Returns true if audio is muted or if there are no audio\n * tracks, otherwise returns false\n * @returns {boolean} is audio muted?\n */\n public isAudioMuted(): boolean {\n return this.stream.getAudioTracks().length === 0;\n }\n\n /**\n * Returns true video is muted or if there are no video\n * tracks, otherwise returns false\n * @returns {boolean} is video muted?\n */\n public isVideoMuted(): boolean {\n // We assume only one video track\n return this.stream.getVideoTracks().length === 0;\n }\n\n /**\n * Replaces the current MediaStream with a new one.\n * This method should be only used by MatrixCall.\n * @param newStream new stream with which to replace the current one\n */\n public setNewStream(newStream: MediaStream) {\n this.stream = newStream;\n this.emit(CallFeedEvent.NewStream, this.stream);\n }\n}\n"
]
}