-
-
Notifications
You must be signed in to change notification settings - Fork 702
Expand file tree
/
Copy pathToDeviceKeyTransport.ts
More file actions
197 lines (170 loc) · 7.5 KB
/
Copy pathToDeviceKeyTransport.ts
File metadata and controls
197 lines (170 loc) · 7.5 KB
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
/*
Copyright 2025 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 { type WidgetApiResponseError } from "matrix-widget-api";
import { TypedEventEmitter } from "../models/typed-event-emitter.ts";
import { type IKeyTransport, KeyTransportEvents, type KeyTransportEventsHandlerMap } from "./IKeyTransport.ts";
import { type Logger, logger as rootLogger } from "../logger.ts";
import { type EncryptionKeysToDeviceEventContent, type ParticipantDeviceInfo, type Statistics } from "./types.ts";
import { ClientEvent, type MatrixClient } from "../client.ts";
import type { MatrixEvent } from "../models/event.ts";
import { EventType } from "../@types/event.ts";
import { type CallMembershipIdentityParts } from "./EncryptionManager.ts";
export class NotSupportedError extends Error {
public constructor(message?: string) {
super(message);
}
public get name(): string {
return "NotSupportedError";
}
}
/**
* ToDeviceKeyTransport is used to send MatrixRTC keys to other devices using the
* to-device CS-API.
*/
export class ToDeviceKeyTransport
extends TypedEventEmitter<KeyTransportEvents, KeyTransportEventsHandlerMap>
implements IKeyTransport
{
private logger: Logger = rootLogger;
public setParentLogger(parentLogger: Logger): void {
this.logger = parentLogger.getChild(`[ToDeviceKeyTransport]`);
}
public constructor(
private membership: CallMembershipIdentityParts,
private roomId: string,
private client: Pick<MatrixClient, "encryptAndSendToDevice" | "on" | "off">,
private statistics: Statistics,
parentLogger?: Logger,
) {
super();
this.setParentLogger(parentLogger ?? rootLogger);
}
public start(): void {
this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
}
public stop(): void {
this.client.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
}
public async sendKey(keyBase64Encoded: string, index: number, members: ParticipantDeviceInfo[]): Promise<void> {
const content: EncryptionKeysToDeviceEventContent = {
keys: {
index: index,
key: keyBase64Encoded,
},
room_id: this.roomId,
member: {
claimed_device_id: this.membership.deviceId,
id: this.membership.memberId,
},
session: {
call_id: "",
application: "m.call",
scope: "m.room",
},
sent_ts: Date.now(),
};
const targets = members
.map((member) => {
return {
userId: member.userId,
deviceId: member.deviceId,
};
})
// filter out me
.filter(
(member) => !(member.userId == this.membership.userId && member.deviceId == this.membership.deviceId),
);
if (targets.length > 0) {
await this.client
.encryptAndSendToDevice(EventType.CallEncryptionKeysPrefix, targets, content)
.catch((error: WidgetApiResponseError) => {
const msg: string = error.message;
// This is not ideal. We would want to have a custom error type for unsupported actions.
// This is not part of the widget API spec. Since as of now there are only two implementations:
// Rust SDK + JS-SDK, and the JS-SDK does support to-device sending, we can assume that
// this is a widget driver issue error message.
if (
(msg.includes("unknown variant") && msg.includes("send_to_device")) ||
msg.includes("not supported")
) {
throw new NotSupportedError("The widget driver does not support to-device encryption");
}
});
this.statistics.counters.roomEventEncryptionKeysSent += 1;
} else {
this.logger.warn("No targets found for sending key");
}
}
private receiveCallKeyEvent(fromUser: string, content: EncryptionKeysToDeviceEventContent): void {
// The event has already been validated at this point.
this.statistics.counters.roomEventEncryptionKeysReceived += 1;
// What is this, and why is it needed?
// Also to device events do not have an origin server ts
const now = Date.now();
const age = now - (typeof content.sent_ts === "number" ? content.sent_ts : now);
this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge += age;
const hardcodedMemberIdAlternative = `${fromUser}:${content.member.claimed_device_id}`;
this.emit(
KeyTransportEvents.ReceivedKeys,
// TODO userId this is claimed information, deviceId is claimed information
{
userId: fromUser,
deviceId: content.member.claimed_device_id,
memberId: content.member.id ?? hardcodedMemberIdAlternative,
},
content.keys.key,
content.keys.index,
now,
);
}
private onToDeviceEvent = (event: MatrixEvent): void => {
if (event.getType() !== EventType.CallEncryptionKeysPrefix) {
// Ignore this is not a call encryption event
return;
}
// NB: When received via the widget driver, the to-device events
// are properly reconstructed as if they are encrypted (see MatrixEvent#makeEncrypted).
if (event.getWireType() != EventType.RoomMessageEncrypted) {
// WARN: The call keys were sent in clear. Ignore them
this.logger.warn(`Call encryption keys sent in clear from: ${event.getSender()}`);
return;
}
const content = this.getValidEventContent(event);
if (!content) return;
if (!event.getSender()) return;
this.receiveCallKeyEvent(event.getSender()!, content);
};
private getValidEventContent(event: MatrixEvent): EncryptionKeysToDeviceEventContent | undefined {
const content = event.getContent();
const roomId = content.room_id;
if (!roomId) {
// Invalid event
this.logger.warn("Malformed Event: invalid call encryption keys event, no roomId");
return;
}
if (roomId !== this.roomId) {
this.logger.warn("Malformed Event: Mismatch roomId");
return;
}
if (!content.keys || !content.keys.key || typeof content.keys.index !== "number") {
this.logger.warn("Malformed Event: Missing keys field");
return;
}
if (!content.member || !content.member.claimed_device_id) {
this.logger.warn("Malformed Event: Missing claimed_device_id");
return;
}
// TODO check for session related fields once the to-device encryption uses the new format.
return content as EncryptionKeysToDeviceEventContent;
}
}