-
Notifications
You must be signed in to change notification settings - Fork 25
/
app-service-registration.ts
352 lines (321 loc) · 11.4 KB
/
app-service-registration.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
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
import { randomBytes } from "crypto";
import yaml from "js-yaml";
import fs from "fs";
export interface RegexObj {
regex: string;
exclusive: boolean;
}
export interface AppServiceOutput {
url: string|null;
id: string;
// eslint-disable-next-line camelcase
hs_token: string;
// eslint-disable-next-line camelcase
as_token: string;
// eslint-disable-next-line camelcase
sender_localpart: string;
// eslint-disable-next-line camelcase
rate_limited?: boolean;
protocols?: string[]|null;
"de.sorunome.msc2409.push_ephemeral"?: boolean;
namespaces?: {
users?: RegexObj[];
rooms?: RegexObj[];
aliases?: RegexObj[];
}
}
export class AppServiceRegistration {
/**
* Generate a random token.
* @return {string} A randomly generated token.
*/
public static generateToken() {
return randomBytes(32).toString('hex');
}
/**
* Convert a JSON object to an AppServiceRegistration object.
* @static
* @param obj The registration object
* @return The registration.
*/
public static fromObject(obj: AppServiceOutput): AppServiceRegistration {
const reg = new AppServiceRegistration(obj.url);
reg.setId(obj.id);
reg.setHomeserverToken(obj.hs_token);
reg.setAppServiceToken(obj.as_token);
reg.setSenderLocalpart(obj.sender_localpart);
if (obj.rate_limited !== undefined) reg.setRateLimited(obj.rate_limited);
if (obj.protocols) reg.setProtocols(obj.protocols);
reg.pushEphemeral = obj["de.sorunome.msc2409.push_ephemeral"];
if (obj.namespaces) {
const kinds: ("users"|"aliases"|"rooms")[] = ["users", "aliases", "rooms"];
for (const kind of kinds) {
const namespace = obj.namespaces[kind];
if (!namespace) {
continue;
}
namespace.forEach((regexObj: RegexObj) => {
reg.addRegexPattern(
kind, regexObj.regex, regexObj.exclusive,
);
});
}
}
return reg;
}
/**
* Construct a new application service registration.
* @constructor
* @param {string} appServiceUrl The base URL the AS can be reached via.
*/
private id: string|null = null;
private hsToken: string|null = null;
private asToken: string|null = null;
private senderLocalpart: string|null = null;
private rateLimited: boolean|undefined = undefined;
/**
* **Experimental**
* Signal to the homeserver that this appservice will accept ephemeral events.
*/
public pushEphemeral: boolean|undefined = undefined;
private namespaces: {
users?: RegexObj[];
aliases?: RegexObj[];
rooms?: RegexObj[];
} = {};
private protocols: string[]|null = null;
private cachedRegex: {[regextext: string]: RegExp} = {};
constructor (private url: string|null) { }
/**
* Set the URL which the home server will hit in order to talk to the AS.
* @param {string} url The application service url
*/
public setAppServiceUrl(url: string) {
this.url = url;
}
/**
* Get the URL which the home server will hit in order to talk to the AS.
*/
public getAppServiceUrl() {
return this.url;
}
/**
* Set the ID of the appservice; must be unique across the homeserver and never change.
* @param {string} id The ID
*/
public setId(id: string) {
this.id = id;
}
/**
* Get the ID of the appservice.
* @return {?string} The ID
*/
public getId() {
return this.id;
}
/**
* Set the list of protocols that this appservice will serve for third party lookups.
* @param {string[]} protocols The protocols
*/
public setProtocols(protocols: string[]) {
this.protocols = protocols;
}
/**
* Get the list of protocols that this appservice will serve for third party lookups.
* Will return null if no protocols have been set.
* @return {string[]} The protocols.
*/
public getProtocols() {
return this.protocols;
}
/**
* Set the token the homeserver will use to communicate with the app service.
* @param {string} token The token
*/
public setHomeserverToken(token: string) {
this.hsToken = token;
}
/**
* Get the token the homeserver will use to communicate with the app service.
* @return {?string} The token
*/
public getHomeserverToken() {
return this.hsToken;
}
/**
* Set the token the app service will use to communicate with the homeserver.
* @param {string} token The token
*/
public setAppServiceToken(token: string) {
this.asToken = token;
}
/**
* Get the token the app service will use to communicate with the homeserver.
* @return {?string} The token
*/
public getAppServiceToken() {
return this.asToken;
}
/**
* Set the desired user_id localpart for the app service itself.
* @param {string} localpart The user_id localpart ("alice" in "@alice:domain")
*/
public setSenderLocalpart(localpart: string) {
this.senderLocalpart = localpart;
}
/**
* Get whether requests from this AS are rate-limited by the home server.
*/
public isRateLimited() {
return this.rateLimited === undefined ? true : this.rateLimited;
}
/**
* Set whether requests from this AS are rate-limited by the home server.
* @param {boolean} isRateLimited The flag which is set to true to enable rate
* rate limiting, false to disable.
*/
public setRateLimited(isRateLimited: boolean) {
this.rateLimited = isRateLimited;
}
/**
* **Experimental**
*
* Should the appservice receive ephemeral events. Note this requires
* a homeserver implementing MSC2409.
*/
public pushEphemeralEnabled() {
return this.pushEphemeral || false;
}
/**
* Get the desired user_id localpart for the app service itself.
* @return {?string} The user_id localpart ("alice" in "@alice:domain")
*/
public getSenderLocalpart() {
return this.senderLocalpart;
}
/**
* Add a regex pattern to be registered.
* @param {String} type : The type of regex pattern. Must be 'users', 'rooms', or
* 'aliases'.
* @param {String} regex : The regex pattern.
* @param {Boolean} exclusive : True to reserve the matched namespace.
* @throws If given an invalid type or regex.
*/
public addRegexPattern(type: "users"|"rooms"|"aliases", regex: string, exclusive?: boolean) {
if (typeof regex != "string") {
throw new Error("Regex must be a string");
}
if (["users", "aliases", "rooms"].indexOf(type) == -1) {
throw new Error("'type' must be 'users', 'rooms' or 'aliases'");
}
const regexObject = {
exclusive: Boolean(exclusive),
regex: regex
};
const namespace = this.namespaces[type];
if (namespace) {
namespace.push(regexObject);
} else {
this.namespaces[type] = [regexObject];
}
}
/**
* Output this registration to the given file name.
* @param {String} filename The file name to write the yaml to.
* @throws If required fields hs_token, as_token, url are missing.
*/
public outputAsYaml(filename: string) {
const reg = this.getOutput();
fs.writeFileSync(filename, yaml.dump(reg));
}
/**
* Get the key-value output which should be written to a YAML file.
* @throws If required fields hs_token, as-token, url, sender_localpart are missing.
*/
public getOutput(): AppServiceOutput {
// Typescript will default any string array to a set of strings, even if it's a static array.
const requiredFields: ("id"|"hsToken"|"asToken"|"senderLocalpart")[] = [
"id", "hsToken", "asToken", "senderLocalpart"
];
const missingFields = requiredFields.filter((key) => !this[key]);
if (missingFields.length) {
throw new Error(
`Missing required field(s): ${missingFields}`
);
}
const responseFormat: AppServiceOutput = {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: this.id!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
hs_token: this.hsToken!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
as_token: this.asToken!,
url: this.url,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
sender_localpart: this.senderLocalpart!,
};
if (this.pushEphemeral !== undefined) {
responseFormat["de.sorunome.msc2409.push_ephemeral"] = this.pushEphemeral;
}
if (this.protocols) {
responseFormat.protocols = this.protocols;
}
if (Object.keys(this.namespaces).length > 0) {
responseFormat.namespaces = this.namespaces;
}
if(this.rateLimited !== undefined) {
responseFormat.rate_limited = this.rateLimited;
}
return responseFormat;
}
/**
* Check if a user_id meets this registration regex.
* @param {string} userId The user ID
* @param {boolean} onlyExclusive True to restrict matching to only exclusive
* regexes. False to allow exclusive or non-exlusive regexes to match.
* @return {boolean} True if there is a match.
*/
public isUserMatch(userId: string, onlyExclusive: boolean) {
return this._isMatch(this.namespaces.users, userId, onlyExclusive);
}
/**
* Check if a room alias meets this registration regex.
* @param {string} alias The room alias
* @param {boolean} onlyExclusive True to restrict matching to only exclusive
* regexes. False to allow exclusive or non-exlusive regexes to match.
* @return {boolean} True if there is a match.
*/
public isAliasMatch(alias: string, onlyExclusive: boolean) {
return this._isMatch(this.namespaces.aliases, alias, onlyExclusive);
}
/**
* Check if a room ID meets this registration regex.
* @param {string} roomId The room ID
* @param {boolean} onlyExclusive True to restrict matching to only exclusive
* regexes. False to allow exclusive or non-exlusive regexes to match.
* @return {boolean} True if there is a match.
*/
public isRoomMatch(roomId: string, onlyExclusive: boolean) {
return this._isMatch(this.namespaces.rooms, roomId, onlyExclusive);
}
public _isMatch(regexList: RegexObj[]|undefined, sample: string, onlyExclusive: boolean) {
if (!regexList) {
return false;
}
onlyExclusive = Boolean(onlyExclusive);
for (const regexObj of regexList) {
let regex = this.cachedRegex[regexObj.regex];
if (!regex) {
regex = new RegExp(regexObj.regex);
this.cachedRegex[regexObj.regex] = regex;
}
if (regex.test(sample)) {
if (onlyExclusive && !regexObj.exclusive) {
continue;
}
return true;
}
}
return false;
}
}