@celljs/web 4.1.0 → 4.3.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
@@ -0,0 +1,80 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { CookiesImpl } from './cookies';
4
+
5
+ function response() {
6
+ const headers: Record<string, unknown> = {};
7
+ return {
8
+ getHeader: (name: string) => headers[name.toLowerCase()],
9
+ setHeader: (name: string, value: unknown) => { headers[name.toLowerCase()] = value; },
10
+ cookies: () => headers['set-cookie'] as string[]
11
+ };
12
+ }
13
+
14
+ function cookies(cookie?: string, keys?: string[], protocol = 'http') {
15
+ const res = response();
16
+ return { res, cookies: new CookiesImpl({ headers: { cookie }, protocol }, res, keys) };
17
+ }
18
+
19
+ describe('CookiesImpl', () => {
20
+ // keygrip(['abcdef']).sign('cell:sessionId=abc'): cookies signed by the cookies package stay valid.
21
+ const SIGNATURE = '7WK2earn8SWPa1NGaYYWW0FhmfU';
22
+
23
+ it('reads plain cookies', () => {
24
+ const { cookies: c } = cookies('a=1; b=two; c=');
25
+ expect(c.get('a')).to.equal('1');
26
+ expect(c.get('b')).to.equal('two');
27
+ expect(c.get('c')).to.equal('');
28
+ expect(c.get('d')).to.equal(undefined);
29
+ });
30
+
31
+ it('signs like keygrip', () => {
32
+ const { res, cookies: c } = cookies(undefined, ['abcdef', 'old']);
33
+ c.set('cell:sessionId', 'abc');
34
+ expect(res.cookies()).to.deep.equal([
35
+ 'cell:sessionId=abc; path=/; httponly',
36
+ `cell:sessionId.sig=${SIGNATURE}; path=/; httponly`
37
+ ]);
38
+ });
39
+
40
+ it('reads signed cookies and drops a bad signature', () => {
41
+ expect(cookies(`cell:sessionId=abc; cell:sessionId.sig=${SIGNATURE}`, ['abcdef']).cookies.get('cell:sessionId', {})).to.equal('abc');
42
+ const bad = cookies('cell:sessionId=abd; cell:sessionId.sig=' + SIGNATURE, ['abcdef']);
43
+ expect(bad.cookies.get('cell:sessionId', {})).to.equal(undefined);
44
+ expect(bad.res.cookies()).to.deep.equal(['cell:sessionId.sig=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; httponly']);
45
+ expect(cookies('cell:sessionId=abc', ['abcdef']).cookies.get('cell:sessionId', {})).to.equal(undefined);
46
+ expect(cookies('cell:sessionId=abc', ['abcdef']).cookies.get('cell:sessionId', { signed: false })).to.equal('abc');
47
+ // Like the cookies package, no options means no check.
48
+ expect(cookies('cell:sessionId=abc', ['abcdef']).cookies.get('cell:sessionId')).to.equal('abc');
49
+ });
50
+
51
+ it('signs again with the first key a cookie signed with an older one', () => {
52
+ const { res, cookies: c } = cookies(`cell:sessionId=abc; cell:sessionId.sig=${SIGNATURE}`, ['new', 'abcdef']);
53
+ expect(c.get('cell:sessionId', {})).to.equal('abc');
54
+ expect(res.cookies()).to.have.length(1);
55
+ expect(res.cookies()[0]).to.match(/^cell:sessionId\.sig=[\w-]+; path=\/; httponly$/);
56
+ expect(res.cookies()[0]).not.to.contain(SIGNATURE);
57
+ });
58
+
59
+ it('writes the attributes', () => {
60
+ const { res, cookies: c } = cookies(undefined, undefined, 'https');
61
+ c.set('a', 'b', { maxAge: 1000, domain: 'example.com', path: '/p', sameSite: 'lax', secure: true, httpOnly: false, priority: 'high', partitioned: true });
62
+ expect(res.cookies()[0]).to.match(/^a=b; path=\/p; expires=.+ GMT; domain=example\.com; priority=high; samesite=lax; secure; partitioned$/);
63
+ });
64
+
65
+ it('deletes with an empty value and overwrites on request', () => {
66
+ const { res, cookies: c } = cookies(undefined, ['k']);
67
+ c.set('a', 'b');
68
+ c.set('a', '', { overwrite: true });
69
+ expect(res.cookies()).to.have.length(2);
70
+ expect(res.cookies().every(cookie => cookie.includes('expires=Thu, 01 Jan 1970'))).to.equal(true);
71
+ });
72
+
73
+ it('refuses secure cookies over http and invalid values', () => {
74
+ const { cookies: c } = cookies();
75
+ expect(() => c.set('a', 'b', { secure: true })).to.throw('Cannot send secure cookie over unencrypted connection');
76
+ expect(() => c.set('a', 'b\n')).to.throw('argument value is invalid');
77
+ expect(() => c.set('a;b', 'c')).to.throw('argument name is invalid');
78
+ expect(() => c.set('a', 'b', { signed: true })).to.throw('.keys required for signed cookies');
79
+ });
80
+ });
@@ -0,0 +1,138 @@
1
+ import { createHmac, timingSafeEqual } from 'crypto';
2
+ import { CookieGetOptions, Cookies, CookieSetOptions } from './cookies-protocol';
3
+
4
+ /** RFC 7230 field-content: what a cookie name or value may hold. */
5
+ const FIELD_CONTENT = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
6
+ const SAME_SITE = /^(?:lax|none|strict)$/i;
7
+ const PRIORITY = /^(?:low|medium|high)$/i;
8
+
9
+ /** `(?:^|;) *<name>=([^;]*)` per cookie name; names come from code, so there are few. */
10
+ const PATTERNS = new Map<string, RegExp>();
11
+
12
+ /** Same signatures as keygrip (HMAC-SHA1, base64url): cookies signed by Cell 4.1 stay valid. */
13
+ function sign(data: string, key: string): string {
14
+ return createHmac('sha1', key).update(data).digest('base64url');
15
+ }
16
+
17
+ function equals(a: string, b: string): boolean {
18
+ const x = Buffer.from(a);
19
+ const y = Buffer.from(b);
20
+ return x.length === y.length && timingSafeEqual(x, y);
21
+ }
22
+
23
+ function escape(name: string): string {
24
+ return name.replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&');
25
+ }
26
+
27
+ /**
28
+ * Cookies of the current request and response. Signed cookies (when `cell.cookies.keys` are set) carry a
29
+ * `<name>.sig` cookie made with the first key; any of the keys verifies it, and a cookie signed with an
30
+ * older key is signed again with the first.
31
+ */
32
+ export class CookiesImpl implements Cookies {
33
+
34
+ constructor(protected readonly request: any, protected readonly response: any, protected readonly keys?: string[], protected readonly secure?: boolean) {
35
+ }
36
+
37
+ get(name: string, opts?: CookieGetOptions): string | undefined {
38
+ const header = this.request.headers.cookie as string | undefined;
39
+ if (!header) {
40
+ return;
41
+ }
42
+ const value = this.read(header, name);
43
+ // As the cookies package: the signature is only checked when options are passed.
44
+ const signed = opts?.signed ?? !!this.keys?.length;
45
+ if (value === undefined || !opts || !signed) {
46
+ return value;
47
+ }
48
+ const sigName = `${name}.sig`;
49
+ const signature = this.read(header, sigName);
50
+ if (!signature) {
51
+ return;
52
+ }
53
+ const index = this.keys ? this.keys.findIndex(key => equals(sign(`${name}=${value}`, key), signature)) : -1;
54
+ if (index < 0) {
55
+ this.set(sigName, null, { path: '/', signed: false });
56
+ return;
57
+ }
58
+ if (index > 0) {
59
+ this.set(sigName, sign(`${name}=${value}`, this.keys![0]), { signed: false });
60
+ }
61
+ return value;
62
+ }
63
+
64
+ set(name: string, value?: string | null, opts: CookieSetOptions = {}): this {
65
+ const secure = this.secure !== undefined ? this.secure : this.request.protocol === 'https' || !!this.request.connection?.encrypted;
66
+ if (!secure && opts.secure) {
67
+ throw new Error('Cannot send secure cookie over unencrypted connection');
68
+ }
69
+ const signed = opts.signed ?? !!this.keys?.length;
70
+ if (signed && !this.keys?.length) {
71
+ throw new Error('.keys required for signed cookies');
72
+ }
73
+ // An empty value deletes the cookie, and its signature with it.
74
+ const expires = !value ? new Date(0) : opts.maxAge ? new Date(Date.now() + opts.maxAge) : opts.expires;
75
+ const cookies = [this.serialize(name, value || '', expires, opts)];
76
+ if (signed) {
77
+ cookies.push(this.serialize(`${name}.sig`, sign(`${name}=${value || ''}`, this.keys![0]), expires, opts));
78
+ }
79
+ const existing = this.response.getHeader('Set-Cookie');
80
+ let headers: string[] = existing === undefined ? [] : Array.isArray(existing) ? existing : [String(existing)];
81
+ if (opts.overwrite) {
82
+ const prefixes = [`${name}=`, `${name}.sig=`];
83
+ headers = headers.filter(header => !prefixes.some(prefix => header.startsWith(prefix)));
84
+ }
85
+ this.response.setHeader('Set-Cookie', [...headers, ...cookies]);
86
+ return this;
87
+ }
88
+
89
+ protected read(header: string, name: string): string | undefined {
90
+ let pattern = PATTERNS.get(name);
91
+ if (!pattern) {
92
+ pattern = new RegExp(`(?:^|;) *${escape(name)}=([^;]*)`);
93
+ if (PATTERNS.size < 1000) {
94
+ PATTERNS.set(name, pattern);
95
+ }
96
+ }
97
+ return pattern.exec(header)?.[1];
98
+ }
99
+
100
+ protected serialize(name: string, value: string, expires: Date | undefined, opts: CookieSetOptions): string {
101
+ if (!FIELD_CONTENT.test(name) || /[=;]/.test(name)) {
102
+ throw new TypeError('argument name is invalid');
103
+ }
104
+ if (value && !FIELD_CONTENT.test(value)) {
105
+ throw new TypeError('argument value is invalid');
106
+ }
107
+ let header = `${name}=${value}; path=${opts.path ?? '/'}`;
108
+ if (expires) {
109
+ header += `; expires=${expires.toUTCString()}`;
110
+ }
111
+ if (opts.domain) {
112
+ header += `; domain=${opts.domain}`;
113
+ }
114
+ if (opts.priority) {
115
+ if (!PRIORITY.test(opts.priority)) {
116
+ throw new TypeError('option priority is invalid');
117
+ }
118
+ header += `; priority=${opts.priority.toLowerCase()}`;
119
+ }
120
+ if (opts.sameSite) {
121
+ const sameSite = opts.sameSite === true ? 'strict' : String(opts.sameSite);
122
+ if (!SAME_SITE.test(sameSite)) {
123
+ throw new TypeError('option sameSite is invalid');
124
+ }
125
+ header += `; samesite=${sameSite.toLowerCase()}`;
126
+ }
127
+ if (opts.secure) {
128
+ header += '; secure';
129
+ }
130
+ if (opts.httpOnly !== false) {
131
+ header += '; httponly';
132
+ }
133
+ if (opts.partitioned) {
134
+ header += '; partitioned';
135
+ }
136
+ return header;
137
+ }
138
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './cookies-protocol';
2
+ export * from './cookies';
2
3
  export * from './cookies-middleware';
3
4
  export * from './cookies-factory';
@@ -0,0 +1,59 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { CorsMiddleware } from './cors-middleware';
4
+ import { CorsOptions } from './cors-protocol';
5
+
6
+ async function run(options: CorsOptions | undefined, method: string, headers: Record<string, string> = {}, endpoint?: string) {
7
+ const middleware = new CorsMiddleware();
8
+ Object.assign(middleware, { options, endpoint });
9
+ (middleware as unknown as { init(): void }).init();
10
+ const set: Record<string, string> = {};
11
+ const response = {
12
+ statusCode: 200,
13
+ ended: false,
14
+ getHeader: (name: string) => set[name.toLowerCase()],
15
+ setHeader: (name: string, value: string) => { set[name.toLowerCase()] = value; },
16
+ end() { this.ended = true; }
17
+ };
18
+ let nextCalled = false;
19
+ await middleware.handle({ request: { method, headers }, response } as any, async () => { nextCalled = true; });
20
+ return { headers: set, status: response.statusCode, ended: response.ended, nextCalled };
21
+ }
22
+
23
+ describe('CorsMiddleware', () => {
24
+ it('allows any origin by default', async () => {
25
+ const result = await run(undefined, 'GET', { origin: 'https://a.com' });
26
+ expect(result.headers).to.deep.equal({ 'access-control-allow-origin': '*' });
27
+ expect(result.nextCalled).to.equal(true);
28
+ });
29
+
30
+ it('answers preflight requests', async () => {
31
+ const result = await run({ credentials: true, maxAge: 600 }, 'OPTIONS', { origin: 'https://a.com', 'access-control-request-headers': 'x-a' });
32
+ expect(result.headers).to.deep.equal({
33
+ 'access-control-allow-origin': '*',
34
+ 'access-control-allow-credentials': 'true',
35
+ 'access-control-allow-methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
36
+ 'access-control-allow-headers': 'x-a',
37
+ 'access-control-max-age': '600',
38
+ 'content-length': '0',
39
+ vary: 'Access-Control-Request-Headers'
40
+ });
41
+ expect(result).to.deep.include({ status: 204, ended: true, nextCalled: false });
42
+ expect((await run({ preflightContinue: true }, 'OPTIONS', {})).nextCalled).to.equal(true);
43
+ });
44
+
45
+ it('reflects allowed origins only', async () => {
46
+ const options = { origin: [/\.example\.com$/, 'https://b.com'], exposedHeaders: ['x-a', 'x-b'] };
47
+ const allowed = await run(options, 'GET', { origin: 'https://app.example.com' });
48
+ expect(allowed.headers).to.deep.equal({ 'access-control-allow-origin': 'https://app.example.com', vary: 'Origin', 'access-control-expose-headers': 'x-a,x-b' });
49
+ const refused = await run(options, 'GET', { origin: 'https://c.com' });
50
+ expect(refused.headers['access-control-allow-origin']).to.equal(undefined);
51
+ expect((await run({ origin: true }, 'GET', { origin: 'https://c.com' })).headers['access-control-allow-origin']).to.equal('https://c.com');
52
+ expect((await run({ origin: 'https://fixed.com' }, 'GET', { origin: 'https://c.com' })).headers['access-control-allow-origin']).to.equal('https://fixed.com');
53
+ });
54
+
55
+ it('sets nothing when origin is false, except the endpoint', async () => {
56
+ expect((await run({ origin: false }, 'GET', { origin: 'https://c.com' })).headers).to.deep.equal({});
57
+ expect((await run({ origin: false }, 'GET', {}, 'http://localhost:3000')).headers).to.deep.equal({ 'access-control-allow-origin': 'http://localhost:3000' });
58
+ });
59
+ });
@@ -1,33 +1,130 @@
1
- import { convertExpressMiddleware, Middleware } from '../middleware';
1
+ import { Middleware } from '../middleware';
2
2
  import { Context } from '../context';
3
- import { Component, Value, Autowired } from '@celljs/core';
4
- import cors from 'cors';
3
+ import { Component, Value, PostConstruct } from '@celljs/core';
5
4
  import { HttpHeaders } from '@celljs/http';
6
5
  import { CORS, ENDPOINT } from '../../common';
7
- import { CORS_MIDDLEWARE_PRIORITY } from './cors-protocol';
8
- import { HandlerExecutionChain } from '../handler';
6
+ import { CORS_MIDDLEWARE_PRIORITY, CorsOptions, CorsOrigin } from './cors-protocol';
9
7
 
8
+ function join(value: string | string[] | undefined): string | undefined {
9
+ return Array.isArray(value) ? value.join(',') : value;
10
+ }
11
+
12
+ /** Adds a field to the Vary header, once. */
13
+ function vary(response: any, field: string): void {
14
+ const current = response.getHeader('Vary');
15
+ if (!current) {
16
+ response.setHeader('Vary', field);
17
+ return;
18
+ }
19
+ const fields = String(current).split(',').map(f => f.trim().toLowerCase());
20
+ if (!fields.includes('*') && !fields.includes(field.toLowerCase())) {
21
+ response.setHeader('Vary', `${current}, ${field}`);
22
+ }
23
+ }
24
+
25
+ function isAllowed(origin: string, allowed: CorsOrigin): boolean {
26
+ if (Array.isArray(allowed)) {
27
+ return allowed.some(a => isAllowed(origin, a));
28
+ }
29
+ if (typeof allowed === 'string') {
30
+ return origin === allowed;
31
+ }
32
+ if (allowed instanceof RegExp) {
33
+ return allowed.test(origin);
34
+ }
35
+ return !!allowed;
36
+ }
37
+
38
+ /** CORS headers from `cell.web.cors`, with the options and defaults of the `cors` package of express. */
10
39
  @Component(Middleware)
11
40
  export class CorsMiddleware implements Middleware {
12
41
 
13
42
  @Value(CORS)
14
- protected readonly options: any;
43
+ protected readonly options?: CorsOptions;
15
44
 
16
45
  @Value(ENDPOINT)
17
46
  protected readonly endpoint?: string;
18
47
 
19
- @Autowired(HandlerExecutionChain)
20
- protected handlerExecutionChain: HandlerExecutionChain;
48
+ protected methods: string;
49
+ protected allowedHeaders?: string;
50
+ protected exposedHeaders?: string;
51
+ protected maxAge?: string;
52
+
53
+ @PostConstruct()
54
+ protected init(): void {
55
+ const options = this.options || {};
56
+ this.methods = join(options.methods) ?? 'GET,HEAD,PUT,PATCH,POST,DELETE';
57
+ this.allowedHeaders = join(options.allowedHeaders ?? options.headers);
58
+ this.exposedHeaders = join(options.exposedHeaders);
59
+ this.maxAge = options.maxAge !== undefined && options.maxAge !== '' ? String(options.maxAge) : undefined;
60
+ }
21
61
 
22
62
  async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
23
- return this.handlerExecutionChain.execute([
24
- convertExpressMiddleware(cors(this.options))
25
- ], () => {
26
- if (this.endpoint && !ctx.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)) {
27
- ctx.response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, this.endpoint);
63
+ const { request, response } = ctx;
64
+ const resolved = this.resolveOrigin(request.headers.origin);
65
+ const origin = resolved instanceof Promise ? await resolved : resolved;
66
+ if (origin !== false && origin !== '') {
67
+ const options = this.options || {};
68
+ this.setOrigin(response, origin, request.headers.origin);
69
+ if (options.credentials === true) {
70
+ response.setHeader('Access-Control-Allow-Credentials', 'true');
71
+ }
72
+ const preflight = request.method === 'OPTIONS';
73
+ if (preflight) {
74
+ response.setHeader('Access-Control-Allow-Methods', this.methods);
75
+ this.setAllowedHeaders(response, request.headers['access-control-request-headers']);
76
+ if (this.maxAge) {
77
+ response.setHeader('Access-Control-Max-Age', this.maxAge);
78
+ }
79
+ }
80
+ if (this.exposedHeaders) {
81
+ response.setHeader('Access-Control-Expose-Headers', this.exposedHeaders);
82
+ }
83
+ if (preflight && !options.preflightContinue) {
84
+ response.statusCode = options.optionsSuccessStatus ?? 204;
85
+ response.setHeader('Content-Length', '0');
86
+ response.end();
87
+ return;
88
+ }
89
+ }
90
+ if (this.endpoint && !response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)) {
91
+ response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, this.endpoint);
92
+ }
93
+ return next();
94
+ }
95
+
96
+ protected resolveOrigin(requestOrigin: string | undefined): Promise<CorsOrigin> | CorsOrigin {
97
+ const origin = this.options?.origin ?? '*';
98
+ if (typeof origin !== 'function') {
99
+ return origin;
100
+ }
101
+ return new Promise<CorsOrigin>((resolve, reject) => origin(requestOrigin, (err, value) => err ? reject(err) : resolve(value ?? false)));
102
+ }
103
+
104
+ protected setOrigin(response: any, origin: CorsOrigin, requestOrigin: string | undefined): void {
105
+ if (origin === '*') {
106
+ response.setHeader('Access-Control-Allow-Origin', '*');
107
+ return;
108
+ }
109
+ if (typeof origin === 'string') {
110
+ response.setHeader('Access-Control-Allow-Origin', origin);
111
+ } else if (requestOrigin && isAllowed(requestOrigin, origin)) {
112
+ response.setHeader('Access-Control-Allow-Origin', requestOrigin);
113
+ }
114
+ vary(response, 'Origin');
115
+ }
116
+
117
+ protected setAllowedHeaders(response: any, requested: string | undefined): void {
118
+ if (this.allowedHeaders !== undefined) {
119
+ if (this.allowedHeaders) {
120
+ response.setHeader('Access-Control-Allow-Headers', this.allowedHeaders);
28
121
  }
29
- return next();
30
- });
122
+ return;
123
+ }
124
+ vary(response, 'Access-Control-Request-Headers');
125
+ if (requested) {
126
+ response.setHeader('Access-Control-Allow-Headers', requested);
127
+ }
31
128
  }
32
129
 
33
130
  readonly priority = CORS_MIDDLEWARE_PRIORITY;
@@ -1,2 +1,27 @@
1
1
  import { TRACE_MIDDLEWARE_PRIORITY } from '../trace';
2
2
  export const CORS_MIDDLEWARE_PRIORITY = TRACE_MIDDLEWARE_PRIORITY - 100;
3
+
4
+ export type CorsOrigin = boolean | string | RegExp | (string | RegExp)[];
5
+
6
+ /** `cell.web.cors`, with the options and defaults of the `cors` package of express. */
7
+ export interface CorsOptions {
8
+ /**
9
+ * `'*'` (default): any origin; a string: that origin; `true`: the origin of the request; a RegExp or a list:
10
+ * the origin of the request when it matches; `false`: no CORS headers.
11
+ */
12
+ origin?: CorsOrigin | ((origin: string | undefined, callback: (err: Error | null, origin?: CorsOrigin) => void) => void);
13
+ /** Default `GET,HEAD,PUT,PATCH,POST,DELETE`. */
14
+ methods?: string | string[];
15
+ /** Default: the headers the preflight request asks for. */
16
+ allowedHeaders?: string | string[];
17
+ /** Alias of `allowedHeaders`. */
18
+ headers?: string | string[];
19
+ exposedHeaders?: string | string[];
20
+ credentials?: boolean;
21
+ /** Seconds. */
22
+ maxAge?: number | string;
23
+ /** Pass preflight (OPTIONS) requests on instead of answering them. Default false. */
24
+ preflightContinue?: boolean;
25
+ /** Default 204. */
26
+ optionsSuccessStatus?: number;
27
+ }
@@ -1,11 +1,10 @@
1
1
  import { Context } from '../context';
2
- import { Component, Autowired, Prioritizeable, Injectable } from '@celljs/core';
2
+ import { Component, Autowired, Prioritizeable } from '@celljs/core';
3
3
  import { ErrorHandler, DEFALUT_ERROR_HANDLER_PRIORITY, HTTP_ERROR_HANDLER_PRIORITY, VALIDATION_ERRORS_ERROR_HANDLER_PRIORITY } from './error-protocol';
4
4
  import { HttpError } from './http-error';
5
5
  import { HttpStatus } from '@celljs/http';
6
6
  import { ValidationErrors } from '../../common/pipe';
7
7
 
8
- @Injectable()
9
8
  export abstract class AbstractErrorHandler implements ErrorHandler {
10
9
  readonly priority: number = DEFALUT_ERROR_HANDLER_PRIORITY;
11
10
 
@@ -31,7 +31,7 @@ export class HealthMiddleware implements Middleware {
31
31
  const result = await this.match();
32
32
  if (result) {
33
33
  const health = await this.healthExecutor.execute(result.indicatorName);
34
- response.status(200);
34
+ response.statusCode = 200;
35
35
  response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
36
36
  response.body = JSON.stringify(health);
37
37
  return;
@@ -1,17 +1,41 @@
1
- import { Request as RawRequest, Response as RawResponse } from 'express';
1
+ import type { IncomingMessage, Server, ServerResponse } from 'http';
2
2
  import { CORS_MIDDLEWARE_PRIORITY } from '../cors';
3
- import * as http from 'http';
4
3
 
5
4
  export const ServerAware = Symbol('ServerAware');
6
5
  export const HTTP_MIDDLEWARE_PRIORITY = CORS_MIDDLEWARE_PRIORITY - 100;
7
6
 
8
- export interface Request extends RawRequest {
7
+ /** Node's `IncomingMessage` with what Cell reads from a request (see {@link HttpRequest}). */
8
+ export interface Request extends IncomingMessage {
9
+ /** Always set for a request a server received. */
10
+ url: string;
11
+ method: string;
12
+ /** Path of the URL without the query, not decoded: `/users/1`. */
13
+ readonly path: string;
14
+ /** Query of the URL, with brackets: `?a[b]=1&c=2&c=3` → `{ a: { b: '1' }, c: ['2', '3'] }`. */
15
+ query: Record<string, any>;
16
+ /** `https` when the connection is TLS. `X-Forwarded-Proto` is not read. */
17
+ readonly protocol: 'http' | 'https';
18
+ readonly secure: boolean;
19
+ /** Host header without the port. */
20
+ readonly hostname: string | undefined;
21
+ /** Address of the client socket. */
22
+ readonly ip: string | undefined;
23
+ /** The URL as the client sent it, before anything rewrote `url`. */
24
+ originalUrl: string;
25
+ /** Set by the body middleware. */
26
+ body: any;
27
+ /** A header, by any case; `referer` and `referrer` are the same. */
28
+ get(name: 'set-cookie'): string[] | undefined;
29
+ get(name: string): string | undefined;
30
+ header(name: 'set-cookie'): string[] | undefined;
31
+ header(name: string): string | undefined;
9
32
  }
10
33
 
11
- export interface Response extends RawResponse {
34
+ export interface Response extends ServerResponse {
35
+ /** What the http middleware writes once the handler has run. */
12
36
  body?: any;
13
37
  }
14
38
 
15
39
  export interface ServerAware {
16
- setServer(server: http.Server): Promise<void>;
40
+ setServer(server: Server): Promise<void>;
17
41
  }
@@ -0,0 +1,68 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { IncomingMessage } from 'node:http';
4
+ import { Socket } from 'node:net';
5
+ import { HttpRequest } from './http-request';
6
+
7
+ function request(url: string, headers: Record<string, string> = {}) {
8
+ const req = new IncomingMessage(new Socket());
9
+ req.url = url;
10
+ req.method = 'GET';
11
+ req.headers = headers;
12
+ return HttpRequest.enhance(req);
13
+ }
14
+
15
+ describe('HttpRequest', () => {
16
+ it('gives a request of another server its members', () => {
17
+ const req = request('/users/1?x=1');
18
+ expect(req).to.be.instanceOf(HttpRequest);
19
+ expect(req).to.be.instanceOf(IncomingMessage);
20
+ expect(HttpRequest.enhance(req)).to.equal(req);
21
+ });
22
+
23
+ it('splits the URL into path and query, as express did', () => {
24
+ expect(request('/users/1').path).to.equal('/users/1');
25
+ expect(request('/a%20b?q=1').path).to.equal('/a%20b');
26
+ expect(request('/a?').query).to.deep.equal({});
27
+ expect(request('/').query).to.deep.equal({});
28
+ expect(request('/s?a[b]=1&c=2&c=3&d=x+y').query).to.deep.equal({ a: { b: '1' }, c: ['2', '3'], d: 'x y' });
29
+ expect(request('/s?a[b][c][d][e][f][g]=1').query).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g]': '1' } } } } } } });
30
+ expect(request('/s?a[21]=x').query).to.deep.equal({ a: { 21: 'x' } });
31
+ expect(request('http://example.com/p?x=1').path).to.equal('/p');
32
+ expect(request('http://example.com/p?x=1').query).to.deep.equal({ x: '1' });
33
+ });
34
+
35
+ it('reads the URL again when it changes, and keeps an assigned query', () => {
36
+ const req = request('/a?x=1');
37
+ expect(req.query).to.deep.equal({ x: '1' });
38
+ req.url = '/b?y=2';
39
+ expect(req.path).to.equal('/b');
40
+ expect(req.query).to.deep.equal({ y: '2' });
41
+ req.query = { z: '3' };
42
+ expect(req.query).to.deep.equal({ z: '3' });
43
+ expect(req.originalUrl).to.equal('/b?y=2');
44
+ req.originalUrl = '/mounted/b?y=2';
45
+ expect(req.originalUrl).to.equal('/mounted/b?y=2');
46
+ });
47
+
48
+ it('reads headers by any case, referer and referrer alike', () => {
49
+ const req = request('/', { 'x-trace': 't', referer: 'http://a', host: 'example.com:3000' });
50
+ expect(req.get('X-Trace')).to.equal('t');
51
+ expect(req.header('x-trace')).to.equal('t');
52
+ expect(req.get('Referrer')).to.equal('http://a');
53
+ expect(req.get('missing')).to.equal(undefined);
54
+ expect(req.hostname).to.equal('example.com');
55
+ expect(request('/', { host: '[::1]:3000' }).hostname).to.equal('[::1]');
56
+ expect(request('/', { host: 'example.com' }).hostname).to.equal('example.com');
57
+ expect(request('/').hostname).to.equal(undefined);
58
+ });
59
+
60
+ it('takes the protocol from the connection', () => {
61
+ const req = request('/');
62
+ expect(req.protocol).to.equal('http');
63
+ expect(req.secure).to.equal(false);
64
+ (req.socket as unknown as { encrypted: boolean }).encrypted = true;
65
+ expect(req.protocol).to.equal('https');
66
+ expect(req.secure).to.equal(true);
67
+ });
68
+ });