/
context.ts
910 lines (823 loc) · 20.3 KB
/
context.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
import { WorkerLogLevel } from "@webda/workout";
import acceptLanguage from "accept-language";
import { EventEmitter } from "events";
import * as http from "http";
import sanitize from "sanitize-html";
import { Readable, Writable } from "stream";
import { WritableStreamBuffer } from "stream-buffers";
import { Core } from "../core";
import { NotEnumerable } from "../models/coremodel";
import { User } from "../models/user";
import { Service } from "../services/service";
import { Session, SessionManager } from "../utils/session";
import { HttpContext } from "./httpcontext";
import { JSONUtils } from "./serializers";
/**
* @category CoreFeatures
*/
class Cookie {
name: string;
value: string;
options: any;
}
/**
* Data provided by the context
*/
export interface ContextProviderInfo {
/**
* Stream to write to
*/
stream?: Writable;
/**
* If this is http context
*/
http?: HttpContext;
/**
* true if this is a global context
*/
global?: boolean;
/**
* Can contain any type of information
*/
[key: string]: any;
}
/**
* @category CoreFeatures
*/
export interface ContextProvider {
/**
* Info can contain any type of information
* @param info
*/
getContext(info: ContextProviderInfo): OperationContext;
}
/**
* OperationContext is used when call to an operation
*
* @param T type of input for this context
* @param U type of output for this context
*/
export class OperationContext<T = any, U = any> extends EventEmitter {
protected static __globalContext: OperationContext;
/**
* Contain emitting Core
*/
@NotEnumerable
protected _webda: Core;
/**
* Session
*/
protected session: Session;
/**
* Allow extensions
*/
protected extensions: { [key: string]: any };
/**
* Contain the sanitized request body if computed
*/
protected _sanitized: any;
/**
* Output
*/
protected _body: string;
/**
* Loaded user if exist
*/
private user: User;
/**
* Contain all registered promises to this context
*/
@NotEnumerable
_promises: Promise<any>[];
/**
* @ignore
* Used by Webda framework to set the body, session and output stream if known
*/
constructor(webda: Core, stream: Writable = undefined) {
super();
this.extensions = {};
this._webda = webda;
this._promises = [];
this._body = undefined;
this._stream = stream;
if (stream === undefined) {
this.createStream();
}
}
/**
* Output stream
*/
@NotEnumerable
_stream: Writable;
/**
* Get an extension of the context
* @param name of the extension
* @returns extension object
*/
public getExtension<K = any>(name: string): K {
return <K>this.extensions[name];
}
/**
* For easier compatibility with WebContext
* On OperationContext this call is simply ignored
*/
setHeader(_name: string, _value: string) {
// Do nothing
}
/**
* For easier compatibility with WebContext
* On OperationContext this call is simply ignored
*/
writeHead(_code: number, _headers: any) {
// Do nothing
}
/**
*
* @param name to add
* @param extension object to store
*/
public setExtension(name: string, extension: any): this {
this.extensions[name] = extension;
return this;
}
/**
* Return the webda
*/
getWebda() {
return this._webda;
}
/**
* Register a promise with the context
* @param promise
*/
addAsyncRequest(promise) {
this._promises.push(promise);
}
/**
* Get output as string, if a OutputStream is provided it will returned null
* @returns
*/
getOutput(): string {
if (this._stream instanceof WritableStreamBuffer && (<WritableStreamBuffer>this._stream).size()) {
return (<WritableStreamBuffer>this._stream).getContents().toString();
}
return this._body;
}
/**
* Get current http context
*/
public getHttpContext(): HttpContext | undefined {
return this.getExtension<HttpContext>("http");
}
/**
* Ensure the whole execution is finished
*/
async end() {
this.emit("end");
await Promise.all(this._promises);
this.emit("close");
}
async getInput(
sanitizedOptions: sanitize.IOptions & { defaultValue?: any; raw?: boolean | string[] } = {
allowedTags: [],
allowedAttributes: {}
}
): Promise<T> {
if (this._sanitized && !sanitizedOptions.raw) {
return this._sanitized;
}
let recursiveSanitize = (obj, options = undefined, path: string = "") => {
if (typeof obj === "string") {
return sanitize(obj, options);
}
if (obj !== null && typeof obj === "object") {
Object.keys(obj).forEach(key => {
obj[key] =
Array.isArray(sanitizedOptions.raw) && sanitizedOptions.raw.includes(path + key)
? obj[key]
: recursiveSanitize(obj[key], options, path + key + ".");
});
}
return obj;
};
try {
let data = await this.getRawInputAsString(
this.getWebda().getGlobalParams().requestLimit,
this.getWebda().getGlobalParams().requestTimeout
);
if (sanitizedOptions.raw === true) {
return JSON.parse(data || sanitizedOptions.defaultValue);
}
if (!data || data.length === 0) {
this._sanitized = sanitizedOptions.defaultValue;
return this._sanitized;
}
this._sanitized = recursiveSanitize(JSON.parse(data), sanitizedOptions);
} catch (err) {
this.log("ERROR", err, `Body: '${await this.getRawInputAsString()}'`);
this._sanitized = sanitizedOptions.defaultValue;
}
return this._sanitized;
}
/**
* By default empty
* @returns
*/
async getRawInputAsString(
limit: number = 1024 * 1024 * 10,
timeout: number = 60000,
encoding?: BufferEncoding
): Promise<string> {
return (await this.getRawInput(limit, timeout)).toString(encoding);
}
/**
* @override
*/
async getRawInput(_limit: number = 1024 * 1024 * 10, _timeout: number = 60000): Promise<Buffer> {
return Buffer.from("");
}
/**
* @override
*/
getRawStream(): Readable {
return undefined;
}
/**
* Get the HTTP stream to output raw data
* @returns {*}
*/
getOutputStream() {
return this._stream;
}
/**
* Get linked session
* @returns
*/
public getSession<K = Session>(): K {
return <K>(<unknown>this.session);
}
/**
* Remove sanitized body
*/
public reinit() {
this._sanitized = undefined;
if (!this._stream || this._stream instanceof WritableStreamBuffer) {
this.createStream();
}
}
/**
* Create a buffer stream
*/
createStream() {
this._stream = new WritableStreamBuffer({
initialSize: 100 * 1024,
incrementAmount: 100 * 1024
});
}
/**
* Proxy for simplification
* @param level
* @param args
*/
log(level: WorkerLogLevel, ...args: any[]) {
this._webda.log(level, ...args);
}
/**
* Create a new session
* @returns
*/
async newSession() {
this.session = await this._webda.getService<SessionManager>("SessionManager").newSession(this);
return this.session;
}
/**
* Remove everything that was about to be sent
*/
public resetResponse() {
this._body = undefined;
if (this._stream instanceof WritableStreamBuffer) {
this.createStream();
}
}
/**
* Write data to the client
*
* @param output If it is an object it will be serialized with toPublicJSON, if it is a String it will be appended to the result, if it is a buffer it will replace the result
* @param ...args any arguments to pass to the toPublicJSON method
*/
public write(output: U, _encoding?: string, _cb?: (error: Error) => void): boolean {
if (!output) {
return false;
}
if (typeof output === "object" && !(output instanceof Buffer)) {
this._body = JSONUtils.stringify(output, undefined, 0, true);
} else if (typeof output == "string") {
if (this._body == undefined) {
this._body = "";
}
this._body += output;
} else {
this._body = output.toString();
}
return true;
}
async init(): Promise<this> {
return this;
}
/**
* Get the current user from session
*/
async getCurrentUser<K extends User>(refresh: boolean = false): Promise<K> {
if (!this.getCurrentUserId()) {
return undefined;
}
// Caching the answer
if (!this.user || refresh) {
this.user = <User>await this._webda.getApplication().getModel("User").ref(this.getCurrentUserId()).get(this);
}
return <K>this.user;
}
/**
* Get the current user id from session
*/
getCurrentUserId() {
return undefined;
}
/**
* Global context is the default Context
*
* Whenever a request is internal to the system
* or not linked to a user request
* @returns
*/
isGlobal() {
return false;
}
}
export class GlobalContext extends OperationContext {
session: Session = new Session();
constructor(webda: Core) {
super(webda);
this.session.login("system", "system");
// Disable logout
this.session.logout = () => {};
}
/**
* @override
*/
isGlobal() {
return true;
}
}
/**
* Simple Operation Context with custom input
*/
export class SimpleOperationContext extends OperationContext {
constructor(webda: Core) {
super(webda);
}
input: Buffer;
/**
* Create another context from an existing one
* @param context
* @returns
*/
static async fromContext(context: OperationContext): Promise<SimpleOperationContext> {
const ctx = new SimpleOperationContext(context.getWebda());
ctx.setSession(context.getSession());
ctx.setInput(Buffer.from(JSONUtils.stringify(await context.getInput())));
return ctx;
}
/**
* Set the input
*/
setInput(input: Buffer): this {
this.input = input;
return this;
}
/**
* Set the session
* @param session
* @returns
*/
setSession(session: Session): this {
this.session = session;
return this;
}
/**
* @override
*/
async getRawInput(limit: number = 1024 * 1024 * 10, _timeout: number = 60000): Promise<Buffer> {
return this.input.slice(0, limit);
}
}
/**
* This represent in fact a WebContext
* In 3.0 an abstract version of Context will replace this (closer to OperationContext)
* @category CoreFeatures
*
*/
export class WebContext<T = any, U = any> extends OperationContext<T, U> {
/**
* Contains the response headers
*/
protected _outputHeaders: http.OutgoingHttpHeaders;
/**
* Current status code
*/
statusCode: number;
/**
* Cookies to send back
*/
_cookie: Map<string, Cookie>;
/**
*
*/
headers: Map<string, string>;
_route: any;
_ended: Promise<any> = undefined;
_executor: Service<any>;
/**
* If headers were flushed
*/
protected headersFlushed: boolean;
protected parameters: any = undefined;
protected _pathParams: any = {};
protected _serviceParams: any = {};
private _init: Promise<this>;
/**
* Set current http context
* @param httpContext current http context
*/
public setHttpContext(httpContext: HttpContext) {
this.extensions["http"] = httpContext;
this.reinit();
}
/**
* @override
*/
async getRawInputAsString(
limit: number = 1024 * 1024 * 10,
timeout: number = 60000,
encoding?: string
): Promise<string> {
return this.getHttpContext().getRawBodyAsString(limit, timeout, encoding);
}
/**
* @override
*/
async getRawInput(limit: number = 1024 * 1024 * 10, timeout: number = 60000) {
return this.getHttpContext().getRawBody(limit, timeout);
}
/**
* @override
*/
getRawStream(): Readable {
return this.getHttpContext().getRawStream();
}
/**
* Get output headers
*/
public getResponseHeaders(): any {
return this._outputHeaders;
}
public getRequestParameters() {
return this.parameters;
}
public parameter(name: string) {
return this.getParameters()[name];
}
public getParameters() {
return this.parameters;
}
private processParameters() {
this.parameters = Object.assign({}, this._serviceParams);
this.parameters = Object.assign(this.parameters, this._pathParams);
}
public getServiceParameters() {
return this._serviceParams;
}
public getPathParameters() {
return this._pathParams;
}
public setServiceParameters(params: any) {
this._serviceParams = params;
this.processParameters();
}
public setPathParameters(params: any) {
this._pathParams = params;
this.processParameters();
}
/**
* Remove everything that was about to be sent
*/
public resetResponse() {
this._outputHeaders = {};
super.resetResponse();
}
/**
* Write data to the client
*
* @param output If it is an object it will be serializeb with toPublicJSON, if it is a String it will be appended to the result, if it is a buffer it will replace the result
* @param ...args any arguments to pass to the toPublicJSON method
*/
// @ts-ignore
public write(output: U, encoding?: string, cb?: (error: Error) => void): boolean {
if (this.statusCode === 204) {
this.statusCode = 200;
}
if (typeof output === "object" && !(output instanceof Buffer) && !this.hasFlushedHeaders()) {
this.setHeader("Content-type", "application/json");
}
return super.write(output, encoding, cb);
}
/**
* Set a header value
*
* @param {String} header name
* @param {String} value
*/
public setHeader(header, value) {
if (this.headersFlushed) {
throw new Error("Headers have been sent already");
}
if (value) {
this._outputHeaders[header] = value;
} else if (this._outputHeaders[header]) {
delete this._outputHeaders[header];
}
}
/**
* Write the http return code and some headers
* Those headers are not flushed yet so can still be overwritten
*
* @param {Number} statusCode to return to the client
* @param {Object} headers to add to the response
*/
writeHead(statusCode: number, headers: http.OutgoingHttpHeaders = undefined): this {
this._outputHeaders = { ...this._outputHeaders, ...headers };
// Ensure undefined values are removed
Object.keys(this._outputHeaders)
.filter(h => this._outputHeaders[h] === undefined)
.forEach(h => delete this._outputHeaders[h]);
if (statusCode !== undefined) {
this.statusCode = statusCode;
}
return this;
}
/**
*
* @returns
*/
getResponseCode() {
return this.statusCode || 200;
}
/**
* Redirect to another url
* @param url
*/
redirect(url: string) {
this.writeHead(302, { Location: url });
}
/**
* For compatibility reason
*/
cookie(param, value, options = undefined) {
/** @ignore */
if (this._cookie === undefined) {
this._cookie = new Map();
}
this._cookie[param] = { name: param, value, options };
}
getResponseCookies(): Map<string, Cookie> {
return this._cookie;
}
isEnded() {
return this._ended;
}
/******************************
*
* Express Compatibiliy method
*
******************************/
/**
* Express response allow statusCode to be defined this way
* @param code to return
*/
public status(code: number): this {
this.statusCode = code;
return this;
}
/**
* Express response allow answer to be sent this way
* @param code to return
*/
public json(obj: any): this {
this.write(obj);
return this;
}
/**
* Return the response size
* @returns
*/
getResponseSize(): number | undefined {
return this._body ? Buffer.byteLength(this._body, "utf8") : undefined;
}
/**
* Flush the request
*
* @emits 'finish' event
* @throws Error if the request was already ended
*/
async end() {
/** @ignore */
if (this._ended) {
return this._ended;
}
this._ended = (async () => {
this.emit("end");
if (this.getExtension("http")) {
await this._webda.getService<SessionManager>("SessionManager").save(this, this.session);
}
await Promise.all(this._promises);
if (this._stream instanceof WritableStreamBuffer && (<WritableStreamBuffer>this._stream).size()) {
this._body = (<WritableStreamBuffer>this._stream).getContents().toString();
this.statusCode = this.statusCode < 300 ? 200 : this.statusCode;
}
if (!this.headersFlushed) {
this._webda.flushHeaders(this);
}
this._webda.flush(this);
this.emit("close");
})();
return this._ended;
}
/**
* Alias to keep compatibility with WebContext
* @param sanitizedOptions
* @returns
*/
async getRequestBody(
sanitizedOptions: any = {
allowedTags: [],
allowedAttributes: {}
}
): Promise<T> {
return this.getInput(sanitizedOptions);
}
/**
* Get request body
* @returns
*/
getResponseBody() {
if (!this._body && this._stream instanceof WritableStreamBuffer) {
return (<WritableStreamBuffer>this._stream).getContents();
}
return this._body;
}
/**
* Retrieve a http.IncomingMessage valid from Context
*
* Need more testing
* @returns
*/
getRequest(): http.IncomingMessage {
const stream = Readable.from([JSON.stringify(this.getRequestBody())]);
return <http.IncomingMessage>(<unknown>{
httpVersionMajor: 1,
httpVersionMinor: 0,
headers: this.headers,
httpVersion: "1.0",
method: this.getHttpContext().getMethod(),
rawHeaders: [], // TODO Regenerate headers based on the map
rawTrailers: [],
setTimeout: (msec, callback) => {
setTimeout(callback, msec);
},
socket: undefined,
statusCode: 200,
trailers: {},
url: this.getHttpContext().getUrl(),
connection: undefined,
...stream
});
}
/**
* Get a service from webda
*
* @see Webda
* @param {String} name of the service
*/
getService<K extends Service>(name): K {
return this._webda.getService<K>(name);
}
/**
* Get the HTTP stream to output raw data
* @returns {*}
*/
getStream() {
return this.getOutputStream();
}
/**
* Get the current user id from session
*/
getCurrentUserId() {
if (this.session) {
return this.session.userId;
}
return undefined;
}
/**
* Return the service handling the request
*/
getExecutor(): Service<any> {
return this._executor;
}
/**
* Execute the target route
*/
async execute() {
return this._route._method(this);
}
/**
* Get the request locale if found
*/
getLocale() {
let locales = this._webda.getLocales();
acceptLanguage.languages(locales);
let header = this.getHttpContext().getUniqueHeader("accept-language");
if (header) {
return acceptLanguage.get(header);
}
return locales[0];
}
/**
* @ignore
* Used by Webda framework to set the current route
*/
setRoute(route) {
this._route = route;
this.parameters = { ...route.params, ...this.parameters };
}
getRoute() {
return this._route;
}
/**
* @param executor {object} Set the current executor for this context
*/
setExecutor(executor) {
this._executor = executor;
}
/**
* @ignore
* Used for compatibility with express module
*/
logIn() {
// Empty for compatibility
}
/**
* Return true if Headers got flushed already
* @returns
*/
hasFlushedHeaders() {
return this.headersFlushed;
}
/**
* Set flushed header status
* @param status
*/
setFlushedHeaders(status: boolean = true) {
this.headersFlushed = status;
}
/**
* @ignore
* Used by Webda framework to set the body, session and output stream if known
*/
constructor(webda: Core, httpContext: HttpContext, stream: Writable = undefined) {
super(webda, stream);
this.setHttpContext(httpContext);
this._outputHeaders = {};
this.headersFlushed = false;
this.statusCode = 204;
this.parameters = {};
this.headers = new Map();
this.processParameters();
}
async init(force: boolean = false): Promise<this> {
if (this._init && !force) {
return this._init;
}
this._stream.on("pipe", () => {
this._webda.flushHeaders(this);
this.headersFlushed = true;
});
if (this.getExtension("http")) {
this.session = (await this._webda.getService<SessionManager>("SessionManager").load(this)).getProxy();
}
this._init = super.init();
return this._init;
}
emitError(err) {
this.emit("error", err);
}
}