/
cli.ts
351 lines (323 loc) · 12.8 KB
/
cli.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
/*
Copyright 2020 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 * as fs from "fs";
import path from "path";
import * as yaml from "js-yaml";
import nopt from "nopt";
import { AppServiceOutput, AppServiceRegistration } from "matrix-appservice";
import { ConfigValidator } from "./config-validator";
import * as logging from "./logging";
const log = logging.get("cli");
export interface CliOpts<ConfigType extends Record<string, unknown>> {
run: (port: number, config: ConfigType|null, registration: AppServiceRegistration|null) => void;
onConfigChanged?: (config: ConfigType) => void,
generateRegistration?: (reg: AppServiceRegistration, cb: (finalReg: AppServiceRegistration) => void) => void;
bridgeConfig?: {
affectsRegistration?: boolean;
schema: string|Record<string, unknown>;
defaults: Record<string, unknown>;
};
registrationPath?: string;
enableRegistration?: boolean;
enableLocalpart?: boolean;
port?: number;
noUrl?: boolean;
}
interface VettedCliOpts<ConfigType extends Record<string, unknown>> {
run: (port: number, config: ConfigType | null, registration: AppServiceRegistration | null) => void;
onConfigChanged?: (config: ConfigType) => void,
generateRegistration?: (reg: AppServiceRegistration, cb: (finalReg: AppServiceRegistration) => void) => void;
bridgeConfig?: {
affectsRegistration?: boolean;
schema: string | Record<string, unknown>;
defaults: Record<string, unknown>;
};
registrationPath: string;
enableRegistration: boolean;
enableLocalpart: boolean;
port: number;
noUrl?: boolean;
}
interface CliArgs {
"generate-registration": boolean;
config: string;
url?: string;
localpart: string;
port: number;
file: string;
help: boolean;
}
export class Cli<ConfigType extends Record<string, unknown>> {
public static DEFAULT_PORT = 8090;
public static DEFAULT_WATCH_INTERVAL = 2500;
public static DEFAULT_FILENAME = "registration.yaml";
private bridgeConfig: ConfigType|null = null;
private args: CliArgs|null = null;
private opts: VettedCliOpts<ConfigType>;
/**
* @constructor
* @param opts CLI options
* @param opts.run The function called when you should run the bridge.
* @param opts.generateRegistration The function
* called when you should generate a registration.
* @param opts.bridgeConfig Bridge-specific config info. If null, no
* --config option will be present in the CLI. Default: null.
* @param opts.bridgeConfig.affectsRegistration True to make the
* --config option required when generating the registration. The parsed config
* can be accessed via <code>Cli.getConfig()</code>.
* @param opts.bridgeConfig.schema Path to a schema YAML file
* (string) or the parsed schema file (Object).
* @param opts.bridgeConfig.defaults The default options for the
* config file.
* @param opts.noUrl Don't ask user for appservice url when generating
* registration.
* @param opts.enableRegistration Enable '--generate-registration'.
* Default True.
* @param opts.registrationPath The path to write the registration
* file to. Users can overwrite this with -f.
* @param opts.enableLocalpart Enable '--localpart [-l]'. Default: false.
*/
constructor(opts: CliOpts<ConfigType>) {
if (!opts.run || typeof opts.run !== "function") {
throw new Error("Requires 'run' function.");
}
if (opts.enableRegistration && !opts.generateRegistration) {
throw new Error(
"Registration generation is enabled but no " +
"'generateRegistration' function has been provided"
);
}
this.opts = {
...opts,
enableRegistration: typeof opts.enableRegistration === 'boolean' ? opts.enableRegistration : true,
enableLocalpart: Boolean(opts.enableLocalpart),
registrationPath: opts.registrationPath || Cli.DEFAULT_FILENAME,
port: opts.port || Cli.DEFAULT_PORT,
};
}
/**
* Get the parsed arguments. Only set after run is called and arguments parsed.
* @return The parsed arguments
*/
public getArgs() {
return this.args;
}
/**
* Get the loaded and parsed bridge config. Only set after run() has been called.
* @return The config
*/
public getConfig() {
return this.bridgeConfig;
}
/**
* Get the path to the registration file. This may be different to the one supplied
* in the constructor if the user passed a -f flag.
* @return The path to the registration file.
*/
public getRegistrationFilePath() {
return this.opts.registrationPath;
}
/**
* Run the app from the command line. Will parse sys args.
*/
public run(args?: CliArgs) {
this.args = args || nopt({
"generate-registration": Boolean,
"config": path,
"url": String,
"localpart": String,
"port": Number,
"file": path,
"help": Boolean
}, {
"c": "--config",
"u": "--url",
"r": "--generate-registration",
"l": "--localpart",
"p": "--port",
"f": "--file",
"h": "--help"
// We know the typings will be correct.
}) as unknown as CliArgs;
if (this.args.file) {
this.opts.registrationPath = this.args.file;
}
if (this.opts.enableRegistration && this.args["generate-registration"]) {
if (!this.args.url && !this.opts.noUrl) {
this.printHelp();
console.log("Missing --url [-u]");
process.exit(1);
}
else if (this.args.url && this.opts.noUrl) {
this.printHelp();
console.log("--url [-u] is not valid option for this bridge.");
process.exit(1);
}
if (this.args.port) {
this.printHelp();
console.log("--port [-p] is not valid when generating a registration file.");
process.exit(1);
}
if (this.opts.bridgeConfig && this.opts.bridgeConfig.affectsRegistration) {
if (!this.args.config) {
this.printHelp();
console.log("Missing --config [-c]");
process.exit(1);
}
this.assignConfigFile(this.args.config);
}
this.generateRegistration(this.args.url, this.args.localpart);
return;
}
if (this.args.help || (this.opts.bridgeConfig && !this.args.config)) {
this.printHelp();
process.exit(0);
return;
}
if (this.args.localpart) {
this.printHelp();
console.log(
"--localpart [-l] can only be provided when generating a registration."
);
process.exit(1);
return;
}
if (this.args.port) {
this.opts.port = this.args.port;
}
this.assignConfigFile(this.args.config);
this.startWithConfig(this.bridgeConfig, this.args.config);
}
private assignConfigFile(configFilePath: string) {
const configFile = (this.opts.bridgeConfig && configFilePath) ? configFilePath : undefined;
if (!configFile) {
return;
}
const config = this.loadConfig(configFile);
this.bridgeConfig = config;
}
private loadConfig(filename: string): ConfigType {
log.info("Loading config file", filename);
const cfg = this.loadYaml(filename);
if (!cfg || typeof cfg === "string") {
throw Error("Config file " + filename + " isn't valid YAML.");
}
if (!this.opts.bridgeConfig?.schema) {
return cfg as ConfigType;
}
let validator: ConfigValidator;
if (typeof this.opts.bridgeConfig.schema === "string") {
validator = ConfigValidator.fromSchemaFile(this.opts.bridgeConfig.schema);
}
else {
validator = new ConfigValidator(this.opts.bridgeConfig.schema);
}
return validator.validate(cfg, this.opts.bridgeConfig.defaults) as ConfigType;
}
private generateRegistration(appServiceUrl: string | undefined, localpart: string) {
let reg = new AppServiceRegistration(appServiceUrl || "");
if (localpart) {
reg.setSenderLocalpart(localpart);
}
if (!this.opts.generateRegistration) {
throw Error('No generateRegistraton function provided');
}
this.opts.generateRegistration.bind(this)(reg, (completeReg) => {
reg = completeReg;
reg.outputAsYaml(this.opts.registrationPath);
log.info("Output registration to: " + this.opts.registrationPath);
process.exit(0);
});
}
private startWithConfig(config: ConfigType|null, configFilename: string) {
if (this.opts.onConfigChanged && this.opts.bridgeConfig) {
log.info("Will listen for SIGHUP");
process.on("SIGHUP",
() => {
log.info("Got SIGHUP, reloading config file");
try {
const newConfig = this.loadConfig(configFilename);
if (this.opts.onConfigChanged) {
this.opts.onConfigChanged(newConfig);
}
}
catch (ex) {
log.warn("Failed to reload config file:", ex);
}
});
}
const yamlObj = this.loadYaml(this.opts.registrationPath);
if (typeof yamlObj !== "object") {
throw Error('Registration file did not parse to an object');
}
this.opts.run(
this.opts.port, config,
AppServiceRegistration.fromObject(yamlObj as AppServiceOutput)
);
}
private loadYaml(fpath: string) {
return yaml.safeLoad(fs.readFileSync(fpath, 'utf8'));
}
private printHelp() {
const help: {[flag: string]: string} = {
"--help -h": "Display this help message",
"--file -f": "The registration file to load or save to."
};
const appPart = (process.argv[0] === "node" ?
// node file/path
(process.argv[0] + " " + path.relative(process.cwd(), process.argv[1])) :
// app-name
process.argv[0]
);
const usages = [];
if (this.opts.enableRegistration) {
help["--generate-registration -r"] = "Create a registration YAML file " +
"for this application service";
if (!this.opts.noUrl) {
help["--url -u"] = "Registration Option. Required if -r is set. The " +
"URL where the application service is listening for HS requests";
}
if (this.opts.enableLocalpart) {
help["--localpart -l"] = "Registration Option. Valid if -r is set. " +
"The user_id localpart to assign to the AS.";
}
let regUsage = "-r [-f /path/to/save/registration.yaml] " +
"-u 'http://localhost:6789'";
if (this.opts.bridgeConfig && this.opts.bridgeConfig.affectsRegistration) {
regUsage += " -c CONFIG_FILE";
}
if (this.opts.enableLocalpart) {
regUsage += " [-l my-app-service]";
}
usages.push(regUsage);
}
if (this.opts.bridgeConfig) {
help["--config -c"] = "The config file to load";
usages.push("-c CONFIG_FILE [-f /path/to/load/registration.yaml] [-p NUMBER]");
}
else {
usages.push("[-f /path/to/load/registration.yaml] [-p NUMBER]");
}
help["--port -p"] = "The port to listen on for HS requests";
console.log("Usage:\n");
console.log("Generating an application service registration file:");
console.log("%s %s\n", appPart, usages[0]);
console.log("Running an application service with an existing registration file:");
console.log("%s %s", appPart, usages[1]);
console.log("\nOptions:");
Object.keys(help).forEach(function(k) {
console.log(" %s", k);
console.log(" %s", help[k]);
});
}
}