@faasjs/http 0.0.2-beta.99 → 0.0.3-beta.2

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