@tessellation/http 0.0.0-stage → 2.0.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/LICENSE +21 -0
- package/README.md +412 -2
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/lib/auth/api-key.d.ts +17 -0
- package/dist/lib/auth/api-key.d.ts.map +1 -0
- package/dist/lib/auth/api-key.js +48 -0
- package/dist/lib/auth/jwt.d.ts +33 -0
- package/dist/lib/auth/jwt.d.ts.map +1 -0
- package/dist/lib/auth/jwt.js +227 -0
- package/dist/lib/auth/provide-auth.d.ts +30 -0
- package/dist/lib/auth/provide-auth.d.ts.map +1 -0
- package/dist/lib/auth/provide-auth.js +69 -0
- package/dist/lib/auth/strategy.d.ts +47 -0
- package/dist/lib/auth/strategy.d.ts.map +1 -0
- package/dist/lib/auth/strategy.js +18 -0
- package/dist/lib/compile.d.ts +46 -0
- package/dist/lib/compile.d.ts.map +1 -0
- package/dist/lib/compile.js +126 -0
- package/dist/lib/compression.d.ts +23 -0
- package/dist/lib/compression.d.ts.map +1 -0
- package/dist/lib/compression.js +86 -0
- package/dist/lib/config.d.ts +173 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +93 -0
- package/dist/lib/cors.d.ts +41 -0
- package/dist/lib/cors.d.ts.map +1 -0
- package/dist/lib/cors.js +101 -0
- package/dist/lib/docs.d.ts +15 -0
- package/dist/lib/docs.d.ts.map +1 -0
- package/dist/lib/docs.js +93 -0
- package/dist/lib/engine.d.ts +83 -0
- package/dist/lib/engine.d.ts.map +1 -0
- package/dist/lib/engine.js +562 -0
- package/dist/lib/errors.d.ts +31 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +55 -0
- package/dist/lib/etag.d.ts +5 -0
- package/dist/lib/etag.d.ts.map +1 -0
- package/dist/lib/etag.js +30 -0
- package/dist/lib/headers.d.ts +3 -0
- package/dist/lib/headers.d.ts.map +1 -0
- package/dist/lib/headers.js +14 -0
- package/dist/lib/json-schema.d.ts +11 -0
- package/dist/lib/json-schema.d.ts.map +1 -0
- package/dist/lib/json-schema.js +23 -0
- package/dist/lib/openapi.d.ts +18 -0
- package/dist/lib/openapi.d.ts.map +1 -0
- package/dist/lib/openapi.js +218 -0
- package/dist/lib/rate-limit.d.ts +52 -0
- package/dist/lib/rate-limit.d.ts.map +1 -0
- package/dist/lib/rate-limit.js +87 -0
- package/dist/lib/reply.d.ts +27 -0
- package/dist/lib/reply.d.ts.map +1 -0
- package/dist/lib/reply.js +52 -0
- package/dist/lib/request.d.ts +55 -0
- package/dist/lib/request.d.ts.map +1 -0
- package/dist/lib/request.js +36 -0
- package/dist/lib/router.d.ts +35 -0
- package/dist/lib/router.d.ts.map +1 -0
- package/dist/lib/router.js +173 -0
- package/dist/lib/routes.d.ts +196 -0
- package/dist/lib/routes.d.ts.map +1 -0
- package/dist/lib/routes.js +98 -0
- package/dist/lib/security-headers.d.ts +19 -0
- package/dist/lib/security-headers.d.ts.map +1 -0
- package/dist/lib/security-headers.js +22 -0
- package/dist/lib/serializer.d.ts +35 -0
- package/dist/lib/serializer.d.ts.map +1 -0
- package/dist/lib/serializer.js +147 -0
- package/dist/lib/server.d.ts +86 -0
- package/dist/lib/server.d.ts.map +1 -0
- package/dist/lib/server.js +255 -0
- package/dist/lib/testing.d.ts +21 -0
- package/dist/lib/testing.d.ts.map +1 -0
- package/dist/lib/testing.js +62 -0
- package/dist/lib/transports/node.d.ts +4 -0
- package/dist/lib/transports/node.d.ts.map +1 -0
- package/dist/lib/transports/node.js +249 -0
- package/dist/lib/transports/transport.d.ts +32 -0
- package/dist/lib/transports/transport.d.ts.map +1 -0
- package/dist/lib/transports/transport.js +1 -0
- package/dist/lib/transports/uws.d.ts +8 -0
- package/dist/lib/transports/uws.d.ts.map +1 -0
- package/dist/lib/transports/uws.js +246 -0
- package/dist/lib/websocket.d.ts +71 -0
- package/dist/lib/websocket.d.ts.map +1 -0
- package/dist/lib/websocket.js +125 -0
- package/package.json +67 -3
- package/src/index.ts +103 -0
- package/src/lib/auth/api-key.ts +73 -0
- package/src/lib/auth/jwt.ts +339 -0
- package/src/lib/auth/provide-auth.ts +99 -0
- package/src/lib/auth/strategy.ts +66 -0
- package/src/lib/compile.ts +207 -0
- package/src/lib/compression.ts +121 -0
- package/src/lib/config.ts +107 -0
- package/src/lib/cors.ts +146 -0
- package/src/lib/docs.ts +115 -0
- package/src/lib/engine.ts +770 -0
- package/src/lib/errors.ts +84 -0
- package/src/lib/etag.ts +37 -0
- package/src/lib/headers.ts +18 -0
- package/src/lib/json-schema.ts +36 -0
- package/src/lib/openapi.ts +299 -0
- package/src/lib/rate-limit.ts +142 -0
- package/src/lib/reply.ts +70 -0
- package/src/lib/request.ts +83 -0
- package/src/lib/router.ts +217 -0
- package/src/lib/routes.ts +414 -0
- package/src/lib/security-headers.ts +38 -0
- package/src/lib/serializer.ts +203 -0
- package/src/lib/server.ts +352 -0
- package/src/lib/testing.ts +88 -0
- package/src/lib/transports/node.ts +315 -0
- package/src/lib/transports/transport.ts +39 -0
- package/src/lib/transports/uws.ts +310 -0
- package/src/lib/websocket.ts +184 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Headers added to every response that does not already set them. The
|
|
3
|
+
* defaults suit a JSON API: no MIME sniffing, no framing, no referrers.
|
|
4
|
+
*/
|
|
5
|
+
export function securityHeaders(options = {}) {
|
|
6
|
+
const headers = [
|
|
7
|
+
['x-content-type-options', 'nosniff'],
|
|
8
|
+
['x-frame-options', options.frameOptions ?? 'DENY'],
|
|
9
|
+
['referrer-policy', options.referrerPolicy ?? 'no-referrer'],
|
|
10
|
+
['cross-origin-opener-policy', 'same-origin'],
|
|
11
|
+
];
|
|
12
|
+
if (options.hsts !== undefined && options.hsts > 0) {
|
|
13
|
+
headers.push([
|
|
14
|
+
'strict-transport-security',
|
|
15
|
+
`max-age=${Math.floor(options.hsts / 1000)}; includeSubDomains`,
|
|
16
|
+
]);
|
|
17
|
+
}
|
|
18
|
+
if (options.contentSecurityPolicy !== undefined) {
|
|
19
|
+
headers.push(['content-security-policy', options.contentSecurityPolicy]);
|
|
20
|
+
}
|
|
21
|
+
return headers;
|
|
22
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response serialization driven by a route's response schema.
|
|
3
|
+
*
|
|
4
|
+
* Benchmarks on Node 26 showed that V8's `JSON.stringify` (C++, with a
|
|
5
|
+
* vectorized escaping scan) beats any serializer generated in JavaScript on
|
|
6
|
+
* string-heavy payloads: escaping checks alone cost ~28ns per string in JS.
|
|
7
|
+
* So V8 does the serializing, and the schema decides what is serialized: a
|
|
8
|
+
* compiled projection copies only declared properties, so fields a handler
|
|
9
|
+
* returns by accident (such as a password hash) never leak. Projection plus
|
|
10
|
+
* `JSON.stringify` measured within ~5% of `JSON.stringify` alone.
|
|
11
|
+
*
|
|
12
|
+
* Local references (`#/$defs/...`, which Zod emits for schemas named with
|
|
13
|
+
* `.meta({ id })`) are followed, including recursive ones. Parts of a schema
|
|
14
|
+
* without a fixed set of properties (records, open objects, unions other
|
|
15
|
+
* than `T | null`, other references) are passed through as-is.
|
|
16
|
+
*/
|
|
17
|
+
export type JsonSchema = boolean | {
|
|
18
|
+
type?: string | string[];
|
|
19
|
+
properties?: Record<string, JsonSchema>;
|
|
20
|
+
additionalProperties?: JsonSchema;
|
|
21
|
+
patternProperties?: Record<string, JsonSchema>;
|
|
22
|
+
items?: JsonSchema;
|
|
23
|
+
prefixItems?: JsonSchema[];
|
|
24
|
+
anyOf?: JsonSchema[];
|
|
25
|
+
oneOf?: JsonSchema[];
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
};
|
|
28
|
+
export type Serializer = (value: unknown) => string;
|
|
29
|
+
type Projection = (value: unknown) => unknown;
|
|
30
|
+
/** Compiles a projection keeping only declared properties, or undefined if none applies. */
|
|
31
|
+
export declare function compileProjection(schema: JsonSchema): Projection | undefined;
|
|
32
|
+
/** A serializer for values described by `schema`: projection, then `JSON.stringify`. */
|
|
33
|
+
export declare function compileSerializer(schema: JsonSchema): Serializer;
|
|
34
|
+
export {};
|
|
35
|
+
//# sourceMappingURL=serializer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serializer.d.ts","sourceRoot":"","sources":["../../src/lib/serializer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,UAAU,GAClB,OAAO,GACP;IACE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACxC,oBAAoB,CAAC,EAAE,UAAU,CAAC;IAClC,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAC/C,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,WAAW,CAAC,EAAE,UAAU,EAAE,CAAC;IAC3B,KAAK,CAAC,EAAE,UAAU,EAAE,CAAC;IACrB,KAAK,CAAC,EAAE,UAAU,EAAE,CAAC;IACrB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAEN,MAAM,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,CAAC;AACpD,KAAK,UAAU,GAAG,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;AAmJ9C,4FAA4F;AAC5F,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,GAAG,SAAS,CAc5E;AAED,wFAAwF;AACxF,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,CAKhE"}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response serialization driven by a route's response schema.
|
|
3
|
+
*
|
|
4
|
+
* Benchmarks on Node 26 showed that V8's `JSON.stringify` (C++, with a
|
|
5
|
+
* vectorized escaping scan) beats any serializer generated in JavaScript on
|
|
6
|
+
* string-heavy payloads: escaping checks alone cost ~28ns per string in JS.
|
|
7
|
+
* So V8 does the serializing, and the schema decides what is serialized: a
|
|
8
|
+
* compiled projection copies only declared properties, so fields a handler
|
|
9
|
+
* returns by accident (such as a password hash) never leak. Projection plus
|
|
10
|
+
* `JSON.stringify` measured within ~5% of `JSON.stringify` alone.
|
|
11
|
+
*
|
|
12
|
+
* Local references (`#/$defs/...`, which Zod emits for schemas named with
|
|
13
|
+
* `.meta({ id })`) are followed, including recursive ones. Parts of a schema
|
|
14
|
+
* without a fixed set of properties (records, open objects, unions other
|
|
15
|
+
* than `T | null`, other references) are passed through as-is.
|
|
16
|
+
*/
|
|
17
|
+
const LOCAL_REF = /^#\/\$defs\/(.+)$/;
|
|
18
|
+
class Compiler {
|
|
19
|
+
defs;
|
|
20
|
+
functions = [];
|
|
21
|
+
/** Function names for `$defs` entries, so each is compiled once (and recursion terminates). */
|
|
22
|
+
definitions = new Map();
|
|
23
|
+
constructor(defs) {
|
|
24
|
+
this.defs = defs;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Returns the name of a generated function projecting values of `schema`,
|
|
28
|
+
* or undefined when values pass through unchanged.
|
|
29
|
+
*/
|
|
30
|
+
compile(schema) {
|
|
31
|
+
if (typeof schema !== 'object') {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
if (typeof schema['$ref'] === 'string') {
|
|
35
|
+
return this.reference(schema['$ref']);
|
|
36
|
+
}
|
|
37
|
+
const nullable = nullableInner(schema);
|
|
38
|
+
if (nullable !== undefined) {
|
|
39
|
+
const inner = this.compile(nullable);
|
|
40
|
+
return inner === undefined
|
|
41
|
+
? undefined
|
|
42
|
+
: this.define((name) => `function ${name}(v) { return v === null ? null : ${inner}(v); }`);
|
|
43
|
+
}
|
|
44
|
+
if (schema.type === 'array' &&
|
|
45
|
+
schema.items !== undefined &&
|
|
46
|
+
schema.prefixItems === undefined) {
|
|
47
|
+
const item = this.compile(schema.items);
|
|
48
|
+
return item === undefined
|
|
49
|
+
? undefined
|
|
50
|
+
: this.define((name) => `function ${name}(v) {\n` +
|
|
51
|
+
` if (!Array.isArray(v)) return v;\n` +
|
|
52
|
+
` const n = v.length, out = new Array(n);\n` +
|
|
53
|
+
` for (let i = 0; i < n; i++) out[i] = ${item}(v[i]);\n` +
|
|
54
|
+
` return out;\n}`);
|
|
55
|
+
}
|
|
56
|
+
if (schema.type === 'object' &&
|
|
57
|
+
schema.properties !== undefined &&
|
|
58
|
+
!keepsExtraProperties(schema)) {
|
|
59
|
+
const entries = Object.entries(schema.properties).map(([key, property]) => {
|
|
60
|
+
const access = `v[${JSON.stringify(key)}]`;
|
|
61
|
+
const fn = this.compile(property);
|
|
62
|
+
// A literal "__proto__" key would set the prototype; compute it instead.
|
|
63
|
+
const literalKey = key === '__proto__'
|
|
64
|
+
? `[${JSON.stringify(key)}]`
|
|
65
|
+
: JSON.stringify(key);
|
|
66
|
+
return `${literalKey}: ${fn === undefined ? access : `${fn}(${access})`}`;
|
|
67
|
+
});
|
|
68
|
+
return this.define((name) => `function ${name}(v) {\n` +
|
|
69
|
+
` if (typeof v !== 'object' || v === null || Array.isArray(v) || typeof v.toJSON === 'function') return v;\n` +
|
|
70
|
+
` return { ${entries.join(', ')} };\n}`);
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
reference(ref) {
|
|
75
|
+
const name = LOCAL_REF.exec(ref)?.[1];
|
|
76
|
+
const definition = name === undefined ? undefined : this.defs[name];
|
|
77
|
+
if (name === undefined || definition === undefined) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
if (this.definitions.has(name)) {
|
|
81
|
+
return this.definitions.get(name);
|
|
82
|
+
}
|
|
83
|
+
// Reserve a name first, so a definition referring to itself calls it.
|
|
84
|
+
const fn = `d${this.definitions.size}`;
|
|
85
|
+
this.definitions.set(name, fn);
|
|
86
|
+
const body = this.compile(definition);
|
|
87
|
+
if (body === undefined) {
|
|
88
|
+
this.definitions.set(name, undefined);
|
|
89
|
+
// Earlier references (in recursive schemas) need the function to exist.
|
|
90
|
+
this.functions.push(`function ${fn}(v) { return v; }`);
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
this.functions.push(`function ${fn}(v) { return ${body}(v); }`);
|
|
94
|
+
return fn;
|
|
95
|
+
}
|
|
96
|
+
source(entry) {
|
|
97
|
+
return `${this.functions.join('\n')}\nreturn ${entry};`;
|
|
98
|
+
}
|
|
99
|
+
define(build) {
|
|
100
|
+
const name = `p${this.functions.length}`;
|
|
101
|
+
this.functions.push(build(name));
|
|
102
|
+
return name;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function keepsExtraProperties(schema) {
|
|
106
|
+
return ((schema.additionalProperties !== undefined &&
|
|
107
|
+
schema.additionalProperties !== false) ||
|
|
108
|
+
schema.patternProperties !== undefined);
|
|
109
|
+
}
|
|
110
|
+
/** For `T | null` (as `anyOf`/`oneOf` or a type list), returns the schema of `T`. */
|
|
111
|
+
function nullableInner(schema) {
|
|
112
|
+
const options = schema.anyOf ?? schema.oneOf;
|
|
113
|
+
if (options?.length === 2 && Object.keys(schema).length === 1) {
|
|
114
|
+
const nonNull = options.filter((option) => !(typeof option === 'object' && option.type === 'null'));
|
|
115
|
+
if (nonNull.length === 1) {
|
|
116
|
+
return nonNull[0];
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(schema.type) &&
|
|
120
|
+
schema.type.length === 2 &&
|
|
121
|
+
schema.type.includes('null')) {
|
|
122
|
+
return { ...schema, type: schema.type.find((type) => type !== 'null') };
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/** Compiles a projection keeping only declared properties, or undefined if none applies. */
|
|
127
|
+
export function compileProjection(schema) {
|
|
128
|
+
const defs = typeof schema === 'object' &&
|
|
129
|
+
typeof schema['$defs'] === 'object' &&
|
|
130
|
+
schema['$defs'] !== null
|
|
131
|
+
? schema['$defs']
|
|
132
|
+
: {};
|
|
133
|
+
const compiler = new Compiler(defs);
|
|
134
|
+
const entry = compiler.compile(schema);
|
|
135
|
+
if (entry === undefined) {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
// Keys are embedded only through JSON.stringify, never as raw source.
|
|
139
|
+
return new Function(compiler.source(entry))();
|
|
140
|
+
}
|
|
141
|
+
/** A serializer for values described by `schema`: projection, then `JSON.stringify`. */
|
|
142
|
+
export function compileSerializer(schema) {
|
|
143
|
+
const project = compileProjection(schema);
|
|
144
|
+
return project === undefined
|
|
145
|
+
? (value) => JSON.stringify(value)
|
|
146
|
+
: (value) => JSON.stringify(project(value));
|
|
147
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { InjectionToken, type ProvidedIn, type Provider } from '@tessellation/core';
|
|
2
|
+
import { type HttpSettings } from './config.js';
|
|
3
|
+
import type { Middleware, RouteTree } from './routes.js';
|
|
4
|
+
import { type TestRequestInit, type TestResponse } from './testing.js';
|
|
5
|
+
type NestedSettings = 'websocket' | 'docs' | 'cors' | 'requestId' | 'compression' | 'securityHeaders' | 'rateLimit';
|
|
6
|
+
export interface HttpOptions extends Omit<HttpSettings, NestedSettings> {
|
|
7
|
+
/** Route trees to serve. */
|
|
8
|
+
routes: readonly RouteTree[];
|
|
9
|
+
/** Path prefix for every route, such as `/api`. */
|
|
10
|
+
prefix?: string;
|
|
11
|
+
/** Middleware for every route, outermost first. */
|
|
12
|
+
middleware?: readonly Middleware[];
|
|
13
|
+
docs?: HttpSettings['docs'];
|
|
14
|
+
/** Cross-origin resource sharing; off unless origins are given. */
|
|
15
|
+
cors?: HttpSettings['cors'];
|
|
16
|
+
requestId?: HttpSettings['requestId'];
|
|
17
|
+
compression?: HttpSettings['compression'];
|
|
18
|
+
securityHeaders?: HttpSettings['securityHeaders'];
|
|
19
|
+
/** A rate limit for every route; off unless `limit` is given. */
|
|
20
|
+
rateLimit?: HttpSettings['rateLimit'];
|
|
21
|
+
websocket?: HttpSettings['websocket'];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Global middleware contributed by other modules, outermost first. Runs
|
|
25
|
+
* before the middleware passed to `provideHttp()`.
|
|
26
|
+
*/
|
|
27
|
+
export declare const HTTP_MIDDLEWARE: InjectionToken<Middleware[]>;
|
|
28
|
+
/** Adds global middleware from a module, such as metrics or auditing. */
|
|
29
|
+
export declare function provideHttpMiddleware(...middleware: Middleware[]): Provider[];
|
|
30
|
+
export declare const HTTP_OPTIONS: InjectionToken<HttpOptions>;
|
|
31
|
+
/**
|
|
32
|
+
* The HTTP server. Starts listening in a start hook; on shutdown it stops
|
|
33
|
+
* accepting connections, lets in-flight requests finish (asking clients to
|
|
34
|
+
* close their connections), then closes what is left.
|
|
35
|
+
*/
|
|
36
|
+
export declare class HttpServer implements AsyncDisposable {
|
|
37
|
+
static readonly providedIn: ProvidedIn;
|
|
38
|
+
/** Code options with the `http` config section applied on top. */
|
|
39
|
+
readonly options: HttpOptions;
|
|
40
|
+
private readonly injector;
|
|
41
|
+
private readonly log;
|
|
42
|
+
private readonly plugins;
|
|
43
|
+
private readonly metrics;
|
|
44
|
+
private readonly tracer;
|
|
45
|
+
private readonly authStrategies;
|
|
46
|
+
private engine;
|
|
47
|
+
private server;
|
|
48
|
+
private transportName;
|
|
49
|
+
constructor();
|
|
50
|
+
/** The bound port, once listening. */
|
|
51
|
+
get port(): number | undefined;
|
|
52
|
+
/** The transport in use, once listening: `uws` or `node`. */
|
|
53
|
+
get transport(): string | undefined;
|
|
54
|
+
listen(): Promise<void>;
|
|
55
|
+
/** Request metrics, when `provideMetrics()` is used. */
|
|
56
|
+
private requestMetrics;
|
|
57
|
+
/** The rate limit from config, then plugin middleware, then `provideHttp({ middleware })`. */
|
|
58
|
+
private globalMiddleware;
|
|
59
|
+
/**
|
|
60
|
+
* Sends a request through the full pipeline in memory, without a socket.
|
|
61
|
+
* Use it in tests, with `http.transport: none` to skip listening.
|
|
62
|
+
*
|
|
63
|
+
* ```ts
|
|
64
|
+
* const response = await server.request({ method: 'POST', path: '/users', body: { name: 'Ada' } });
|
|
65
|
+
* expect(response.status).toBe(201);
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
request(init: TestRequestInit): Promise<TestResponse>;
|
|
69
|
+
/** Sends a message to every WebSocket subscribed to `topic`, on any route. */
|
|
70
|
+
publish(topic: string, message: string | Uint8Array): void;
|
|
71
|
+
/** Graceful close: stop accepting, drain in-flight requests, close connections. */
|
|
72
|
+
close(): Promise<void>;
|
|
73
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
74
|
+
private forceClose;
|
|
75
|
+
private selectTransport;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Serves routes over HTTP for the lifetime of the application.
|
|
79
|
+
*
|
|
80
|
+
* ```ts
|
|
81
|
+
* provideHttp({ prefix: '/api', routes: [userRoutes] })
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
export declare function provideHttp(options: HttpOptions): Provider[];
|
|
85
|
+
export {};
|
|
86
|
+
//# sourceMappingURL=server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/lib/server.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { inject, METRICS, InjectionToken, Injector, Logger, onShutdown, onStart, provide, provideConfig, Tracer, } from '@tessellation/core';
|
|
2
|
+
import { AUTH_STRATEGIES } from './auth/strategy.js';
|
|
3
|
+
import { compileRoutes } from './compile.js';
|
|
4
|
+
import { Compressor } from './compression.js';
|
|
5
|
+
import { HttpConfig } from './config.js';
|
|
6
|
+
import { CorsPolicy } from './cors.js';
|
|
7
|
+
import { docsRoutes } from './docs.js';
|
|
8
|
+
import { HttpEngine } from './engine.js';
|
|
9
|
+
import { rateLimit } from './rate-limit.js';
|
|
10
|
+
import { securityHeaders } from './security-headers.js';
|
|
11
|
+
import { nodeTransport } from './transports/node.js';
|
|
12
|
+
import { dispatch, } from './testing.js';
|
|
13
|
+
const NESTED = [
|
|
14
|
+
'websocket',
|
|
15
|
+
'docs',
|
|
16
|
+
'cors',
|
|
17
|
+
'requestId',
|
|
18
|
+
'compression',
|
|
19
|
+
'securityHeaders',
|
|
20
|
+
'rateLimit',
|
|
21
|
+
];
|
|
22
|
+
/**
|
|
23
|
+
* Global middleware contributed by other modules, outermost first. Runs
|
|
24
|
+
* before the middleware passed to `provideHttp()`.
|
|
25
|
+
*/
|
|
26
|
+
export const HTTP_MIDDLEWARE = new InjectionToken('HTTP_MIDDLEWARE');
|
|
27
|
+
/** Adds global middleware from a module, such as metrics or auditing. */
|
|
28
|
+
export function provideHttpMiddleware(...middleware) {
|
|
29
|
+
return middleware.map((entry) => provide(HTTP_MIDDLEWARE, { useValue: entry, multi: true }));
|
|
30
|
+
}
|
|
31
|
+
export const HTTP_OPTIONS = new InjectionToken('HTTP_OPTIONS');
|
|
32
|
+
const DEFAULT_BODY_LIMIT = 1024 * 1024;
|
|
33
|
+
/**
|
|
34
|
+
* The HTTP server. Starts listening in a start hook; on shutdown it stops
|
|
35
|
+
* accepting connections, lets in-flight requests finish (asking clients to
|
|
36
|
+
* close their connections), then closes what is left.
|
|
37
|
+
*/
|
|
38
|
+
export class HttpServer {
|
|
39
|
+
static providedIn = null;
|
|
40
|
+
/** Code options with the `http` config section applied on top. */
|
|
41
|
+
options;
|
|
42
|
+
injector = inject(Injector);
|
|
43
|
+
log = inject(Logger).child('http');
|
|
44
|
+
plugins = inject(HTTP_MIDDLEWARE, { optional: true }) ?? [];
|
|
45
|
+
metrics = inject(METRICS, { optional: true });
|
|
46
|
+
tracer = inject(Tracer);
|
|
47
|
+
authStrategies = inject(AUTH_STRATEGIES, { optional: true }) ?? [];
|
|
48
|
+
engine;
|
|
49
|
+
server;
|
|
50
|
+
transportName;
|
|
51
|
+
constructor() {
|
|
52
|
+
const code = inject(HTTP_OPTIONS);
|
|
53
|
+
const config = inject(HttpConfig, { optional: true }) ?? {};
|
|
54
|
+
const merged = { ...code, ...config };
|
|
55
|
+
for (const key of NESTED) {
|
|
56
|
+
merged[key] = { ...code[key], ...config[key] };
|
|
57
|
+
}
|
|
58
|
+
this.options = merged;
|
|
59
|
+
}
|
|
60
|
+
/** The bound port, once listening. */
|
|
61
|
+
get port() {
|
|
62
|
+
return this.server?.port;
|
|
63
|
+
}
|
|
64
|
+
/** The transport in use, once listening: `uws` or `node`. */
|
|
65
|
+
get transport() {
|
|
66
|
+
return this.transportName;
|
|
67
|
+
}
|
|
68
|
+
async listen() {
|
|
69
|
+
if (this.engine !== undefined) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const { options } = this;
|
|
73
|
+
const routes = compileRoutes(options.routes, {
|
|
74
|
+
prefix: options.prefix,
|
|
75
|
+
middleware: this.globalMiddleware(),
|
|
76
|
+
});
|
|
77
|
+
const docs = options.docs ?? {};
|
|
78
|
+
const docsPath = docs.path ?? '/docs';
|
|
79
|
+
const docsEnabled = docs.enabled ?? true;
|
|
80
|
+
if (docsEnabled) {
|
|
81
|
+
routes.push(...docsRoutes(routes, {
|
|
82
|
+
path: docsPath,
|
|
83
|
+
securitySchemes: Object.fromEntries(this.authStrategies
|
|
84
|
+
.filter((strategy) => strategy.scheme !== undefined)
|
|
85
|
+
.map((strategy) => [strategy.name, strategy.scheme])),
|
|
86
|
+
title: docs.title ?? 'API',
|
|
87
|
+
version: docs.version ?? '1.0.0',
|
|
88
|
+
...(docs.description === undefined
|
|
89
|
+
? {}
|
|
90
|
+
: { description: docs.description }),
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
this.engine = new HttpEngine(routes, {
|
|
94
|
+
injector: this.injector,
|
|
95
|
+
logger: this.log,
|
|
96
|
+
accessLog: options.accessLog ?? false,
|
|
97
|
+
cors: new CorsPolicy(options.cors ?? {}),
|
|
98
|
+
requestIdHeader: options.requestId?.enabled === false
|
|
99
|
+
? undefined
|
|
100
|
+
: (options.requestId?.header ?? 'x-request-id').toLowerCase(),
|
|
101
|
+
requestTimeout: options.requestTimeout ?? 0,
|
|
102
|
+
trustProxy: options.trustProxy ?? 0,
|
|
103
|
+
securityHeaders: options.securityHeaders?.enabled === false
|
|
104
|
+
? []
|
|
105
|
+
: securityHeaders(options.securityHeaders),
|
|
106
|
+
compressor: options.compression?.enabled === true
|
|
107
|
+
? new Compressor(options.compression)
|
|
108
|
+
: undefined,
|
|
109
|
+
observe: this.requestMetrics(),
|
|
110
|
+
etag: options.etag ?? false,
|
|
111
|
+
tracer: this.tracer.enabled ? this.tracer : undefined,
|
|
112
|
+
});
|
|
113
|
+
if (options.transport === 'none') {
|
|
114
|
+
this.transportName = 'none';
|
|
115
|
+
this.log.info('HTTP server ready without a transport', {
|
|
116
|
+
routes: routes.length,
|
|
117
|
+
});
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const transport = await this.selectTransport();
|
|
121
|
+
this.transportName = transport.name;
|
|
122
|
+
this.server = await transport.listen({
|
|
123
|
+
port: options.port ?? 8080,
|
|
124
|
+
host: options.host,
|
|
125
|
+
bodyLimit: options.bodyLimit ?? DEFAULT_BODY_LIMIT,
|
|
126
|
+
websocket: {
|
|
127
|
+
maxPayload: options.websocket?.maxPayload ?? 64 * 1024,
|
|
128
|
+
idleTimeout: options.websocket?.idleTimeout ?? 120_000,
|
|
129
|
+
},
|
|
130
|
+
}, this.engine.handle);
|
|
131
|
+
this.log.info('HTTP server listening', {
|
|
132
|
+
port: this.server.port,
|
|
133
|
+
transport: transport.name,
|
|
134
|
+
routes: routes.length,
|
|
135
|
+
docs: docsEnabled ? docsPath : false,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/** Request metrics, when `provideMetrics()` is used. */
|
|
139
|
+
requestMetrics() {
|
|
140
|
+
const { metrics } = this;
|
|
141
|
+
if (metrics === null) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
const duration = metrics.histogram('http_request_duration_seconds', 'HTTP request duration in seconds, by method, route pattern and status.', { labels: ['method', 'route', 'status'] });
|
|
145
|
+
metrics.gauge('http_requests_in_flight', 'HTTP requests being handled.', {
|
|
146
|
+
collect: (gauge) => gauge.set(this.engine?.pending ?? 0),
|
|
147
|
+
});
|
|
148
|
+
metrics.gauge('websocket_connections', 'Open WebSocket connections.', {
|
|
149
|
+
collect: (gauge) => gauge.set(this.engine?.webSocketCount ?? 0),
|
|
150
|
+
});
|
|
151
|
+
return (method, route, status, seconds) => duration.observe(seconds, { method, route, status });
|
|
152
|
+
}
|
|
153
|
+
/** The rate limit from config, then plugin middleware, then `provideHttp({ middleware })`. */
|
|
154
|
+
globalMiddleware() {
|
|
155
|
+
const { rateLimit: limits, middleware = [] } = this.options;
|
|
156
|
+
const global = [];
|
|
157
|
+
if (limits?.limit !== undefined) {
|
|
158
|
+
const header = limits.keyHeader?.toLowerCase();
|
|
159
|
+
global.push(rateLimit({
|
|
160
|
+
limit: limits.limit,
|
|
161
|
+
window: limits.window ?? 60_000,
|
|
162
|
+
name: 'global',
|
|
163
|
+
...(header === undefined
|
|
164
|
+
? {}
|
|
165
|
+
: { key: (context) => context.request.headers[header] }),
|
|
166
|
+
}));
|
|
167
|
+
}
|
|
168
|
+
global.push(...this.plugins, ...middleware);
|
|
169
|
+
return global;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Sends a request through the full pipeline in memory, without a socket.
|
|
173
|
+
* Use it in tests, with `http.transport: none` to skip listening.
|
|
174
|
+
*
|
|
175
|
+
* ```ts
|
|
176
|
+
* const response = await server.request({ method: 'POST', path: '/users', body: { name: 'Ada' } });
|
|
177
|
+
* expect(response.status).toBe(201);
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
request(init) {
|
|
181
|
+
if (this.engine === undefined) {
|
|
182
|
+
throw new Error('The HTTP server has not started.');
|
|
183
|
+
}
|
|
184
|
+
return dispatch(this.engine, init);
|
|
185
|
+
}
|
|
186
|
+
/** Sends a message to every WebSocket subscribed to `topic`, on any route. */
|
|
187
|
+
publish(topic, message) {
|
|
188
|
+
this.server?.publish(topic, message);
|
|
189
|
+
}
|
|
190
|
+
/** Graceful close: stop accepting, drain in-flight requests, close connections. */
|
|
191
|
+
async close() {
|
|
192
|
+
const { server, engine } = this;
|
|
193
|
+
if (server === undefined || engine === undefined) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
engine.closing = true;
|
|
197
|
+
server.stopAccepting();
|
|
198
|
+
engine.closeWebSockets(1001, 'The server is shutting down.');
|
|
199
|
+
if (engine.pending > 0) {
|
|
200
|
+
this.log.info('Waiting for in-flight requests', {
|
|
201
|
+
pending: engine.pending,
|
|
202
|
+
});
|
|
203
|
+
await engine.drain();
|
|
204
|
+
}
|
|
205
|
+
await this.forceClose();
|
|
206
|
+
}
|
|
207
|
+
async [Symbol.asyncDispose]() {
|
|
208
|
+
await this.forceClose();
|
|
209
|
+
}
|
|
210
|
+
async forceClose() {
|
|
211
|
+
const { server } = this;
|
|
212
|
+
if (server === undefined) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.server = undefined;
|
|
216
|
+
await server.close();
|
|
217
|
+
}
|
|
218
|
+
async selectTransport() {
|
|
219
|
+
const choice = this.options.transport ?? 'auto';
|
|
220
|
+
if (choice === 'node') {
|
|
221
|
+
return nodeTransport;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const { uwsTransport } = await import('./transports/uws.js');
|
|
225
|
+
return await uwsTransport();
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (choice === 'uws') {
|
|
229
|
+
throw new Error('The uws transport could not be loaded.', {
|
|
230
|
+
cause: error,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
this.log.warn('uWebSockets.js is unavailable; using node:http', {
|
|
234
|
+
err: error,
|
|
235
|
+
});
|
|
236
|
+
return nodeTransport;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Serves routes over HTTP for the lifetime of the application.
|
|
242
|
+
*
|
|
243
|
+
* ```ts
|
|
244
|
+
* provideHttp({ prefix: '/api', routes: [userRoutes] })
|
|
245
|
+
* ```
|
|
246
|
+
*/
|
|
247
|
+
export function provideHttp(options) {
|
|
248
|
+
return [
|
|
249
|
+
provide(HTTP_OPTIONS, { useValue: options }),
|
|
250
|
+
provideConfig(HttpConfig),
|
|
251
|
+
HttpServer,
|
|
252
|
+
onStart(() => inject(HttpServer).listen()),
|
|
253
|
+
onShutdown(() => inject(HttpServer).close()),
|
|
254
|
+
];
|
|
255
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { HttpEngine } from './engine.js';
|
|
2
|
+
export interface TestRequestInit {
|
|
3
|
+
method?: string;
|
|
4
|
+
/** Path, optionally with a query string: `/users?page=2`. */
|
|
5
|
+
path: string;
|
|
6
|
+
headers?: Record<string, string>;
|
|
7
|
+
/** A string or bytes are sent as-is; anything else as JSON (with content-type set). */
|
|
8
|
+
body?: unknown;
|
|
9
|
+
remoteAddress?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface TestResponse {
|
|
12
|
+
status: number;
|
|
13
|
+
/** Lower-case header names. */
|
|
14
|
+
headers: Record<string, string>;
|
|
15
|
+
body: Buffer;
|
|
16
|
+
text(): string;
|
|
17
|
+
json<T = unknown>(): T;
|
|
18
|
+
}
|
|
19
|
+
/** Sends a request through the engine in memory: no sockets, same pipeline. */
|
|
20
|
+
export declare function dispatch(engine: HttpEngine, init: TestRequestInit): Promise<TestResponse>;
|
|
21
|
+
//# sourceMappingURL=testing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../src/lib/testing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAG9C,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,uFAAuF;IACvF,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,+BAA+B;IAC/B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,IAAI,MAAM,CAAC;IACf,IAAI,CAAC,CAAC,GAAG,OAAO,KAAK,CAAC,CAAC;CACxB;AAwCD,+EAA+E;AAC/E,wBAAgB,QAAQ,CACtB,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC,YAAY,CAAC,CAuBvB"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { HttpRequest } from './request.js';
|
|
2
|
+
class TestRequest extends HttpRequest {
|
|
3
|
+
method;
|
|
4
|
+
path;
|
|
5
|
+
query;
|
|
6
|
+
headers;
|
|
7
|
+
remoteAddress;
|
|
8
|
+
bytes;
|
|
9
|
+
constructor(init) {
|
|
10
|
+
super();
|
|
11
|
+
const queryStart = init.path.indexOf('?');
|
|
12
|
+
this.method = (init.method ?? 'GET').toUpperCase();
|
|
13
|
+
this.path = queryStart === -1 ? init.path : init.path.slice(0, queryStart);
|
|
14
|
+
this.query = queryStart === -1 ? '' : init.path.slice(queryStart + 1);
|
|
15
|
+
this.remoteAddress = init.remoteAddress ?? '127.0.0.1';
|
|
16
|
+
this.headers = {};
|
|
17
|
+
for (const [name, value] of Object.entries(init.headers ?? {})) {
|
|
18
|
+
this.headers[name.toLowerCase()] = value;
|
|
19
|
+
}
|
|
20
|
+
const { body } = init;
|
|
21
|
+
if (body === undefined) {
|
|
22
|
+
this.bytes = new Uint8Array(0);
|
|
23
|
+
}
|
|
24
|
+
else if (typeof body === 'string') {
|
|
25
|
+
this.bytes = Buffer.from(body);
|
|
26
|
+
}
|
|
27
|
+
else if (body instanceof Uint8Array) {
|
|
28
|
+
this.bytes = body;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
this.bytes = Buffer.from(JSON.stringify(body));
|
|
32
|
+
this.headers['content-type'] ??= 'application/json';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
body() {
|
|
36
|
+
return Promise.resolve(this.bytes);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Sends a request through the engine in memory: no sockets, same pipeline. */
|
|
40
|
+
export function dispatch(engine, init) {
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
const sink = {
|
|
43
|
+
aborted: false,
|
|
44
|
+
onAbort: () => undefined,
|
|
45
|
+
send(status, headers, body, head) {
|
|
46
|
+
const bytes = head || body === undefined
|
|
47
|
+
? Buffer.alloc(0)
|
|
48
|
+
: typeof body === 'string'
|
|
49
|
+
? Buffer.from(body)
|
|
50
|
+
: Buffer.from(body.buffer, body.byteOffset, body.byteLength);
|
|
51
|
+
resolve({
|
|
52
|
+
status,
|
|
53
|
+
headers: { ...headers },
|
|
54
|
+
body: bytes,
|
|
55
|
+
text: () => bytes.toString('utf8'),
|
|
56
|
+
json: () => JSON.parse(bytes.toString('utf8')),
|
|
57
|
+
});
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
engine.handle(new TestRequest(init), sink);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../../src/lib/transports/node.ts"],"names":[],"mappings":"AAaA,OAAO,EAIL,KAAK,SAAS,EAEf,MAAM,gBAAgB,CAAC;AA4NxB,yEAAyE;AACzE,eAAO,MAAM,aAAa,EAAE,SA0E3B,CAAC"}
|