@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.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -2
  3. package/dist/index.d.ts +20 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +16 -0
  6. package/dist/lib/auth/api-key.d.ts +17 -0
  7. package/dist/lib/auth/api-key.d.ts.map +1 -0
  8. package/dist/lib/auth/api-key.js +48 -0
  9. package/dist/lib/auth/jwt.d.ts +33 -0
  10. package/dist/lib/auth/jwt.d.ts.map +1 -0
  11. package/dist/lib/auth/jwt.js +227 -0
  12. package/dist/lib/auth/provide-auth.d.ts +30 -0
  13. package/dist/lib/auth/provide-auth.d.ts.map +1 -0
  14. package/dist/lib/auth/provide-auth.js +69 -0
  15. package/dist/lib/auth/strategy.d.ts +47 -0
  16. package/dist/lib/auth/strategy.d.ts.map +1 -0
  17. package/dist/lib/auth/strategy.js +18 -0
  18. package/dist/lib/compile.d.ts +46 -0
  19. package/dist/lib/compile.d.ts.map +1 -0
  20. package/dist/lib/compile.js +126 -0
  21. package/dist/lib/compression.d.ts +23 -0
  22. package/dist/lib/compression.d.ts.map +1 -0
  23. package/dist/lib/compression.js +86 -0
  24. package/dist/lib/config.d.ts +173 -0
  25. package/dist/lib/config.d.ts.map +1 -0
  26. package/dist/lib/config.js +93 -0
  27. package/dist/lib/cors.d.ts +41 -0
  28. package/dist/lib/cors.d.ts.map +1 -0
  29. package/dist/lib/cors.js +101 -0
  30. package/dist/lib/docs.d.ts +15 -0
  31. package/dist/lib/docs.d.ts.map +1 -0
  32. package/dist/lib/docs.js +93 -0
  33. package/dist/lib/engine.d.ts +83 -0
  34. package/dist/lib/engine.d.ts.map +1 -0
  35. package/dist/lib/engine.js +562 -0
  36. package/dist/lib/errors.d.ts +31 -0
  37. package/dist/lib/errors.d.ts.map +1 -0
  38. package/dist/lib/errors.js +55 -0
  39. package/dist/lib/etag.d.ts +5 -0
  40. package/dist/lib/etag.d.ts.map +1 -0
  41. package/dist/lib/etag.js +30 -0
  42. package/dist/lib/headers.d.ts +3 -0
  43. package/dist/lib/headers.d.ts.map +1 -0
  44. package/dist/lib/headers.js +14 -0
  45. package/dist/lib/json-schema.d.ts +11 -0
  46. package/dist/lib/json-schema.d.ts.map +1 -0
  47. package/dist/lib/json-schema.js +23 -0
  48. package/dist/lib/openapi.d.ts +18 -0
  49. package/dist/lib/openapi.d.ts.map +1 -0
  50. package/dist/lib/openapi.js +218 -0
  51. package/dist/lib/rate-limit.d.ts +52 -0
  52. package/dist/lib/rate-limit.d.ts.map +1 -0
  53. package/dist/lib/rate-limit.js +87 -0
  54. package/dist/lib/reply.d.ts +27 -0
  55. package/dist/lib/reply.d.ts.map +1 -0
  56. package/dist/lib/reply.js +52 -0
  57. package/dist/lib/request.d.ts +55 -0
  58. package/dist/lib/request.d.ts.map +1 -0
  59. package/dist/lib/request.js +36 -0
  60. package/dist/lib/router.d.ts +35 -0
  61. package/dist/lib/router.d.ts.map +1 -0
  62. package/dist/lib/router.js +173 -0
  63. package/dist/lib/routes.d.ts +196 -0
  64. package/dist/lib/routes.d.ts.map +1 -0
  65. package/dist/lib/routes.js +98 -0
  66. package/dist/lib/security-headers.d.ts +19 -0
  67. package/dist/lib/security-headers.d.ts.map +1 -0
  68. package/dist/lib/security-headers.js +22 -0
  69. package/dist/lib/serializer.d.ts +35 -0
  70. package/dist/lib/serializer.d.ts.map +1 -0
  71. package/dist/lib/serializer.js +147 -0
  72. package/dist/lib/server.d.ts +86 -0
  73. package/dist/lib/server.d.ts.map +1 -0
  74. package/dist/lib/server.js +255 -0
  75. package/dist/lib/testing.d.ts +21 -0
  76. package/dist/lib/testing.d.ts.map +1 -0
  77. package/dist/lib/testing.js +62 -0
  78. package/dist/lib/transports/node.d.ts +4 -0
  79. package/dist/lib/transports/node.d.ts.map +1 -0
  80. package/dist/lib/transports/node.js +249 -0
  81. package/dist/lib/transports/transport.d.ts +32 -0
  82. package/dist/lib/transports/transport.d.ts.map +1 -0
  83. package/dist/lib/transports/transport.js +1 -0
  84. package/dist/lib/transports/uws.d.ts +8 -0
  85. package/dist/lib/transports/uws.d.ts.map +1 -0
  86. package/dist/lib/transports/uws.js +246 -0
  87. package/dist/lib/websocket.d.ts +71 -0
  88. package/dist/lib/websocket.d.ts.map +1 -0
  89. package/dist/lib/websocket.js +125 -0
  90. package/package.json +67 -3
  91. package/src/index.ts +103 -0
  92. package/src/lib/auth/api-key.ts +73 -0
  93. package/src/lib/auth/jwt.ts +339 -0
  94. package/src/lib/auth/provide-auth.ts +99 -0
  95. package/src/lib/auth/strategy.ts +66 -0
  96. package/src/lib/compile.ts +207 -0
  97. package/src/lib/compression.ts +121 -0
  98. package/src/lib/config.ts +107 -0
  99. package/src/lib/cors.ts +146 -0
  100. package/src/lib/docs.ts +115 -0
  101. package/src/lib/engine.ts +770 -0
  102. package/src/lib/errors.ts +84 -0
  103. package/src/lib/etag.ts +37 -0
  104. package/src/lib/headers.ts +18 -0
  105. package/src/lib/json-schema.ts +36 -0
  106. package/src/lib/openapi.ts +299 -0
  107. package/src/lib/rate-limit.ts +142 -0
  108. package/src/lib/reply.ts +70 -0
  109. package/src/lib/request.ts +83 -0
  110. package/src/lib/router.ts +217 -0
  111. package/src/lib/routes.ts +414 -0
  112. package/src/lib/security-headers.ts +38 -0
  113. package/src/lib/serializer.ts +203 -0
  114. package/src/lib/server.ts +352 -0
  115. package/src/lib/testing.ts +88 -0
  116. package/src/lib/transports/node.ts +315 -0
  117. package/src/lib/transports/transport.ts +39 -0
  118. package/src/lib/transports/uws.ts +310 -0
  119. package/src/lib/websocket.ts +184 -0
@@ -0,0 +1,86 @@
1
+ import { promisify } from 'node:util';
2
+ import { brotliCompress, constants, gzip, zstdCompress } from 'node:zlib';
3
+ import { appendVary } from './headers.js';
4
+ const COMPRESSORS = {
5
+ // Levels tuned for dynamic responses: fast, with most of the size benefit.
6
+ zstd: (data) => promisify(zstdCompress)(data, {
7
+ params: { [constants.ZSTD_c_compressionLevel]: 3 },
8
+ }),
9
+ br: (data) => promisify(brotliCompress)(data, {
10
+ params: {
11
+ [constants.BROTLI_PARAM_QUALITY]: 4,
12
+ [constants.BROTLI_PARAM_SIZE_HINT]: data.byteLength,
13
+ },
14
+ }),
15
+ gzip: (data) => promisify(gzip)(data, { level: 6 }),
16
+ };
17
+ const COMPRESSIBLE = /^(?:text\/|application\/(?:[\w.+-]*\+)?(?:json|xml)\b|application\/(?:javascript|x-javascript|ecmascript)\b|image\/svg\+xml\b)/i;
18
+ /** Negotiates and applies response compression. */
19
+ export class Compressor {
20
+ encodings;
21
+ threshold;
22
+ /** Compressed copies of byte bodies, such as static assets served from memory. */
23
+ cache = new WeakMap();
24
+ constructor(options = {}) {
25
+ this.encodings = options.encodings ?? ['zstd', 'br', 'gzip'];
26
+ this.threshold = options.threshold ?? 1024;
27
+ }
28
+ /**
29
+ * Compresses `body` if the response and the client allow it, updating the
30
+ * headers. Returns the body to send.
31
+ */
32
+ async apply(acceptEncoding, headers, body) {
33
+ const type = headers['content-type'] ?? '';
34
+ if (!COMPRESSIBLE.test(type) ||
35
+ headers['content-encoding'] !== undefined ||
36
+ /\bno-transform\b/i.test(headers['cache-control'] ?? '')) {
37
+ return body;
38
+ }
39
+ // The response depends on Accept-Encoding even when it is not compressed.
40
+ appendVary(headers, 'Accept-Encoding');
41
+ const size = typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength;
42
+ const encoding = size < this.threshold ? undefined : this.negotiate(acceptEncoding);
43
+ if (encoding === undefined) {
44
+ return body;
45
+ }
46
+ headers['content-encoding'] = encoding;
47
+ if (typeof body === 'string') {
48
+ return COMPRESSORS[encoding](Buffer.from(body));
49
+ }
50
+ let cached = this.cache.get(body);
51
+ if (cached === undefined) {
52
+ cached = new Map();
53
+ this.cache.set(body, cached);
54
+ }
55
+ let compressed = cached.get(encoding);
56
+ if (compressed === undefined) {
57
+ compressed = await COMPRESSORS[encoding](Buffer.from(body.buffer, body.byteOffset, body.byteLength));
58
+ cached.set(encoding, compressed);
59
+ }
60
+ return compressed;
61
+ }
62
+ /** The most preferred encoding the client accepts (q > 0), if any. */
63
+ negotiate(acceptEncoding) {
64
+ if (acceptEncoding === undefined || acceptEncoding === '') {
65
+ return undefined;
66
+ }
67
+ const quality = new Map();
68
+ for (const part of acceptEncoding.split(',')) {
69
+ const [name = '', ...params] = part.trim().toLowerCase().split(';');
70
+ const q = params
71
+ .map((param) => param.trim())
72
+ .find((param) => param.startsWith('q='));
73
+ quality.set(name.trim(), q === undefined ? 1 : Number(q.slice(2)) || 0);
74
+ }
75
+ let best;
76
+ let bestQuality = 0;
77
+ for (const encoding of this.encodings) {
78
+ const q = quality.get(encoding) ?? quality.get('*') ?? 0;
79
+ if (q > bestQuality) {
80
+ best = encoding;
81
+ bestQuality = q;
82
+ }
83
+ }
84
+ return best;
85
+ }
86
+ }
@@ -0,0 +1,173 @@
1
+ import { settings } from '@tessellation/core';
2
+ declare const httpShape: {
3
+ /** Port to listen on. Defaults to 8080; 0 picks a free port. */
4
+ port: settings.FieldParser<number>;
5
+ /** Interface to bind. Defaults to all interfaces. */
6
+ host: settings.FieldParser<string>;
7
+ /**
8
+ * `uws` (uWebSockets.js, fastest), `node` (`node:http`, no native code),
9
+ * `auto` (the default: `uws` when it can be loaded, otherwise `node`) or
10
+ * `none` (no socket; for tests using `HttpServer.request()`).
11
+ */
12
+ transport: settings.FieldParser<"auto" | "uws" | "node" | "none">;
13
+ /** Generate weak ETags and answer If-None-Match with 304. Defaults to false. */
14
+ etag: settings.FieldParser<boolean>;
15
+ /** Maximum request body size. Defaults to 1mb. */
16
+ bodyLimit: settings.FieldParser<number>;
17
+ /** Log every request at info level. Defaults to false. */
18
+ accessLog: settings.FieldParser<boolean>;
19
+ /** Proxies in front of the server (such as an ingress), for client IPs. Defaults to 0. */
20
+ trustProxy: settings.FieldParser<number>;
21
+ /** Answer 503 and abort the request's signal after this long. Off by default. */
22
+ requestTimeout: settings.FieldParser<number>;
23
+ requestId: settings.FieldParser<settings.Settings<{
24
+ /** Tag requests and their logs with an id. Defaults to true. */
25
+ enabled: settings.FieldParser<boolean>;
26
+ /** Header read (when valid) and returned. Defaults to x-request-id. */
27
+ header: settings.FieldParser<string>;
28
+ }>>;
29
+ compression: settings.FieldParser<settings.Settings<{
30
+ /** Compress responses. Defaults to false (often done by the ingress). */
31
+ enabled: settings.FieldParser<boolean>;
32
+ /** Smallest body worth compressing. Defaults to 1kb. */
33
+ threshold: settings.FieldParser<number>;
34
+ /** Encodings offered, most preferred first. Defaults to zstd, br, gzip. */
35
+ encodings: settings.FieldParser<("zstd" | "br" | "gzip")[]>;
36
+ }>>;
37
+ securityHeaders: settings.FieldParser<settings.Settings<{
38
+ /** Add security headers to every response. Defaults to true. */
39
+ enabled: settings.FieldParser<boolean>;
40
+ /** Enables strict-transport-security with this max-age, such as 180d. */
41
+ hsts: settings.FieldParser<number>;
42
+ frameOptions: settings.FieldParser<"DENY" | "SAMEORIGIN">;
43
+ referrerPolicy: settings.FieldParser<string>;
44
+ contentSecurityPolicy: settings.FieldParser<string>;
45
+ }>>;
46
+ rateLimit: settings.FieldParser<settings.Settings<{
47
+ /** Requests per window for every route; off unless set. */
48
+ limit: settings.FieldParser<number>;
49
+ /** Window length. Defaults to 1m. */
50
+ window: settings.FieldParser<number>;
51
+ /** Count by this header (such as x-api-key) instead of the client IP. */
52
+ keyHeader: settings.FieldParser<string>;
53
+ }>>;
54
+ cors: settings.FieldParser<settings.Settings<{
55
+ /** Allowed origins; CORS is off when empty. Exact, `https://*.example.com` or `*`. */
56
+ origins: settings.FieldParser<string[]>;
57
+ methods: settings.FieldParser<string[]>;
58
+ allowedHeaders: settings.FieldParser<string[]>;
59
+ exposedHeaders: settings.FieldParser<string[]>;
60
+ credentials: settings.FieldParser<boolean>;
61
+ /** How long browsers may cache preflight responses, such as 10m. */
62
+ maxAge: settings.FieldParser<number>;
63
+ }>>;
64
+ websocket: settings.FieldParser<settings.Settings<{
65
+ /** Largest accepted message. Defaults to 64kb. */
66
+ maxPayload: settings.FieldParser<number>;
67
+ /** Close idle connections after this long (uws). Defaults to 2m. */
68
+ idleTimeout: settings.FieldParser<number>;
69
+ }>>;
70
+ docs: settings.FieldParser<settings.Settings<{
71
+ /** Serve Swagger UI and the OpenAPI document. Defaults to true. */
72
+ enabled: settings.FieldParser<boolean>;
73
+ /** Where Swagger UI is served. Defaults to /docs. */
74
+ path: settings.FieldParser<string>;
75
+ title: settings.FieldParser<string>;
76
+ version: settings.FieldParser<string>;
77
+ description: settings.FieldParser<string>;
78
+ }>>;
79
+ };
80
+ /** Settings under the `http` config section. */
81
+ export type HttpSettings = settings.Settings<typeof httpShape>;
82
+ /**
83
+ * The `http` config section, registered by `provideHttp()`. Its values take
84
+ * precedence over the options passed in code.
85
+ *
86
+ * ```yaml
87
+ * http:
88
+ * port: ${env:PORT:-8080}
89
+ * bodyLimit: 5mb
90
+ * docs:
91
+ * enabled: false
92
+ * ```
93
+ */
94
+ export declare const HttpConfig: import("@tessellation/core").ConfigSection<settings.Settings<{
95
+ /** Port to listen on. Defaults to 8080; 0 picks a free port. */
96
+ port: settings.FieldParser<number>;
97
+ /** Interface to bind. Defaults to all interfaces. */
98
+ host: settings.FieldParser<string>;
99
+ /**
100
+ * `uws` (uWebSockets.js, fastest), `node` (`node:http`, no native code),
101
+ * `auto` (the default: `uws` when it can be loaded, otherwise `node`) or
102
+ * `none` (no socket; for tests using `HttpServer.request()`).
103
+ */
104
+ transport: settings.FieldParser<"auto" | "uws" | "node" | "none">;
105
+ /** Generate weak ETags and answer If-None-Match with 304. Defaults to false. */
106
+ etag: settings.FieldParser<boolean>;
107
+ /** Maximum request body size. Defaults to 1mb. */
108
+ bodyLimit: settings.FieldParser<number>;
109
+ /** Log every request at info level. Defaults to false. */
110
+ accessLog: settings.FieldParser<boolean>;
111
+ /** Proxies in front of the server (such as an ingress), for client IPs. Defaults to 0. */
112
+ trustProxy: settings.FieldParser<number>;
113
+ /** Answer 503 and abort the request's signal after this long. Off by default. */
114
+ requestTimeout: settings.FieldParser<number>;
115
+ requestId: settings.FieldParser<settings.Settings<{
116
+ /** Tag requests and their logs with an id. Defaults to true. */
117
+ enabled: settings.FieldParser<boolean>;
118
+ /** Header read (when valid) and returned. Defaults to x-request-id. */
119
+ header: settings.FieldParser<string>;
120
+ }>>;
121
+ compression: settings.FieldParser<settings.Settings<{
122
+ /** Compress responses. Defaults to false (often done by the ingress). */
123
+ enabled: settings.FieldParser<boolean>;
124
+ /** Smallest body worth compressing. Defaults to 1kb. */
125
+ threshold: settings.FieldParser<number>;
126
+ /** Encodings offered, most preferred first. Defaults to zstd, br, gzip. */
127
+ encodings: settings.FieldParser<("zstd" | "br" | "gzip")[]>;
128
+ }>>;
129
+ securityHeaders: settings.FieldParser<settings.Settings<{
130
+ /** Add security headers to every response. Defaults to true. */
131
+ enabled: settings.FieldParser<boolean>;
132
+ /** Enables strict-transport-security with this max-age, such as 180d. */
133
+ hsts: settings.FieldParser<number>;
134
+ frameOptions: settings.FieldParser<"DENY" | "SAMEORIGIN">;
135
+ referrerPolicy: settings.FieldParser<string>;
136
+ contentSecurityPolicy: settings.FieldParser<string>;
137
+ }>>;
138
+ rateLimit: settings.FieldParser<settings.Settings<{
139
+ /** Requests per window for every route; off unless set. */
140
+ limit: settings.FieldParser<number>;
141
+ /** Window length. Defaults to 1m. */
142
+ window: settings.FieldParser<number>;
143
+ /** Count by this header (such as x-api-key) instead of the client IP. */
144
+ keyHeader: settings.FieldParser<string>;
145
+ }>>;
146
+ cors: settings.FieldParser<settings.Settings<{
147
+ /** Allowed origins; CORS is off when empty. Exact, `https://*.example.com` or `*`. */
148
+ origins: settings.FieldParser<string[]>;
149
+ methods: settings.FieldParser<string[]>;
150
+ allowedHeaders: settings.FieldParser<string[]>;
151
+ exposedHeaders: settings.FieldParser<string[]>;
152
+ credentials: settings.FieldParser<boolean>;
153
+ /** How long browsers may cache preflight responses, such as 10m. */
154
+ maxAge: settings.FieldParser<number>;
155
+ }>>;
156
+ websocket: settings.FieldParser<settings.Settings<{
157
+ /** Largest accepted message. Defaults to 64kb. */
158
+ maxPayload: settings.FieldParser<number>;
159
+ /** Close idle connections after this long (uws). Defaults to 2m. */
160
+ idleTimeout: settings.FieldParser<number>;
161
+ }>>;
162
+ docs: settings.FieldParser<settings.Settings<{
163
+ /** Serve Swagger UI and the OpenAPI document. Defaults to true. */
164
+ enabled: settings.FieldParser<boolean>;
165
+ /** Where Swagger UI is served. Defaults to /docs. */
166
+ path: settings.FieldParser<string>;
167
+ title: settings.FieldParser<string>;
168
+ version: settings.FieldParser<string>;
169
+ description: settings.FieldParser<string>;
170
+ }>>;
171
+ }>>;
172
+ export {};
173
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/lib/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAI5D,QAAA,MAAM,SAAS;IACb,gEAAgE;;IAEhE,qDAAqD;;IAErD;;;;OAIG;;IAEH,gFAAgF;;IAEhF,kDAAkD;;IAElD,0DAA0D;;IAE1D,0FAA0F;;IAE1F,iFAAiF;;;QAG/E,gEAAgE;;QAEhE,uEAAuE;;;;QAIvE,yEAAyE;;QAEzE,wDAAwD;;QAExD,2EAA2E;;;;QAI3E,gEAAgE;;QAEhE,yEAAyE;;;;;;;QAUzE,2DAA2D;;QAE3D,qCAAqC;;QAErC,yEAAyE;;;;QAIzE,sFAAsF;;;;;;QAWtF,oEAAoE;;;;QAIpE,kDAAkD;;QAElD,oEAAoE;;;;QAIpE,mEAAmE;;QAEnE,qDAAqD;;;;;;CAMxD,CAAC;AAEF,gDAAgD;AAChD,MAAM,MAAM,YAAY,GAAG,QAAQ,CAAC,QAAQ,CAAC,OAAO,SAAS,CAAC,CAAC;AAE/D;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU;IArGrB,gEAAgE;;IAEhE,qDAAqD;;IAErD;;;;OAIG;;IAEH,gFAAgF;;IAEhF,kDAAkD;;IAElD,0DAA0D;;IAE1D,0FAA0F;;IAE1F,iFAAiF;;;QAG/E,gEAAgE;;QAEhE,uEAAuE;;;;QAIvE,yEAAyE;;QAEzE,wDAAwD;;QAExD,2EAA2E;;;;QAI3E,gEAAgE;;QAEhE,yEAAyE;;;;;;;QAUzE,2DAA2D;;QAE3D,qCAAqC;;QAErC,yEAAyE;;;;QAIzE,sFAAsF;;;;;;QAWtF,oEAAoE;;;;QAIpE,kDAAkD;;QAElD,oEAAoE;;;;QAIpE,mEAAmE;;QAEnE,qDAAqD;;;;;;GAuBiB,CAAC"}
@@ -0,0 +1,93 @@
1
+ import { defineConfig, settings } from '@tessellation/core';
2
+ const path = settings.string(/^\/\S*$/, 'a path starting with "/"');
3
+ const httpShape = {
4
+ /** Port to listen on. Defaults to 8080; 0 picks a free port. */
5
+ port: settings.integer(0, 65_535),
6
+ /** Interface to bind. Defaults to all interfaces. */
7
+ host: settings.string(/\S/, 'a host name or address'),
8
+ /**
9
+ * `uws` (uWebSockets.js, fastest), `node` (`node:http`, no native code),
10
+ * `auto` (the default: `uws` when it can be loaded, otherwise `node`) or
11
+ * `none` (no socket; for tests using `HttpServer.request()`).
12
+ */
13
+ transport: settings.oneOf(['auto', 'uws', 'node', 'none']),
14
+ /** Generate weak ETags and answer If-None-Match with 304. Defaults to false. */
15
+ etag: settings.boolean(),
16
+ /** Maximum request body size. Defaults to 1mb. */
17
+ bodyLimit: settings.size(),
18
+ /** Log every request at info level. Defaults to false. */
19
+ accessLog: settings.boolean(),
20
+ /** Proxies in front of the server (such as an ingress), for client IPs. Defaults to 0. */
21
+ trustProxy: settings.integer(0, 10),
22
+ /** Answer 503 and abort the request's signal after this long. Off by default. */
23
+ requestTimeout: settings.duration(),
24
+ requestId: settings.nested({
25
+ /** Tag requests and their logs with an id. Defaults to true. */
26
+ enabled: settings.boolean(),
27
+ /** Header read (when valid) and returned. Defaults to x-request-id. */
28
+ header: settings.string(/^[\w-]+$/, 'a header name'),
29
+ }),
30
+ compression: settings.nested({
31
+ /** Compress responses. Defaults to false (often done by the ingress). */
32
+ enabled: settings.boolean(),
33
+ /** Smallest body worth compressing. Defaults to 1kb. */
34
+ threshold: settings.size(),
35
+ /** Encodings offered, most preferred first. Defaults to zstd, br, gzip. */
36
+ encodings: settings.list(settings.oneOf(['zstd', 'br', 'gzip'])),
37
+ }),
38
+ securityHeaders: settings.nested({
39
+ /** Add security headers to every response. Defaults to true. */
40
+ enabled: settings.boolean(),
41
+ /** Enables strict-transport-security with this max-age, such as 180d. */
42
+ hsts: settings.duration(),
43
+ frameOptions: settings.oneOf(['DENY', 'SAMEORIGIN']),
44
+ referrerPolicy: settings.string(/^[\w-]+(,\s*[\w-]+)*$/, 'a referrer policy'),
45
+ contentSecurityPolicy: settings.string(/\S/, 'a content security policy'),
46
+ }),
47
+ rateLimit: settings.nested({
48
+ /** Requests per window for every route; off unless set. */
49
+ limit: settings.integer(1, 1_000_000_000),
50
+ /** Window length. Defaults to 1m. */
51
+ window: settings.duration(),
52
+ /** Count by this header (such as x-api-key) instead of the client IP. */
53
+ keyHeader: settings.string(/^[\w-]+$/, 'a header name'),
54
+ }),
55
+ cors: settings.nested({
56
+ /** Allowed origins; CORS is off when empty. Exact, `https://*.example.com` or `*`. */
57
+ origins: settings.list(settings.string(/^(\*|https?:\/\/\S+)$/, 'an origin such as https://app.example.com, or *')),
58
+ methods: settings.list(settings.string(/^[A-Z]+$/, 'an upper-case method')),
59
+ allowedHeaders: settings.list(settings.string(/^[\w-]+$/, 'a header name')),
60
+ exposedHeaders: settings.list(settings.string(/^[\w-]+$/, 'a header name')),
61
+ credentials: settings.boolean(),
62
+ /** How long browsers may cache preflight responses, such as 10m. */
63
+ maxAge: settings.duration(),
64
+ }),
65
+ websocket: settings.nested({
66
+ /** Largest accepted message. Defaults to 64kb. */
67
+ maxPayload: settings.size(),
68
+ /** Close idle connections after this long (uws). Defaults to 2m. */
69
+ idleTimeout: settings.duration(),
70
+ }),
71
+ docs: settings.nested({
72
+ /** Serve Swagger UI and the OpenAPI document. Defaults to true. */
73
+ enabled: settings.boolean(),
74
+ /** Where Swagger UI is served. Defaults to /docs. */
75
+ path,
76
+ title: settings.string(),
77
+ version: settings.string(),
78
+ description: settings.string(),
79
+ }),
80
+ };
81
+ /**
82
+ * The `http` config section, registered by `provideHttp()`. Its values take
83
+ * precedence over the options passed in code.
84
+ *
85
+ * ```yaml
86
+ * http:
87
+ * port: ${env:PORT:-8080}
88
+ * bodyLimit: 5mb
89
+ * docs:
90
+ * enabled: false
91
+ * ```
92
+ */
93
+ export const HttpConfig = defineConfig('http', settings.schema(httpShape));
@@ -0,0 +1,41 @@
1
+ import { Reply } from './reply.js';
2
+ import type { HttpRequest } from './request.js';
3
+ export interface CorsOptions {
4
+ /**
5
+ * Origins allowed to call the API: exact origins such as
6
+ * `https://app.example.com`, subdomain patterns such as
7
+ * `https://*.example.com`, or `*` for any origin. CORS is off when empty.
8
+ */
9
+ origins?: readonly string[];
10
+ /** Methods allowed in preflight responses. Defaults to the methods the path supports. */
11
+ methods?: readonly string[];
12
+ /** Request headers allowed. Defaults to whatever the preflight asks for. */
13
+ allowedHeaders?: readonly string[];
14
+ /** Response headers the browser may read, beyond the CORS-safelisted ones. */
15
+ exposedHeaders?: readonly string[];
16
+ /** Allow cookies and authorization headers. With `*`, the request's origin is echoed back. */
17
+ credentials?: boolean;
18
+ /** How long, in milliseconds, browsers may cache a preflight response. */
19
+ maxAge?: number;
20
+ }
21
+ /**
22
+ * Cross-origin resource sharing, applied by the engine to every response
23
+ * (including errors) and answering preflight requests for any route.
24
+ */
25
+ export declare class CorsPolicy {
26
+ private readonly options;
27
+ private readonly any;
28
+ private readonly exact;
29
+ private readonly patterns;
30
+ constructor(options: CorsOptions);
31
+ get enabled(): boolean;
32
+ isPreflight(request: HttpRequest): boolean;
33
+ /** Answers a preflight request for a path supporting `methods`. */
34
+ preflight(request: HttpRequest, methods: readonly string[]): Reply;
35
+ /** Adds CORS headers to a response for an allowed origin. */
36
+ apply(request: HttpRequest, response: Reply): void;
37
+ /** The `access-control-allow-origin` value for an origin, or undefined if it is not allowed. */
38
+ private allowedOrigin;
39
+ private setOrigin;
40
+ }
41
+ //# sourceMappingURL=cors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.d.ts","sourceRoot":"","sources":["../../src/lib/cors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,WAAW,WAAW;IAC1B;;;;OAIG;IACH,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,yFAAyF;IACzF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,4EAA4E;IAC5E,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,8EAA8E;IAC9E,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,8FAA8F;IAC9F,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,qBAAa,UAAU;IAKT,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJpC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAU;IAC9B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAc;IACpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAW;gBAEP,OAAO,EAAE,WAAW;IASjD,IAAI,OAAO,IAAI,OAAO,CAErB;IAED,WAAW,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO;IAQ1C,mEAAmE;IACnE,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,KAAK;IA+BlE,6DAA6D;IAC7D,KAAK,CAAC,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,GAAG,IAAI;IAqBlD,gGAAgG;IAChG,OAAO,CAAC,aAAa;IAcrB,OAAO,CAAC,SAAS;CASlB"}
@@ -0,0 +1,101 @@
1
+ import { problem } from './errors.js';
2
+ import { appendVary as appendVaryHeader } from './headers.js';
3
+ import { Reply } from './reply.js';
4
+ /**
5
+ * Cross-origin resource sharing, applied by the engine to every response
6
+ * (including errors) and answering preflight requests for any route.
7
+ */
8
+ export class CorsPolicy {
9
+ options;
10
+ any;
11
+ exact;
12
+ patterns;
13
+ constructor(options) {
14
+ this.options = options;
15
+ const origins = options.origins ?? [];
16
+ this.any = origins.includes('*');
17
+ this.exact = new Set(origins.filter((origin) => !origin.includes('*')));
18
+ this.patterns = origins
19
+ .filter((origin) => origin !== '*' && origin.includes('*'))
20
+ .map(originPattern);
21
+ }
22
+ get enabled() {
23
+ return this.any || this.exact.size > 0 || this.patterns.length > 0;
24
+ }
25
+ isPreflight(request) {
26
+ return (request.method === 'OPTIONS' &&
27
+ request.headers['origin'] !== undefined &&
28
+ request.headers['access-control-request-method'] !== undefined);
29
+ }
30
+ /** Answers a preflight request for a path supporting `methods`. */
31
+ preflight(request, methods) {
32
+ const origin = request.headers['origin'] ?? '';
33
+ const allowed = this.allowedOrigin(origin);
34
+ if (allowed === undefined) {
35
+ return problem(403, `The origin ${origin} is not allowed.`);
36
+ }
37
+ const response = new Reply(204, undefined);
38
+ this.setOrigin(response, allowed);
39
+ response.header('access-control-allow-methods', (this.options.methods ?? methods).join(', '));
40
+ const requested = request.headers['access-control-request-headers'];
41
+ const headers = this.options.allowedHeaders?.join(', ') ?? requested;
42
+ if (headers !== undefined && headers !== '') {
43
+ response.header('access-control-allow-headers', headers);
44
+ }
45
+ if (this.options.maxAge !== undefined) {
46
+ response.header('access-control-max-age', String(Math.floor(this.options.maxAge / 1000)));
47
+ }
48
+ if (this.options.allowedHeaders === undefined) {
49
+ appendVary(response, 'Access-Control-Request-Headers');
50
+ }
51
+ return response;
52
+ }
53
+ /** Adds CORS headers to a response for an allowed origin. */
54
+ apply(request, response) {
55
+ const origin = request.headers['origin'];
56
+ if (origin === undefined) {
57
+ return;
58
+ }
59
+ const allowed = this.allowedOrigin(origin);
60
+ if (allowed === undefined) {
61
+ return;
62
+ }
63
+ this.setOrigin(response, allowed);
64
+ if (this.options.exposedHeaders !== undefined &&
65
+ this.options.exposedHeaders.length > 0) {
66
+ response.header('access-control-expose-headers', this.options.exposedHeaders.join(', '));
67
+ }
68
+ }
69
+ /** The `access-control-allow-origin` value for an origin, or undefined if it is not allowed. */
70
+ allowedOrigin(origin) {
71
+ if (this.exact.has(origin) ||
72
+ this.patterns.some((pattern) => pattern.test(origin))) {
73
+ return origin;
74
+ }
75
+ if (this.any) {
76
+ // Browsers reject `*` for credentialed requests, so echo the origin.
77
+ return this.options.credentials ? origin : '*';
78
+ }
79
+ return undefined;
80
+ }
81
+ setOrigin(response, allowed) {
82
+ response.header('access-control-allow-origin', allowed);
83
+ if (allowed !== '*') {
84
+ appendVary(response, 'Origin');
85
+ }
86
+ if (this.options.credentials) {
87
+ response.header('access-control-allow-credentials', 'true');
88
+ }
89
+ }
90
+ }
91
+ /** `https://*.example.com` matches one or more subdomain labels. */
92
+ function originPattern(pattern) {
93
+ const source = pattern
94
+ .split('*')
95
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
96
+ .join('(?:[a-z0-9-]+\\.)*[a-z0-9-]+');
97
+ return new RegExp(`^${source}$`, 'i');
98
+ }
99
+ function appendVary(response, value) {
100
+ appendVaryHeader(response.headers, value);
101
+ }
@@ -0,0 +1,15 @@
1
+ import { type CompiledRoute } from './compile.js';
2
+ import { type OpenApiInfo } from './openapi.js';
3
+ export interface DocsOptions extends OpenApiInfo {
4
+ /** Where Swagger UI is served, such as `/docs`. */
5
+ path: string;
6
+ /** OpenAPI security schemes by name, from the auth strategies. */
7
+ securitySchemes?: Readonly<Record<string, unknown>>;
8
+ }
9
+ /**
10
+ * Routes serving Swagger UI at `path` and the OpenAPI document at
11
+ * `path/openapi.json`, built from `apiRoutes`. Assets come from the bundled
12
+ * `swagger-ui-dist` package and are held in memory.
13
+ */
14
+ export declare function docsRoutes(apiRoutes: readonly CompiledRoute[], options: DocsOptions): CompiledRoute[];
15
+ //# sourceMappingURL=docs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs.d.ts","sourceRoot":"","sources":["../../src/lib/docs.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,aAAa,EAA4B,MAAM,cAAc,CAAC;AAE5E,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAY9D,MAAM,WAAW,WAAY,SAAQ,WAAW;IAC9C,mDAAmD;IACnD,IAAI,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,eAAe,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACrD;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CACxB,SAAS,EAAE,SAAS,aAAa,EAAE,EACnC,OAAO,EAAE,WAAW,GACnB,aAAa,EAAE,CAiCjB"}
@@ -0,0 +1,93 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join } from 'node:path';
4
+ import { compileRoutes, joinPaths } from './compile.js';
5
+ import { weakEtag } from './etag.js';
6
+ import { buildOpenApi } from './openapi.js';
7
+ import { reply } from './reply.js';
8
+ import { routes } from './routes.js';
9
+ const ASSETS = {
10
+ 'swagger-ui.css': 'text/css; charset=utf-8',
11
+ 'swagger-ui-bundle.js': 'text/javascript; charset=utf-8',
12
+ 'swagger-ui-standalone-preset.js': 'text/javascript; charset=utf-8',
13
+ 'favicon-32x32.png': 'image/png',
14
+ 'favicon-16x16.png': 'image/png',
15
+ };
16
+ /**
17
+ * Routes serving Swagger UI at `path` and the OpenAPI document at
18
+ * `path/openapi.json`, built from `apiRoutes`. Assets come from the bundled
19
+ * `swagger-ui-dist` package and are held in memory.
20
+ */
21
+ export function docsRoutes(apiRoutes, options) {
22
+ const { path, securitySchemes, ...info } = options;
23
+ const spec = JSON.stringify(buildOpenApi(apiRoutes, info, securitySchemes));
24
+ const specTag = weakEtag(spec);
25
+ const specUrl = joinPaths(path, '/openapi.json');
26
+ const page = indexPage(info.title, joinPaths(path, '/'), specUrl);
27
+ const assets = loadAssets();
28
+ const cache = { 'cache-control': 'public, max-age=86400' };
29
+ const tree = routes(path, { hidden: true }, (r) => [
30
+ r.get('/', {
31
+ handler: () => reply(200, page, { 'content-type': 'text/html; charset=utf-8' }),
32
+ }),
33
+ r.get('/openapi.json', {
34
+ handler: () => reply(200, spec, { 'content-type': 'application/json', etag: specTag }),
35
+ }),
36
+ r.get('/:asset', {
37
+ handler: ({ params }) => {
38
+ const asset = assets.get(params.asset);
39
+ return asset === undefined
40
+ ? reply(404, 'Not Found')
41
+ : reply(200, asset.body, {
42
+ 'content-type': asset.type,
43
+ etag: weakEtag(asset.body),
44
+ ...cache,
45
+ });
46
+ },
47
+ }),
48
+ ]);
49
+ return compileRoutes([tree]);
50
+ }
51
+ function loadAssets() {
52
+ const require = createRequire(import.meta.url);
53
+ const directory = dirname(require.resolve('swagger-ui-dist/package.json'));
54
+ return new Map(Object.entries(ASSETS).map(([name, type]) => [
55
+ name,
56
+ { body: readFileSync(join(directory, name)), type },
57
+ ]));
58
+ }
59
+ function indexPage(title, base, specUrl) {
60
+ const prefix = base === '/' ? '' : base;
61
+ return `<!doctype html>
62
+ <html lang="en">
63
+ <head>
64
+ <meta charset="utf-8">
65
+ <meta name="viewport" content="width=device-width, initial-scale=1">
66
+ <title>${escapeHtml(title)}</title>
67
+ <link rel="stylesheet" href="${prefix}/swagger-ui.css">
68
+ <link rel="icon" type="image/png" href="${prefix}/favicon-32x32.png" sizes="32x32">
69
+ </head>
70
+ <body>
71
+ <div id="swagger-ui"></div>
72
+ <script src="${prefix}/swagger-ui-bundle.js"></script>
73
+ <script src="${prefix}/swagger-ui-standalone-preset.js"></script>
74
+ <script>
75
+ window.ui = SwaggerUIBundle({
76
+ url: ${JSON.stringify(specUrl).replaceAll('<', '\\u003c')},
77
+ dom_id: '#swagger-ui',
78
+ deepLinking: true,
79
+ presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
80
+ layout: 'StandaloneLayout',
81
+ });
82
+ </script>
83
+ </body>
84
+ </html>
85
+ `;
86
+ }
87
+ function escapeHtml(text) {
88
+ return text
89
+ .replaceAll('&', '&amp;')
90
+ .replaceAll('<', '&lt;')
91
+ .replaceAll('>', '&gt;')
92
+ .replaceAll('"', '&quot;');
93
+ }