-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathinvite.ts
More file actions
386 lines (338 loc) · 9.35 KB
/
invite.ts
File metadata and controls
386 lines (338 loc) · 9.35 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import { FederationMatrix, Room } from '@rocket.chat/core-services';
import { isUserNativeFederated, type IUser } from '@rocket.chat/core-typings';
import { eventIdSchema, roomIdSchema } from '@rocket.chat/federation-sdk';
import type {
HomeserverServices,
RoomService,
StateService,
PduMembershipEventContent,
PersistentEventBase,
RoomVersion,
} from '@rocket.chat/federation-sdk';
import { Router } from '@rocket.chat/http-router';
import { Rooms, Users } from '@rocket.chat/models';
import { ajv } from '@rocket.chat/rest-typings/dist/v1/Ajv';
import { createOrUpdateFederatedUser, getUsernameServername } from '../../FederationMatrix';
import { isAuthenticatedMiddleware } from '../middlewares/isAuthenticated';
const EventBaseSchema = {
type: 'object',
properties: {
type: {
type: 'string',
description: 'Event type',
},
content: {
type: 'object',
description: 'Event content',
},
sender: {
type: 'string',
},
room_id: {
type: 'string',
},
origin_server_ts: {
type: 'number',
},
depth: {
type: 'number',
},
prev_events: {
type: 'array',
items: {
type: 'string',
},
description: 'Previous events in the room',
},
auth_events: {
type: 'array',
items: {
type: 'string',
},
description: 'Authorization events',
},
origin: {
type: 'string',
description: 'Origin server',
},
hashes: {
type: 'object',
nullable: true,
},
signatures: {
type: 'object',
nullable: true,
},
unsigned: {
type: 'object',
description: 'Unsigned data',
nullable: true,
},
},
required: ['type', 'content', 'sender', 'room_id', 'origin_server_ts', 'depth', 'prev_events', 'auth_events', 'origin'],
};
const MembershipEventContentSchema = {
type: 'object',
properties: {
membership: {
type: 'string',
},
displayname: {
type: 'string',
nullable: true,
},
avatar_url: {
type: 'string',
nullable: true,
},
},
required: ['membership'],
};
const RoomMemberEventSchema = {
type: 'object',
allOf: [
EventBaseSchema,
{
type: 'object',
properties: {
type: {
type: 'string',
const: 'm.room.member',
},
content: MembershipEventContentSchema,
state_key: {
type: 'string',
},
},
required: ['type', 'content', 'state_key'],
},
],
};
const ProcessInviteParamsSchema = {
type: 'object',
properties: {
roomId: {
type: 'string',
},
eventId: {
type: 'string',
},
},
required: ['roomId', 'eventId'],
};
const isProcessInviteParamsProps = ajv.compile(ProcessInviteParamsSchema);
const ProcessInviteResponseSchema = {
type: 'object',
properties: {
event: RoomMemberEventSchema,
},
required: ['event'],
};
const isProcessInviteResponseProps = ajv.compile(ProcessInviteResponseSchema);
// 5 seconds
// 25 seconds
// 625 seconds = 10 minutes 25 seconds // max
async function runWithBackoff(fn: () => Promise<void>, delaySec = 5) {
try {
await fn();
} catch (e) {
const delay = Math.min(625, delaySec ** 2);
console.error(`error occurred, retrying in ${delay}s`, e);
setTimeout(() => {
runWithBackoff(fn, delay);
}, delay * 1000);
}
}
async function joinRoom({
inviteEvent,
user, // ours trying to join the room
room,
state,
}: {
inviteEvent: PersistentEventBase<RoomVersion, 'm.room.member'>;
user: IUser;
room: RoomService;
state: StateService;
}) {
// from the response we get the event
if (!inviteEvent.stateKey) {
throw new Error('join event has missing state key, unable to determine user to join');
}
// backoff needed for this call, can fail
await room.joinUser(inviteEvent.roomId, inviteEvent.event.state_key);
// now we create the room we saved post joining
const matrixRoom = await state.getLatestRoomState2(inviteEvent.roomId);
if (!matrixRoom) {
throw new Error('room not found not processing invite');
}
// we only understand these two types of rooms, plus direct messages
const isDM = inviteEvent.getContent<PduMembershipEventContent>().is_direct;
if (!isDM && !matrixRoom.isPublic() && !matrixRoom.isInviteOnly()) {
throw new Error('room is neither direct message - rocketchat is unable to join for now');
}
// need both the sender and the participating user to exist in the room
// TODO implement on model
const senderUser = await Users.findOneByUsername(inviteEvent.sender, { projection: { _id: 1 } });
const senderUserId =
senderUser?._id ||
(await createOrUpdateFederatedUser({
username: inviteEvent.sender,
origin: matrixRoom.origin,
}));
if (!senderUserId) {
throw new Error('Sender user ID not found');
}
let internalRoomId: string;
const internalMappedRoom = await Rooms.findOne({ 'federation.mrid': inviteEvent.roomId });
if (!internalMappedRoom) {
let roomType: 'c' | 'p' | 'd';
if (isDM) {
roomType = 'd';
} else if (matrixRoom.isPublic()) {
roomType = 'c';
} else if (matrixRoom.isInviteOnly()) {
roomType = 'p';
} else {
throw new Error('room is neither public, private, nor direct message - rocketchat is unable to join for now');
}
let ourRoom: { _id: string };
if (isDM) {
const senderUser = await Users.findOneById(senderUserId, { projection: { _id: 1, username: 1 } });
const inviteeUser = user;
if (!senderUser?.username) {
throw new Error('Sender user not found');
}
if (!inviteeUser?.username) {
throw new Error('Invitee user not found');
}
ourRoom = await Room.create(senderUserId, {
type: roomType,
name: inviteEvent.sender,
members: [senderUser.username, inviteeUser.username],
options: {
federatedRoomId: inviteEvent.roomId,
creator: senderUserId,
},
extraData: {
federated: true,
},
});
} else {
const roomFname = `${matrixRoom.name}:${matrixRoom.origin}`;
const roomName = inviteEvent.roomId.replace('!', '').replace(':', '_');
ourRoom = await Room.create(senderUserId, {
type: roomType,
name: roomName,
options: {
federatedRoomId: inviteEvent.roomId,
creator: senderUserId,
},
extraData: {
federated: true,
fname: roomFname,
},
});
}
internalRoomId = ourRoom._id;
} else {
internalRoomId = internalMappedRoom._id;
}
await Room.addUserToRoom(internalRoomId, { _id: user._id }, { _id: senderUserId, username: inviteEvent.sender });
for await (const event of matrixRoom.getMemberJoinEvents()) {
await FederationMatrix.emitJoin(event.event, event.eventId);
}
}
async function startJoiningRoom(...opts: Parameters<typeof joinRoom>) {
void runWithBackoff(() => joinRoom(...opts));
}
// This is a special case where inside rocket chat we invite users inside rockechat, so if the sender or the invitee are external iw should throw an error
export const acceptInvite = async (
inviteEvent: PersistentEventBase<RoomVersion, 'm.room.member'>,
username: string,
services: HomeserverServices,
) => {
if (!inviteEvent.stateKey) {
throw new Error('join event has missing state key, unable to determine user to join');
}
const internalMappedRoom = await Rooms.findOne({ 'federation.mrid': inviteEvent.roomId });
if (!internalMappedRoom) {
throw new Error('room not found not processing invite');
}
const inviter = await Users.findOneByUsername<Pick<IUser, '_id' | 'username'>>(
getUsernameServername(inviteEvent.sender, services.config.serverName)[0],
{
projection: { _id: 1, username: 1 },
},
);
if (!inviter) {
throw new Error('Sender user ID not found');
}
if (isUserNativeFederated(inviter)) {
throw new Error('Sender user is native federated');
}
const user = await Users.findOneByUsername<Pick<IUser, '_id' | 'username' | 'federation' | 'federated'>>(username, {
projection: { username: 1, federation: 1, federated: 1 },
});
// we cannot accept invites from users that are external
if (!user) {
throw new Error('User not found');
}
if (isUserNativeFederated(user)) {
throw new Error('User is native federated');
}
await services.room.joinUser(inviteEvent.roomId, inviteEvent.event.state_key);
};
export const getMatrixInviteRoutes = (services: HomeserverServices) => {
const { invite, state, room, federationAuth } = services;
return new Router('/federation').put(
'/v2/invite/:roomId/:eventId',
{
body: ajv.compile({ type: 'object' }), // TODO: add schema from room package.
params: isProcessInviteParamsProps,
response: {
200: isProcessInviteResponseProps,
},
tags: ['Federation'],
license: ['federation'],
},
isAuthenticatedMiddleware(federationAuth),
async (c) => {
const { roomId, eventId } = c.req.param();
const { event, room_version: roomVersion } = await c.req.json();
const userToCheck = event.state_key as string;
if (!userToCheck) {
throw new Error('join event has missing state key, unable to determine user to join');
}
const [username /* domain */] = userToCheck.split(':');
// TODO: check domain
const ourUser = await Users.findOneByUsername(username.slice(1));
if (!ourUser) {
throw new Error('user not found not processing invite');
}
const inviteEvent = await invite.processInvite(
event,
roomIdSchema.parse(roomId),
eventIdSchema.parse(eventId),
roomVersion,
c.get('authenticatedServer'),
);
setTimeout(
() => {
void startJoiningRoom({
inviteEvent,
user: ourUser,
room,
state,
});
},
inviteEvent.event.content.is_direct ? 2000 : 0,
);
return {
body: {
event: inviteEvent.event,
},
statusCode: 200,
};
},
);
};