@cslug/http 0.0.0-stage → 0.2.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/README.md +6 -2
- package/docs/README.md +24 -0
- package/docs/api.md +100 -0
- package/package.json +33 -4
- package/src/body.ts +72 -0
- package/src/commands.ts +132 -0
- package/src/context.ts +232 -0
- package/src/errors.ts +130 -0
- package/src/index.ts +41 -0
- package/src/kernel.ts +302 -0
- package/src/middleware/index.ts +121 -0
- package/src/middleware/web.ts +140 -0
- package/src/provider.ts +104 -0
- package/src/responses.ts +113 -0
- package/src/router.ts +202 -0
- package/src/session.ts +163 -0
- package/src/static.ts +34 -0
- package/src/url.ts +87 -0
- package/stubs/controller.resource.stub +37 -0
- package/stubs/controller.stub +9 -0
- package/stubs/middleware.stub +9 -0
- package/stubs/validator.stub +7 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { AppError, type Application, Logger, t, validationTranslator } from '@cslug/core'
|
|
2
|
+
import { ValidationError } from '@cslug/validation'
|
|
3
|
+
import type { HttpContext } from './context'
|
|
4
|
+
import { json } from './responses'
|
|
5
|
+
|
|
6
|
+
/** A renderer may return a Response for an error, or undefined to let the next one try. */
|
|
7
|
+
export type ErrorRenderer = (error: unknown, ctx: HttpContext) => Response | undefined | Promise<Response | undefined>
|
|
8
|
+
export type ErrorReporter = (error: unknown, ctx: HttpContext | undefined) => void
|
|
9
|
+
|
|
10
|
+
const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Turns errors into responses. Packages and apps add renderers in front (e.g. sessions: redirect back with
|
|
14
|
+
* errors for HTML forms) and reporters (Sentry…). Default: RFC 9457 problem+json for API clients, a minimal HTML
|
|
15
|
+
* page for browsers. Unknown errors are 500s with the request id; their details never leave the server in production.
|
|
16
|
+
*/
|
|
17
|
+
export class ExceptionHandler {
|
|
18
|
+
readonly renderers: ErrorRenderer[] = []
|
|
19
|
+
readonly reporters: ErrorReporter[] = []
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly app: Application,
|
|
23
|
+
private readonly log: Logger = Logger.null(),
|
|
24
|
+
) {}
|
|
25
|
+
|
|
26
|
+
/** Add a renderer that runs before the defaults. */
|
|
27
|
+
render(renderer: ErrorRenderer): this {
|
|
28
|
+
this.renderers.unshift(renderer)
|
|
29
|
+
return this
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Add an error reporter (called for 5xx errors). */
|
|
33
|
+
report(reporter: ErrorReporter): this {
|
|
34
|
+
this.reporters.push(reporter)
|
|
35
|
+
return this
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
status(error: unknown): number {
|
|
39
|
+
if (error instanceof ValidationError) return 422
|
|
40
|
+
if (error instanceof AppError) return error.status
|
|
41
|
+
const s = (error as { status?: unknown })?.status
|
|
42
|
+
return typeof s === 'number' && s >= 400 && s < 600 ? s : 500
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async handle(error: unknown, ctx: HttpContext): Promise<Response> {
|
|
46
|
+
const status = this.status(error)
|
|
47
|
+
if (status >= 500) {
|
|
48
|
+
this.log.error('request failed', { error, requestId: ctx.requestId, path: ctx.request.path })
|
|
49
|
+
for (const r of this.reporters) {
|
|
50
|
+
try {
|
|
51
|
+
r(error, ctx)
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
for (const renderer of this.renderers) {
|
|
56
|
+
const response = await renderer(error, ctx)
|
|
57
|
+
if (response) return response
|
|
58
|
+
}
|
|
59
|
+
const back = this.formRedirect(error, ctx)
|
|
60
|
+
if (back) return back
|
|
61
|
+
return this.defaultResponse(error, ctx, status)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A failed HTML form post goes back to the form with the errors and the input flashed, so the page can show
|
|
66
|
+
* them. JSON clients, GET requests and routes without a session get problem+json instead.
|
|
67
|
+
*/
|
|
68
|
+
protected formRedirect(error: unknown, ctx: HttpContext): Response | undefined {
|
|
69
|
+
if (!(error instanceof ValidationError) || ctx.request.wantsJson() || ctx.request.method === 'GET') return undefined
|
|
70
|
+
if (!ctx.session.available) return undefined
|
|
71
|
+
ctx.session.flash('_errors', error.messages(validationTranslator(ctx.locale)))
|
|
72
|
+
ctx.session.flash('_old', this.oldInput(ctx))
|
|
73
|
+
return new Response(null, { status: 303, headers: { location: ctx.request.header('referer') ?? '/' } })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The submitted input to show again: without passwords, tokens and files. */
|
|
77
|
+
protected oldInput(ctx: HttpContext): Record<string, unknown> {
|
|
78
|
+
const body = ctx.request.parsedBody ?? {}
|
|
79
|
+
return Object.fromEntries(
|
|
80
|
+
Object.entries(body).filter(([k, v]) => !/password|token|^_/.test(k.toLowerCase()) && !(v instanceof Blob)),
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
protected problem(error: unknown, ctx: HttpContext, status: number) {
|
|
85
|
+
const production = this.app.config('app.env') === 'production'
|
|
86
|
+
const code =
|
|
87
|
+
error instanceof ValidationError
|
|
88
|
+
? 'validation.failed'
|
|
89
|
+
: status >= 500
|
|
90
|
+
? 'server.error'
|
|
91
|
+
: ((error as { code?: string }).code ?? 'http.error')
|
|
92
|
+
const fallback =
|
|
93
|
+
error instanceof ValidationError
|
|
94
|
+
? 'The given data was invalid.'
|
|
95
|
+
: status >= 500
|
|
96
|
+
? 'Something went wrong on our side.'
|
|
97
|
+
: ((error as Error).message ?? 'Error')
|
|
98
|
+
const translated = t(code, (error as AppError).params ?? {})
|
|
99
|
+
const title = translated !== code ? translated : fallback
|
|
100
|
+
const base =
|
|
101
|
+
this.app.config<string | undefined>('http.problemBase') ??
|
|
102
|
+
`${this.app.config<string | undefined>('app.url') ?? ''}/errors`
|
|
103
|
+
return {
|
|
104
|
+
type: `${base}/${code}`,
|
|
105
|
+
title,
|
|
106
|
+
status,
|
|
107
|
+
code,
|
|
108
|
+
...(error instanceof ValidationError ? { errors: error.messages(validationTranslator(ctx.locale)) } : {}),
|
|
109
|
+
...((error as AppError).params && status < 500 ? { params: (error as AppError).params } : {}),
|
|
110
|
+
requestId: ctx.requestId,
|
|
111
|
+
...(status >= 500 && !production
|
|
112
|
+
? { detail: (error as Error)?.message, stack: (error as Error)?.stack?.split('\n').slice(0, 8) }
|
|
113
|
+
: {}),
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
protected defaultResponse(error: unknown, ctx: HttpContext, status: number): Response {
|
|
118
|
+
const body = this.problem(error, ctx, status)
|
|
119
|
+
const headers = new Headers()
|
|
120
|
+
const retry = (error as { retryAfter?: number }).retryAfter
|
|
121
|
+
if (retry) headers.set('retry-after', String(retry))
|
|
122
|
+
if (ctx.request.wantsJson() || !(ctx.request.header('accept') ?? '').includes('text/html')) {
|
|
123
|
+
headers.set('content-type', 'application/problem+json; charset=utf-8')
|
|
124
|
+
return json(body, { status, headers })
|
|
125
|
+
}
|
|
126
|
+
headers.set('content-type', 'text/html; charset=utf-8')
|
|
127
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><title>${status} ${escapeHtml(body.title)}</title></head><body><h1>${status}</h1><p>${escapeHtml(body.title)}</p><p><small>Request ${escapeHtml(ctx.requestId)}</small></p></body></html>`
|
|
128
|
+
return new Response(html, { status, headers })
|
|
129
|
+
}
|
|
130
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/http: router (groups, names, domains, resources), HttpContext and request validation, responses,
|
|
3
|
+
* error rendering (RFC 9457), the HTTP kernel on Bun.serve, health endpoints,
|
|
4
|
+
* sessions, CSRF, flash and old input,
|
|
5
|
+
throttling and locale detection. Middleware: `@cslug/http/middleware`.
|
|
6
|
+
*/
|
|
7
|
+
export { coerceForm, nestKeys } from './body'
|
|
8
|
+
export { httpCommands, MakeControllerCommand, RoutesCommand, ServeCommand } from './commands'
|
|
9
|
+
export { type HttpContext, HttpRequest, ResponseBuilder, type Validated } from './context'
|
|
10
|
+
export { type ErrorRenderer, type ErrorReporter, ExceptionHandler } from './errors'
|
|
11
|
+
export { HttpKernel, toResponse } from './kernel'
|
|
12
|
+
export { API_MIDDLEWARE, type HttpConfig, HttpProvider, WEB_MIDDLEWARE } from './provider'
|
|
13
|
+
export {
|
|
14
|
+
accepted,
|
|
15
|
+
created,
|
|
16
|
+
download,
|
|
17
|
+
isResponsable,
|
|
18
|
+
json,
|
|
19
|
+
noContent,
|
|
20
|
+
Redirect,
|
|
21
|
+
type Responsable,
|
|
22
|
+
redirect,
|
|
23
|
+
sse,
|
|
24
|
+
stream,
|
|
25
|
+
} from './responses'
|
|
26
|
+
export {
|
|
27
|
+
type Action,
|
|
28
|
+
defineRoutes,
|
|
29
|
+
type GroupOptions,
|
|
30
|
+
type Method,
|
|
31
|
+
type Middleware,
|
|
32
|
+
type MiddlewareClass,
|
|
33
|
+
type MiddlewareFn,
|
|
34
|
+
type Next,
|
|
35
|
+
RouteBuilder,
|
|
36
|
+
type RouteDef,
|
|
37
|
+
RouteRegistrar,
|
|
38
|
+
Router,
|
|
39
|
+
} from './router'
|
|
40
|
+
export { MissingSession, Session } from './session'
|
|
41
|
+
export { route, type UrlOptions, urlFor, verifySignedUrl } from './url'
|
package/src/kernel.ts
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Application,
|
|
3
|
+
currentContext,
|
|
4
|
+
HEALTH_CHECKS,
|
|
5
|
+
type HealthCheck,
|
|
6
|
+
Logger,
|
|
7
|
+
NotFoundError,
|
|
8
|
+
runInContext,
|
|
9
|
+
type Token,
|
|
10
|
+
} from '@cslug/core'
|
|
11
|
+
import { type HttpContext, HttpRequest, ResponseBuilder } from './context'
|
|
12
|
+
import type { ExceptionHandler } from './errors'
|
|
13
|
+
import { isResponsable, json } from './responses'
|
|
14
|
+
import type { Middleware, MiddlewareFn, Next, RouteDef, Router } from './router'
|
|
15
|
+
import { MissingSession } from './session'
|
|
16
|
+
import { serveStatic } from './static'
|
|
17
|
+
|
|
18
|
+
type Compiled = { route: RouteDef; path: RegExp; domain?: RegExp; score: number[] }
|
|
19
|
+
|
|
20
|
+
const toRegExp = (pattern: string, separator: '/' | '.') =>
|
|
21
|
+
new RegExp(
|
|
22
|
+
`^${pattern
|
|
23
|
+
.split(separator)
|
|
24
|
+
.map((seg) =>
|
|
25
|
+
seg.startsWith(':')
|
|
26
|
+
? `(?<${seg.slice(1)}>[^${separator === '/' ? '/' : '.'}]+)`
|
|
27
|
+
: seg === '*'
|
|
28
|
+
? '(?<wildcard>.*)'
|
|
29
|
+
: seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
|
|
30
|
+
)
|
|
31
|
+
.join(separator === '/' ? '/' : '\\.')}$`,
|
|
32
|
+
'i',
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
/** Static segments beat parameters, parameters beat wildcards; routes with a domain come first. */
|
|
36
|
+
const scoreOf = (r: RouteDef) => [
|
|
37
|
+
r.domain ? 1 : 0,
|
|
38
|
+
...r.path.split('/').map((s) => (s === '*' ? 0 : s.startsWith(':') ? 1 : 2)),
|
|
39
|
+
]
|
|
40
|
+
const compareScores = (a: number[], b: number[]) => {
|
|
41
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
42
|
+
const d = (b[i] ?? -1) - (a[i] ?? -1)
|
|
43
|
+
if (d) return d
|
|
44
|
+
}
|
|
45
|
+
return 0
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const decode = (v: string) => {
|
|
49
|
+
try {
|
|
50
|
+
return decodeURIComponent(v)
|
|
51
|
+
} catch {
|
|
52
|
+
return v
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Turns a `Request` into a `Response`: request id, context and scope, route matching (domain, path, method,
|
|
60
|
+
* constraints), middleware, the action, result → Response, errors → ExceptionHandler. `handle()` needs no port,
|
|
61
|
+
* which is how @cslug/testing calls it; `listen()` puts it behind `Bun.serve`.
|
|
62
|
+
*/
|
|
63
|
+
export class HttpKernel {
|
|
64
|
+
private compiled: Compiled[] = []
|
|
65
|
+
/** Middleware run for every request (before routing). */
|
|
66
|
+
readonly global: Middleware[] = []
|
|
67
|
+
private server?: ReturnType<typeof Bun.serve>
|
|
68
|
+
|
|
69
|
+
constructor(
|
|
70
|
+
readonly app: Application,
|
|
71
|
+
readonly router: Router,
|
|
72
|
+
private readonly errors: ExceptionHandler,
|
|
73
|
+
private readonly log: Logger = Logger.null(),
|
|
74
|
+
) {}
|
|
75
|
+
|
|
76
|
+
/** Serve files from this folder for GET/HEAD requests that match no route (`public/`; `http.public: false` turns it off). */
|
|
77
|
+
publicDir?: string
|
|
78
|
+
|
|
79
|
+
/** Compile the router's routes (called at boot; call again after adding routes). */
|
|
80
|
+
compile(): this {
|
|
81
|
+
this.router.validate()
|
|
82
|
+
this.compiled = this.router.routes
|
|
83
|
+
.map((route) => ({
|
|
84
|
+
route,
|
|
85
|
+
path: toRegExp(route.path === '/' ? '' : route.path, '/'),
|
|
86
|
+
domain: route.domain ? toRegExp(route.domain, '.') : undefined,
|
|
87
|
+
score: scoreOf(route),
|
|
88
|
+
}))
|
|
89
|
+
.sort((a, b) => compareScores(a.score, b.score))
|
|
90
|
+
return this
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Find the route for a method, host and path; `allowed` lists methods that exist for the path (for 405). */
|
|
94
|
+
match(method: string, host: string, path: string) {
|
|
95
|
+
const allowed = new Set<string>()
|
|
96
|
+
const normalized = path.length > 1 ? path.replace(/\/+$/, '') : path
|
|
97
|
+
for (const c of this.compiled) {
|
|
98
|
+
const d = c.domain ? c.domain.exec(host) : null
|
|
99
|
+
if (c.domain && !d) continue
|
|
100
|
+
const m = c.path.exec(normalized === '/' ? '' : normalized)
|
|
101
|
+
if (!m) continue
|
|
102
|
+
const params: Record<string, string> = {}
|
|
103
|
+
for (const [k, v] of Object.entries({ ...d?.groups, ...m.groups })) if (v !== undefined) params[k] = decode(v)
|
|
104
|
+
if (Object.entries(c.route.wheres).some(([k, re]) => params[k] === undefined || !re.test(params[k]))) continue
|
|
105
|
+
allowed.add(c.route.method)
|
|
106
|
+
if (c.route.method === method || (method === 'HEAD' && c.route.method === 'GET'))
|
|
107
|
+
return { route: c.route, params, allowed }
|
|
108
|
+
}
|
|
109
|
+
return { route: undefined, params: {}, allowed }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Handle one request (no network needed). */
|
|
113
|
+
async handle(request: Request, info: { ip?: string } = {}): Promise<Response> {
|
|
114
|
+
const started = performance.now()
|
|
115
|
+
const given = request.headers.get('x-request-id')
|
|
116
|
+
const requestId = given && REQUEST_ID.test(given) ? given : Bun.randomUUIDv7()
|
|
117
|
+
const scope = this.app.createScope()
|
|
118
|
+
const url = new URL(request.url)
|
|
119
|
+
const host = (request.headers.get('host') ?? url.host).replace(/:\d+$/, '').toLowerCase()
|
|
120
|
+
const ip = this.clientIp(request, info.ip)
|
|
121
|
+
const req = new HttpRequest(request, scope, ip)
|
|
122
|
+
const response = new ResponseBuilder()
|
|
123
|
+
const defaultLocale = this.app.config<string | undefined>('i18n.default') ?? 'en'
|
|
124
|
+
// packages add fields to HttpContext (`auth`, `user` from @cslug/auth) and set them in their middleware
|
|
125
|
+
const ctx = {
|
|
126
|
+
request: req,
|
|
127
|
+
params: {},
|
|
128
|
+
response,
|
|
129
|
+
app: this.app,
|
|
130
|
+
scope,
|
|
131
|
+
requestId,
|
|
132
|
+
signal: request.signal,
|
|
133
|
+
log: this.log.child({ requestId }),
|
|
134
|
+
locale: defaultLocale,
|
|
135
|
+
session: new MissingSession(),
|
|
136
|
+
resolve: <K extends Token>(token: K) => scope.resolve(token) as never,
|
|
137
|
+
} satisfies Partial<HttpContext> as unknown as HttpContext
|
|
138
|
+
|
|
139
|
+
let status = 500
|
|
140
|
+
let routeName: string | undefined
|
|
141
|
+
try {
|
|
142
|
+
return await runInContext(
|
|
143
|
+
{ ...(currentContext() ?? {}), app: this.app, scope, requestId, locale: defaultLocale, http: ctx },
|
|
144
|
+
async () => {
|
|
145
|
+
const run = async (): Promise<Response> => {
|
|
146
|
+
// HTML forms can only send GET/POST: `<input name="_method" value="PUT">` spoofs the others
|
|
147
|
+
let method = request.method
|
|
148
|
+
if (method === 'POST' && req.isForm) {
|
|
149
|
+
const spoofed = (await req.body())._method
|
|
150
|
+
if (typeof spoofed === 'string' && ['PUT', 'PATCH', 'DELETE'].includes(spoofed.toUpperCase()))
|
|
151
|
+
method = spoofed.toUpperCase()
|
|
152
|
+
}
|
|
153
|
+
const { route, params, allowed } = this.match(method, host, url.pathname)
|
|
154
|
+
if (!route) {
|
|
155
|
+
if (this.publicDir && (request.method === 'GET' || request.method === 'HEAD')) {
|
|
156
|
+
const file = serveStatic(this.publicDir, url.pathname, request)
|
|
157
|
+
if (file) return file
|
|
158
|
+
}
|
|
159
|
+
if (allowed.size) {
|
|
160
|
+
const allow = [...allowed, ...(allowed.has('GET') ? ['HEAD'] : [])].join(', ')
|
|
161
|
+
return json(
|
|
162
|
+
{ title: 'Method Not Allowed', status: 405, code: 'http.method_not_allowed', requestId },
|
|
163
|
+
{ status: 405, headers: { allow } },
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
throw new NotFoundError('route')
|
|
167
|
+
}
|
|
168
|
+
routeName = route.name
|
|
169
|
+
Object.assign(ctx.params, params)
|
|
170
|
+
Object.assign(ctx, { routeName: route.name })
|
|
171
|
+
return this.pipeline(ctx, route.middleware, () => this.callAction(ctx, route))
|
|
172
|
+
}
|
|
173
|
+
let res: Response
|
|
174
|
+
try {
|
|
175
|
+
res = await this.pipeline(ctx, this.global, run)
|
|
176
|
+
} catch (error) {
|
|
177
|
+
res = await this.errors.handle(error, ctx)
|
|
178
|
+
}
|
|
179
|
+
res = this.finalize(res, ctx, request.method)
|
|
180
|
+
status = res.status
|
|
181
|
+
return res
|
|
182
|
+
},
|
|
183
|
+
)
|
|
184
|
+
} finally {
|
|
185
|
+
await scope.dispose()
|
|
186
|
+
this.log.info('request', {
|
|
187
|
+
method: request.method,
|
|
188
|
+
path: url.pathname,
|
|
189
|
+
status,
|
|
190
|
+
ms: Math.round((performance.now() - started) * 10) / 10,
|
|
191
|
+
route: routeName,
|
|
192
|
+
requestId,
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
private finalize(res: Response, ctx: HttpContext, method: string): Response {
|
|
198
|
+
const headers = new Headers(res.headers)
|
|
199
|
+
ctx.response.headers.forEach((v, k) => {
|
|
200
|
+
if (k === 'set-cookie') headers.append(k, v)
|
|
201
|
+
else if (!headers.has(k)) headers.set(k, v)
|
|
202
|
+
})
|
|
203
|
+
headers.set('x-request-id', ctx.requestId)
|
|
204
|
+
const status = ctx.response.status ?? res.status
|
|
205
|
+
return new Response(method === 'HEAD' ? null : res.body, { status, statusText: res.statusText, headers })
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
private pipeline(ctx: HttpContext, middleware: Middleware[], last: Next): Promise<Response> {
|
|
209
|
+
const fns: MiddlewareFn[] = middleware.map((m) =>
|
|
210
|
+
isMiddlewareClass(m)
|
|
211
|
+
? (c, next) => (ctx.scope.resolve(m) as { handle: MiddlewareFn }).handle(c, next)
|
|
212
|
+
: (m as MiddlewareFn),
|
|
213
|
+
)
|
|
214
|
+
const dispatch = (i: number): Promise<Response> => {
|
|
215
|
+
const fn = fns[i]
|
|
216
|
+
return fn ? Promise.resolve(fn(ctx, () => dispatch(i + 1))) : last()
|
|
217
|
+
}
|
|
218
|
+
return dispatch(0)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private async callAction(ctx: HttpContext, route: RouteDef): Promise<Response> {
|
|
222
|
+
const action = route.action
|
|
223
|
+
let result: unknown
|
|
224
|
+
if (Array.isArray(action)) {
|
|
225
|
+
const [cls, method] = action as [new () => object, string]
|
|
226
|
+
const controller = ctx.scope.resolve(cls) as Record<string, unknown>
|
|
227
|
+
const fn = controller[method]
|
|
228
|
+
if (typeof fn !== 'function')
|
|
229
|
+
throw new Error(`${cls.name} has no method "${method}" (route ${route.method} ${route.path})`)
|
|
230
|
+
result = await (fn as (c: HttpContext) => unknown).call(controller, ctx)
|
|
231
|
+
} else if (isClass(action)) {
|
|
232
|
+
const controller = ctx.scope.resolve(action) as { handle(c: HttpContext): unknown }
|
|
233
|
+
result = await controller.handle(ctx)
|
|
234
|
+
} else result = await (action as (c: HttpContext) => unknown)(ctx)
|
|
235
|
+
return toResponse(result, ctx)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
private clientIp(request: Request, socketIp: string | undefined): string | undefined {
|
|
239
|
+
const trusted = this.app.config<string[] | undefined>('http.trustedProxies') ?? []
|
|
240
|
+
const loopback = socketIp === '127.0.0.1' || socketIp === '::1' || socketIp?.startsWith('::ffff:127.') === true
|
|
241
|
+
const isTrusted =
|
|
242
|
+
socketIp !== undefined && (trusted.includes(socketIp) || (trusted.includes('loopback') && loopback))
|
|
243
|
+
const forwarded = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
|
|
244
|
+
return isTrusted && forwarded ? forwarded : socketIp
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Serve over HTTP. */
|
|
248
|
+
listen(options: { port?: number; hostname?: string; reusePort?: boolean } = {}) {
|
|
249
|
+
this.compile()
|
|
250
|
+
const port = options.port ?? this.app.config<number | undefined>('http.port') ?? 3000
|
|
251
|
+
this.server = Bun.serve({
|
|
252
|
+
port,
|
|
253
|
+
hostname: options.hostname ?? this.app.config<string | undefined>('http.host'),
|
|
254
|
+
reusePort: options.reusePort,
|
|
255
|
+
maxRequestBodySize: this.app.config<number | undefined>('http.maxBodyBytes') ?? 10 * 1024 * 1024,
|
|
256
|
+
fetch: (req, server) => this.handle(req, { ip: server.requestIP(req)?.address }),
|
|
257
|
+
})
|
|
258
|
+
return this.server
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Stop accepting requests, wait for in-flight ones up to `timeoutMs`, then close what is left. */
|
|
262
|
+
async stop(timeoutMs = 10_000): Promise<void> {
|
|
263
|
+
const server = this.server
|
|
264
|
+
if (!server) return
|
|
265
|
+
this.server = undefined
|
|
266
|
+
const graceful = server.stop(false)
|
|
267
|
+
const timedOut = await Promise.race([graceful.then(() => false), Bun.sleep(timeoutMs).then(() => true)])
|
|
268
|
+
if (timedOut) await server.stop(true)
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** `/health/live` and `/health/ready` (runs every check tagged `HEALTH_CHECKS`). */
|
|
272
|
+
async health(kind: 'live' | 'ready'): Promise<Response> {
|
|
273
|
+
if (kind === 'live') return json({ status: 'ok' })
|
|
274
|
+
const checks = this.app.tagged<HealthCheck>(HEALTH_CHECKS)
|
|
275
|
+
const results = await Promise.all(
|
|
276
|
+
checks.map(async (c) => {
|
|
277
|
+
try {
|
|
278
|
+
await c.check()
|
|
279
|
+
return [c.name, 'ok'] as const
|
|
280
|
+
} catch (e) {
|
|
281
|
+
return [c.name, (e as Error).message ?? 'failed'] as const
|
|
282
|
+
}
|
|
283
|
+
}),
|
|
284
|
+
)
|
|
285
|
+
const ok = results.every(([, r]) => r === 'ok')
|
|
286
|
+
return json({ status: ok ? 'ok' : 'unavailable', checks: Object.fromEntries(results) }, { status: ok ? 200 : 503 })
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const isClass = (v: unknown): v is new (...a: never[]) => unknown =>
|
|
291
|
+
typeof v === 'function' && /^class[\s{]/.test(Function.prototype.toString.call(v))
|
|
292
|
+
const isMiddlewareClass = (m: Middleware) => isClass(m)
|
|
293
|
+
|
|
294
|
+
/** A handler's return value → Response. */
|
|
295
|
+
export async function toResponse(result: unknown, ctx: HttpContext): Promise<Response> {
|
|
296
|
+
if (result instanceof Response) return result
|
|
297
|
+
if (isResponsable(result)) return result.toResponse(ctx)
|
|
298
|
+
if (result === null || result === undefined) return new Response(null, { status: 204 })
|
|
299
|
+
if (typeof result === 'string')
|
|
300
|
+
return new Response(result, { headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
301
|
+
return json(result)
|
|
302
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/** Built-in middleware: `import { securityHeaders, bodyLimit, … } from '@cslug/http/middleware'`. */
|
|
2
|
+
import { CslugError, ForbiddenError, parseDuration } from '@cslug/core'
|
|
3
|
+
import type { MiddlewareFn } from '../router'
|
|
4
|
+
import { verifySignedUrl } from '../url'
|
|
5
|
+
|
|
6
|
+
export { csrf, locale, type SessionOptions, session, throttle } from './web'
|
|
7
|
+
|
|
8
|
+
/** Security headers on every response (CSP is opt-in: it depends on your assets). */
|
|
9
|
+
export const securityHeaders =
|
|
10
|
+
(options: { hsts?: boolean; csp?: string; frameOptions?: 'DENY' | 'SAMEORIGIN' } = {}): MiddlewareFn =>
|
|
11
|
+
async (ctx, next) => {
|
|
12
|
+
const res = await next()
|
|
13
|
+
const h = res.headers
|
|
14
|
+
const set = (k: string, v: string) => {
|
|
15
|
+
if (!h.has(k)) h.set(k, v)
|
|
16
|
+
}
|
|
17
|
+
set('x-content-type-options', 'nosniff')
|
|
18
|
+
set('x-frame-options', options.frameOptions ?? 'DENY')
|
|
19
|
+
set('referrer-policy', 'strict-origin-when-cross-origin')
|
|
20
|
+
set('cross-origin-opener-policy', 'same-origin')
|
|
21
|
+
if (options.csp) set('content-security-policy', options.csp)
|
|
22
|
+
if (options.hsts ?? ctx.app.config('app.env') === 'production')
|
|
23
|
+
set('strict-transport-security', 'max-age=31536000; includeSubDomains')
|
|
24
|
+
return res
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const SIZE = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/i
|
|
28
|
+
const bytes = (size: string | number) => {
|
|
29
|
+
if (typeof size === 'number') return size
|
|
30
|
+
const m = SIZE.exec(size.trim())
|
|
31
|
+
if (!m) throw new CslugError('http.invalid_size', `Invalid size "${size}"`)
|
|
32
|
+
return Math.round(
|
|
33
|
+
Number(m[1]) * { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 }[(m[2] as string).toLowerCase() as 'b'],
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 413 when the declared body size is over the limit: `bodyLimit('1mb')`, `bodyLimit('20mb')` for uploads. */
|
|
38
|
+
export const bodyLimit =
|
|
39
|
+
(limit: string | number): MiddlewareFn =>
|
|
40
|
+
async (ctx, next) => {
|
|
41
|
+
const max = bytes(limit)
|
|
42
|
+
const declared = Number(ctx.request.header('content-length') ?? 0)
|
|
43
|
+
if (declared > max) {
|
|
44
|
+
throw Object.assign(new CslugError('http.payload_too_large', `The request body is larger than ${limit}.`), {
|
|
45
|
+
status: 413,
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
// also enforced on the bytes actually read (bodies without Content-Length, chunked uploads)
|
|
49
|
+
ctx.request.maxBodyBytes = Math.min(ctx.request.maxBodyBytes ?? Number.POSITIVE_INFINITY, max)
|
|
50
|
+
return next()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Abort the handler's work after a duration (`ctx.signal` fires) and answer 503. */
|
|
54
|
+
export const timeout =
|
|
55
|
+
(duration: string | number): MiddlewareFn =>
|
|
56
|
+
async (ctx, next) => {
|
|
57
|
+
const controller = new AbortController()
|
|
58
|
+
const onAbort = () => controller.abort(ctx.signal.reason)
|
|
59
|
+
ctx.signal.addEventListener('abort', onAbort, { once: true })
|
|
60
|
+
Object.assign(ctx, { signal: controller.signal })
|
|
61
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
62
|
+
try {
|
|
63
|
+
return await Promise.race([
|
|
64
|
+
next(),
|
|
65
|
+
new Promise<never>((_, reject) => {
|
|
66
|
+
timer = setTimeout(() => {
|
|
67
|
+
controller.abort(new Error('timeout'))
|
|
68
|
+
reject(Object.assign(new CslugError('http.timeout', 'The request took too long.'), { status: 503 }))
|
|
69
|
+
}, parseDuration(duration))
|
|
70
|
+
}),
|
|
71
|
+
])
|
|
72
|
+
} finally {
|
|
73
|
+
clearTimeout(timer)
|
|
74
|
+
ctx.signal.removeEventListener?.('abort', onAbort)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 403 unless the URL was made by `route(name, params, { signed: true })` and has not expired. */
|
|
79
|
+
export const signed = (): MiddlewareFn => async (ctx, next) => {
|
|
80
|
+
const key = ctx.app.config<string | undefined>('app.key')
|
|
81
|
+
if (!key || !verifySignedUrl(ctx.request.url.toString(), key))
|
|
82
|
+
throw new ForbiddenError('http.invalid_signature', 'This link is invalid or has expired.')
|
|
83
|
+
return next()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** CORS for API routes. `origins: ['*']` allows any origin (without credentials). */
|
|
87
|
+
export const cors =
|
|
88
|
+
(options: {
|
|
89
|
+
origins: string[]
|
|
90
|
+
methods?: string[]
|
|
91
|
+
headers?: string[]
|
|
92
|
+
credentials?: boolean
|
|
93
|
+
maxAge?: number
|
|
94
|
+
}): MiddlewareFn =>
|
|
95
|
+
async (ctx, next) => {
|
|
96
|
+
const origin = ctx.request.header('origin')
|
|
97
|
+
const allowed = origin && (options.origins.includes('*') || options.origins.includes(origin)) ? origin : undefined
|
|
98
|
+
const apply = (h: Headers) => {
|
|
99
|
+
if (!allowed) return
|
|
100
|
+
h.set('access-control-allow-origin', options.origins.includes('*') && !options.credentials ? '*' : allowed)
|
|
101
|
+
if (options.credentials) h.set('access-control-allow-credentials', 'true')
|
|
102
|
+
h.append('vary', 'Origin')
|
|
103
|
+
}
|
|
104
|
+
if (ctx.request.method === 'OPTIONS' && ctx.request.header('access-control-request-method')) {
|
|
105
|
+
const res = new Response(null, { status: 204 })
|
|
106
|
+
apply(res.headers)
|
|
107
|
+
res.headers.set(
|
|
108
|
+
'access-control-allow-methods',
|
|
109
|
+
(options.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).join(', '),
|
|
110
|
+
)
|
|
111
|
+
res.headers.set(
|
|
112
|
+
'access-control-allow-headers',
|
|
113
|
+
(options.headers ?? ['content-type', 'authorization', 'x-csrf-token']).join(', '),
|
|
114
|
+
)
|
|
115
|
+
res.headers.set('access-control-max-age', String(options.maxAge ?? 600))
|
|
116
|
+
return res
|
|
117
|
+
}
|
|
118
|
+
const res = await next()
|
|
119
|
+
apply(res.headers)
|
|
120
|
+
return res
|
|
121
|
+
}
|