@cslug/security 0.0.0 → 0.10.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 ADDED
@@ -0,0 +1,10 @@
1
+ # @cslug/security
2
+
3
+ A Content-Security-Policy with a new nonce per request (`<Assets>` from `@cslug/vue` puts it on its tags), one rate
4
+ limit over every request from an IP, an IP filter with CIDR ranges (IPv4 and IPv6), `/.well-known/security.txt`
5
+ (RFC 9116), account lockout on `@cslug/auth`'s login events, `notBreached()` for passwords (HaveIBeenPwned,
6
+ k-anonymity), and an audit log on `@cslug/database` with auth events recorded. `cslug add security` installs it, lists `SecurityProvider` and writes
7
+ `config/security.ts`.
8
+
9
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
10
+ [guide 24](../../guides/24-security.md).
package/docs/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @cslug/security
2
+
3
+ `SecurityProvider` reads `config/security.ts` and adds global middleware, in this order: the IP filter, the per-IP
4
+ limit, then the Content-Security-Policy. With `@cslug/auth` it adds account lockout; with `@cslug/database`, the
5
+ audit log (and records auth events). List it after `HttpProvider`. The rest of an app's defences (security
6
+ headers, CSRF, `throttle()`, signed URLs, password hashing) are in `@cslug/http` and `@cslug/auth`.
7
+
8
+ ## Configuration
9
+
10
+ ```ts
11
+ // config/security.ts
12
+ export default defineConfig({
13
+ csp: {
14
+ directives: { 'img-src': ["'self'", 'data:', 'https://images.example.com'], 'font-src': false },
15
+ reportOnly: false,
16
+ reportUri: '/csp-reports',
17
+ }, // default: on with the default policy; false: off
18
+ limit: '600/min', // default: off
19
+ ipFilter: { allow: ['10.0.0.0/8'], deny: ['10.6.6.0/24'] },
20
+ securityTxt: { contact: 'mailto:security@example.com', expires: '2027-06-30', preferredLanguages: ['en', 'fr'] },
21
+ lockout: { attempts: 5, decay: '15m' }, // default: off
22
+ audit: { keep: '365d', auth: true }, // default: on with @cslug/database; false: off
23
+ })
24
+ ```
25
+
26
+ Behind a load balancer, set `http.trustedProxies`: the limit and the filter use `ctx.request.ip()`.
27
+
28
+ ## Content Security Policy
29
+
30
+ `csp()` makes a 16-byte nonce per request, sets `ctx.nonce`, and the header on the response (error pages
31
+ included). The default policy:
32
+
33
+ ```
34
+ default-src 'self'; script-src 'self' 'nonce-…'; style-src 'self' 'nonce-…'; style-src-attr 'unsafe-inline';
35
+ img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self';
36
+ form-action 'self'; frame-ancestors 'none'
37
+ ```
38
+
39
+ plus `upgrade-insecure-requests` when `app.env` is `production`. `directives` replaces a directive's sources, and
40
+ `false` removes it; the nonce is always added to `script-src` and `style-src`. A response that sets its own
41
+ `Content-Security-Policy` keeps it.
42
+
43
+ `<Assets>` adds the nonce to its `<script>` and `<style>` tags, the component styles and the `cslug dev` client. Your
44
+ own inline tags take it from `useRequest().nonce`:
45
+
46
+ ```vue
47
+ <script setup lang="ts">
48
+ const { nonce } = useRequest()
49
+ </script>
50
+ <template>
51
+ <script :nonce="nonce" src="https://plausible.io/js/script.js" defer />
52
+ </template>
53
+ ```
54
+
55
+ Only on some routes: `csp: false`, then `r.group({ middleware: [csp({ … })] }, …)`.
56
+
57
+ ## IP filter and per-IP limit
58
+
59
+ `ipFilter({ allow, deny })` answers 403 `security.ip_denied` to an address in `deny`, or outside `allow` when it is
60
+ given. Entries are addresses or CIDR ranges, IPv4 or IPv6; an IPv4-mapped IPv6 address (`::ffff:10.0.0.1`) is
61
+ matched as IPv4. `ipInRange(ip, ranges)` is the check on its own.
62
+
63
+ `ipLimit('600/min', { except })` counts every request per IP in the `RateLimiter` (shared across processes with
64
+ `@cslug/redis`) and answers 429 with `Retry-After` past the limit. Paths in `except` (default `['/health/']`) are not
65
+ counted. Assets served from `public/` count, so leave room for them.
66
+
67
+ ## security.txt
68
+
69
+ With `securityTxt`, `GET /.well-known/security.txt` answers `text/plain`: `Contact` (required, one or more),
70
+ `Expires` (default: a year after the process started), then `Encryption`, `Acknowledgments`,
71
+ `Preferred-Languages`, `Policy`, `Hiring` and `Canonical` (default: `app.url`'s). A missing contact or an invalid
72
+ `expires` fails at boot.
73
+
74
+ ## Account lockout
75
+
76
+ With `lockout` and `@cslug/auth`: a `LoginAttempting` listener refuses a locked email with `AccountLockedError`
77
+ (423 `security.account_locked`, `params.retryAfter`); `LoginFailed` (wrong password, known or unknown email)
78
+ counts a failure; at `attempts` within `decay` the email is locked for `decay` and `AccountLocked`
79
+ `{ email, userId?, ip, until }` is emitted (listen to it to tell the owner). `LoginSucceeded` in the same request
80
+ resets the count. Counts and locks are in the `Cache`.
81
+
82
+ `Lockout` (injectable): `lockedUntil(email)`, `assertUnlocked(email)`, `failed(email, { userId, ip })`,
83
+ `succeeded(email)`, `unlock(email)`.
84
+
85
+ ## Breached passwords
86
+
87
+ ```ts
88
+ password: v.string().min(12).refineAsync(notBreached(), { message: 'validation.password_breached' })
89
+ ```
90
+
91
+ `notBreached({ threshold = 1, timeout = '2s' })` asks `api.pwnedpasswords.com/range/<first 5 of SHA-1>` with
92
+ `Add-Padding: true` and looks for the rest of the hash in the answer. Down or slow: the password passes and
93
+ `security.breached_passwords_unavailable` is logged. `BreachedPasswords.count(password)` gives the number;
94
+ `BreachedPasswords.fake(['password123'])` in tests (returns a restore function; `{ unavailable: true }` simulates
95
+ an outage).
96
+
97
+ ## Audit log
98
+
99
+ `cslug_audit_log` (migration `00000000_000700`): `id` (UUIDv7), `action`, `user_id`, `subject_type`, `subject_id`,
100
+ `ip`, `request_id`, `data` (jsonb), `created_at`.
101
+
102
+ ```ts
103
+ await audit.record('booking.refunded', { subject: { type: 'booking', id: booking.id }, data: { amount } })
104
+ await audit.for({ type: 'booking', id: booking.id }) // newest first, { limit } (default 100)
105
+ await audit.byUser(user.id)
106
+ await audit.prune('90d') // default: audit.keep
107
+ ```
108
+
109
+ `record()` takes the user (`userId` overrides it, `null` for none), IP and request id from the context and runs on
110
+ the ambient transaction. `data` is copied JSON-safe (bigint as string, dates as ISO) with keys containing
111
+ `password`, `secret`, `token`, `authorization`, `cookie`, `apikey`, `cardnumber` or `cvv` redacted. Auth events are
112
+ recorded under their event names; a failure to record one is logged, never thrown into the login.
113
+
114
+ `cslug audit:prune` deletes entries older than `audit.keep`. Without `@cslug/database`, `Audit` throws
115
+ `security.audit_needs_database`.
package/docs/api.md ADDED
@@ -0,0 +1,28 @@
1
+ # @cslug/security API
2
+
3
+ | Export | |
4
+ |---|---|
5
+ | `SecurityProvider` | Adds `ipFilter`, `ipLimit` and `csp` as global middleware from `config/security.ts`, and the `security.txt` route |
6
+ | `SecurityConfig` | `{ csp?: CspOptions \| false, limit?: RateLimit \| false, ipFilter?: IpFilterOptions, securityTxt?: SecurityTxtOptions \| false, lockout?: LockoutOptions \| false, audit?: { keep?, auth? } \| false }` |
7
+ | `csp(options?)` | Middleware: a nonce per request on `ctx.nonce`, and the `Content-Security-Policy` (or `-Report-Only`) header |
8
+ | `CspOptions` | `{ directives?: Record<string, string[] \| false>, reportOnly?: boolean, reportUri?: string }` |
9
+ | `cspPolicy(nonce, options?, production?)` | The policy text |
10
+ | `newNonce()` | 16 random bytes, base64 |
11
+ | `ipFilter({ allow?, deny? })` | Middleware: 403 `security.ip_denied` |
12
+ | `ipInRange(ip, ranges)` | Whether an address is in a list of addresses and CIDR ranges (IPv4, IPv6) |
13
+ | `ipLimit(limit, { except? })` | Middleware: one rate limit per IP over every request; 429 with `Retry-After` |
14
+ | `securityTxt(options, { expires, canonical? })` | The body of `security.txt` (RFC 9116) |
15
+ | `Lockout` | `lockedUntil(email)`, `assertUnlocked(email)`, `failed(email, info?)`, `succeeded(email)`, `unlock(email)` |
16
+ | `LockoutOptions` | `{ attempts?: number (5), decay?: Duration ('15m') }` |
17
+ | `AccountLocked` | Event `security.account_locked`: `{ email, userId?, ip, until }` |
18
+ | `AccountLockedError` | 423 `security.account_locked`, `params.retryAfter` |
19
+ | `notBreached({ threshold?, timeout? })` | `(password) => Promise<boolean>` for `refineAsync`; fails open |
20
+ | `BreachedPasswords` | `count(password, { timeout? })` (undefined when unavailable), `fake(passwords, { unavailable? })` |
21
+ | `Audit` | `record(action, { subject?, data?, userId? })`, `for(subject, { limit? })`, `byUser(id, { limit? })`, `prune(olderThan?)`, `keep` |
22
+ | `AuditEntry`, `AuditSubject`, `AuditStore` | An entry; `{ type, id }`; the storage interface (`store` on `Audit`) |
23
+ | `AuditPruneCommand` | `cslug audit:prune` |
24
+ | `AUDIT_MIGRATIONS` | The migrations folder (`cslug_audit_log`) |
25
+ | `SecurityTxtOptions` | `contact` (required), `expires`, `encryption`, `acknowledgments`, `preferredLanguages`, `policy`, `hiring`, `canonical` |
26
+
27
+ Errors: `security.ip_denied` (403), `http.too_many_requests` (429), `security.account_locked` (423),
28
+ `security.audit_needs_database`, `security.txt_contact` and `security.txt_expires` (at boot).
@@ -0,0 +1,18 @@
1
+ -- up
2
+ create table cslug_audit_log (
3
+ id uuid primary key,
4
+ action text not null,
5
+ user_id text,
6
+ subject_type text,
7
+ subject_id text,
8
+ ip text,
9
+ request_id text,
10
+ data jsonb,
11
+ created_at timestamptz not null default now()
12
+ );
13
+ create index cslug_audit_log_subject_idx on cslug_audit_log (subject_type, subject_id, created_at desc);
14
+ create index cslug_audit_log_user_idx on cslug_audit_log (user_id, created_at desc);
15
+ create index cslug_audit_log_created_idx on cslug_audit_log (created_at);
16
+
17
+ -- down
18
+ drop table cslug_audit_log;
package/package.json CHANGED
@@ -1 +1,57 @@
1
- {"name":"@cslug/security","version":"0.0.0","description":"Placeholder: the real package is published by the cslug release workflow.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/cslugts/cslug.git","directory":"packages/security"}}
1
+ {
2
+ "name": "@cslug/security",
3
+ "version": "0.10.0",
4
+ "description": "Content-Security-Policy nonces, IP filter and per-IP limit, security.txt, account lockout, breached passwords and an audit log for cslug apps.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/security"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/security",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework",
17
+ "security",
18
+ "csp",
19
+ "nonce",
20
+ "security.txt",
21
+ "audit-log",
22
+ "lockout",
23
+ "haveibeenpwned"
24
+ ],
25
+ "exports": {
26
+ ".": "./src/index.ts"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "migrations",
31
+ "docs",
32
+ "README.md"
33
+ ],
34
+ "engines": {
35
+ "bun": ">=1.3.14"
36
+ },
37
+ "peerDependencies": {
38
+ "@cslug/core": "0.10.0",
39
+ "@cslug/http": "0.10.0",
40
+ "@cslug/database": "0.10.0",
41
+ "@cslug/auth": "0.10.0"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "@cslug/database": {
45
+ "optional": true
46
+ },
47
+ "@cslug/auth": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "devDependencies": {
52
+ "@cslug/auth": "workspace:*",
53
+ "@cslug/database": "workspace:*",
54
+ "@cslug/testing": "workspace:*",
55
+ "@cslug/validation": "workspace:*"
56
+ }
57
+ }
package/src/audit.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { join } from 'node:path'
2
+ import {
3
+ Clock,
4
+ Command,
5
+ type Container,
6
+ CslugError,
7
+ currentContext,
8
+ DEFAULT_REDACT,
9
+ type Duration,
10
+ resolve,
11
+ } from '@cslug/core'
12
+
13
+ /** The `cslug_audit_log` migration (registered with @cslug/database). */
14
+ export const AUDIT_MIGRATIONS = join(import.meta.dir, '../migrations')
15
+
16
+ /** What an entry is about: `{ type: 'booking', id: booking.id }`. */
17
+ export type AuditSubject = { type: string; id: string | number | bigint }
18
+
19
+ export type AuditEntry = {
20
+ id: string
21
+ action: string
22
+ userId: string | null
23
+ subjectType: string | null
24
+ subjectId: string | null
25
+ ip: string | null
26
+ requestId: string | null
27
+ data: Record<string, unknown> | null
28
+ createdAt: Date
29
+ }
30
+
31
+ /** Where entries go: `SecurityProvider` sets one on @cslug/database. */
32
+ export type AuditStore = {
33
+ insert(entry: Omit<AuditEntry, 'createdAt'>): Promise<void>
34
+ list(where: { subject?: AuditSubject; userId?: string }, limit: number): Promise<AuditEntry[]>
35
+ prune(before: Date): Promise<number>
36
+ }
37
+
38
+ const redacted = (key: string) => DEFAULT_REDACT.some((r) => key.toLowerCase().includes(r))
39
+
40
+ /** A JSON-safe copy with secret-looking keys redacted (as in logs). */
41
+ function clean(value: unknown, depth = 0): unknown {
42
+ if (value === null || value === undefined) return null
43
+ if (typeof value === 'bigint') return value.toString()
44
+ if (value instanceof Date) return value.toISOString()
45
+ if (typeof value !== 'object') return value
46
+ if (depth > 8) return '[deep]'
47
+ if (Array.isArray(value)) return value.map((v) => clean(v, depth + 1))
48
+ const out: Record<string, unknown> = {}
49
+ for (const [k, v] of Object.entries(value)) out[k] = redacted(k) ? '[redacted]' : clean(v, depth + 1)
50
+ return out
51
+ }
52
+
53
+ /**
54
+ * The audit log: who did what, when, from where. `record()` takes the user, IP and request id from the context,
55
+ * and writes in the current transaction (a rolled-back change leaves no entry).
56
+ */
57
+ export class Audit {
58
+ store?: AuditStore
59
+
60
+ constructor(
61
+ private readonly container: Container,
62
+ readonly keep: Duration = '365d',
63
+ ) {}
64
+
65
+ private get db(): AuditStore {
66
+ if (!this.store) throw new CslugError('security.audit_needs_database', 'The audit log needs @cslug/database')
67
+ return this.store
68
+ }
69
+
70
+ async record(
71
+ action: string,
72
+ options: { subject?: AuditSubject; data?: Record<string, unknown>; userId?: string | null } = {},
73
+ ): Promise<void> {
74
+ const ctx = currentContext()
75
+ const http = ctx?.http as { request?: { ip(): string | undefined } } | undefined
76
+ const userId = options.userId === undefined ? (ctx?.userId as string | undefined) : options.userId
77
+ await this.db.insert({
78
+ id: Bun.randomUUIDv7(),
79
+ action,
80
+ userId: userId == null ? null : String(userId),
81
+ subjectType: options.subject?.type ?? null,
82
+ subjectId: options.subject ? String(options.subject.id) : null,
83
+ ip: http?.request?.ip() ?? null,
84
+ requestId: (ctx?.requestId as string | undefined) ?? null,
85
+ data: options.data ? (clean(options.data) as Record<string, unknown>) : null,
86
+ })
87
+ }
88
+
89
+ /** Entries about a subject, newest first. */
90
+ for(subject: AuditSubject, options: { limit?: number } = {}): Promise<AuditEntry[]> {
91
+ return this.db.list({ subject }, options.limit ?? 100)
92
+ }
93
+
94
+ /** Entries by a user, newest first. */
95
+ byUser(userId: string, options: { limit?: number } = {}): Promise<AuditEntry[]> {
96
+ return this.db.list({ userId: String(userId) }, options.limit ?? 100)
97
+ }
98
+
99
+ /** Delete entries older than `olderThan` (default: `security.audit.keep`, 365 days). Returns how many. */
100
+ prune(olderThan: Duration = this.keep): Promise<number> {
101
+ return this.db.prune(this.container.resolve(Clock).subtract(olderThan))
102
+ }
103
+ }
104
+
105
+ /** `cslug audit:prune`: delete audit entries older than `security.audit.keep`. Schedule it daily. */
106
+ export class AuditPruneCommand extends Command {
107
+ static signature = 'audit:prune'
108
+ static description = 'Delete audit log entries older than security.audit.keep'
109
+
110
+ async handle() {
111
+ const audit = resolve(Audit)
112
+ const deleted = await audit.prune()
113
+ this.success(`Deleted ${deleted} audit entr${deleted === 1 ? 'y' : 'ies'} older than ${audit.keep}`)
114
+ return 0
115
+ }
116
+ }
@@ -0,0 +1,84 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { currentApp, type Duration, Logger, parseDuration } from '@cslug/core'
3
+
4
+ type Range = (prefix: string, signal: AbortSignal) => Promise<string>
5
+
6
+ const hibp: Range = async (prefix, signal) => {
7
+ const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`, {
8
+ headers: { 'add-padding': 'true', 'user-agent': 'cslug' },
9
+ signal,
10
+ })
11
+ if (!res.ok) throw new Error(`HaveIBeenPwned answered ${res.status}`)
12
+ return res.text()
13
+ }
14
+
15
+ const sha1 = (password: string) => createHash('sha1').update(password).digest('hex').toUpperCase()
16
+
17
+ const warn = (message: string, fields: Record<string, unknown>) => {
18
+ try {
19
+ currentApp().resolve(Logger).warn(message, fields)
20
+ } catch {
21
+ console.warn(message, fields)
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Passwords seen in public breaches, through HaveIBeenPwned's range API (k-anonymity: only the first 5 characters of
27
+ * the password's SHA-1 leave the server, and the answer is padded).
28
+ */
29
+ // biome-ignore lint/complexity/noStaticOnlyClass: the name guide 24 documents (`BreachedPasswords.fake()`)
30
+ export class BreachedPasswords {
31
+ private static range: Range = hibp
32
+
33
+ /** How many times the password appears in breaches (0: never), or undefined when the API could not answer. */
34
+ static async count(password: string, options: { timeout?: Duration } = {}): Promise<number | undefined> {
35
+ const hash = sha1(password)
36
+ try {
37
+ const body = await BreachedPasswords.range(
38
+ hash.slice(0, 5),
39
+ AbortSignal.timeout(parseDuration(options.timeout ?? '2s')),
40
+ )
41
+ for (const line of body.split('\n')) {
42
+ const [suffix, count] = line.trim().split(':')
43
+ if (suffix?.toUpperCase() === hash.slice(5)) return Number(count) || 0
44
+ }
45
+ return 0
46
+ } catch (error) {
47
+ warn('security.breached_passwords_unavailable', { error: (error as Error).message })
48
+ return undefined
49
+ }
50
+ }
51
+
52
+ /** In tests: only `passwords` count as breached, and nothing is sent. Returns a function that restores the API. */
53
+ static fake(passwords: string[] = [], options: { unavailable?: boolean } = {}): () => void {
54
+ const previous = BreachedPasswords.range
55
+ const hashes = passwords.map(sha1)
56
+ BreachedPasswords.range = async (prefix) => {
57
+ if (options.unavailable) throw new Error('unavailable (fake)')
58
+ return hashes
59
+ .filter((h) => h.startsWith(prefix))
60
+ .map((h) => `${h.slice(5)}:1`)
61
+ .join('\r\n')
62
+ }
63
+ return () => {
64
+ BreachedPasswords.range = previous
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * A check for `refineAsync`: false when the password appears in at least `threshold` breaches (default 1). Fails
71
+ * open: when the API is down or slow, the password is accepted and a warning is logged.
72
+ *
73
+ * ```ts
74
+ * password: v.string().min(12).refineAsync(notBreached(), { message: 'validation.password_breached' })
75
+ * ```
76
+ */
77
+ export function notBreached(
78
+ options: { threshold?: number; timeout?: Duration } = {},
79
+ ): (password: string) => Promise<boolean> {
80
+ return async (password) => {
81
+ const count = await BreachedPasswords.count(password, options)
82
+ return count === undefined || count < (options.threshold ?? 1)
83
+ }
84
+ }
package/src/csp.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { MiddlewareFn } from '@cslug/http'
2
+
3
+ export type CspOptions = {
4
+ /** Sources per directive, replacing the default's; `false` removes a directive. */
5
+ directives?: Record<string, string[] | false>
6
+ /** Send `Content-Security-Policy-Report-Only`: the browser reports what it would block, and blocks nothing. */
7
+ reportOnly?: boolean
8
+ /** Where browsers post violation reports (`report-uri`). */
9
+ reportUri?: string
10
+ }
11
+
12
+ const DEFAULTS: Record<string, string[]> = {
13
+ 'default-src': ["'self'"],
14
+ 'script-src': ["'self'"],
15
+ 'style-src': ["'self'"],
16
+ // Vue's :style bindings render style attributes; inline <style> and <script> still need the nonce
17
+ 'style-src-attr': ["'unsafe-inline'"],
18
+ 'img-src': ["'self'", 'data:'],
19
+ 'font-src': ["'self'"],
20
+ 'connect-src': ["'self'"],
21
+ 'object-src': ["'none'"],
22
+ 'base-uri': ["'self'"],
23
+ 'form-action': ["'self'"],
24
+ 'frame-ancestors': ["'none'"],
25
+ }
26
+
27
+ /** The policy text for a nonce. */
28
+ export function cspPolicy(nonce: string, options: CspOptions = {}, production = false): string {
29
+ const directives: Record<string, string[] | false> = { ...DEFAULTS, ...options.directives }
30
+ if (production && !('upgrade-insecure-requests' in (options.directives ?? {})))
31
+ directives['upgrade-insecure-requests'] = []
32
+ if (options.reportUri) directives['report-uri'] = [options.reportUri]
33
+ const parts: string[] = []
34
+ for (const [name, sources] of Object.entries(directives)) {
35
+ if (sources === false) continue
36
+ const all = name === 'script-src' || name === 'style-src' ? [...sources, `'nonce-${nonce}'`] : sources
37
+ parts.push([name, ...all].join(' '))
38
+ }
39
+ return parts.join('; ')
40
+ }
41
+
42
+ /** 16 random bytes, base64. */
43
+ export function newNonce(): string {
44
+ return Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64')
45
+ }
46
+
47
+ /**
48
+ * A Content-Security-Policy with a new nonce per request: `ctx.nonce`, which `<Assets>` (@cslug/vue) adds to its
49
+ * tags. The header is on error responses too; a response that sets its own policy keeps it.
50
+ */
51
+ export const csp =
52
+ (options: CspOptions = {}): MiddlewareFn =>
53
+ (ctx, next) => {
54
+ const nonce = newNonce()
55
+ ctx.nonce = nonce
56
+ const header = options.reportOnly ? 'content-security-policy-report-only' : 'content-security-policy'
57
+ ctx.response.headers.set(header, cspPolicy(nonce, options, ctx.app.config('app.env') === 'production'))
58
+ return next()
59
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @cslug/security: a Content-Security-Policy with per-request nonces, a per-IP limit, an IP filter (CIDR, IPv4 and
3
+ * IPv6), `/.well-known/security.txt`, account lockout, the breached-password check and the audit log. Guide 24.
4
+ */
5
+ export {
6
+ AUDIT_MIGRATIONS,
7
+ Audit,
8
+ type AuditEntry,
9
+ AuditPruneCommand,
10
+ type AuditStore,
11
+ type AuditSubject,
12
+ } from './audit'
13
+ export { BreachedPasswords, notBreached } from './breached'
14
+ export { type CspOptions, csp, cspPolicy, newNonce } from './csp'
15
+ export { type IpFilterOptions, ipFilter, ipInRange } from './ip'
16
+ export { ipLimit } from './limit'
17
+ export { AccountLocked, AccountLockedError, Lockout, type LockoutOptions } from './lockout'
18
+ export { type SecurityConfig, SecurityProvider } from './provider'
19
+ export { type SecurityTxtOptions, securityTxt } from './security-txt'
package/src/ip.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { ForbiddenError } from '@cslug/core'
2
+ import type { MiddlewareFn } from '@cslug/http'
3
+
4
+ type Address = { v6: boolean; n: bigint }
5
+
6
+ function ipv4(text: string): bigint | undefined {
7
+ const parts = text.split('.')
8
+ if (parts.length !== 4 || parts.some((p) => !/^\d{1,3}$/.test(p) || Number(p) > 255)) return undefined
9
+ return parts.reduce((n, p) => n * 256n + BigInt(p), 0n)
10
+ }
11
+
12
+ function ipv6(text: string): bigint | undefined {
13
+ let groups = text
14
+ let tail: bigint | undefined
15
+ // an embedded IPv4 address at the end: ::ffff:1.2.3.4
16
+ const v4 = /(?:^|:)(\d{1,3}(?:\.\d{1,3}){3})$/.exec(groups)
17
+ if (v4) {
18
+ tail = ipv4(v4[1] as string)
19
+ if (tail === undefined) return undefined
20
+ groups = `${groups.slice(0, groups.length - (v4[1] as string).length)}0:0`
21
+ }
22
+ const halves = groups.split('::')
23
+ if (halves.length > 2) return undefined
24
+ const split = (s: string) => (s ? s.split(':') : [])
25
+ const head = split(halves[0] as string)
26
+ const rest = halves.length === 2 ? split(halves[1] as string) : []
27
+ const missing = 8 - head.length - rest.length
28
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return undefined
29
+ const all = [...head, ...Array<string>(halves.length === 2 ? missing : 0).fill('0'), ...rest]
30
+ if (all.some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) return undefined
31
+ const n = all.reduce((acc, g) => (acc << 16n) | BigInt(Number.parseInt(g, 16)), 0n)
32
+ return tail === undefined ? n : (n & ~0xffffffffn) | tail
33
+ }
34
+
35
+ /** An address as a number; IPv4-mapped IPv6 (`::ffff:1.2.3.4`) counts as IPv4. */
36
+ function parse(ip: string): Address | undefined {
37
+ const text = ip
38
+ .trim()
39
+ .replace(/^\[|\]$/g, '')
40
+ .replace(/%.*$/, '')
41
+ const four = ipv4(text)
42
+ if (four !== undefined) return { v6: false, n: four }
43
+ const six = text.includes(':') ? ipv6(text) : undefined
44
+ if (six === undefined) return undefined
45
+ if (six >> 32n === 0xffffn) return { v6: false, n: six & 0xffffffffn }
46
+ return { v6: true, n: six }
47
+ }
48
+
49
+ /** Whether `ip` is one of `ranges`: addresses or CIDR ranges, IPv4 or IPv6 (`10.0.0.0/8`, `2001:db8::/32`). */
50
+ export function ipInRange(ip: string | undefined, ranges: readonly string[]): boolean {
51
+ const address = ip ? parse(ip) : undefined
52
+ if (!address) return false
53
+ return ranges.some((entry) => {
54
+ const [base, bits] = entry.split('/') as [string, string | undefined]
55
+ const range = parse(base)
56
+ if (!range || range.v6 !== address.v6) return false
57
+ const width = address.v6 ? 128 : 32
58
+ const size = bits === undefined ? width : Number(bits)
59
+ if (!Number.isInteger(size) || size < 0 || size > width) return false
60
+ const shift = BigInt(width - size)
61
+ return address.n >> shift === range.n >> shift
62
+ })
63
+ }
64
+
65
+ export type IpFilterOptions = {
66
+ /** Only these addresses and ranges get in. */
67
+ allow?: string[]
68
+ /** These never do (checked first). */
69
+ deny?: string[]
70
+ }
71
+
72
+ /** 403 `security.ip_denied` for an address in `deny`, or outside `allow` when it is given. */
73
+ export const ipFilter =
74
+ (options: IpFilterOptions): MiddlewareFn =>
75
+ (ctx, next) => {
76
+ const ip = ctx.request.ip()
77
+ if ((options.deny && ipInRange(ip, options.deny)) || (options.allow && !ipInRange(ip, options.allow)))
78
+ throw new ForbiddenError('security.ip_denied', 'Access from this address is not allowed.')
79
+ return next()
80
+ }
package/src/limit.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type RateLimit, RateLimiter, TooManyRequestsError } from '@cslug/core'
2
+ import type { MiddlewareFn } from '@cslug/http'
3
+
4
+ /**
5
+ * One rate limit over every request from an IP (`'600/min'`), through the `RateLimiter` (shared with
6
+ * @cslug/redis). Past it: 429 with `Retry-After`. Paths starting with one of `except` are not counted.
7
+ */
8
+ export const ipLimit =
9
+ (limit: RateLimit, options: { except?: string[] } = {}): MiddlewareFn =>
10
+ async (ctx, next) => {
11
+ const ip = ctx.request.ip()
12
+ const except = options.except ?? ['/health/']
13
+ if (!ip || except.some((p) => ctx.request.path.startsWith(p))) return next()
14
+ const result = await ctx.resolve(RateLimiter).hit(`security:ip:${ip}`, limit)
15
+ if (!result.allowed) throw new TooManyRequestsError(result.retryAfter)
16
+ return next()
17
+ }
package/src/lockout.ts ADDED
@@ -0,0 +1,83 @@
1
+ import { AppError, Cache, Clock, type Container, type Duration, Event } from '@cslug/core'
2
+
3
+ /** An account was locked after too many failed passwords. Listen to it to tell the user. */
4
+ export class AccountLocked extends Event<{ email: string; userId?: string; ip: string | undefined; until: Date }>(
5
+ 'security.account_locked',
6
+ ) {}
7
+
8
+ /** 423: the account is locked until `until` (`retryAfter` in seconds). */
9
+ export class AccountLockedError extends AppError {
10
+ constructor(readonly until: Date) {
11
+ super('security.account_locked', 'This account is locked after too many failed attempts. Try again later.', {
12
+ status: 423,
13
+ params: { retryAfter: Math.max(1, Math.ceil((until.getTime() - Date.now()) / 1000)) },
14
+ })
15
+ }
16
+ }
17
+
18
+ export type LockoutOptions = {
19
+ /** Failed passwords before the account locks (default 5). */
20
+ attempts?: number
21
+ /** How long failures are counted, and how long the lock lasts (default `'15m'`). */
22
+ decay?: Duration
23
+ }
24
+
25
+ const normal = (email: string) => email.trim().toLowerCase()
26
+
27
+ /**
28
+ * Account lockout, per email (not per IP: it stops a slow guess spread over many addresses). Failures are counted in
29
+ * the `Cache` (shared through @cslug/redis). With @cslug/auth, `SecurityProvider` wires it to the login events.
30
+ */
31
+ export class Lockout {
32
+ constructor(
33
+ private readonly container: Container,
34
+ readonly options: LockoutOptions = {},
35
+ ) {}
36
+
37
+ // resolved on each use, so a swapped Cache or Clock (tests) is the one used
38
+ private get cache() {
39
+ return this.container.resolve(Cache)
40
+ }
41
+ private get clock() {
42
+ return this.container.resolve(Clock)
43
+ }
44
+
45
+ private get decay(): Duration {
46
+ return this.options.decay ?? '15m'
47
+ }
48
+
49
+ /** When the account's lock ends, or undefined if it is not locked. */
50
+ async lockedUntil(email: string): Promise<Date | undefined> {
51
+ const until = await this.cache.get<string>(`security:locked:${normal(email)}`)
52
+ return until ? new Date(until) : undefined
53
+ }
54
+
55
+ /** Throw `AccountLockedError` if the account is locked. */
56
+ async assertUnlocked(email: string): Promise<void> {
57
+ const until = await this.lockedUntil(email)
58
+ if (until) throw new AccountLockedError(until)
59
+ }
60
+
61
+ /** Count a failed password; locks the account (and emits `AccountLocked`) at the limit. True when it locked. */
62
+ async failed(email: string, info: { userId?: string; ip?: string } = {}): Promise<boolean> {
63
+ const key = normal(email)
64
+ const count = await this.cache.increment(`security:failures:${key}`, 1, this.decay)
65
+ if (count < (this.options.attempts ?? 5) || (await this.lockedUntil(key))) return false
66
+ const until = this.clock.add(this.decay)
67
+ await this.cache.set(`security:locked:${key}`, until.toISOString(), this.decay)
68
+ await this.cache.forget(`security:failures:${key}`)
69
+ await AccountLocked.emit({ email: key, ...(info.userId ? { userId: info.userId } : {}), ip: info.ip, until })
70
+ return true
71
+ }
72
+
73
+ /** Forget the failures (after a successful login). */
74
+ async succeeded(email: string): Promise<void> {
75
+ await this.cache.forget(`security:failures:${normal(email)}`)
76
+ }
77
+
78
+ /** Unlock an account now (support, an admin screen). */
79
+ async unlock(email: string): Promise<void> {
80
+ await this.cache.forget(`security:locked:${normal(email)}`)
81
+ await this.cache.forget(`security:failures:${normal(email)}`)
82
+ }
83
+ }
@@ -0,0 +1,188 @@
1
+ import {
2
+ type Application,
3
+ Clock,
4
+ currentContext,
5
+ type Duration,
6
+ EventBus,
7
+ type EventClass,
8
+ Logger,
9
+ type RateLimit,
10
+ ServiceProvider,
11
+ } from '@cslug/core'
12
+ import { HttpKernel, Router } from '@cslug/http'
13
+ import { AUDIT_MIGRATIONS, Audit, type AuditEntry, AuditPruneCommand, type AuditStore } from './audit'
14
+ import { type CspOptions, csp } from './csp'
15
+ import { type IpFilterOptions, ipFilter } from './ip'
16
+ import { ipLimit } from './limit'
17
+ import { AccountLocked, Lockout, type LockoutOptions } from './lockout'
18
+ import { type SecurityTxtOptions, securityTxt } from './security-txt'
19
+
20
+ export type SecurityConfig = {
21
+ /** A Content-Security-Policy with a per-request nonce on every response (default: on); false: off. */
22
+ csp?: CspOptions | false
23
+ /** One rate limit over every request from an IP (`'600/min'`); health checks are not counted. Default: off. */
24
+ limit?: RateLimit | false
25
+ /** Allow or deny addresses and CIDR ranges for the whole app. */
26
+ ipFilter?: IpFilterOptions
27
+ /** Serve `/.well-known/security.txt`. */
28
+ securityTxt?: SecurityTxtOptions | false
29
+ /** Lock an account after repeated failed passwords (with @cslug/auth). Default: off. */
30
+ lockout?: LockoutOptions | false
31
+ /**
32
+ * The audit log (with @cslug/database). `keep`: how long `audit:prune` keeps entries (default `'365d'`);
33
+ * `auth: false` stops recording auth events.
34
+ */
35
+ audit?: { keep?: Duration; auth?: boolean } | false
36
+ }
37
+
38
+ /** A login event's payload, as far as this package reads it. */
39
+ type AuthPayload = { email?: string; userId?: string; ip?: string; reason?: string; tokenId?: string } & Record<
40
+ string,
41
+ unknown
42
+ >
43
+ type AuthEvent = EventClass<AuthPayload> & { readonly eventName: string }
44
+ /**
45
+ * @cslug/auth's events, loaded at runtime with a local type: importing its types would load a second copy of its
46
+ * `HttpContext` augmentation when the workspace is reachable through two paths (as in @cslug/testing).
47
+ */
48
+ type AuthEvents = Record<
49
+ | 'LoginAttempting'
50
+ | 'LoginFailed'
51
+ | 'LoginSucceeded'
52
+ | 'LoggedOut'
53
+ | 'TwoFactorEnabled'
54
+ | 'TwoFactorDisabled'
55
+ | 'RecoveryCodesRegenerated'
56
+ | 'TokenCreated'
57
+ | 'TokenRevoked',
58
+ AuthEvent
59
+ >
60
+ const importOptional = <M>(name: string): Promise<M> => import(name)
61
+
62
+ /** Rows in the ambient transaction, through @cslug/database. */
63
+ async function databaseStore(app: Application): Promise<AuditStore | undefined> {
64
+ const db = await import('@cslug/database').catch(() => undefined)
65
+ if (!db || !app.has(db.Database)) return undefined
66
+ db.addMigrations(AUDIT_MIGRATIONS)
67
+ const { sql } = db
68
+ const database = () => app.resolve(db.Database)
69
+ return {
70
+ insert: async (e) => {
71
+ await database().exec(sql`insert into cslug_audit_log
72
+ (id, action, user_id, subject_type, subject_id, ip, request_id, data)
73
+ values (${e.id}, ${e.action}, ${e.userId}, ${e.subjectType}, ${e.subjectId}, ${e.ip}, ${e.requestId},
74
+ ${e.data === null ? null : sql.json(e.data)})`)
75
+ },
76
+ list: (where, limit) =>
77
+ database().many<AuditEntry>(
78
+ sql`select * from cslug_audit_log where ${
79
+ where.subject
80
+ ? sql`subject_type = ${where.subject.type} and subject_id = ${String(where.subject.id)}`
81
+ : sql`user_id = ${where.userId ?? null}`
82
+ } order by created_at desc, id desc limit ${limit}`,
83
+ ),
84
+ prune: (before) => database().exec(sql`delete from cslug_audit_log where created_at < ${before}`),
85
+ }
86
+ }
87
+
88
+ /**
89
+ * From `config/security.ts`: global middleware (IP filter, then the per-IP limit, then CSP),
90
+ * `/.well-known/security.txt`, account lockout on @cslug/auth's login events, and the audit log on
91
+ * @cslug/database (auth events recorded). List it after `HttpProvider`.
92
+ */
93
+ export class SecurityProvider extends ServiceProvider {
94
+ private config(): SecurityConfig {
95
+ return this.app.config<SecurityConfig | undefined>('security') ?? {}
96
+ }
97
+
98
+ register() {
99
+ const { lockout, audit } = this.config()
100
+ this.app.singleton(Lockout, () => new Lockout(this.app, lockout || {}))
101
+ this.app.singleton(Audit, () => new Audit(this.app, audit ? audit.keep : undefined))
102
+ this.commands([AuditPruneCommand])
103
+ }
104
+
105
+ async boot() {
106
+ const config = this.config()
107
+ const kernel = this.app.resolve(HttpKernel)
108
+ if (config.ipFilter?.allow || config.ipFilter?.deny) kernel.global.push(ipFilter(config.ipFilter))
109
+ if (config.limit) kernel.global.push(ipLimit(config.limit))
110
+ if (config.csp !== false) kernel.global.push(csp(config.csp ?? {}))
111
+ if (config.securityTxt) this.securityTxtRoute(config.securityTxt)
112
+
113
+ const audit = this.app.resolve(Audit)
114
+ if (config.audit !== false) audit.store = await databaseStore(this.app)
115
+ const authEvents = await importOptional<AuthEvents>('@cslug/auth').catch(() => undefined)
116
+ if (!authEvents) return
117
+ if (config.lockout) this.lockout(authEvents)
118
+ if (audit.store && config.audit !== false && config.audit?.auth !== false) this.recordAuth(authEvents, audit)
119
+ }
120
+
121
+ /** Refuse a locked account before its password is checked; count failed passwords; reset after a login. */
122
+ private lockout(a: AuthEvents) {
123
+ const bus = this.app.resolve(EventBus)
124
+ const lockout = this.app.resolve(Lockout)
125
+ // the email of this request's login attempt, to reset its failures when it succeeds
126
+ const attempts = new WeakMap<object, string>()
127
+ bus.on(a.LoginAttempting, async ({ email }) => {
128
+ if (!email) return
129
+ await lockout.assertUnlocked(email)
130
+ const ctx = currentContext()
131
+ if (ctx) attempts.set(ctx, email)
132
+ })
133
+ bus.on(a.LoginFailed, async ({ reason, email, userId, ip }) => {
134
+ if (reason === 'credentials' && email) await lockout.failed(email, { userId, ip })
135
+ })
136
+ bus.on(a.LoginSucceeded, async () => {
137
+ const ctx = currentContext()
138
+ const email = ctx && attempts.get(ctx)
139
+ if (email) await lockout.succeeded(email)
140
+ })
141
+ }
142
+
143
+ /** Each auth event becomes an entry (action: the event's name); a failure to record is logged, not thrown. */
144
+ private recordAuth(a: AuthEvents, audit: Audit) {
145
+ const bus = this.app.resolve(EventBus)
146
+ const log = this.app.resolve(Logger)
147
+ const events: AuthEvent[] = [
148
+ a.LoginSucceeded,
149
+ a.LoginFailed,
150
+ a.LoggedOut,
151
+ a.TwoFactorEnabled,
152
+ a.TwoFactorDisabled,
153
+ a.RecoveryCodesRegenerated,
154
+ a.TokenCreated,
155
+ a.TokenRevoked,
156
+ AccountLocked as unknown as AuthEvent,
157
+ ]
158
+ for (const event of events) {
159
+ const action = event.eventName
160
+ bus.on(event, async (payload) => {
161
+ const { userId, ip: _ip, tokenId, ...data } = payload
162
+ try {
163
+ await audit.record(action, {
164
+ ...(userId !== undefined ? { userId: userId ?? null } : {}),
165
+ ...(tokenId ? { subject: { type: 'access_token', id: tokenId } } : {}),
166
+ ...(Object.keys(data).length ? { data } : {}),
167
+ })
168
+ } catch (error) {
169
+ log.error('security.audit_failed', { action, error })
170
+ }
171
+ })
172
+ }
173
+ }
174
+
175
+ private securityTxtRoute(options: SecurityTxtOptions) {
176
+ const url = this.app.config<string | undefined>('app.url')
177
+ const body = securityTxt(options, {
178
+ expires: this.app.resolve(Clock).add('365d'),
179
+ canonical: url ? new URL('/.well-known/security.txt', url).toString() : undefined,
180
+ })
181
+ this.app.resolve(Router).load((r) => {
182
+ r.get(
183
+ '/.well-known/security.txt',
184
+ () => new Response(body, { headers: { 'content-type': 'text/plain; charset=utf-8' } }),
185
+ ).name('security.txt')
186
+ })
187
+ }
188
+ }
@@ -0,0 +1,39 @@
1
+ import { CslugError } from '@cslug/core'
2
+
3
+ export type SecurityTxtOptions = {
4
+ /** Where to report a vulnerability: `mailto:` or `https:` URLs (required). */
5
+ contact: string | string[]
6
+ /** When the file is stale (default: a year after the process started). */
7
+ expires?: Date | string
8
+ encryption?: string | string[]
9
+ acknowledgments?: string | string[]
10
+ /** Languages reports may be written in (`['en', 'fr']`). */
11
+ preferredLanguages?: string | string[]
12
+ policy?: string | string[]
13
+ hiring?: string | string[]
14
+ /** Default: `<app.url>/.well-known/security.txt`. */
15
+ canonical?: string | string[]
16
+ }
17
+
18
+ const list = (value: string | string[] | undefined) => (value === undefined ? [] : [value].flat())
19
+
20
+ /** The body of `/.well-known/security.txt` (RFC 9116). */
21
+ export function securityTxt(options: SecurityTxtOptions, defaults: { expires: Date; canonical?: string }): string {
22
+ const contacts = list(options.contact)
23
+ if (!contacts.length)
24
+ throw new CslugError('security.txt_contact', 'security.securityTxt needs a contact (mailto: or https: URL)')
25
+ const expires = options.expires === undefined ? defaults.expires : new Date(options.expires)
26
+ if (Number.isNaN(expires.getTime()))
27
+ throw new CslugError('security.txt_expires', `security.securityTxt.expires is not a date: ${options.expires}`)
28
+ const lines = [
29
+ ...contacts.map((c) => `Contact: ${c}`),
30
+ `Expires: ${expires.toISOString()}`,
31
+ ...list(options.encryption).map((v) => `Encryption: ${v}`),
32
+ ...list(options.acknowledgments).map((v) => `Acknowledgments: ${v}`),
33
+ ...(options.preferredLanguages ? [`Preferred-Languages: ${list(options.preferredLanguages).join(', ')}`] : []),
34
+ ...list(options.policy).map((v) => `Policy: ${v}`),
35
+ ...list(options.hiring).map((v) => `Hiring: ${v}`),
36
+ ...list(options.canonical ?? defaults.canonical).map((v) => `Canonical: ${v}`),
37
+ ]
38
+ return `${lines.join('\n')}\n`
39
+ }