@celljs/web 4.0.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -1
- package/cell.yml +0 -3
- package/esm/browser/module.d.ts +1 -1
- package/esm/common/module.d.ts +1 -1
- package/esm/common/pipe/index.d.ts +1 -1
- package/esm/common/pipe/index.js +1 -1
- package/esm/common/pipe/index.js.map +1 -1
- package/esm/common/pipe/type-conversion-pipe.d.ts +12 -0
- package/esm/common/pipe/type-conversion-pipe.js +43 -0
- package/esm/common/pipe/type-conversion-pipe.js.map +1 -0
- package/esm/common/pipe/validation-errors.d.ts +11 -2
- package/esm/common/pipe/validation-errors.js +2 -0
- package/esm/common/pipe/validation-errors.js.map +1 -1
- package/esm/node/body/body-middleware.d.ts +5 -4
- package/esm/node/body/body-middleware.js +14 -15
- package/esm/node/body/body-middleware.js.map +1 -1
- package/esm/node/body/body-parser.d.ts +32 -0
- package/esm/node/body/body-parser.js +205 -0
- package/esm/node/body/body-parser.js.map +1 -0
- package/esm/node/body/body-protocol.d.ts +15 -0
- package/esm/node/body/form-util.d.ts +15 -0
- package/esm/node/body/form-util.js +120 -0
- package/esm/node/body/form-util.js.map +1 -0
- package/esm/node/body/index.d.ts +2 -0
- package/esm/node/body/index.js +2 -0
- package/esm/node/body/index.js.map +1 -1
- package/esm/node/context.js +1 -1
- package/esm/node/context.js.map +1 -1
- package/esm/node/cookies/cookies-factory.js +2 -6
- package/esm/node/cookies/cookies-factory.js.map +1 -1
- package/esm/node/cookies/cookies-protocol.d.ts +25 -2
- package/esm/node/cookies/cookies.d.ts +17 -0
- package/esm/node/cookies/cookies.js +137 -0
- package/esm/node/cookies/cookies.js.map +1 -0
- package/esm/node/cookies/index.d.ts +1 -0
- package/esm/node/cookies/index.js +1 -0
- package/esm/node/cookies/index.js.map +1 -1
- package/esm/node/cors/cors-middleware.d.ts +11 -3
- package/esm/node/cors/cors-middleware.js +108 -14
- package/esm/node/cors/cors-middleware.js.map +1 -1
- package/esm/node/cors/cors-protocol.d.ts +23 -0
- package/esm/node/error/error-handler-provider.js +3 -7
- package/esm/node/error/error-handler-provider.js.map +1 -1
- package/esm/node/health/health-middleware.js +1 -1
- package/esm/node/health/health-middleware.js.map +1 -1
- package/esm/node/http/http-middleware.d.ts +1 -0
- package/esm/node/http/http-middleware.js +10 -5
- package/esm/node/http/http-middleware.js.map +1 -1
- package/esm/node/http/http-protocol.d.ts +29 -5
- package/esm/node/http/http-protocol.js.map +1 -1
- package/esm/node/http/http-request.d.ts +41 -0
- package/esm/node/http/http-request.js +106 -0
- package/esm/node/http/http-request.js.map +1 -0
- package/esm/node/http/index.d.ts +1 -0
- package/esm/node/http/index.js +1 -0
- package/esm/node/http/index.js.map +1 -1
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +1 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/matcher/index.d.ts +1 -0
- package/esm/node/matcher/index.js +1 -0
- package/esm/node/matcher/index.js.map +1 -1
- package/esm/node/matcher/path-pattern.d.ts +23 -0
- package/esm/node/matcher/path-pattern.js +115 -0
- package/esm/node/matcher/path-pattern.js.map +1 -0
- package/esm/node/matcher/request-matcher.d.ts +2 -2
- package/esm/node/matcher/request-matcher.js +8 -9
- package/esm/node/matcher/request-matcher.js.map +1 -1
- package/esm/node/module.d.ts +1 -1
- package/esm/node/server/http-server.d.ts +13 -0
- package/esm/node/server/http-server.js +32 -0
- package/esm/node/server/http-server.js.map +1 -0
- package/esm/node/server/index.d.ts +1 -0
- package/esm/node/server/index.js +2 -0
- package/esm/node/server/index.js.map +1 -0
- package/esm/node/session/session-manager.js +1 -2
- package/esm/node/session/session-manager.js.map +1 -1
- package/esm/node/session/session-store.js +5 -5
- package/esm/node/session/session-store.js.map +1 -1
- package/esm/node/session/session.d.ts +3 -2
- package/esm/node/session/session.js +4 -10
- package/esm/node/session/session.js.map +1 -1
- package/lib/browser/module.d.ts +1 -1
- package/lib/common/module.d.ts +1 -1
- package/lib/common/pipe/index.d.ts +1 -1
- package/lib/common/pipe/index.d.ts.map +1 -1
- package/lib/common/pipe/index.js +1 -1
- package/lib/common/pipe/index.js.map +1 -1
- package/lib/common/pipe/type-conversion-pipe.d.ts +13 -0
- package/lib/common/pipe/type-conversion-pipe.d.ts.map +1 -0
- package/lib/common/pipe/type-conversion-pipe.js +46 -0
- package/lib/common/pipe/type-conversion-pipe.js.map +1 -0
- package/lib/common/pipe/type-conversion-pipe.spec.d.ts +2 -0
- package/lib/common/pipe/type-conversion-pipe.spec.d.ts.map +1 -0
- package/lib/common/pipe/type-conversion-pipe.spec.js +36 -0
- package/lib/common/pipe/type-conversion-pipe.spec.js.map +1 -0
- package/lib/common/pipe/validation-errors.d.ts +11 -2
- package/lib/common/pipe/validation-errors.d.ts.map +1 -1
- package/lib/common/pipe/validation-errors.js +2 -0
- package/lib/common/pipe/validation-errors.js.map +1 -1
- package/lib/node/body/body-middleware.d.ts +5 -4
- package/lib/node/body/body-middleware.d.ts.map +1 -1
- package/lib/node/body/body-middleware.js +12 -12
- package/lib/node/body/body-middleware.js.map +1 -1
- package/lib/node/body/body-middleware.spec.d.ts +2 -0
- package/lib/node/body/body-middleware.spec.d.ts.map +1 -0
- package/lib/node/body/body-middleware.spec.js +85 -0
- package/lib/node/body/body-middleware.spec.js.map +1 -0
- package/lib/node/body/body-parser.d.ts +33 -0
- package/lib/node/body/body-parser.d.ts.map +1 -0
- package/lib/node/body/body-parser.js +210 -0
- package/lib/node/body/body-parser.js.map +1 -0
- package/lib/node/body/body-protocol.d.ts +15 -0
- package/lib/node/body/body-protocol.d.ts.map +1 -1
- package/lib/node/body/form-util.d.ts +16 -0
- package/lib/node/body/form-util.d.ts.map +1 -0
- package/lib/node/body/form-util.js +123 -0
- package/lib/node/body/form-util.js.map +1 -0
- package/lib/node/body/form-util.spec.d.ts +2 -0
- package/lib/node/body/form-util.spec.d.ts.map +1 -0
- package/lib/node/body/form-util.spec.js +44 -0
- package/lib/node/body/form-util.spec.js.map +1 -0
- package/lib/node/body/index.d.ts +2 -0
- package/lib/node/body/index.d.ts.map +1 -1
- package/lib/node/body/index.js +2 -0
- package/lib/node/body/index.js.map +1 -1
- package/lib/node/context.js +1 -1
- package/lib/node/context.js.map +1 -1
- package/lib/node/cookies/cookies-factory.d.ts.map +1 -1
- package/lib/node/cookies/cookies-factory.js +2 -9
- package/lib/node/cookies/cookies-factory.js.map +1 -1
- package/lib/node/cookies/cookies-protocol.d.ts +25 -2
- package/lib/node/cookies/cookies-protocol.d.ts.map +1 -1
- package/lib/node/cookies/cookies.d.ts +18 -0
- package/lib/node/cookies/cookies.d.ts.map +1 -0
- package/lib/node/cookies/cookies.js +141 -0
- package/lib/node/cookies/cookies.js.map +1 -0
- package/lib/node/cookies/cookies.spec.d.ts +2 -0
- package/lib/node/cookies/cookies.spec.d.ts.map +1 -0
- package/lib/node/cookies/cookies.spec.js +73 -0
- package/lib/node/cookies/cookies.spec.js.map +1 -0
- package/lib/node/cookies/index.d.ts +1 -0
- package/lib/node/cookies/index.d.ts.map +1 -1
- package/lib/node/cookies/index.js +1 -0
- package/lib/node/cookies/index.js.map +1 -1
- package/lib/node/cors/cors-middleware.d.ts +11 -3
- package/lib/node/cors/cors-middleware.d.ts.map +1 -1
- package/lib/node/cors/cors-middleware.js +106 -15
- package/lib/node/cors/cors-middleware.js.map +1 -1
- package/lib/node/cors/cors-middleware.spec.d.ts +2 -0
- package/lib/node/cors/cors-middleware.spec.d.ts.map +1 -0
- package/lib/node/cors/cors-middleware.spec.js +56 -0
- package/lib/node/cors/cors-middleware.spec.js.map +1 -0
- package/lib/node/cors/cors-protocol.d.ts +23 -0
- package/lib/node/cors/cors-protocol.d.ts.map +1 -1
- package/lib/node/error/error-handler-provider.d.ts.map +1 -1
- package/lib/node/error/error-handler-provider.js +2 -5
- package/lib/node/error/error-handler-provider.js.map +1 -1
- package/lib/node/health/health-middleware.js +1 -1
- package/lib/node/health/health-middleware.js.map +1 -1
- package/lib/node/http/http-middleware.d.ts +1 -0
- package/lib/node/http/http-middleware.d.ts.map +1 -1
- package/lib/node/http/http-middleware.js +10 -5
- package/lib/node/http/http-middleware.js.map +1 -1
- package/lib/node/http/http-protocol.d.ts +29 -5
- package/lib/node/http/http-protocol.d.ts.map +1 -1
- package/lib/node/http/http-protocol.js.map +1 -1
- package/lib/node/http/http-request.d.ts +42 -0
- package/lib/node/http/http-request.d.ts.map +1 -0
- package/lib/node/http/http-request.js +110 -0
- package/lib/node/http/http-request.js.map +1 -0
- package/lib/node/http/http-request.spec.d.ts +2 -0
- package/lib/node/http/http-request.spec.d.ts.map +1 -0
- package/lib/node/http/http-request.spec.js +65 -0
- package/lib/node/http/http-request.spec.js.map +1 -0
- package/lib/node/http/index.d.ts +1 -0
- package/lib/node/http/index.d.ts.map +1 -1
- package/lib/node/http/index.js +1 -0
- package/lib/node/http/index.js.map +1 -1
- package/lib/node/index.d.ts +1 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +1 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/matcher/index.d.ts +1 -0
- package/lib/node/matcher/index.d.ts.map +1 -1
- package/lib/node/matcher/index.js +1 -0
- package/lib/node/matcher/index.js.map +1 -1
- package/lib/node/matcher/path-pattern.d.ts +24 -0
- package/lib/node/matcher/path-pattern.d.ts.map +1 -0
- package/lib/node/matcher/path-pattern.js +119 -0
- package/lib/node/matcher/path-pattern.js.map +1 -0
- package/lib/node/matcher/path-pattern.spec.d.ts +2 -0
- package/lib/node/matcher/path-pattern.spec.d.ts.map +1 -0
- package/lib/node/matcher/path-pattern.spec.js +43 -0
- package/lib/node/matcher/path-pattern.spec.js.map +1 -0
- package/lib/node/matcher/request-matcher.d.ts +2 -2
- package/lib/node/matcher/request-matcher.d.ts.map +1 -1
- package/lib/node/matcher/request-matcher.js +8 -12
- package/lib/node/matcher/request-matcher.js.map +1 -1
- package/lib/node/module.d.ts +1 -1
- package/lib/node/server/http-server.d.ts +14 -0
- package/lib/node/server/http-server.d.ts.map +1 -0
- package/lib/node/server/http-server.js +35 -0
- package/lib/node/server/http-server.js.map +1 -0
- package/lib/node/server/http-server.spec.d.ts +2 -0
- package/lib/node/server/http-server.spec.d.ts.map +1 -0
- package/lib/node/server/http-server.spec.js +41 -0
- package/lib/node/server/http-server.spec.js.map +1 -0
- package/lib/node/server/index.d.ts +2 -0
- package/lib/node/server/index.d.ts.map +1 -0
- package/lib/node/server/index.js +18 -0
- package/lib/node/server/index.js.map +1 -0
- package/lib/node/session/session-manager.d.ts.map +1 -1
- package/lib/node/session/session-manager.js +1 -2
- package/lib/node/session/session-manager.js.map +1 -1
- package/lib/node/session/session-store.d.ts.map +1 -1
- package/lib/node/session/session-store.js +5 -3
- package/lib/node/session/session-store.js.map +1 -1
- package/lib/node/session/session.d.ts +3 -2
- package/lib/node/session/session.d.ts.map +1 -1
- package/lib/node/session/session.js +4 -8
- package/lib/node/session/session.js.map +1 -1
- package/lib/node/session/session.spec.d.ts +2 -0
- package/lib/node/session/session.spec.d.ts.map +1 -0
- package/lib/node/session/session.spec.js +84 -0
- package/lib/node/session/session.spec.js.map +1 -0
- package/package.json +10 -18
- package/src/common/pipe/index.ts +1 -1
- package/src/common/pipe/type-conversion-pipe.spec.ts +38 -0
- package/src/common/pipe/type-conversion-pipe.ts +36 -0
- package/src/common/pipe/validation-errors.ts +11 -2
- package/src/node/body/body-middleware.spec.ts +96 -0
- package/src/node/body/body-middleware.ts +14 -15
- package/src/node/body/body-parser.ts +216 -0
- package/src/node/body/body-protocol.ts +15 -0
- package/src/node/body/form-util.spec.ts +45 -0
- package/src/node/body/form-util.ts +132 -0
- package/src/node/body/index.ts +2 -0
- package/src/node/context.ts +1 -1
- package/src/node/cookies/cookies-factory.ts +2 -6
- package/src/node/cookies/cookies-protocol.ts +28 -3
- package/src/node/cookies/cookies.spec.ts +80 -0
- package/src/node/cookies/cookies.ts +138 -0
- package/src/node/cookies/index.ts +1 -0
- package/src/node/cors/cors-middleware.spec.ts +59 -0
- package/src/node/cors/cors-middleware.ts +112 -15
- package/src/node/cors/cors-protocol.ts +25 -0
- package/src/node/error/error-handler-provider.ts +1 -2
- package/src/node/health/health-middleware.ts +1 -1
- package/src/node/http/http-middleware.ts +10 -5
- package/src/node/http/http-protocol.ts +29 -5
- package/src/node/http/http-request.spec.ts +68 -0
- package/src/node/http/http-request.ts +132 -0
- package/src/node/http/index.ts +1 -0
- package/src/node/index.ts +1 -0
- package/src/node/matcher/index.ts +1 -0
- package/src/node/matcher/path-pattern.spec.ts +43 -0
- package/src/node/matcher/path-pattern.ts +113 -0
- package/src/node/matcher/request-matcher.ts +9 -10
- package/src/node/server/http-server.spec.ts +45 -0
- package/src/node/server/http-server.ts +35 -0
- package/src/node/server/index.ts +1 -0
- package/src/node/session/session-manager.ts +1 -2
- package/src/node/session/session-store.ts +6 -3
- package/src/node/session/session.spec.ts +88 -0
- package/src/node/session/session.ts +6 -9
- package/esm/common/pipe/pipe-transtorm.d.ts +0 -17
- package/esm/common/pipe/pipe-transtorm.js +0 -110
- package/esm/common/pipe/pipe-transtorm.js.map +0 -1
- package/lib/common/pipe/pipe-transtorm.d.ts +0 -18
- package/lib/common/pipe/pipe-transtorm.d.ts.map +0 -1
- package/lib/common/pipe/pipe-transtorm.js +0 -113
- package/lib/common/pipe/pipe-transtorm.js.map +0 -1
- package/lib/common/pipe/pipe-transtorm.spec.d.ts +0 -2
- package/lib/common/pipe/pipe-transtorm.spec.d.ts.map +0 -1
- package/lib/common/pipe/pipe-transtorm.spec.js +0 -69
- package/lib/common/pipe/pipe-transtorm.spec.js.map +0 -1
- package/src/common/pipe/pipe-transtorm.spec.ts +0 -62
- package/src/common/pipe/pipe-transtorm.ts +0 -113
|
@@ -0,0 +1,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
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { IncomingMessage } from 'http';
|
|
2
|
+
import { FormUtil } from '../body/form-util';
|
|
3
|
+
import { Request } from './http-protocol';
|
|
4
|
+
|
|
5
|
+
const URL_PARTS = Symbol('urlParts');
|
|
6
|
+
const QUERY = Symbol('query');
|
|
7
|
+
const ORIGINAL_URL = Symbol('originalUrl');
|
|
8
|
+
|
|
9
|
+
interface UrlParts {
|
|
10
|
+
url: string;
|
|
11
|
+
path: string;
|
|
12
|
+
search: string;
|
|
13
|
+
query?: Record<string, any>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The request of Cell's server: Node's `IncomingMessage` with `path`, `query`, `protocol`, `hostname`,
|
|
18
|
+
* `ip`, `originalUrl` and `get()`. Computed when read and kept until `url` changes. A request from another
|
|
19
|
+
* server (a test, a serverless proxy) gets them with {@link HttpRequest.enhance}.
|
|
20
|
+
*/
|
|
21
|
+
export class HttpRequest extends IncomingMessage {
|
|
22
|
+
|
|
23
|
+
declare body: any;
|
|
24
|
+
declare protected [URL_PARTS]?: UrlParts;
|
|
25
|
+
declare protected [QUERY]?: Record<string, any>;
|
|
26
|
+
declare protected [ORIGINAL_URL]?: string;
|
|
27
|
+
|
|
28
|
+
/** `request` with the members of HttpRequest, by changing its prototype as express did. */
|
|
29
|
+
static enhance(request: IncomingMessage): Request {
|
|
30
|
+
if (!(request instanceof HttpRequest)) {
|
|
31
|
+
Object.setPrototypeOf(request, HttpRequest.prototype);
|
|
32
|
+
}
|
|
33
|
+
return request as unknown as Request;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get path(): string {
|
|
37
|
+
return this.urlParts().path;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
get query(): Record<string, any> {
|
|
41
|
+
const assigned = this[QUERY];
|
|
42
|
+
if (assigned) {
|
|
43
|
+
return assigned;
|
|
44
|
+
}
|
|
45
|
+
const parts = this.urlParts();
|
|
46
|
+
if (!parts.query) {
|
|
47
|
+
// The query parser of express (qs): five levels of brackets, arrays up to index 20.
|
|
48
|
+
parts.query = parts.search.length > 1 ? FormUtil.parse(parts.search.slice(1), { depth: 5, arrayLimit: 20, parameterLimit: Infinity }) : {};
|
|
49
|
+
}
|
|
50
|
+
return parts.query;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
set query(query: Record<string, any>) {
|
|
54
|
+
this[QUERY] = query;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
get protocol(): 'http' | 'https' {
|
|
58
|
+
return (this.socket as { encrypted?: boolean } | null)?.encrypted ? 'https' : 'http';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
get secure(): boolean {
|
|
62
|
+
return this.protocol === 'https';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
get hostname(): string | undefined {
|
|
66
|
+
const host = this.headers.host;
|
|
67
|
+
if (!host) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
// [::1]:3000 → [::1]
|
|
71
|
+
const end = host[0] === '[' ? host.indexOf(']') + 1 : 0;
|
|
72
|
+
const colon = host.indexOf(':', end);
|
|
73
|
+
return colon < 0 ? host : host.slice(0, colon);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
get ip(): string | undefined {
|
|
77
|
+
return this.socket?.remoteAddress;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
get originalUrl(): string {
|
|
81
|
+
return this[ORIGINAL_URL] ?? this.url ?? '/';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
set originalUrl(url: string) {
|
|
85
|
+
this[ORIGINAL_URL] = url;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
get(name: 'set-cookie'): string[] | undefined;
|
|
89
|
+
get(name: string): string | undefined;
|
|
90
|
+
get(name: string): string | string[] | undefined {
|
|
91
|
+
const key = name.toLowerCase();
|
|
92
|
+
if (key === 'referer' || key === 'referrer') {
|
|
93
|
+
return this.headers.referrer as string | undefined ?? this.headers.referer;
|
|
94
|
+
}
|
|
95
|
+
return this.headers[key];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
header(name: 'set-cookie'): string[] | undefined;
|
|
99
|
+
header(name: string): string | undefined;
|
|
100
|
+
header(name: string): string | string[] | undefined {
|
|
101
|
+
return this.get(name);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
protected urlParts(): UrlParts {
|
|
105
|
+
const url = this.url ?? '/';
|
|
106
|
+
let parts = this[URL_PARTS];
|
|
107
|
+
if (parts?.url !== url) {
|
|
108
|
+
parts = HttpRequest.split(url);
|
|
109
|
+
this[URL_PARTS] = parts;
|
|
110
|
+
}
|
|
111
|
+
return parts;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** `/a?b=1` → path `/a`, search `?b=1`; an absolute URL (a proxy request) keeps only its path. */
|
|
115
|
+
protected static split(url: string): UrlParts {
|
|
116
|
+
if (url[0] !== '/') {
|
|
117
|
+
try {
|
|
118
|
+
const parsed = new URL(url);
|
|
119
|
+
return { url, path: parsed.pathname, search: parsed.search };
|
|
120
|
+
} catch {
|
|
121
|
+
// Not absolute: read it as a path.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const hash = url.indexOf('#');
|
|
125
|
+
const end = hash < 0 ? url.length : hash;
|
|
126
|
+
const question = url.indexOf('?');
|
|
127
|
+
if (question < 0 || question > end) {
|
|
128
|
+
return { url, path: url.slice(0, end), search: '' };
|
|
129
|
+
}
|
|
130
|
+
return { url, path: url.slice(0, question), search: url.slice(question, end) };
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/node/http/index.ts
CHANGED
package/src/node/index.ts
CHANGED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { PathPattern } from './path-pattern';
|
|
4
|
+
|
|
5
|
+
describe('PathPattern', () => {
|
|
6
|
+
// What url-pattern 1.0.3 returned.
|
|
7
|
+
const cases: [string, string, unknown][] = [
|
|
8
|
+
['/users/:id', '/users/42', { id: '42' }],
|
|
9
|
+
['/users/:id', '/users/42/x', null],
|
|
10
|
+
['/*', '/a/b', { _: 'a/b' }],
|
|
11
|
+
['/*', '/', { _: '' }],
|
|
12
|
+
['/api(/:v)/x', '/api/x', {}],
|
|
13
|
+
['/api(/:v)/x', '/api/v1/x', { v: 'v1' }],
|
|
14
|
+
['/a/:x/:x', '/a/1/2', { x: ['1', '2'] }],
|
|
15
|
+
['/login/oauth2/code/*', '/login/oauth2/code/github', { _: 'github' }],
|
|
16
|
+
['/health', '/health', {}],
|
|
17
|
+
['/health', '/health/', null],
|
|
18
|
+
['/health(/:indicatorName)', '/health/db', { indicatorName: 'db' }],
|
|
19
|
+
['/u/:id', '/u/a%20b', { id: 'a%20b' }],
|
|
20
|
+
['/u/:id', '/u/a.b', null],
|
|
21
|
+
['/f\\*', '/f*', {}],
|
|
22
|
+
['/f\\*', '/fx', null],
|
|
23
|
+
['api', 'api', {}],
|
|
24
|
+
['/a/*/b/*', '/a/1/b/2/3', { _: ['1', '2/3'] }],
|
|
25
|
+
['/a.b', '/aXb', null]
|
|
26
|
+
];
|
|
27
|
+
for (const [pattern, path, expected] of cases) {
|
|
28
|
+
it(`${pattern} on ${path}`, () => {
|
|
29
|
+
expect(new PathPattern(pattern).match(path)).to.deep.equal(expected);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
it('returns the groups of a RegExp', () => {
|
|
34
|
+
expect(new PathPattern(/^\/api\/(\d+)$/).match('/api/12')).to.deep.equal(['12']);
|
|
35
|
+
expect(new PathPattern(/^\/api\/(\d+)$/).match('/api/x')).to.equal(null);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('refuses patterns it cannot read', () => {
|
|
39
|
+
for (const pattern of ['', '/a b', '/a(/b', '/a)', '/:', '/()']) {
|
|
40
|
+
expect(() => new PathPattern(pattern), pattern).to.throw();
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const NAME = /^[a-zA-Z0-9]+/;
|
|
2
|
+
const VALUE = '([a-zA-Z0-9\\-_~ %]+)';
|
|
3
|
+
|
|
4
|
+
function escapeRegExp(text: string): string {
|
|
5
|
+
return text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A route pattern, compiled once to a regular expression:
|
|
10
|
+
*
|
|
11
|
+
* - `:name` matches one segment (letters, digits, `-_~ %`) into `name`; a name that appears twice gives an array;
|
|
12
|
+
* - `*` matches anything (also `/`) into `_`;
|
|
13
|
+
* - `(...)` is optional: `/users(/:id)`;
|
|
14
|
+
* - `\\` makes the next character plain: `/files\\*`.
|
|
15
|
+
*
|
|
16
|
+
* `match()` returns the named values (`{}` when there are none) or `null`. A RegExp pattern returns its groups.
|
|
17
|
+
* This is the syntax of the `url-pattern` package, which Cell used before.
|
|
18
|
+
*/
|
|
19
|
+
export class PathPattern {
|
|
20
|
+
|
|
21
|
+
protected readonly regex: RegExp;
|
|
22
|
+
protected readonly names: string[] = [];
|
|
23
|
+
|
|
24
|
+
constructor(protected readonly pattern: string | RegExp) {
|
|
25
|
+
if (pattern instanceof RegExp) {
|
|
26
|
+
this.regex = pattern;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (typeof pattern !== 'string') {
|
|
30
|
+
throw new TypeError('argument must be a regex or a string');
|
|
31
|
+
}
|
|
32
|
+
if (pattern === '') {
|
|
33
|
+
throw new Error('argument must not be the empty string');
|
|
34
|
+
}
|
|
35
|
+
if (/\s/.test(pattern)) {
|
|
36
|
+
throw new Error('argument must not contain whitespace');
|
|
37
|
+
}
|
|
38
|
+
const { source, rest } = this.compile(pattern, false);
|
|
39
|
+
if (rest) {
|
|
40
|
+
throw new Error(`could not parse pattern ${pattern}`);
|
|
41
|
+
}
|
|
42
|
+
this.regex = new RegExp(`^${source}$`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
match(path: string): Record<string, string | string[]> | string[] | null {
|
|
46
|
+
const match = this.regex.exec(path);
|
|
47
|
+
if (!match) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (this.pattern instanceof RegExp) {
|
|
51
|
+
return match.slice(1);
|
|
52
|
+
}
|
|
53
|
+
const params: Record<string, string | string[]> = {};
|
|
54
|
+
for (let i = 0; i < this.names.length; i++) {
|
|
55
|
+
const value = match[i + 1];
|
|
56
|
+
if (value === undefined) {
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const name = this.names[i];
|
|
60
|
+
const existing = params[name];
|
|
61
|
+
if (existing === undefined) {
|
|
62
|
+
params[name] = value;
|
|
63
|
+
} else if (Array.isArray(existing)) {
|
|
64
|
+
existing.push(value);
|
|
65
|
+
} else {
|
|
66
|
+
params[name] = [existing, value];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return params;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Compiles until the end, or until the `)` that closes an optional part; returns what is left after it. */
|
|
73
|
+
protected compile(pattern: string, optional: boolean): { source: string, rest: string } {
|
|
74
|
+
let source = '';
|
|
75
|
+
let rest = pattern;
|
|
76
|
+
while (rest) {
|
|
77
|
+
const c = rest[0];
|
|
78
|
+
if (c === ')') {
|
|
79
|
+
if (!optional) {
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
return { source, rest };
|
|
83
|
+
}
|
|
84
|
+
if (c === '*') {
|
|
85
|
+
this.names.push('_');
|
|
86
|
+
source += '(.*?)';
|
|
87
|
+
rest = rest.slice(1);
|
|
88
|
+
} else if (c === '(') {
|
|
89
|
+
const inner = this.compile(rest.slice(1), true);
|
|
90
|
+
if (!inner.source || !inner.rest.startsWith(')')) {
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
source += `(?:${inner.source})?`;
|
|
94
|
+
rest = inner.rest.slice(1);
|
|
95
|
+
} else if (c === ':') {
|
|
96
|
+
const name = NAME.exec(rest.slice(1))?.[0];
|
|
97
|
+
if (!name) {
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
this.names.push(name);
|
|
101
|
+
source += VALUE;
|
|
102
|
+
rest = rest.slice(1 + name.length);
|
|
103
|
+
} else if (c === '\\' && rest.length > 1) {
|
|
104
|
+
source += escapeRegExp(rest[1]);
|
|
105
|
+
rest = rest.slice(2);
|
|
106
|
+
} else {
|
|
107
|
+
source += escapeRegExp(c);
|
|
108
|
+
rest = rest.slice(1);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { source, rest };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -1,35 +1,34 @@
|
|
|
1
1
|
import { RequestMatcher } from './matcher-protocol';
|
|
2
2
|
import { Context } from '../context';
|
|
3
3
|
import { Component, Value } from '@celljs/core';
|
|
4
|
-
import
|
|
4
|
+
import { PathPattern } from './path-pattern';
|
|
5
5
|
|
|
6
6
|
@Component(RequestMatcher)
|
|
7
7
|
export class RequestMatcherImpl implements RequestMatcher {
|
|
8
|
-
protected caches: Map<string,
|
|
8
|
+
protected caches: Map<string, PathPattern> = new Map<string, PathPattern>();
|
|
9
9
|
|
|
10
10
|
@Value('cell.web.route.cacheSize')
|
|
11
11
|
protected readonly cacheSize: number;
|
|
12
12
|
|
|
13
13
|
async match(pattern: any, method?: string): Promise<any> {
|
|
14
14
|
const request = Context.getRequest();
|
|
15
|
-
const path = request.path;
|
|
16
15
|
if (method && request.method && method.toUpperCase() !== request.method.toUpperCase()) {
|
|
17
16
|
return false;
|
|
18
17
|
}
|
|
19
18
|
pattern = pattern || '/';
|
|
20
|
-
let
|
|
19
|
+
let pathPattern: PathPattern | undefined;
|
|
21
20
|
if (typeof pattern === 'string') {
|
|
22
|
-
|
|
23
|
-
if (!
|
|
24
|
-
|
|
21
|
+
pathPattern = this.caches.get(pattern);
|
|
22
|
+
if (!pathPattern) {
|
|
23
|
+
pathPattern = new PathPattern(pattern);
|
|
25
24
|
if (this.caches.size < this.cacheSize) {
|
|
26
|
-
this.caches.set(pattern,
|
|
25
|
+
this.caches.set(pattern, pathPattern);
|
|
27
26
|
}
|
|
28
27
|
}
|
|
29
28
|
} else {
|
|
30
|
-
|
|
29
|
+
pathPattern = new PathPattern(pattern);
|
|
31
30
|
}
|
|
32
|
-
return
|
|
31
|
+
return pathPattern.match(request.path);
|
|
33
32
|
}
|
|
34
33
|
|
|
35
34
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { afterEach, describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { Server } from 'node:http';
|
|
4
|
+
import type { AddressInfo } from 'node:net';
|
|
5
|
+
import type { Context } from '../context';
|
|
6
|
+
import { Dispatcher } from '../dispatcher/dispatcher-protocol';
|
|
7
|
+
import { HttpRequest } from '../http/http-request';
|
|
8
|
+
import { HttpServerUtil } from './http-server';
|
|
9
|
+
|
|
10
|
+
let server: Server | undefined;
|
|
11
|
+
|
|
12
|
+
afterEach(() => server?.close());
|
|
13
|
+
|
|
14
|
+
async function serve(dispatch: (ctx: Context) => Promise<void>): Promise<string> {
|
|
15
|
+
const container = { get: (id: unknown) => (id === Dispatcher ? { dispatch } : undefined) } as any;
|
|
16
|
+
server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container));
|
|
17
|
+
await new Promise<void>(resolve => server!.listen(0, '127.0.0.1', resolve));
|
|
18
|
+
return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('HttpServerUtil', () => {
|
|
22
|
+
it('dispatches each request with an HttpRequest', async () => {
|
|
23
|
+
const url = await serve(async ctx => {
|
|
24
|
+
expect(ctx.request).to.be.instanceOf(HttpRequest);
|
|
25
|
+
ctx.response.setHeader('content-type', 'application/json');
|
|
26
|
+
ctx.response.end(JSON.stringify({ path: ctx.request.path, query: ctx.request.query, host: ctx.request.hostname }));
|
|
27
|
+
});
|
|
28
|
+
const res = await fetch(`${url}/users/1?tag=a&tag=b`);
|
|
29
|
+
expect(await res.json()).to.deep.equal({ path: '/users/1', query: { tag: ['a', 'b'] }, host: '127.0.0.1' });
|
|
30
|
+
expect(res.headers.get('x-powered-by')).to.equal(null);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('answers 500 when the dispatcher fails', async () => {
|
|
34
|
+
const url = await serve(async () => {
|
|
35
|
+
throw new Error('dispatcher broke');
|
|
36
|
+
});
|
|
37
|
+
const original = console.error;
|
|
38
|
+
console.error = () => undefined;
|
|
39
|
+
try {
|
|
40
|
+
expect((await fetch(url)).status).to.equal(500);
|
|
41
|
+
} finally {
|
|
42
|
+
console.error = original;
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createServer, IncomingMessage, Server, ServerResponse } from 'http';
|
|
2
|
+
import type { Container } from '@celljs/core';
|
|
3
|
+
import { Context } from '../context';
|
|
4
|
+
import { Dispatcher } from '../dispatcher/dispatcher-protocol';
|
|
5
|
+
import { HttpRequest } from '../http/http-request';
|
|
6
|
+
import { Response } from '../http/http-protocol';
|
|
7
|
+
|
|
8
|
+
export type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;
|
|
9
|
+
|
|
10
|
+
export namespace HttpServerUtil {
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The Node `(req, res)` handler of the application: each request runs through the {@link Dispatcher}
|
|
14
|
+
* in its own {@link Context}. Requests of another server (a dev server, a test, a serverless proxy)
|
|
15
|
+
* get the members of {@link HttpRequest} first.
|
|
16
|
+
*/
|
|
17
|
+
export function createHandler(container: Pick<Container, 'get'>): RequestListener {
|
|
18
|
+
const dispatcher = container.get<Dispatcher<Context>>(Dispatcher);
|
|
19
|
+
return (req, res) => {
|
|
20
|
+
const ctx = new Context(HttpRequest.enhance(req), res as Response);
|
|
21
|
+
Context.run(() => dispatcher.dispatch(ctx)).catch(error => {
|
|
22
|
+
console.error(error);
|
|
23
|
+
if (!res.headersSent) {
|
|
24
|
+
res.statusCode = 500;
|
|
25
|
+
}
|
|
26
|
+
res.end();
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A `node:http` server whose requests are {@link HttpRequest}s from the start. */
|
|
32
|
+
export function createHttpServer(handler: RequestListener): Server {
|
|
33
|
+
return createServer({ IncomingMessage: HttpRequest }, handler);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './http-server';
|
|
@@ -41,8 +41,7 @@ export class SessionManagerImpl implements SessionManager {
|
|
|
41
41
|
await this.sessionStore.remove(Context.getSession().id);
|
|
42
42
|
}
|
|
43
43
|
Context.getCookies().set(this.sessionIdKey, '', {
|
|
44
|
-
expires: COOKIE_EXP_DATE
|
|
45
|
-
maxAge: false,
|
|
44
|
+
expires: COOKIE_EXP_DATE
|
|
46
45
|
});
|
|
47
46
|
}
|
|
48
47
|
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { Session, SessionStrategy, SessionStore, COOKIE_EXP_DATE } from './session-protocol';
|
|
2
2
|
import { Autowired, Value, Component, Logger } from '@celljs/core';
|
|
3
3
|
import { Context } from '../context';
|
|
4
|
-
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { gzip as gzipCallback, gunzip } from 'node:zlib';
|
|
6
|
+
|
|
7
|
+
const gzip = promisify(gzipCallback);
|
|
8
|
+
const ungzip = promisify(gunzip);
|
|
5
9
|
|
|
6
10
|
@Component(SessionStore)
|
|
7
11
|
export class CookieSessionStore implements SessionStore {
|
|
@@ -37,8 +41,7 @@ export class CookieSessionStore implements SessionStore {
|
|
|
37
41
|
|
|
38
42
|
async remove(id: string): Promise<void> {
|
|
39
43
|
Context.getCookies().set(this.sessionOptions.sessionKey, '', {
|
|
40
|
-
expires: COOKIE_EXP_DATE
|
|
41
|
-
maxAge: false,
|
|
44
|
+
expires: COOKIE_EXP_DATE
|
|
42
45
|
});
|
|
43
46
|
}
|
|
44
47
|
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { Context } from '../context';
|
|
4
|
+
import { SessionImpl } from './session';
|
|
5
|
+
import { CookieSessionStore } from './session-store';
|
|
6
|
+
import { SessionStrategyImpl } from './session-strategy';
|
|
7
|
+
|
|
8
|
+
const options = { maxAge: 1000, sessionKey: 'cell:session' };
|
|
9
|
+
|
|
10
|
+
/** Runs fn in a request context and waits for it (Context.run does not return its promise with cls-hooked). */
|
|
11
|
+
function inContext(fn: () => Promise<void>): Promise<void> {
|
|
12
|
+
return new Promise((resolve, reject) => {
|
|
13
|
+
Context.run(async () => {
|
|
14
|
+
try {
|
|
15
|
+
Context.setCurrent(new Context({} as any, {} as any));
|
|
16
|
+
await fn();
|
|
17
|
+
resolve();
|
|
18
|
+
} catch (error) {
|
|
19
|
+
reject(error);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('SessionImpl', () => {
|
|
26
|
+
it('is unchanged until a value changes', () => {
|
|
27
|
+
const session = new SessionImpl(options) as SessionImpl & Record<string, unknown>;
|
|
28
|
+
expect(session.isNew).to.equal(true);
|
|
29
|
+
expect(session.changed).to.equal(false);
|
|
30
|
+
session.user = 'tom';
|
|
31
|
+
expect(session.changed).to.equal(true);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('serializes its values without isNew and private fields', () => {
|
|
35
|
+
const session = new SessionImpl(options) as SessionImpl & Record<string, unknown>;
|
|
36
|
+
session.user = 'tom';
|
|
37
|
+
const json = session.toJSON();
|
|
38
|
+
expect(json).to.include({ user: 'tom', maxAge: 1000 });
|
|
39
|
+
expect(Object.keys(json)).to.not.include.members(['isNew', '_snapshot']);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('notices changes inside nested values', () => {
|
|
43
|
+
const session = new SessionImpl(options, { id: 'x', user: { name: 'tom', roles: ['admin'] }, expire: 5, maxAge: 1000 }) as SessionImpl & { user: { roles: string[] } };
|
|
44
|
+
expect(session.changed).to.equal(false);
|
|
45
|
+
session.user.roles.push('dev');
|
|
46
|
+
expect(session.changed).to.equal(true);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('restored from its values it is not new and unchanged', () => {
|
|
50
|
+
const session = new SessionImpl(options, { id: 'x', user: 'tom', expire: 5, maxAge: 1000 });
|
|
51
|
+
expect(session.isNew).to.equal(false);
|
|
52
|
+
expect(session.changed).to.equal(false);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('CookieSessionStore', () => {
|
|
57
|
+
it('stores a session compressed in a cookie and reads it back', async () => {
|
|
58
|
+
const jar = new Map<string, string>();
|
|
59
|
+
const store = new CookieSessionStore();
|
|
60
|
+
const strategy = new SessionStrategyImpl();
|
|
61
|
+
Object.assign(strategy, { sessionOptions: options });
|
|
62
|
+
Object.assign(store, { sessionOptions: options, sessionStrategy: strategy, logger: { error: () => undefined } });
|
|
63
|
+
await inContext(async () => {
|
|
64
|
+
Context.setCookies({ get: (k: string) => jar.get(k), set: (k: string, v: string) => { jar.set(k, v); } } as any);
|
|
65
|
+
const session = new SessionImpl(options) as SessionImpl & Record<string, unknown>;
|
|
66
|
+
session.user = '中文 user';
|
|
67
|
+
await store.set(session);
|
|
68
|
+
const value = jar.get('cell:session')!;
|
|
69
|
+
expect(value).to.match(/^[A-Za-z0-9+/]+=*$/);
|
|
70
|
+
expect(Buffer.from(value, 'base64').subarray(0, 2)).to.deep.equal(Buffer.from([0x1f, 0x8b]));
|
|
71
|
+
const restored = await store.get('ignored') as SessionImpl & Record<string, unknown>;
|
|
72
|
+
expect(restored.user).to.equal('中文 user');
|
|
73
|
+
expect(restored.id).to.equal(session.id);
|
|
74
|
+
expect(restored.changed).to.equal(false);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('ignores a cookie it cannot read', async () => {
|
|
79
|
+
const errors: unknown[] = [];
|
|
80
|
+
const store = new CookieSessionStore();
|
|
81
|
+
Object.assign(store, { sessionOptions: options, sessionStrategy: new SessionStrategyImpl(), logger: { error: (e: unknown) => errors.push(e) } });
|
|
82
|
+
await inContext(async () => {
|
|
83
|
+
Context.setCookies({ get: () => 'bm90IGd6aXA=' } as any);
|
|
84
|
+
expect(await store.get('x')).to.equal(undefined);
|
|
85
|
+
});
|
|
86
|
+
expect(errors).to.have.length(1);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { generateUUUID } from '@celljs/core/lib/common/utils/uuid';
|
|
2
2
|
import { Session } from './session-protocol';
|
|
3
|
-
const crc32 = require('crc/crc32');
|
|
4
3
|
|
|
5
4
|
export class SessionImpl implements Session {
|
|
6
5
|
readonly id = generateUUUID();
|
|
7
6
|
isNew = true;
|
|
8
7
|
expire: number;
|
|
9
8
|
maxAge: number;
|
|
10
|
-
|
|
9
|
+
/** The serialized values when the session was created or restored, to tell whether it changed. */
|
|
10
|
+
protected _snapshot: string;
|
|
11
11
|
constructor(sessionOptions: any, obj?: any) {
|
|
12
12
|
if (obj) {
|
|
13
13
|
this.isNew = false;
|
|
@@ -18,11 +18,11 @@ export class SessionImpl implements Session {
|
|
|
18
18
|
this.expire = sessionOptions.maxAge + Date.now();
|
|
19
19
|
this.maxAge = sessionOptions.maxAge;
|
|
20
20
|
}
|
|
21
|
-
this.
|
|
21
|
+
this._snapshot = this.serialize();
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
protected
|
|
25
|
-
return
|
|
24
|
+
protected serialize(): string {
|
|
25
|
+
return JSON.stringify(this.toJSON());
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
toJSON(): any {
|
|
@@ -36,10 +36,7 @@ export class SessionImpl implements Session {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
get changed() {
|
|
39
|
-
|
|
40
|
-
return true;
|
|
41
|
-
}
|
|
42
|
-
return false;
|
|
39
|
+
return this._snapshot !== this.serialize();
|
|
43
40
|
}
|
|
44
41
|
|
|
45
42
|
}
|