@cslug/http 0.6.1 → 0.7.1

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/README.md CHANGED
@@ -10,7 +10,7 @@ export default defineRoutes((r) => {
10
10
  r.get('/circuits/:slug', [CircuitController, 'show']).name('circuits.show')
11
11
  })
12
12
  r.resource('operators', OperatorController).only(['index', 'show'])
13
- r.group({ domain: 'api.albastr.com', prefix: '/v1' }, (r) => { … })
13
+ r.group({ domain: 'api.example.com', prefix: '/v1' }, (r) => { … })
14
14
  })
15
15
 
16
16
  // a controller action
package/docs/api.md CHANGED
@@ -9,6 +9,7 @@
9
9
  |---|---|
10
10
  | `r.get/post/put/patch/delete/options(path, action)` | `action`: `[Controller, 'method']`, a single-action class (`handle`), or a closure |
11
11
  | `.name(n)`, `.middleware(...m)`, `.where('param', /re/)` | |
12
+ | `.validates(schema)` | Live validation: a request with `X-Cslug-Validate: field,…` (or `*`) runs the route's middleware and this schema, answers `204` (`X-Cslug-Validated: 1`) or `422` with only those fields' errors, and never calls the handler; without `.validates()` such a request is `400` (`http.no_live_validation`) |
12
13
  | `r.group({ prefix, domain, middleware, as, ...meta }, fn)` | Nested groups accumulate prefix, middleware and name prefix; `domain` may contain `:params` |
13
14
  | `r.resource('operators', Ctl).only([...]) / .except([...])` | index, create, store, show, edit, update (PATCH), destroy; nested `'operators.documents'` |
14
15
 
@@ -38,7 +39,9 @@ the container (DI).
38
39
  Return a `Response`, a `Responsable` (`toResponse(ctx)`), an object/array (JSON: bigint → string, Date → ISO,
39
40
  `toJSON()`), a string (`text/plain`), or `null`/`undefined` (204). Helpers: `json`, `created`, `accepted`,
40
41
  `noContent`, `download(content, filename, type?)`, `stream(asyncIterable)`, `sse(asyncIterable)`,
41
- `redirect().route(name, params) / .to(url) / .away(url) / .back(fallback) / .intended(fallback) / .with(key, value)`
42
+ `redirect().route(name, params) / .to(url) / .away(url) / .back(fallback) / .intended(fallback) / .with(key, value)`.
43
+ For a request with `X-Cslug-Request: 1` (from `@cslug/vue`'s `useForm` / `http`), it answers `204` with
44
+ `X-Cslug-Redirect: <url>` instead of a 3xx (flashes are kept), so `fetch` can read where to go.
42
45
  (303 after non-GET; `.with()` and `.intended()` need the session).
43
46
 
44
47
  ## Errors (`ExceptionHandler`)
@@ -51,7 +54,9 @@ Extend with `handler.render(fn)` (first match wins) and `handler.report(fn)` (5x
51
54
  ## Middleware (`@cslug/http/middleware`)
52
55
 
53
56
  `securityHeaders({ hsts?, csp?, frameOptions? })` (global by default), `bodyLimit(size)` (global `1mb`; also
54
- enforced on bytes read), `timeout(duration)` (503, aborts `ctx.signal`), `signed()`, `cors({ origins, … })`.
57
+ enforced on bytes read), `timeout(duration)` (503, aborts `ctx.signal`), `signed()`, `cors({ origins, … })`,
58
+ `statefulApi(origins?)` (session + CSRF for requests from the app's own pages: `Origin`, else `Referer`, else
59
+ `Sec-Fetch-Site: same-origin`; `fromFrontEnd(request, origins)` is the check).
55
60
  Function middleware `(ctx, next) => Response`, or a class with `handle(ctx, next)` built by the container.
56
61
 
57
62
  ## Kernel
@@ -62,7 +67,8 @@ the database's). One log line per request: method, path, status, ms, route, requ
62
67
 
63
68
  ## `HttpProvider`
64
69
 
65
- Config `http`: `port`, `host`, `shutdownTimeout`, `bodyLimit`, `trustedProxies`, `cors` (api group),
70
+ Config `http`: `port`, `host`, `shutdownTimeout`, `bodyLimit`, `trustedProxies`, `cors` (api group), `api.stateful`
71
+ (`true` for `app.url`'s origin, or a list: `statefulApi()` first in the api group, before `authenticate()`),
66
72
  `groups.{web,api}`, `middleware`, `problemBase`, `health`.
67
73
 
68
74
  ## Sessions, CSRF, forms (web group)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/http",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
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.6.1",
33
- "@cslug/validation": "0.6.1"
32
+ "@cslug/core": "0.7.1",
33
+ "@cslug/validation": "0.7.1"
34
34
  }
35
35
  }
package/src/context.ts CHANGED
@@ -3,7 +3,7 @@ import { type Output, type Schema, type Validatable, Validator, validate } from
3
3
  import { coerceForm, nestKeys } from './body'
4
4
  import type { Session } from './session'
5
5
 
6
- type ValidatorClass = abstract new (...args: never[]) => Validator
6
+ export type ValidatorClass = abstract new (...args: never[]) => Validator
7
7
  /** What `request.validate()` accepts: a schema, a Validator instance or class, a Standard Schema. */
8
8
  export type Validated<T> = T extends ValidatorClass ? Output<InstanceType<T>> : Output<T>
9
9
 
package/src/kernel.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  type Application,
3
+ BadRequestError,
3
4
  currentContext,
4
5
  HEALTH_CHECKS,
5
6
  type HealthCheck,
@@ -7,6 +8,7 @@ import {
7
8
  NotFoundError,
8
9
  runInContext,
9
10
  type Token,
11
+ ValidationError,
10
12
  } from '@cslug/core'
11
13
  import { type HttpContext, HttpRequest, ResponseBuilder } from './context'
12
14
  import type { ExceptionHandler } from './errors'
@@ -219,6 +221,8 @@ export class HttpKernel {
219
221
  }
220
222
 
221
223
  private async callAction(ctx: HttpContext, route: RouteDef): Promise<Response> {
224
+ const fields = ctx.request.header('x-cslug-validate')
225
+ if (fields !== undefined) return this.validateOnly(ctx, route, fields)
222
226
  const action = route.action
223
227
  let result: unknown
224
228
  if (Array.isArray(action)) {
@@ -235,6 +239,34 @@ export class HttpKernel {
235
239
  return toResponse(result, ctx)
236
240
  }
237
241
 
242
+ /**
243
+ * Live validation (`X-Cslug-Validate: email,name` or `*`): the route's declared schema checks the input; only the
244
+ * named fields' errors are reported (422), else 204. The handler never runs.
245
+ */
246
+ private async validateOnly(ctx: HttpContext, route: RouteDef, header: string): Promise<Response> {
247
+ if (!route.validates)
248
+ throw new BadRequestError(
249
+ 'http.no_live_validation',
250
+ `${route.method} ${route.path} does not support live validation: declare .validates(schema) on the route`,
251
+ )
252
+ const wanted = header
253
+ .split(',')
254
+ .map((f) => f.trim())
255
+ .filter(Boolean)
256
+ try {
257
+ await ctx.request.validate(route.validates)
258
+ } catch (error) {
259
+ if (!(error instanceof ValidationError)) throw error
260
+ const all = wanted.includes('*') || !wanted.length
261
+ const issues = error.issues.filter((i) => {
262
+ const path = i.path.join('.')
263
+ return all || wanted.some((f) => path === f || path.startsWith(`${f}.`))
264
+ })
265
+ if (issues.length) throw new ValidationError(issues)
266
+ }
267
+ return new Response(null, { status: 204, headers: { 'x-cslug-validated': '1' } })
268
+ }
269
+
238
270
  private clientIp(request: Request, socketIp: string | undefined): string | undefined {
239
271
  const trusted = this.app.config<string[] | undefined>('http.trustedProxies') ?? []
240
272
  const loopback = socketIp === '127.0.0.1' || socketIp === '::1' || socketIp?.startsWith('::ffff:127.') === true
@@ -3,6 +3,8 @@ import { CslugError, ForbiddenError, parseDuration } from '@cslug/core'
3
3
  import type { MiddlewareFn } from '../router'
4
4
  import { verifySignedUrl } from '../url'
5
5
 
6
+ import { csrf, session } from './web'
7
+
6
8
  export { csrf, locale, type SessionOptions, session, throttle } from './web'
7
9
 
8
10
  /** Security headers on every response (CSP is opt-in: it depends on your assets). */
@@ -83,6 +85,39 @@ export const signed = (): MiddlewareFn => async (ctx, next) => {
83
85
  return next()
84
86
  }
85
87
 
88
+ /**
89
+ * Is this request from the app's own pages? Its `Origin` (or, without one, its `Referer`) is one of `origins`, or the
90
+ * browser says `Sec-Fetch-Site: same-origin`.
91
+ */
92
+ export function fromFrontEnd(headers: { header(name: string): string | undefined }, origins: string[]): boolean {
93
+ const originOf = (url: string | undefined) => {
94
+ try {
95
+ return url ? new URL(url).origin : undefined
96
+ } catch {
97
+ return undefined
98
+ }
99
+ }
100
+ const origin = headers.header('origin') ?? originOf(headers.header('referer'))
101
+ if (origin) return origins.includes(origin)
102
+ return headers.header('sec-fetch-site') === 'same-origin'
103
+ }
104
+
105
+ /**
106
+ * The session for API routes called by the app's own pages (`http.api.stateful`, what Laravel Sanctum calls an SPA):
107
+ * a request from one of `origins` (default: `app.url`'s) gets `session()` and `csrf()`, so `useForm` / `http` in an
108
+ * island reach `routes/api.ts` with the signed-in user. Other clients are left to API tokens. Runs before
109
+ * `authenticate()`.
110
+ */
111
+ export const statefulApi = (origins?: string[]): MiddlewareFn => {
112
+ const withSession = session()
113
+ const withCsrf = csrf()
114
+ return (ctx, next) => {
115
+ const allowed = origins ?? [new URL(ctx.app.config<string>('app.url') ?? 'http://localhost').origin]
116
+ if (!fromFrontEnd(ctx.request, allowed)) return next()
117
+ return withSession(ctx, () => Promise.resolve(withCsrf(ctx, next)))
118
+ }
119
+ }
120
+
86
121
  /** CORS for API routes. `origins: ['*']` allows any origin (without credentials). */
87
122
  export const cors =
88
123
  (options: {
@@ -16,7 +16,7 @@ export type SessionOptions = {
16
16
  cookie?: string
17
17
  lifetime?: string
18
18
  sameSite?: 'lax' | 'strict' | 'none'
19
- /** Cookie domain, e.g. `.albastr.com` to share a login across subdomains. */
19
+ /** Cookie domain, e.g. `.example.com` to share a login across subdomains. */
20
20
  domain?: string
21
21
  }
22
22
 
package/src/provider.ts CHANGED
@@ -4,7 +4,7 @@ import { Logger, ServiceProvider } from '@cslug/core'
4
4
  import { httpCommands, routeRows } from './commands'
5
5
  import { ExceptionHandler } from './errors'
6
6
  import { HttpKernel } from './kernel'
7
- import { bodyLimit, cors, csrf, securityHeaders, session } from './middleware'
7
+ import { bodyLimit, cors, csrf, securityHeaders, session, statefulApi } from './middleware'
8
8
  import { type GroupOptions, type Middleware, type RouteRegistrar, Router } from './router'
9
9
 
10
10
  export type HttpConfig = {
@@ -17,6 +17,12 @@ export type HttpConfig = {
17
17
  public?: boolean | string
18
18
  trustedProxies?: string[]
19
19
  cors?: { origins: string[]; credentials?: boolean }
20
+ /**
21
+ * `stateful: true` (the origin of `app.url`) or a list of origins: requests from the app's own pages to
22
+ * `routes/api.ts` get the session and CSRF (`statefulApi()`), so islands call API routes as the signed-in user.
23
+ * Other clients authenticate with API tokens.
24
+ */
25
+ api?: { stateful?: boolean | string[] }
20
26
  /** Extra middleware for the `web` (routes/web.ts) and `api` (routes/api.ts) groups. */
21
27
  groups?: { web?: Middleware[]; api?: Middleware[] }
22
28
  /** Global middleware added after the defaults. */
@@ -79,6 +85,9 @@ export class HttpProvider extends ServiceProvider {
79
85
  {
80
86
  middleware: [
81
87
  ...(config.cors ? [cors(config.cors)] : []),
88
+ ...(config.api?.stateful
89
+ ? [statefulApi(Array.isArray(config.api.stateful) ? config.api.stateful : undefined)]
90
+ : []),
82
91
  ...this.app.tagged<Middleware>(API_MIDDLEWARE),
83
92
  ...(config.groups?.api ?? []),
84
93
  ],
package/src/responses.ts CHANGED
@@ -103,6 +103,9 @@ export class Redirect implements Responsable {
103
103
  let location = referrer ?? this.target ?? '/'
104
104
  if (this.useIntended) location = ctx.session.pull<string>('url.intended') ?? location
105
105
  for (const [k, v] of Object.entries(this.flashes)) ctx.session.flash(k, v)
106
+ // a request from @cslug/vue's useForm / http (fetch): the URL to go to, which fetch could not read from a 3xx
107
+ if (ctx.request.header('x-cslug-request') === '1')
108
+ return new Response(null, { status: 204, headers: { 'x-cslug-redirect': location } })
106
109
  // 303 after non-GET so the browser follows with GET
107
110
  const status =
108
111
  this.status === 302 && ctx.request.method && !['GET', 'HEAD'].includes(ctx.request.method) ? 303 : this.status
package/src/router.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type Class, CslugError } from '@cslug/core'
2
- import type { HttpContext } from './context'
2
+ import type { Validatable } from '@cslug/validation'
3
+ import type { HttpContext, ValidatorClass } from './context'
3
4
 
4
5
  export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS'
5
6
  export type Next = () => Promise<Response>
@@ -24,11 +25,13 @@ export type RouteDef = {
24
25
  middleware: Middleware[]
25
26
  wheres: Record<string, RegExp>
26
27
  meta: Record<string, unknown>
28
+ /** The schema live validation checks this route's input against (`.validates(schema)`). */
29
+ validates?: Validatable | ValidatorClass
27
30
  }
28
31
 
29
32
  export type GroupOptions = {
30
33
  prefix?: string
31
- /** Host to match, may contain parameters: `':operator.albastr.com'`. */
34
+ /** Host to match, may contain parameters: `':operator.example.com'`. */
32
35
  domain?: string
33
36
  middleware?: Middleware[]
34
37
  /** Route-name prefix: `as: 'admin'` + `.name('show')` → `admin.show`. */
@@ -56,6 +59,15 @@ export class RouteBuilder {
56
59
  this.def.middleware.push(...middleware)
57
60
  return this
58
61
  }
62
+ /**
63
+ * The schema this route validates its input with, for live validation (`form.validate()` in `@cslug/vue`): a
64
+ * request with `X-Cslug-Validate` runs the route's middleware and this validation, answers 204 or 422, and never
65
+ * calls the handler. The handler still calls `request.validate()` itself.
66
+ */
67
+ validates(schema: Validatable | ValidatorClass): this {
68
+ this.def.validates = schema
69
+ return this
70
+ }
59
71
  /** Constrain a path or domain parameter: `.where('operator', /^[a-z0-9-]{3,40}$/)`. */
60
72
  where(param: string, pattern: RegExp): this {
61
73
  this.def.wheres[param] = pattern