@celljs/web 4.1.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.
Files changed (262) hide show
  1. package/README.md +39 -1
  2. package/cell.yml +0 -3
  3. package/esm/browser/module.d.ts +1 -1
  4. package/esm/common/module.d.ts +1 -1
  5. package/esm/common/pipe/index.d.ts +1 -1
  6. package/esm/common/pipe/index.js +1 -1
  7. package/esm/common/pipe/index.js.map +1 -1
  8. package/esm/common/pipe/type-conversion-pipe.d.ts +12 -0
  9. package/esm/common/pipe/type-conversion-pipe.js +43 -0
  10. package/esm/common/pipe/type-conversion-pipe.js.map +1 -0
  11. package/esm/common/pipe/validation-errors.d.ts +11 -2
  12. package/esm/common/pipe/validation-errors.js +2 -0
  13. package/esm/common/pipe/validation-errors.js.map +1 -1
  14. package/esm/node/body/body-middleware.d.ts +4 -6
  15. package/esm/node/body/body-middleware.js +6 -16
  16. package/esm/node/body/body-middleware.js.map +1 -1
  17. package/esm/node/body/body-parser.d.ts +32 -0
  18. package/esm/node/body/body-parser.js +205 -0
  19. package/esm/node/body/body-parser.js.map +1 -0
  20. package/esm/node/body/body-protocol.d.ts +15 -0
  21. package/esm/node/body/form-util.d.ts +15 -0
  22. package/esm/node/body/form-util.js +120 -0
  23. package/esm/node/body/form-util.js.map +1 -0
  24. package/esm/node/body/index.d.ts +2 -0
  25. package/esm/node/body/index.js +2 -0
  26. package/esm/node/body/index.js.map +1 -1
  27. package/esm/node/cookies/cookies-factory.js +2 -6
  28. package/esm/node/cookies/cookies-factory.js.map +1 -1
  29. package/esm/node/cookies/cookies-protocol.d.ts +25 -2
  30. package/esm/node/cookies/cookies.d.ts +17 -0
  31. package/esm/node/cookies/cookies.js +137 -0
  32. package/esm/node/cookies/cookies.js.map +1 -0
  33. package/esm/node/cookies/index.d.ts +1 -0
  34. package/esm/node/cookies/index.js +1 -0
  35. package/esm/node/cookies/index.js.map +1 -1
  36. package/esm/node/cors/cors-middleware.d.ts +11 -3
  37. package/esm/node/cors/cors-middleware.js +108 -14
  38. package/esm/node/cors/cors-middleware.js.map +1 -1
  39. package/esm/node/cors/cors-protocol.d.ts +23 -0
  40. package/esm/node/error/error-handler-provider.js +3 -7
  41. package/esm/node/error/error-handler-provider.js.map +1 -1
  42. package/esm/node/health/health-middleware.js +1 -1
  43. package/esm/node/health/health-middleware.js.map +1 -1
  44. package/esm/node/http/http-protocol.d.ts +29 -5
  45. package/esm/node/http/http-protocol.js.map +1 -1
  46. package/esm/node/http/http-request.d.ts +41 -0
  47. package/esm/node/http/http-request.js +106 -0
  48. package/esm/node/http/http-request.js.map +1 -0
  49. package/esm/node/http/index.d.ts +1 -0
  50. package/esm/node/http/index.js +1 -0
  51. package/esm/node/http/index.js.map +1 -1
  52. package/esm/node/index.d.ts +1 -0
  53. package/esm/node/index.js +1 -0
  54. package/esm/node/index.js.map +1 -1
  55. package/esm/node/matcher/index.d.ts +1 -0
  56. package/esm/node/matcher/index.js +1 -0
  57. package/esm/node/matcher/index.js.map +1 -1
  58. package/esm/node/matcher/path-pattern.d.ts +23 -0
  59. package/esm/node/matcher/path-pattern.js +115 -0
  60. package/esm/node/matcher/path-pattern.js.map +1 -0
  61. package/esm/node/matcher/request-matcher.d.ts +2 -2
  62. package/esm/node/matcher/request-matcher.js +8 -9
  63. package/esm/node/matcher/request-matcher.js.map +1 -1
  64. package/esm/node/module.d.ts +1 -1
  65. package/esm/node/server/http-server.d.ts +13 -0
  66. package/esm/node/server/http-server.js +32 -0
  67. package/esm/node/server/http-server.js.map +1 -0
  68. package/esm/node/server/index.d.ts +1 -0
  69. package/esm/node/server/index.js +2 -0
  70. package/esm/node/server/index.js.map +1 -0
  71. package/esm/node/session/session-manager.js +1 -2
  72. package/esm/node/session/session-manager.js.map +1 -1
  73. package/esm/node/session/session-store.js +1 -2
  74. package/esm/node/session/session-store.js.map +1 -1
  75. package/esm/node/session/session.d.ts +3 -2
  76. package/esm/node/session/session.js +4 -10
  77. package/esm/node/session/session.js.map +1 -1
  78. package/lib/browser/module.d.ts +1 -1
  79. package/lib/common/module.d.ts +1 -1
  80. package/lib/common/pipe/index.d.ts +1 -1
  81. package/lib/common/pipe/index.d.ts.map +1 -1
  82. package/lib/common/pipe/index.js +1 -1
  83. package/lib/common/pipe/index.js.map +1 -1
  84. package/lib/common/pipe/type-conversion-pipe.d.ts +13 -0
  85. package/lib/common/pipe/type-conversion-pipe.d.ts.map +1 -0
  86. package/lib/common/pipe/type-conversion-pipe.js +46 -0
  87. package/lib/common/pipe/type-conversion-pipe.js.map +1 -0
  88. package/lib/common/pipe/type-conversion-pipe.spec.d.ts +2 -0
  89. package/lib/common/pipe/type-conversion-pipe.spec.d.ts.map +1 -0
  90. package/lib/common/pipe/type-conversion-pipe.spec.js +36 -0
  91. package/lib/common/pipe/type-conversion-pipe.spec.js.map +1 -0
  92. package/lib/common/pipe/validation-errors.d.ts +11 -2
  93. package/lib/common/pipe/validation-errors.d.ts.map +1 -1
  94. package/lib/common/pipe/validation-errors.js +2 -0
  95. package/lib/common/pipe/validation-errors.js.map +1 -1
  96. package/lib/node/body/body-middleware.d.ts +4 -6
  97. package/lib/node/body/body-middleware.d.ts.map +1 -1
  98. package/lib/node/body/body-middleware.js +4 -13
  99. package/lib/node/body/body-middleware.js.map +1 -1
  100. package/lib/node/body/body-middleware.spec.js +78 -12
  101. package/lib/node/body/body-middleware.spec.js.map +1 -1
  102. package/lib/node/body/body-parser.d.ts +33 -0
  103. package/lib/node/body/body-parser.d.ts.map +1 -0
  104. package/lib/node/body/body-parser.js +210 -0
  105. package/lib/node/body/body-parser.js.map +1 -0
  106. package/lib/node/body/body-protocol.d.ts +15 -0
  107. package/lib/node/body/body-protocol.d.ts.map +1 -1
  108. package/lib/node/body/form-util.d.ts +16 -0
  109. package/lib/node/body/form-util.d.ts.map +1 -0
  110. package/lib/node/body/form-util.js +123 -0
  111. package/lib/node/body/form-util.js.map +1 -0
  112. package/lib/node/body/form-util.spec.d.ts +2 -0
  113. package/lib/node/body/form-util.spec.d.ts.map +1 -0
  114. package/lib/node/body/form-util.spec.js +44 -0
  115. package/lib/node/body/form-util.spec.js.map +1 -0
  116. package/lib/node/body/index.d.ts +2 -0
  117. package/lib/node/body/index.d.ts.map +1 -1
  118. package/lib/node/body/index.js +2 -0
  119. package/lib/node/body/index.js.map +1 -1
  120. package/lib/node/cookies/cookies-factory.d.ts.map +1 -1
  121. package/lib/node/cookies/cookies-factory.js +2 -9
  122. package/lib/node/cookies/cookies-factory.js.map +1 -1
  123. package/lib/node/cookies/cookies-protocol.d.ts +25 -2
  124. package/lib/node/cookies/cookies-protocol.d.ts.map +1 -1
  125. package/lib/node/cookies/cookies.d.ts +18 -0
  126. package/lib/node/cookies/cookies.d.ts.map +1 -0
  127. package/lib/node/cookies/cookies.js +141 -0
  128. package/lib/node/cookies/cookies.js.map +1 -0
  129. package/lib/node/cookies/cookies.spec.d.ts +2 -0
  130. package/lib/node/cookies/cookies.spec.d.ts.map +1 -0
  131. package/lib/node/cookies/cookies.spec.js +73 -0
  132. package/lib/node/cookies/cookies.spec.js.map +1 -0
  133. package/lib/node/cookies/index.d.ts +1 -0
  134. package/lib/node/cookies/index.d.ts.map +1 -1
  135. package/lib/node/cookies/index.js +1 -0
  136. package/lib/node/cookies/index.js.map +1 -1
  137. package/lib/node/cors/cors-middleware.d.ts +11 -3
  138. package/lib/node/cors/cors-middleware.d.ts.map +1 -1
  139. package/lib/node/cors/cors-middleware.js +106 -15
  140. package/lib/node/cors/cors-middleware.js.map +1 -1
  141. package/lib/node/cors/cors-middleware.spec.d.ts +2 -0
  142. package/lib/node/cors/cors-middleware.spec.d.ts.map +1 -0
  143. package/lib/node/cors/cors-middleware.spec.js +56 -0
  144. package/lib/node/cors/cors-middleware.spec.js.map +1 -0
  145. package/lib/node/cors/cors-protocol.d.ts +23 -0
  146. package/lib/node/cors/cors-protocol.d.ts.map +1 -1
  147. package/lib/node/error/error-handler-provider.d.ts.map +1 -1
  148. package/lib/node/error/error-handler-provider.js +2 -5
  149. package/lib/node/error/error-handler-provider.js.map +1 -1
  150. package/lib/node/health/health-middleware.js +1 -1
  151. package/lib/node/health/health-middleware.js.map +1 -1
  152. package/lib/node/http/http-protocol.d.ts +29 -5
  153. package/lib/node/http/http-protocol.d.ts.map +1 -1
  154. package/lib/node/http/http-protocol.js.map +1 -1
  155. package/lib/node/http/http-request.d.ts +42 -0
  156. package/lib/node/http/http-request.d.ts.map +1 -0
  157. package/lib/node/http/http-request.js +110 -0
  158. package/lib/node/http/http-request.js.map +1 -0
  159. package/lib/node/http/http-request.spec.d.ts +2 -0
  160. package/lib/node/http/http-request.spec.d.ts.map +1 -0
  161. package/lib/node/http/http-request.spec.js +65 -0
  162. package/lib/node/http/http-request.spec.js.map +1 -0
  163. package/lib/node/http/index.d.ts +1 -0
  164. package/lib/node/http/index.d.ts.map +1 -1
  165. package/lib/node/http/index.js +1 -0
  166. package/lib/node/http/index.js.map +1 -1
  167. package/lib/node/index.d.ts +1 -0
  168. package/lib/node/index.d.ts.map +1 -1
  169. package/lib/node/index.js +1 -0
  170. package/lib/node/index.js.map +1 -1
  171. package/lib/node/matcher/index.d.ts +1 -0
  172. package/lib/node/matcher/index.d.ts.map +1 -1
  173. package/lib/node/matcher/index.js +1 -0
  174. package/lib/node/matcher/index.js.map +1 -1
  175. package/lib/node/matcher/path-pattern.d.ts +24 -0
  176. package/lib/node/matcher/path-pattern.d.ts.map +1 -0
  177. package/lib/node/matcher/path-pattern.js +119 -0
  178. package/lib/node/matcher/path-pattern.js.map +1 -0
  179. package/lib/node/matcher/path-pattern.spec.d.ts +2 -0
  180. package/lib/node/matcher/path-pattern.spec.d.ts.map +1 -0
  181. package/lib/node/matcher/path-pattern.spec.js +43 -0
  182. package/lib/node/matcher/path-pattern.spec.js.map +1 -0
  183. package/lib/node/matcher/request-matcher.d.ts +2 -2
  184. package/lib/node/matcher/request-matcher.d.ts.map +1 -1
  185. package/lib/node/matcher/request-matcher.js +8 -12
  186. package/lib/node/matcher/request-matcher.js.map +1 -1
  187. package/lib/node/module.d.ts +1 -1
  188. package/lib/node/server/http-server.d.ts +14 -0
  189. package/lib/node/server/http-server.d.ts.map +1 -0
  190. package/lib/node/server/http-server.js +35 -0
  191. package/lib/node/server/http-server.js.map +1 -0
  192. package/lib/node/server/http-server.spec.d.ts +2 -0
  193. package/lib/node/server/http-server.spec.d.ts.map +1 -0
  194. package/lib/node/server/http-server.spec.js +41 -0
  195. package/lib/node/server/http-server.spec.js.map +1 -0
  196. package/lib/node/server/index.d.ts +2 -0
  197. package/lib/node/server/index.d.ts.map +1 -0
  198. package/lib/node/server/index.js +18 -0
  199. package/lib/node/server/index.js.map +1 -0
  200. package/lib/node/session/session-manager.d.ts.map +1 -1
  201. package/lib/node/session/session-manager.js +1 -2
  202. package/lib/node/session/session-manager.js.map +1 -1
  203. package/lib/node/session/session-store.d.ts.map +1 -1
  204. package/lib/node/session/session-store.js +1 -2
  205. package/lib/node/session/session-store.js.map +1 -1
  206. package/lib/node/session/session.d.ts +3 -2
  207. package/lib/node/session/session.d.ts.map +1 -1
  208. package/lib/node/session/session.js +4 -43
  209. package/lib/node/session/session.js.map +1 -1
  210. package/lib/node/session/session.spec.js +7 -1
  211. package/lib/node/session/session.spec.js.map +1 -1
  212. package/package.json +10 -15
  213. package/src/common/pipe/index.ts +1 -1
  214. package/src/common/pipe/type-conversion-pipe.spec.ts +38 -0
  215. package/src/common/pipe/type-conversion-pipe.ts +36 -0
  216. package/src/common/pipe/validation-errors.ts +11 -2
  217. package/src/node/body/body-middleware.spec.ts +93 -14
  218. package/src/node/body/body-middleware.ts +9 -18
  219. package/src/node/body/body-parser.ts +216 -0
  220. package/src/node/body/body-protocol.ts +15 -0
  221. package/src/node/body/form-util.spec.ts +45 -0
  222. package/src/node/body/form-util.ts +132 -0
  223. package/src/node/body/index.ts +2 -0
  224. package/src/node/cookies/cookies-factory.ts +2 -6
  225. package/src/node/cookies/cookies-protocol.ts +28 -3
  226. package/src/node/cookies/cookies.spec.ts +80 -0
  227. package/src/node/cookies/cookies.ts +138 -0
  228. package/src/node/cookies/index.ts +1 -0
  229. package/src/node/cors/cors-middleware.spec.ts +59 -0
  230. package/src/node/cors/cors-middleware.ts +112 -15
  231. package/src/node/cors/cors-protocol.ts +25 -0
  232. package/src/node/error/error-handler-provider.ts +1 -2
  233. package/src/node/health/health-middleware.ts +1 -1
  234. package/src/node/http/http-protocol.ts +29 -5
  235. package/src/node/http/http-request.spec.ts +68 -0
  236. package/src/node/http/http-request.ts +132 -0
  237. package/src/node/http/index.ts +1 -0
  238. package/src/node/index.ts +1 -0
  239. package/src/node/matcher/index.ts +1 -0
  240. package/src/node/matcher/path-pattern.spec.ts +43 -0
  241. package/src/node/matcher/path-pattern.ts +113 -0
  242. package/src/node/matcher/request-matcher.ts +9 -10
  243. package/src/node/server/http-server.spec.ts +45 -0
  244. package/src/node/server/http-server.ts +35 -0
  245. package/src/node/server/index.ts +1 -0
  246. package/src/node/session/session-manager.ts +1 -2
  247. package/src/node/session/session-store.ts +1 -2
  248. package/src/node/session/session.spec.ts +8 -1
  249. package/src/node/session/session.ts +6 -12
  250. package/esm/common/pipe/pipe-transtorm.d.ts +0 -17
  251. package/esm/common/pipe/pipe-transtorm.js +0 -110
  252. package/esm/common/pipe/pipe-transtorm.js.map +0 -1
  253. package/lib/common/pipe/pipe-transtorm.d.ts +0 -18
  254. package/lib/common/pipe/pipe-transtorm.d.ts.map +0 -1
  255. package/lib/common/pipe/pipe-transtorm.js +0 -113
  256. package/lib/common/pipe/pipe-transtorm.js.map +0 -1
  257. package/lib/common/pipe/pipe-transtorm.spec.d.ts +0 -2
  258. package/lib/common/pipe/pipe-transtorm.spec.d.ts.map +0 -1
  259. package/lib/common/pipe/pipe-transtorm.spec.js +0 -69
  260. package/lib/common/pipe/pipe-transtorm.spec.js.map +0 -1
  261. package/src/common/pipe/pipe-transtorm.spec.ts +0 -62
  262. package/src/common/pipe/pipe-transtorm.ts +0 -113
@@ -1,17 +1,96 @@
1
- import { describe, it } from 'bun:test';
1
+ import { afterAll, beforeAll, describe, it } from 'bun:test';
2
2
  import { expect } from 'chai';
3
- import { BodyMiddleware } from './body-middleware';
4
-
5
- describe('BodyMiddleware', () => {
6
- it('makes its parsers once, not per request', async () => {
7
- const middleware = new BodyMiddleware();
8
- const seen: unknown[] = [];
9
- Object.assign(middleware, { options: { limit: '1kb' }, handlerExecutionChain: { execute: async (parsers: unknown[]) => { seen.push(parsers); } } });
10
- (middleware as unknown as { init(): void }).init();
11
- await middleware.handle({} as any, async () => undefined);
12
- await middleware.handle({} as any, async () => undefined);
13
- expect(seen).to.have.length(2);
14
- expect(seen[0]).to.have.length(4);
15
- expect(seen[1]).to.equal(seen[0]);
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
+ }
16
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}/`;
17
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,34 +1,25 @@
1
- import { convertExpressMiddleware, Middleware } from '../middleware';
1
+ import { Middleware } from '../middleware';
2
2
  import { Context } from '../context';
3
- import { Component, Autowired, Value, PostConstruct } from '@celljs/core';
4
- import { json, text, raw, urlencoded, Options } from 'body-parser';
5
- import { BODY_MIDDLEWARE_PRIORITY } from './body-protocol';
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: Options;
11
+ protected readonly options?: BodyOptions;
16
12
 
17
- /** The four parsers, made once: making them per request cost a noticeable share of each request. */
18
- protected parsers: Middleware[];
13
+ protected parser: BodyParser;
19
14
 
20
15
  @PostConstruct()
21
16
  protected init(): void {
22
- this.parsers = [
23
- convertExpressMiddleware(json({ ...this.options })),
24
- convertExpressMiddleware(text({ ...this.options })),
25
- convertExpressMiddleware(raw({ ...this.options })),
26
- convertExpressMiddleware(urlencoded({ ...this.options, ...{ extended: true } }))
27
- ];
17
+ this.parser = new BodyParser(this.options);
28
18
  }
29
19
 
30
20
  async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
31
- return this.handlerExecutionChain.execute(this.parsers, next);
21
+ await this.parser.parse(ctx.request, ctx.response);
22
+ return next();
32
23
  }
33
24
 
34
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
+ }
@@ -1,2 +1,4 @@
1
1
  export * from './body-protocol';
2
+ export * from './body-parser';
2
3
  export * from './body-middleware';
4
+ export * from './form-util';
@@ -1,7 +1,7 @@
1
1
  import { Context } from '../context';
2
2
  import { Component, Value } from '@celljs/core';
3
- import _Cookies from 'cookies';
4
3
  import { Cookies } from './cookies-protocol';
4
+ import { CookiesImpl } from './cookies';
5
5
 
6
6
  @Component()
7
7
  export class CookiesFactory {
@@ -13,10 +13,6 @@ export class CookiesFactory {
13
13
  protected secure?: boolean;
14
14
 
15
15
  async create(): Promise<Cookies> {
16
- const cookies = new _Cookies(Context.getRequest() as any, Context.getResponse() as any, {
17
- keys: this.keys,
18
- secure: this.secure
19
- });
20
- return <Cookies>cookies;
16
+ return new CookiesImpl(Context.getRequest(), Context.getResponse(), this.keys, this.secure);
21
17
  }
22
18
  }
@@ -4,7 +4,32 @@ export const COOKIES_MIDDLEWARE_PRIORITY = HTTP_MIDDLEWARE_PRIORITY - 100;
4
4
 
5
5
  export const Cookies = Symbol('Cookies');
6
6
 
7
- export interface Cookies {
8
- get(name: string, opt?: any): string | undefined;
9
- set(name: string, vaule: string, opt?: any): void;
7
+ export interface CookieGetOptions {
8
+ /** Check the `<name>.sig` signature; default: whether `cell.cookies.keys` are set. Without options nothing is checked. */
9
+ signed?: boolean;
10
+ }
11
+
12
+ export interface CookieSetOptions extends CookieGetOptions {
13
+ /** Milliseconds from now; sets `expires`. */
14
+ maxAge?: number;
15
+ expires?: Date;
16
+ /** Default `/`. */
17
+ path?: string;
18
+ domain?: string;
19
+ /** Only over HTTPS; setting it on a plain HTTP request throws. */
20
+ secure?: boolean;
21
+ /** Default true. */
22
+ httpOnly?: boolean;
23
+ sameSite?: 'strict' | 'lax' | 'none' | boolean;
24
+ priority?: 'low' | 'medium' | 'high';
25
+ partitioned?: boolean;
26
+ /** Replace a cookie of the same name set earlier in this response. Default false. */
27
+ overwrite?: boolean;
28
+ /** Other keys (such as the session options) are ignored. */
29
+ [key: string]: unknown;
10
30
  }
31
+
32
+ export interface Cookies {
33
+ get(name: string, opts?: CookieGetOptions): string | undefined;
34
+ set(name: string, value?: string | null, opts?: CookieSetOptions): this;
35
+ }