Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f34e568a98 | |||
| 6fd80ed3ed | |||
| 9ff11d1f32 | |||
| 41ab3337b5 | |||
| 1432e094c2 | |||
| e09936cc9b | |||
| d32d190a8a | |||
| 53de8d5690 | |||
| 829110b580 | |||
| 59c82cb679 | |||
| 6d3741d55c | |||
| fb565f301b | |||
| afa3b37ad5 | |||
| a57c430b09 | |||
| 583e48086b | |||
| b22c671fee | |||
| 1b86acb2fb | |||
| d2f7a2575e | |||
| 8490f72488 | |||
| d87e53858b | |||
| 917e8c01d8 | |||
| eb3309db43 | |||
| 65741d7860 | |||
| a7a264f4e7 | |||
| 0fa125b60a | |||
| 8aee884d03 | |||
| 876491e38d | |||
| ac7f505a2b | |||
| b5576758e4 | |||
| c32a83fdac | |||
| 2d9556c1bb | |||
| 818b70554a | |||
| 725336ffc6 |
@@ -25,6 +25,6 @@ jobs:
|
||||
steps:
|
||||
- uses: tibdex/backport@v2
|
||||
with:
|
||||
labels_template: "<%= JSON.stringify(labels) %>"
|
||||
labels_template: "<%= JSON.stringify([...labels, 'X-Release-Blocker']) %>"
|
||||
# We can't use GITHUB_TOKEN here or CI won't run on the new PR
|
||||
github_token: ${{ secrets.ELEMENT_BOT_TOKEN }}
|
||||
|
||||
@@ -17,6 +17,7 @@ jobs:
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
cache: "yarn"
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: 🔨 Install dependencies
|
||||
run: "yarn install --pure-lockfile"
|
||||
|
||||
@@ -10,7 +10,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.workflow_run.conclusion == 'success'
|
||||
steps:
|
||||
# We create the status here and then update it to success/failure in the `report` stage
|
||||
# This provides an easy link to this workflow_run from the PR before Cypress is done.
|
||||
- uses: Sibz/github-status-action@v1
|
||||
with:
|
||||
authToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
state: pending
|
||||
context: ${{ github.workflow }} / SonarCloud (${{ github.event.workflow_run.event }} => ${{ github.event_name }})
|
||||
sha: ${{ github.event.workflow_run.head_sha }}
|
||||
target_url: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
|
||||
- name: "🩻 SonarCloud Scan"
|
||||
id: sonarcloud
|
||||
uses: matrix-org/sonarcloud-workflow-action@v2.2
|
||||
with:
|
||||
repository: ${{ github.event.workflow_run.head_repository.full_name }}
|
||||
@@ -22,3 +33,13 @@ jobs:
|
||||
coverage_run_id: ${{ github.event.workflow_run.id }}
|
||||
coverage_workflow_name: tests.yml
|
||||
coverage_extract_path: coverage
|
||||
|
||||
|
||||
- uses: Sibz/github-status-action@v1
|
||||
if: always()
|
||||
with:
|
||||
authToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
state: ${{ steps.sonarcloud.outcome == 'success' && 'success' || 'failure' }}
|
||||
context: ${{ github.workflow }} / SonarCloud (${{ github.event.workflow_run.event }} => ${{ github.event_name }})
|
||||
sha: ${{ github.event.workflow_run.head_sha }}
|
||||
target_url: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
|
||||
@@ -73,7 +73,7 @@ jobs:
|
||||
|
||||
- name: Detecting files changed
|
||||
id: files
|
||||
uses: futuratrepadeira/changed-files@v3.2.1
|
||||
uses: futuratrepadeira/changed-files@v4.0.0
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
pattern: '^.*\.tsx?$'
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
Changes in [19.6.0-rc.1](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v19.6.0-rc.1) (2022-09-20)
|
||||
============================================================================================================
|
||||
|
||||
## ✨ Features
|
||||
* Add a property aggregating all names of a NamespacedValue ([\#2656](https://github.com/matrix-org/matrix-js-sdk/pull/2656)).
|
||||
* Implementation of MSC3824 to add action= param on SSO login ([\#2398](https://github.com/matrix-org/matrix-js-sdk/pull/2398)). Contributed by @hughns.
|
||||
* Add invited_count and joined_count to sliding sync room responses. ([\#2628](https://github.com/matrix-org/matrix-js-sdk/pull/2628)).
|
||||
* Base support for MSC3847: Ignore invites with policy rooms ([\#2626](https://github.com/matrix-org/matrix-js-sdk/pull/2626)). Contributed by @Yoric.
|
||||
|
||||
## 🐛 Bug Fixes
|
||||
* Fix handling of remote echoes doubling up ([\#2639](https://github.com/matrix-org/matrix-js-sdk/pull/2639)). Fixes #2618.
|
||||
|
||||
Changes in [19.5.0](https://github.com/matrix-org/matrix-js-sdk/releases/tag/v19.5.0) (2022-09-13)
|
||||
==================================================================================================
|
||||
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "matrix-js-sdk",
|
||||
"version": "19.5.0",
|
||||
"version": "19.6.0-rc.1",
|
||||
"description": "Matrix Client-Server SDK for Javascript",
|
||||
"engines": {
|
||||
"node": ">=12.9.0"
|
||||
@@ -81,24 +81,24 @@
|
||||
"@matrix-org/olm": "https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.12.tgz",
|
||||
"@types/bs58": "^4.0.1",
|
||||
"@types/content-type": "^1.1.5",
|
||||
"@types/jest": "^28.0.0",
|
||||
"@types/jest": "^29.0.0",
|
||||
"@types/node": "16",
|
||||
"@types/request": "^2.48.5",
|
||||
"@typescript-eslint/eslint-plugin": "^5.6.0",
|
||||
"@typescript-eslint/parser": "^5.6.0",
|
||||
"allchange": "^1.0.6",
|
||||
"babel-jest": "^28.0.0",
|
||||
"babel-jest": "^29.0.0",
|
||||
"babelify": "^10.0.0",
|
||||
"better-docs": "^2.4.0-beta.9",
|
||||
"browserify": "^17.0.0",
|
||||
"docdash": "^1.2.0",
|
||||
"eslint": "8.22.0",
|
||||
"eslint": "8.23.0",
|
||||
"eslint-config-google": "^0.14.0",
|
||||
"eslint-plugin-import": "^2.25.4",
|
||||
"eslint-plugin-matrix-org": "^0.6.0",
|
||||
"exorcist": "^2.0.0",
|
||||
"fake-indexeddb": "^4.0.0",
|
||||
"jest": "^28.0.0",
|
||||
"jest": "^29.0.0",
|
||||
"jest-localstorage-mock": "^2.4.6",
|
||||
"jest-sonar-reporter": "^2.0.0",
|
||||
"jsdoc": "^3.6.6",
|
||||
|
||||
@@ -96,6 +96,9 @@ function check_dependency {
|
||||
}
|
||||
|
||||
function reset_dependency {
|
||||
local depver=$(cat package.json | jq -r .dependencies[\"$1\"])
|
||||
if [ "$depver" == "null" ]; then return 0; fi
|
||||
|
||||
echo "Resetting $1 to develop branch..."
|
||||
yarn add "github:matrix-org/$1#develop"
|
||||
git add -u
|
||||
|
||||
@@ -168,6 +168,7 @@ describe("SlidingSyncSdk", () => {
|
||||
const roomD = "!d_with_notif_count:localhost";
|
||||
const roomE = "!e_with_invite:localhost";
|
||||
const roomF = "!f_calc_room_name:localhost";
|
||||
const roomG = "!g_join_invite_counts:localhost";
|
||||
const data: Record<string, MSC3575RoomData> = {
|
||||
[roomA]: {
|
||||
name: "A",
|
||||
@@ -261,12 +262,25 @@ describe("SlidingSyncSdk", () => {
|
||||
],
|
||||
initial: true,
|
||||
},
|
||||
[roomG]: {
|
||||
name: "G",
|
||||
required_state: [],
|
||||
timeline: [
|
||||
mkOwnStateEvent(EventType.RoomCreate, { creator: selfUserId }, ""),
|
||||
mkOwnStateEvent(EventType.RoomMember, { membership: "join" }, selfUserId),
|
||||
mkOwnStateEvent(EventType.RoomPowerLevels, { users: { [selfUserId]: 100 } }, ""),
|
||||
],
|
||||
joined_count: 5,
|
||||
invited_count: 2,
|
||||
initial: true,
|
||||
},
|
||||
};
|
||||
|
||||
it("can be created with required_state and timeline", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomA, data[roomA]);
|
||||
const gotRoom = client.getRoom(roomA);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.name).toEqual(data[roomA].name);
|
||||
expect(gotRoom.getMyMembership()).toEqual("join");
|
||||
assertTimelineEvents(gotRoom.getLiveTimeline().getEvents().slice(-2), data[roomA].timeline);
|
||||
@@ -276,6 +290,7 @@ describe("SlidingSyncSdk", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomB, data[roomB]);
|
||||
const gotRoom = client.getRoom(roomB);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.name).toEqual(data[roomB].name);
|
||||
expect(gotRoom.getMyMembership()).toEqual("join");
|
||||
assertTimelineEvents(gotRoom.getLiveTimeline().getEvents().slice(-5), data[roomB].timeline);
|
||||
@@ -285,6 +300,7 @@ describe("SlidingSyncSdk", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomC, data[roomC]);
|
||||
const gotRoom = client.getRoom(roomC);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(
|
||||
gotRoom.getUnreadNotificationCount(NotificationCountType.Highlight),
|
||||
).toEqual(data[roomC].highlight_count);
|
||||
@@ -294,15 +310,26 @@ describe("SlidingSyncSdk", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomD, data[roomD]);
|
||||
const gotRoom = client.getRoom(roomD);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(
|
||||
gotRoom.getUnreadNotificationCount(NotificationCountType.Total),
|
||||
).toEqual(data[roomD].notification_count);
|
||||
});
|
||||
|
||||
it("can be created with an invited/joined_count", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomG, data[roomG]);
|
||||
const gotRoom = client.getRoom(roomG);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.getInvitedMemberCount()).toEqual(data[roomG].invited_count);
|
||||
expect(gotRoom.getJoinedMemberCount()).toEqual(data[roomG].joined_count);
|
||||
});
|
||||
|
||||
it("can be created with invite_state", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomE, data[roomE]);
|
||||
const gotRoom = client.getRoom(roomE);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.getMyMembership()).toEqual("invite");
|
||||
expect(gotRoom.currentState.getJoinRule()).toEqual(JoinRule.Invite);
|
||||
});
|
||||
@@ -311,6 +338,7 @@ describe("SlidingSyncSdk", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomF, data[roomF]);
|
||||
const gotRoom = client.getRoom(roomF);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(
|
||||
gotRoom.name,
|
||||
).toEqual(data[roomF].name);
|
||||
@@ -326,6 +354,7 @@ describe("SlidingSyncSdk", () => {
|
||||
});
|
||||
const gotRoom = client.getRoom(roomA);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
const newTimeline = data[roomA].timeline;
|
||||
newTimeline.push(newEvent);
|
||||
assertTimelineEvents(gotRoom.getLiveTimeline().getEvents().slice(-3), newTimeline);
|
||||
@@ -333,6 +362,8 @@ describe("SlidingSyncSdk", () => {
|
||||
|
||||
it("can update with a new required_state event", async () => {
|
||||
let gotRoom = client.getRoom(roomB);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.getJoinRule()).toEqual(JoinRule.Invite); // default
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomB, {
|
||||
required_state: [
|
||||
@@ -343,6 +374,7 @@ describe("SlidingSyncSdk", () => {
|
||||
});
|
||||
gotRoom = client.getRoom(roomB);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.getJoinRule()).toEqual(JoinRule.Restricted);
|
||||
});
|
||||
|
||||
@@ -355,6 +387,7 @@ describe("SlidingSyncSdk", () => {
|
||||
});
|
||||
const gotRoom = client.getRoom(roomC);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(
|
||||
gotRoom.getUnreadNotificationCount(NotificationCountType.Highlight),
|
||||
).toEqual(1);
|
||||
@@ -369,11 +402,25 @@ describe("SlidingSyncSdk", () => {
|
||||
});
|
||||
const gotRoom = client.getRoom(roomD);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(
|
||||
gotRoom.getUnreadNotificationCount(NotificationCountType.Total),
|
||||
).toEqual(1);
|
||||
});
|
||||
|
||||
it("can update with a new joined_count", () => {
|
||||
mockSlidingSync.emit(SlidingSyncEvent.RoomData, roomG, {
|
||||
name: data[roomD].name,
|
||||
required_state: [],
|
||||
timeline: [],
|
||||
joined_count: 1,
|
||||
});
|
||||
const gotRoom = client.getRoom(roomG);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
expect(gotRoom.getJoinedMemberCount()).toEqual(1);
|
||||
});
|
||||
|
||||
// Regression test for a bug which caused the timeline entries to be out-of-order
|
||||
// when the same room appears twice with different timeline limits. E.g appears in
|
||||
// the list with timeline_limit:1 then appears again as a room subscription with
|
||||
@@ -394,6 +441,7 @@ describe("SlidingSyncSdk", () => {
|
||||
});
|
||||
const gotRoom = client.getRoom(roomA);
|
||||
expect(gotRoom).toBeDefined();
|
||||
if (gotRoom == null) { return; }
|
||||
|
||||
logger.log("want:", oldTimeline.map((e) => (e.type + " : " + (e.content || {}).body)));
|
||||
logger.log("got:", gotRoom.getLiveTimeline().getEvents().map(
|
||||
|
||||
@@ -21,18 +21,21 @@ describe("NamespacedValue", () => {
|
||||
const ns = new NamespacedValue("stable", "unstable");
|
||||
expect(ns.name).toBe(ns.stable);
|
||||
expect(ns.altName).toBe(ns.unstable);
|
||||
expect(ns.names).toEqual([ns.stable, ns.unstable]);
|
||||
});
|
||||
|
||||
it("should return unstable if there is no stable", () => {
|
||||
const ns = new NamespacedValue(null, "unstable");
|
||||
expect(ns.name).toBe(ns.unstable);
|
||||
expect(ns.altName).toBeFalsy();
|
||||
expect(ns.names).toEqual([ns.unstable]);
|
||||
});
|
||||
|
||||
it("should have a falsey unstable if needed", () => {
|
||||
const ns = new NamespacedValue("stable", null);
|
||||
expect(ns.name).toBe(ns.stable);
|
||||
expect(ns.altName).toBeFalsy();
|
||||
expect(ns.names).toEqual([ns.stable]);
|
||||
});
|
||||
|
||||
it("should match against either stable or unstable", () => {
|
||||
@@ -58,12 +61,14 @@ describe("UnstableValue", () => {
|
||||
const ns = new UnstableValue("stable", "unstable");
|
||||
expect(ns.name).toBe(ns.unstable);
|
||||
expect(ns.altName).toBe(ns.stable);
|
||||
expect(ns.names).toEqual([ns.unstable, ns.stable]);
|
||||
});
|
||||
|
||||
it("should return unstable if there is no stable", () => {
|
||||
const ns = new UnstableValue(null, "unstable");
|
||||
expect(ns.name).toBe(ns.unstable);
|
||||
expect(ns.altName).toBeFalsy();
|
||||
expect(ns.names).toEqual([ns.unstable]);
|
||||
});
|
||||
|
||||
it("should not permit falsey unstable values", () => {
|
||||
|
||||
@@ -250,8 +250,8 @@ describe("Secrets", function() {
|
||||
|
||||
osborne2.client.crypto.deviceList.storeDevicesForUser("@alice:example.com", {
|
||||
"VAX": {
|
||||
user_id: "@alice:example.com",
|
||||
device_id: "VAX",
|
||||
verified: 0,
|
||||
known: false,
|
||||
algorithms: [olmlib.OLM_ALGORITHM, olmlib.MEGOLM_ALGORITHM],
|
||||
keys: {
|
||||
"ed25519:VAX": vaxDevice.deviceEd25519Key,
|
||||
@@ -261,9 +261,9 @@ describe("Secrets", function() {
|
||||
});
|
||||
vax.client.crypto.deviceList.storeDevicesForUser("@alice:example.com", {
|
||||
"Osborne2": {
|
||||
user_id: "@alice:example.com",
|
||||
device_id: "Osborne2",
|
||||
algorithms: [olmlib.OLM_ALGORITHM, olmlib.MEGOLM_ALGORITHM],
|
||||
verified: 0,
|
||||
known: false,
|
||||
keys: {
|
||||
"ed25519:Osborne2": osborne2Device.deviceEd25519Key,
|
||||
"curve25519:Osborne2": osborne2Device.deviceCurve25519Key,
|
||||
|
||||
+2
-2
@@ -13,9 +13,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
import { MatrixClient } from "../../../../src/client";
|
||||
import { InRoomChannel } from "../../../../src/crypto/verification/request/InRoomChannel";
|
||||
import { MatrixEvent } from "../../../../src/models/event";
|
||||
"../../../../src/crypto/verification/request/ToDeviceChannel";
|
||||
|
||||
describe("InRoomChannel tests", function() {
|
||||
const ALICE = "@alice:hs.tld";
|
||||
@@ -23,7 +23,7 @@ describe("InRoomChannel tests", function() {
|
||||
const MALORY = "@malory:hs.tld";
|
||||
const client = {
|
||||
getUserId() { return ALICE; },
|
||||
};
|
||||
} as unknown as MatrixClient;
|
||||
|
||||
it("getEventType only returns .request for a message with a msgtype", function() {
|
||||
const invalidEvent = new MatrixEvent({
|
||||
+9
-10
@@ -15,7 +15,7 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
import "../../../olm-loader";
|
||||
import { verificationMethods } from "../../../../src/crypto";
|
||||
import { CryptoEvent, verificationMethods } from "../../../../src/crypto";
|
||||
import { logger } from "../../../../src/logger";
|
||||
import { SAS } from "../../../../src/crypto/verification/SAS";
|
||||
import { makeTestClients, setupWebcrypto, teardownWebcrypto } from './util';
|
||||
@@ -52,23 +52,22 @@ describe("verification request integration tests with crypto layer", function()
|
||||
alice.client.crypto.deviceList.getRawStoredDevicesForUser = function() {
|
||||
return {
|
||||
Dynabook: {
|
||||
algorithms: [],
|
||||
verified: 0,
|
||||
known: false,
|
||||
keys: {
|
||||
"ed25519:Dynabook": "bob+base64+ed25519+key",
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
alice.client.downloadKeys = () => {
|
||||
return Promise.resolve();
|
||||
};
|
||||
bob.client.downloadKeys = () => {
|
||||
return Promise.resolve();
|
||||
};
|
||||
bob.client.on("crypto.verification.request", (request) => {
|
||||
alice.client.downloadKeys = jest.fn().mockResolvedValue({});
|
||||
bob.client.downloadKeys = jest.fn().mockResolvedValue({});
|
||||
bob.client.on(CryptoEvent.VerificationRequest, (request) => {
|
||||
const bobVerifier = request.beginKeyVerification(verificationMethods.SAS);
|
||||
bobVerifier.verify();
|
||||
|
||||
// XXX: Private function access (but it's a test, so we're okay)
|
||||
// @ts-ignore Private function access (but it's a test, so we're okay)
|
||||
bobVerifier.endTimer();
|
||||
});
|
||||
const aliceRequest = await alice.client.requestVerification("@bob:example.com");
|
||||
@@ -76,7 +75,7 @@ describe("verification request integration tests with crypto layer", function()
|
||||
const aliceVerifier = aliceRequest.verifier;
|
||||
expect(aliceVerifier).toBeInstanceOf(SAS);
|
||||
|
||||
// XXX: Private function access (but it's a test, so we're okay)
|
||||
// @ts-ignore Private function access (but it's a test, so we're okay)
|
||||
aliceVerifier.endTimer();
|
||||
|
||||
alice.stop();
|
||||
+17
-15
@@ -19,10 +19,14 @@ import { makeTestClients, setupWebcrypto, teardownWebcrypto } from './util';
|
||||
import { MatrixEvent } from "../../../../src/models/event";
|
||||
import { SAS } from "../../../../src/crypto/verification/SAS";
|
||||
import { DeviceInfo } from "../../../../src/crypto/deviceinfo";
|
||||
import { verificationMethods } from "../../../../src/crypto";
|
||||
import { CryptoEvent, verificationMethods } from "../../../../src/crypto";
|
||||
import * as olmlib from "../../../../src/crypto/olmlib";
|
||||
import { logger } from "../../../../src/logger";
|
||||
import { resetCrossSigningKeys } from "../crypto-utils";
|
||||
import { VerificationBase } from "../../../../src/crypto/verification/Base";
|
||||
import { IVerificationChannel } from "../../../../src/crypto/verification/request/Channel";
|
||||
import { MatrixClient } from "../../../../src";
|
||||
import { VerificationRequest } from "../../../../src/crypto/verification/request/VerificationRequest";
|
||||
|
||||
const Olm = global.Olm;
|
||||
|
||||
@@ -48,13 +52,15 @@ describe("SAS verification", function() {
|
||||
//channel, baseApis, userId, deviceId, startEvent, request
|
||||
const request = {
|
||||
onVerifierCancelled: function() {},
|
||||
};
|
||||
} as VerificationRequest;
|
||||
const channel = {
|
||||
send: function() {
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
const sas = new SAS(channel, {}, "@alice:example.com", "ABCDEFG", null, request);
|
||||
} as unknown as IVerificationChannel;
|
||||
const mockClient = {} as unknown as MatrixClient;
|
||||
const event = new MatrixEvent({ type: 'test' });
|
||||
const sas = new SAS(channel, mockClient, "@alice:example.com", "ABCDEFG", event, request);
|
||||
sas.handleEvent(new MatrixEvent({
|
||||
sender: "@alice:example.com",
|
||||
type: "es.inquisition",
|
||||
@@ -65,7 +71,7 @@ describe("SAS verification", function() {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
|
||||
// Cancel the SAS for cleanup (we started a verification, so abort)
|
||||
sas.cancel();
|
||||
sas.cancel(new Error('error'));
|
||||
});
|
||||
|
||||
describe("verification", () => {
|
||||
@@ -403,16 +409,12 @@ describe("SAS verification", function() {
|
||||
},
|
||||
);
|
||||
alice.client.setDeviceVerified = jest.fn();
|
||||
alice.client.downloadKeys = () => {
|
||||
return Promise.resolve();
|
||||
};
|
||||
alice.client.downloadKeys = jest.fn().mockResolvedValue({});
|
||||
bob.client.setDeviceVerified = jest.fn();
|
||||
bob.client.downloadKeys = () => {
|
||||
return Promise.resolve();
|
||||
};
|
||||
bob.client.downloadKeys = jest.fn().mockResolvedValue({});
|
||||
|
||||
const bobPromise = new Promise((resolve, reject) => {
|
||||
bob.client.on("crypto.verification.request", request => {
|
||||
const bobPromise = new Promise<VerificationBase<any, any>>((resolve, reject) => {
|
||||
bob.client.on(CryptoEvent.VerificationRequest, request => {
|
||||
request.verifier.on("show_sas", (e) => {
|
||||
e.mismatch();
|
||||
});
|
||||
@@ -421,7 +423,7 @@ describe("SAS verification", function() {
|
||||
});
|
||||
|
||||
const aliceVerifier = alice.client.beginKeyVerification(
|
||||
verificationMethods.SAS, bob.client.getUserId(), bob.client.deviceId,
|
||||
verificationMethods.SAS, bob.client.getUserId()!, bob.client.deviceId!,
|
||||
);
|
||||
|
||||
const aliceSpy = jest.fn();
|
||||
@@ -501,7 +503,7 @@ describe("SAS verification", function() {
|
||||
aliceSasEvent = null;
|
||||
bobSasEvent = null;
|
||||
|
||||
bobPromise = new Promise((resolve, reject) => {
|
||||
bobPromise = new Promise<void>((resolve, reject) => {
|
||||
bob.client.on("crypto.verification.request", async (request) => {
|
||||
const verifier = request.beginKeyVerification(SAS.NAME);
|
||||
verifier.on("show_sas", (e) => {
|
||||
+27
-10
@@ -18,6 +18,9 @@ import { CrossSigningInfo } from '../../../../src/crypto/CrossSigning';
|
||||
import { encodeBase64 } from "../../../../src/crypto/olmlib";
|
||||
import { setupWebcrypto, teardownWebcrypto } from './util';
|
||||
import { VerificationBase } from '../../../../src/crypto/verification/Base';
|
||||
import { MatrixClient, MatrixEvent } from '../../../../src';
|
||||
import { VerificationRequest } from '../../../../src/crypto/verification/request/VerificationRequest';
|
||||
import { IVerificationChannel } from '../../../../src/crypto/verification/request/Channel';
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
@@ -54,9 +57,21 @@ describe("self-verifications", () => {
|
||||
cacheCallbacks,
|
||||
);
|
||||
crossSigningInfo.keys = {
|
||||
master: { keys: { X: testKeyPub } },
|
||||
self_signing: { keys: { X: testKeyPub } },
|
||||
user_signing: { keys: { X: testKeyPub } },
|
||||
master: {
|
||||
keys: { X: testKeyPub },
|
||||
usage: [],
|
||||
user_id: 'user-id',
|
||||
},
|
||||
self_signing: {
|
||||
keys: { X: testKeyPub },
|
||||
usage: [],
|
||||
user_id: 'user-id',
|
||||
},
|
||||
user_signing: {
|
||||
keys: { X: testKeyPub },
|
||||
usage: [],
|
||||
user_id: 'user-id',
|
||||
},
|
||||
};
|
||||
|
||||
const secretStorage = {
|
||||
@@ -79,20 +94,22 @@ describe("self-verifications", () => {
|
||||
getUserId: () => userId,
|
||||
getKeyBackupVersion: () => Promise.resolve({}),
|
||||
restoreKeyBackupWithCache,
|
||||
};
|
||||
} as unknown as MatrixClient;
|
||||
|
||||
const request = {
|
||||
onVerifierFinished: () => undefined,
|
||||
};
|
||||
} as unknown as VerificationRequest;
|
||||
|
||||
const verification = new VerificationBase(
|
||||
undefined, // channel
|
||||
undefined as unknown as IVerificationChannel, // channel
|
||||
client, // baseApis
|
||||
userId,
|
||||
"ABC", // deviceId
|
||||
undefined, // startEvent
|
||||
undefined as unknown as MatrixEvent, // startEvent
|
||||
request,
|
||||
);
|
||||
|
||||
// @ts-ignore set private property
|
||||
verification.resolve = () => undefined;
|
||||
|
||||
const result = await verification.done();
|
||||
@@ -102,12 +119,12 @@ describe("self-verifications", () => {
|
||||
expect(secretStorage.request.mock.calls.length).toBe(4);
|
||||
|
||||
expect(cacheCallbacks.storeCrossSigningKeyCache.mock.calls[0][1])
|
||||
.toEqual(testKey);
|
||||
.toEqual(testKey);
|
||||
expect(cacheCallbacks.storeCrossSigningKeyCache.mock.calls[1][1])
|
||||
.toEqual(testKey);
|
||||
.toEqual(testKey);
|
||||
|
||||
expect(storeSessionBackupPrivateKey.mock.calls[0][0])
|
||||
.toEqual(testKey);
|
||||
.toEqual(testKey);
|
||||
|
||||
expect(restoreKeyBackupWithCache).toHaveBeenCalled();
|
||||
|
||||
@@ -19,20 +19,23 @@ import nodeCrypto from "crypto";
|
||||
|
||||
import { TestClient } from '../../../TestClient';
|
||||
import { MatrixEvent } from "../../../../src/models/event";
|
||||
import { IRoomTimelineData } from "../../../../src/models/event-timeline-set";
|
||||
import { Room, RoomEvent } from "../../../../src/models/room";
|
||||
import { logger } from '../../../../src/logger';
|
||||
import { MatrixClient, ClientEvent } from '../../../../src/client';
|
||||
|
||||
export async function makeTestClients(userInfos, options) {
|
||||
const clients = [];
|
||||
const timeouts = [];
|
||||
const clientMap = {};
|
||||
const sendToDevice = function(type, map) {
|
||||
export async function makeTestClients(userInfos, options): Promise<[TestClient[], () => void]> {
|
||||
const clients: TestClient[] = [];
|
||||
const timeouts: ReturnType<typeof setTimeout>[] = [];
|
||||
const clientMap: Record<string, Record<string, MatrixClient>> = {};
|
||||
const makeSendToDevice = (matrixClient: MatrixClient): MatrixClient['sendToDevice'] => async (type, map) => {
|
||||
// logger.log(this.getUserId(), "sends", type, map);
|
||||
for (const [userId, devMap] of Object.entries(map)) {
|
||||
if (userId in clientMap) {
|
||||
for (const [deviceId, msg] of Object.entries(devMap)) {
|
||||
if (deviceId in clientMap[userId]) {
|
||||
const event = new MatrixEvent({
|
||||
sender: this.getUserId(), // eslint-disable-line @babel/no-invalid-this
|
||||
sender: matrixClient.getUserId()!,
|
||||
type: type,
|
||||
content: msg,
|
||||
});
|
||||
@@ -42,18 +45,19 @@ export async function makeTestClients(userInfos, options) {
|
||||
Promise.resolve();
|
||||
|
||||
decryptionPromise.then(
|
||||
() => client.emit("toDeviceEvent", event),
|
||||
() => client.emit(ClientEvent.ToDeviceEvent, event),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {};
|
||||
};
|
||||
const sendEvent = function(room, type, content) {
|
||||
const makeSendEvent = (matrixClient: MatrixClient) => (room, type, content) => {
|
||||
// make up a unique ID as the event ID
|
||||
const eventId = "$" + this.makeTxnId(); // eslint-disable-line @babel/no-invalid-this
|
||||
const eventId = "$" + matrixClient.makeTxnId();
|
||||
const rawEvent = {
|
||||
sender: this.getUserId(), // eslint-disable-line @babel/no-invalid-this
|
||||
sender: matrixClient.getUserId()!,
|
||||
type: type,
|
||||
content: content,
|
||||
room_id: room,
|
||||
@@ -63,22 +67,24 @@ export async function makeTestClients(userInfos, options) {
|
||||
const event = new MatrixEvent(rawEvent);
|
||||
const remoteEcho = new MatrixEvent(Object.assign({}, rawEvent, {
|
||||
unsigned: {
|
||||
transaction_id: this.makeTxnId(), // eslint-disable-line @babel/no-invalid-this
|
||||
transaction_id: matrixClient.makeTxnId(),
|
||||
},
|
||||
}));
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
for (const tc of clients) {
|
||||
if (tc.client === this) { // eslint-disable-line @babel/no-invalid-this
|
||||
const room = new Room('test', tc.client, tc.client.getUserId()!);
|
||||
const roomTimelineData = {} as unknown as IRoomTimelineData;
|
||||
if (tc.client === matrixClient) {
|
||||
logger.log("sending remote echo!!");
|
||||
tc.client.emit("Room.timeline", remoteEcho);
|
||||
tc.client.emit(RoomEvent.Timeline, remoteEcho, room, false, false, roomTimelineData);
|
||||
} else {
|
||||
tc.client.emit("Room.timeline", event);
|
||||
tc.client.emit(RoomEvent.Timeline, event, room, false, false, roomTimelineData);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
timeouts.push(timeout);
|
||||
timeouts.push(timeout as unknown as ReturnType<typeof setTimeout>);
|
||||
|
||||
return Promise.resolve({ event_id: eventId });
|
||||
};
|
||||
@@ -99,8 +105,8 @@ export async function makeTestClients(userInfos, options) {
|
||||
clientMap[userInfo.userId] = {};
|
||||
}
|
||||
clientMap[userInfo.userId][userInfo.deviceId] = testClient.client;
|
||||
testClient.client.sendToDevice = sendToDevice;
|
||||
testClient.client.sendEvent = sendEvent;
|
||||
testClient.client.sendToDevice = makeSendToDevice(testClient.client);
|
||||
testClient.client.sendEvent = makeSendEvent(testClient.client);
|
||||
clients.push(testClient);
|
||||
}
|
||||
|
||||
@@ -116,11 +122,12 @@ export async function makeTestClients(userInfos, options) {
|
||||
export function setupWebcrypto() {
|
||||
global.crypto = {
|
||||
getRandomValues: (buf) => {
|
||||
return nodeCrypto.randomFillSync(buf);
|
||||
return nodeCrypto.randomFillSync(buf as any);
|
||||
},
|
||||
};
|
||||
} as unknown as Crypto;
|
||||
}
|
||||
|
||||
export function teardownWebcrypto() {
|
||||
// @ts-ignore undefined != Crypto
|
||||
global.crypto = undefined;
|
||||
}
|
||||
+97
-33
@@ -19,11 +19,18 @@ import { InRoomChannel } from "../../../../src/crypto/verification/request/InRoo
|
||||
import { ToDeviceChannel } from
|
||||
"../../../../src/crypto/verification/request/ToDeviceChannel";
|
||||
import { MatrixEvent } from "../../../../src/models/event";
|
||||
import { MatrixClient } from "../../../../src/client";
|
||||
import { setupWebcrypto, teardownWebcrypto } from "./util";
|
||||
import { IVerificationChannel } from "../../../../src/crypto/verification/request/Channel";
|
||||
import { VerificationBase } from "../../../../src/crypto/verification/Base";
|
||||
|
||||
function makeMockClient(userId, deviceId) {
|
||||
type MockClient = MatrixClient & {
|
||||
popEvents: () => MatrixEvent[];
|
||||
popDeviceEvents: (userId: string, deviceId: string) => MatrixEvent[];
|
||||
};
|
||||
function makeMockClient(userId: string, deviceId: string): MockClient {
|
||||
let counter = 1;
|
||||
let events = [];
|
||||
let events: MatrixEvent[] = [];
|
||||
const deviceEvents = {};
|
||||
return {
|
||||
getUserId() { return userId; },
|
||||
@@ -54,16 +61,18 @@ function makeMockClient(userId, deviceId) {
|
||||
deviceEvents[userId][deviceId].push(event);
|
||||
}
|
||||
}
|
||||
return Promise.resolve();
|
||||
return Promise.resolve({});
|
||||
},
|
||||
|
||||
popEvents() {
|
||||
// @ts-ignore special testing fn
|
||||
popEvents(): MatrixEvent[] {
|
||||
const e = events;
|
||||
events = [];
|
||||
return e;
|
||||
},
|
||||
|
||||
popDeviceEvents(userId, deviceId) {
|
||||
// @ts-ignore special testing fn
|
||||
popDeviceEvents(userId: string, deviceId: string): MatrixEvent[] {
|
||||
const forDevice = deviceEvents[userId];
|
||||
const events = forDevice && forDevice[deviceId];
|
||||
const result = events || [];
|
||||
@@ -72,12 +81,21 @@ function makeMockClient(userId, deviceId) {
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
} as unknown as MockClient;
|
||||
}
|
||||
|
||||
const MOCK_METHOD = "mock-verify";
|
||||
class MockVerifier {
|
||||
constructor(channel, client, userId, deviceId, startEvent) {
|
||||
class MockVerifier extends VerificationBase<'', any> {
|
||||
public _channel;
|
||||
public _startEvent;
|
||||
constructor(
|
||||
channel: IVerificationChannel,
|
||||
client: MatrixClient,
|
||||
userId: string,
|
||||
deviceId: string,
|
||||
startEvent: MatrixEvent,
|
||||
) {
|
||||
super(channel, client, userId, deviceId, startEvent, {} as unknown as VerificationRequest);
|
||||
this._channel = channel;
|
||||
this._startEvent = startEvent;
|
||||
}
|
||||
@@ -115,7 +133,10 @@ function makeRemoteEcho(event) {
|
||||
|
||||
async function distributeEvent(ownRequest, theirRequest, event) {
|
||||
await ownRequest.channel.handleEvent(
|
||||
makeRemoteEcho(event), ownRequest, true);
|
||||
makeRemoteEcho(event),
|
||||
ownRequest,
|
||||
true,
|
||||
);
|
||||
await theirRequest.channel.handleEvent(event, theirRequest, true);
|
||||
}
|
||||
|
||||
@@ -133,12 +154,19 @@ describe("verification request unit tests", function() {
|
||||
it("transition from UNSENT to DONE through happy path", async function() {
|
||||
const alice = makeMockClient("@alice:matrix.tld", "device1");
|
||||
const bob = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const verificationMethods = new Map(
|
||||
[[MOCK_METHOD, MockVerifier]],
|
||||
) as unknown as Map<string, typeof VerificationBase>;
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()),
|
||||
new Map([[MOCK_METHOD, MockVerifier]]), alice);
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()!),
|
||||
verificationMethods,
|
||||
alice,
|
||||
);
|
||||
const bobRequest = new VerificationRequest(
|
||||
new InRoomChannel(bob, "!room"),
|
||||
new Map([[MOCK_METHOD, MockVerifier]]), bob);
|
||||
verificationMethods,
|
||||
bob,
|
||||
);
|
||||
expect(aliceRequest.invalid).toBe(true);
|
||||
expect(bobRequest.invalid).toBe(true);
|
||||
|
||||
@@ -157,7 +185,7 @@ describe("verification request unit tests", function() {
|
||||
expect(aliceRequest.ready).toBe(true);
|
||||
|
||||
const verifier = aliceRequest.beginKeyVerification(MOCK_METHOD);
|
||||
await verifier.start();
|
||||
await (verifier as MockVerifier).start();
|
||||
const [startEvent] = alice.popEvents();
|
||||
expect(startEvent.getType()).toBe(START_TYPE);
|
||||
await distributeEvent(aliceRequest, bobRequest, startEvent);
|
||||
@@ -165,8 +193,7 @@ describe("verification request unit tests", function() {
|
||||
expect(aliceRequest.verifier).toBeInstanceOf(MockVerifier);
|
||||
expect(bobRequest.started).toBe(true);
|
||||
expect(bobRequest.verifier).toBeInstanceOf(MockVerifier);
|
||||
|
||||
await bobRequest.verifier.start();
|
||||
await (bobRequest.verifier as MockVerifier).start();
|
||||
const [bobDoneEvent] = bob.popEvents();
|
||||
expect(bobDoneEvent.getType()).toBe(DONE_TYPE);
|
||||
await distributeEvent(bobRequest, aliceRequest, bobDoneEvent);
|
||||
@@ -180,12 +207,20 @@ describe("verification request unit tests", function() {
|
||||
it("methods only contains common methods", async function() {
|
||||
const alice = makeMockClient("@alice:matrix.tld", "device1");
|
||||
const bob = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const aliceVerificationMethods = new Map(
|
||||
[["c", function() {}], ["a", function() {}]],
|
||||
) as unknown as Map<string, typeof VerificationBase>;
|
||||
const bobVerificationMethods = new Map(
|
||||
[["c", function() {}], ["b", function() {}]],
|
||||
) as unknown as Map<string, typeof VerificationBase>;
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()),
|
||||
new Map([["c", function() {}], ["a", function() {}]]), alice);
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()!),
|
||||
aliceVerificationMethods, alice);
|
||||
const bobRequest = new VerificationRequest(
|
||||
new InRoomChannel(bob, "!room"),
|
||||
new Map([["c", function() {}], ["b", function() {}]]), bob);
|
||||
bobVerificationMethods,
|
||||
bob,
|
||||
);
|
||||
await aliceRequest.sendRequest();
|
||||
const [requestEvent] = alice.popEvents();
|
||||
await distributeEvent(aliceRequest, bobRequest, requestEvent);
|
||||
@@ -201,13 +236,22 @@ describe("verification request unit tests", function() {
|
||||
const bob1 = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const bob2 = makeMockClient("@bob:matrix.tld", "device2");
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob1.getUserId()), new Map(), alice);
|
||||
new InRoomChannel(alice, "!room", bob1.getUserId()!),
|
||||
new Map(),
|
||||
alice,
|
||||
);
|
||||
await aliceRequest.sendRequest();
|
||||
const [requestEvent] = alice.popEvents();
|
||||
const bob1Request = new VerificationRequest(
|
||||
new InRoomChannel(bob1, "!room"), new Map(), bob1);
|
||||
new InRoomChannel(bob1, "!room"),
|
||||
new Map(),
|
||||
bob1,
|
||||
);
|
||||
const bob2Request = new VerificationRequest(
|
||||
new InRoomChannel(bob2, "!room"), new Map(), bob2);
|
||||
new InRoomChannel(bob2, "!room"),
|
||||
new Map(),
|
||||
bob2,
|
||||
);
|
||||
|
||||
await bob1Request.channel.handleEvent(requestEvent, bob1Request, true);
|
||||
await bob2Request.channel.handleEvent(requestEvent, bob2Request, true);
|
||||
@@ -222,22 +266,34 @@ describe("verification request unit tests", function() {
|
||||
it("verify own device with to_device messages", async function() {
|
||||
const bob1 = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const bob2 = makeMockClient("@bob:matrix.tld", "device2");
|
||||
const verificationMethods = new Map(
|
||||
[[MOCK_METHOD, MockVerifier]],
|
||||
) as unknown as Map<string, typeof VerificationBase>;
|
||||
const bob1Request = new VerificationRequest(
|
||||
new ToDeviceChannel(bob1, bob1.getUserId(), ["device1", "device2"],
|
||||
ToDeviceChannel.makeTransactionId(), "device2"),
|
||||
new Map([[MOCK_METHOD, MockVerifier]]), bob1);
|
||||
new ToDeviceChannel(
|
||||
bob1,
|
||||
bob1.getUserId()!,
|
||||
["device1", "device2"],
|
||||
ToDeviceChannel.makeTransactionId(),
|
||||
"device2",
|
||||
),
|
||||
verificationMethods,
|
||||
bob1,
|
||||
);
|
||||
const to = { userId: "@bob:matrix.tld", deviceId: "device2" };
|
||||
const verifier = bob1Request.beginKeyVerification(MOCK_METHOD, to);
|
||||
expect(verifier).toBeInstanceOf(MockVerifier);
|
||||
await verifier.start();
|
||||
await (verifier as MockVerifier).start();
|
||||
const [startEvent] = bob1.popDeviceEvents(to.userId, to.deviceId);
|
||||
expect(startEvent.getType()).toBe(START_TYPE);
|
||||
const bob2Request = new VerificationRequest(
|
||||
new ToDeviceChannel(bob2, bob2.getUserId(), ["device1"]),
|
||||
new Map([[MOCK_METHOD, MockVerifier]]), bob2);
|
||||
new ToDeviceChannel(bob2, bob2.getUserId()!, ["device1"]),
|
||||
verificationMethods,
|
||||
bob2,
|
||||
);
|
||||
|
||||
await bob2Request.channel.handleEvent(startEvent, bob2Request, true);
|
||||
await bob2Request.verifier.start();
|
||||
await (bob2Request.verifier as MockVerifier).start();
|
||||
const [doneEvent1] = bob2.popDeviceEvents("@bob:matrix.tld", "device1");
|
||||
expect(doneEvent1.getType()).toBe(DONE_TYPE);
|
||||
await bob1Request.channel.handleEvent(doneEvent1, bob1Request, true);
|
||||
@@ -253,11 +309,13 @@ describe("verification request unit tests", function() {
|
||||
const alice = makeMockClient("@alice:matrix.tld", "device1");
|
||||
const bob = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()), new Map(), alice);
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()!),
|
||||
new Map(),
|
||||
alice,
|
||||
);
|
||||
await aliceRequest.sendRequest();
|
||||
const [requestEvent] = alice.popEvents();
|
||||
await aliceRequest.channel.handleEvent(requestEvent, aliceRequest, true,
|
||||
true, true);
|
||||
await aliceRequest.channel.handleEvent(requestEvent, aliceRequest, true);
|
||||
|
||||
expect(aliceRequest.cancelled).toBe(false);
|
||||
expect(aliceRequest._cancellingUserId).toBe(undefined);
|
||||
@@ -269,11 +327,17 @@ describe("verification request unit tests", function() {
|
||||
const alice = makeMockClient("@alice:matrix.tld", "device1");
|
||||
const bob = makeMockClient("@bob:matrix.tld", "device1");
|
||||
const aliceRequest = new VerificationRequest(
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()), new Map(), alice);
|
||||
new InRoomChannel(alice, "!room", bob.getUserId()!),
|
||||
new Map(),
|
||||
alice,
|
||||
);
|
||||
await aliceRequest.sendRequest();
|
||||
const [requestEvent] = alice.popEvents();
|
||||
const bobRequest = new VerificationRequest(
|
||||
new InRoomChannel(bob, "!room"), new Map(), bob);
|
||||
new InRoomChannel(bob, "!room"),
|
||||
new Map(),
|
||||
bob,
|
||||
);
|
||||
|
||||
await bobRequest.channel.handleEvent(requestEvent, bobRequest, true);
|
||||
|
||||
@@ -16,14 +16,15 @@ limitations under the License.
|
||||
|
||||
import * as utils from "../test-utils/test-utils";
|
||||
import {
|
||||
DuplicateStrategy,
|
||||
EventTimeline,
|
||||
EventTimelineSet,
|
||||
EventType,
|
||||
Filter,
|
||||
MatrixClient,
|
||||
MatrixEvent,
|
||||
MatrixEventEvent,
|
||||
Room,
|
||||
DuplicateStrategy,
|
||||
} from '../../src';
|
||||
import { Thread } from "../../src/models/thread";
|
||||
import { ReEmitter } from "../../src/ReEmitter";
|
||||
@@ -291,4 +292,34 @@ describe('EventTimelineSet', () => {
|
||||
expect(eventTimelineSet.canContain(event)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleRemoteEcho", () => {
|
||||
it("should add to liveTimeline only if the event matches the filter", () => {
|
||||
const filter = new Filter(client.getUserId()!, "test_filter");
|
||||
filter.setDefinition({
|
||||
room: {
|
||||
timeline: {
|
||||
types: [EventType.RoomMessage],
|
||||
},
|
||||
},
|
||||
});
|
||||
const eventTimelineSet = new EventTimelineSet(room, { filter }, client);
|
||||
|
||||
const roomMessageEvent = new MatrixEvent({
|
||||
type: EventType.RoomMessage,
|
||||
content: { body: "test" },
|
||||
event_id: "!test1:server",
|
||||
});
|
||||
eventTimelineSet.handleRemoteEcho(roomMessageEvent, "~!local-event-id:server", roomMessageEvent.getId());
|
||||
expect(eventTimelineSet.getLiveTimeline().getEvents()).toContain(roomMessageEvent);
|
||||
|
||||
const roomFilteredEvent = new MatrixEvent({
|
||||
type: "other_event_type",
|
||||
content: { body: "test" },
|
||||
event_id: "!test2:server",
|
||||
});
|
||||
eventTimelineSet.handleRemoteEcho(roomFilteredEvent, "~!local-event-id:server", roomFilteredEvent.getId());
|
||||
expect(eventTimelineSet.getLiveTimeline().getEvents()).not.toContain(roomFilteredEvent);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SSOAction } from '../../src/@types/auth';
|
||||
import { TestClient } from '../TestClient';
|
||||
|
||||
describe('Login request', function() {
|
||||
@@ -22,3 +23,37 @@ describe('Login request', function() {
|
||||
expect(client.client.getUserId()).toBe(response.user_id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SSO login URL', function() {
|
||||
let client: TestClient;
|
||||
|
||||
beforeEach(function() {
|
||||
client = new TestClient();
|
||||
});
|
||||
|
||||
afterEach(function() {
|
||||
client.stop();
|
||||
});
|
||||
|
||||
describe('SSOAction', function() {
|
||||
const redirectUri = "https://test.com/foo";
|
||||
|
||||
it('No action', function() {
|
||||
const urlString = client.client.getSsoLoginUrl(redirectUri, undefined, undefined, undefined);
|
||||
const url = new URL(urlString);
|
||||
expect(url.searchParams.has('org.matrix.msc3824.action')).toBe(false);
|
||||
});
|
||||
|
||||
it('register', function() {
|
||||
const urlString = client.client.getSsoLoginUrl(redirectUri, undefined, undefined, SSOAction.REGISTER);
|
||||
const url = new URL(urlString);
|
||||
expect(url.searchParams.get('org.matrix.msc3824.action')).toEqual('register');
|
||||
});
|
||||
|
||||
it('login', function() {
|
||||
const urlString = client.client.getSsoLoginUrl(redirectUri, undefined, undefined, SSOAction.LOGIN);
|
||||
const url = new URL(urlString);
|
||||
expect(url.searchParams.get('org.matrix.msc3824.action')).toEqual('login');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,9 +36,14 @@ import { ReceiptType } from "../../src/@types/read_receipts";
|
||||
import * as testUtils from "../test-utils/test-utils";
|
||||
import { makeBeaconInfoContent } from "../../src/content-helpers";
|
||||
import { M_BEACON_INFO } from "../../src/@types/beacon";
|
||||
import { ContentHelpers, Room } from "../../src";
|
||||
import { ContentHelpers, EventTimeline, Room } from "../../src";
|
||||
import { supportsMatrixCall } from "../../src/webrtc/call";
|
||||
import { makeBeaconEvent } from "../test-utils/beacon";
|
||||
import {
|
||||
IGNORE_INVITES_ACCOUNT_EVENT_KEY,
|
||||
POLICIES_ACCOUNT_EVENT_TYPE,
|
||||
PolicyScope,
|
||||
} from "../../src/models/invites-ignorer";
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
@@ -1412,4 +1417,301 @@ describe("MatrixClient", function() {
|
||||
expect(client.crypto.encryptAndSendToDevices).toHaveBeenLastCalledWith(deviceInfos, payload);
|
||||
});
|
||||
});
|
||||
|
||||
describe("support for ignoring invites", () => {
|
||||
beforeEach(() => {
|
||||
// Mockup `getAccountData`/`setAccountData`.
|
||||
const dataStore = new Map();
|
||||
client.setAccountData = function(eventType, content) {
|
||||
dataStore.set(eventType, content);
|
||||
return Promise.resolve();
|
||||
};
|
||||
client.getAccountData = function(eventType) {
|
||||
const data = dataStore.get(eventType);
|
||||
return new MatrixEvent({
|
||||
content: data,
|
||||
});
|
||||
};
|
||||
|
||||
// Mockup `createRoom`/`getRoom`/`joinRoom`, including state.
|
||||
const rooms = new Map();
|
||||
client.createRoom = function(options = {}) {
|
||||
const roomId = options["_roomId"] || `!room-${rooms.size}:example.org`;
|
||||
const state = new Map();
|
||||
const room = {
|
||||
roomId,
|
||||
_options: options,
|
||||
_state: state,
|
||||
getUnfilteredTimelineSet: function() {
|
||||
return {
|
||||
getLiveTimeline: function() {
|
||||
return {
|
||||
getState: function(direction) {
|
||||
expect(direction).toBe(EventTimeline.FORWARDS);
|
||||
return {
|
||||
getStateEvents: function(type) {
|
||||
const store = state.get(type) || {};
|
||||
return Object.keys(store).map(key => store[key]);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
rooms.set(roomId, room);
|
||||
return Promise.resolve({ room_id: roomId });
|
||||
};
|
||||
client.getRoom = function(roomId) {
|
||||
return rooms.get(roomId);
|
||||
};
|
||||
client.joinRoom = function(roomId) {
|
||||
return this.getRoom(roomId) || this.createRoom({ _roomId: roomId });
|
||||
};
|
||||
|
||||
// Mockup state events
|
||||
client.sendStateEvent = function(roomId, type, content) {
|
||||
const room = this.getRoom(roomId);
|
||||
const state: Map<string, any> = room._state;
|
||||
let store = state.get(type);
|
||||
if (!store) {
|
||||
store = {};
|
||||
state.set(type, store);
|
||||
}
|
||||
const eventId = `$event-${Math.random()}:example.org`;
|
||||
store[eventId] = {
|
||||
getId: function() {
|
||||
return eventId;
|
||||
},
|
||||
getRoomId: function() {
|
||||
return roomId;
|
||||
},
|
||||
getContent: function() {
|
||||
return content;
|
||||
},
|
||||
};
|
||||
return { event_id: eventId };
|
||||
};
|
||||
client.redactEvent = function(roomId, eventId) {
|
||||
const room = this.getRoom(roomId);
|
||||
const state: Map<string, any> = room._state;
|
||||
for (const store of state.values()) {
|
||||
delete store[eventId];
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
it("should initialize and return the same `target` consistently", async () => {
|
||||
const target1 = await client.ignoredInvites.getOrCreateTargetRoom();
|
||||
const target2 = await client.ignoredInvites.getOrCreateTargetRoom();
|
||||
expect(target1).toBeTruthy();
|
||||
expect(target1).toBe(target2);
|
||||
});
|
||||
|
||||
it("should initialize and return the same `sources` consistently", async () => {
|
||||
const sources1 = await client.ignoredInvites.getOrCreateSourceRooms();
|
||||
const sources2 = await client.ignoredInvites.getOrCreateSourceRooms();
|
||||
expect(sources1).toBeTruthy();
|
||||
expect(sources1).toHaveLength(1);
|
||||
expect(sources1).toEqual(sources2);
|
||||
});
|
||||
|
||||
it("should initially not reject any invite", async () => {
|
||||
const rule = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(rule).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should reject invites once we have added a matching rule in the target room (scope: user)", async () => {
|
||||
await client.ignoredInvites.addRule(PolicyScope.User, "*:example.org", "just a test");
|
||||
|
||||
// We should reject this invite.
|
||||
const ruleMatch = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleMatch).toBeTruthy();
|
||||
expect(ruleMatch.getContent()).toMatchObject({
|
||||
recommendation: "m.ban",
|
||||
reason: "just a test",
|
||||
});
|
||||
|
||||
// We should let these invites go through.
|
||||
const ruleWrongServer = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:somewhere.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleWrongServer).toBeFalsy();
|
||||
|
||||
const ruleWrongServerRoom = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:somewhere.org",
|
||||
roomId: "!snafu:example.org",
|
||||
});
|
||||
expect(ruleWrongServerRoom).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should reject invites once we have added a matching rule in the target room (scope: server)", async () => {
|
||||
const REASON = `Just a test ${Math.random()}`;
|
||||
await client.ignoredInvites.addRule(PolicyScope.Server, "example.org", REASON);
|
||||
|
||||
// We should reject these invites.
|
||||
const ruleSenderMatch = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleSenderMatch).toBeTruthy();
|
||||
expect(ruleSenderMatch.getContent()).toMatchObject({
|
||||
recommendation: "m.ban",
|
||||
reason: REASON,
|
||||
});
|
||||
|
||||
const ruleRoomMatch = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:somewhere.org",
|
||||
roomId: "!snafu:example.org",
|
||||
});
|
||||
expect(ruleRoomMatch).toBeTruthy();
|
||||
expect(ruleRoomMatch.getContent()).toMatchObject({
|
||||
recommendation: "m.ban",
|
||||
reason: REASON,
|
||||
});
|
||||
|
||||
// We should let these invites go through.
|
||||
const ruleWrongServer = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:somewhere.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleWrongServer).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should reject invites once we have added a matching rule in the target room (scope: room)", async () => {
|
||||
const REASON = `Just a test ${Math.random()}`;
|
||||
const BAD_ROOM_ID = "!bad:example.org";
|
||||
const GOOD_ROOM_ID = "!good:example.org";
|
||||
await client.ignoredInvites.addRule(PolicyScope.Room, BAD_ROOM_ID, REASON);
|
||||
|
||||
// We should reject this invite.
|
||||
const ruleSenderMatch = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: BAD_ROOM_ID,
|
||||
});
|
||||
expect(ruleSenderMatch).toBeTruthy();
|
||||
expect(ruleSenderMatch.getContent()).toMatchObject({
|
||||
recommendation: "m.ban",
|
||||
reason: REASON,
|
||||
});
|
||||
|
||||
// We should let these invites go through.
|
||||
const ruleWrongRoom = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: BAD_ROOM_ID,
|
||||
roomId: GOOD_ROOM_ID,
|
||||
});
|
||||
expect(ruleWrongRoom).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should reject invites once we have added a matching rule in a non-target source room", async () => {
|
||||
const NEW_SOURCE_ROOM_ID = "!another-source:example.org";
|
||||
|
||||
// Make sure that everything is initialized.
|
||||
await client.ignoredInvites.getOrCreateSourceRooms();
|
||||
await client.joinRoom(NEW_SOURCE_ROOM_ID);
|
||||
await client.ignoredInvites.addSource(NEW_SOURCE_ROOM_ID);
|
||||
|
||||
// Add a rule in the new source room.
|
||||
await client.sendStateEvent(NEW_SOURCE_ROOM_ID, PolicyScope.User, {
|
||||
entity: "*:example.org",
|
||||
reason: "just a test",
|
||||
recommendation: "m.ban",
|
||||
});
|
||||
|
||||
// We should reject this invite.
|
||||
const ruleMatch = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleMatch).toBeTruthy();
|
||||
expect(ruleMatch.getContent()).toMatchObject({
|
||||
recommendation: "m.ban",
|
||||
reason: "just a test",
|
||||
});
|
||||
|
||||
// We should let these invites go through.
|
||||
const ruleWrongServer = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:somewhere.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleWrongServer).toBeFalsy();
|
||||
|
||||
const ruleWrongServerRoom = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:somewhere.org",
|
||||
roomId: "!snafu:example.org",
|
||||
});
|
||||
expect(ruleWrongServerRoom).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should not reject invites anymore once we have removed a rule", async () => {
|
||||
await client.ignoredInvites.addRule(PolicyScope.User, "*:example.org", "just a test");
|
||||
|
||||
// We should reject this invite.
|
||||
const ruleMatch = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleMatch).toBeTruthy();
|
||||
expect(ruleMatch.getContent()).toMatchObject({
|
||||
recommendation: "m.ban",
|
||||
reason: "just a test",
|
||||
});
|
||||
|
||||
// After removing the invite, we shouldn't reject it anymore.
|
||||
await client.ignoredInvites.removeRule(ruleMatch);
|
||||
const ruleMatch2 = await client.ignoredInvites.getRuleForInvite({
|
||||
sender: "@foobar:example.org",
|
||||
roomId: "!snafu:somewhere.org",
|
||||
});
|
||||
expect(ruleMatch2).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should add new rules in the target room, rather than any other source room", async () => {
|
||||
const NEW_SOURCE_ROOM_ID = "!another-source:example.org";
|
||||
|
||||
// Make sure that everything is initialized.
|
||||
await client.ignoredInvites.getOrCreateSourceRooms();
|
||||
await client.joinRoom(NEW_SOURCE_ROOM_ID);
|
||||
const newSourceRoom = client.getRoom(NEW_SOURCE_ROOM_ID);
|
||||
|
||||
// Fetch the list of sources and check that we do not have the new room yet.
|
||||
const policies = await client.getAccountData(POLICIES_ACCOUNT_EVENT_TYPE.name).getContent();
|
||||
expect(policies).toBeTruthy();
|
||||
const ignoreInvites = policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name];
|
||||
expect(ignoreInvites).toBeTruthy();
|
||||
expect(ignoreInvites.sources).toBeTruthy();
|
||||
expect(ignoreInvites.sources).not.toContain(NEW_SOURCE_ROOM_ID);
|
||||
|
||||
// Add a source.
|
||||
const added = await client.ignoredInvites.addSource(NEW_SOURCE_ROOM_ID);
|
||||
expect(added).toBe(true);
|
||||
const added2 = await client.ignoredInvites.addSource(NEW_SOURCE_ROOM_ID);
|
||||
expect(added2).toBe(false);
|
||||
|
||||
// Fetch the list of sources and check that we have added the new room.
|
||||
const policies2 = await client.getAccountData(POLICIES_ACCOUNT_EVENT_TYPE.name).getContent();
|
||||
expect(policies2).toBeTruthy();
|
||||
const ignoreInvites2 = policies2[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name];
|
||||
expect(ignoreInvites2).toBeTruthy();
|
||||
expect(ignoreInvites2.sources).toBeTruthy();
|
||||
expect(ignoreInvites2.sources).toContain(NEW_SOURCE_ROOM_ID);
|
||||
|
||||
// Add a rule.
|
||||
const eventId = await client.ignoredInvites.addRule(PolicyScope.User, "*:example.org", "just a test");
|
||||
|
||||
// Check where it shows up.
|
||||
const targetRoomId = ignoreInvites2.target;
|
||||
const targetRoom = client.getRoom(targetRoomId);
|
||||
expect(targetRoom._state.get(PolicyScope.User)[eventId]).toBeTruthy();
|
||||
expect(newSourceRoom._state.get(PolicyScope.User)?.[eventId]).toBeFalsy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+24
-33
@@ -288,11 +288,11 @@ describe("Room", function() {
|
||||
room.addLiveEvents(events);
|
||||
expect(room.currentState.setStateEvents).toHaveBeenCalledWith(
|
||||
[events[0]],
|
||||
{ timelineWasEmpty: undefined },
|
||||
{ timelineWasEmpty: false },
|
||||
);
|
||||
expect(room.currentState.setStateEvents).toHaveBeenCalledWith(
|
||||
[events[1]],
|
||||
{ timelineWasEmpty: undefined },
|
||||
{ timelineWasEmpty: false },
|
||||
);
|
||||
expect(events[0].forwardLooking).toBe(true);
|
||||
expect(events[1].forwardLooking).toBe(true);
|
||||
@@ -426,6 +426,17 @@ describe("Room", function() {
|
||||
// but without the event ID matching we will still have the local event in pending events
|
||||
expect(room.getEventForTxnId(txnId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should correctly handle remote echoes from other devices", () => {
|
||||
const remoteEvent = utils.mkMessage({
|
||||
room: roomId, user: userA, event: true,
|
||||
});
|
||||
remoteEvent.event.unsigned = { transaction_id: "TXN_ID" };
|
||||
|
||||
// add the remoteEvent
|
||||
room.addLiveEvents([remoteEvent]);
|
||||
expect(room.timeline.length).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addEphemeralEvents', () => {
|
||||
@@ -2441,15 +2452,13 @@ describe("Room", function() {
|
||||
if (receiptType === ReceiptType.ReadPrivate) {
|
||||
return { eventId: "eventId1" } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.UnstableReadPrivate) {
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId2" } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId3" } as IWrappedReceipt;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
for (let i = 1; i <= 2; i++) {
|
||||
room.getUnfilteredTimelineSet = () => ({ compareEventOrdering: (event1, event2) => {
|
||||
return (event1 === `eventId${i}`) ? 1 : -1;
|
||||
} } as EventTimelineSet);
|
||||
@@ -2460,20 +2469,18 @@ describe("Room", function() {
|
||||
|
||||
describe("correctly compares by timestamp", () => {
|
||||
it("should correctly compare, if we have all receipts", () => {
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
for (let i = 1; i <= 2; i++) {
|
||||
room.getUnfilteredTimelineSet = () => ({
|
||||
compareEventOrdering: (_1, _2) => null,
|
||||
} as EventTimelineSet);
|
||||
room.getReadReceiptForUserId = (userId, ignore, receiptType) => {
|
||||
if (receiptType === ReceiptType.ReadPrivate) {
|
||||
return { eventId: "eventId1", data: { ts: i === 1 ? 1 : 0 } } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.UnstableReadPrivate) {
|
||||
return { eventId: "eventId2", data: { ts: i === 2 ? 1 : 0 } } as IWrappedReceipt;
|
||||
return { eventId: "eventId1", data: { ts: i === 1 ? 2 : 1 } } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId3", data: { ts: i === 3 ? 1 : 0 } } as IWrappedReceipt;
|
||||
return { eventId: "eventId2", data: { ts: i === 2 ? 2 : 1 } } as IWrappedReceipt;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
expect(room.getEventReadUpTo(userA)).toEqual(`eventId${i}`);
|
||||
@@ -2485,12 +2492,10 @@ describe("Room", function() {
|
||||
compareEventOrdering: (_1, _2) => null,
|
||||
} as EventTimelineSet);
|
||||
room.getReadReceiptForUserId = (userId, ignore, receiptType) => {
|
||||
if (receiptType === ReceiptType.UnstableReadPrivate) {
|
||||
return { eventId: "eventId1", data: { ts: 0 } } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId2", data: { ts: 1 } } as IWrappedReceipt;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
expect(room.getEventReadUpTo(userA)).toEqual(`eventId2`);
|
||||
@@ -2509,35 +2514,21 @@ describe("Room", function() {
|
||||
if (receiptType === ReceiptType.ReadPrivate) {
|
||||
return { eventId: "eventId1" } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.UnstableReadPrivate) {
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId2" } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId3" } as IWrappedReceipt;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
expect(room.getEventReadUpTo(userA)).toEqual(`eventId1`);
|
||||
});
|
||||
|
||||
it("should give precedence to org.matrix.msc2285.read.private", () => {
|
||||
room.getReadReceiptForUserId = (userId, ignore, receiptType) => {
|
||||
if (receiptType === ReceiptType.UnstableReadPrivate) {
|
||||
return { eventId: "eventId2" } as IWrappedReceipt;
|
||||
}
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId2" } as IWrappedReceipt;
|
||||
}
|
||||
};
|
||||
|
||||
expect(room.getEventReadUpTo(userA)).toEqual(`eventId2`);
|
||||
});
|
||||
|
||||
it("should give precedence to m.read", () => {
|
||||
room.getReadReceiptForUserId = (userId, ignore, receiptType) => {
|
||||
if (receiptType === ReceiptType.Read) {
|
||||
return { eventId: "eventId3" } as IWrappedReceipt;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
expect(room.getEventReadUpTo(userA)).toEqual(`eventId3`);
|
||||
|
||||
@@ -302,9 +302,6 @@ describe("SyncAccumulator", function() {
|
||||
[ReceiptType.ReadPrivate]: {
|
||||
"@dan:localhost": { ts: 4 },
|
||||
},
|
||||
[ReceiptType.UnstableReadPrivate]: {
|
||||
"@matthew:localhost": { ts: 5 },
|
||||
},
|
||||
"some.other.receipt.type": {
|
||||
"@should_be_ignored:localhost": { key: "val" },
|
||||
},
|
||||
@@ -350,9 +347,6 @@ describe("SyncAccumulator", function() {
|
||||
[ReceiptType.ReadPrivate]: {
|
||||
"@dan:localhost": { ts: 4 },
|
||||
},
|
||||
[ReceiptType.UnstableReadPrivate]: {
|
||||
"@matthew:localhost": { ts: 5 },
|
||||
},
|
||||
},
|
||||
"$event2:localhost": {
|
||||
[ReceiptType.Read]: {
|
||||
|
||||
@@ -528,38 +528,6 @@ describe("utils", function() {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPrivateReadReceiptField', () => {
|
||||
it('should return m.read.private if server supports stable', async () => {
|
||||
expect(await utils.getPrivateReadReceiptField({
|
||||
doesServerSupportUnstableFeature: jest.fn().mockImplementation((feature) => {
|
||||
return feature === "org.matrix.msc2285.stable";
|
||||
}),
|
||||
} as any)).toBe(ReceiptType.ReadPrivate);
|
||||
});
|
||||
|
||||
it('should return m.read.private if server supports stable and unstable', async () => {
|
||||
expect(await utils.getPrivateReadReceiptField({
|
||||
doesServerSupportUnstableFeature: jest.fn().mockImplementation((feature) => {
|
||||
return ["org.matrix.msc2285.stable", "org.matrix.msc2285"].includes(feature);
|
||||
}),
|
||||
} as any)).toBe(ReceiptType.ReadPrivate);
|
||||
});
|
||||
|
||||
it('should return org.matrix.msc2285.read.private if server supports unstable', async () => {
|
||||
expect(await utils.getPrivateReadReceiptField({
|
||||
doesServerSupportUnstableFeature: jest.fn().mockImplementation((feature) => {
|
||||
return feature === "org.matrix.msc2285";
|
||||
}),
|
||||
} as any)).toBe(ReceiptType.UnstableReadPrivate);
|
||||
});
|
||||
|
||||
it('should return none if server does not support either', async () => {
|
||||
expect(await utils.getPrivateReadReceiptField({
|
||||
doesServerSupportUnstableFeature: jest.fn().mockResolvedValue(false),
|
||||
} as any)).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSupportedReceiptType', () => {
|
||||
it('should support m.read', () => {
|
||||
expect(utils.isSupportedReceiptType(ReceiptType.Read)).toBeTruthy();
|
||||
@@ -569,10 +537,6 @@ describe("utils", function() {
|
||||
expect(utils.isSupportedReceiptType(ReceiptType.ReadPrivate)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should support org.matrix.msc2285.read.private', () => {
|
||||
expect(utils.isSupportedReceiptType(ReceiptType.UnstableReadPrivate)).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should not support other receipt types', () => {
|
||||
expect(utils.isSupportedReceiptType("this is a receipt type")).toBeFalsy();
|
||||
});
|
||||
|
||||
@@ -27,3 +27,66 @@ export interface IRefreshTokenResponse {
|
||||
}
|
||||
|
||||
/* eslint-enable camelcase */
|
||||
|
||||
/**
|
||||
* Response to GET login flows as per https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3login
|
||||
*/
|
||||
export interface ILoginFlowsResponse {
|
||||
flows: LoginFlow[];
|
||||
}
|
||||
|
||||
export type LoginFlow = ISSOFlow | IPasswordFlow | ILoginFlow;
|
||||
|
||||
export interface ILoginFlow {
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface IPasswordFlow extends ILoginFlow {
|
||||
type: "m.login.password";
|
||||
}
|
||||
|
||||
/**
|
||||
* Representation of SSO flow as per https://spec.matrix.org/latest/client-server-api/#client-login-via-sso
|
||||
*/
|
||||
export interface ISSOFlow extends ILoginFlow {
|
||||
type: "m.login.sso" | "m.login.cas";
|
||||
// eslint-disable-next-line camelcase
|
||||
identity_providers?: IIdentityProvider[];
|
||||
}
|
||||
|
||||
export enum IdentityProviderBrand {
|
||||
Gitlab = "gitlab",
|
||||
Github = "github",
|
||||
Apple = "apple",
|
||||
Google = "google",
|
||||
Facebook = "facebook",
|
||||
Twitter = "twitter",
|
||||
}
|
||||
|
||||
export interface IIdentityProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
icon?: string;
|
||||
brand?: IdentityProviderBrand | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters to login request as per https://spec.matrix.org/latest/client-server-api/#login
|
||||
*/
|
||||
/* eslint-disable camelcase */
|
||||
export interface ILoginParams {
|
||||
identifier?: object;
|
||||
password?: string;
|
||||
token?: string;
|
||||
device_id?: string;
|
||||
initial_device_display_name?: string;
|
||||
}
|
||||
/* eslint-enable camelcase */
|
||||
|
||||
export enum SSOAction {
|
||||
/** The user intends to login to an existing account */
|
||||
LOGIN = "login",
|
||||
|
||||
/** The user intends to register for a new account */
|
||||
REGISTER = "register",
|
||||
}
|
||||
|
||||
@@ -18,8 +18,4 @@ export enum ReceiptType {
|
||||
Read = "m.read",
|
||||
FullyRead = "m.fully_read",
|
||||
ReadPrivate = "m.read.private",
|
||||
/**
|
||||
* @deprecated Please use the ReadPrivate type when possible. This value may be removed at any time without notice.
|
||||
*/
|
||||
UnstableReadPrivate = "org.matrix.msc2285.read.private",
|
||||
}
|
||||
|
||||
@@ -41,6 +41,13 @@ export class NamespacedValue<S extends string, U extends string> {
|
||||
return this.unstable;
|
||||
}
|
||||
|
||||
public get names(): (U | S)[] {
|
||||
const names = [this.name];
|
||||
const altName = this.altName;
|
||||
if (altName) names.push(altName);
|
||||
return names;
|
||||
}
|
||||
|
||||
public matches(val: string): boolean {
|
||||
return this.name === val || this.altName === val;
|
||||
}
|
||||
|
||||
+26
-7
@@ -188,15 +188,17 @@ import { IPusher, IPusherRequest, IPushRules, PushRuleAction, PushRuleKind, Rule
|
||||
import { IThreepid } from "./@types/threepids";
|
||||
import { CryptoStore } from "./crypto/store/base";
|
||||
import { MediaHandler } from "./webrtc/mediaHandler";
|
||||
import { IRefreshTokenResponse } from "./@types/auth";
|
||||
import { IRefreshTokenResponse, SSOAction } from "./@types/auth";
|
||||
import { TypedEventEmitter } from "./models/typed-event-emitter";
|
||||
import { ReceiptType } from "./@types/read_receipts";
|
||||
import { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from "./sliding-sync";
|
||||
import { SlidingSyncSdk } from "./sliding-sync-sdk";
|
||||
import { Thread, THREAD_RELATION_TYPE } from "./models/thread";
|
||||
import { MBeaconInfoEventContent, M_BEACON_INFO } from "./@types/beacon";
|
||||
import { UnstableValue } from "./NamespacedValue";
|
||||
import { ToDeviceMessageQueue } from "./ToDeviceMessageQueue";
|
||||
import { ToDeviceBatch } from "./models/ToDeviceMessage";
|
||||
import { IgnoredInvites } from "./models/invites-ignorer";
|
||||
|
||||
export type Store = IStore;
|
||||
|
||||
@@ -880,6 +882,8 @@ export type ClientEventHandlerMap = {
|
||||
& HttpApiEventHandlerMap
|
||||
& BeaconEventHandlerMap;
|
||||
|
||||
const SSO_ACTION_PARAM = new UnstableValue("action", "org.matrix.msc3824.action");
|
||||
|
||||
/**
|
||||
* Represents a Matrix Client. Only directly construct this if you want to use
|
||||
* custom modules. Normally, {@link createClient} should be used
|
||||
@@ -954,6 +958,9 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
||||
|
||||
private toDeviceMessageQueue: ToDeviceMessageQueue;
|
||||
|
||||
// A manager for determining which invites should be ignored.
|
||||
public readonly ignoredInvites: IgnoredInvites;
|
||||
|
||||
constructor(opts: IMatrixClientCreateOpts) {
|
||||
super();
|
||||
|
||||
@@ -1135,6 +1142,8 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
||||
room.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);
|
||||
}
|
||||
});
|
||||
|
||||
this.ignoredInvites = new IgnoredInvites(this);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5359,7 +5368,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
||||
};
|
||||
|
||||
await thread.fetchInitialEvents();
|
||||
let nextBatch = thread.liveTimeline.getPaginationToken(Direction.Backward);
|
||||
let nextBatch: string | null | undefined = thread.liveTimeline.getPaginationToken(Direction.Backward);
|
||||
|
||||
// Fetch events until we find the one we were asked for, or we run out of pages
|
||||
while (!thread.findEventById(eventId)) {
|
||||
@@ -7150,15 +7159,26 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
||||
* @param {string} loginType The type of SSO login we are doing (sso or cas).
|
||||
* Defaults to 'sso'.
|
||||
* @param {string} idpId The ID of the Identity Provider being targeted, optional.
|
||||
* @param {SSOAction} action the SSO flow to indicate to the IdP, optional.
|
||||
* @return {string} The HS URL to hit to begin the SSO login process.
|
||||
*/
|
||||
public getSsoLoginUrl(redirectUrl: string, loginType = "sso", idpId?: string): string {
|
||||
public getSsoLoginUrl(
|
||||
redirectUrl: string,
|
||||
loginType = "sso",
|
||||
idpId?: string,
|
||||
action?: SSOAction,
|
||||
): string {
|
||||
let url = "/login/" + loginType + "/redirect";
|
||||
if (idpId) {
|
||||
url += "/" + idpId;
|
||||
}
|
||||
|
||||
return this.http.getUrl(url, { redirectUrl }, PREFIX_R0);
|
||||
const params = {
|
||||
redirectUrl,
|
||||
[SSO_ACTION_PARAM.unstable!]: action,
|
||||
};
|
||||
|
||||
return this.http.getUrl(url, params, PREFIX_R0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -7523,9 +7543,8 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
|
||||
[ReceiptType.Read]: rrEventId,
|
||||
};
|
||||
|
||||
const privateField = await utils.getPrivateReadReceiptField(this);
|
||||
if (privateField) {
|
||||
content[privateField] = rpEventId;
|
||||
if (await this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")) {
|
||||
content[ReceiptType.ReadPrivate] = rpEventId;
|
||||
}
|
||||
|
||||
return this.http.authedRequest(undefined, Method.Post, path, undefined, content);
|
||||
|
||||
@@ -729,18 +729,10 @@ export class EventTimelineSet extends TypedEventEmitter<EmittedEvents, EventTime
|
||||
if (existingTimeline) {
|
||||
this._eventIdToTimeline.delete(oldEventId);
|
||||
this._eventIdToTimeline.set(newEventId, existingTimeline);
|
||||
} else {
|
||||
if (this.filter) {
|
||||
if (this.filter.filterRoomTimeline([localEvent]).length) {
|
||||
this.addEventToTimeline(localEvent, this.liveTimeline, {
|
||||
toStartOfTimeline: false,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
this.addEventToTimeline(localEvent, this.liveTimeline, {
|
||||
toStartOfTimeline: false,
|
||||
});
|
||||
}
|
||||
} else if (!this.filter || this.filter.filterRoomTimeline([localEvent]).length) {
|
||||
this.addEventToTimeline(localEvent, this.liveTimeline, {
|
||||
toStartOfTimeline: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -307,7 +307,7 @@ export class EventTimeline {
|
||||
*
|
||||
* @param {?string} token pagination token
|
||||
*
|
||||
* @param {string} direction EventTimeline.BACKWARDS to set the pagination
|
||||
* @param {string} direction EventTimeline.BACKWARDS to set the paginatio
|
||||
* token for going backwards in time; EventTimeline.FORWARDS to set the
|
||||
* pagination token for going forwards in time.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
/*
|
||||
Copyright 2022 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { UnstableValue } from "matrix-events-sdk";
|
||||
|
||||
import { MatrixClient } from "../client";
|
||||
import { MatrixEvent } from "./event";
|
||||
import { EventTimeline } from "./event-timeline";
|
||||
import { Preset } from "../@types/partials";
|
||||
import { globToRegexp } from "../utils";
|
||||
import { Room } from "./room";
|
||||
|
||||
/// The event type storing the user's individual policies.
|
||||
///
|
||||
/// Exported for testing purposes.
|
||||
export const POLICIES_ACCOUNT_EVENT_TYPE = new UnstableValue("m.policies", "org.matrix.msc3847.policies");
|
||||
|
||||
/// The key within the user's individual policies storing the user's ignored invites.
|
||||
///
|
||||
/// Exported for testing purposes.
|
||||
export const IGNORE_INVITES_ACCOUNT_EVENT_KEY = new UnstableValue("m.ignore.invites",
|
||||
"org.matrix.msc3847.ignore.invites");
|
||||
|
||||
/// The types of recommendations understood.
|
||||
enum PolicyRecommendation {
|
||||
Ban = "m.ban",
|
||||
}
|
||||
|
||||
/**
|
||||
* The various scopes for policies.
|
||||
*/
|
||||
export enum PolicyScope {
|
||||
/**
|
||||
* The policy deals with an individual user, e.g. reject invites
|
||||
* from this user.
|
||||
*/
|
||||
User = "m.policy.user",
|
||||
|
||||
/**
|
||||
* The policy deals with a room, e.g. reject invites towards
|
||||
* a specific room.
|
||||
*/
|
||||
Room = "m.policy.room",
|
||||
|
||||
/**
|
||||
* The policy deals with a server, e.g. reject invites from
|
||||
* this server.
|
||||
*/
|
||||
Server = "m.policy.server",
|
||||
}
|
||||
|
||||
/**
|
||||
* A container for ignored invites.
|
||||
*
|
||||
* # Performance
|
||||
*
|
||||
* This implementation is extremely naive. It expects that we are dealing
|
||||
* with a very short list of sources (e.g. only one). If real-world
|
||||
* applications turn out to require longer lists, we may need to rework
|
||||
* our data structures.
|
||||
*/
|
||||
export class IgnoredInvites {
|
||||
constructor(
|
||||
private readonly client: MatrixClient,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new rule.
|
||||
*
|
||||
* @param scope The scope for this rule.
|
||||
* @param entity The entity covered by this rule. Globs are supported.
|
||||
* @param reason A human-readable reason for introducing this new rule.
|
||||
* @return The event id for the new rule.
|
||||
*/
|
||||
public async addRule(scope: PolicyScope, entity: string, reason: string): Promise<string> {
|
||||
const target = await this.getOrCreateTargetRoom();
|
||||
const response = await this.client.sendStateEvent(target.roomId, scope, {
|
||||
entity,
|
||||
reason,
|
||||
recommendation: PolicyRecommendation.Ban,
|
||||
});
|
||||
return response.event_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a rule.
|
||||
*/
|
||||
public async removeRule(event: MatrixEvent) {
|
||||
await this.client.redactEvent(event.getRoomId()!, event.getId()!);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new room to the list of sources. If the user isn't a member of the
|
||||
* room, attempt to join it.
|
||||
*
|
||||
* @param roomId A valid room id. If this room is already in the list
|
||||
* of sources, it will not be duplicated.
|
||||
* @return `true` if the source was added, `false` if it was already present.
|
||||
* @throws If `roomId` isn't the id of a room that the current user is already
|
||||
* member of or can join.
|
||||
*
|
||||
* # Safety
|
||||
*
|
||||
* This method will rewrite the `Policies` object in the user's account data.
|
||||
* This rewrite is inherently racy and could overwrite or be overwritten by
|
||||
* other concurrent rewrites of the same object.
|
||||
*/
|
||||
public async addSource(roomId: string): Promise<boolean> {
|
||||
// We attempt to join the room *before* calling
|
||||
// `await this.getOrCreateSourceRooms()` to decrease the duration
|
||||
// of the racy section.
|
||||
await this.client.joinRoom(roomId);
|
||||
// Race starts.
|
||||
const sources = (await this.getOrCreateSourceRooms())
|
||||
.map(room => room.roomId);
|
||||
if (sources.includes(roomId)) {
|
||||
return false;
|
||||
}
|
||||
sources.push(roomId);
|
||||
await this.withIgnoreInvitesPolicies(ignoreInvitesPolicies => {
|
||||
ignoreInvitesPolicies.sources = sources;
|
||||
});
|
||||
|
||||
// Race ends.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find out whether an invite should be ignored.
|
||||
*
|
||||
* @param sender The user id for the user who issued the invite.
|
||||
* @param roomId The room to which the user is invited.
|
||||
* @returns A rule matching the entity, if any was found, `null` otherwise.
|
||||
*/
|
||||
public async getRuleForInvite({ sender, roomId }: {
|
||||
sender: string;
|
||||
roomId: string;
|
||||
}): Promise<Readonly<MatrixEvent | null>> {
|
||||
// In this implementation, we perform a very naive lookup:
|
||||
// - search in each policy room;
|
||||
// - turn each (potentially glob) rule entity into a regexp.
|
||||
//
|
||||
// Real-world testing will tell us whether this is performant enough.
|
||||
// In the (unfortunately likely) case it isn't, there are several manners
|
||||
// in which we could optimize this:
|
||||
// - match several entities per go;
|
||||
// - pre-compile each rule entity into a regexp;
|
||||
// - pre-compile entire rooms into a single regexp.
|
||||
const policyRooms = await this.getOrCreateSourceRooms();
|
||||
const senderServer = sender.split(":")[1];
|
||||
const roomServer = roomId.split(":")[1];
|
||||
for (const room of policyRooms) {
|
||||
const state = room.getUnfilteredTimelineSet().getLiveTimeline().getState(EventTimeline.FORWARDS);
|
||||
|
||||
for (const { scope, entities } of [
|
||||
{ scope: PolicyScope.Room, entities: [roomId] },
|
||||
{ scope: PolicyScope.User, entities: [sender] },
|
||||
{ scope: PolicyScope.Server, entities: [senderServer, roomServer] },
|
||||
]) {
|
||||
const events = state.getStateEvents(scope);
|
||||
for (const event of events) {
|
||||
const content = event.getContent();
|
||||
if (content?.recommendation != PolicyRecommendation.Ban) {
|
||||
// Ignoring invites only looks at `m.ban` recommendations.
|
||||
continue;
|
||||
}
|
||||
const glob = content?.entity;
|
||||
if (!glob) {
|
||||
// Invalid event.
|
||||
continue;
|
||||
}
|
||||
let regexp: RegExp;
|
||||
try {
|
||||
regexp = new RegExp(globToRegexp(glob, false));
|
||||
} catch (ex) {
|
||||
// Assume invalid event.
|
||||
continue;
|
||||
}
|
||||
for (const entity of entities) {
|
||||
if (entity && regexp.test(entity)) {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
// No match.
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the target room, i.e. the room in which any new rule should be written.
|
||||
*
|
||||
* If there is no target room setup, a target room is created.
|
||||
*
|
||||
* Note: This method is public for testing reasons. Most clients should not need
|
||||
* to call it directly.
|
||||
*
|
||||
* # Safety
|
||||
*
|
||||
* This method will rewrite the `Policies` object in the user's account data.
|
||||
* This rewrite is inherently racy and could overwrite or be overwritten by
|
||||
* other concurrent rewrites of the same object.
|
||||
*/
|
||||
public async getOrCreateTargetRoom(): Promise<Room> {
|
||||
const ignoreInvitesPolicies = this.getIgnoreInvitesPolicies();
|
||||
let target = ignoreInvitesPolicies.target;
|
||||
// Validate `target`. If it is invalid, trash out the current `target`
|
||||
// and create a new room.
|
||||
if (typeof target !== "string") {
|
||||
target = null;
|
||||
}
|
||||
if (target) {
|
||||
// Check that the room exists and is valid.
|
||||
const room = this.client.getRoom(target);
|
||||
if (room) {
|
||||
return room;
|
||||
} else {
|
||||
target = null;
|
||||
}
|
||||
}
|
||||
// We need to create our own policy room for ignoring invites.
|
||||
target = (await this.client.createRoom({
|
||||
name: "Individual Policy Room",
|
||||
preset: Preset.PrivateChat,
|
||||
})).room_id;
|
||||
await this.withIgnoreInvitesPolicies(ignoreInvitesPolicies => {
|
||||
ignoreInvitesPolicies.target = target;
|
||||
});
|
||||
|
||||
// Since we have just called `createRoom`, `getRoom` should not be `null`.
|
||||
return this.client.getRoom(target)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of source rooms, i.e. the rooms from which rules need to be read.
|
||||
*
|
||||
* If no source rooms are setup, the target room is used as sole source room.
|
||||
*
|
||||
* Note: This method is public for testing reasons. Most clients should not need
|
||||
* to call it directly.
|
||||
*
|
||||
* # Safety
|
||||
*
|
||||
* This method will rewrite the `Policies` object in the user's account data.
|
||||
* This rewrite is inherently racy and could overwrite or be overwritten by
|
||||
* other concurrent rewrites of the same object.
|
||||
*/
|
||||
public async getOrCreateSourceRooms(): Promise<Room[]> {
|
||||
const ignoreInvitesPolicies = this.getIgnoreInvitesPolicies();
|
||||
let sources = ignoreInvitesPolicies.sources;
|
||||
|
||||
// Validate `sources`. If it is invalid, trash out the current `sources`
|
||||
// and create a new list of sources from `target`.
|
||||
let hasChanges = false;
|
||||
if (!Array.isArray(sources)) {
|
||||
// `sources` could not be an array.
|
||||
hasChanges = true;
|
||||
sources = [];
|
||||
}
|
||||
let sourceRooms: Room[] = sources
|
||||
// `sources` could contain non-string / invalid room ids
|
||||
.filter(roomId => typeof roomId === "string")
|
||||
.map(roomId => this.client.getRoom(roomId))
|
||||
.filter(room => !!room);
|
||||
if (sourceRooms.length != sources.length) {
|
||||
hasChanges = true;
|
||||
}
|
||||
if (sourceRooms.length == 0) {
|
||||
// `sources` could be empty (possibly because we've removed
|
||||
// invalid content)
|
||||
const target = await this.getOrCreateTargetRoom();
|
||||
hasChanges = true;
|
||||
sourceRooms = [target];
|
||||
}
|
||||
if (hasChanges) {
|
||||
// Reload `policies`/`ignoreInvitesPolicies` in case it has been changed
|
||||
// during or by our call to `this.getTargetRoom()`.
|
||||
await this.withIgnoreInvitesPolicies(ignoreInvitesPolicies => {
|
||||
ignoreInvitesPolicies.sources = sources;
|
||||
});
|
||||
}
|
||||
return sourceRooms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the `IGNORE_INVITES_POLICIES` object from account data.
|
||||
*
|
||||
* If both an unstable prefix version and a stable prefix version are available,
|
||||
* it will return the stable prefix version preferentially.
|
||||
*
|
||||
* The result is *not* validated but is guaranteed to be a non-null object.
|
||||
*
|
||||
* @returns A non-null object.
|
||||
*/
|
||||
private getIgnoreInvitesPolicies(): {[key: string]: any} {
|
||||
return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify in place the `IGNORE_INVITES_POLICIES` object from account data.
|
||||
*/
|
||||
private async withIgnoreInvitesPolicies(cb: (ignoreInvitesPolicies: {[key: string]: any}) => void) {
|
||||
const { policies, ignoreInvitesPolicies } = this.getPoliciesAndIgnoreInvitesPolicies();
|
||||
cb(ignoreInvitesPolicies);
|
||||
policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;
|
||||
await this.client.setAccountData(POLICIES_ACCOUNT_EVENT_TYPE.name, policies);
|
||||
}
|
||||
|
||||
/**
|
||||
* As `getIgnoreInvitesPolicies` but also return the `POLICIES_ACCOUNT_EVENT_TYPE`
|
||||
* object.
|
||||
*/
|
||||
private getPoliciesAndIgnoreInvitesPolicies():
|
||||
{policies: {[key: string]: any}, ignoreInvitesPolicies: {[key: string]: any}} {
|
||||
let policies = {};
|
||||
for (const key of [POLICIES_ACCOUNT_EVENT_TYPE.name, POLICIES_ACCOUNT_EVENT_TYPE.altName]) {
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
const value = this.client.getAccountData(key)?.getContent();
|
||||
if (value) {
|
||||
policies = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let ignoreInvitesPolicies = {};
|
||||
let hasIgnoreInvitesPolicies = false;
|
||||
for (const key of [IGNORE_INVITES_ACCOUNT_EVENT_KEY.name, IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]) {
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
const value = policies[key];
|
||||
if (value && typeof value == "object") {
|
||||
ignoreInvitesPolicies = value;
|
||||
hasIgnoreInvitesPolicies = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!hasIgnoreInvitesPolicies) {
|
||||
policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;
|
||||
}
|
||||
|
||||
return { policies, ignoreInvitesPolicies };
|
||||
}
|
||||
}
|
||||
+34
-64
@@ -1981,14 +1981,6 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (event.getUnsigned().transaction_id) {
|
||||
const existingEvent = this.txnToEvent[event.getUnsigned().transaction_id];
|
||||
if (existingEvent) {
|
||||
// remote echo of an event we sent earlier
|
||||
this.handleRemoteEcho(event, existingEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1996,7 +1988,7 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
|
||||
* "Room.timeline".
|
||||
*
|
||||
* @param {MatrixEvent} event Event to be added
|
||||
* @param {IAddLiveEventOptions} options addLiveEvent options
|
||||
* @param {IAddLiveEventOptions} addLiveEventOptions addLiveEvent options
|
||||
* @fires module:client~MatrixClient#event:"Room.timeline"
|
||||
* @private
|
||||
*/
|
||||
@@ -2344,7 +2336,7 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
|
||||
fromCache = false,
|
||||
): void {
|
||||
let duplicateStrategy = duplicateStrategyOrOpts as DuplicateStrategy;
|
||||
let timelineWasEmpty: boolean;
|
||||
let timelineWasEmpty = false;
|
||||
if (typeof (duplicateStrategyOrOpts) === 'object') {
|
||||
({
|
||||
duplicateStrategy,
|
||||
@@ -2383,10 +2375,25 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
|
||||
const threadRoots = this.findThreadRoots(events);
|
||||
const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};
|
||||
|
||||
const options: IAddLiveEventOptions = {
|
||||
duplicateStrategy,
|
||||
fromCache,
|
||||
timelineWasEmpty,
|
||||
};
|
||||
|
||||
for (const event of events) {
|
||||
// TODO: We should have a filter to say "only add state event types X Y Z to the timeline".
|
||||
this.processLiveEvent(event);
|
||||
|
||||
if (event.getUnsigned().transaction_id) {
|
||||
const existingEvent = this.txnToEvent[event.getUnsigned().transaction_id!];
|
||||
if (existingEvent) {
|
||||
// remote echo of an event we sent earlier
|
||||
this.handleRemoteEcho(event, existingEvent);
|
||||
continue; // we can skip adding the event to the timeline sets, it is already there
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
shouldLiveInRoom,
|
||||
shouldLiveInThread,
|
||||
@@ -2399,11 +2406,7 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
|
||||
eventsByThread[threadId]?.push(event);
|
||||
|
||||
if (shouldLiveInRoom) {
|
||||
this.addLiveEvent(event, {
|
||||
duplicateStrategy,
|
||||
fromCache,
|
||||
timelineWasEmpty,
|
||||
});
|
||||
this.addLiveEvent(event, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2597,59 +2600,26 @@ export class Room extends TypedEventEmitter<EmittedEvents, RoomEventHandlerMap>
|
||||
// some more intelligent manner or the client should just use timestamps
|
||||
|
||||
const timelineSet = this.getUnfilteredTimelineSet();
|
||||
const publicReadReceipt = this.getReadReceiptForUserId(
|
||||
userId,
|
||||
ignoreSynthesized,
|
||||
ReceiptType.Read,
|
||||
);
|
||||
const privateReadReceipt = this.getReadReceiptForUserId(
|
||||
userId,
|
||||
ignoreSynthesized,
|
||||
ReceiptType.ReadPrivate,
|
||||
);
|
||||
const unstablePrivateReadReceipt = this.getReadReceiptForUserId(
|
||||
userId,
|
||||
ignoreSynthesized,
|
||||
ReceiptType.UnstableReadPrivate,
|
||||
);
|
||||
const publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.Read);
|
||||
const privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.ReadPrivate);
|
||||
|
||||
// If we have all, compare them
|
||||
if (publicReadReceipt?.eventId && privateReadReceipt?.eventId && unstablePrivateReadReceipt?.eventId) {
|
||||
const comparison1 = timelineSet.compareEventOrdering(
|
||||
publicReadReceipt.eventId,
|
||||
privateReadReceipt.eventId,
|
||||
);
|
||||
const comparison2 = timelineSet.compareEventOrdering(
|
||||
publicReadReceipt.eventId,
|
||||
unstablePrivateReadReceipt.eventId,
|
||||
);
|
||||
const comparison3 = timelineSet.compareEventOrdering(
|
||||
privateReadReceipt.eventId,
|
||||
unstablePrivateReadReceipt.eventId,
|
||||
);
|
||||
if (comparison1 && comparison2 && comparison3) {
|
||||
return (comparison1 > 0)
|
||||
? ((comparison2 > 0) ? publicReadReceipt.eventId : unstablePrivateReadReceipt.eventId)
|
||||
: ((comparison3 > 0) ? privateReadReceipt.eventId : unstablePrivateReadReceipt.eventId);
|
||||
}
|
||||
// If we have both, compare them
|
||||
let comparison: number | null | undefined;
|
||||
if (publicReadReceipt?.eventId && privateReadReceipt?.eventId) {
|
||||
comparison = timelineSet.compareEventOrdering(publicReadReceipt?.eventId, privateReadReceipt?.eventId);
|
||||
}
|
||||
|
||||
let latest = privateReadReceipt;
|
||||
[unstablePrivateReadReceipt, publicReadReceipt].forEach((receipt) => {
|
||||
if (receipt?.data?.ts > latest?.data?.ts || !latest) {
|
||||
latest = receipt;
|
||||
}
|
||||
});
|
||||
if (latest?.eventId) return latest?.eventId;
|
||||
// If we didn't get a comparison try to compare the ts of the receipts
|
||||
if (!comparison && publicReadReceipt?.data?.ts && privateReadReceipt?.data?.ts) {
|
||||
comparison = publicReadReceipt?.data?.ts - privateReadReceipt?.data?.ts;
|
||||
}
|
||||
|
||||
// The more less likely it is for a read receipt to drift out of date
|
||||
// the bigger is its precedence
|
||||
return (
|
||||
privateReadReceipt?.eventId ??
|
||||
unstablePrivateReadReceipt?.eventId ??
|
||||
publicReadReceipt?.eventId ??
|
||||
null
|
||||
);
|
||||
// The public receipt is more likely to drift out of date so the private
|
||||
// one has precedence
|
||||
if (!comparison) return privateReadReceipt?.eventId ?? publicReadReceipt?.eventId ?? null;
|
||||
|
||||
// If public read receipt is older, return the private one
|
||||
return ((comparison < 0) ? privateReadReceipt?.eventId : publicReadReceipt?.eventId) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -335,7 +335,7 @@ export class Thread extends TypedEventEmitter<EmittedEvents, EventHandlerMap> {
|
||||
/**
|
||||
* Return last reply to the thread, if known.
|
||||
*/
|
||||
public lastReply(matches: (ev: MatrixEvent) => boolean = () => true): Optional<MatrixEvent> {
|
||||
public lastReply(matches: (ev: MatrixEvent) => boolean = () => true): MatrixEvent | null {
|
||||
for (let i = this.events.length - 1; i >= 0; i--) {
|
||||
const event = this.events[i];
|
||||
if (matches(event)) {
|
||||
@@ -384,7 +384,7 @@ export class Thread extends TypedEventEmitter<EmittedEvents, EventHandlerMap> {
|
||||
public async fetchEvents(opts: IRelationsRequestOpts = { limit: 20, direction: Direction.Backward }): Promise<{
|
||||
originalEvent: MatrixEvent;
|
||||
events: MatrixEvent[];
|
||||
nextBatch?: string;
|
||||
nextBatch?: string | null;
|
||||
prevBatch?: string;
|
||||
}> {
|
||||
let {
|
||||
|
||||
+11
-1
@@ -293,13 +293,16 @@ export class SlidingSyncSdk {
|
||||
this.processRoomData(this.client, room, roomData);
|
||||
}
|
||||
|
||||
private onLifecycle(state: SlidingSyncState, resp: MSC3575SlidingSyncResponse, err?: Error): void {
|
||||
private onLifecycle(state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, err: Error | null): void {
|
||||
if (err) {
|
||||
logger.debug("onLifecycle", state, err);
|
||||
}
|
||||
switch (state) {
|
||||
case SlidingSyncState.Complete:
|
||||
this.purgeNotifications();
|
||||
if (!resp) {
|
||||
break;
|
||||
}
|
||||
// Element won't stop showing the initial loading spinner unless we fire SyncState.Prepared
|
||||
if (!this.lastPos) {
|
||||
this.updateSyncState(SyncState.Prepared, {
|
||||
@@ -472,6 +475,13 @@ export class SlidingSyncSdk {
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isInteger(roomData.invited_count)) {
|
||||
room.currentState.setInvitedMemberCount(roomData.invited_count!);
|
||||
}
|
||||
if (Number.isInteger(roomData.joined_count)) {
|
||||
room.currentState.setJoinedMemberCount(roomData.joined_count!);
|
||||
}
|
||||
|
||||
if (roomData.invite_state) {
|
||||
const inviteStateEvents = mapEvents(this.client, room.roomId, roomData.invite_state);
|
||||
this.processRoomEvents(room, inviteStateEvents);
|
||||
|
||||
+5
-1
@@ -84,6 +84,8 @@ export interface MSC3575RoomData {
|
||||
timeline: (IRoomEvent | IStateEvent)[];
|
||||
notification_count?: number;
|
||||
highlight_count?: number;
|
||||
joined_count?: number;
|
||||
invited_count?: number;
|
||||
invite_state?: IStateEvent[];
|
||||
initial?: boolean;
|
||||
limited?: boolean;
|
||||
@@ -320,7 +322,9 @@ export enum SlidingSyncEvent {
|
||||
|
||||
export type SlidingSyncEventHandlerMap = {
|
||||
[SlidingSyncEvent.RoomData]: (roomId: string, roomData: MSC3575RoomData) => void;
|
||||
[SlidingSyncEvent.Lifecycle]: (state: SlidingSyncState, resp: MSC3575SlidingSyncResponse, err: Error) => void;
|
||||
[SlidingSyncEvent.Lifecycle]: (
|
||||
state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, err: Error | null,
|
||||
) => void;
|
||||
[SlidingSyncEvent.List]: (
|
||||
listIndex: number, joinedCount: number, roomIndexToRoomId: Record<number, string>,
|
||||
) => void;
|
||||
|
||||
+4
-14
@@ -24,7 +24,7 @@ import unhomoglyph from "unhomoglyph";
|
||||
import promiseRetry from "p-retry";
|
||||
|
||||
import type * as NodeCrypto from "crypto";
|
||||
import { MatrixClient, MatrixEvent } from ".";
|
||||
import { MatrixEvent } from ".";
|
||||
import { M_TIMESTAMP } from "./@types/location";
|
||||
import { ReceiptType } from "./@types/read_receipts";
|
||||
|
||||
@@ -341,7 +341,7 @@ export function escapeRegExp(string: string): string {
|
||||
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
export function globToRegexp(glob: string, extended?: any): string {
|
||||
export function globToRegexp(glob: string, extended = false): string {
|
||||
// From
|
||||
// https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132
|
||||
// Because micromatch is about 130KB with dependencies,
|
||||
@@ -349,7 +349,7 @@ export function globToRegexp(glob: string, extended?: any): string {
|
||||
const replacements: ([RegExp, string | ((substring: string, ...args: any[]) => string) ])[] = [
|
||||
[/\\\*/g, '.*'],
|
||||
[/\?/g, '.'],
|
||||
extended !== false && [
|
||||
!extended && [
|
||||
/\\\[(!|)(.*)\\]/g,
|
||||
(_match: string, neg: string, pat: string) => [
|
||||
'[',
|
||||
@@ -670,17 +670,7 @@ export function sortEventsByLatestContentTimestamp(left: MatrixEvent, right: Mat
|
||||
return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left);
|
||||
}
|
||||
|
||||
export async function getPrivateReadReceiptField(client: MatrixClient): Promise<ReceiptType | null> {
|
||||
if (await client.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")) return ReceiptType.ReadPrivate;
|
||||
if (await client.doesServerSupportUnstableFeature("org.matrix.msc2285")) return ReceiptType.UnstableReadPrivate;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isSupportedReceiptType(receiptType: string): boolean {
|
||||
return [
|
||||
ReceiptType.Read,
|
||||
ReceiptType.ReadPrivate,
|
||||
ReceiptType.UnstableReadPrivate,
|
||||
].includes(receiptType as ReceiptType);
|
||||
return [ReceiptType.Read, ReceiptType.ReadPrivate].includes(receiptType as ReceiptType);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user