This repository has been archived by the owner on Sep 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 830
/
AutoRageshakeStore.ts
210 lines (183 loc) · 8.2 KB
/
AutoRageshakeStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
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 {
ClientEvent,
MatrixEvent,
MatrixEventEvent,
SyncStateData,
SyncState,
ToDeviceMessageId,
} from "matrix-js-sdk/src/matrix";
import { sleep } from "matrix-js-sdk/src/utils";
import { v4 as uuidv4 } from "uuid";
import { logger } from "matrix-js-sdk/src/logger";
import SdkConfig from "../SdkConfig";
import sendBugReport from "../rageshake/submit-rageshake";
import defaultDispatcher from "../dispatcher/dispatcher";
import { AsyncStoreWithClient } from "./AsyncStoreWithClient";
import { ActionPayload } from "../dispatcher/payloads";
import SettingsStore from "../settings/SettingsStore";
import { Action } from "../dispatcher/actions";
// Minimum interval of 1 minute between reports
const RAGESHAKE_INTERVAL = 60000;
// Before rageshaking, wait 5 seconds and see if the message has successfully decrypted
const GRACE_PERIOD = 5000;
// Event type for to-device messages requesting sender auto-rageshakes
const AUTO_RS_REQUEST = "im.vector.auto_rs_request";
interface IState {
reportedSessionIds: Set<string>;
lastRageshakeTime: number;
initialSyncCompleted: boolean;
}
/**
* Watches for decryption errors to auto-report if the relevant lab is
* enabled, and keeps track of session IDs that have already been
* reported.
*/
export default class AutoRageshakeStore extends AsyncStoreWithClient<IState> {
private static readonly internalInstance = (() => {
const instance = new AutoRageshakeStore();
instance.start();
return instance;
})();
private constructor() {
super(defaultDispatcher, {
reportedSessionIds: new Set<string>(),
lastRageshakeTime: 0,
initialSyncCompleted: false,
});
this.onDecryptionAttempt = this.onDecryptionAttempt.bind(this);
this.onDeviceMessage = this.onDeviceMessage.bind(this);
this.onSyncStateChange = this.onSyncStateChange.bind(this);
}
public static get instance(): AutoRageshakeStore {
return AutoRageshakeStore.internalInstance;
}
protected async onAction(payload: ActionPayload): Promise<void> {
switch (payload.action) {
case Action.ReportKeyBackupNotEnabled:
this.onReportKeyBackupNotEnabled();
}
}
protected async onReady(): Promise<void> {
if (!SettingsStore.getValue("automaticDecryptionErrorReporting")) return;
if (this.matrixClient) {
this.matrixClient.on(MatrixEventEvent.Decrypted, this.onDecryptionAttempt);
this.matrixClient.on(ClientEvent.ToDeviceEvent, this.onDeviceMessage);
this.matrixClient.on(ClientEvent.Sync, this.onSyncStateChange);
}
}
protected async onNotReady(): Promise<void> {
if (this.matrixClient) {
this.matrixClient.removeListener(ClientEvent.ToDeviceEvent, this.onDeviceMessage);
this.matrixClient.removeListener(MatrixEventEvent.Decrypted, this.onDecryptionAttempt);
this.matrixClient.removeListener(ClientEvent.Sync, this.onSyncStateChange);
}
}
private async onDecryptionAttempt(ev: MatrixEvent): Promise<void> {
if (!this.state.initialSyncCompleted) {
return;
}
const wireContent = ev.getWireContent();
const sessionId = wireContent.session_id;
if (ev.isDecryptionFailure() && !this.state.reportedSessionIds.has(sessionId)) {
await sleep(GRACE_PERIOD);
if (!ev.isDecryptionFailure()) {
return;
}
const newReportedSessionIds = new Set(this.state.reportedSessionIds);
await this.updateState({ reportedSessionIds: newReportedSessionIds.add(sessionId) });
const now = new Date().getTime();
if (now - this.state.lastRageshakeTime < RAGESHAKE_INTERVAL) {
logger.info(
`Not sending recipient-side autorageshake for event ${ev.getId()}/session ${sessionId}: last rageshake was too recent`,
);
return;
}
await this.updateState({ lastRageshakeTime: now });
const senderUserId = ev.getSender()!;
const eventInfo = {
event_id: ev.getId(),
room_id: ev.getRoomId(),
session_id: sessionId,
device_id: wireContent.device_id,
user_id: senderUserId,
sender_key: wireContent.sender_key,
};
logger.info(`Sending recipient-side autorageshake for event ${ev.getId()}/session ${sessionId}`);
// XXX: the rageshake server returns the URL for the github issue... which is typically absent for
// auto-uisis, because we've disabled creation of GH issues for them. So the `recipient_rageshake`
// field is broken.
const rageshakeURL = await sendBugReport(SdkConfig.get().bug_report_endpoint_url, {
userText: "Auto-reporting decryption error (recipient)",
sendLogs: true,
labels: ["Z-UISI", "web", "uisi-recipient"],
customApp: SdkConfig.get().uisi_autorageshake_app,
customFields: { auto_uisi: JSON.stringify(eventInfo) },
});
const messageContent = {
...eventInfo,
recipient_rageshake: rageshakeURL,
[ToDeviceMessageId]: uuidv4(),
};
this.matrixClient?.sendToDevice(
AUTO_RS_REQUEST,
new Map([[senderUserId, new Map([[messageContent.device_id, messageContent]])]]),
);
}
}
private async onSyncStateChange(
_state: SyncState,
_prevState: SyncState | null,
data?: SyncStateData,
): Promise<void> {
if (!this.state.initialSyncCompleted) {
await this.updateState({ initialSyncCompleted: !!data?.nextSyncToken });
}
}
private async onDeviceMessage(ev: MatrixEvent): Promise<void> {
if (ev.getType() !== AUTO_RS_REQUEST) return;
const messageContent = ev.getContent();
const recipientRageshake = messageContent["recipient_rageshake"] || "";
const now = new Date().getTime();
if (now - this.state.lastRageshakeTime > RAGESHAKE_INTERVAL) {
await this.updateState({ lastRageshakeTime: now });
logger.info(
`Sending sender-side autorageshake for event ${messageContent["event_id"]}/session ${messageContent["session_id"]}`,
);
await sendBugReport(SdkConfig.get().bug_report_endpoint_url, {
userText: `Auto-reporting decryption error (sender)\nRecipient rageshake: ${recipientRageshake}`,
sendLogs: true,
labels: ["Z-UISI", "web", "uisi-sender"],
customApp: SdkConfig.get().uisi_autorageshake_app,
customFields: {
recipient_rageshake: recipientRageshake,
auto_uisi: JSON.stringify(messageContent),
},
});
} else {
logger.info(
`Not sending sender-side autorageshake for event ${messageContent["event_id"]}/session ${messageContent["session_id"]}: last rageshake was too recent`,
);
}
}
private async onReportKeyBackupNotEnabled(): Promise<void> {
if (!SettingsStore.getValue("automaticKeyBackNotEnabledReporting")) return;
await sendBugReport(SdkConfig.get().bug_report_endpoint_url, {
userText: `Auto-reporting key backup not enabled`,
sendLogs: true,
labels: ["web", Action.ReportKeyBackupNotEnabled],
});
}
}
window.mxAutoRageshakeStore = AutoRageshakeStore.instance;