@cslug/http 0.8.0 → 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 +1 -1
- package/package.json +3 -3
- package/src/middleware/index.ts +2 -3
- package/src/static.ts +10 -2
- package/src/url.ts +15 -13
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 `
|
|
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.
|
|
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.
|
|
33
|
-
"@cslug/validation": "0.
|
|
32
|
+
"@cslug/core": "0.9.0",
|
|
33
|
+
"@cslug/validation": "0.9.0"
|
|
34
34
|
}
|
|
35
35
|
}
|
package/src/middleware/index.ts
CHANGED
|
@@ -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
|
-
|
|
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-
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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',
|
|
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
|
-
|
|
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.
|
|
84
|
+
app.resolve(Encrypter),
|
|
83
85
|
name,
|
|
84
86
|
params,
|
|
85
87
|
options,
|