@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,84 @@
1
+ import { STATUS_CODES } from 'node:http';
2
+
3
+ import { Reply } from './reply.js';
4
+
5
+ export interface HttpErrorOptions extends ErrorOptions {
6
+ /** Extra members for the problem details body, such as `{ field: 'email' }`. */
7
+ details?: Record<string, unknown>;
8
+ /** Response headers, such as `retry-after`. */
9
+ headers?: Record<string, string>;
10
+ }
11
+
12
+ /**
13
+ * Throw from a handler or middleware to send an error response. The body is
14
+ * an RFC 9457 problem details object (`application/problem+json`):
15
+ * `{ type, title, status, detail, ...details }`.
16
+ */
17
+ export class HttpError extends Error {
18
+ override readonly name = 'HttpError';
19
+ readonly details: Record<string, unknown> | undefined;
20
+ readonly headers: Record<string, string> | undefined;
21
+
22
+ constructor(
23
+ readonly status: number,
24
+ message?: string,
25
+ options: HttpErrorOptions = {},
26
+ ) {
27
+ super(message ?? statusText(status), options);
28
+ this.details = options.details;
29
+ this.headers = options.headers;
30
+ }
31
+ }
32
+
33
+ export const badRequest = (message?: string, options?: HttpErrorOptions) =>
34
+ new HttpError(400, message, options);
35
+ export const unauthorized = (message?: string, options?: HttpErrorOptions) =>
36
+ new HttpError(401, message, options);
37
+ export const forbidden = (message?: string, options?: HttpErrorOptions) =>
38
+ new HttpError(403, message, options);
39
+ export const notFound = (message?: string, options?: HttpErrorOptions) =>
40
+ new HttpError(404, message, options);
41
+ export const conflict = (message?: string, options?: HttpErrorOptions) =>
42
+ new HttpError(409, message, options);
43
+ export const unprocessable = (message?: string, options?: HttpErrorOptions) =>
44
+ new HttpError(422, message, options);
45
+ export const tooManyRequests = (message?: string, options?: HttpErrorOptions) =>
46
+ new HttpError(429, message, options);
47
+
48
+ export function statusText(status: number): string {
49
+ return STATUS_CODES[status] ?? 'Unknown Status';
50
+ }
51
+
52
+ /** The problem details reply for an error status. */
53
+ export function problem(
54
+ status: number,
55
+ detail?: string,
56
+ extra: Record<string, unknown> = {},
57
+ headers: Record<string, string> = {},
58
+ ): Reply<Record<string, unknown>> {
59
+ const body: Record<string, unknown> = {
60
+ type: 'about:blank',
61
+ title: statusText(status),
62
+ status,
63
+ };
64
+ if (detail !== undefined && detail !== body['title']) {
65
+ body['detail'] = detail;
66
+ }
67
+ for (const [key, value] of Object.entries(extra)) {
68
+ if (!(key in body)) {
69
+ body[key] = value;
70
+ }
71
+ }
72
+
73
+ const reply = new Reply(status, body, {
74
+ 'content-type': 'application/problem+json',
75
+ });
76
+ for (const [name, value] of Object.entries(headers)) {
77
+ reply.header(name, value);
78
+ }
79
+ return reply;
80
+ }
81
+
82
+ export function errorReply(error: HttpError): Reply<Record<string, unknown>> {
83
+ return problem(error.status, error.message, error.details, error.headers);
84
+ }
@@ -0,0 +1,37 @@
1
+ import { hash } from 'node:crypto';
2
+
3
+ const cache = new WeakMap<Uint8Array, string>();
4
+
5
+ /** A weak ETag for a body (weak, because compression changes the bytes sent). */
6
+ export function weakEtag(body: string | Uint8Array): string {
7
+ if (typeof body === 'string') {
8
+ return `W/"${hash('sha1', body, 'base64url')}"`;
9
+ }
10
+ let tag = cache.get(body);
11
+ if (tag === undefined) {
12
+ tag = `W/"${hash('sha1', body, 'base64url')}"`;
13
+ cache.set(body, tag);
14
+ }
15
+ return tag;
16
+ }
17
+
18
+ /** Whether an If-None-Match header matches an ETag (weak comparison). */
19
+ export function etagMatches(
20
+ ifNoneMatch: string | undefined,
21
+ etag: string,
22
+ ): boolean {
23
+ if (ifNoneMatch === undefined) {
24
+ return false;
25
+ }
26
+ if (ifNoneMatch.trim() === '*') {
27
+ return true;
28
+ }
29
+ const target = stripWeak(etag);
30
+ return ifNoneMatch
31
+ .split(',')
32
+ .some((candidate) => stripWeak(candidate.trim()) === target);
33
+ }
34
+
35
+ function stripWeak(tag: string): string {
36
+ return tag.startsWith('W/') ? tag.slice(2) : tag;
37
+ }
@@ -0,0 +1,18 @@
1
+ /** Adds a value to a comma-separated `vary` header without duplicating it. */
2
+ export function appendVary(
3
+ headers: Record<string, string>,
4
+ value: string,
5
+ ): void {
6
+ const existing = headers['vary'];
7
+ if (existing === undefined || existing === '') {
8
+ headers['vary'] = value;
9
+ } else if (
10
+ existing !== '*' &&
11
+ !existing
12
+ .toLowerCase()
13
+ .split(/\s*,\s*/)
14
+ .includes(value.toLowerCase())
15
+ ) {
16
+ headers['vary'] = `${existing}, ${value}`;
17
+ }
18
+ }
@@ -0,0 +1,36 @@
1
+ import type { StandardSchemaV1 } from '@tessellation/core';
2
+
3
+ import type { JsonSchema } from './serializer.js';
4
+
5
+ interface JsonSchemaConverter {
6
+ input?: (options: { target: string }) => unknown;
7
+ output?: (options: { target: string }) => unknown;
8
+ }
9
+
10
+ /**
11
+ * The JSON Schema of a Standard Schema, via the Standard JSON Schema
12
+ * extension (`~standard.jsonSchema`, implemented by Zod 4, Valibot, ArkType).
13
+ * `input` describes what clients send (fields with defaults are optional);
14
+ * `output` describes what the schema produces. Undefined when the library
15
+ * does not support it or the schema cannot be expressed (e.g. transforms).
16
+ */
17
+ export function jsonSchemaOf(
18
+ schema: StandardSchemaV1,
19
+ io: 'input' | 'output',
20
+ ): Exclude<JsonSchema, boolean> | undefined {
21
+ const converter = (
22
+ schema['~standard'] as { jsonSchema?: JsonSchemaConverter }
23
+ ).jsonSchema;
24
+ const convert = converter?.[io];
25
+ if (typeof convert !== 'function') {
26
+ return undefined;
27
+ }
28
+ try {
29
+ const result = convert.call(converter, { target: 'draft-2020-12' });
30
+ return typeof result === 'object' && result !== null
31
+ ? (result as Exclude<JsonSchema, boolean>)
32
+ : undefined;
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ }
@@ -0,0 +1,299 @@
1
+ import type { StandardSchemaV1 } from '@tessellation/core';
2
+
3
+ import type { CompiledRoute } from './compile.js';
4
+ import { statusText } from './errors.js';
5
+ import { jsonSchemaOf } from './json-schema.js';
6
+ import { parsePattern } from './router.js';
7
+ import type { JsonSchema } from './serializer.js';
8
+
9
+ type ObjectSchema = Exclude<JsonSchema, boolean>;
10
+
11
+ export interface OpenApiInfo {
12
+ title: string;
13
+ version: string;
14
+ description?: string;
15
+ }
16
+
17
+ export interface OpenApiDocument {
18
+ openapi: '3.1.0';
19
+ info: OpenApiInfo;
20
+ paths: Record<string, Record<string, unknown>>;
21
+ components: {
22
+ schemas: Record<string, unknown>;
23
+ securitySchemes?: Record<string, unknown>;
24
+ };
25
+ }
26
+
27
+ const PROBLEM_REF = '#/components/schemas/ProblemDetails';
28
+
29
+ const PROBLEM_SCHEMA: ObjectSchema = {
30
+ type: 'object',
31
+ description: 'RFC 9457 problem details.',
32
+ properties: {
33
+ type: { type: 'string' },
34
+ title: { type: 'string' },
35
+ status: { type: 'integer' },
36
+ detail: { type: 'string' },
37
+ issues: {
38
+ type: 'array',
39
+ description: 'Validation problems, for 400 responses.',
40
+ items: {
41
+ type: 'object',
42
+ properties: {
43
+ in: { type: 'string', enum: ['params', 'query', 'body'] },
44
+ path: { type: 'string' },
45
+ message: { type: 'string' },
46
+ },
47
+ required: ['in', 'path', 'message'],
48
+ },
49
+ },
50
+ },
51
+ required: ['type', 'title', 'status'],
52
+ };
53
+
54
+ /** Builds an OpenAPI 3.1 document from compiled routes. */
55
+ export function buildOpenApi(
56
+ routes: readonly CompiledRoute[],
57
+ info: OpenApiInfo,
58
+ securitySchemes: Readonly<Record<string, unknown>> = {},
59
+ ): OpenApiDocument {
60
+ // Secured routes accept any of the configured schemes.
61
+ const security = Object.keys(securitySchemes).map((name) => ({ [name]: [] }));
62
+ const components = new Components();
63
+ const paths: OpenApiDocument['paths'] = {};
64
+
65
+ for (const route of routes) {
66
+ if (route.docs.hidden) {
67
+ continue;
68
+ }
69
+ const path = openApiPath(route.path);
70
+ paths[path] ??= {};
71
+ const op = operation(route, components);
72
+ if (route.docs.secured && security.length > 0) {
73
+ op['security'] = security;
74
+ const responses = op['responses'] as Record<string, unknown>;
75
+ responses['401'] ??= { description: 'Authentication is required.' };
76
+ }
77
+ (paths[path] as Record<string, unknown>)[route.method.toLowerCase()] = op;
78
+ }
79
+
80
+ return {
81
+ openapi: '3.1.0',
82
+ info: { ...info },
83
+ paths,
84
+ components: {
85
+ schemas: components.schemas,
86
+ ...(security.length > 0
87
+ ? { securitySchemes: { ...securitySchemes } }
88
+ : {}),
89
+ },
90
+ };
91
+ }
92
+
93
+ function operation(
94
+ route: CompiledRoute,
95
+ components: Components,
96
+ ): Record<string, unknown> {
97
+ const { docs } = route;
98
+ const op: Record<string, unknown> = {};
99
+
100
+ if (docs.operationId !== undefined) op['operationId'] = docs.operationId;
101
+ if (docs.summary !== undefined) op['summary'] = docs.summary;
102
+ if (docs.description !== undefined) op['description'] = docs.description;
103
+ if (docs.tags.length > 0) op['tags'] = docs.tags;
104
+ if (docs.deprecated) op['deprecated'] = true;
105
+
106
+ const parameters = [
107
+ ...pathParameters(route, components),
108
+ ...queryParameters(route, components),
109
+ ];
110
+ if (parameters.length > 0) {
111
+ op['parameters'] = parameters;
112
+ }
113
+
114
+ if (route.body !== undefined) {
115
+ op['requestBody'] = {
116
+ required: true,
117
+ content: {
118
+ 'application/json': { schema: components.embed(route.body, 'input') },
119
+ },
120
+ };
121
+ }
122
+
123
+ const responses: Record<string, unknown> = {};
124
+ for (const [status, schema] of [...route.responses].sort(
125
+ ([a], [b]) => a - b,
126
+ )) {
127
+ responses[String(status)] = {
128
+ description: statusText(status),
129
+ content: {
130
+ 'application/json': { schema: components.embed(schema, 'output') },
131
+ },
132
+ };
133
+ }
134
+ if (route.responses.size === 0) {
135
+ responses['200'] = { description: statusText(200) };
136
+ }
137
+
138
+ const validates =
139
+ route.paramLevels.length > 0 ||
140
+ route.query !== undefined ||
141
+ route.body !== undefined;
142
+ if (validates) {
143
+ components.schemas['ProblemDetails'] ??= PROBLEM_SCHEMA;
144
+ responses['400'] ??= {
145
+ description: 'The request is invalid.',
146
+ content: {
147
+ 'application/problem+json': { schema: { $ref: PROBLEM_REF } },
148
+ },
149
+ };
150
+ }
151
+ op['responses'] = responses;
152
+
153
+ return op;
154
+ }
155
+
156
+ function pathParameters(
157
+ route: CompiledRoute,
158
+ components: Components,
159
+ ): unknown[] {
160
+ const schemas = new Map<string, unknown>();
161
+ for (const level of route.paramLevels) {
162
+ const json = components.inline(level.schema, 'input');
163
+ for (const name of level.names) {
164
+ const property = json?.properties?.[name];
165
+ if (property !== undefined) {
166
+ schemas.set(name, property);
167
+ }
168
+ }
169
+ }
170
+
171
+ return route.paramNames.map((name) => ({
172
+ name,
173
+ in: 'path',
174
+ required: true,
175
+ schema: schemas.get(name) ?? { type: 'string' },
176
+ }));
177
+ }
178
+
179
+ function queryParameters(
180
+ route: CompiledRoute,
181
+ components: Components,
182
+ ): unknown[] {
183
+ if (route.query === undefined) {
184
+ return [];
185
+ }
186
+ const json = components.inline(route.query, 'input');
187
+ const required = new Set(
188
+ Array.isArray(json?.['required']) ? (json['required'] as string[]) : [],
189
+ );
190
+
191
+ return Object.entries(json?.properties ?? {}).map(([name, schema]) => {
192
+ const parameter: Record<string, unknown> = {
193
+ name,
194
+ in: 'query',
195
+ required: required.has(name),
196
+ schema,
197
+ };
198
+ if (
199
+ typeof schema === 'object' &&
200
+ typeof schema['description'] === 'string'
201
+ ) {
202
+ parameter['description'] = schema['description'];
203
+ }
204
+ return parameter;
205
+ });
206
+ }
207
+
208
+ /** `/users/:id/*rest` → `/users/{id}/{rest}`. */
209
+ function openApiPath(pattern: string): string {
210
+ const segments = parsePattern(pattern).map((segment) =>
211
+ segment.kind === 'static' ? segment.value : `{${segment.value}}`,
212
+ );
213
+ return `/${segments.join('/')}`;
214
+ }
215
+
216
+ /**
217
+ * Collects shared schemas. Definitions (`$defs`) inside a schema are moved to
218
+ * `components.schemas` under unique names, and their `$ref`s rewritten, so
219
+ * references resolve against the OpenAPI document.
220
+ */
221
+ class Components {
222
+ readonly schemas: Record<string, unknown> = {};
223
+
224
+ /** A schema for use in the document, or `{}` if it cannot be expressed. */
225
+ embed(schema: StandardSchemaV1, io: 'input' | 'output'): unknown {
226
+ return this.inline(schema, io) ?? {};
227
+ }
228
+
229
+ inline(
230
+ schema: StandardSchemaV1,
231
+ io: 'input' | 'output',
232
+ ): ObjectSchema | undefined {
233
+ const json = jsonSchemaOf(schema, io);
234
+ if (json === undefined) {
235
+ return undefined;
236
+ }
237
+
238
+ const rest: ObjectSchema = { ...json };
239
+ const $defs = rest['$defs'] as Record<string, unknown> | undefined;
240
+ delete rest['$schema'];
241
+ delete rest['$defs'];
242
+ if ($defs === undefined) {
243
+ return rest;
244
+ }
245
+
246
+ // Start by keeping each definition's own name. A name already used by an
247
+ // identical component is shared; a different schema with the same name
248
+ // gets a suffix. Renaming changes references, so repeat until stable.
249
+ const renames = new Map(
250
+ Object.keys($defs).map((name) => [name, sanitize(name)]),
251
+ );
252
+ const rewrite = (value: unknown): unknown =>
253
+ JSON.parse(
254
+ JSON.stringify(value).replace(
255
+ /"#\/\$defs\/([^"]+)"/g,
256
+ (_match, name: string) =>
257
+ JSON.stringify(`#/components/schemas/${renames.get(name) ?? name}`),
258
+ ),
259
+ );
260
+
261
+ let rewritten = new Map<string, unknown>();
262
+ for (let changed = true; changed;) {
263
+ changed = false;
264
+ rewritten = new Map(
265
+ Object.entries($defs).map(([name, def]) => [name, rewrite(def)]),
266
+ );
267
+ for (const [name, definition] of rewritten) {
268
+ const target = renames.get(name) as string;
269
+ const existing = this.schemas[target];
270
+ if (
271
+ existing !== undefined &&
272
+ JSON.stringify(existing) !== JSON.stringify(definition)
273
+ ) {
274
+ renames.set(name, this.freeName(target, renames));
275
+ changed = true;
276
+ }
277
+ }
278
+ }
279
+
280
+ for (const [name, definition] of rewritten) {
281
+ this.schemas[renames.get(name) as string] = definition;
282
+ }
283
+ return rewrite(rest) as ObjectSchema;
284
+ }
285
+
286
+ /** `base_2`, `base_3`, ...: the first not used by a component or another rename. */
287
+ private freeName(base: string, renames: Map<string, string>): string {
288
+ const taken = new Set([...Object.keys(this.schemas), ...renames.values()]);
289
+ let suffix = 2;
290
+ while (taken.has(`${base}_${suffix}`)) {
291
+ suffix += 1;
292
+ }
293
+ return `${base}_${suffix}`;
294
+ }
295
+ }
296
+
297
+ function sanitize(name: string): string {
298
+ return name.replace(/[^\w.-]/g, '_');
299
+ }
@@ -0,0 +1,142 @@
1
+ import { inject, InjectionToken } from '@tessellation/core';
2
+
3
+ import { errorReply, tooManyRequests } from './errors.js';
4
+ import type { Middleware, MiddlewareContext } from './routes.js';
5
+
6
+ export interface RateLimitHit {
7
+ /** Requests counted for the key in the current window, including this one. */
8
+ count: number;
9
+ /** When the window ends, in epoch milliseconds. */
10
+ resetAt: number;
11
+ }
12
+
13
+ /**
14
+ * Counts requests per key in fixed windows. The default keeps counts in
15
+ * memory, per process; provide another (such as one backed by Redis) to
16
+ * share limits across instances.
17
+ */
18
+ export interface RateLimitStore {
19
+ hit(key: string, windowMs: number): RateLimitHit | Promise<RateLimitHit>;
20
+ }
21
+
22
+ /** Fixed-window counts in memory, swept as windows expire. */
23
+ export class MemoryRateLimitStore implements RateLimitStore, Disposable {
24
+ private readonly windows = new Map<string, RateLimitHit>();
25
+ private sweeper: NodeJS.Timeout | undefined;
26
+
27
+ hit(key: string, windowMs: number): RateLimitHit {
28
+ const now = Date.now();
29
+ let entry = this.windows.get(key);
30
+ if (entry === undefined || entry.resetAt <= now) {
31
+ entry = { count: 0, resetAt: now + windowMs };
32
+ this.windows.set(key, entry);
33
+ this.sweeper ??= setInterval(
34
+ () => this.sweep(),
35
+ Math.max(windowMs, 1000),
36
+ ).unref();
37
+ }
38
+ entry.count += 1;
39
+ return entry;
40
+ }
41
+
42
+ /** Number of keys being tracked. */
43
+ get size(): number {
44
+ return this.windows.size;
45
+ }
46
+
47
+ private sweep(): void {
48
+ const now = Date.now();
49
+ for (const [key, entry] of this.windows) {
50
+ if (entry.resetAt <= now) {
51
+ this.windows.delete(key);
52
+ }
53
+ }
54
+ }
55
+
56
+ [Symbol.dispose](): void {
57
+ clearInterval(this.sweeper);
58
+ this.windows.clear();
59
+ }
60
+ }
61
+
62
+ /** The store rate limits use. Defaults to a `MemoryRateLimitStore`. */
63
+ export const RATE_LIMIT_STORE = new InjectionToken<RateLimitStore>(
64
+ 'RATE_LIMIT_STORE',
65
+ {
66
+ factory: () => new MemoryRateLimitStore(),
67
+ },
68
+ );
69
+
70
+ export interface RateLimitOptions {
71
+ /** Requests allowed per window. */
72
+ limit: number;
73
+ /** Window length in milliseconds. */
74
+ window: number;
75
+ /** Separates these counts from other limits. Defaults to `default`. */
76
+ name?: string;
77
+ /**
78
+ * What to count by. Defaults to the client IP (see `http.trustProxy`).
79
+ * Return undefined to skip the limit for a request.
80
+ */
81
+ key?: (context: MiddlewareContext) => string | undefined;
82
+ }
83
+
84
+ /**
85
+ * Limits how often a client may call the routes it wraps. Adds
86
+ * `ratelimit-limit`, `ratelimit-remaining` and `ratelimit-reset` headers, and
87
+ * answers 429 with `retry-after` once the limit is reached.
88
+ *
89
+ * ```ts
90
+ * r.post('/login', { middleware: [rateLimit({ limit: 5, window: 60_000, name: 'login' })], ... })
91
+ * ```
92
+ */
93
+ export function rateLimit(options: RateLimitOptions): Middleware {
94
+ const { limit, window } = options;
95
+ if (!(limit > 0) || !(window > 0)) {
96
+ throw new Error('rateLimit() needs a positive limit and window.');
97
+ }
98
+ const prefix = `${options.name ?? 'default'}:`;
99
+
100
+ return async (context, next) => {
101
+ const store = inject(RATE_LIMIT_STORE);
102
+ const key =
103
+ options.key === undefined
104
+ ? context.request.clientIp
105
+ : options.key(context);
106
+ if (key === undefined) {
107
+ return next();
108
+ }
109
+
110
+ let hit = store.hit(prefix + key, window);
111
+ if (hit instanceof Promise) {
112
+ hit = await hit;
113
+ }
114
+
115
+ const reset = String(
116
+ Math.max(0, Math.ceil((hit.resetAt - Date.now()) / 1000)),
117
+ );
118
+ const headers: Record<string, string> = {
119
+ 'ratelimit-limit': String(limit),
120
+ 'ratelimit-remaining': String(Math.max(0, limit - hit.count)),
121
+ 'ratelimit-reset': reset,
122
+ };
123
+
124
+ if (hit.count > limit) {
125
+ return errorReply(
126
+ tooManyRequests('Too many requests; try again later.', {
127
+ headers: { ...headers, 'retry-after': reset },
128
+ }),
129
+ );
130
+ }
131
+
132
+ const response = await next();
133
+ // With nested limits (global and per route), report the most restrictive.
134
+ const inner = response.headers['ratelimit-remaining'];
135
+ if (inner === undefined || Number(inner) > limit - hit.count) {
136
+ for (const [name, value] of Object.entries(headers)) {
137
+ response.header(name, value);
138
+ }
139
+ }
140
+ return response;
141
+ };
142
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * A response with an explicit status and headers. Handlers can return a
3
+ * plain value instead, which is sent as 200 JSON (or 204 for `undefined`).
4
+ *
5
+ * The body is serialized when the response is sent: a string is sent as
6
+ * text, a `Uint8Array` as bytes, `undefined` as no body, and anything else as
7
+ * JSON (using the route's response schema for that status, if any).
8
+ */
9
+ export class Reply<Body = unknown> {
10
+ readonly headers: Record<string, string>;
11
+
12
+ constructor(
13
+ readonly status: number,
14
+ readonly body: Body,
15
+ headers: Record<string, string> = {},
16
+ ) {
17
+ this.headers = headers;
18
+ }
19
+
20
+ /** Sets a header (names are lower-cased) and returns this reply. */
21
+ header(name: string, value: string): this {
22
+ this.headers[name.toLowerCase()] = value;
23
+ return this;
24
+ }
25
+ }
26
+
27
+ export function reply<Body>(
28
+ status: number,
29
+ body: Body,
30
+ headers?: Record<string, string>,
31
+ ): Reply<Body> {
32
+ return new Reply(status, body, lowerCaseKeys(headers));
33
+ }
34
+
35
+ export function ok<Body>(body: Body): Reply<Body> {
36
+ return new Reply(200, body);
37
+ }
38
+
39
+ /** 201 Created, with a `location` header when given. */
40
+ export function created<Body>(body: Body, location?: string): Reply<Body> {
41
+ return new Reply(201, body, location === undefined ? {} : { location });
42
+ }
43
+
44
+ /** 202 Accepted. */
45
+ export function accepted<Body>(body: Body): Reply<Body> {
46
+ return new Reply(202, body);
47
+ }
48
+
49
+ /** 204 No Content. */
50
+ export function noContent(): Reply<undefined> {
51
+ return new Reply(204, undefined);
52
+ }
53
+
54
+ /** A redirect, 302 by default. */
55
+ export function redirect(
56
+ location: string,
57
+ status: 301 | 302 | 303 | 307 | 308 = 302,
58
+ ): Reply<undefined> {
59
+ return new Reply(status, undefined, { location });
60
+ }
61
+
62
+ function lowerCaseKeys(
63
+ headers: Record<string, string> | undefined,
64
+ ): Record<string, string> {
65
+ const result: Record<string, string> = {};
66
+ for (const [name, value] of Object.entries(headers ?? {})) {
67
+ result[name.toLowerCase()] = value;
68
+ }
69
+ return result;
70
+ }