@cslug/http 0.0.0-stage → 0.1.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 +93 -0
- package/package.json +33 -4
- package/src/body.ts +72 -0
- package/src/commands.ts +113 -0
- package/src/context.ts +232 -0
- package/src/errors.ts +131 -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 +112 -0
- package/src/router.ts +202 -0
- package/src/session.ts +160 -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/session.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { CslugError, type SessionData, type SessionStore } from '@cslug/core'
|
|
3
|
+
|
|
4
|
+
const randomId = (bytes = 32) => Buffer.from(crypto.getRandomValues(new Uint8Array(bytes))).toString('base64url')
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The session of one request: data in the `SessionStore` (memory or Redis), the id in a cookie.
|
|
8
|
+
* Flash values live for the next request only.
|
|
9
|
+
*/
|
|
10
|
+
export class Session {
|
|
11
|
+
private data: SessionData
|
|
12
|
+
private dirty = false
|
|
13
|
+
private destroyed: string[] = []
|
|
14
|
+
/** Flash values set during the previous request (readable now). */
|
|
15
|
+
private readonly previous: SessionData
|
|
16
|
+
private next: SessionData = {}
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
public id: string,
|
|
20
|
+
data: SessionData,
|
|
21
|
+
readonly isNew: boolean,
|
|
22
|
+
) {
|
|
23
|
+
const { _flash, ...rest } = data
|
|
24
|
+
this.previous = (_flash as SessionData | undefined) ?? {}
|
|
25
|
+
this.data = rest
|
|
26
|
+
if (Object.keys(this.previous).length) this.dirty = true // the flash must be cleared on save
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
static create(): Session {
|
|
30
|
+
return new Session(randomId(), {}, true)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get<T = unknown>(key: string): T | undefined {
|
|
34
|
+
return this.data[key] as T | undefined
|
|
35
|
+
}
|
|
36
|
+
has(key: string): boolean {
|
|
37
|
+
return key in this.data
|
|
38
|
+
}
|
|
39
|
+
put(key: string, value: unknown): void {
|
|
40
|
+
this.data[key] = value
|
|
41
|
+
this.dirty = true
|
|
42
|
+
}
|
|
43
|
+
forget(key: string): void {
|
|
44
|
+
delete this.data[key]
|
|
45
|
+
this.dirty = true
|
|
46
|
+
}
|
|
47
|
+
/** Read and remove. */
|
|
48
|
+
pull<T = unknown>(key: string): T | undefined {
|
|
49
|
+
const v = this.get<T>(key)
|
|
50
|
+
this.forget(key)
|
|
51
|
+
return v
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A value for the next request only (`redirect().with()` uses this). */
|
|
55
|
+
flash(key: string, value: unknown): void {
|
|
56
|
+
this.next[key] = value
|
|
57
|
+
this.dirty = true
|
|
58
|
+
}
|
|
59
|
+
/** Keep this request's flash values for one more request. */
|
|
60
|
+
reflash(): void {
|
|
61
|
+
this.next = { ...this.previous, ...this.next }
|
|
62
|
+
this.dirty = true
|
|
63
|
+
}
|
|
64
|
+
/** Flash values from the previous request, without the internal ones (`success`, `error`, …). */
|
|
65
|
+
flashed(): SessionData {
|
|
66
|
+
return Object.fromEntries(Object.entries(this.previous).filter(([k]) => !k.startsWith('_')))
|
|
67
|
+
}
|
|
68
|
+
/** Validation errors flashed by a failed form post: `{ field: ['message'] }`. */
|
|
69
|
+
errors(): Record<string, string[]> {
|
|
70
|
+
return (this.previous._errors as Record<string, string[]> | undefined) ?? {}
|
|
71
|
+
}
|
|
72
|
+
/** The previous form input (after a failed validation), or one field of it. */
|
|
73
|
+
old(): SessionData
|
|
74
|
+
old(key: string): unknown
|
|
75
|
+
old(key?: string): unknown {
|
|
76
|
+
const old = (this.previous._old as SessionData | undefined) ?? {}
|
|
77
|
+
return key === undefined ? old : old[key]
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The CSRF token (created on first use). */
|
|
81
|
+
token(): string {
|
|
82
|
+
let t = this.get<string>('_token')
|
|
83
|
+
if (!t) {
|
|
84
|
+
t = randomId()
|
|
85
|
+
this.put('_token', t)
|
|
86
|
+
}
|
|
87
|
+
return t
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Constant-time comparison with the session's CSRF token. */
|
|
91
|
+
verifyToken(given: string | undefined): boolean {
|
|
92
|
+
const expected = this.get<string>('_token')
|
|
93
|
+
if (!given || !expected) return false
|
|
94
|
+
const a = Buffer.from(given)
|
|
95
|
+
const b = Buffer.from(expected)
|
|
96
|
+
return a.length === b.length && timingSafeEqual(a, b)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** New id, same data: call on login (prevents session fixation). */
|
|
100
|
+
regenerate(): void {
|
|
101
|
+
this.destroyed.push(this.id)
|
|
102
|
+
this.id = randomId()
|
|
103
|
+
this.dirty = true
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Empty the session and give it a new id: call on logout. */
|
|
107
|
+
invalidate(): void {
|
|
108
|
+
this.data = {}
|
|
109
|
+
this.next = {}
|
|
110
|
+
this.regenerate()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Persist (only what changed) and return the ids to destroy. */
|
|
114
|
+
async save(store: SessionStore, lifetime: string | number): Promise<void> {
|
|
115
|
+
for (const id of this.destroyed) await store.destroy(id)
|
|
116
|
+
this.destroyed = []
|
|
117
|
+
if (!this.dirty && !this.isNew) return
|
|
118
|
+
await store.write(
|
|
119
|
+
this.id,
|
|
120
|
+
Object.keys(this.next).length ? { ...this.data, _flash: this.next } : this.data,
|
|
121
|
+
lifetime,
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Whether a cookie should be sent (new session with data, or a changed id). */
|
|
126
|
+
get needsCookie(): boolean {
|
|
127
|
+
return this.dirty || !this.isNew
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Placeholder until the `session()` middleware runs: every use explains how to fix it. */
|
|
132
|
+
export class MissingSession extends Session {
|
|
133
|
+
constructor() {
|
|
134
|
+
super('', {}, true)
|
|
135
|
+
}
|
|
136
|
+
private fail(): never {
|
|
137
|
+
throw new CslugError(
|
|
138
|
+
'http.no_session',
|
|
139
|
+
'This route has no session: add the session() middleware (routes in routes/web.ts have it).',
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
override get<T>(): T | undefined {
|
|
143
|
+
return this.fail()
|
|
144
|
+
}
|
|
145
|
+
override put(): void {
|
|
146
|
+
this.fail()
|
|
147
|
+
}
|
|
148
|
+
override flash(): void {
|
|
149
|
+
this.fail()
|
|
150
|
+
}
|
|
151
|
+
override token(): string {
|
|
152
|
+
return this.fail()
|
|
153
|
+
}
|
|
154
|
+
override errors(): Record<string, string[]> {
|
|
155
|
+
return {}
|
|
156
|
+
}
|
|
157
|
+
override old(): never {
|
|
158
|
+
return this.fail()
|
|
159
|
+
}
|
|
160
|
+
}
|
package/src/static.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs'
|
|
2
|
+
import { join, normalize, sep } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/** Hashed build output (`client-3f9a1c2e.js`): cached for a year. */
|
|
5
|
+
const HASHED = /-[a-z0-9]{8}\.[a-z0-9]+$/
|
|
6
|
+
|
|
7
|
+
/**
|
|
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.
|
|
10
|
+
*/
|
|
11
|
+
export function serveStatic(publicDir: string, pathname: string, request: Request): Response | undefined {
|
|
12
|
+
let decoded: string
|
|
13
|
+
try {
|
|
14
|
+
decoded = decodeURIComponent(pathname)
|
|
15
|
+
} catch {
|
|
16
|
+
return undefined
|
|
17
|
+
}
|
|
18
|
+
if (decoded.includes('\0') || decoded.split('/').some((part) => part.startsWith('.'))) return undefined
|
|
19
|
+
const file = normalize(join(publicDir, decoded))
|
|
20
|
+
if (!file.startsWith(publicDir.endsWith(sep) ? publicDir : publicDir + sep) || !existsSync(file)) return undefined
|
|
21
|
+
const stat = statSync(file)
|
|
22
|
+
if (!stat.isFile()) return undefined
|
|
23
|
+
const modified = new Date(Math.floor(stat.mtimeMs / 1000) * 1000)
|
|
24
|
+
const headers = new Headers({
|
|
25
|
+
'last-modified': modified.toUTCString(),
|
|
26
|
+
'cache-control': HASHED.test(file) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
|
|
27
|
+
})
|
|
28
|
+
const since = request.headers.get('if-modified-since')
|
|
29
|
+
if (since && new Date(since).getTime() >= modified.getTime()) return new Response(null, { status: 304, headers })
|
|
30
|
+
const body = Bun.file(file)
|
|
31
|
+
headers.set('content-type', body.type)
|
|
32
|
+
headers.set('content-length', String(stat.size))
|
|
33
|
+
return new Response(request.method === 'HEAD' ? null : body, { headers })
|
|
34
|
+
}
|
package/src/url.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { CslugError, currentApp, parseDuration } from '@cslug/core'
|
|
3
|
+
import { Router } from './router'
|
|
4
|
+
|
|
5
|
+
export type UrlOptions = {
|
|
6
|
+
absolute?: boolean
|
|
7
|
+
query?: Record<string, string | number | boolean | null | undefined>
|
|
8
|
+
/** Add an HMAC signature (APP_KEY); verify with the `signed()` middleware. */
|
|
9
|
+
signed?: boolean
|
|
10
|
+
expiresIn?: string | number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const fill = (pattern: string, params: Record<string, unknown>, name: string, used: Set<string>) =>
|
|
14
|
+
pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {
|
|
15
|
+
const value = params[key]
|
|
16
|
+
if (value === undefined || value === null)
|
|
17
|
+
throw new CslugError('http.missing_route_param', `Route "${name}" needs parameter "${key}"`)
|
|
18
|
+
used.add(key)
|
|
19
|
+
return encodeURIComponent(String(value))
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const signature = (key: string, url: string) => createHmac('sha256', key).update(url).digest('base64url')
|
|
23
|
+
|
|
24
|
+
/** Build a URL from a route name. Without `absolute`, a path is returned unless the route is on another domain. */
|
|
25
|
+
export function urlFor(
|
|
26
|
+
router: Router,
|
|
27
|
+
appUrl: string | undefined,
|
|
28
|
+
key: string | undefined,
|
|
29
|
+
name: string,
|
|
30
|
+
params: Record<string, unknown> = {},
|
|
31
|
+
options: UrlOptions = {},
|
|
32
|
+
): string {
|
|
33
|
+
const route = router.byName(name)
|
|
34
|
+
if (!route) throw new CslugError('http.unknown_route', `No route named "${name}"`)
|
|
35
|
+
const used = new Set<string>()
|
|
36
|
+
const path = fill(route.path, params, name, used)
|
|
37
|
+
const query = new URLSearchParams()
|
|
38
|
+
for (const [k, v] of Object.entries(params))
|
|
39
|
+
if (!used.has(k) && v !== undefined && v !== null && !route.domain?.includes(`:${k}`)) query.set(k, String(v))
|
|
40
|
+
for (const [k, v] of Object.entries(options.query ?? {})) if (v !== undefined && v !== null) query.set(k, String(v))
|
|
41
|
+
|
|
42
|
+
const base = appUrl ? new URL(appUrl) : undefined
|
|
43
|
+
const host = route.domain ? fill(route.domain, params, name, used) : undefined
|
|
44
|
+
const absolute = options.absolute || options.signed || (host !== undefined && host !== base?.hostname)
|
|
45
|
+
let origin = ''
|
|
46
|
+
if (absolute) {
|
|
47
|
+
if (!base) throw new CslugError('http.no_app_url', 'Absolute URLs need config app.url')
|
|
48
|
+
origin = `${base.protocol}//${host ?? base.host}${host && base.port ? `:${base.port}` : ''}`
|
|
49
|
+
}
|
|
50
|
+
if (options.signed) {
|
|
51
|
+
if (!key) throw new CslugError('http.no_app_key', 'Signed URLs need APP_KEY (config app.key)')
|
|
52
|
+
if (options.expiresIn !== undefined)
|
|
53
|
+
query.set('expires', String(Math.floor((Date.now() + parseDuration(options.expiresIn)) / 1000)))
|
|
54
|
+
query.sort()
|
|
55
|
+
const unsigned = `${origin}${path}${query.size ? `?${query}` : ''}`
|
|
56
|
+
query.set('signature', signature(key, unsigned))
|
|
57
|
+
}
|
|
58
|
+
return `${origin}${path}${query.size ? `?${query}` : ''}`
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Is a request URL correctly signed (and not expired)? */
|
|
62
|
+
export function verifySignedUrl(url: string, key: string, now = Date.now()): boolean {
|
|
63
|
+
const u = new URL(url)
|
|
64
|
+
const given = u.searchParams.get('signature')
|
|
65
|
+
if (!given) return false
|
|
66
|
+
u.searchParams.delete('signature')
|
|
67
|
+
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
|
|
72
|
+
const expires = u.searchParams.get('expires')
|
|
73
|
+
return !expires || Number(expires) * 1000 > now
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `route('bookings.show', { booking: id })` from the current app. */
|
|
77
|
+
export function route(name: string, params: Record<string, unknown> = {}, options: UrlOptions = {}): string {
|
|
78
|
+
const app = currentApp()
|
|
79
|
+
return urlFor(
|
|
80
|
+
app.resolve(Router),
|
|
81
|
+
app.config<string | undefined>('app.url'),
|
|
82
|
+
app.config<string | undefined>('app.key'),
|
|
83
|
+
name,
|
|
84
|
+
params,
|
|
85
|
+
options,
|
|
86
|
+
)
|
|
87
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { inject, NotFoundError } from '@cslug/core'
|
|
2
|
+
import { type HttpContext, redirect } from '@cslug/http'
|
|
3
|
+
|
|
4
|
+
@inject()
|
|
5
|
+
export class {{ class }} {
|
|
6
|
+
/** GET /{{ plural }} */
|
|
7
|
+
async index({ request }: HttpContext) {
|
|
8
|
+
return []
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** GET /{{ plural }}/create */
|
|
12
|
+
async create(ctx: HttpContext) {}
|
|
13
|
+
|
|
14
|
+
/** POST /{{ plural }} */
|
|
15
|
+
async store({ request }: HttpContext) {
|
|
16
|
+
// const data = await request.validate(Store{{ base }}Validator)
|
|
17
|
+
return redirect().to('/{{ plural }}')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** GET /{{ plural }}/:id */
|
|
21
|
+
async show({ params }: HttpContext) {
|
|
22
|
+
throw new NotFoundError(`{{ base }} ${params.id} not found`)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** GET /{{ plural }}/:id/edit */
|
|
26
|
+
async edit({ params }: HttpContext) {}
|
|
27
|
+
|
|
28
|
+
/** PUT /{{ plural }}/:id */
|
|
29
|
+
async update({ params, request }: HttpContext) {
|
|
30
|
+
return redirect().back()
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** DELETE /{{ plural }}/:id */
|
|
34
|
+
async destroy({ params }: HttpContext) {
|
|
35
|
+
return redirect().to('/{{ plural }}')
|
|
36
|
+
}
|
|
37
|
+
}
|