@cslug/http 0.7.1 → 0.9.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/docs/api.md CHANGED
@@ -96,7 +96,7 @@ Config `http`: `port`, `host`, `shutdownTimeout`, `bodyLimit`, `trustedProxies`,
96
96
 
97
97
  GET/HEAD requests that match no route are served from `public/` (`config('http.public')`: a folder name, or
98
98
  `false`). Dotfiles and paths escaping the folder are refused. Hashed build files (`name-1a2b3c4d.js`) get
99
- `Cache-Control: public, max-age=31536000, immutable`; others revalidate with `Last-Modified` / 304.
99
+ `Cache-Control: public, max-age=31536000, immutable`; others revalidate with an `ETag` (size and exact mtime; it wins over `If-Modified-Since`) or `Last-Modified`, answered 304 when unchanged.
100
100
 
101
101
  ## Commands
102
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/http",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "Router, middleware, HttpContext, sessions, CSRF, error rendering on Bun.serve.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,7 +29,7 @@
29
29
  "bun": ">=1.3.14"
30
30
  },
31
31
  "peerDependencies": {
32
- "@cslug/core": "0.7.1",
33
- "@cslug/validation": "0.7.1"
32
+ "@cslug/core": "0.9.0",
33
+ "@cslug/validation": "0.9.0"
34
34
  }
35
35
  }
package/src/kernel.ts CHANGED
@@ -5,9 +5,11 @@ import {
5
5
  HEALTH_CHECKS,
6
6
  type HealthCheck,
7
7
  Logger,
8
+ Metrics,
8
9
  NotFoundError,
9
10
  runInContext,
10
11
  type Token,
12
+ Tracer,
11
13
  ValidationError,
12
14
  } from '@cslug/core'
13
15
  import { type HttpContext, HttpRequest, ResponseBuilder } from './context'
@@ -140,58 +142,87 @@ export class HttpKernel {
140
142
 
141
143
  let status = 500
142
144
  let routeName: string | undefined
145
+ let routePath: string | undefined
146
+ let traceId: string | undefined
147
+ const tracer = this.app.resolve(Tracer)
143
148
  try {
144
149
  return await runInContext(
145
150
  { ...(currentContext() ?? {}), app: this.app, scope, requestId, locale: defaultLocale, http: ctx },
146
- async () => {
147
- const run = async (): Promise<Response> => {
148
- // HTML forms can only send GET/POST: `<input name="_method" value="PUT">` spoofs the others
149
- let method = request.method
150
- if (method === 'POST' && req.isForm) {
151
- const spoofed = (await req.body())._method
152
- if (typeof spoofed === 'string' && ['PUT', 'PATCH', 'DELETE'].includes(spoofed.toUpperCase()))
153
- method = spoofed.toUpperCase()
154
- }
155
- const { route, params, allowed } = this.match(method, host, url.pathname)
156
- if (!route) {
157
- if (this.publicDir && (request.method === 'GET' || request.method === 'HEAD')) {
158
- const file = serveStatic(this.publicDir, url.pathname, request)
159
- if (file) return file
151
+ () =>
152
+ // a server span per request, continuing the caller's trace (W3C `traceparent`)
153
+ tracer.span(
154
+ request.method,
155
+ {
156
+ kind: 'server',
157
+ parent: request.headers.get('traceparent') ?? undefined,
158
+ attributes: tracer.enabled
159
+ ? { 'http.request.method': request.method, 'url.path': url.pathname, 'server.address': host }
160
+ : undefined,
161
+ },
162
+ async (span) => {
163
+ traceId = span.traceId || undefined
164
+ const run = async (): Promise<Response> => {
165
+ // HTML forms can only send GET/POST: `<input name="_method" value="PUT">` spoofs the others
166
+ let method = request.method
167
+ if (method === 'POST' && req.isForm) {
168
+ const spoofed = (await req.body())._method
169
+ if (typeof spoofed === 'string' && ['PUT', 'PATCH', 'DELETE'].includes(spoofed.toUpperCase()))
170
+ method = spoofed.toUpperCase()
171
+ }
172
+ const { route, params, allowed } = this.match(method, host, url.pathname)
173
+ if (!route) {
174
+ if (this.publicDir && (request.method === 'GET' || request.method === 'HEAD')) {
175
+ const file = serveStatic(this.publicDir, url.pathname, request)
176
+ if (file) return file
177
+ }
178
+ if (allowed.size) {
179
+ const allow = [...allowed, ...(allowed.has('GET') ? ['HEAD'] : [])].join(', ')
180
+ return json(
181
+ { title: 'Method Not Allowed', status: 405, code: 'http.method_not_allowed', requestId },
182
+ { status: 405, headers: { allow } },
183
+ )
184
+ }
185
+ throw new NotFoundError('route')
186
+ }
187
+ routeName = route.name
188
+ routePath = route.path
189
+ span.updateName(`${method} ${route.path}`)
190
+ Object.assign(ctx.params, params)
191
+ Object.assign(ctx, { routeName: route.name })
192
+ return this.pipeline(ctx, route.middleware, () => this.callAction(ctx, route))
160
193
  }
161
- if (allowed.size) {
162
- const allow = [...allowed, ...(allowed.has('GET') ? ['HEAD'] : [])].join(', ')
163
- return json(
164
- { title: 'Method Not Allowed', status: 405, code: 'http.method_not_allowed', requestId },
165
- { status: 405, headers: { allow } },
166
- )
194
+ let res: Response
195
+ try {
196
+ res = await this.pipeline(ctx, this.global, run)
197
+ } catch (error) {
198
+ res = await this.errors.handle(error, ctx)
199
+ if (res.status >= 500) span.recordError(error)
167
200
  }
168
- throw new NotFoundError('route')
169
- }
170
- routeName = route.name
171
- Object.assign(ctx.params, params)
172
- Object.assign(ctx, { routeName: route.name })
173
- return this.pipeline(ctx, route.middleware, () => this.callAction(ctx, route))
174
- }
175
- let res: Response
176
- try {
177
- res = await this.pipeline(ctx, this.global, run)
178
- } catch (error) {
179
- res = await this.errors.handle(error, ctx)
180
- }
181
- res = this.finalize(res, ctx, request.method)
182
- status = res.status
183
- return res
184
- },
201
+ res = this.finalize(res, ctx, request.method)
202
+ status = res.status
203
+ span.setAttributes({ 'http.response.status_code': status, 'http.route': routePath })
204
+ return res
205
+ },
206
+ ),
185
207
  )
186
208
  } finally {
187
209
  await scope.dispose()
210
+ const ms = performance.now() - started
211
+ const metrics = this.app.resolve(Metrics)
212
+ if (metrics.enabled)
213
+ metrics.record('http.server.request.duration', ms / 1000, {
214
+ 'http.request.method': request.method,
215
+ 'http.route': routePath,
216
+ 'http.response.status_code': status,
217
+ })
188
218
  this.log.info('request', {
189
219
  method: request.method,
190
220
  path: url.pathname,
191
221
  status,
192
- ms: Math.round((performance.now() - started) * 10) / 10,
222
+ ms: Math.round(ms * 10) / 10,
193
223
  route: routeName,
194
224
  requestId,
225
+ ...(traceId ? { traceId } : {}),
195
226
  })
196
227
  }
197
228
  }
@@ -1,5 +1,5 @@
1
1
  /** Built-in middleware: `import { securityHeaders, bodyLimit, … } from '@cslug/http/middleware'`. */
2
- import { CslugError, ForbiddenError, parseDuration } from '@cslug/core'
2
+ import { CslugError, Encrypter, ForbiddenError, parseDuration } from '@cslug/core'
3
3
  import type { MiddlewareFn } from '../router'
4
4
  import { verifySignedUrl } from '../url'
5
5
 
@@ -79,8 +79,7 @@ export const timeout =
79
79
 
80
80
  /** 403 unless the URL was made by `route(name, params, { signed: true })` and has not expired. */
81
81
  export const signed = (): MiddlewareFn => async (ctx, next) => {
82
- const key = ctx.app.config<string | undefined>('app.key')
83
- if (!key || !verifySignedUrl(ctx.request.url.toString(), key))
82
+ if (!verifySignedUrl(ctx.request.url.toString(), ctx.app.resolve(Encrypter)))
84
83
  throw new ForbiddenError('http.invalid_signature', 'This link is invalid or has expired.')
85
84
  return next()
86
85
  }
package/src/static.ts CHANGED
@@ -6,7 +6,9 @@ const HASHED = /-[a-z0-9]{8}\.[a-z0-9]+$/
6
6
 
7
7
  /**
8
8
  * A file from `public/` for a GET/HEAD that matched no route, or undefined. Dotfiles and paths escaping the
9
- * folder are refused. `If-Modified-Since` gets a 304.
9
+ * folder are refused. A matching `If-None-Match` (ETag from the size and exact mtime) or, without one,
10
+ * `If-Modified-Since` gets a 304. The ETag matters for files rewritten within a second (development rebuilds),
11
+ * which `Last-Modified` cannot tell apart.
10
12
  */
11
13
  export function serveStatic(publicDir: string, pathname: string, request: Request): Response | undefined {
12
14
  let decoded: string
@@ -21,12 +23,18 @@ export function serveStatic(publicDir: string, pathname: string, request: Reques
21
23
  const stat = statSync(file)
22
24
  if (!stat.isFile()) return undefined
23
25
  const modified = new Date(Math.floor(stat.mtimeMs / 1000) * 1000)
26
+ const etag = `W/"${stat.size.toString(36)}-${Math.round(stat.mtimeMs * 1000).toString(36)}"`
24
27
  const headers = new Headers({
28
+ etag,
25
29
  'last-modified': modified.toUTCString(),
26
30
  'cache-control': HASHED.test(file) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
27
31
  })
32
+ const match = request.headers.get('if-none-match')
28
33
  const since = request.headers.get('if-modified-since')
29
- if (since && new Date(since).getTime() >= modified.getTime()) return new Response(null, { status: 304, headers })
34
+ const fresh = match
35
+ ? match.split(',').some((t) => t.trim() === etag || t.trim() === '*')
36
+ : !!since && new Date(since).getTime() >= modified.getTime()
37
+ if (fresh) return new Response(null, { status: 304, headers })
30
38
  const body = Bun.file(file)
31
39
  headers.set('content-type', body.type)
32
40
  headers.set('content-length', String(stat.size))
package/src/url.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { createHmac, timingSafeEqual } from 'node:crypto'
2
- import { CslugError, currentApp, parseDuration } from '@cslug/core'
1
+ import { CslugError, currentApp, Encrypter, parseDuration } from '@cslug/core'
3
2
  import { Router } from './router'
4
3
 
5
4
  export type UrlOptions = {
@@ -19,13 +18,16 @@ const fill = (pattern: string, params: Record<string, unknown>, name: string, us
19
18
  return encodeURIComponent(String(value))
20
19
  })
21
20
 
22
- const signature = (key: string, url: string) => createHmac('sha256', key).update(url).digest('base64url')
21
+ /** The app's `Encrypter` (current and previous keys), or one for a plain key. */
22
+ const signer = (key: string | Encrypter | undefined): Encrypter | undefined =>
23
+ typeof key === 'string' ? (key ? new Encrypter(key) : undefined) : key?.configured ? key : undefined
23
24
 
24
25
  /** Build a URL from a route name. Without `absolute`, a path is returned unless the route is on another domain. */
25
26
  export function urlFor(
26
27
  router: Router,
27
28
  appUrl: string | undefined,
28
- key: string | undefined,
29
+ /** `APP_KEY`, or the app's `Encrypter` (signed with `APP_KEY`, verified with previous keys too). */
30
+ key: string | Encrypter | undefined,
29
31
  name: string,
30
32
  params: Record<string, unknown> = {},
31
33
  options: UrlOptions = {},
@@ -48,27 +50,27 @@ export function urlFor(
48
50
  origin = `${base.protocol}//${host ?? base.host}${host && base.port ? `:${base.port}` : ''}`
49
51
  }
50
52
  if (options.signed) {
51
- if (!key) throw new CslugError('http.no_app_key', 'Signed URLs need APP_KEY (config app.key)')
53
+ const keys = signer(key)
54
+ if (!keys) throw new CslugError('http.no_app_key', 'Signed URLs need APP_KEY (config app.key)')
52
55
  if (options.expiresIn !== undefined)
53
56
  query.set('expires', String(Math.floor((Date.now() + parseDuration(options.expiresIn)) / 1000)))
54
57
  query.sort()
55
58
  const unsigned = `${origin}${path}${query.size ? `?${query}` : ''}`
56
- query.set('signature', signature(key, unsigned))
59
+ query.set('signature', keys.sign(unsigned))
57
60
  }
58
61
  return `${origin}${path}${query.size ? `?${query}` : ''}`
59
62
  }
60
63
 
61
- /** Is a request URL correctly signed (and not expired)? */
62
- export function verifySignedUrl(url: string, key: string, now = Date.now()): boolean {
64
+ /** Is a request URL correctly signed (with `APP_KEY` or a previous key) and not expired? */
65
+ export function verifySignedUrl(url: string, key: string | Encrypter | undefined, now = Date.now()): boolean {
66
+ const keys = signer(key)
67
+ if (!keys) return false
63
68
  const u = new URL(url)
64
69
  const given = u.searchParams.get('signature')
65
70
  if (!given) return false
66
71
  u.searchParams.delete('signature')
67
72
  u.searchParams.sort()
68
- const expected = signature(key, `${u.origin}${u.pathname}${u.searchParams.size ? `?${u.searchParams}` : ''}`)
69
- const a = Buffer.from(given)
70
- const b = Buffer.from(expected)
71
- if (a.length !== b.length || !timingSafeEqual(a, b)) return false
73
+ if (!keys.verify(`${u.origin}${u.pathname}${u.searchParams.size ? `?${u.searchParams}` : ''}`, given)) return false
72
74
  const expires = u.searchParams.get('expires')
73
75
  return !expires || Number(expires) * 1000 > now
74
76
  }
@@ -79,7 +81,7 @@ export function route(name: string, params: Record<string, unknown> = {}, option
79
81
  return urlFor(
80
82
  app.resolve(Router),
81
83
  app.config<string | undefined>('app.url'),
82
- app.config<string | undefined>('app.key'),
84
+ app.resolve(Encrypter),
83
85
  name,
84
86
  params,
85
87
  options,