@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.
Files changed (279) 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 +5 -4
  15. package/esm/node/body/body-middleware.js +14 -15
  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/context.js +1 -1
  28. package/esm/node/context.js.map +1 -1
  29. package/esm/node/cookies/cookies-factory.js +2 -6
  30. package/esm/node/cookies/cookies-factory.js.map +1 -1
  31. package/esm/node/cookies/cookies-protocol.d.ts +25 -2
  32. package/esm/node/cookies/cookies.d.ts +17 -0
  33. package/esm/node/cookies/cookies.js +137 -0
  34. package/esm/node/cookies/cookies.js.map +1 -0
  35. package/esm/node/cookies/index.d.ts +1 -0
  36. package/esm/node/cookies/index.js +1 -0
  37. package/esm/node/cookies/index.js.map +1 -1
  38. package/esm/node/cors/cors-middleware.d.ts +11 -3
  39. package/esm/node/cors/cors-middleware.js +108 -14
  40. package/esm/node/cors/cors-middleware.js.map +1 -1
  41. package/esm/node/cors/cors-protocol.d.ts +23 -0
  42. package/esm/node/error/error-handler-provider.js +3 -7
  43. package/esm/node/error/error-handler-provider.js.map +1 -1
  44. package/esm/node/health/health-middleware.js +1 -1
  45. package/esm/node/health/health-middleware.js.map +1 -1
  46. package/esm/node/http/http-middleware.d.ts +1 -0
  47. package/esm/node/http/http-middleware.js +10 -5
  48. package/esm/node/http/http-middleware.js.map +1 -1
  49. package/esm/node/http/http-protocol.d.ts +29 -5
  50. package/esm/node/http/http-protocol.js.map +1 -1
  51. package/esm/node/http/http-request.d.ts +41 -0
  52. package/esm/node/http/http-request.js +106 -0
  53. package/esm/node/http/http-request.js.map +1 -0
  54. package/esm/node/http/index.d.ts +1 -0
  55. package/esm/node/http/index.js +1 -0
  56. package/esm/node/http/index.js.map +1 -1
  57. package/esm/node/index.d.ts +1 -0
  58. package/esm/node/index.js +1 -0
  59. package/esm/node/index.js.map +1 -1
  60. package/esm/node/matcher/index.d.ts +1 -0
  61. package/esm/node/matcher/index.js +1 -0
  62. package/esm/node/matcher/index.js.map +1 -1
  63. package/esm/node/matcher/path-pattern.d.ts +23 -0
  64. package/esm/node/matcher/path-pattern.js +115 -0
  65. package/esm/node/matcher/path-pattern.js.map +1 -0
  66. package/esm/node/matcher/request-matcher.d.ts +2 -2
  67. package/esm/node/matcher/request-matcher.js +8 -9
  68. package/esm/node/matcher/request-matcher.js.map +1 -1
  69. package/esm/node/module.d.ts +1 -1
  70. package/esm/node/server/http-server.d.ts +13 -0
  71. package/esm/node/server/http-server.js +32 -0
  72. package/esm/node/server/http-server.js.map +1 -0
  73. package/esm/node/server/index.d.ts +1 -0
  74. package/esm/node/server/index.js +2 -0
  75. package/esm/node/server/index.js.map +1 -0
  76. package/esm/node/session/session-manager.js +1 -2
  77. package/esm/node/session/session-manager.js.map +1 -1
  78. package/esm/node/session/session-store.js +5 -5
  79. package/esm/node/session/session-store.js.map +1 -1
  80. package/esm/node/session/session.d.ts +3 -2
  81. package/esm/node/session/session.js +4 -10
  82. package/esm/node/session/session.js.map +1 -1
  83. package/lib/browser/module.d.ts +1 -1
  84. package/lib/common/module.d.ts +1 -1
  85. package/lib/common/pipe/index.d.ts +1 -1
  86. package/lib/common/pipe/index.d.ts.map +1 -1
  87. package/lib/common/pipe/index.js +1 -1
  88. package/lib/common/pipe/index.js.map +1 -1
  89. package/lib/common/pipe/type-conversion-pipe.d.ts +13 -0
  90. package/lib/common/pipe/type-conversion-pipe.d.ts.map +1 -0
  91. package/lib/common/pipe/type-conversion-pipe.js +46 -0
  92. package/lib/common/pipe/type-conversion-pipe.js.map +1 -0
  93. package/lib/common/pipe/type-conversion-pipe.spec.d.ts +2 -0
  94. package/lib/common/pipe/type-conversion-pipe.spec.d.ts.map +1 -0
  95. package/lib/common/pipe/type-conversion-pipe.spec.js +36 -0
  96. package/lib/common/pipe/type-conversion-pipe.spec.js.map +1 -0
  97. package/lib/common/pipe/validation-errors.d.ts +11 -2
  98. package/lib/common/pipe/validation-errors.d.ts.map +1 -1
  99. package/lib/common/pipe/validation-errors.js +2 -0
  100. package/lib/common/pipe/validation-errors.js.map +1 -1
  101. package/lib/node/body/body-middleware.d.ts +5 -4
  102. package/lib/node/body/body-middleware.d.ts.map +1 -1
  103. package/lib/node/body/body-middleware.js +12 -12
  104. package/lib/node/body/body-middleware.js.map +1 -1
  105. package/lib/node/body/body-middleware.spec.d.ts +2 -0
  106. package/lib/node/body/body-middleware.spec.d.ts.map +1 -0
  107. package/lib/node/body/body-middleware.spec.js +85 -0
  108. package/lib/node/body/body-middleware.spec.js.map +1 -0
  109. package/lib/node/body/body-parser.d.ts +33 -0
  110. package/lib/node/body/body-parser.d.ts.map +1 -0
  111. package/lib/node/body/body-parser.js +210 -0
  112. package/lib/node/body/body-parser.js.map +1 -0
  113. package/lib/node/body/body-protocol.d.ts +15 -0
  114. package/lib/node/body/body-protocol.d.ts.map +1 -1
  115. package/lib/node/body/form-util.d.ts +16 -0
  116. package/lib/node/body/form-util.d.ts.map +1 -0
  117. package/lib/node/body/form-util.js +123 -0
  118. package/lib/node/body/form-util.js.map +1 -0
  119. package/lib/node/body/form-util.spec.d.ts +2 -0
  120. package/lib/node/body/form-util.spec.d.ts.map +1 -0
  121. package/lib/node/body/form-util.spec.js +44 -0
  122. package/lib/node/body/form-util.spec.js.map +1 -0
  123. package/lib/node/body/index.d.ts +2 -0
  124. package/lib/node/body/index.d.ts.map +1 -1
  125. package/lib/node/body/index.js +2 -0
  126. package/lib/node/body/index.js.map +1 -1
  127. package/lib/node/context.js +1 -1
  128. package/lib/node/context.js.map +1 -1
  129. package/lib/node/cookies/cookies-factory.d.ts.map +1 -1
  130. package/lib/node/cookies/cookies-factory.js +2 -9
  131. package/lib/node/cookies/cookies-factory.js.map +1 -1
  132. package/lib/node/cookies/cookies-protocol.d.ts +25 -2
  133. package/lib/node/cookies/cookies-protocol.d.ts.map +1 -1
  134. package/lib/node/cookies/cookies.d.ts +18 -0
  135. package/lib/node/cookies/cookies.d.ts.map +1 -0
  136. package/lib/node/cookies/cookies.js +141 -0
  137. package/lib/node/cookies/cookies.js.map +1 -0
  138. package/lib/node/cookies/cookies.spec.d.ts +2 -0
  139. package/lib/node/cookies/cookies.spec.d.ts.map +1 -0
  140. package/lib/node/cookies/cookies.spec.js +73 -0
  141. package/lib/node/cookies/cookies.spec.js.map +1 -0
  142. package/lib/node/cookies/index.d.ts +1 -0
  143. package/lib/node/cookies/index.d.ts.map +1 -1
  144. package/lib/node/cookies/index.js +1 -0
  145. package/lib/node/cookies/index.js.map +1 -1
  146. package/lib/node/cors/cors-middleware.d.ts +11 -3
  147. package/lib/node/cors/cors-middleware.d.ts.map +1 -1
  148. package/lib/node/cors/cors-middleware.js +106 -15
  149. package/lib/node/cors/cors-middleware.js.map +1 -1
  150. package/lib/node/cors/cors-middleware.spec.d.ts +2 -0
  151. package/lib/node/cors/cors-middleware.spec.d.ts.map +1 -0
  152. package/lib/node/cors/cors-middleware.spec.js +56 -0
  153. package/lib/node/cors/cors-middleware.spec.js.map +1 -0
  154. package/lib/node/cors/cors-protocol.d.ts +23 -0
  155. package/lib/node/cors/cors-protocol.d.ts.map +1 -1
  156. package/lib/node/error/error-handler-provider.d.ts.map +1 -1
  157. package/lib/node/error/error-handler-provider.js +2 -5
  158. package/lib/node/error/error-handler-provider.js.map +1 -1
  159. package/lib/node/health/health-middleware.js +1 -1
  160. package/lib/node/health/health-middleware.js.map +1 -1
  161. package/lib/node/http/http-middleware.d.ts +1 -0
  162. package/lib/node/http/http-middleware.d.ts.map +1 -1
  163. package/lib/node/http/http-middleware.js +10 -5
  164. package/lib/node/http/http-middleware.js.map +1 -1
  165. package/lib/node/http/http-protocol.d.ts +29 -5
  166. package/lib/node/http/http-protocol.d.ts.map +1 -1
  167. package/lib/node/http/http-protocol.js.map +1 -1
  168. package/lib/node/http/http-request.d.ts +42 -0
  169. package/lib/node/http/http-request.d.ts.map +1 -0
  170. package/lib/node/http/http-request.js +110 -0
  171. package/lib/node/http/http-request.js.map +1 -0
  172. package/lib/node/http/http-request.spec.d.ts +2 -0
  173. package/lib/node/http/http-request.spec.d.ts.map +1 -0
  174. package/lib/node/http/http-request.spec.js +65 -0
  175. package/lib/node/http/http-request.spec.js.map +1 -0
  176. package/lib/node/http/index.d.ts +1 -0
  177. package/lib/node/http/index.d.ts.map +1 -1
  178. package/lib/node/http/index.js +1 -0
  179. package/lib/node/http/index.js.map +1 -1
  180. package/lib/node/index.d.ts +1 -0
  181. package/lib/node/index.d.ts.map +1 -1
  182. package/lib/node/index.js +1 -0
  183. package/lib/node/index.js.map +1 -1
  184. package/lib/node/matcher/index.d.ts +1 -0
  185. package/lib/node/matcher/index.d.ts.map +1 -1
  186. package/lib/node/matcher/index.js +1 -0
  187. package/lib/node/matcher/index.js.map +1 -1
  188. package/lib/node/matcher/path-pattern.d.ts +24 -0
  189. package/lib/node/matcher/path-pattern.d.ts.map +1 -0
  190. package/lib/node/matcher/path-pattern.js +119 -0
  191. package/lib/node/matcher/path-pattern.js.map +1 -0
  192. package/lib/node/matcher/path-pattern.spec.d.ts +2 -0
  193. package/lib/node/matcher/path-pattern.spec.d.ts.map +1 -0
  194. package/lib/node/matcher/path-pattern.spec.js +43 -0
  195. package/lib/node/matcher/path-pattern.spec.js.map +1 -0
  196. package/lib/node/matcher/request-matcher.d.ts +2 -2
  197. package/lib/node/matcher/request-matcher.d.ts.map +1 -1
  198. package/lib/node/matcher/request-matcher.js +8 -12
  199. package/lib/node/matcher/request-matcher.js.map +1 -1
  200. package/lib/node/module.d.ts +1 -1
  201. package/lib/node/server/http-server.d.ts +14 -0
  202. package/lib/node/server/http-server.d.ts.map +1 -0
  203. package/lib/node/server/http-server.js +35 -0
  204. package/lib/node/server/http-server.js.map +1 -0
  205. package/lib/node/server/http-server.spec.d.ts +2 -0
  206. package/lib/node/server/http-server.spec.d.ts.map +1 -0
  207. package/lib/node/server/http-server.spec.js +41 -0
  208. package/lib/node/server/http-server.spec.js.map +1 -0
  209. package/lib/node/server/index.d.ts +2 -0
  210. package/lib/node/server/index.d.ts.map +1 -0
  211. package/lib/node/server/index.js +18 -0
  212. package/lib/node/server/index.js.map +1 -0
  213. package/lib/node/session/session-manager.d.ts.map +1 -1
  214. package/lib/node/session/session-manager.js +1 -2
  215. package/lib/node/session/session-manager.js.map +1 -1
  216. package/lib/node/session/session-store.d.ts.map +1 -1
  217. package/lib/node/session/session-store.js +5 -3
  218. package/lib/node/session/session-store.js.map +1 -1
  219. package/lib/node/session/session.d.ts +3 -2
  220. package/lib/node/session/session.d.ts.map +1 -1
  221. package/lib/node/session/session.js +4 -8
  222. package/lib/node/session/session.js.map +1 -1
  223. package/lib/node/session/session.spec.d.ts +2 -0
  224. package/lib/node/session/session.spec.d.ts.map +1 -0
  225. package/lib/node/session/session.spec.js +84 -0
  226. package/lib/node/session/session.spec.js.map +1 -0
  227. package/package.json +10 -18
  228. package/src/common/pipe/index.ts +1 -1
  229. package/src/common/pipe/type-conversion-pipe.spec.ts +38 -0
  230. package/src/common/pipe/type-conversion-pipe.ts +36 -0
  231. package/src/common/pipe/validation-errors.ts +11 -2
  232. package/src/node/body/body-middleware.spec.ts +96 -0
  233. package/src/node/body/body-middleware.ts +14 -15
  234. package/src/node/body/body-parser.ts +216 -0
  235. package/src/node/body/body-protocol.ts +15 -0
  236. package/src/node/body/form-util.spec.ts +45 -0
  237. package/src/node/body/form-util.ts +132 -0
  238. package/src/node/body/index.ts +2 -0
  239. package/src/node/context.ts +1 -1
  240. package/src/node/cookies/cookies-factory.ts +2 -6
  241. package/src/node/cookies/cookies-protocol.ts +28 -3
  242. package/src/node/cookies/cookies.spec.ts +80 -0
  243. package/src/node/cookies/cookies.ts +138 -0
  244. package/src/node/cookies/index.ts +1 -0
  245. package/src/node/cors/cors-middleware.spec.ts +59 -0
  246. package/src/node/cors/cors-middleware.ts +112 -15
  247. package/src/node/cors/cors-protocol.ts +25 -0
  248. package/src/node/error/error-handler-provider.ts +1 -2
  249. package/src/node/health/health-middleware.ts +1 -1
  250. package/src/node/http/http-middleware.ts +10 -5
  251. package/src/node/http/http-protocol.ts +29 -5
  252. package/src/node/http/http-request.spec.ts +68 -0
  253. package/src/node/http/http-request.ts +132 -0
  254. package/src/node/http/index.ts +1 -0
  255. package/src/node/index.ts +1 -0
  256. package/src/node/matcher/index.ts +1 -0
  257. package/src/node/matcher/path-pattern.spec.ts +43 -0
  258. package/src/node/matcher/path-pattern.ts +113 -0
  259. package/src/node/matcher/request-matcher.ts +9 -10
  260. package/src/node/server/http-server.spec.ts +45 -0
  261. package/src/node/server/http-server.ts +35 -0
  262. package/src/node/server/index.ts +1 -0
  263. package/src/node/session/session-manager.ts +1 -2
  264. package/src/node/session/session-store.ts +6 -3
  265. package/src/node/session/session.spec.ts +88 -0
  266. package/src/node/session/session.ts +6 -9
  267. package/esm/common/pipe/pipe-transtorm.d.ts +0 -17
  268. package/esm/common/pipe/pipe-transtorm.js +0 -110
  269. package/esm/common/pipe/pipe-transtorm.js.map +0 -1
  270. package/lib/common/pipe/pipe-transtorm.d.ts +0 -18
  271. package/lib/common/pipe/pipe-transtorm.d.ts.map +0 -1
  272. package/lib/common/pipe/pipe-transtorm.js +0 -113
  273. package/lib/common/pipe/pipe-transtorm.js.map +0 -1
  274. package/lib/common/pipe/pipe-transtorm.spec.d.ts +0 -2
  275. package/lib/common/pipe/pipe-transtorm.spec.d.ts.map +0 -1
  276. package/lib/common/pipe/pipe-transtorm.spec.js +0 -69
  277. package/lib/common/pipe/pipe-transtorm.spec.js.map +0 -1
  278. package/src/common/pipe/pipe-transtorm.spec.ts +0 -62
  279. package/src/common/pipe/pipe-transtorm.ts +0 -113
@@ -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
+ }
@@ -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;
@@ -9,11 +9,14 @@ export class HttpMiddleware implements Middleware {
9
9
  @Autowired(Logger)
10
10
  protected readonly logger: Logger;
11
11
 
12
+ /** The access log: one line before and one after each request, at the debug level. */
12
13
  async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
13
- const method = ctx.request.method;
14
- const path = ctx.request.path;
15
- this.logger.info(`starting ${method} ${path}`);
16
- const now = Date.now();
14
+ // Checked once per request: the lines are only built when they are written.
15
+ const log = this.logger.isEnabled('debug');
16
+ const start = log ? Date.now() : 0;
17
+ if (log) {
18
+ this.logger.debug(`starting ${ctx.request.method} ${ctx.request.path}`);
19
+ }
17
20
  try {
18
21
  await next();
19
22
  const response = ctx.response;
@@ -21,7 +24,9 @@ export class HttpMiddleware implements Middleware {
21
24
  response.end(response.body);
22
25
  }
23
26
  } finally {
24
- this.logger.info(`ending ${method} ${path} [${Date.now() - now}ms]`);
27
+ if (log) {
28
+ this.logger.debug(`ending ${ctx.request.method} ${ctx.request.path} [${Date.now() - start}ms]`);
29
+ }
25
30
  }
26
31
  }
27
32
 
@@ -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
  }