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