@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present Ethan Elliott
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,413 @@
1
- # Temporary Holding Version
1
+ # @tessellation/http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A fast HTTP layer for Tessellation: typed nested routes, Standard Schema
4
+ validation, per-request dependency injection, OpenAPI 3.1 and Swagger UI.
5
+ It runs on uWebSockets.js (native, the fastest available) and falls back to
6
+ `node:http`, with identical behaviour on both.
7
+
8
+ ```sh
9
+ pnpm add @tessellation/core @tessellation/http
10
+ ```
11
+
12
+ Needs Node.js 26 or later.
13
+
14
+ ```ts
15
+ import { inject } from '@tessellation/core';
16
+ import { created, notFound, provideHttp, routes } from '@tessellation/http';
17
+ import { z } from 'zod';
18
+
19
+ const User = z.object({ id: z.uuid(), name: z.string() }).meta({ id: 'User' });
20
+
21
+ export const userRoutes = routes('/users', { tags: ['users'] }, (r) => [
22
+ r.get('/', {
23
+ query: z.object({ page: z.coerce.number().int().default(1) }),
24
+ response: z.array(User),
25
+ handler: ({ query }) => inject(UserService).list(query.page),
26
+ }),
27
+ r.post('/', {
28
+ body: z.object({ name: z.string().min(1) }),
29
+ response: { 201: User },
30
+ handler: async ({ body }) =>
31
+ created(await inject(UserService).create(body)),
32
+ }),
33
+ r.group('/:userId', { params: z.object({ userId: z.uuid() }) }, (r) => [
34
+ r.get('/', {
35
+ response: User,
36
+ handler: async ({ params }) => {
37
+ const user = await inject(UserService).find(params.userId);
38
+ if (user === undefined) throw notFound();
39
+ return user;
40
+ },
41
+ }),
42
+ r.group('/posts', (r) => [
43
+ r.get('/:postId', {
44
+ params: z.object({ postId: z.coerce.number().int() }),
45
+ // params.userId and params.postId are both typed
46
+ handler: ({ params }) =>
47
+ inject(PostService).get(params.userId, params.postId),
48
+ }),
49
+ ]),
50
+ ]),
51
+ ]);
52
+
53
+ await bootstrapApplication({
54
+ providers: [
55
+ provideHealthServer(),
56
+ provideHttp({ prefix: '/api', routes: [userRoutes] }),
57
+ ],
58
+ });
59
+ ```
60
+
61
+ ## Routes
62
+
63
+ - `routes(path, [options], (r) => [...])` defines a tree. `r.get/post/put/patch/delete/options`
64
+ add routes; `r.group(path, [options], (r) => [...])` nests; `r.include(tree)` adds
65
+ a tree from another file.
66
+ - Path params are typed from the path (`/:id`, `/*rest`), or from a `params` schema,
67
+ which validates (and can convert) them. A group's params, middleware,
68
+ request-scoped providers and tags apply to everything inside it.
69
+ - `routes.withParams<{ userId: string }>()('/posts', ...)` defines a tree that needs
70
+ params from where it is included; `include()` checks they are there.
71
+ - `query` and `body` (JSON) schemas validate the request; every problem is
72
+ reported in one 400 response. Any Standard Schema works.
73
+ - Handlers run in the injection context, so they can `inject()` services before
74
+ their first `await`. Return a value (200 JSON), `undefined` (204), a string
75
+ (text), bytes, or a `Reply` from `created()`, `noContent()`, `redirect()`,
76
+ `reply(status, body, headers)`.
77
+ - Throw `HttpError` (or `notFound()`, `badRequest()`, `unauthorized()`, ...) for
78
+ error responses. Errors are RFC 9457 problem details
79
+ (`application/problem+json`); unexpected errors are logged and answered with a
80
+ bare 500.
81
+
82
+ ## Responses
83
+
84
+ With a `response` schema, only the properties it declares are sent, so fields a
85
+ handler returns by accident (a password hash, internal ids) never leak. V8's
86
+ `JSON.stringify` does the serializing: on Node 26 it beats any serializer
87
+ generated in JavaScript, and the projection costs about 5%.
88
+
89
+ ## Middleware
90
+
91
+ ```ts
92
+ const timing: Middleware = async (context, next) => {
93
+ const started = performance.now();
94
+ const response = await next();
95
+ return response.header(
96
+ 'server-timing',
97
+ `app;dur=${performance.now() - started}`,
98
+ );
99
+ };
100
+ ```
101
+
102
+ Middleware runs outermost first: `provideHttp({ middleware })`, then groups,
103
+ then the route. `next()` always resolves to a reply, including for errors
104
+ thrown further in. Return a reply without calling `next()` to answer early.
105
+
106
+ ## Request-scoped providers
107
+
108
+ Providers listed on a route or group are created once per request, in a child
109
+ of the application injector, and disposed after the response. They can inject
110
+ `HttpRequest`. Routes without them pay nothing for the feature.
111
+
112
+ ```ts
113
+ class CurrentUser {
114
+ static readonly providedIn: ProvidedIn = null;
115
+ readonly id = verifyToken(inject(HttpRequest).header('authorization'));
116
+ }
117
+
118
+ routes('/me', { providers: [CurrentUser] }, (r) => [
119
+ r.get('/', {
120
+ handler: () => inject(UserService).find(inject(CurrentUser).id),
121
+ }),
122
+ ]);
123
+ ```
124
+
125
+ ## OpenAPI and Swagger UI
126
+
127
+ Swagger UI is served at `/docs` and the OpenAPI 3.1 document at
128
+ `/docs/openapi.json`, generated from the route schemas and their `summary`,
129
+ `description`, `tags`, `operationId`, `deprecated` and `hidden` options. Named
130
+ schemas (Zod `.meta({ id })`) become `components.schemas`. The UI is bundled,
131
+ not loaded from a CDN.
132
+
133
+ ## Configuration
134
+
135
+ `provideHttp()` registers the `http` config section, which overrides the
136
+ options passed in code:
137
+
138
+ ```yaml
139
+ http:
140
+ port: ${env:PORT:-8080}
141
+ host: 0.0.0.0
142
+ transport: auto # uws | node | auto (uws when it loads)
143
+ bodyLimit: 1mb
144
+ accessLog: false
145
+ trustProxy: 0
146
+ requestTimeout: 10s
147
+ etag: false
148
+ docs:
149
+ enabled: true
150
+ path: /docs
151
+ title: Users API
152
+ version: 1.0.0
153
+ ```
154
+
155
+ ## Request ids and log correlation
156
+
157
+ Every request gets an id: the incoming `x-request-id` when it is valid,
158
+ otherwise a new UUID. It is returned in the same header, available as
159
+ `request.id`, and added to **every log line written while handling the
160
+ request**, including from services and after `await`s (via core's
161
+ `withLogFields`). Turn it off or rename the header with
162
+ `http.requestId: { enabled, header }`.
163
+
164
+ ## Cancellation and timeouts
165
+
166
+ Handlers and middleware get a `signal` that is aborted when the client
167
+ disconnects or the request times out. Pass it on so abandoned work stops:
168
+
169
+ ```ts
170
+ r.get('/report', {
171
+ handler: ({ signal }) => inject(Reports).build({ signal }),
172
+ });
173
+ ```
174
+
175
+ `http.requestTimeout: 10s` answers 503 after that long and aborts the signal
176
+ (`TimeoutError`); request-scoped providers are cleaned up once the handler
177
+ actually finishes. Off by default.
178
+
179
+ ## Security headers
180
+
181
+ On by default, for every response that does not set them itself:
182
+ `x-content-type-options: nosniff`, `x-frame-options: DENY`,
183
+ `referrer-policy: no-referrer`, `cross-origin-opener-policy: same-origin`.
184
+
185
+ ```yaml
186
+ http:
187
+ securityHeaders:
188
+ hsts: 180d # strict-transport-security, only when served over HTTPS
189
+ contentSecurityPolicy: "default-src 'none'"
190
+ frameOptions: SAMEORIGIN
191
+ referrerPolicy: strict-origin-when-cross-origin
192
+ # enabled: false
193
+ ```
194
+
195
+ ## Compression
196
+
197
+ Off by default, since an ingress often compresses. When enabled, JSON, text,
198
+ JavaScript, XML and SVG responses over the threshold are compressed with the
199
+ best encoding the client accepts. Byte bodies (such as the Swagger UI assets)
200
+ are compressed once and cached.
201
+
202
+ ```yaml
203
+ http:
204
+ compression:
205
+ enabled: true
206
+ threshold: 1kb
207
+ encodings: [zstd, br, gzip] # most preferred first
208
+ ```
209
+
210
+ ## Rate limiting
211
+
212
+ A limit for every route from config, or per route with middleware:
213
+
214
+ ```yaml
215
+ http:
216
+ trustProxy: 1 # proxies in front (e.g. an ingress), so client IPs come from x-forwarded-for
217
+ rateLimit:
218
+ limit: 600
219
+ window: 1m
220
+ keyHeader: x-api-key # count per API key instead of per client IP
221
+ ```
222
+
223
+ ```ts
224
+ r.post('/login', {
225
+ middleware: [rateLimit({ limit: 5, window: 60_000, name: 'login' })],
226
+ handler: ...,
227
+ });
228
+ ```
229
+
230
+ Responses carry `ratelimit-limit`, `ratelimit-remaining` and
231
+ `ratelimit-reset`; over the limit the answer is 429 with `retry-after`.
232
+ Counts live in a `MemoryRateLimitStore` (per process, cleared on shutdown);
233
+ provide `RATE_LIMIT_STORE` to share them, for example through Redis.
234
+
235
+ ## Authentication
236
+
237
+ `provideAuth()` authenticates every request with the first strategy that
238
+ recognizes its credentials. Routes opt in to protection:
239
+
240
+ ```ts
241
+ provideAuth(
242
+ () => apiKeyAuth({ keys: inject(AuthConfig).apiKeys }), // factories can read config
243
+ jwtAuth({ jwksUrl: 'https://id.example.com/.well-known/jwks.json', audience: 'api' }),
244
+ );
245
+
246
+ r.get('/me', { middleware: [authenticated()], handler: () => requirePrincipal() });
247
+ r.delete('/:id', { middleware: [requireRoles('admin')], handler: ... });
248
+ r.post('/:id/publish', { middleware: [authorize((p) => p.claims['plan'] === 'pro')], handler: ... });
249
+ ```
250
+
251
+ - `apiKeyAuth`: keys by user (compared in constant time) or a lookup function.
252
+ - `jwtAuth`: HS*, RS*, PS*, ES* and EdDSA, with a secret, a public key or a
253
+ JWKS URL (cached, refreshed on key rotation); checks `exp`, `nbf`, `iss` and
254
+ `aud`. Algorithms are tied to key types, and `none` is never accepted.
255
+ - The principal (`{ id, strategy, roles, claims }`) is available anywhere in
256
+ the request through `principal()` / `requirePrincipal()`, and request logs
257
+ carry its id.
258
+ - Strategies' security schemes, and which routes need them, appear in OpenAPI.
259
+
260
+ Your own scheme plugs into the same pipeline by implementing `AuthStrategy`:
261
+
262
+ ```ts
263
+ const sessionAuth: AuthStrategy = {
264
+ name: 'session',
265
+ scheme: { type: 'apiKey', in: 'cookie', name: 'sid' },
266
+ async authenticate(request) {
267
+ const sid = readCookie(request.header('cookie'), 'sid');
268
+ if (sid === undefined) return undefined; // not ours: try the next strategy
269
+ const session = await inject(Sessions).find(sid);
270
+ if (session === undefined) throw unauthorized('Session expired.');
271
+ return {
272
+ id: session.userId,
273
+ strategy: 'session',
274
+ roles: session.roles,
275
+ claims: {},
276
+ };
277
+ },
278
+ };
279
+ ```
280
+
281
+ For other per-request state, use core's `AsyncContext` in middleware.
282
+
283
+ ## ETags
284
+
285
+ Responses whose handlers set an `etag` header answer a matching
286
+ `If-None-Match` with 304. `http.etag: true` generates weak ETags for
287
+ successful GET responses (off by default, as it hashes every response).
288
+ Swagger UI assets always have ETags.
289
+
290
+ ## Metrics
291
+
292
+ With `provideMetrics()` from core, every request is recorded in
293
+ `http_request_duration_seconds` by method, route pattern and status, and
294
+ `http_requests_in_flight` is reported.
295
+
296
+ ## Testing
297
+
298
+ `HttpServer.request()` sends a request through the whole pipeline in
299
+ memory. With `http.transport: none`, no port is opened:
300
+
301
+ ```ts
302
+ const app = createApplication({
303
+ providers: [
304
+ ...appProviders(),
305
+ provideConfigValues({ http: { transport: 'none' } }),
306
+ ],
307
+ });
308
+ await app.start();
309
+
310
+ const response = await app.injector.get(HttpServer).request({
311
+ method: 'POST',
312
+ path: '/api/projects',
313
+ headers: { 'x-api-key': 'test-key' },
314
+ body: { name: 'Launch' },
315
+ });
316
+ expect(response.status).toBe(201);
317
+ expect(response.json()).toMatchObject({ name: 'Launch' });
318
+ ```
319
+
320
+ ## WebSockets
321
+
322
+ ```ts
323
+ r.websocket('/rooms/:room', {
324
+ middleware: [authenticated()],
325
+ upgrade: ({ params }) => ({ room: params.room, user: requirePrincipal().id }),
326
+ open: (socket) => socket.subscribe(socket.data.room),
327
+ message: (socket, text) =>
328
+ socket.publish(socket.data.room, `${socket.data.user}: ${text}`),
329
+ close: (socket, code) => {},
330
+ });
331
+
332
+ inject(HttpServer).publish('lobby', 'announcement'); // to every subscriber
333
+ ```
334
+
335
+ The upgrade request goes through the normal pipeline (middleware, auth, rate
336
+ limits, validation, request ids), so it can be refused with any HTTP error;
337
+ `upgrade()` returns the connection's `data`. Handlers then run in the
338
+ upgrade's async context, so `requirePrincipal()`, your own `AsyncContext`s and
339
+ the request's log fields keep working for the life of the connection. Text
340
+ frames arrive as strings, binary frames as bytes. Plain requests get 426;
341
+ failing handlers close the socket with 1011; shutdown closes sockets with 1001.
342
+ Works on both transports (natively on uWebSockets.js, through `ws` on
343
+ `node:http`).
344
+
345
+ ```yaml
346
+ http:
347
+ websocket:
348
+ maxPayload: 64kb
349
+ idleTimeout: 2m
350
+ ```
351
+
352
+ ## Tracing
353
+
354
+ With core's `provideTracing()`, each request runs in a server span named after
355
+ its route pattern (`GET /orders/:id`), continuing an incoming `traceparent`,
356
+ with OpenTelemetry HTTP attributes.
357
+
358
+ ## Middleware from other modules
359
+
360
+ A module can add global middleware without touching `provideHttp()`:
361
+
362
+ ```ts
363
+ export function provideAuditLog(): Provider[] {
364
+ return [provideHttpMiddleware(auditMiddleware)];
365
+ }
366
+ ```
367
+
368
+ Global middleware runs in this order: the config rate limit, then module
369
+ middleware (in provider order), then `provideHttp({ middleware })`.
370
+
371
+ ## Cost of the defaults
372
+
373
+ Measured with `benchmarks/http` (uWebSockets.js transport, relative to raw
374
+ uWebSockets.js): 85% with request ids and security headers off, 74% with both
375
+ on (the defaults). Request ids cost about 8% (mostly `AsyncLocalStorage`),
376
+ security headers about 5%.
377
+
378
+ ## CORS
379
+
380
+ CORS is off until origins are configured. It applies to every response,
381
+ including errors, and answers preflight requests for any route (with the
382
+ methods that path supports).
383
+
384
+ ```yaml
385
+ http:
386
+ cors:
387
+ origins: https://app.example.com, https://*.preview.example.com # or a list, or *
388
+ credentials: true # with *, the request's origin is echoed back
389
+ exposedHeaders: [x-total-count]
390
+ maxAge: 10m # how long browsers cache preflights
391
+ # methods / allowedHeaders default to what the path supports / what is asked for
392
+ ```
393
+
394
+ Lists also accept comma-separated text, so `origins: ${env:CORS_ORIGINS:-}`
395
+ works. Preflights from other origins get 403; other requests from them get
396
+ no CORS headers, so browsers block them.
397
+
398
+ ## Shutdown
399
+
400
+ On shutdown the server stops accepting connections, lets in-flight requests
401
+ finish (answering with `connection: close`), then closes the remaining
402
+ connections. Combine with `application.shutdownDelay` on Kubernetes.
403
+
404
+ ## Transports
405
+
406
+ - `uws`: uWebSockets.js, native networking and HTTP parsing. An optional
407
+ dependency installed from a pinned GitHub release, since it is not on the
408
+ npm registry; it ships binaries per platform and Node version. HTTP/1.1
409
+ only.
410
+ - `node`: Node's `node:http`. No native code.
411
+
412
+ `auto` (the default) uses `uws` when it can be loaded and logs a warning when
413
+ it falls back to `node`. Benchmarks are in `benchmarks/http`.
@@ -0,0 +1,20 @@
1
+ export { apiKeyAuth, type ApiKeyAuthOptions } from './lib/auth/api-key.js';
2
+ export { type JsonWebKey, type JwtAuthOptions, jwtAuth, type JwtClaims, } from './lib/auth/jwt.js';
3
+ export { authenticated, authorize, provideAuth, requireRoles, } from './lib/auth/provide-auth.js';
4
+ export { AUTH_STRATEGIES, type AuthStrategy, CurrentPrincipal, type Principal, principal, requirePrincipal, } from './lib/auth/strategy.js';
5
+ export { type CompressionOptions, Compressor, type Encoding, } from './lib/compression.js';
6
+ export { HttpConfig, type HttpSettings } from './lib/config.js';
7
+ export { type CorsOptions, CorsPolicy } from './lib/cors.js';
8
+ export { badRequest, conflict, forbidden, HttpError, type HttpErrorOptions, notFound, problem, tooManyRequests, unauthorized, unprocessable, } from './lib/errors.js';
9
+ export { accepted, created, noContent, ok, redirect, Reply, reply, } from './lib/reply.js';
10
+ export { HttpRequest, type ResponseSink } from './lib/request.js';
11
+ export type { TestRequestInit, TestResponse } from './lib/testing.js';
12
+ export { type GroupDefinition, type GroupOptions, type HandlerResult, type HttpMethod, type Middleware, type MiddlewareContext, type PathParams, type RawQuery, type RequestContext, RouteBuilder, type RouteDefinition, type RouteDocs, type RouteNode, type RouteOptions, routes, type RouteTree, type WebSocketRouteOptions, } from './lib/routes.js';
13
+ export { MemoryRateLimitStore, RATE_LIMIT_STORE, rateLimit, type RateLimitHit, type RateLimitOptions, type RateLimitStore, } from './lib/rate-limit.js';
14
+ export { type SecurityHeaderOptions, securityHeaders, } from './lib/security-headers.js';
15
+ export { HTTP_MIDDLEWARE, HTTP_OPTIONS, type HttpOptions, HttpServer, provideHttp, provideHttpMiddleware, } from './lib/server.js';
16
+ export { nodeTransport } from './lib/transports/node.js';
17
+ export type { ListeningServer, RequestHandler, Transport, TransportOptions, } from './lib/transports/transport.js';
18
+ export { uwsTransport } from './lib/transports/uws.js';
19
+ export type { TransportSocket, WebSocket, WebSocketHandlers, } from './lib/websocket.js';
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EACL,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,OAAO,EACP,KAAK,SAAS,GACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,aAAa,EACb,SAAS,EACT,WAAW,EACX,YAAY,GACb,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,KAAK,YAAY,EACjB,gBAAgB,EAChB,KAAK,SAAS,EACd,SAAS,EACT,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,KAAK,kBAAkB,EACvB,UAAU,EACV,KAAK,QAAQ,GACd,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,KAAK,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAE,KAAK,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,EACL,UAAU,EACV,QAAQ,EACR,SAAS,EACT,SAAS,EACT,KAAK,gBAAgB,EACrB,QAAQ,EACR,OAAO,EACP,eAAe,EACf,YAAY,EACZ,aAAa,GACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,QAAQ,EACR,OAAO,EACP,SAAS,EACT,EAAE,EACF,QAAQ,EACR,KAAK,EACL,KAAK,GACN,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAClE,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,YAAY,EACZ,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,MAAM,EACN,KAAK,SAAS,EACd,KAAK,qBAAqB,GAC3B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,SAAS,EACT,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,cAAc,GACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,KAAK,qBAAqB,EAC1B,eAAe,GAChB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,eAAe,EACf,YAAY,EACZ,KAAK,WAAW,EAChB,UAAU,EACV,WAAW,EACX,qBAAqB,GACtB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,YAAY,EACV,eAAe,EACf,cAAc,EACd,SAAS,EACT,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,YAAY,EACV,eAAe,EACf,SAAS,EACT,iBAAiB,GAClB,MAAM,oBAAoB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export { apiKeyAuth } from './lib/auth/api-key.js';
2
+ export { jwtAuth, } from './lib/auth/jwt.js';
3
+ export { authenticated, authorize, provideAuth, requireRoles, } from './lib/auth/provide-auth.js';
4
+ export { AUTH_STRATEGIES, CurrentPrincipal, principal, requirePrincipal, } from './lib/auth/strategy.js';
5
+ export { Compressor, } from './lib/compression.js';
6
+ export { HttpConfig } from './lib/config.js';
7
+ export { CorsPolicy } from './lib/cors.js';
8
+ export { badRequest, conflict, forbidden, HttpError, notFound, problem, tooManyRequests, unauthorized, unprocessable, } from './lib/errors.js';
9
+ export { accepted, created, noContent, ok, redirect, Reply, reply, } from './lib/reply.js';
10
+ export { HttpRequest } from './lib/request.js';
11
+ export { RouteBuilder, routes, } from './lib/routes.js';
12
+ export { MemoryRateLimitStore, RATE_LIMIT_STORE, rateLimit, } from './lib/rate-limit.js';
13
+ export { securityHeaders, } from './lib/security-headers.js';
14
+ export { HTTP_MIDDLEWARE, HTTP_OPTIONS, HttpServer, provideHttp, provideHttpMiddleware, } from './lib/server.js';
15
+ export { nodeTransport } from './lib/transports/node.js';
16
+ export { uwsTransport } from './lib/transports/uws.js';
@@ -0,0 +1,17 @@
1
+ import type { AuthStrategy, Principal } from './strategy.js';
2
+ export interface ApiKeyAuthOptions {
3
+ /** Strategy name, used in OpenAPI. Defaults to `apiKey`. */
4
+ name?: string;
5
+ /** Header carrying the key. Defaults to `x-api-key`. */
6
+ header?: string;
7
+ /**
8
+ * Valid keys by principal id, or a function looking a key up (for keys in
9
+ * a database). Keys in a record are compared in constant time.
10
+ */
11
+ keys: Readonly<Record<string, string>> | ((key: string) => Principal | undefined | Promise<Principal | undefined>);
12
+ /** Roles per principal id, for keys given as a record. */
13
+ roles?: Readonly<Record<string, readonly string[]>>;
14
+ }
15
+ /** Authenticates requests by an API key in a header. */
16
+ export declare function apiKeyAuth(options: ApiKeyAuthOptions): AuthStrategy;
17
+ //# sourceMappingURL=api-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-key.d.ts","sourceRoot":"","sources":["../../../src/lib/auth/api-key.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE7D,MAAM,WAAW,iBAAiB;IAChC,4DAA4D;IAC5D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wDAAwD;IACxD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,IAAI,EACA,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAChC,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,SAAS,GAAG,SAAS,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC,CAAC;IAC9E,0DAA0D;IAC1D,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;CACrD;AAED,wDAAwD;AACxD,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,YAAY,CA8CnE"}
@@ -0,0 +1,48 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { unauthorized } from '../errors.js';
3
+ /** Authenticates requests by an API key in a header. */
4
+ export function apiKeyAuth(options) {
5
+ const name = options.name ?? 'apiKey';
6
+ const header = (options.header ?? 'x-api-key').toLowerCase();
7
+ const { keys } = options;
8
+ // Compare digests so neither the key nor its length leaks through timing.
9
+ const digests = typeof keys === 'function'
10
+ ? []
11
+ : Object.entries(keys).map(([id, key]) => ({ id, digest: digest(key) }));
12
+ return {
13
+ name,
14
+ scheme: { type: 'apiKey', in: 'header', name: header },
15
+ async authenticate(request) {
16
+ const key = request.headers[header];
17
+ if (key === undefined || key === '') {
18
+ return undefined;
19
+ }
20
+ if (typeof keys === 'function') {
21
+ const found = await keys(key);
22
+ if (found === undefined) {
23
+ throw unauthorized('The API key is not valid.');
24
+ }
25
+ return found;
26
+ }
27
+ const given = digest(key);
28
+ let match;
29
+ for (const entry of digests) {
30
+ if (timingSafeEqual(entry.digest, given)) {
31
+ match ??= entry.id;
32
+ }
33
+ }
34
+ if (match === undefined) {
35
+ throw unauthorized('The API key is not valid.');
36
+ }
37
+ return {
38
+ id: match,
39
+ strategy: name,
40
+ roles: options.roles?.[match] ?? [],
41
+ claims: {},
42
+ };
43
+ },
44
+ };
45
+ }
46
+ function digest(value) {
47
+ return createHash('sha256').update(value).digest();
48
+ }
@@ -0,0 +1,33 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ import type { AuthStrategy, Principal } from './strategy.js';
3
+ /** A JSON Web Key, as found in JWKS documents. */
4
+ export type JsonWebKey = Readonly<Record<string, unknown>>;
5
+ type Algorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512' | 'PS256' | 'PS384' | 'PS512' | 'ES256' | 'ES384' | 'ES512' | 'EdDSA';
6
+ export type JwtClaims = Readonly<Record<string, unknown>>;
7
+ export interface JwtAuthOptions {
8
+ /** Strategy name, used in OpenAPI. Defaults to `bearer`. */
9
+ name?: string;
10
+ /** Shared secret for HS256/384/512. */
11
+ secret?: string | Uint8Array;
12
+ /** Public key (PEM, JWK or KeyObject) for RS*, PS*, ES* or EdDSA. */
13
+ publicKey?: string | JsonWebKey | KeyObject;
14
+ /** A JWKS endpoint (as published by OIDC providers); keys are cached and refreshed on rotation. */
15
+ jwksUrl?: string;
16
+ /** Accepted algorithms. Defaults to HS256 with a secret, otherwise RS256, PS256, ES256 and EdDSA. */
17
+ algorithms?: readonly Algorithm[];
18
+ /** Required `iss`, one of these values. */
19
+ issuer?: string | readonly string[];
20
+ /** Required `aud`, at least one of these values. */
21
+ audience?: string | readonly string[];
22
+ /** Allowed clock skew for `exp`/`nbf`, in milliseconds. Defaults to 5 seconds. */
23
+ clockTolerance?: number;
24
+ /**
25
+ * Turns verified claims into a principal. Defaults to `sub` as the id and
26
+ * roles from a `roles` array claim or a space-separated `scope`.
27
+ */
28
+ principal?: (claims: JwtClaims) => Omit<Principal, 'strategy'>;
29
+ }
30
+ /** Authenticates `Authorization: Bearer <JWT>` requests. */
31
+ export declare function jwtAuth(options: JwtAuthOptions): AuthStrategy;
32
+ export {};
33
+ //# sourceMappingURL=jwt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../../src/lib/auth/jwt.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,SAAS,EAGf,MAAM,aAAa,CAAC;AAGrB,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE7D,kDAAkD;AAClD,MAAM,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAE3D,KAAK,SAAS,GACV,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,GACP,OAAO,CAAC;AAsBZ,MAAM,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAE1D,MAAM,WAAW,cAAc;IAC7B,4DAA4D;IAC5D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uCAAuC;IACvC,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IAC7B,qEAAqE;IACrE,SAAS,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;IAC5C,mGAAmG;IACnG,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qGAAqG;IACrG,UAAU,CAAC,EAAE,SAAS,SAAS,EAAE,CAAC;IAClC,2CAA2C;IAC3C,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IACpC,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IACtC,kFAAkF;IAClF,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;CAChE;AAED,4DAA4D;AAC5D,wBAAgB,OAAO,CAAC,OAAO,EAAE,cAAc,GAAG,YAAY,CAwI7D"}