@faasjs/http 0.0.2-beta.302 → 0.0.2-beta.320

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.es.js DELETED
@@ -1,539 +0,0 @@
1
- import { usePlugin } from '@faasjs/func';
2
- import { deepMerge } from '@faasjs/deep_merge';
3
- import { Logger } from '@faasjs/logger';
4
- import { randomBytes, pbkdf2Sync, createCipheriv, createHmac, createDecipheriv } from 'crypto';
5
- import { brotliCompressSync, gzipSync, deflateSync } from 'zlib';
6
-
7
- class Session {
8
- constructor(cookie, config) {
9
- this.cookie = cookie;
10
- this.config = Object.assign({
11
- key: 'key',
12
- secret: randomBytes(128).toString('hex'),
13
- salt: 'salt',
14
- signedSalt: 'signedSalt',
15
- keylen: 64,
16
- iterations: 100,
17
- digest: 'sha256',
18
- cipherName: 'aes-256-cbc'
19
- }, config);
20
- this.secret = pbkdf2Sync(this.config.secret, this.config.salt, this.config.iterations, this.config.keylen / 2, this.config.digest);
21
- this.signedSecret = pbkdf2Sync(this.config.secret, this.config.signedSalt, this.config.iterations, this.config.keylen, this.config.digest);
22
- this.content = Object.create(null);
23
- }
24
- invoke(cookie) {
25
- try {
26
- this.content = cookie ? this.decode(cookie) : Object.create(null);
27
- }
28
- catch (error) {
29
- console.error(error);
30
- this.content = Object.create(null);
31
- }
32
- this.changed = false;
33
- }
34
- encode(text) {
35
- if (typeof text !== 'string')
36
- text = JSON.stringify(text);
37
- const iv = randomBytes(16);
38
- const cipher = createCipheriv(this.config.cipherName, this.secret, iv);
39
- const encrypted = Buffer.concat([cipher.update(text), cipher.final()]).toString('base64');
40
- const main = Buffer.from([encrypted, iv.toString('base64')].join('--')).toString('base64');
41
- const hmac = createHmac(this.config.digest, this.signedSecret);
42
- hmac.update(main);
43
- const digest = hmac.digest('hex');
44
- return main + '--' + digest;
45
- }
46
- decode(text) {
47
- text = decodeURIComponent(text);
48
- const signedParts = text.split('--');
49
- const hmac = createHmac(this.config.digest, this.signedSecret);
50
- hmac.update(signedParts[0]);
51
- const digest = hmac.digest('hex');
52
- if (signedParts[1] !== digest)
53
- throw Error('Not valid');
54
- const message = Buffer.from(signedParts[0], 'base64').toString();
55
- const parts = message.split('--').map(function (part) {
56
- return Buffer.from(part, 'base64');
57
- });
58
- const cipher = createDecipheriv(this.config.cipherName, this.secret, parts[1]);
59
- const part = Buffer.from(cipher.update(parts[0])).toString('utf8');
60
- const final = cipher.final('utf8');
61
- const decrypt = [part, final].join('');
62
- return JSON.parse(decrypt);
63
- }
64
- read(key) {
65
- return this.content[key];
66
- }
67
- write(key, value) {
68
- if (value === null || typeof value === 'undefined')
69
- delete this.content[key];
70
- else
71
- this.content[key] = value;
72
- this.changed = true;
73
- return this;
74
- }
75
- update() {
76
- if (this.changed)
77
- this.cookie.write(this.config.key, this.encode(JSON.stringify(this.content)));
78
- return this;
79
- }
80
- }
81
-
82
- class Cookie {
83
- constructor(config) {
84
- this.config = deepMerge({
85
- path: '/',
86
- expires: 31536000,
87
- secure: true,
88
- httpOnly: true,
89
- session: {}
90
- }, config);
91
- this.session = new Session(this, this.config.session);
92
- this.content = Object.create(null);
93
- this.setCookie = Object.create(null);
94
- }
95
- invoke(cookie) {
96
- this.content = Object.create(null);
97
- // 解析 cookie
98
- if (cookie)
99
- cookie.split(';').forEach(x => {
100
- x = x.trim();
101
- const k = /([^=]+)/.exec(x);
102
- if (k !== null)
103
- this.content[k[0]] = decodeURIComponent(x.replace(`${k[0]}=`, '').replace(/;$/, ''));
104
- });
105
- this.setCookie = Object.create(null);
106
- // 预读取 session
107
- this.session.invoke(this.read(this.session.config.key));
108
- return this;
109
- }
110
- read(key) {
111
- return this.content[key];
112
- }
113
- write(key, value, opts) {
114
- opts = Object.assign(this.config, opts || {});
115
- let cookie;
116
- if (value === null || typeof value === 'undefined') {
117
- opts.expires = 'Thu, 01 Jan 1970 00:00:01 GMT';
118
- cookie = `${key}=;`;
119
- delete this.content[key];
120
- }
121
- else {
122
- cookie = `${key}=${encodeURIComponent(value)};`;
123
- this.content[key] = value;
124
- }
125
- if (typeof opts.expires === 'number')
126
- cookie += `max-age=${opts.expires};`;
127
- else if (typeof opts.expires === 'string')
128
- cookie += `expires=${opts.expires};`;
129
- cookie += `path=${opts.path || '/'};`;
130
- if (opts.domain)
131
- cookie += `domain=${opts.domain};`;
132
- if (opts.secure)
133
- cookie += 'Secure;';
134
- if (opts.httpOnly)
135
- cookie += 'HttpOnly;';
136
- if (opts.sameSite)
137
- cookie += `SameSite=${opts.sameSite};`;
138
- this.setCookie[key] = cookie;
139
- return this;
140
- }
141
- headers() {
142
- if (Object.keys(this.setCookie).length === 0)
143
- return {};
144
- else
145
- return { 'Set-Cookie': Object.values(this.setCookie) };
146
- }
147
- }
148
-
149
- class Validator {
150
- constructor(config, logger) {
151
- this.paramsConfig = config.params;
152
- this.cookieConfig = config.cookie;
153
- this.sessionConfig = config.session;
154
- this.before = config.before;
155
- this.logger = logger;
156
- }
157
- async valid(request) {
158
- if (this.before) {
159
- const result = await this.before(request);
160
- if (result)
161
- throw new HttpError(result);
162
- }
163
- this.request = request;
164
- if (this.paramsConfig && request.params) {
165
- this.logger.debug('Valid Params');
166
- this.validContent('params', request.params, '', this.paramsConfig);
167
- }
168
- if (this.cookieConfig && request.cookie) {
169
- this.logger.debug('Valid Cookie');
170
- if (request.cookie == null)
171
- throw Error('Not found Cookie');
172
- this.validContent('cookie', request.cookie.content, '', this.cookieConfig);
173
- }
174
- if (this.sessionConfig && request.session) {
175
- this.logger.debug('Valid Session');
176
- if (request.session == null)
177
- throw Error('Not found Session');
178
- this.validContent('session', request.session.content, '', this.sessionConfig);
179
- }
180
- }
181
- validContent(type, params, baseKey, config) {
182
- if (config.whitelist) {
183
- const paramsKeys = Object.keys(params);
184
- const rulesKeys = Object.keys(config.rules);
185
- const diff = paramsKeys.filter(k => !rulesKeys.includes(k));
186
- if (diff.length > 0)
187
- if (config.whitelist === 'error') {
188
- const diffKeys = diff.map(k => `${baseKey}${k}`);
189
- const error = Error(`[${type}] Not permitted keys: ${diffKeys.join(', ')}`);
190
- if (config.onError) {
191
- const res = config.onError(`${type}.whitelist`, baseKey, diffKeys);
192
- if (res)
193
- throw new HttpError(res);
194
- }
195
- throw error;
196
- }
197
- else if (config.whitelist === 'ignore')
198
- for (const key of diff)
199
- delete params[key];
200
- }
201
- for (const key in config.rules) {
202
- const rule = config.rules[key];
203
- if (!rule)
204
- continue;
205
- let value = params[key];
206
- // default
207
- if (rule.default)
208
- if (type === 'cookie' || type === 'session')
209
- this.logger.warn('Cookie and Session not support default rule.');
210
- else if (typeof value === 'undefined' && rule.default) {
211
- value = typeof rule.default === 'function' ? rule.default(this.request) : rule.default;
212
- params[key] = value;
213
- }
214
- // required
215
- if (rule.required)
216
- if (typeof value === 'undefined' || value === null) {
217
- const error = Error(`[${type}] ${baseKey}${key} is required.`);
218
- if (config.onError) {
219
- const res = config.onError(`${type}.rule.required`, `${baseKey}${key}`, value);
220
- if (res)
221
- throw new HttpError(res);
222
- }
223
- throw error;
224
- }
225
- if (typeof value !== 'undefined' && value !== null) {
226
- // type
227
- if (rule.type)
228
- if (type === 'cookie')
229
- this.logger.warn('Cookie not support type rule');
230
- else {
231
- let typed = true;
232
- switch (rule.type) {
233
- case 'array':
234
- typed = Array.isArray(value);
235
- break;
236
- case 'object':
237
- typed = Object.prototype.toString.call(value) === '[object Object]';
238
- break;
239
- default:
240
- typed = typeof value === rule.type;
241
- break;
242
- }
243
- if (!typed) {
244
- const error = Error(`[${type}] ${baseKey}${key} must be a ${rule.type}.`);
245
- if (config.onError) {
246
- const res = config.onError(`${type}.rule.type`, `${baseKey}${key}`, value);
247
- if (res)
248
- throw new HttpError(res);
249
- }
250
- throw error;
251
- }
252
- }
253
- // in
254
- if ((rule.in) && !rule.in.includes(value)) {
255
- const error = Error(`[${type}] ${baseKey}${key} must be in ${rule.in.join(', ')}.`);
256
- if (config.onError) {
257
- const res = config.onError(`${type}.rule.in`, `${baseKey}${key}`, value);
258
- if (res)
259
- throw new HttpError(res);
260
- }
261
- throw error;
262
- }
263
- // nest config
264
- if (rule.config)
265
- if (type === 'cookie')
266
- this.logger.warn('Cookie not support nest rule.');
267
- else if (Array.isArray(value))
268
- // array
269
- for (const val of value)
270
- this.validContent(type, val, (baseKey ? `${baseKey}.${key}.` : `${key}.`), rule.config);
271
- else if (typeof value === 'object')
272
- // object
273
- this.validContent(type, value, (baseKey ? `${baseKey}.${key}.` : `${key}.`), rule.config);
274
- }
275
- }
276
- }
277
- }
278
-
279
- const ContentType = {
280
- plain: 'text/plain',
281
- html: 'text/html',
282
- xml: 'application/xml',
283
- csv: 'text/csv',
284
- css: 'text/css',
285
- javascript: 'application/javascript',
286
- json: 'application/json',
287
- jsonp: 'application/javascript'
288
- };
289
- class HttpError extends Error {
290
- constructor({ statusCode, message }) {
291
- super(message);
292
- if (Error.captureStackTrace)
293
- Error.captureStackTrace(this, HttpError);
294
- this.statusCode = statusCode || 500;
295
- this.message = message;
296
- }
297
- }
298
- const Name = 'http';
299
- class Http {
300
- /**
301
- * 创建 Http 插件实例
302
- * @param config {object} 配置项
303
- * @param config.name {string} 配置名
304
- * @param config.config {object} 网关配置
305
- * @param config.config.method {string} 请求方法,默认为 POST
306
- * @param config.config.path {string} 请求路径,默认为云函数文件路径
307
- * @param config.config.ignorePathPrefix {string} 排除的路径前缀,当设置 path 时无效
308
- * @param config.config.cookie {object} Cookie 配置
309
- * @param config.validator {object} 入参校验配置
310
- * @param config.validator.params {object} params 校验配置
311
- * @param config.validator.params.whitelist {string} 白名单配置
312
- * @param config.validator.params.onError {function} 自定义报错
313
- * @param config.validator.params.rules {object} 参数校验规则
314
- * @param config.validator.cookie {object} cookie 校验配置
315
- * @param config.validator.cookie.whitelist {string} 白名单配置
316
- * @param config.validator.cookie.onError {function} 自定义报错
317
- * @param config.validator.cookie.rules {object} 参数校验规则
318
- * @param config.validator.session {object} session 校验配置
319
- * @param config.validator.session.whitelist {string} 白名单配置
320
- * @param config.validator.session.onError {function} 自定义报错
321
- * @param config.validator.session.rules {object} 参数校验规则
322
- * @param config.validator.before {function} 参数校验前自定义函数
323
- */
324
- constructor(config) {
325
- this.type = Name;
326
- this.name = Name;
327
- this.name = (config === null || config === void 0 ? void 0 : config.name) || this.type;
328
- this.config = ((config === null || config === void 0 ? void 0 : config.config)) || Object.create(null);
329
- if ((config === null || config === void 0 ? void 0 : config.validator))
330
- this.validatorOptions = config.validator;
331
- this.logger = new Logger(this.name);
332
- this.headers = Object.create(null);
333
- this.cookie = new Cookie(this.config.cookie || {});
334
- this.session = this.cookie.session;
335
- }
336
- async onDeploy(data, next) {
337
- var _a;
338
- await next();
339
- this.logger.debug('组装网关配置');
340
- this.logger.debug('%j', data);
341
- const config = data.config.plugins ?
342
- deepMerge(data.config.plugins[this.name || this.type], { config: this.config }) :
343
- { config: this.config };
344
- // 根据文件及文件夹名生成路径
345
- if (!config.config.path) {
346
- config.config.path = '/' + ((_a = data.name) === null || _a === void 0 ? void 0 : _a.replace(/_/g, '/').replace(/\/index$/, ''));
347
- if (config.config.path === '/index')
348
- config.config.path = '/';
349
- if (config.config.ignorePathPrefix) {
350
- config.config.path = config.config.path.replace(new RegExp('^' + config.config.ignorePathPrefix), '');
351
- if (config.config.path === '')
352
- config.config.path = '/';
353
- }
354
- }
355
- this.logger.debug('组装完成 %j', config);
356
- // 引用服务商部署插件
357
- // eslint-disable-next-line @typescript-eslint/no-var-requires
358
- const Provider = require(config.provider.type).Provider;
359
- const provider = new Provider(config.provider.config);
360
- // 部署网关
361
- await provider.deploy(this.type, data, config);
362
- }
363
- async onMount(data, next) {
364
- this.logger.debug('[onMount] merge config');
365
- if (data.config.plugins && data.config.plugins[this.name || this.type])
366
- this.config = deepMerge(this.config, data.config.plugins[this.name || this.type].config);
367
- this.logger.debug('[onMount] prepare cookie & session');
368
- this.cookie = new Cookie(this.config.cookie || {});
369
- this.session = this.cookie.session;
370
- if (this.validatorOptions) {
371
- this.logger.debug('[onMount] prepare validator');
372
- this.validator = new Validator(this.validatorOptions, this.logger);
373
- }
374
- await next();
375
- }
376
- async onInvoke(data, next) {
377
- var _a, _b;
378
- this.headers = data.event.headers || Object.create(null);
379
- this.body = data.event.body;
380
- this.params = Object.create(null);
381
- this.response = { headers: Object.create(null) };
382
- if (data.event.body) {
383
- if (data.event.headers && data.event.headers['content-type'] && data.event.headers['content-type'].includes('application/json')) {
384
- this.logger.debug('[onInvoke] Parse params from json body');
385
- this.params = JSON.parse(data.event.body);
386
- }
387
- else {
388
- this.logger.debug('[onInvoke] Parse params from raw body');
389
- this.params = data.event.body;
390
- }
391
- this.logger.debug('[onInvoke] Params: %j', this.params);
392
- }
393
- else if (data.event.queryString) {
394
- this.logger.debug('[onInvoke] Parse params from queryString');
395
- this.params = data.event.queryString;
396
- this.logger.debug('[onInvoke] Params: %j', this.params);
397
- }
398
- this.cookie.invoke(this.headers.cookie);
399
- if (this.headers.cookie) {
400
- this.logger.debug('[onInvoke] Cookie: %j', this.cookie.content);
401
- this.logger.debug('[onInvoke] Session: %j', this.session.content);
402
- }
403
- if (this.validator) {
404
- this.logger.debug('[onInvoke] Valid request');
405
- try {
406
- await this.validator.valid({
407
- headers: this.headers,
408
- params: this.params,
409
- cookie: this.cookie,
410
- session: this.session
411
- });
412
- }
413
- catch (error) {
414
- this.logger.error(error);
415
- data.response = {
416
- statusCode: error.statusCode || 500,
417
- headers: { 'Content-Type': 'application/json; charset=utf-8' },
418
- body: JSON.stringify({ error: { message: error.message } })
419
- };
420
- return;
421
- }
422
- }
423
- try {
424
- await next();
425
- }
426
- catch (error) {
427
- data.response = error;
428
- }
429
- // update session
430
- this.session.update();
431
- // 处理 body
432
- if (data.response)
433
- if (data.response instanceof Error || ((_a = data.response.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Error') {
434
- // 当结果是错误类型时
435
- this.logger.error(data.response);
436
- this.response.body = JSON.stringify({ error: { message: data.response.message } });
437
- try {
438
- this.response.statusCode = data.response.statusCode || 500;
439
- }
440
- catch (error) {
441
- this.response.statusCode = 500;
442
- }
443
- }
444
- else if (Object.prototype.toString.call(data.response) === '[object Object]' && data.response.statusCode && data.response.headers)
445
- // 当返回结果是响应结构体时
446
- this.response = data.response;
447
- else
448
- this.response.body = JSON.stringify({ data: data.response });
449
- // 处理 statusCode
450
- if (!this.response.statusCode)
451
- this.response.statusCode = this.response.body ? 200 : 201;
452
- // 处理 headers
453
- this.response.headers = Object.assign({
454
- 'Content-Type': 'application/json; charset=utf-8',
455
- 'Cache-Control': 'no-cache, no-store'
456
- }, this.cookie.headers(), this.response.headers);
457
- data.response = this.response;
458
- if (process.env.FaasMode === 'local') {
459
- this.logger.debug('[onInvoke] Response: %j', data.response);
460
- return;
461
- }
462
- // 判断是否需要压缩
463
- if (data.response.isBase64Encoded ||
464
- typeof data.response.body !== 'string' ||
465
- !((_b = data.response.headers['Content-Type']) === null || _b === void 0 ? void 0 : _b.includes('json')) ||
466
- data.response.body.length < 100)
467
- return;
468
- const acceptEncoding = this.headers['accept-encoding'] || this.headers['Accept-Encoding'];
469
- if (!acceptEncoding || !/(br|gzip|deflate)/.test(acceptEncoding))
470
- return;
471
- const originBody = data.response.body;
472
- try {
473
- if (acceptEncoding.includes('br')) {
474
- data.response.headers['Content-Encoding'] = 'br';
475
- data.response.body = brotliCompressSync(originBody).toString('base64');
476
- }
477
- else if (acceptEncoding.includes('gzip')) {
478
- data.response.headers['Content-Encoding'] = 'gzip';
479
- data.response.body = gzipSync(originBody).toString('base64');
480
- }
481
- else if (acceptEncoding.includes('deflate')) {
482
- data.response.headers['Content-Encoding'] = 'deflate';
483
- data.response.body = deflateSync(originBody).toString('base64');
484
- }
485
- else
486
- throw Error('No matched compression.');
487
- data.response.isBase64Encoded = true;
488
- data.response.originBody = originBody;
489
- }
490
- catch (error) {
491
- console.error(error);
492
- // 若压缩失败还原
493
- data.response.body = originBody;
494
- delete data.response.headers['Content-Encoding'];
495
- }
496
- }
497
- /**
498
- * 设置 header
499
- * @param key {string} key
500
- * @param value {*} value
501
- */
502
- setHeader(key, value) {
503
- this.response.headers[key] = value;
504
- return this;
505
- }
506
- /**
507
- * 设置 Content-Type
508
- * @param type {string} 类型
509
- * @param charset {string} 编码
510
- */
511
- setContentType(type, charset = 'utf-8') {
512
- if (ContentType[type])
513
- this.setHeader('Content-Type', `${ContentType[type]}; charset=${charset}`);
514
- else
515
- this.setHeader('Content-Type', `${type}; charset=${charset}`);
516
- return this;
517
- }
518
- /**
519
- * 设置状态码
520
- * @param code {number} 状态码
521
- */
522
- setStatusCode(code) {
523
- this.response.statusCode = code;
524
- return this;
525
- }
526
- /**
527
- * 设置 body
528
- * @param body {*} 内容
529
- */
530
- setBody(body) {
531
- this.response.body = body;
532
- return this;
533
- }
534
- }
535
- function useHttp(config) {
536
- return usePlugin(new Http(config));
537
- }
538
-
539
- export { ContentType, Cookie, Http, HttpError, Session, Validator, useHttp };