@davaux/csrf 0.8.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/CLAUDE.md ADDED
@@ -0,0 +1,95 @@
1
+ <!-- pka-generated -->
2
+ # @davaux/csrf
3
+
4
+ > Generated by Project Knowledge Analyzer on 2026-06-06T21:53:10.185Z
5
+
6
+ ## Overview
7
+
8
+ CSRF protection middleware for Davaux
9
+
10
+ **Version**: 0.8.0
11
+ **Author**: David L Dyess II
12
+ **License**: MIT
13
+ **Repository**: https://codeberg.org/davaux/davaux#readme
14
+
15
+ ## Tech Stack
16
+
17
+ - **Language**: TypeScript
18
+ - **Module System**: ESM (`type: module`)
19
+
20
+ ## Commands
21
+
22
+ - `npm run build` — tsc
23
+ - `npm run typecheck` — tsc --noEmit
24
+
25
+ ## Project Structure
26
+
27
+ ```
28
+ ├── CLAUDE.md
29
+ ├── README.md
30
+ ├── package.json
31
+ ├── tsconfig.json
32
+ └── src/
33
+ └── index.ts
34
+
35
+ ```
36
+
37
+ ## Entry Points
38
+
39
+ - `src/index.ts`
40
+
41
+ ## Files by Type
42
+
43
+ ### Documentation (2)
44
+ - `CLAUDE.md`
45
+ - `README.md`
46
+
47
+ ### Config (2)
48
+ - `package.json`
49
+ - `tsconfig.json`
50
+
51
+ ### Module (1)
52
+ - `src/index.ts`
53
+
54
+
55
+ ## Git
56
+ - **Branch**: main
57
+ - **Last Commit**: chore: Add alpha status note to README
58
+ - **Author**: David Dyess II
59
+ - **Date**: 2026-06-06 15:52:27 -0600
60
+ - **Remote**: https://codeberg.org/davaux/davaux.git
61
+
62
+ ### Recent Commits
63
+ ```
64
+ f527031 chore: Add alpha status note to README
65
+ 90c819e chore: Add repo info to package.json files
66
+ b200d9d feat(davaux)!: Add OmlCacheConfig - opt-in with includes option or opt-out with excludes option; Fix OML implementation to follow OML spec - use output instead of return
67
+ 3bce0c2 chore: Update and add READMEs to packages; update ROADMAP
68
+ fc27c20 fix(davaux): Remove old dist folder on new builds; fix server port per DavauxConfig
69
+ c760659 feat(davaux): Add minify CSS in production builds
70
+ c899ab8 fix(davaux): Added method JS and JSX extenstion to scanner
71
+ 7d99f04 feat(davaux): Add support for declarative partial updates
72
+ 3b47f37 chore: Bump package versions to 0.8.0
73
+ aa0460f chore: Add CHANGELOG.md
74
+ ```
75
+
76
+ ## Dependencies
77
+
78
+
79
+ ### Development
80
+ @davaux/session, @types/node, davaux, typescript
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+ ## Exported Symbols
91
+
92
+ **`src/index.ts`**
93
+ `csrfMiddleware`, `CsrfOptions`
94
+
95
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David L Dyess II
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @davaux/csrf
2
+
3
+ CSRF protection middleware for Davaux. Generates a per-session token and rejects mutating requests (`POST`, `PUT`, `PATCH`, `DELETE`) that don't carry it.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @davaux/csrf
9
+ ```
10
+
11
+ Requires `@davaux/session`.
12
+
13
+ ## Setup
14
+
15
+ Register `sessionMiddleware` before `csrfMiddleware`:
16
+
17
+ ```ts
18
+ // davaux.config.ts
19
+ import { defineConfig } from 'davaux/config'
20
+ import { sessionMiddleware } from '@davaux/session'
21
+ import { csrfMiddleware } from '@davaux/csrf'
22
+
23
+ export default defineConfig({
24
+ middleware: [
25
+ sessionMiddleware({ secret: process.env.SESSION_SECRET! }),
26
+ csrfMiddleware(),
27
+ ],
28
+ })
29
+ ```
30
+
31
+ ## Embedding the token in forms
32
+
33
+ `ctx.state.csrf.token` is available in every handler and layout:
34
+
35
+ ```tsx
36
+ // src/routes/contact.page.tsx
37
+ export default definePage((ctx) => (
38
+ <form method="post">
39
+ <input type="hidden" name="_csrf" value={ctx.state.csrf.token} />
40
+ <button type="submit">Send</button>
41
+ </form>
42
+ ))
43
+ ```
44
+
45
+ For API clients, send the token in the `x-csrf-token` header instead of a form field.
46
+
47
+ ## Options
48
+
49
+ | Option | Type | Default | Description |
50
+ |---|---|---|---|
51
+ | `field` | `string` | `'_csrf'` | Form field name to check |
52
+ | `header` | `string` | `'x-csrf-token'` | Request header name (case-insensitive) |
53
+ | `sessionKey` | `string` | `'_csrf'` | Session key used to store the token |
54
+
55
+ ## Documentation
56
+
57
+ [davaux.codeberg.page/docs/csrf](https://davaux.codeberg.page/docs/csrf)
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@davaux/csrf",
3
+ "version": "0.8.0",
4
+ "description": "CSRF protection middleware for Davaux",
5
+ "type": "module",
6
+ "author": "David L Dyess II",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://codeberg.org/davaux/davaux"
11
+ },
12
+ "bugs": {
13
+ "url": "https://codeberg.org/davaux/davaux/issues"
14
+ },
15
+ "homepage": "https://codeberg.org/davaux/davaux#readme",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.js",
19
+ "types": "./dist/index.d.ts"
20
+ }
21
+ },
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "peerDependencies": {
27
+ "@davaux/session": ">=0.8.0",
28
+ "davaux": ">=0.8.0"
29
+ },
30
+ "devDependencies": {
31
+ "@davaux/session": "*",
32
+ "@types/node": "^25.0.0",
33
+ "davaux": "*",
34
+ "typescript": "^6.0.3"
35
+ }
36
+ }
package/src/index.ts ADDED
@@ -0,0 +1,121 @@
1
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
2
+ import type {} from '@davaux/session'
3
+ import type { MiddlewareFn } from 'davaux'
4
+
5
+ // ─── State augmentation ───────────────────────────────────────────────────────
6
+
7
+ declare module 'davaux' {
8
+ interface State {
9
+ csrf: { token: string }
10
+ }
11
+ }
12
+
13
+ // ─── Options ──────────────────────────────────────────────────────────────────
14
+
15
+ export interface CsrfOptions {
16
+ /**
17
+ * Form field name to check on `application/x-www-form-urlencoded` requests.
18
+ * Default: `'_csrf'`
19
+ */
20
+ field?: string
21
+ /**
22
+ * Request header name to check (case-insensitive).
23
+ * Default: `'x-csrf-token'`
24
+ */
25
+ header?: string
26
+ /**
27
+ * Session key used to store the token.
28
+ * Default: `'_csrf'`
29
+ */
30
+ sessionKey?: string
31
+ }
32
+
33
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
34
+
35
+ // ─── Middleware ───────────────────────────────────────────────────────────────
36
+
37
+ /**
38
+ * CSRF protection middleware. Generates a random token per session and rejects
39
+ * mutating requests (`POST`, `PUT`, `PATCH`, `DELETE`) that do not carry a
40
+ * matching token in either the request header or a form field.
41
+ *
42
+ * Requires `@davaux/session` — register `sessionMiddleware` before this in
43
+ * your middleware chain. The current token is available as `ctx.state.csrf.token`
44
+ * for embedding in forms.
45
+ *
46
+ * @example
47
+ * // _global.ts
48
+ * import { csrfMiddleware } from '@davaux/csrf'
49
+ * export default csrfMiddleware({ field: '_csrf' })
50
+ */
51
+ export function csrfMiddleware(options: CsrfOptions = {}): MiddlewareFn {
52
+ const field = options.field ?? '_csrf'
53
+ const headerName = (options.header ?? 'x-csrf-token').toLowerCase()
54
+ const sessionKey = options.sessionKey ?? '_csrf'
55
+
56
+ return async (ctx, next) => {
57
+ if (!ctx.state.session) {
58
+ throw new Error('@davaux/csrf: sessionMiddleware must be registered before csrfMiddleware')
59
+ }
60
+
61
+ // Get or generate the token for this session
62
+ let token = ctx.state.session.get<string>(sessionKey)
63
+ if (!token) {
64
+ token = randomBytes(32).toString('hex')
65
+ ctx.state.session.set(sessionKey, token)
66
+ }
67
+ ctx.state.csrf = { token }
68
+
69
+ // Safe methods pass through immediately
70
+ const method = (ctx.req.method ?? 'GET').toUpperCase()
71
+ if (SAFE_METHODS.has(method)) {
72
+ return next()
73
+ }
74
+
75
+ // Mutating requests must carry a valid token
76
+ const submitted = await resolveSubmitted(
77
+ ctx.req,
78
+ ctx.req.headers[headerName] as string | undefined,
79
+ field,
80
+ ctx,
81
+ )
82
+ if (!submitted || !safeEqual(submitted, token)) {
83
+ ctx.res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' })
84
+ ctx.res.end('Forbidden: invalid or missing CSRF token')
85
+ return
86
+ }
87
+
88
+ await next()
89
+ }
90
+ }
91
+
92
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
93
+
94
+ async function resolveSubmitted(
95
+ req: import('node:http').IncomingMessage,
96
+ headerValue: string | undefined,
97
+ field: string,
98
+ ctx: import('davaux').RequestContext,
99
+ ): Promise<string | undefined> {
100
+ if (headerValue) return headerValue
101
+
102
+ const contentType = req.headers['content-type'] ?? ''
103
+ if (contentType.includes('application/x-www-form-urlencoded')) {
104
+ const body = await ctx.form()
105
+ return body[field] as string | undefined
106
+ }
107
+
108
+ if (contentType.includes('multipart/form-data')) {
109
+ const { fields } = await ctx.multipart()
110
+ return fields[field]
111
+ }
112
+
113
+ return undefined
114
+ }
115
+
116
+ function safeEqual(a: string, b: string): boolean {
117
+ const aBuf = Buffer.from(a)
118
+ const bBuf = Buffer.from(b)
119
+ if (aBuf.length !== bBuf.length) return false
120
+ return timingSafeEqual(aBuf, bBuf)
121
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "declaration": true,
8
+ "declarationMap": true,
9
+ "sourceMap": true,
10
+ "outDir": "./dist",
11
+ "rootDir": "./src",
12
+ "skipLibCheck": true,
13
+ "lib": ["ESNext"],
14
+ "types": ["node"]
15
+ },
16
+ "include": ["src/**/*"]
17
+ }