-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathlib.ts
650 lines (581 loc) · 19.9 KB
/
lib.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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import { NextFunction, Request, Response } from "express"
import FS from "fs/promises"
import Path from "path"
import jwt, { Algorithm } from "jsonwebtoken"
import moment from "moment"
import base64url from "base64-url"
import request from "request"
import { format } from "util"
import FHIR, { OperationOutcome } from "fhir/r4"
import { Dirent } from "fs"
import config from "./config"
import getDB from "./db"
import { JSONValue } from "./types"
import { ScopeList } from "./scope"
const RE_GT = />/g;
const RE_LT = /</g;
const RE_AMP = /&/g;
const RE_QUOT = /"/g;
const RE_FALSE = /^(0|no|false|off|null|undefined|NaN|)$/i;
export function bool(x: any): boolean {
return !RE_FALSE.test(String(x).trim());
}
export function htmlEncode(html: string): string {
return String(html)
.trim()
.replace(RE_AMP , "&")
.replace(RE_LT , "<")
.replace(RE_GT , ">")
.replace(RE_QUOT, """);
}
export function operationOutcome(
res: Response,
message: string,
options: {
httpCode?: number,
severity?: "fatal" | "error" | "warning" | "information",
issueCode?: string
} = {})
{
return res.status(options.httpCode || 500).json(
createOperationOutcome(message, options)
);
}
export function createOperationOutcome(message: string, {
issueCode = "processing", // http://hl7.org/fhir/valueset-issue-type.html
severity = "error" // fatal | error | warning | information
}: {
issueCode?: string
severity?: "fatal" | "error" | "warning" | "information"
} = {}): OperationOutcome
{
return {
"resourceType": "OperationOutcome",
"text": {
"status": "generated",
"div": `<div xmlns="http://www.w3.org/1999/xhtml">` +
`<h1>Operation Outcome</h1><table border="0"><tr>` +
`<td style="font-weight:bold;">${severity}</td><td>[]</td>` +
`<td><pre>${htmlEncode(message)}</pre></td></tr></table></div>`
},
"issue": [
{
"severity" : severity,
"code" : issueCode,
"diagnostics": message
}
]
};
}
export function makeArray(x: any[]): typeof x;
export function makeArray(x: string): any[];
export function makeArray(x: any): [typeof x];
export function makeArray(x: any): any[] {
if (Array.isArray(x)) {
return x;
}
if (typeof x == "string") {
return x.trim().split(/\s*,\s*/);
}
return [x];
}
/**
* This will parse and return the JSON contained within a base64-encoded string
* @param {String} inputString Base64url-encoded string
* @returns {Object}
*/
export function decodeArgs(inputString: string): Record<string, any> {
let args: any = {};
try {
args = JSON.parse(base64url.decode(inputString));
}
catch(ex) {
args = null;
}
finally {
if (!args || typeof args !== "object") {
args = {};
}
}
return args;
}
/**
* This will parse and return the JSON contained within a base64-encoded route
* fragment. Given a request object and a paramName, this function will look for
* route parameter with that name and parse it to JSON and return the result
* object. If anything goes wrong, an empty object will be returned.
*/
export function getRequestedParams(req: Request, paramName = "sim") {
return decodeArgs(req.params[paramName]);
}
/**
* Parses the given json string into a JSON object. Internally it uses the
* JSON.parse() method but adds three things to it:
* 1. Returns a promise
* 2. Ensures async result
* 3. Catches errors and rejects the promise
*/
export async function parseJSON<T=JSONValue>(json: string): Promise<T>
{
return new Promise((resolve, reject) => {
setImmediate(() => {
try {
var out = JSON.parse(json || "null");
}
catch (error) {
return reject(error);
}
resolve(out as T);
});
});
}
/**
* Serializes the given object into json if possible. Internally it uses the
* JSON.stringify() method but adds three things to it:
* 1. Returns a promise
* 2. Ensures async result
* 3. Catches errors and rejects the promise
*/
export async function stringifyJSON(json: JSONValue, indentation?: string | number): Promise<string>
{
return new Promise((resolve, reject) => {
setImmediate(() => {
try {
var out = JSON.stringify(json, null, indentation);
}
catch (error) {
return reject(error);
}
resolve(out);
});
});
}
/**
* Read a file and parse it as JSON.
*/
export async function readJSON<T=JSONValue>(path: string): Promise<T>
{
return FS.readFile(path, "utf8").then(json => parseJSON<T>(json));
}
export async function forEachFile(options: {
dir : string,
limit ?: number,
filter?: (path: string, dirent: Dirent) => boolean | undefined
}, cb: (path: string, dirent: Dirent) => any) {
try {
const dir = await FS.opendir(options.dir);
let i = 0;
for await (const dirent of dir) {
if (options.limit && ++i > options.limit) {
continue;
}
if (dirent.isFile()) {
const path = Path.join(options.dir, dirent.name);
if (options.filter && !options.filter(path, dirent)) {
continue;
}
await cb(path, dirent);
}
}
} catch (err) {
console.error(err);
}
}
/**
* Walks thru an object (ar array) and returns the value found at the
* provided path. This function is very simple so it intentionally does not
* support any argument polymorphism, meaning that the path can only be a
* dot-separated string. If the path is invalid returns undefined.
* @param obj The object (or Array) to walk through
* @param path The path (eg. "a.b.4.c")
* @returns Whatever is found in the path or undefined
*/
export function getPath(obj: any, path = ""): any
{
return path.split(".").reduce((out, key) => out ? out[key] : undefined, obj)
}
// require a valid auth token if there is an auth token
export function checkAuth(req: Request, res: Response, next: NextFunction)
{
if (req.headers.authorization) {
try {
var token = jwt.verify(
req.headers.authorization.split(" ")[1],
config.jwtSecret,
{
algorithms: config.supportedSigningAlgorithms as Algorithm[]
}
);
} catch (e) {
return operationOutcome(
res,
"Invalid token " + (e as Error).message,
{ httpCode: 401 }
);
}
// @ts-ignore
let error = token.err || token.sim_error || token.auth_error;
if (error) {
return res.status(401).send(error);
}
}
else {
if ((req as any).sim && (req as any).sim.secure) {
return operationOutcome(
res,
"Authentication is required",
{ httpCode: 401 }
)
}
}
next();
}
export function getErrorText(name: keyof typeof config.errors, ...rest: any[])
{
return format(config.errors[name], ...rest);
}
export function replyWithError(res: Response, name: keyof typeof config.errors, code = 500, ...params: any[])
{
return res.status(code).send(getErrorText(name, ...params));
}
export function replyWithOAuthError(res: Response, name: keyof typeof config.oauthErrors, options: {
code?: number
message?: string
params?: any[]
} = {})
{
const code = options.code || 400;
const params = options.params || [];
const defaultDescription = config.oauthErrors[name];
if (!defaultDescription) {
return res.status(500).send(`"${name}" is not a valid oAuth error name.`);
}
let message = defaultDescription;
if (options.message) {
// @ts-ignore
if (config.errors[options.message]) {
// @ts-ignore
message = getErrorText(options.message, ...params);
}
else {
message = options.message;
}
}
return res.status(code).json({
error: name,
error_description: message
});
}
export function buildUrlPath(...segments: string[])
{
return segments.map(
s => String(s)
.replace(/^\//, "")
.replace(/\/$/, "")
).join("\/");
}
export function parseToken(t: string)
{
if (typeof t != "string") {
throw new Error("The token must be a string");
}
let token = t.split(".");
if (token.length != 3) {
throw new Error("Invalid token structure. Must contain 3 parts.");
}
// Token header ------------------------------------------------------------
try {
var header = JSON.parse(Buffer.from(token[0], "base64").toString("utf8"));
} catch (ex) {
throw new Error("Invalid token structure. Cannot parse the token header.");
}
// alg (required) ----------------------------------------------------------
// algorithm used for signing the authentication JWT (e.g., `RS384`, `EC384`).
if (!header.alg) {
throw new Error("Invalid JWT token header. Missing 'alg' property.");
}
// kid (required) ----------------------------------------------------------
// The identifier of the key-pair used to sign this JWT. This identifier
// MUST be unique within the backend service's JWK Set.
if (!header.kid) {
throw new Error("Invalid JWT token header. Missing 'kid' property.");
}
// typ (required) ----------------------------------------------------------
// Fixed value: JWT.
if (!header.typ) {
throw new Error("Invalid JWT token header. Missing 'typ' property.");
}
if (header.typ != "JWT") {
throw new Error("Invalid JWT token header.The 'typ' property must equal 'JWT'.");
}
// Token body --------------------------------------------------------------
try {
var body = JSON.parse(Buffer.from(token[1], "base64").toString("utf8"));
} catch (ex) {
throw new Error("Invalid token structure. Cannot parse the token body.");
}
return body;
}
export function getGrantedScopes(req: Request): ScopeList {
try {
const accessToken = jwt.verify((req.headers.authorization || "").replace(/^bearer\s+/i, ""), config.jwtSecret, {
algorithms: config.supportedSigningAlgorithms as Algorithm[]
})
// @ts-ignore jwt.verify returns string | object but for JWK we know it is an object
return ScopeList.fromString(accessToken.scope)
} catch {
return new ScopeList() // no scopes granted
}
}
export function hasAccessToResourceType(
grantedScopes: {system: string, resource: string, action: string}[],
resourceType: string,
access = "read"
): boolean {
return grantedScopes.some(scope => (
(scope.system === "*" || scope.system === "system") &&
(scope.resource === "*" || scope.resource === resourceType) &&
(scope.action === "*" || scope.action === access)
))
}
export function wait(ms = 0) {
return new Promise(resolve => {
setTimeout(resolve, uInt(ms));
});
}
export function uInt(x: any, defaultValue = 0): number {
x = parseInt(x + "", 10);
if (isNaN(x) || !isFinite(x) || x < 0) {
x = uInt(defaultValue, 0);
}
return x;
}
/**
* @param dateTime Either a date/dateTime string or a timestamp number
* @see https://momentjs.com/docs/#/parsing/ for the possible date-time
* formats.
*
* A dateTime string can be in any of the following formats in SQLite:
* YYYY-MM-DD
* YYYY-MM-DD HH:MM
* YYYY-MM-DD HH:MM:SS
* YYYY-MM-DD HH:MM:SS.SSS
* YYYY-MM-DDTHH:MM
* YYYY-MM-DDTHH:MM:SS
* YYYY-MM-DDTHH:MM:SS.SSS
* now
* DDDDDDDDDD
*/
export function fhirDateTime(dateTime: string | number, noFuture?: boolean) {
dateTime = String(dateTime || "").trim();
// YYYY (FHIR)
if (/^\d{4}$/.test(dateTime)) dateTime += "-01-01";
// YYYY-MM (FHIR)
else if (/^\d{4}-\d{2}$/.test(dateTime)) dateTime += "-01";
// TIMESTAMP
else if (/^\d{9,}(\.\d+)?/.test(dateTime)) dateTime = +dateTime;
// Parse
let t = moment(dateTime);
if (!t.isValid()) {
throw new Error(`Invalid dateTime "${dateTime}"`);
}
if (noFuture && t.isAfter(moment())) {
throw new Error(`Invalid dateTime "${dateTime}. Future dates are not accepted!"`);
}
return t.format("YYYY-MM-DD HH:mm:ss");
}
export function fetchJwks(url: string): Promise<any> {
return new Promise((resolve, reject) => {
request({ url, json: true }, (error, resp, body) => {
if (error) {
return reject(error);
}
if (resp.statusCode >= 400) {
return reject(new Error(
`Requesting "${url}" returned ${resp.statusCode} status code`
));
}
// if (resp.headers["content-type"].indexOf("json") == -1) {
// return reject(new Error(
// `Requesting "${url}" did not return a JSON content-type`
// ));
// }
resolve(body);
});
});
}
/**
* Simple Express middleware that will require the request to have "accept"
* header set to "application/fhir+ndjson".
*/
export function requireFhirJsonAcceptHeader(req: Request, res: Response, next: NextFunction) {
if (req.headers.accept != "application/fhir+json") {
return outcomes.requireAcceptFhirJson(res);
}
next();
}
/**
* Simple Express middleware that will require the request to have "prefer"
* header set to "respond-async".
*/
export function requireRespondAsyncHeader(req: Request, res: Response, next: NextFunction) {
const tokens = String(req.headers.prefer || "").trim().split(/\s*[,;]\s*/);
if (!tokens.includes("respond-async")) {
return outcomes.requirePreferAsync(res);
}
next();
}
/**
* Simple Express middleware that will require the request to have "Content-Type"
* header set to "application/json".
*/
export function requireJsonContentTypeHeader(req: Request, res: Response, next: NextFunction) {
if (!req.is("application/json")) {
return outcomes.requireJsonContentType(res);
}
next();
}
/**
* Get a list of all the resource types present in the database
*/
export function getAvailableResourceTypes(fhirVersion: number): Promise<string[]> {
const DB = getDB(fhirVersion);
return DB.promise("all", 'SELECT DISTINCT "fhir_type" FROM "data"')
.then((rows: any[]) => rows.map(row => row.fhir_type));
}
export function tagResource(resource: Partial<FHIR.Resource>, code: string, system = "https://smarthealthit.org/tags")
{
if (!resource.meta) {
resource.meta = {};
}
if (!Array.isArray(resource.meta.tag)) {
resource.meta.tag = [];
}
const tag = resource.meta.tag.find(x => x.system === system);
if (tag) {
tag.code = code;
} else {
resource.meta.tag.push({ system, code });
}
}
/**
* Checks if the given scopes string is valid for use by backend services.
* This will only accept system scopes and will also reject empty scope.
* @param scopes The scopes to check
* @param [fhirVersion] The FHIR version that this scope should be
* validated against. If provided, the scope should match one of the resource
* types available in the database for that version (or *). Otherwise no
* check is performed.
* @returns The invalid scope or empty string on success
* @static
*/
export async function getInvalidSystemScopes(scopes: string, fhirVersion: number): Promise<string> {
scopes = String(scopes || "").trim();
if (!scopes) {
return config.errors.missing_scope;
}
const scopesArray = scopes.split(/\s+/);
// If no FHIR version is specified accept anything that looks like a
// resource
let availableResources = "[A-Z][A-Za-z0-9]+";
// Otherwise check the DB to see what types of resources we have
if (fhirVersion) {
availableResources = (await getAvailableResourceTypes(fhirVersion)).join("|");
}
const re = new RegExp("^system/(\\*|" + availableResources + ")(\\.(read|write|\\*))?$");
return scopesArray.find(s => !(re.test(s))) || "";
}
// Errors as operationOutcome responses
export const outcomes = {
fileExpired: (res: Response) => operationOutcome(
res,
"Access to the target resource is no longer available at the server " +
"and this condition is likely to be permanent because the file " +
"expired",
{ httpCode: 410 }
),
invalidAccept: (res: Response, accept: string) => operationOutcome(
res,
`Invalid Accept header "${accept}". Currently we only recognize ` +
`"application/fhir+ndjson" and "application/fhir+json"`,
{ httpCode: 400 }
),
invalidSinceParameter: (res: Response, value: any) => operationOutcome(
res,
`Invalid _since parameter "${value}". It must be valid FHIR instant and ` +
`cannot be a date in the future"`,
{ httpCode: 400 }
),
requireJsonContentType: (res: Response) => operationOutcome(
res,
"The Content-Type header must be application/json",
{ httpCode: 400 }
),
requireAcceptFhirJson: (res: Response) => operationOutcome(
res,
"The Accept header must be application/fhir+json",
{ httpCode: 400 }
),
requirePreferAsync: (res: Response) => operationOutcome(
res,
"The Prefer header must be respond-async",
{ httpCode: 400 }
),
fileGenerationFailed: (res: Response) => operationOutcome(
res,
getErrorText("file_generation_failed")
),
cancelAccepted: (res: Response) => operationOutcome(
res,
"The procedure was canceled",
{ severity: "information", httpCode: 202 /* Accepted */ }
),
cancelCompleted: (res: Response) => operationOutcome(
res,
"The export was already completed",
{ httpCode: 404 }
),
cancelNotFound: (res: Response) => operationOutcome(
res,
"Unknown procedure. Perhaps it is already completed and thus, it cannot be canceled",
{ httpCode: 404 /* Not Found */ }
),
importAccepted: (res: Response, location: string) => operationOutcome(
res,
`Your request has been accepted. You can check its status at "${location}"`,
{ httpCode: 202, severity: "information" }
),
exportAccepted: (res: Response, location: string) => operationOutcome(
res,
`Your request has been accepted. You can check its status at "${location}"`,
{ httpCode: 202, severity: "information" }
),
exportDeleted: (res: Response) => operationOutcome(
res,
"The exported resources have been deleted",
{ httpCode: 404 }
),
exportNotCompleted: (res: Response) => operationOutcome(
res,
"The export is not completed yet",
{ httpCode: 404 }
)
};
/**
* Make Promise abortable with the given signal.
*/
export function abortablePromise<T=any>(p: Promise<T>, signal: AbortSignal): Promise<T> {
if (signal.aborted) {
return Promise.reject(new AbortError("Already aborted"));
}
return new Promise((resolve, reject) => {
const abort = () => reject(new AbortError());
signal.addEventListener("abort", abort, { once: true });
return p.then(resolve).finally(() => signal.removeEventListener("abort", abort));
});
}
export class AbortError extends Error {
constructor(message = "Aborted") {
super(message)
}
}