@celljs/web 4.0.0 → 4.2.0
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/README.md +39 -1
- package/cell.yml +0 -3
- package/esm/browser/module.d.ts +1 -1
- package/esm/common/module.d.ts +1 -1
- package/esm/common/pipe/index.d.ts +1 -1
- package/esm/common/pipe/index.js +1 -1
- package/esm/common/pipe/index.js.map +1 -1
- package/esm/common/pipe/type-conversion-pipe.d.ts +12 -0
- package/esm/common/pipe/type-conversion-pipe.js +43 -0
- package/esm/common/pipe/type-conversion-pipe.js.map +1 -0
- package/esm/common/pipe/validation-errors.d.ts +11 -2
- package/esm/common/pipe/validation-errors.js +2 -0
- package/esm/common/pipe/validation-errors.js.map +1 -1
- package/esm/node/body/body-middleware.d.ts +5 -4
- package/esm/node/body/body-middleware.js +14 -15
- package/esm/node/body/body-middleware.js.map +1 -1
- package/esm/node/body/body-parser.d.ts +32 -0
- package/esm/node/body/body-parser.js +205 -0
- package/esm/node/body/body-parser.js.map +1 -0
- package/esm/node/body/body-protocol.d.ts +15 -0
- package/esm/node/body/form-util.d.ts +15 -0
- package/esm/node/body/form-util.js +120 -0
- package/esm/node/body/form-util.js.map +1 -0
- package/esm/node/body/index.d.ts +2 -0
- package/esm/node/body/index.js +2 -0
- package/esm/node/body/index.js.map +1 -1
- package/esm/node/context.js +1 -1
- package/esm/node/context.js.map +1 -1
- package/esm/node/cookies/cookies-factory.js +2 -6
- package/esm/node/cookies/cookies-factory.js.map +1 -1
- package/esm/node/cookies/cookies-protocol.d.ts +25 -2
- package/esm/node/cookies/cookies.d.ts +17 -0
- package/esm/node/cookies/cookies.js +137 -0
- package/esm/node/cookies/cookies.js.map +1 -0
- package/esm/node/cookies/index.d.ts +1 -0
- package/esm/node/cookies/index.js +1 -0
- package/esm/node/cookies/index.js.map +1 -1
- package/esm/node/cors/cors-middleware.d.ts +11 -3
- package/esm/node/cors/cors-middleware.js +108 -14
- package/esm/node/cors/cors-middleware.js.map +1 -1
- package/esm/node/cors/cors-protocol.d.ts +23 -0
- package/esm/node/error/error-handler-provider.js +3 -7
- package/esm/node/error/error-handler-provider.js.map +1 -1
- package/esm/node/health/health-middleware.js +1 -1
- package/esm/node/health/health-middleware.js.map +1 -1
- package/esm/node/http/http-middleware.d.ts +1 -0
- package/esm/node/http/http-middleware.js +10 -5
- package/esm/node/http/http-middleware.js.map +1 -1
- package/esm/node/http/http-protocol.d.ts +29 -5
- package/esm/node/http/http-protocol.js.map +1 -1
- package/esm/node/http/http-request.d.ts +41 -0
- package/esm/node/http/http-request.js +106 -0
- package/esm/node/http/http-request.js.map +1 -0
- package/esm/node/http/index.d.ts +1 -0
- package/esm/node/http/index.js +1 -0
- package/esm/node/http/index.js.map +1 -1
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +1 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/matcher/index.d.ts +1 -0
- package/esm/node/matcher/index.js +1 -0
- package/esm/node/matcher/index.js.map +1 -1
- package/esm/node/matcher/path-pattern.d.ts +23 -0
- package/esm/node/matcher/path-pattern.js +115 -0
- package/esm/node/matcher/path-pattern.js.map +1 -0
- package/esm/node/matcher/request-matcher.d.ts +2 -2
- package/esm/node/matcher/request-matcher.js +8 -9
- package/esm/node/matcher/request-matcher.js.map +1 -1
- package/esm/node/module.d.ts +1 -1
- package/esm/node/server/http-server.d.ts +13 -0
- package/esm/node/server/http-server.js +32 -0
- package/esm/node/server/http-server.js.map +1 -0
- package/esm/node/server/index.d.ts +1 -0
- package/esm/node/server/index.js +2 -0
- package/esm/node/server/index.js.map +1 -0
- package/esm/node/session/session-manager.js +1 -2
- package/esm/node/session/session-manager.js.map +1 -1
- package/esm/node/session/session-store.js +5 -5
- package/esm/node/session/session-store.js.map +1 -1
- package/esm/node/session/session.d.ts +3 -2
- package/esm/node/session/session.js +4 -10
- package/esm/node/session/session.js.map +1 -1
- package/lib/browser/module.d.ts +1 -1
- package/lib/common/module.d.ts +1 -1
- package/lib/common/pipe/index.d.ts +1 -1
- package/lib/common/pipe/index.d.ts.map +1 -1
- package/lib/common/pipe/index.js +1 -1
- package/lib/common/pipe/index.js.map +1 -1
- package/lib/common/pipe/type-conversion-pipe.d.ts +13 -0
- package/lib/common/pipe/type-conversion-pipe.d.ts.map +1 -0
- package/lib/common/pipe/type-conversion-pipe.js +46 -0
- package/lib/common/pipe/type-conversion-pipe.js.map +1 -0
- package/lib/common/pipe/type-conversion-pipe.spec.d.ts +2 -0
- package/lib/common/pipe/type-conversion-pipe.spec.d.ts.map +1 -0
- package/lib/common/pipe/type-conversion-pipe.spec.js +36 -0
- package/lib/common/pipe/type-conversion-pipe.spec.js.map +1 -0
- package/lib/common/pipe/validation-errors.d.ts +11 -2
- package/lib/common/pipe/validation-errors.d.ts.map +1 -1
- package/lib/common/pipe/validation-errors.js +2 -0
- package/lib/common/pipe/validation-errors.js.map +1 -1
- package/lib/node/body/body-middleware.d.ts +5 -4
- package/lib/node/body/body-middleware.d.ts.map +1 -1
- package/lib/node/body/body-middleware.js +12 -12
- package/lib/node/body/body-middleware.js.map +1 -1
- package/lib/node/body/body-middleware.spec.d.ts +2 -0
- package/lib/node/body/body-middleware.spec.d.ts.map +1 -0
- package/lib/node/body/body-middleware.spec.js +85 -0
- package/lib/node/body/body-middleware.spec.js.map +1 -0
- package/lib/node/body/body-parser.d.ts +33 -0
- package/lib/node/body/body-parser.d.ts.map +1 -0
- package/lib/node/body/body-parser.js +210 -0
- package/lib/node/body/body-parser.js.map +1 -0
- package/lib/node/body/body-protocol.d.ts +15 -0
- package/lib/node/body/body-protocol.d.ts.map +1 -1
- package/lib/node/body/form-util.d.ts +16 -0
- package/lib/node/body/form-util.d.ts.map +1 -0
- package/lib/node/body/form-util.js +123 -0
- package/lib/node/body/form-util.js.map +1 -0
- package/lib/node/body/form-util.spec.d.ts +2 -0
- package/lib/node/body/form-util.spec.d.ts.map +1 -0
- package/lib/node/body/form-util.spec.js +44 -0
- package/lib/node/body/form-util.spec.js.map +1 -0
- package/lib/node/body/index.d.ts +2 -0
- package/lib/node/body/index.d.ts.map +1 -1
- package/lib/node/body/index.js +2 -0
- package/lib/node/body/index.js.map +1 -1
- package/lib/node/context.js +1 -1
- package/lib/node/context.js.map +1 -1
- package/lib/node/cookies/cookies-factory.d.ts.map +1 -1
- package/lib/node/cookies/cookies-factory.js +2 -9
- package/lib/node/cookies/cookies-factory.js.map +1 -1
- package/lib/node/cookies/cookies-protocol.d.ts +25 -2
- package/lib/node/cookies/cookies-protocol.d.ts.map +1 -1
- package/lib/node/cookies/cookies.d.ts +18 -0
- package/lib/node/cookies/cookies.d.ts.map +1 -0
- package/lib/node/cookies/cookies.js +141 -0
- package/lib/node/cookies/cookies.js.map +1 -0
- package/lib/node/cookies/cookies.spec.d.ts +2 -0
- package/lib/node/cookies/cookies.spec.d.ts.map +1 -0
- package/lib/node/cookies/cookies.spec.js +73 -0
- package/lib/node/cookies/cookies.spec.js.map +1 -0
- package/lib/node/cookies/index.d.ts +1 -0
- package/lib/node/cookies/index.d.ts.map +1 -1
- package/lib/node/cookies/index.js +1 -0
- package/lib/node/cookies/index.js.map +1 -1
- package/lib/node/cors/cors-middleware.d.ts +11 -3
- package/lib/node/cors/cors-middleware.d.ts.map +1 -1
- package/lib/node/cors/cors-middleware.js +106 -15
- package/lib/node/cors/cors-middleware.js.map +1 -1
- package/lib/node/cors/cors-middleware.spec.d.ts +2 -0
- package/lib/node/cors/cors-middleware.spec.d.ts.map +1 -0
- package/lib/node/cors/cors-middleware.spec.js +56 -0
- package/lib/node/cors/cors-middleware.spec.js.map +1 -0
- package/lib/node/cors/cors-protocol.d.ts +23 -0
- package/lib/node/cors/cors-protocol.d.ts.map +1 -1
- package/lib/node/error/error-handler-provider.d.ts.map +1 -1
- package/lib/node/error/error-handler-provider.js +2 -5
- package/lib/node/error/error-handler-provider.js.map +1 -1
- package/lib/node/health/health-middleware.js +1 -1
- package/lib/node/health/health-middleware.js.map +1 -1
- package/lib/node/http/http-middleware.d.ts +1 -0
- package/lib/node/http/http-middleware.d.ts.map +1 -1
- package/lib/node/http/http-middleware.js +10 -5
- package/lib/node/http/http-middleware.js.map +1 -1
- package/lib/node/http/http-protocol.d.ts +29 -5
- package/lib/node/http/http-protocol.d.ts.map +1 -1
- package/lib/node/http/http-protocol.js.map +1 -1
- package/lib/node/http/http-request.d.ts +42 -0
- package/lib/node/http/http-request.d.ts.map +1 -0
- package/lib/node/http/http-request.js +110 -0
- package/lib/node/http/http-request.js.map +1 -0
- package/lib/node/http/http-request.spec.d.ts +2 -0
- package/lib/node/http/http-request.spec.d.ts.map +1 -0
- package/lib/node/http/http-request.spec.js +65 -0
- package/lib/node/http/http-request.spec.js.map +1 -0
- package/lib/node/http/index.d.ts +1 -0
- package/lib/node/http/index.d.ts.map +1 -1
- package/lib/node/http/index.js +1 -0
- package/lib/node/http/index.js.map +1 -1
- package/lib/node/index.d.ts +1 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +1 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/matcher/index.d.ts +1 -0
- package/lib/node/matcher/index.d.ts.map +1 -1
- package/lib/node/matcher/index.js +1 -0
- package/lib/node/matcher/index.js.map +1 -1
- package/lib/node/matcher/path-pattern.d.ts +24 -0
- package/lib/node/matcher/path-pattern.d.ts.map +1 -0
- package/lib/node/matcher/path-pattern.js +119 -0
- package/lib/node/matcher/path-pattern.js.map +1 -0
- package/lib/node/matcher/path-pattern.spec.d.ts +2 -0
- package/lib/node/matcher/path-pattern.spec.d.ts.map +1 -0
- package/lib/node/matcher/path-pattern.spec.js +43 -0
- package/lib/node/matcher/path-pattern.spec.js.map +1 -0
- package/lib/node/matcher/request-matcher.d.ts +2 -2
- package/lib/node/matcher/request-matcher.d.ts.map +1 -1
- package/lib/node/matcher/request-matcher.js +8 -12
- package/lib/node/matcher/request-matcher.js.map +1 -1
- package/lib/node/module.d.ts +1 -1
- package/lib/node/server/http-server.d.ts +14 -0
- package/lib/node/server/http-server.d.ts.map +1 -0
- package/lib/node/server/http-server.js +35 -0
- package/lib/node/server/http-server.js.map +1 -0
- package/lib/node/server/http-server.spec.d.ts +2 -0
- package/lib/node/server/http-server.spec.d.ts.map +1 -0
- package/lib/node/server/http-server.spec.js +41 -0
- package/lib/node/server/http-server.spec.js.map +1 -0
- package/lib/node/server/index.d.ts +2 -0
- package/lib/node/server/index.d.ts.map +1 -0
- package/lib/node/server/index.js +18 -0
- package/lib/node/server/index.js.map +1 -0
- package/lib/node/session/session-manager.d.ts.map +1 -1
- package/lib/node/session/session-manager.js +1 -2
- package/lib/node/session/session-manager.js.map +1 -1
- package/lib/node/session/session-store.d.ts.map +1 -1
- package/lib/node/session/session-store.js +5 -3
- package/lib/node/session/session-store.js.map +1 -1
- package/lib/node/session/session.d.ts +3 -2
- package/lib/node/session/session.d.ts.map +1 -1
- package/lib/node/session/session.js +4 -8
- package/lib/node/session/session.js.map +1 -1
- package/lib/node/session/session.spec.d.ts +2 -0
- package/lib/node/session/session.spec.d.ts.map +1 -0
- package/lib/node/session/session.spec.js +84 -0
- package/lib/node/session/session.spec.js.map +1 -0
- package/package.json +10 -18
- package/src/common/pipe/index.ts +1 -1
- package/src/common/pipe/type-conversion-pipe.spec.ts +38 -0
- package/src/common/pipe/type-conversion-pipe.ts +36 -0
- package/src/common/pipe/validation-errors.ts +11 -2
- package/src/node/body/body-middleware.spec.ts +96 -0
- package/src/node/body/body-middleware.ts +14 -15
- package/src/node/body/body-parser.ts +216 -0
- package/src/node/body/body-protocol.ts +15 -0
- package/src/node/body/form-util.spec.ts +45 -0
- package/src/node/body/form-util.ts +132 -0
- package/src/node/body/index.ts +2 -0
- package/src/node/context.ts +1 -1
- package/src/node/cookies/cookies-factory.ts +2 -6
- package/src/node/cookies/cookies-protocol.ts +28 -3
- package/src/node/cookies/cookies.spec.ts +80 -0
- package/src/node/cookies/cookies.ts +138 -0
- package/src/node/cookies/index.ts +1 -0
- package/src/node/cors/cors-middleware.spec.ts +59 -0
- package/src/node/cors/cors-middleware.ts +112 -15
- package/src/node/cors/cors-protocol.ts +25 -0
- package/src/node/error/error-handler-provider.ts +1 -2
- package/src/node/health/health-middleware.ts +1 -1
- package/src/node/http/http-middleware.ts +10 -5
- package/src/node/http/http-protocol.ts +29 -5
- package/src/node/http/http-request.spec.ts +68 -0
- package/src/node/http/http-request.ts +132 -0
- package/src/node/http/index.ts +1 -0
- package/src/node/index.ts +1 -0
- package/src/node/matcher/index.ts +1 -0
- package/src/node/matcher/path-pattern.spec.ts +43 -0
- package/src/node/matcher/path-pattern.ts +113 -0
- package/src/node/matcher/request-matcher.ts +9 -10
- package/src/node/server/http-server.spec.ts +45 -0
- package/src/node/server/http-server.ts +35 -0
- package/src/node/server/index.ts +1 -0
- package/src/node/session/session-manager.ts +1 -2
- package/src/node/session/session-store.ts +6 -3
- package/src/node/session/session.spec.ts +88 -0
- package/src/node/session/session.ts +6 -9
- package/esm/common/pipe/pipe-transtorm.d.ts +0 -17
- package/esm/common/pipe/pipe-transtorm.js +0 -110
- package/esm/common/pipe/pipe-transtorm.js.map +0 -1
- package/lib/common/pipe/pipe-transtorm.d.ts +0 -18
- package/lib/common/pipe/pipe-transtorm.d.ts.map +0 -1
- package/lib/common/pipe/pipe-transtorm.js +0 -113
- package/lib/common/pipe/pipe-transtorm.js.map +0 -1
- package/lib/common/pipe/pipe-transtorm.spec.d.ts +0 -2
- package/lib/common/pipe/pipe-transtorm.spec.d.ts.map +0 -1
- package/lib/common/pipe/pipe-transtorm.spec.js +0 -69
- package/lib/common/pipe/pipe-transtorm.spec.js.map +0 -1
- package/src/common/pipe/pipe-transtorm.spec.ts +0 -62
- package/src/common/pipe/pipe-transtorm.ts +0 -113
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import { Socket } from 'node:net';
|
|
5
|
+
import { TypeConversionPipe } from './type-conversion-pipe';
|
|
6
|
+
|
|
7
|
+
class CreateUser {
|
|
8
|
+
name: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
describe('TypeConversionPipe', () => {
|
|
12
|
+
const pipe = new TypeConversionPipe();
|
|
13
|
+
|
|
14
|
+
it('converts to primitive parameter types as class-transformer did', () => {
|
|
15
|
+
expect(pipe.transform('5', { argType: Number })).to.equal(5);
|
|
16
|
+
expect(pipe.transform('abc', { argType: Number })).to.be.NaN;
|
|
17
|
+
expect(pipe.transform('', { argType: Number })).to.equal(0);
|
|
18
|
+
expect(pipe.transform(['1', '2'], { argType: Number })).to.deep.equal([1, 2]);
|
|
19
|
+
expect(pipe.transform(5, { argType: String })).to.equal('5');
|
|
20
|
+
expect(pipe.transform('false', { argType: Boolean })).to.equal(true);
|
|
21
|
+
expect(pipe.transform('', { argType: Boolean })).to.equal(false);
|
|
22
|
+
expect(pipe.transform(undefined, { argType: Number })).to.equal(undefined);
|
|
23
|
+
expect(pipe.transform(null, { argType: String })).to.equal(null);
|
|
24
|
+
expect(pipe.transform('2020-01-01', { argType: Date }).toISOString()).to.equal('2020-01-01T00:00:00.000Z');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('passes everything else as it is', () => {
|
|
28
|
+
const data = { name: 'Tom' };
|
|
29
|
+
expect(pipe.transform(data, { argType: CreateUser })).to.equal(data);
|
|
30
|
+
expect(pipe.transform(data, { argType: Object })).to.equal(data);
|
|
31
|
+
expect(pipe.transform(data, { argType: String })).to.equal(data);
|
|
32
|
+
expect(pipe.transform('5', {})).to.equal('5');
|
|
33
|
+
const request = new IncomingMessage(new Socket());
|
|
34
|
+
const response = new ServerResponse(request);
|
|
35
|
+
expect(pipe.transform(response, { argType: Object })).to.equal(response);
|
|
36
|
+
expect(pipe.transform(request, { argType: String })).to.equal(request);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { Component } from '@celljs/core';
|
|
2
|
+
import { ArgumentMetadata, PipeTransform } from './pipe-protocol';
|
|
3
|
+
|
|
4
|
+
const TYPES: Function[] = [String, Number, Boolean, Date];
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Converts request data to a `String`, `Number`, `Boolean` or `Date` parameter as class-transformer did:
|
|
8
|
+
* `'5'` → `5`, `'abc'` → `NaN`, `'false'` → `true` (any non-empty string), arrays item by item;
|
|
9
|
+
* `null` and `undefined` stay. Parameters of other types get the data as it is; `@celljs/validation`
|
|
10
|
+
* turns it into instances of the parameter class and validates them.
|
|
11
|
+
*/
|
|
12
|
+
@Component(PipeTransform)
|
|
13
|
+
export class TypeConversionPipe implements PipeTransform<any> {
|
|
14
|
+
|
|
15
|
+
readonly priority = 1000;
|
|
16
|
+
|
|
17
|
+
transform(value: any, { argType }: ArgumentMetadata): any {
|
|
18
|
+
if (!argType || !TYPES.includes(argType) || (value !== null && typeof value === 'object' && !Array.isArray(value))) {
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
return this.convert(argType, value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
protected convert(type: Function, value: unknown): unknown {
|
|
25
|
+
if (value === null || value === undefined) {
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
if (Array.isArray(value)) {
|
|
29
|
+
return value.map(item => this.convert(type, item));
|
|
30
|
+
}
|
|
31
|
+
if (type === Date) {
|
|
32
|
+
return value instanceof Date ? value : new Date(value as string);
|
|
33
|
+
}
|
|
34
|
+
return (type as (value: unknown) => unknown)(value);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { CustomError } from '@celljs/core';
|
|
2
|
-
import { ValidationError } from 'class-validator';
|
|
3
2
|
|
|
3
|
+
/** What class-validator reports for one property (the part Cell reads; the rest is kept as it is). */
|
|
4
|
+
export interface ValidationError {
|
|
5
|
+
property: string;
|
|
6
|
+
value?: unknown;
|
|
7
|
+
constraints?: Record<string, string>;
|
|
8
|
+
children?: ValidationError[];
|
|
9
|
+
[key: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Request data that failed validation; answers 400 with the errors as JSON (unless `detailedOutputDisabled`). */
|
|
4
13
|
export class ValidationErrors extends CustomError {
|
|
5
14
|
|
|
6
|
-
constructor(errors?: ValidationError[]) {
|
|
15
|
+
constructor(readonly errors?: ValidationError[]) {
|
|
7
16
|
super(errors === undefined ? undefined : JSON.stringify(errors));
|
|
8
17
|
}
|
|
9
18
|
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { createServer, Server } from 'node:http';
|
|
4
|
+
import type { AddressInfo } from 'node:net';
|
|
5
|
+
import { gzipSync } from 'node:zlib';
|
|
6
|
+
import { BodyParser, parseBytes } from './body-parser';
|
|
7
|
+
import { BodyOptions } from './body-protocol';
|
|
8
|
+
import { HttpError } from '../error/http-error';
|
|
9
|
+
|
|
10
|
+
/** A server that parses each request with the options in the x-options header and answers with what it got. */
|
|
11
|
+
let server: Server;
|
|
12
|
+
let url: string;
|
|
13
|
+
|
|
14
|
+
beforeAll(async () => {
|
|
15
|
+
server = createServer(async (req, res) => {
|
|
16
|
+
const options: BodyOptions = JSON.parse(String(req.headers['x-options'] || '{}'));
|
|
17
|
+
try {
|
|
18
|
+
await new BodyParser(options).parse(req);
|
|
19
|
+
const body = (req as any).body;
|
|
20
|
+
res.setHeader('content-type', 'application/json');
|
|
21
|
+
res.end(JSON.stringify({ type: Buffer.isBuffer(body) ? 'buffer' : typeof body, body: Buffer.isBuffer(body) ? body.toString('hex') : body }));
|
|
22
|
+
} catch (error) {
|
|
23
|
+
res.statusCode = error instanceof HttpError ? error.statusCode : 500;
|
|
24
|
+
res.end(String((error as Error).message));
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
28
|
+
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
afterAll(() => server.close());
|
|
32
|
+
|
|
33
|
+
async function post(body: BodyInit | undefined, headers: Record<string, string> = {}, options: BodyOptions = {}) {
|
|
34
|
+
const res = await fetch(url, { method: body === undefined ? 'GET' : 'POST', body, headers: { ...headers, 'x-options': JSON.stringify(options) } });
|
|
35
|
+
const text = await res.text();
|
|
36
|
+
return { status: res.status, ...(res.status === 200 ? JSON.parse(text) : { message: text }) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('BodyParser', () => {
|
|
40
|
+
it('parses JSON', async () => {
|
|
41
|
+
expect(await post('{"a":[1,2]}', { 'content-type': 'application/json' })).to.deep.equal({ status: 200, type: 'object', body: { a: [1, 2] } });
|
|
42
|
+
expect(await post('', { 'content-type': 'application/json; charset=utf-8' })).to.deep.include({ status: 200, body: {} });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('refuses malformed and, when strict, non-object JSON', async () => {
|
|
46
|
+
expect((await post('{a', { 'content-type': 'application/json' })).status).to.equal(400);
|
|
47
|
+
expect((await post('"text"', { 'content-type': 'application/json' })).status).to.equal(400);
|
|
48
|
+
expect(await post('"text"', { 'content-type': 'application/json' }, { strict: false })).to.deep.include({ status: 200, body: 'text' });
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('parses text, raw and forms', async () => {
|
|
52
|
+
expect(await post('héllo', { 'content-type': 'text/plain' })).to.deep.include({ type: 'string', body: 'héllo' });
|
|
53
|
+
expect(await post(new Uint8Array([0xe9]), { 'content-type': 'text/plain; charset=latin1' })).to.deep.include({ body: 'é' });
|
|
54
|
+
expect(await post(new Uint8Array([1, 2, 255]), { 'content-type': 'application/octet-stream' })).to.deep.include({ type: 'buffer', body: '0102ff' });
|
|
55
|
+
expect(await post('a[b]=1&c=x+y', { 'content-type': 'application/x-www-form-urlencoded' })).to.deep.include({ body: { a: { b: '1' }, c: 'x y' } });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('gives {} to requests without a body or of another type', async () => {
|
|
59
|
+
expect(await post(undefined)).to.deep.include({ status: 200, body: {} });
|
|
60
|
+
expect(await post('<a/>', { 'content-type': 'application/xml' })).to.deep.include({ status: 200, body: {} });
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('decompresses gzip unless inflate is off', async () => {
|
|
64
|
+
const body = new Uint8Array(gzipSync('{"zipped":true}'));
|
|
65
|
+
expect(await post(body, { 'content-type': 'application/json', 'content-encoding': 'gzip' })).to.deep.include({ body: { zipped: true } });
|
|
66
|
+
expect((await post(body, { 'content-type': 'application/json', 'content-encoding': 'gzip' }, { inflate: false })).status).to.equal(415);
|
|
67
|
+
expect((await post(body, { 'content-type': 'application/json', 'content-encoding': 'compress' })).status).to.equal(415);
|
|
68
|
+
expect((await post('not gzip', { 'content-type': 'application/json', 'content-encoding': 'gzip' })).status).to.equal(400);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('refuses bodies over the limit, also after decompression', async () => {
|
|
72
|
+
expect((await post('x'.repeat(2048), { 'content-type': 'text/plain' }, { limit: '1kb' })).status).to.equal(413);
|
|
73
|
+
expect((await post(new Uint8Array(gzipSync('x'.repeat(4096))), { 'content-type': 'text/plain', 'content-encoding': 'gzip' }, { limit: '1kb' })).status).to.equal(413);
|
|
74
|
+
expect(await post('x'.repeat(1024), { 'content-type': 'text/plain' }, { limit: '1kb' })).to.deep.include({ status: 200 });
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('refuses unsupported charsets and too many form parameters', async () => {
|
|
78
|
+
expect((await post('{}', { 'content-type': 'application/json; charset=latin1' })).status).to.equal(415);
|
|
79
|
+
expect((await post('a=1', { 'content-type': 'application/x-www-form-urlencoded; charset=latin1' })).status).to.equal(415);
|
|
80
|
+
expect((await post('a=1&b=2&c=3', { 'content-type': 'application/x-www-form-urlencoded' }, { parameterLimit: 2 })).status).to.equal(413);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('reads sizes', () => {
|
|
84
|
+
expect(parseBytes('100kb')).to.equal(102400);
|
|
85
|
+
expect(parseBytes('5mb')).to.equal(5 * 1024 * 1024);
|
|
86
|
+
expect(parseBytes('1.5KB')).to.equal(1536);
|
|
87
|
+
expect(parseBytes(10)).to.equal(10);
|
|
88
|
+
expect(() => parseBytes('lots')).to.throw(TypeError);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('leaves a body that was already read', async () => {
|
|
92
|
+
const request = { _body: true, body: 'kept', headers: { 'content-length': '3', 'content-type': 'text/plain' } };
|
|
93
|
+
await new BodyParser().parse(request);
|
|
94
|
+
expect(request.body).to.equal('kept');
|
|
95
|
+
});
|
|
96
|
+
});
|
|
@@ -1,26 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Middleware } from '../middleware';
|
|
2
2
|
import { Context } from '../context';
|
|
3
|
-
import { Component,
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { HandlerExecutionChain } from '../handler';
|
|
3
|
+
import { Component, Value, PostConstruct } from '@celljs/core';
|
|
4
|
+
import { BODY_MIDDLEWARE_PRIORITY, BodyOptions } from './body-protocol';
|
|
5
|
+
import { BodyParser } from './body-parser';
|
|
7
6
|
|
|
8
7
|
@Component(Middleware)
|
|
9
8
|
export class BodyMiddleware implements Middleware {
|
|
10
9
|
|
|
11
|
-
@Autowired(HandlerExecutionChain)
|
|
12
|
-
protected handlerExecutionChain: HandlerExecutionChain;
|
|
13
|
-
|
|
14
10
|
@Value('cell.web.body')
|
|
15
|
-
protected readonly options
|
|
11
|
+
protected readonly options?: BodyOptions;
|
|
12
|
+
|
|
13
|
+
protected parser: BodyParser;
|
|
14
|
+
|
|
15
|
+
@PostConstruct()
|
|
16
|
+
protected init(): void {
|
|
17
|
+
this.parser = new BodyParser(this.options);
|
|
18
|
+
}
|
|
16
19
|
|
|
17
20
|
async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
convertExpressMiddleware(text({ ...this.options })),
|
|
21
|
-
convertExpressMiddleware(raw({ ...this.options })),
|
|
22
|
-
convertExpressMiddleware(urlencoded({ ...this.options, ...{ extended: true } }))
|
|
23
|
-
], next);
|
|
21
|
+
await this.parser.parse(ctx.request, ctx.response);
|
|
22
|
+
return next();
|
|
24
23
|
}
|
|
25
24
|
|
|
26
25
|
readonly priority = BODY_MIDDLEWARE_PRIORITY;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createBrotliDecompress, createGunzip, createInflate } from 'zlib';
|
|
2
|
+
import { Readable } from 'stream';
|
|
3
|
+
import { HttpError } from '../error/http-error';
|
|
4
|
+
import { BodyOptions } from './body-protocol';
|
|
5
|
+
import { FormUtil } from './form-util';
|
|
6
|
+
|
|
7
|
+
const UNITS: Record<string, number> = { b: 1, kb: 1 << 10, mb: 1 << 20, gb: 1 << 30 };
|
|
8
|
+
|
|
9
|
+
type BodyType = 'json' | 'text' | 'raw' | 'urlencoded';
|
|
10
|
+
|
|
11
|
+
const TYPES: Record<string, BodyType> = {
|
|
12
|
+
'application/json': 'json',
|
|
13
|
+
'text/plain': 'text',
|
|
14
|
+
'application/octet-stream': 'raw',
|
|
15
|
+
'application/x-www-form-urlencoded': 'urlencoded'
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** `'100kb'` → 102400. */
|
|
19
|
+
export function parseBytes(value: number | string): number {
|
|
20
|
+
if (typeof value === 'number') {
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
const match = /^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?\s*$/i.exec(value);
|
|
24
|
+
if (!match) {
|
|
25
|
+
throw new TypeError(`Invalid size: ${value}`);
|
|
26
|
+
}
|
|
27
|
+
return Math.floor(Number(match[1]) * UNITS[(match[2] || 'b').toLowerCase()]);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Reads the body of a request into `request.body`: JSON (`application/json`), text (`text/plain`), a Buffer
|
|
32
|
+
* (`application/octet-stream`) or a form (`application/x-www-form-urlencoded`, nested with brackets). Other
|
|
33
|
+
* requests get `{}`. Failures are {@link HttpError}s: 400 for a malformed body, 413 for a large one, 415 for
|
|
34
|
+
* an unsupported charset or encoding.
|
|
35
|
+
*/
|
|
36
|
+
export class BodyParser {
|
|
37
|
+
|
|
38
|
+
protected readonly limit: number;
|
|
39
|
+
protected readonly inflate: boolean;
|
|
40
|
+
protected readonly strict: boolean;
|
|
41
|
+
protected readonly parameterLimit: number;
|
|
42
|
+
protected readonly depth: number;
|
|
43
|
+
|
|
44
|
+
constructor(protected readonly options: BodyOptions = {}) {
|
|
45
|
+
this.limit = parseBytes(options.limit ?? '100kb');
|
|
46
|
+
this.inflate = options.inflate !== false;
|
|
47
|
+
this.strict = options.strict !== false;
|
|
48
|
+
this.parameterLimit = options.parameterLimit ?? 1000;
|
|
49
|
+
this.depth = options.depth ?? 32;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async parse(request: any, response?: any): Promise<void> {
|
|
53
|
+
if (request._body) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
request.body = request.body || {};
|
|
57
|
+
const headers = request.headers;
|
|
58
|
+
if (headers['transfer-encoding'] === undefined && isNaN(headers['content-length'])) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const { type, charset } = this.contentType(headers['content-type']);
|
|
62
|
+
const bodyType = TYPES[type];
|
|
63
|
+
if (!bodyType) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const encoding = bodyType === 'raw' ? 'binary' : this.charset(bodyType, charset);
|
|
67
|
+
const body = await this.read(request, headers);
|
|
68
|
+
if (this.options.verify) {
|
|
69
|
+
try {
|
|
70
|
+
this.options.verify(request, response, body, encoding);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
throw new HttpError(403, (error as Error).message);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
request.body = this.convert(bodyType, body, encoding);
|
|
76
|
+
request._body = true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
protected contentType(header: string | undefined): { type: string, charset?: string } {
|
|
80
|
+
if (!header) {
|
|
81
|
+
return { type: '' };
|
|
82
|
+
}
|
|
83
|
+
const [type, ...params] = header.split(';');
|
|
84
|
+
let charset: string | undefined;
|
|
85
|
+
for (const param of params) {
|
|
86
|
+
const equals = param.indexOf('=');
|
|
87
|
+
if (equals > 0 && param.slice(0, equals).trim().toLowerCase() === 'charset') {
|
|
88
|
+
charset = param.slice(equals + 1).trim().replace(/^"(.*)"$/, '$1').toLowerCase();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return { type: type.trim().toLowerCase(), charset };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
protected charset(type: BodyType, charset = 'utf-8'): string {
|
|
95
|
+
const supported = type === 'json' ? charset.startsWith('utf-')
|
|
96
|
+
: type === 'urlencoded' ? charset === 'utf-8'
|
|
97
|
+
: this.isKnownCharset(charset);
|
|
98
|
+
if (!supported) {
|
|
99
|
+
throw new HttpError(415, `unsupported charset "${charset.toUpperCase()}"`);
|
|
100
|
+
}
|
|
101
|
+
return charset;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
protected isKnownCharset(charset: string): boolean {
|
|
105
|
+
try {
|
|
106
|
+
new TextDecoder(charset);
|
|
107
|
+
return true;
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
protected convert(type: BodyType, body: Buffer, charset: string): unknown {
|
|
114
|
+
if (type === 'raw') {
|
|
115
|
+
return body;
|
|
116
|
+
}
|
|
117
|
+
const text = charset === 'utf-8' || charset === 'utf8' ? body.toString('utf8') : new TextDecoder(charset).decode(body);
|
|
118
|
+
if (type === 'text') {
|
|
119
|
+
return text;
|
|
120
|
+
}
|
|
121
|
+
if (type === 'urlencoded') {
|
|
122
|
+
try {
|
|
123
|
+
return FormUtil.parse(text, { parameterLimit: this.parameterLimit, depth: this.depth });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
throw new HttpError(413, (error as Error).message);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (text.length === 0) {
|
|
129
|
+
return {};
|
|
130
|
+
}
|
|
131
|
+
if (this.strict) {
|
|
132
|
+
const first = /^[\x20\x09\x0a\x0d]*(.)/.exec(text)?.[1];
|
|
133
|
+
if (first !== '{' && first !== '[') {
|
|
134
|
+
throw new HttpError(400, 'JSON body must be an object or an array');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
return JSON.parse(text);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
throw new HttpError(400, (error as Error).message);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
protected decoder(request: Readable, encoding: string): Readable {
|
|
145
|
+
if (encoding === 'identity') {
|
|
146
|
+
return request;
|
|
147
|
+
}
|
|
148
|
+
if (!this.inflate) {
|
|
149
|
+
throw new HttpError(415, `content encoding unsupported: ${encoding}`);
|
|
150
|
+
}
|
|
151
|
+
const decompress = encoding === 'gzip' ? createGunzip() : encoding === 'deflate' ? createInflate() : encoding === 'br' ? createBrotliDecompress() : undefined;
|
|
152
|
+
if (!decompress) {
|
|
153
|
+
throw new HttpError(415, `unsupported content encoding "${encoding}"`);
|
|
154
|
+
}
|
|
155
|
+
request.pipe(decompress);
|
|
156
|
+
return decompress;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The body, decompressed, at most `limit` bytes. */
|
|
160
|
+
protected read(request: Readable, headers: Record<string, any>): Promise<Buffer> {
|
|
161
|
+
const encoding = String(headers['content-encoding'] || 'identity').toLowerCase();
|
|
162
|
+
const length = encoding === 'identity' && headers['content-length'] !== undefined ? Number(headers['content-length']) : undefined;
|
|
163
|
+
if (length !== undefined && length > this.limit) {
|
|
164
|
+
request.resume();
|
|
165
|
+
return Promise.reject(new HttpError(413, 'request entity too large'));
|
|
166
|
+
}
|
|
167
|
+
let stream: Readable;
|
|
168
|
+
try {
|
|
169
|
+
stream = this.decoder(request, encoding);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
request.resume();
|
|
172
|
+
return Promise.reject(error);
|
|
173
|
+
}
|
|
174
|
+
return new Promise<Buffer>((resolve, reject) => {
|
|
175
|
+
const chunks: Buffer[] = [];
|
|
176
|
+
let received = 0;
|
|
177
|
+
let done = false;
|
|
178
|
+
const finish = (error?: Error) => {
|
|
179
|
+
if (done) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
done = true;
|
|
183
|
+
stream.off('data', onData);
|
|
184
|
+
stream.off('end', onEnd);
|
|
185
|
+
stream.off('error', onError);
|
|
186
|
+
request.off('aborted', onAborted);
|
|
187
|
+
if (error) {
|
|
188
|
+
if (stream !== request) {
|
|
189
|
+
request.unpipe(stream as unknown as NodeJS.WritableStream);
|
|
190
|
+
stream.destroy();
|
|
191
|
+
}
|
|
192
|
+
request.resume();
|
|
193
|
+
reject(error);
|
|
194
|
+
} else {
|
|
195
|
+
resolve(chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, received));
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
const onData = (chunk: Buffer | string) => {
|
|
199
|
+
const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
|
|
200
|
+
received += buffer.length;
|
|
201
|
+
if (received > this.limit) {
|
|
202
|
+
finish(new HttpError(413, 'request entity too large'));
|
|
203
|
+
} else {
|
|
204
|
+
chunks.push(buffer);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
const onEnd = () => finish(length !== undefined && received !== length ? new HttpError(400, 'request size did not match content length') : undefined);
|
|
208
|
+
const onError = (error: Error) => finish(new HttpError(400, error.message));
|
|
209
|
+
const onAborted = () => finish(new HttpError(400, 'request aborted'));
|
|
210
|
+
stream.on('data', onData);
|
|
211
|
+
stream.once('end', onEnd);
|
|
212
|
+
stream.once('error', onError);
|
|
213
|
+
request.once('aborted', onAborted);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
@@ -2,3 +2,18 @@ import { CORS_MIDDLEWARE_PRIORITY } from '../cors';
|
|
|
2
2
|
|
|
3
3
|
export const BODY_MIDDLEWARE_PRIORITY = CORS_MIDDLEWARE_PRIORITY - 100;
|
|
4
4
|
|
|
5
|
+
/** `cell.web.body`: how request bodies are read. */
|
|
6
|
+
export interface BodyOptions {
|
|
7
|
+
/** Largest body, in bytes or as `'100kb'`, `'5mb'` (after decompression). Default `'100kb'`. */
|
|
8
|
+
limit?: number | string;
|
|
9
|
+
/** Decompress gzip, deflate and br bodies; when false they are refused with 415. Default true. */
|
|
10
|
+
inflate?: boolean;
|
|
11
|
+
/** JSON bodies must be an object or an array. Default true. */
|
|
12
|
+
strict?: boolean;
|
|
13
|
+
/** Most parameters in a form body. Default 1000. */
|
|
14
|
+
parameterLimit?: number;
|
|
15
|
+
/** Most levels of `a[b][c]` nesting in a form body; deeper keys stay as they are. Default 32. */
|
|
16
|
+
depth?: number;
|
|
17
|
+
/** Called with the raw body before it is parsed; throwing refuses the request with 403. */
|
|
18
|
+
verify?: (request: any, response: any, body: Buffer, charset: string) => void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { FormUtil } from './form-util';
|
|
4
|
+
|
|
5
|
+
describe('FormUtil.parse', () => {
|
|
6
|
+
// What qs.parse returned with the options body-parser gave it (extended: true).
|
|
7
|
+
const cases: [string, unknown][] = [
|
|
8
|
+
['a=1&b=2', { a: '1', b: '2' }],
|
|
9
|
+
['a=1&a=2', { a: ['1', '2'] }],
|
|
10
|
+
['a[b]=1&a[c]=2', { a: { b: '1', c: '2' } }],
|
|
11
|
+
['a[]=1&a[]=2', { a: ['1', '2'] }],
|
|
12
|
+
['a[0]=x&a[1]=y', { a: ['x', 'y'] }],
|
|
13
|
+
['a[1]=x', { a: ['x'] }],
|
|
14
|
+
['a[25]=x', { a: ['x'] }],
|
|
15
|
+
['a[200]=x', { a: { 200: 'x' } }],
|
|
16
|
+
['x=a+b%20c', { x: 'a b c' }],
|
|
17
|
+
['k', { k: '' }],
|
|
18
|
+
['a[b][c][d]=1', { a: { b: { c: { d: '1' } } } }],
|
|
19
|
+
['__proto__[x]=1&ok=1', { ok: '1' }],
|
|
20
|
+
['a=%E4%BD%A0', { a: '你' }],
|
|
21
|
+
['a[]=1&a[b]=2', { a: { 0: '1', b: '2' } }],
|
|
22
|
+
['=v&k=', { k: '' }],
|
|
23
|
+
['a=%ZZ', { a: '%ZZ' }],
|
|
24
|
+
['arr[]=a&arr[]=b&arr[]=c', { arr: ['a', 'b', 'c'] }],
|
|
25
|
+
['', {}]
|
|
26
|
+
];
|
|
27
|
+
for (const [text, expected] of cases) {
|
|
28
|
+
it(`parses ${JSON.stringify(text)} as qs did`, () => {
|
|
29
|
+
expect(FormUtil.parse(text)).to.deep.equal(expected);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
it('does not touch Object.prototype', () => {
|
|
34
|
+
FormUtil.parse('__proto__[polluted]=1&constructor[prototype][polluted]=1&a[__proto__][polluted]=1');
|
|
35
|
+
expect(({} as Record<string, unknown>).polluted).to.equal(undefined);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('keeps levels past depth together', () => {
|
|
39
|
+
expect(FormUtil.parse('a[b][c]=1', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': '1' } } });
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('refuses too many parameters', () => {
|
|
43
|
+
expect(() => FormUtil.parse('a=1&b=2&c=3', { parameterLimit: 2 })).to.throw(RangeError);
|
|
44
|
+
});
|
|
45
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
2
|
+
|
|
3
|
+
function decode(text: string): string {
|
|
4
|
+
const value = text.replace(/\+/g, ' ');
|
|
5
|
+
try {
|
|
6
|
+
return decodeURIComponent(value);
|
|
7
|
+
} catch {
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** `a[b][]` → `['a', 'b', '']`; levels past `depth` stay together in the last key. */
|
|
13
|
+
function splitKey(key: string, depth: number): string[] {
|
|
14
|
+
const open = key.indexOf('[');
|
|
15
|
+
if (open <= 0) {
|
|
16
|
+
return [key];
|
|
17
|
+
}
|
|
18
|
+
const keys = [key.slice(0, open)];
|
|
19
|
+
const segment = /\[([^[\]]*)\]/g;
|
|
20
|
+
segment.lastIndex = open;
|
|
21
|
+
let end = open;
|
|
22
|
+
let match: RegExpExecArray | null;
|
|
23
|
+
while (keys.length <= depth && (match = segment.exec(key)) && match.index === end) {
|
|
24
|
+
keys.push(match[1]);
|
|
25
|
+
end = segment.lastIndex;
|
|
26
|
+
}
|
|
27
|
+
if (end < key.length) {
|
|
28
|
+
keys.push(key.slice(end));
|
|
29
|
+
}
|
|
30
|
+
return keys;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isIndex(key: string, arrayLimit: number): boolean {
|
|
34
|
+
return /^\d+$/.test(key) && Number(key) <= arrayLimit;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** An array that is about to get a named key becomes an object with its indexes as keys. */
|
|
38
|
+
function toObject(value: unknown[]): Record<string, unknown> {
|
|
39
|
+
const object: Record<string, unknown> = {};
|
|
40
|
+
value.forEach((item, i) => {
|
|
41
|
+
if (item !== undefined) {
|
|
42
|
+
object[i] = item;
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
return object;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function assign(target: any, keys: string[], value: string, arrayLimit: number): any {
|
|
49
|
+
const [key, ...rest] = keys;
|
|
50
|
+
if (key === undefined) {
|
|
51
|
+
return target === undefined ? value : Array.isArray(target) ? [...target, value] : [target, value];
|
|
52
|
+
}
|
|
53
|
+
if (Array.isArray(target)) {
|
|
54
|
+
if (key === '') {
|
|
55
|
+
target.push(assign(undefined, rest, value, arrayLimit));
|
|
56
|
+
return target;
|
|
57
|
+
}
|
|
58
|
+
if (!isIndex(key, arrayLimit)) {
|
|
59
|
+
target = toObject(target);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (target === undefined || typeof target !== 'object') {
|
|
63
|
+
if (key === '' || isIndex(key, arrayLimit)) {
|
|
64
|
+
target = [];
|
|
65
|
+
if (key === '') {
|
|
66
|
+
target.push(assign(undefined, rest, value, arrayLimit));
|
|
67
|
+
return target;
|
|
68
|
+
}
|
|
69
|
+
} else {
|
|
70
|
+
target = {};
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
target[key] = assign(target[key], rest, value, arrayLimit);
|
|
74
|
+
return target;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function compact(value: any): any {
|
|
78
|
+
if (Array.isArray(value)) {
|
|
79
|
+
return value.filter(item => item !== undefined).map(compact);
|
|
80
|
+
}
|
|
81
|
+
if (value && typeof value === 'object') {
|
|
82
|
+
for (const key of Object.keys(value)) {
|
|
83
|
+
value[key] = compact(value[key]);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export namespace FormUtil {
|
|
90
|
+
|
|
91
|
+
export interface ParseOptions {
|
|
92
|
+
/** Most parameters; more throw a `RangeError`. */
|
|
93
|
+
parameterLimit?: number;
|
|
94
|
+
/** Most levels of nesting. */
|
|
95
|
+
depth?: number;
|
|
96
|
+
/** Largest index that makes an array: `a[200]=x` makes `{ 200: 'x' }`. */
|
|
97
|
+
arrayLimit?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* `application/x-www-form-urlencoded` with the brackets of PHP and qs: `a[b]=1` → `{ a: { b: '1' } }`,
|
|
102
|
+
* `a[]=1&a[]=2` and `a=1&a=2` → `{ a: ['1', '2'] }`. `__proto__`, `constructor` and `prototype` keys are dropped.
|
|
103
|
+
*/
|
|
104
|
+
export function parse(text: string, { parameterLimit = 1000, depth = 32, arrayLimit = 100 }: ParseOptions = {}): Record<string, any> {
|
|
105
|
+
const result: Record<string, any> = {};
|
|
106
|
+
if (!text) {
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
const pairs = text.split('&');
|
|
110
|
+
if (pairs.length > parameterLimit) {
|
|
111
|
+
throw new RangeError('too many parameters');
|
|
112
|
+
}
|
|
113
|
+
for (const pair of pairs) {
|
|
114
|
+
if (!pair) {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const equals = pair.indexOf('=');
|
|
118
|
+
const key = decode(equals < 0 ? pair : pair.slice(0, equals));
|
|
119
|
+
if (!key) {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const value = equals < 0 ? '' : decode(pair.slice(equals + 1));
|
|
123
|
+
const keys = splitKey(key, depth);
|
|
124
|
+
if (keys.some(k => UNSAFE_KEYS.has(k))) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const [first, ...rest] = keys;
|
|
128
|
+
result[first] = assign(result[first], rest, value, arrayLimit);
|
|
129
|
+
}
|
|
130
|
+
return compact(result);
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/node/body/index.ts
CHANGED
package/src/node/context.ts
CHANGED
|
@@ -80,7 +80,7 @@ export class Context extends BaseContext {
|
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
static override getAttr<T>(key: string, scope?: AttributeScope): T {
|
|
83
|
-
if (scope) {
|
|
83
|
+
if (scope !== undefined) {
|
|
84
84
|
if (scope === AttributeScope.Session) {
|
|
85
85
|
return Context.getSession()[key];
|
|
86
86
|
} else {
|