-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathinvite.service.ts
More file actions
261 lines (226 loc) · 7.18 KB
/
invite.service.ts
File metadata and controls
261 lines (226 loc) · 7.18 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
import { createLogger } from '@rocket.chat/federation-core';
import {
EventID,
PduForType,
PersistentEventBase,
PersistentEventFactory,
RoomID,
RoomVersion,
UserID,
extractDomainFromId,
} from '@rocket.chat/federation-room';
import { delay, inject, singleton } from 'tsyringe';
import { EventRepository } from '../repositories/event.repository';
import { ConfigService } from './config.service';
import { EventAuthorizationService } from './event-authorization.service';
import { EventEmitterService } from './event-emitter.service';
import { FederationService } from './federation.service';
import { StateService } from './state.service';
export class NotAllowedError extends Error {
constructor(message: string) {
super(message);
this.name = 'NotAllowedError';
}
}
@singleton()
export class InviteService {
private readonly logger = createLogger('InviteService');
constructor(
private readonly federationService: FederationService,
private readonly stateService: StateService,
private readonly configService: ConfigService,
private readonly eventAuthorizationService: EventAuthorizationService,
private readonly emitterService: EventEmitterService,
@inject(delay(() => EventRepository))
private readonly eventRepository: EventRepository,
) {}
/**
* Invite a user to an existing room
*/
async inviteUserToRoom(
userId: UserID,
roomId: RoomID,
sender: UserID,
isDirectMessage = false,
): Promise<{
event_id: EventID;
event: PersistentEventBase<RoomVersion, 'm.room.member'>;
room_id: RoomID;
}> {
this.logger.debug(`Inviting ${userId} to room ${roomId}`);
const stateService = this.stateService;
const federationService = this.federationService;
const roomVersion = await this.stateService.getRoomVersion(roomId);
// Extract displayname from userId for direct messages
const displayname = isDirectMessage
? userId.split(':').shift()?.slice(1)
: undefined;
const inviteEvent = await stateService.buildEvent<'m.room.member'>(
{
type: 'm.room.member',
content: {
membership: 'invite',
...(isDirectMessage && {
is_direct: true,
displayname: displayname,
}),
},
room_id: roomId,
state_key: userId,
auth_events: [],
depth: 0,
prev_events: [],
origin_server_ts: Date.now(),
sender: sender,
},
roomVersion,
);
// SPEC: Invites a remote user to a room. Once the event has been signed by both the inviting homeserver and the invited homeserver, it can be sent to all of the servers in the room by the inviting homeserver.
const invitedServer = extractDomainFromId(inviteEvent.stateKey ?? '');
if (!invitedServer) {
throw new Error(
`invalid state_key ${inviteEvent.stateKey}, no server_name part`,
);
}
// if user invited belongs to our server
if (invitedServer === this.configService.serverName) {
await stateService.handlePdu(inviteEvent);
// let all servers know of this state change
// without it join events will not be processed if /event/{eventId} causes problems
void federationService.sendEventToAllServersInRoom(inviteEvent);
return {
event_id: inviteEvent.eventId,
event: PersistentEventFactory.createFromRawEvent(
inviteEvent.event,
roomVersion,
),
room_id: roomId,
};
}
// invited user from another room
// get signed invite event
const inviteResponse = await federationService.inviteUser(
inviteEvent,
roomVersion,
);
// try to save
// can only invite if already part of the room
await stateService.handlePdu(
PersistentEventFactory.createFromRawEvent(
inviteResponse.event,
roomVersion,
),
);
// let everyone know
void federationService.sendEventToAllServersInRoom(inviteEvent);
return {
event_id: inviteEvent.eventId,
event: PersistentEventFactory.createFromRawEvent(
inviteEvent.event,
roomVersion,
),
room_id: roomId,
};
}
private async shouldProcessInvite(
strippedStateEvents: PduForType<
| 'm.room.create'
| 'm.room.name'
| 'm.room.avatar'
| 'm.room.topic'
| 'm.room.join_rules'
| 'm.room.canonical_alias'
| 'm.room.encryption'
>[],
): Promise<void> {
const isRoomNonPrivate = strippedStateEvents.some(
(stateEvent) =>
stateEvent.type === 'm.room.join_rules' &&
stateEvent.content.join_rule === 'public',
);
const isRoomEncrypted = strippedStateEvents.some(
(stateEvent) => stateEvent.type === 'm.room.encryption',
);
const { allowedEncryptedRooms, allowedNonPrivateRooms } =
this.configService.getConfig('invite');
const shouldRejectInvite =
(!allowedEncryptedRooms && isRoomEncrypted) ||
(!allowedNonPrivateRooms && isRoomNonPrivate);
if (shouldRejectInvite) {
throw new NotAllowedError(
`Could not process invite due to room being ${isRoomEncrypted ? 'encrypted' : 'public'}`,
);
}
}
async processInvite(
event: PduForType<'m.room.member'>,
eventId: EventID,
roomVersion: RoomVersion,
strippedStateEvents: PduForType<
| 'm.room.create'
| 'm.room.name'
| 'm.room.avatar'
| 'm.room.topic'
| 'm.room.join_rules'
| 'm.room.canonical_alias'
| 'm.room.encryption'
>[],
): Promise<PersistentEventBase<RoomVersion, 'm.room.member'>> {
await this.shouldProcessInvite(strippedStateEvents);
const inviteEvent =
PersistentEventFactory.createFromRawEvent<'m.room.member'>(
event,
roomVersion,
);
if (inviteEvent.eventId !== eventId) {
throw new Error(`Invalid eventId ${eventId}`);
}
const { residentServer } = inviteEvent;
if (residentServer === this.configService.serverName) {
await this.eventAuthorizationService.checkAclForInvite(
event.room_id,
residentServer,
);
await this.stateService.handlePdu(inviteEvent);
return inviteEvent;
}
const invitedServer = extractDomainFromId(event.state_key);
if (!invitedServer) {
throw new Error(
`invalid state_key ${event.state_key}, no server_name part`,
);
}
if (invitedServer !== this.configService.serverName) {
throw new Error(
`Cannot sign invite for user ${event.state_key}: user does not belong to this server (${this.configService.serverName})`,
);
}
await this.stateService.signEvent(inviteEvent);
// we have no specific structure to store the invite_room_state received on the invite route,
// so we store it in the unsigned section of the invite event.
inviteEvent.event.unsigned.invite_room_state = strippedStateEvents;
// check if we are already in the room, if so we can handlePdu because we have the state and should save
// the invite in the state as well
const createEvent = await this.eventRepository.findByRoomIdAndType(
event.room_id,
'm.room.create',
);
if (createEvent) {
await this.stateService.handlePdu(inviteEvent);
} else {
// otherwise we save as outlier only so we can deal with it later
await this.eventRepository.insertOutlierEvent(
inviteEvent.eventId,
inviteEvent.event,
residentServer,
);
}
this.emitterService.emit('homeserver.matrix.membership', {
event_id: inviteEvent.eventId,
event: inviteEvent.event,
});
// we are not the host of the server
// so being the origin of the user, we sign the event and send it to the asking server, let them handle the transactions
return inviteEvent;
}
}