raiton 6.5.0-beta.13 → 6.6.0-beta.14
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/CHANGELOG.md +21 -0
- package/build/bin/index.mjs +1278 -1222
- package/docs/contributors/framework/plugins/csrf.md +277 -0
- package/docs/contributors/framework/plugins/security.md +40 -6
- package/docs/user-guide/README.md +7 -4
- package/docs/user-guide/best-practices.md +1 -0
- package/docs/user-guide/csrf.md +557 -0
- package/docs/user-guide/decorators/README.md +2 -0
- package/docs/user-guide/decorators/health-check.md +125 -0
- package/docs/user-guide/health-check.md +117 -0
- package/docs/user-guide/security.md +8 -2
- package/package.json +1 -1
- package/source/core/application.ts +1 -1
- package/source/core/controller/builder.ts +23 -0
- package/source/core/thread.ts +5 -1
- package/source/framework/artifacts.ts +3 -0
- package/source/framework/constants/decorators.constant.ts +2 -0
- package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
- package/source/framework/decorators/csrf-token.decorator.ts +20 -0
- package/source/framework/decorators/health-check.decorator.ts +50 -0
- package/source/framework/decorators/index.ts +3 -0
- package/source/framework/enums/csrf.enum.ts +4 -0
- package/source/framework/enums/index.ts +2 -1
- package/source/framework/health-check.ts +137 -0
- package/source/framework/index.ts +1 -0
- package/source/framework/plugins/security/csrf.ts +145 -0
- package/source/framework/plugins/security/index.ts +2 -0
- package/source/framework/utilities/artifact.util.ts +4 -0
- package/source/framework/utilities/csrf.util.ts +162 -0
- package/source/framework/utilities/index.ts +2 -1
- package/source/types/application.ts +1 -1
- package/source/types/csrf.ts +38 -0
- package/source/types/index.ts +2 -1
- package/source/types/runtime.ts +1 -1
- /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
- /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import {definePlugin} from "../../../core/plugins";
|
|
3
|
+
import {MiddlewareParametersInterface} from "../../../types";
|
|
4
|
+
import {RaitonResponses, HttpStatus} from "../..";
|
|
5
|
+
import {CsrfUtil} from "../../utilities/csrf.util";
|
|
6
|
+
import {CSRFModeEnum} from "../../enums";
|
|
7
|
+
import type {CsrfOptions, CsrfCookieOptions} from "../../../types";
|
|
8
|
+
|
|
9
|
+
const DEFAULT_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']
|
|
10
|
+
const DEFAULT_COOKIE_NAME = '_csrf'
|
|
11
|
+
const DEFAULT_HEADER_NAME = 'X-CSRF-Token'
|
|
12
|
+
const DEFAULT_TTL = 3600_000
|
|
13
|
+
|
|
14
|
+
export const secureCsrf = (opts: CsrfOptions = {}) => {
|
|
15
|
+
|
|
16
|
+
return definePlugin((scope) => {
|
|
17
|
+
const mode = opts.mode ?? CSRF_MODE_DEFAULT
|
|
18
|
+
const secret = opts.secret ?? cryptoRandomSecret()
|
|
19
|
+
const cookieName = opts.cookieName ?? DEFAULT_COOKIE_NAME
|
|
20
|
+
const headerName = opts.headerName ?? DEFAULT_HEADER_NAME
|
|
21
|
+
const ttl = opts.ttl ?? DEFAULT_TTL
|
|
22
|
+
const methods = (opts.methods ?? DEFAULT_METHODS).map(m => m.toUpperCase())
|
|
23
|
+
const skipPaths = opts.skip ?? []
|
|
24
|
+
const cookieOpts: CsrfCookieOptions = {
|
|
25
|
+
httpOnly: false,
|
|
26
|
+
secure: false,
|
|
27
|
+
sameSite: 'lax',
|
|
28
|
+
path: '/',
|
|
29
|
+
...opts.cookieOptions,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const tokenStore = mode === CSRF_MODE_SYNCHRONIZER
|
|
33
|
+
? CsrfUtil.createTokenStore(ttl)
|
|
34
|
+
: undefined
|
|
35
|
+
|
|
36
|
+
const destroy = () => {
|
|
37
|
+
tokenStore?.destroy()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
scope.addHook('onResponse', async (ctx: any) => {
|
|
41
|
+
if (ctx && typeof ctx === 'object' && 'reply' in ctx) {
|
|
42
|
+
const method = (ctx.req?.method ?? '').toUpperCase()
|
|
43
|
+
if (methods.includes(method)) {
|
|
44
|
+
const token = tokenStore
|
|
45
|
+
? tokenStore.create()
|
|
46
|
+
: CsrfUtil.generateDoubleSubmitToken(secret)
|
|
47
|
+
|
|
48
|
+
ctx.state = ctx.state ?? {}
|
|
49
|
+
ctx.state.csrfToken = token
|
|
50
|
+
|
|
51
|
+
ctx.reply.header(
|
|
52
|
+
'Set-Cookie',
|
|
53
|
+
CsrfUtil.serializeCookie(cookieName, token, cookieOpts)
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
scope.use(async ({context, next}: MiddlewareParametersInterface) => {
|
|
60
|
+
const method = (context.req.method ?? '').toUpperCase()
|
|
61
|
+
|
|
62
|
+
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
|
|
63
|
+
const token = tokenStore
|
|
64
|
+
? tokenStore.create()
|
|
65
|
+
: CsrfUtil.generateDoubleSubmitToken(secret)
|
|
66
|
+
|
|
67
|
+
context.state = context.state ?? {}
|
|
68
|
+
context.state.csrfToken = token
|
|
69
|
+
|
|
70
|
+
context.reply.header(
|
|
71
|
+
'Set-Cookie',
|
|
72
|
+
CsrfUtil.serializeCookie(cookieName, token, cookieOpts)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return next()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (!methods.includes(method)) {
|
|
79
|
+
return next()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const requestPath = new URL(context.req.url, 'http://localhost').pathname
|
|
83
|
+
if (skipPaths.some(p => requestPath.startsWith(p))) {
|
|
84
|
+
return next()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const isBrowser = CsrfUtil.isBrowserClient(context.req.headers, opts.client)
|
|
88
|
+
if (!isBrowser) {
|
|
89
|
+
return next()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const cookieHeader = context.req.headers.get('cookie') ?? ''
|
|
93
|
+
const cookieToken = CsrfUtil.extractCookieValue(cookieHeader, cookieName)
|
|
94
|
+
const headerToken = context.req.headers.get(headerName.toLowerCase())
|
|
95
|
+
|
|
96
|
+
if (!cookieToken || !headerToken) {
|
|
97
|
+
context.reply.status(HttpStatus.FORBIDDEN)
|
|
98
|
+
return context.reply.send(
|
|
99
|
+
RaitonResponses(
|
|
100
|
+
'CSRF token missing',
|
|
101
|
+
null,
|
|
102
|
+
HttpStatus.FORBIDDEN,
|
|
103
|
+
{error: true}
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
let valid = false
|
|
109
|
+
|
|
110
|
+
if (mode === CSRF_MODE_DOUBLE_SUBMIT) {
|
|
111
|
+
valid = CsrfUtil.validateDoubleSubmitToken(secret, cookieToken, ttl)
|
|
112
|
+
&& CsrfUtil.timingSafeEqual(cookieToken, headerToken)
|
|
113
|
+
} else {
|
|
114
|
+
const storeValid = tokenStore?.validate(cookieToken) ?? false
|
|
115
|
+
valid = storeValid && CsrfUtil.timingSafeEqual(cookieToken, headerToken)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (!valid) {
|
|
119
|
+
context.reply.status(HttpStatus.FORBIDDEN)
|
|
120
|
+
return context.reply.send(
|
|
121
|
+
RaitonResponses(
|
|
122
|
+
'CSRF token invalid',
|
|
123
|
+
null,
|
|
124
|
+
HttpStatus.FORBIDDEN,
|
|
125
|
+
{error: true}
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
context.state = context.state ?? {}
|
|
131
|
+
context.state.csrfValidated = true
|
|
132
|
+
|
|
133
|
+
await next()
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
}, 'csrf')
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function cryptoRandomSecret(): string {
|
|
140
|
+
return crypto.randomBytes(32).toString('hex')
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const CSRF_MODE_DEFAULT = CSRFModeEnum.DOUBLE_SUBMIT
|
|
144
|
+
const CSRF_MODE_SYNCHRONIZER = CSRFModeEnum.SYNCHRONIZER
|
|
145
|
+
const CSRF_MODE_DOUBLE_SUBMIT = CSRFModeEnum.DOUBLE_SUBMIT
|
|
@@ -3,6 +3,7 @@ import {secureCors} from './cors'
|
|
|
3
3
|
import {secureRateLimit} from './rate-limit'
|
|
4
4
|
import {secureBodyLimit} from './body-limit'
|
|
5
5
|
import {secureMethodGuard} from './method-guard'
|
|
6
|
+
import {secureCsrf} from './csrf'
|
|
6
7
|
|
|
7
8
|
export class Security {
|
|
8
9
|
static headers = secureHeaders
|
|
@@ -10,4 +11,5 @@ export class Security {
|
|
|
10
11
|
static rateLimit = secureRateLimit
|
|
11
12
|
static bodyLimit = secureBodyLimit
|
|
12
13
|
static methodGuard = secureMethodGuard
|
|
14
|
+
static csrf = secureCsrf
|
|
13
15
|
}
|
|
@@ -14,6 +14,10 @@ export function isMcpArtifact(filename: string) {
|
|
|
14
14
|
return isArtifact(filename, 'mcp')
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
export function isHealthCheckArtifact(filename: string) {
|
|
18
|
+
return isArtifact(filename, 'health-check')
|
|
19
|
+
}
|
|
20
|
+
|
|
17
21
|
export function isArtifact(filename: string, artifact: string) {
|
|
18
22
|
return [
|
|
19
23
|
filename.endsWith(`.${artifact}.ts`),
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import {CsrfTokenPayload} from "../../types";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_TTL = 3600_000
|
|
5
|
+
|
|
6
|
+
export class CsrfUtil {
|
|
7
|
+
|
|
8
|
+
static generateDoubleSubmitToken(secret: string): string {
|
|
9
|
+
const timestamp = Date.now().toString(36)
|
|
10
|
+
const nonce = crypto.randomBytes(16).toString('hex')
|
|
11
|
+
const payload = `${timestamp}.${nonce}`
|
|
12
|
+
const signature = crypto
|
|
13
|
+
.createHmac('sha256', secret)
|
|
14
|
+
.update(payload)
|
|
15
|
+
.digest('hex')
|
|
16
|
+
return `${payload}.${signature}`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
static validateDoubleSubmitToken(secret: string, token: string, maxAge?: number): boolean {
|
|
20
|
+
if (!token || typeof token !== 'string') return false
|
|
21
|
+
|
|
22
|
+
const parts = token.split('.')
|
|
23
|
+
if (parts.length !== 3) return false
|
|
24
|
+
|
|
25
|
+
const [timestampB36, nonce, signature] = parts
|
|
26
|
+
const payload = `${timestampB36}.${nonce}`
|
|
27
|
+
|
|
28
|
+
const expectedSignature = crypto
|
|
29
|
+
.createHmac('sha256', secret)
|
|
30
|
+
.update(payload)
|
|
31
|
+
.digest('hex')
|
|
32
|
+
|
|
33
|
+
if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
|
|
34
|
+
return false
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (maxAge !== undefined) {
|
|
38
|
+
const timestamp = parseInt(timestampB36, 36)
|
|
39
|
+
if (isNaN(timestamp)) return false
|
|
40
|
+
if (Date.now() - timestamp > maxAge) return false
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return true
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
static generateSynchronizerToken(): string {
|
|
47
|
+
return crypto.randomBytes(32).toString('hex')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static createTokenStore(ttl: number = DEFAULT_TTL) {
|
|
51
|
+
const store = new Map<string, CsrfTokenPayload>()
|
|
52
|
+
|
|
53
|
+
const cleanup = () => {
|
|
54
|
+
const now = Date.now()
|
|
55
|
+
for (const [key, entry] of store) {
|
|
56
|
+
if (now > entry.expiresAt) {
|
|
57
|
+
store.delete(key)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const interval = setInterval(cleanup, Math.min(ttl, 60_000))
|
|
63
|
+
if (typeof interval === 'object' && 'unref' in interval) {
|
|
64
|
+
interval.unref()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
create(): string {
|
|
69
|
+
const token = CsrfUtil.generateSynchronizerToken()
|
|
70
|
+
store.set(token, {
|
|
71
|
+
token,
|
|
72
|
+
expiresAt: Date.now() + ttl
|
|
73
|
+
})
|
|
74
|
+
return token
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
validate(token: string): boolean {
|
|
78
|
+
if (!token || typeof token !== 'string') return false
|
|
79
|
+
const entry = store.get(token)
|
|
80
|
+
if (!entry) return false
|
|
81
|
+
if (Date.now() > entry.expiresAt) {
|
|
82
|
+
store.delete(token)
|
|
83
|
+
return false
|
|
84
|
+
}
|
|
85
|
+
return true
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
revoke(token: string): boolean {
|
|
89
|
+
return store.delete(token)
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
get size(): number {
|
|
93
|
+
return store.size
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
destroy(): void {
|
|
97
|
+
clearInterval(interval)
|
|
98
|
+
store.clear()
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
static isBrowserClient(headers: Headers, config?: {
|
|
104
|
+
headerName?: string
|
|
105
|
+
skipClients?: string[]
|
|
106
|
+
}): boolean {
|
|
107
|
+
const clientTypeHeader = config?.headerName ?? 'X-Client-Type'
|
|
108
|
+
const skipClients = config?.skipClients ?? ['mobile', 'desktop']
|
|
109
|
+
|
|
110
|
+
const clientType = headers.get(clientTypeHeader)
|
|
111
|
+
if (clientType && skipClients.includes(clientType.toLowerCase())) {
|
|
112
|
+
return false
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const authorization = headers.get('authorization')
|
|
116
|
+
const hasCookie = headers.get('cookie')?.includes('_csrf') ?? false
|
|
117
|
+
|
|
118
|
+
if (authorization && !hasCookie) {
|
|
119
|
+
return false
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return true
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
static serializeCookie(name: string, value: string, options?: {
|
|
126
|
+
httpOnly?: boolean
|
|
127
|
+
secure?: boolean
|
|
128
|
+
sameSite?: 'strict' | 'lax' | 'none'
|
|
129
|
+
path?: string
|
|
130
|
+
domain?: string
|
|
131
|
+
maxAge?: number
|
|
132
|
+
}): string {
|
|
133
|
+
let cookie = `${name}=${value}`
|
|
134
|
+
|
|
135
|
+
if (options?.httpOnly) cookie += '; HttpOnly'
|
|
136
|
+
if (options?.secure) cookie += '; Secure'
|
|
137
|
+
if (options?.sameSite) {
|
|
138
|
+
cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`
|
|
139
|
+
}
|
|
140
|
+
if (options?.path) cookie += `; Path=${options.path}`
|
|
141
|
+
if (options?.domain) cookie += `; Domain=${options.domain}`
|
|
142
|
+
if (options?.maxAge) cookie += `; Max-Age=${options.maxAge}`
|
|
143
|
+
|
|
144
|
+
return cookie
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
static extractCookieValue(cookieHeader: string, name: string): string | undefined {
|
|
148
|
+
const cookies = cookieHeader.split(';')
|
|
149
|
+
for (const cookie of cookies) {
|
|
150
|
+
const [key, ...valueParts] = cookie.trim().split('=')
|
|
151
|
+
if (key === name) {
|
|
152
|
+
return valueParts.join('=')
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
static timingSafeEqual(a: string, b: string): boolean {
|
|
159
|
+
if (a.length !== b.length) return false
|
|
160
|
+
return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {HttpMethod} from "../framework";
|
|
2
|
-
import {HttpsConfigInput, HttpsConfigInterface} from "../framework/utilities/https";
|
|
2
|
+
import {HttpsConfigInput, HttpsConfigInterface} from "../framework/utilities/https.util";
|
|
3
3
|
|
|
4
4
|
export interface ApplicationConfigInterface {
|
|
5
5
|
workdir?: string;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import {CSRFModeEnum} from "../framework/enums";
|
|
2
|
+
|
|
3
|
+
export interface CsrfClientDetectionConfig {
|
|
4
|
+
headerName?: string
|
|
5
|
+
skipClients?: string[]
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface CsrfOptions {
|
|
9
|
+
mode?: CSRFModeEnum
|
|
10
|
+
secret?: string
|
|
11
|
+
cookieName?: string
|
|
12
|
+
headerName?: string
|
|
13
|
+
ttl?: number
|
|
14
|
+
methods?: string[]
|
|
15
|
+
skip?: string[]
|
|
16
|
+
client?: CsrfClientDetectionConfig
|
|
17
|
+
cookieOptions?: CsrfCookieOptions
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface CsrfCookieOptions {
|
|
21
|
+
httpOnly?: boolean
|
|
22
|
+
secure?: boolean
|
|
23
|
+
sameSite?: 'strict' | 'lax' | 'none'
|
|
24
|
+
path?: string
|
|
25
|
+
domain?: string
|
|
26
|
+
maxAge?: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CsrfTokenPayload {
|
|
30
|
+
token: string
|
|
31
|
+
expiresAt: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CsrfGuardOptions {
|
|
35
|
+
mode?: CSRFModeEnum
|
|
36
|
+
methods?: string[]
|
|
37
|
+
skipPaths?: string[]
|
|
38
|
+
}
|
package/source/types/index.ts
CHANGED
package/source/types/runtime.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {RuntimeType} from "../framework/enums/runtime.enum";
|
|
2
|
-
import {HttpsCertificateConfig, HttpsEnvironment} from "../framework/utilities/https";
|
|
2
|
+
import {HttpsCertificateConfig, HttpsEnvironment} from "../framework/utilities/https.util";
|
|
3
3
|
|
|
4
4
|
export interface RuntimeServerInterface {
|
|
5
5
|
listen(port: number, hostname?: string): Promise<void>
|
|
File without changes
|
|
File without changes
|