@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,121 @@
|
|
|
1
|
+
import { promisify } from 'node:util';
|
|
2
|
+
import { brotliCompress, constants, gzip, zstdCompress } from 'node:zlib';
|
|
3
|
+
|
|
4
|
+
import { appendVary } from './headers.js';
|
|
5
|
+
|
|
6
|
+
export type Encoding = 'zstd' | 'br' | 'gzip';
|
|
7
|
+
|
|
8
|
+
export interface CompressionOptions {
|
|
9
|
+
/** Encodings to offer, most preferred first. Defaults to zstd, br, gzip. */
|
|
10
|
+
encodings?: readonly Encoding[];
|
|
11
|
+
/** Smallest body worth compressing, in bytes. Defaults to 1024. */
|
|
12
|
+
threshold?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const COMPRESSORS: Record<Encoding, (data: Buffer) => Promise<Buffer>> = {
|
|
16
|
+
// Levels tuned for dynamic responses: fast, with most of the size benefit.
|
|
17
|
+
zstd: (data) =>
|
|
18
|
+
promisify(zstdCompress)(data, {
|
|
19
|
+
params: { [constants.ZSTD_c_compressionLevel]: 3 },
|
|
20
|
+
}),
|
|
21
|
+
br: (data) =>
|
|
22
|
+
promisify(brotliCompress)(data, {
|
|
23
|
+
params: {
|
|
24
|
+
[constants.BROTLI_PARAM_QUALITY]: 4,
|
|
25
|
+
[constants.BROTLI_PARAM_SIZE_HINT]: data.byteLength,
|
|
26
|
+
},
|
|
27
|
+
}),
|
|
28
|
+
gzip: (data) => promisify(gzip)(data, { level: 6 }),
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const COMPRESSIBLE =
|
|
32
|
+
/^(?:text\/|application\/(?:[\w.+-]*\+)?(?:json|xml)\b|application\/(?:javascript|x-javascript|ecmascript)\b|image\/svg\+xml\b)/i;
|
|
33
|
+
|
|
34
|
+
/** Negotiates and applies response compression. */
|
|
35
|
+
export class Compressor {
|
|
36
|
+
private readonly encodings: readonly Encoding[];
|
|
37
|
+
private readonly threshold: number;
|
|
38
|
+
/** Compressed copies of byte bodies, such as static assets served from memory. */
|
|
39
|
+
private readonly cache = new WeakMap<Uint8Array, Map<Encoding, Buffer>>();
|
|
40
|
+
|
|
41
|
+
constructor(options: CompressionOptions = {}) {
|
|
42
|
+
this.encodings = options.encodings ?? ['zstd', 'br', 'gzip'];
|
|
43
|
+
this.threshold = options.threshold ?? 1024;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Compresses `body` if the response and the client allow it, updating the
|
|
48
|
+
* headers. Returns the body to send.
|
|
49
|
+
*/
|
|
50
|
+
async apply(
|
|
51
|
+
acceptEncoding: string | undefined,
|
|
52
|
+
headers: Record<string, string>,
|
|
53
|
+
body: string | Uint8Array,
|
|
54
|
+
): Promise<string | Uint8Array> {
|
|
55
|
+
const type = headers['content-type'] ?? '';
|
|
56
|
+
if (
|
|
57
|
+
!COMPRESSIBLE.test(type) ||
|
|
58
|
+
headers['content-encoding'] !== undefined ||
|
|
59
|
+
/\bno-transform\b/i.test(headers['cache-control'] ?? '')
|
|
60
|
+
) {
|
|
61
|
+
return body;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The response depends on Accept-Encoding even when it is not compressed.
|
|
65
|
+
appendVary(headers, 'Accept-Encoding');
|
|
66
|
+
|
|
67
|
+
const size =
|
|
68
|
+
typeof body === 'string' ? Buffer.byteLength(body) : body.byteLength;
|
|
69
|
+
const encoding =
|
|
70
|
+
size < this.threshold ? undefined : this.negotiate(acceptEncoding);
|
|
71
|
+
if (encoding === undefined) {
|
|
72
|
+
return body;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
headers['content-encoding'] = encoding;
|
|
76
|
+
if (typeof body === 'string') {
|
|
77
|
+
return COMPRESSORS[encoding](Buffer.from(body));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let cached = this.cache.get(body);
|
|
81
|
+
if (cached === undefined) {
|
|
82
|
+
cached = new Map();
|
|
83
|
+
this.cache.set(body, cached);
|
|
84
|
+
}
|
|
85
|
+
let compressed = cached.get(encoding);
|
|
86
|
+
if (compressed === undefined) {
|
|
87
|
+
compressed = await COMPRESSORS[encoding](
|
|
88
|
+
Buffer.from(body.buffer, body.byteOffset, body.byteLength),
|
|
89
|
+
);
|
|
90
|
+
cached.set(encoding, compressed);
|
|
91
|
+
}
|
|
92
|
+
return compressed;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The most preferred encoding the client accepts (q > 0), if any. */
|
|
96
|
+
negotiate(acceptEncoding: string | undefined): Encoding | undefined {
|
|
97
|
+
if (acceptEncoding === undefined || acceptEncoding === '') {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const quality = new Map<string, number>();
|
|
102
|
+
for (const part of acceptEncoding.split(',')) {
|
|
103
|
+
const [name = '', ...params] = part.trim().toLowerCase().split(';');
|
|
104
|
+
const q = params
|
|
105
|
+
.map((param) => param.trim())
|
|
106
|
+
.find((param) => param.startsWith('q='));
|
|
107
|
+
quality.set(name.trim(), q === undefined ? 1 : Number(q.slice(2)) || 0);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let best: Encoding | undefined;
|
|
111
|
+
let bestQuality = 0;
|
|
112
|
+
for (const encoding of this.encodings) {
|
|
113
|
+
const q = quality.get(encoding) ?? quality.get('*') ?? 0;
|
|
114
|
+
if (q > bestQuality) {
|
|
115
|
+
best = encoding;
|
|
116
|
+
bestQuality = q;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return best;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { defineConfig, settings } from '@tessellation/core';
|
|
2
|
+
|
|
3
|
+
const path = settings.string(/^\/\S*$/, 'a path starting with "/"');
|
|
4
|
+
|
|
5
|
+
const httpShape = {
|
|
6
|
+
/** Port to listen on. Defaults to 8080; 0 picks a free port. */
|
|
7
|
+
port: settings.integer(0, 65_535),
|
|
8
|
+
/** Interface to bind. Defaults to all interfaces. */
|
|
9
|
+
host: settings.string(/\S/, 'a host name or address'),
|
|
10
|
+
/**
|
|
11
|
+
* `uws` (uWebSockets.js, fastest), `node` (`node:http`, no native code),
|
|
12
|
+
* `auto` (the default: `uws` when it can be loaded, otherwise `node`) or
|
|
13
|
+
* `none` (no socket; for tests using `HttpServer.request()`).
|
|
14
|
+
*/
|
|
15
|
+
transport: settings.oneOf(['auto', 'uws', 'node', 'none']),
|
|
16
|
+
/** Generate weak ETags and answer If-None-Match with 304. Defaults to false. */
|
|
17
|
+
etag: settings.boolean(),
|
|
18
|
+
/** Maximum request body size. Defaults to 1mb. */
|
|
19
|
+
bodyLimit: settings.size(),
|
|
20
|
+
/** Log every request at info level. Defaults to false. */
|
|
21
|
+
accessLog: settings.boolean(),
|
|
22
|
+
/** Proxies in front of the server (such as an ingress), for client IPs. Defaults to 0. */
|
|
23
|
+
trustProxy: settings.integer(0, 10),
|
|
24
|
+
/** Answer 503 and abort the request's signal after this long. Off by default. */
|
|
25
|
+
requestTimeout: settings.duration(),
|
|
26
|
+
requestId: settings.nested({
|
|
27
|
+
/** Tag requests and their logs with an id. Defaults to true. */
|
|
28
|
+
enabled: settings.boolean(),
|
|
29
|
+
/** Header read (when valid) and returned. Defaults to x-request-id. */
|
|
30
|
+
header: settings.string(/^[\w-]+$/, 'a header name'),
|
|
31
|
+
}),
|
|
32
|
+
compression: settings.nested({
|
|
33
|
+
/** Compress responses. Defaults to false (often done by the ingress). */
|
|
34
|
+
enabled: settings.boolean(),
|
|
35
|
+
/** Smallest body worth compressing. Defaults to 1kb. */
|
|
36
|
+
threshold: settings.size(),
|
|
37
|
+
/** Encodings offered, most preferred first. Defaults to zstd, br, gzip. */
|
|
38
|
+
encodings: settings.list(settings.oneOf(['zstd', 'br', 'gzip'])),
|
|
39
|
+
}),
|
|
40
|
+
securityHeaders: settings.nested({
|
|
41
|
+
/** Add security headers to every response. Defaults to true. */
|
|
42
|
+
enabled: settings.boolean(),
|
|
43
|
+
/** Enables strict-transport-security with this max-age, such as 180d. */
|
|
44
|
+
hsts: settings.duration(),
|
|
45
|
+
frameOptions: settings.oneOf(['DENY', 'SAMEORIGIN']),
|
|
46
|
+
referrerPolicy: settings.string(
|
|
47
|
+
/^[\w-]+(,\s*[\w-]+)*$/,
|
|
48
|
+
'a referrer policy',
|
|
49
|
+
),
|
|
50
|
+
contentSecurityPolicy: settings.string(/\S/, 'a content security policy'),
|
|
51
|
+
}),
|
|
52
|
+
rateLimit: settings.nested({
|
|
53
|
+
/** Requests per window for every route; off unless set. */
|
|
54
|
+
limit: settings.integer(1, 1_000_000_000),
|
|
55
|
+
/** Window length. Defaults to 1m. */
|
|
56
|
+
window: settings.duration(),
|
|
57
|
+
/** Count by this header (such as x-api-key) instead of the client IP. */
|
|
58
|
+
keyHeader: settings.string(/^[\w-]+$/, 'a header name'),
|
|
59
|
+
}),
|
|
60
|
+
cors: settings.nested({
|
|
61
|
+
/** Allowed origins; CORS is off when empty. Exact, `https://*.example.com` or `*`. */
|
|
62
|
+
origins: settings.list(
|
|
63
|
+
settings.string(
|
|
64
|
+
/^(\*|https?:\/\/\S+)$/,
|
|
65
|
+
'an origin such as https://app.example.com, or *',
|
|
66
|
+
),
|
|
67
|
+
),
|
|
68
|
+
methods: settings.list(settings.string(/^[A-Z]+$/, 'an upper-case method')),
|
|
69
|
+
allowedHeaders: settings.list(settings.string(/^[\w-]+$/, 'a header name')),
|
|
70
|
+
exposedHeaders: settings.list(settings.string(/^[\w-]+$/, 'a header name')),
|
|
71
|
+
credentials: settings.boolean(),
|
|
72
|
+
/** How long browsers may cache preflight responses, such as 10m. */
|
|
73
|
+
maxAge: settings.duration(),
|
|
74
|
+
}),
|
|
75
|
+
websocket: settings.nested({
|
|
76
|
+
/** Largest accepted message. Defaults to 64kb. */
|
|
77
|
+
maxPayload: settings.size(),
|
|
78
|
+
/** Close idle connections after this long (uws). Defaults to 2m. */
|
|
79
|
+
idleTimeout: settings.duration(),
|
|
80
|
+
}),
|
|
81
|
+
docs: settings.nested({
|
|
82
|
+
/** Serve Swagger UI and the OpenAPI document. Defaults to true. */
|
|
83
|
+
enabled: settings.boolean(),
|
|
84
|
+
/** Where Swagger UI is served. Defaults to /docs. */
|
|
85
|
+
path,
|
|
86
|
+
title: settings.string(),
|
|
87
|
+
version: settings.string(),
|
|
88
|
+
description: settings.string(),
|
|
89
|
+
}),
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/** Settings under the `http` config section. */
|
|
93
|
+
export type HttpSettings = settings.Settings<typeof httpShape>;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The `http` config section, registered by `provideHttp()`. Its values take
|
|
97
|
+
* precedence over the options passed in code.
|
|
98
|
+
*
|
|
99
|
+
* ```yaml
|
|
100
|
+
* http:
|
|
101
|
+
* port: ${env:PORT:-8080}
|
|
102
|
+
* bodyLimit: 5mb
|
|
103
|
+
* docs:
|
|
104
|
+
* enabled: false
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
export const HttpConfig = defineConfig('http', settings.schema(httpShape));
|
package/src/lib/cors.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { problem } from './errors.js';
|
|
2
|
+
import { appendVary as appendVaryHeader } from './headers.js';
|
|
3
|
+
import { Reply } from './reply.js';
|
|
4
|
+
import type { HttpRequest } from './request.js';
|
|
5
|
+
|
|
6
|
+
export interface CorsOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Origins allowed to call the API: exact origins such as
|
|
9
|
+
* `https://app.example.com`, subdomain patterns such as
|
|
10
|
+
* `https://*.example.com`, or `*` for any origin. CORS is off when empty.
|
|
11
|
+
*/
|
|
12
|
+
origins?: readonly string[];
|
|
13
|
+
/** Methods allowed in preflight responses. Defaults to the methods the path supports. */
|
|
14
|
+
methods?: readonly string[];
|
|
15
|
+
/** Request headers allowed. Defaults to whatever the preflight asks for. */
|
|
16
|
+
allowedHeaders?: readonly string[];
|
|
17
|
+
/** Response headers the browser may read, beyond the CORS-safelisted ones. */
|
|
18
|
+
exposedHeaders?: readonly string[];
|
|
19
|
+
/** Allow cookies and authorization headers. With `*`, the request's origin is echoed back. */
|
|
20
|
+
credentials?: boolean;
|
|
21
|
+
/** How long, in milliseconds, browsers may cache a preflight response. */
|
|
22
|
+
maxAge?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Cross-origin resource sharing, applied by the engine to every response
|
|
27
|
+
* (including errors) and answering preflight requests for any route.
|
|
28
|
+
*/
|
|
29
|
+
export class CorsPolicy {
|
|
30
|
+
private readonly any: boolean;
|
|
31
|
+
private readonly exact: Set<string>;
|
|
32
|
+
private readonly patterns: RegExp[];
|
|
33
|
+
|
|
34
|
+
constructor(private readonly options: CorsOptions) {
|
|
35
|
+
const origins = options.origins ?? [];
|
|
36
|
+
this.any = origins.includes('*');
|
|
37
|
+
this.exact = new Set(origins.filter((origin) => !origin.includes('*')));
|
|
38
|
+
this.patterns = origins
|
|
39
|
+
.filter((origin) => origin !== '*' && origin.includes('*'))
|
|
40
|
+
.map(originPattern);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
get enabled(): boolean {
|
|
44
|
+
return this.any || this.exact.size > 0 || this.patterns.length > 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
isPreflight(request: HttpRequest): boolean {
|
|
48
|
+
return (
|
|
49
|
+
request.method === 'OPTIONS' &&
|
|
50
|
+
request.headers['origin'] !== undefined &&
|
|
51
|
+
request.headers['access-control-request-method'] !== undefined
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Answers a preflight request for a path supporting `methods`. */
|
|
56
|
+
preflight(request: HttpRequest, methods: readonly string[]): Reply {
|
|
57
|
+
const origin = request.headers['origin'] ?? '';
|
|
58
|
+
const allowed = this.allowedOrigin(origin);
|
|
59
|
+
if (allowed === undefined) {
|
|
60
|
+
return problem(403, `The origin ${origin} is not allowed.`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const response = new Reply(204, undefined);
|
|
64
|
+
this.setOrigin(response, allowed);
|
|
65
|
+
response.header(
|
|
66
|
+
'access-control-allow-methods',
|
|
67
|
+
(this.options.methods ?? methods).join(', '),
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const requested = request.headers['access-control-request-headers'];
|
|
71
|
+
const headers = this.options.allowedHeaders?.join(', ') ?? requested;
|
|
72
|
+
if (headers !== undefined && headers !== '') {
|
|
73
|
+
response.header('access-control-allow-headers', headers);
|
|
74
|
+
}
|
|
75
|
+
if (this.options.maxAge !== undefined) {
|
|
76
|
+
response.header(
|
|
77
|
+
'access-control-max-age',
|
|
78
|
+
String(Math.floor(this.options.maxAge / 1000)),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
if (this.options.allowedHeaders === undefined) {
|
|
82
|
+
appendVary(response, 'Access-Control-Request-Headers');
|
|
83
|
+
}
|
|
84
|
+
return response;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Adds CORS headers to a response for an allowed origin. */
|
|
88
|
+
apply(request: HttpRequest, response: Reply): void {
|
|
89
|
+
const origin = request.headers['origin'];
|
|
90
|
+
if (origin === undefined) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const allowed = this.allowedOrigin(origin);
|
|
94
|
+
if (allowed === undefined) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.setOrigin(response, allowed);
|
|
98
|
+
if (
|
|
99
|
+
this.options.exposedHeaders !== undefined &&
|
|
100
|
+
this.options.exposedHeaders.length > 0
|
|
101
|
+
) {
|
|
102
|
+
response.header(
|
|
103
|
+
'access-control-expose-headers',
|
|
104
|
+
this.options.exposedHeaders.join(', '),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The `access-control-allow-origin` value for an origin, or undefined if it is not allowed. */
|
|
110
|
+
private allowedOrigin(origin: string): string | undefined {
|
|
111
|
+
if (
|
|
112
|
+
this.exact.has(origin) ||
|
|
113
|
+
this.patterns.some((pattern) => pattern.test(origin))
|
|
114
|
+
) {
|
|
115
|
+
return origin;
|
|
116
|
+
}
|
|
117
|
+
if (this.any) {
|
|
118
|
+
// Browsers reject `*` for credentialed requests, so echo the origin.
|
|
119
|
+
return this.options.credentials ? origin : '*';
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private setOrigin(response: Reply, allowed: string): void {
|
|
125
|
+
response.header('access-control-allow-origin', allowed);
|
|
126
|
+
if (allowed !== '*') {
|
|
127
|
+
appendVary(response, 'Origin');
|
|
128
|
+
}
|
|
129
|
+
if (this.options.credentials) {
|
|
130
|
+
response.header('access-control-allow-credentials', 'true');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** `https://*.example.com` matches one or more subdomain labels. */
|
|
136
|
+
function originPattern(pattern: string): RegExp {
|
|
137
|
+
const source = pattern
|
|
138
|
+
.split('*')
|
|
139
|
+
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
|
|
140
|
+
.join('(?:[a-z0-9-]+\\.)*[a-z0-9-]+');
|
|
141
|
+
return new RegExp(`^${source}$`, 'i');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function appendVary(response: Reply, value: string): void {
|
|
145
|
+
appendVaryHeader(response.headers, value);
|
|
146
|
+
}
|
package/src/lib/docs.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { type CompiledRoute, compileRoutes, joinPaths } from './compile.js';
|
|
6
|
+
import { weakEtag } from './etag.js';
|
|
7
|
+
import { buildOpenApi, type OpenApiInfo } from './openapi.js';
|
|
8
|
+
import { reply } from './reply.js';
|
|
9
|
+
import { routes } from './routes.js';
|
|
10
|
+
|
|
11
|
+
const ASSETS: Record<string, string> = {
|
|
12
|
+
'swagger-ui.css': 'text/css; charset=utf-8',
|
|
13
|
+
'swagger-ui-bundle.js': 'text/javascript; charset=utf-8',
|
|
14
|
+
'swagger-ui-standalone-preset.js': 'text/javascript; charset=utf-8',
|
|
15
|
+
'favicon-32x32.png': 'image/png',
|
|
16
|
+
'favicon-16x16.png': 'image/png',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export interface DocsOptions extends OpenApiInfo {
|
|
20
|
+
/** Where Swagger UI is served, such as `/docs`. */
|
|
21
|
+
path: string;
|
|
22
|
+
/** OpenAPI security schemes by name, from the auth strategies. */
|
|
23
|
+
securitySchemes?: Readonly<Record<string, unknown>>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Routes serving Swagger UI at `path` and the OpenAPI document at
|
|
28
|
+
* `path/openapi.json`, built from `apiRoutes`. Assets come from the bundled
|
|
29
|
+
* `swagger-ui-dist` package and are held in memory.
|
|
30
|
+
*/
|
|
31
|
+
export function docsRoutes(
|
|
32
|
+
apiRoutes: readonly CompiledRoute[],
|
|
33
|
+
options: DocsOptions,
|
|
34
|
+
): CompiledRoute[] {
|
|
35
|
+
const { path, securitySchemes, ...info } = options;
|
|
36
|
+
const spec = JSON.stringify(buildOpenApi(apiRoutes, info, securitySchemes));
|
|
37
|
+
const specTag = weakEtag(spec);
|
|
38
|
+
const specUrl = joinPaths(path, '/openapi.json');
|
|
39
|
+
const page = indexPage(info.title, joinPaths(path, '/'), specUrl);
|
|
40
|
+
const assets = loadAssets();
|
|
41
|
+
const cache = { 'cache-control': 'public, max-age=86400' };
|
|
42
|
+
|
|
43
|
+
const tree = routes(path, { hidden: true }, (r) => [
|
|
44
|
+
r.get('/', {
|
|
45
|
+
handler: () =>
|
|
46
|
+
reply(200, page, { 'content-type': 'text/html; charset=utf-8' }),
|
|
47
|
+
}),
|
|
48
|
+
r.get('/openapi.json', {
|
|
49
|
+
handler: () =>
|
|
50
|
+
reply(200, spec, { 'content-type': 'application/json', etag: specTag }),
|
|
51
|
+
}),
|
|
52
|
+
r.get('/:asset', {
|
|
53
|
+
handler: ({ params }) => {
|
|
54
|
+
const asset = assets.get(params.asset);
|
|
55
|
+
return asset === undefined
|
|
56
|
+
? reply(404, 'Not Found')
|
|
57
|
+
: reply(200, asset.body, {
|
|
58
|
+
'content-type': asset.type,
|
|
59
|
+
etag: weakEtag(asset.body),
|
|
60
|
+
...cache,
|
|
61
|
+
});
|
|
62
|
+
},
|
|
63
|
+
}),
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
return compileRoutes([tree]);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function loadAssets(): Map<string, { body: Uint8Array; type: string }> {
|
|
70
|
+
const require = createRequire(import.meta.url);
|
|
71
|
+
const directory = dirname(require.resolve('swagger-ui-dist/package.json'));
|
|
72
|
+
return new Map(
|
|
73
|
+
Object.entries(ASSETS).map(([name, type]) => [
|
|
74
|
+
name,
|
|
75
|
+
{ body: readFileSync(join(directory, name)), type },
|
|
76
|
+
]),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function indexPage(title: string, base: string, specUrl: string): string {
|
|
81
|
+
const prefix = base === '/' ? '' : base;
|
|
82
|
+
return `<!doctype html>
|
|
83
|
+
<html lang="en">
|
|
84
|
+
<head>
|
|
85
|
+
<meta charset="utf-8">
|
|
86
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
87
|
+
<title>${escapeHtml(title)}</title>
|
|
88
|
+
<link rel="stylesheet" href="${prefix}/swagger-ui.css">
|
|
89
|
+
<link rel="icon" type="image/png" href="${prefix}/favicon-32x32.png" sizes="32x32">
|
|
90
|
+
</head>
|
|
91
|
+
<body>
|
|
92
|
+
<div id="swagger-ui"></div>
|
|
93
|
+
<script src="${prefix}/swagger-ui-bundle.js"></script>
|
|
94
|
+
<script src="${prefix}/swagger-ui-standalone-preset.js"></script>
|
|
95
|
+
<script>
|
|
96
|
+
window.ui = SwaggerUIBundle({
|
|
97
|
+
url: ${JSON.stringify(specUrl).replaceAll('<', '\\u003c')},
|
|
98
|
+
dom_id: '#swagger-ui',
|
|
99
|
+
deepLinking: true,
|
|
100
|
+
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
|
|
101
|
+
layout: 'StandaloneLayout',
|
|
102
|
+
});
|
|
103
|
+
</script>
|
|
104
|
+
</body>
|
|
105
|
+
</html>
|
|
106
|
+
`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function escapeHtml(text: string): string {
|
|
110
|
+
return text
|
|
111
|
+
.replaceAll('&', '&')
|
|
112
|
+
.replaceAll('<', '<')
|
|
113
|
+
.replaceAll('>', '>')
|
|
114
|
+
.replaceAll('"', '"');
|
|
115
|
+
}
|