@faasjs/http 0.0.2-beta.43 → 0.0.2-beta.430

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