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,117 @@
|
|
|
1
|
+
# Health-check
|
|
2
|
+
|
|
3
|
+
> **Navigation :** [← security](security.md) | [https →](https.md)
|
|
4
|
+
|
|
5
|
+
Les health-checks permettent d'exposer un endpoint de contrôle pour les sondes d'infrastructure (load balancer, orchestrateur, « liveness » / « readiness »). Raiton fournit un endpoint **par défaut** et vous permet de le **personnaliser** grâce à `@HealthCheck()` et `HealthCheckManager`.
|
|
6
|
+
|
|
7
|
+
## Endpoint par défaut
|
|
8
|
+
|
|
9
|
+
Sans aucune configuration, Raiton enregistre automatiquement `GET /health` **après** le scan des contrôleurs.
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"statusCode": 200,
|
|
14
|
+
"message": "Service is healthy",
|
|
15
|
+
"data": {
|
|
16
|
+
"status": "healthy",
|
|
17
|
+
"timestamp": "2026-09-03T12:00:00.000Z",
|
|
18
|
+
"uptime": 42.1,
|
|
19
|
+
"version": "0.0.0"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Dès que vous définissez votre propre health-check, le défaut est remplacé.
|
|
25
|
+
|
|
26
|
+
## Définir un health-check personnalisé
|
|
27
|
+
|
|
28
|
+
Utilisez `@HealthCheck()` sur une méthode combinée à un décorateur de route.
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { Controllable, Get, HealthCheck, HttpStatus, RaitonResponses } from "raiton/framework"
|
|
32
|
+
|
|
33
|
+
@Controllable()
|
|
34
|
+
export class HealthController {
|
|
35
|
+
@Get("/health")
|
|
36
|
+
@HealthCheck({ summary: "État de l'application" })
|
|
37
|
+
check() {
|
|
38
|
+
return RaitonResponses(
|
|
39
|
+
"Service is healthy",
|
|
40
|
+
{ status: "healthy" },
|
|
41
|
+
HttpStatus.OK,
|
|
42
|
+
{ error: false }
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Vous pouvez renvoyer un code `503 Service Unavailable` dans le cas où l'application est en mauvaise santé.
|
|
49
|
+
|
|
50
|
+
## Configurer le comportement par défaut
|
|
51
|
+
|
|
52
|
+
`HealthCheckManager.configure(...)` agit sur le health-check par défaut (et sur les sauts de middleware applicables).
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
import { HealthCheckManager, HttpStatus } from "raiton/framework"
|
|
56
|
+
|
|
57
|
+
HealthCheckManager.configure({
|
|
58
|
+
path: "/health",
|
|
59
|
+
response: {
|
|
60
|
+
statusCode: HttpStatus.OK,
|
|
61
|
+
message: "All systems operational"
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Vérifications personnalisées
|
|
67
|
+
|
|
68
|
+
Ajoutez des vérifications de dépendances pour enrichir la réponse.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
HealthCheckManager.configure({
|
|
72
|
+
checks: [
|
|
73
|
+
{
|
|
74
|
+
name: "database",
|
|
75
|
+
check: async () => {
|
|
76
|
+
// testez votre connexion
|
|
77
|
+
return { status: "healthy" as const }
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: "cache",
|
|
82
|
+
check: async () => ({ status: "degraded" as const, message: "cache partiellement disponible" })
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
})
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Les résultats sont agrégés dans `data.checks`. Le statut global est :
|
|
89
|
+
- `unhealthy` si au moins une vérification échoue (code `503`)
|
|
90
|
+
- `degraded` sinon
|
|
91
|
+
- `healthy` par défaut (code `200`)
|
|
92
|
+
|
|
93
|
+
### Handler entièrement personnalisé
|
|
94
|
+
|
|
95
|
+
`registerCustomHandler` remplace entièrement la logique de réponse du health-check par défaut.
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
HealthCheckManager.registerCustomHandler((ctx) => {
|
|
99
|
+
return { ok: true, memory: process.memoryUsage() }
|
|
100
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Types et options
|
|
104
|
+
|
|
105
|
+
- `HealthCheckManager.configure(config)` : `path`, `response` (`statusCode`, `message`), `checks`.
|
|
106
|
+
- `@HealthCheck(options)` : `path`, `tags`, `summary`, `description`, `excludeFromDocs`.
|
|
107
|
+
- `HealthCheckCheck` : `{ name, check }` où `check` renvoie `{ status, message? }`.
|
|
108
|
+
|
|
109
|
+
## Bon usage
|
|
110
|
+
|
|
111
|
+
- garder le endpoint de santé léger et sans logique métier lourde
|
|
112
|
+
- utiliser `checks` pour les dépendances critiques (base de données, cache)
|
|
113
|
+
- renvoyer `503` quand l'application ne peut plus traiter de requêtes
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
[← security](security.md) | [https →](https.md)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Sécurité
|
|
2
2
|
|
|
3
|
-
> **Navigation :** [← body-parser](body-parser.md) | [
|
|
3
|
+
> **Navigation :** [← body-parser](body-parser.md) | [csrf →](csrf.md)
|
|
4
4
|
|
|
5
5
|
Les plugins de sécurité servent à protéger une API exposée publiquement.
|
|
6
6
|
|
|
@@ -8,6 +8,7 @@ Les plugins de sécurité servent à protéger une API exposée publiquement.
|
|
|
8
8
|
|
|
9
9
|
- `Security.headers()`
|
|
10
10
|
- `Security.cors()`
|
|
11
|
+
- `Security.csrf()` — [Documentation complète](csrf.md)
|
|
11
12
|
- `Security.rateLimit()`
|
|
12
13
|
- `Security.bodyLimit()`
|
|
13
14
|
- `Security.methodGuard()`
|
|
@@ -19,6 +20,7 @@ app.register({
|
|
|
19
20
|
plugins: [
|
|
20
21
|
Security.headers(),
|
|
21
22
|
Security.cors({ origin: "*" }),
|
|
23
|
+
Security.csrf({ mode: CSRFModeEnum.DOUBLE_SUBMIT, secret: process.env.CSRF_SECRET }),
|
|
22
24
|
Security.rateLimit({ max: 100, windowMs: 60000 }),
|
|
23
25
|
Security.bodyLimit(1_000_000)
|
|
24
26
|
]
|
|
@@ -30,17 +32,21 @@ app.register({
|
|
|
30
32
|
- réduire les abus
|
|
31
33
|
- contrôler les origines autorisées
|
|
32
34
|
- limiter la taille des payloads
|
|
35
|
+
- protéger contre les attaques CSRF (Cross-Site Request Forgery)
|
|
33
36
|
|
|
34
37
|
## Avantages
|
|
35
38
|
|
|
36
39
|
- facile à activer
|
|
37
40
|
- couvre plusieurs protections de base
|
|
41
|
+
- CSRF supporte le mode stateless (double-submit) et stateful (synchronizer)
|
|
42
|
+
- détection automatique des clients mobile/desktop
|
|
38
43
|
|
|
39
44
|
## Inconvénients
|
|
40
45
|
|
|
41
46
|
- `rateLimit()` est en mémoire, donc non distribué
|
|
42
47
|
- `cors()` doit être configuré selon le contexte réel
|
|
48
|
+
- `csrf()` nécessite une configuration côté client pour les navigateurs
|
|
43
49
|
|
|
44
50
|
---
|
|
45
51
|
|
|
46
|
-
[← body-parser](body-parser.md) | [
|
|
52
|
+
[← body-parser](body-parser.md) | [csrf →](csrf.md)
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ import {Logger} from "@protorians/logger";
|
|
|
8
8
|
import {RaitonConfig} from "./config";
|
|
9
9
|
import {Artifacts} from "../framework/artifacts";
|
|
10
10
|
import {Injection} from "./injection";
|
|
11
|
-
import {HttpsConfigInterface, resolveHttpsConfig} from "../framework/utilities/https";
|
|
11
|
+
import {HttpsConfigInterface, resolveHttpsConfig} from "../framework/utilities/https.util";
|
|
12
12
|
|
|
13
13
|
export class Application implements ApplicationInterface {
|
|
14
14
|
private root: PluginScope
|
|
@@ -7,6 +7,7 @@ import {compileMcp} from "../mcp/builder";
|
|
|
7
7
|
import {RaitonThread} from "../thread";
|
|
8
8
|
import {Injection} from "../injection";
|
|
9
9
|
import {isControllerArtifact, isSocketArtifact, isMcpArtifact} from "../../framework";
|
|
10
|
+
import {Artifacts} from "../../framework/artifacts";
|
|
10
11
|
import path from "node:path";
|
|
11
12
|
import {ControllerRouteTracker} from "./tracker";
|
|
12
13
|
|
|
@@ -16,6 +17,14 @@ export class ControllerBuilder {
|
|
|
16
17
|
const files = fs.readdirSync(workdir, {recursive: true})
|
|
17
18
|
.map(file => file.toString());
|
|
18
19
|
const output: any[] = []
|
|
20
|
+
const timestamp = Date.now()
|
|
21
|
+
|
|
22
|
+
for (const file of files) {
|
|
23
|
+
const filename = path.join(workdir, file);
|
|
24
|
+
const classification = Artifacts.classify(filename);
|
|
25
|
+
if (classification?.channel !== 'hmr:di') continue;
|
|
26
|
+
await this.loadDiArtifact(filename, 1, timestamp);
|
|
27
|
+
}
|
|
19
28
|
|
|
20
29
|
for (const file of files) {
|
|
21
30
|
output.push(await this.build<any>({filename: path.join(workdir, file), version: 1, timestamp: Date.now()}))
|
|
@@ -24,6 +33,20 @@ export class ControllerBuilder {
|
|
|
24
33
|
return output.filter(f => typeof f !== 'undefined');
|
|
25
34
|
}
|
|
26
35
|
|
|
36
|
+
static async loadDiArtifact(filename: string, version = 1, timestamp = Date.now()): Promise<void> {
|
|
37
|
+
const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
|
|
38
|
+
|
|
39
|
+
for (const mod of Object.values(imported)) {
|
|
40
|
+
const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
|
|
41
|
+
typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
if (typeof name === 'string' && Injection.has(name)) {
|
|
45
|
+
Injection.registerArtifactPath(name, filename)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
27
50
|
static async build<T>({filename, version, timestamp}: BuilderHMRDeclarationInterface): Promise<T | undefined> {
|
|
28
51
|
const isController = isControllerArtifact(filename);
|
|
29
52
|
const isSocket = isSocketArtifact(filename);
|
package/source/core/thread.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {ApplicationInterface} from "../types/application";
|
|
|
15
15
|
import {Runtime} from "../framework/runtime";
|
|
16
16
|
import {LBadge, Logger} from "@protorians/logger";
|
|
17
17
|
import {ControllerBuilder} from "./controller";
|
|
18
|
+
import {registerDefaultHealthCheck} from "../framework/health-check";
|
|
18
19
|
import {bodyParserPlugin} from "../framework/plugins/body-parser.plugin";
|
|
19
20
|
import {Injection} from "./injection/injection";
|
|
20
21
|
import {Throwable} from "../framework/exceptions";
|
|
@@ -88,7 +89,10 @@ export class RaitonThread implements ThreadInterface {
|
|
|
88
89
|
if (!this.runtime)
|
|
89
90
|
throw new Throwable('Runtime not defined');
|
|
90
91
|
|
|
91
|
-
if (this.builder.source)
|
|
92
|
+
if (this.builder.source) {
|
|
93
|
+
await ControllerBuilder.scan(this.builder.source)
|
|
94
|
+
registerDefaultHealthCheck(this.application)
|
|
95
|
+
}
|
|
92
96
|
|
|
93
97
|
if (this._options.serve) {
|
|
94
98
|
process.on('SIGINT', async () => {
|
|
@@ -12,6 +12,7 @@ export type HmrChannel =
|
|
|
12
12
|
| 'hmr:middleware'
|
|
13
13
|
| 'hmr:hook'
|
|
14
14
|
| 'hmr:mcp'
|
|
15
|
+
| 'hmr:health-check'
|
|
15
16
|
|
|
16
17
|
export interface ArtifactClassification {
|
|
17
18
|
channel: HmrChannel
|
|
@@ -46,6 +47,7 @@ export const HMR_CHANNELS: Record<HmrChannel, readonly string[]> = {
|
|
|
46
47
|
'hmr:middleware': ['middleware'],
|
|
47
48
|
'hmr:hook': ['hook', 'event', 'listener'],
|
|
48
49
|
'hmr:mcp': ['mcp'],
|
|
50
|
+
'hmr:health-check': ['health-check'],
|
|
49
51
|
}
|
|
50
52
|
|
|
51
53
|
export class Artifacts {
|
|
@@ -81,6 +83,7 @@ export class Artifacts {
|
|
|
81
83
|
'schema',
|
|
82
84
|
'socket',
|
|
83
85
|
'mcp',
|
|
86
|
+
'health-check',
|
|
84
87
|
]
|
|
85
88
|
|
|
86
89
|
static register(type: string) {
|
|
@@ -18,6 +18,8 @@ export const METADATA_KEYS = {
|
|
|
18
18
|
API_PROPERTY: Symbol('api:property'),
|
|
19
19
|
// Route interaction metadata key
|
|
20
20
|
ROUTE_INTERACTION: Symbol('route:interaction'),
|
|
21
|
+
// Health check metadata key
|
|
22
|
+
HEALTH_CHECK: Symbol('health:check'),
|
|
21
23
|
// MCP metadata keys
|
|
22
24
|
MCP: Symbol('mcp:meta'),
|
|
23
25
|
MCP_ELEMENTS: Symbol('mcp:elements'),
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import {MiddlewareParametersInterface, CsrfGuardOptions} from "../../types";
|
|
2
|
+
import {Middleware} from "./middleware.decorator";
|
|
3
|
+
import {HttpStatus, RaitonResponses} from "..";
|
|
4
|
+
import {CsrfUtil} from "../utilities/csrf.util";
|
|
5
|
+
|
|
6
|
+
const DEFAULT_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']
|
|
7
|
+
const DEFAULT_HEADER_NAME = 'X-CSRF-Token'
|
|
8
|
+
const DEFAULT_COOKIE_NAME = '_csrf'
|
|
9
|
+
|
|
10
|
+
export function CsrfGuard(options: CsrfGuardOptions = {}) {
|
|
11
|
+
return Middleware(async ({context, next}: MiddlewareParametersInterface) => {
|
|
12
|
+
const method = (context.req.method ?? '').toUpperCase()
|
|
13
|
+
const methods = (options.methods ?? DEFAULT_METHODS).map(m => m.toUpperCase())
|
|
14
|
+
|
|
15
|
+
if (!methods.includes(method)) {
|
|
16
|
+
return next()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (options.skipPaths) {
|
|
20
|
+
const requestPath = new URL(context.req.url, 'http://localhost').pathname
|
|
21
|
+
if (options.skipPaths.some(p => requestPath.startsWith(p))) {
|
|
22
|
+
return next()
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const headerToken = context.req.headers.get(DEFAULT_HEADER_NAME.toLowerCase())
|
|
27
|
+
const cookieHeader = context.req.headers.get('cookie') ?? ''
|
|
28
|
+
const cookieToken = CsrfUtil.extractCookieValue(cookieHeader, DEFAULT_COOKIE_NAME)
|
|
29
|
+
|
|
30
|
+
if (!headerToken || !cookieToken) {
|
|
31
|
+
context.reply.status(HttpStatus.FORBIDDEN)
|
|
32
|
+
return context.reply.send(
|
|
33
|
+
RaitonResponses(
|
|
34
|
+
'CSRF token missing',
|
|
35
|
+
null,
|
|
36
|
+
HttpStatus.FORBIDDEN,
|
|
37
|
+
{error: true}
|
|
38
|
+
)
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const valid = CsrfUtil.timingSafeEqual(cookieToken, headerToken)
|
|
43
|
+
if (!valid) {
|
|
44
|
+
context.reply.status(HttpStatus.FORBIDDEN)
|
|
45
|
+
return context.reply.send(
|
|
46
|
+
RaitonResponses(
|
|
47
|
+
'CSRF token mismatch',
|
|
48
|
+
null,
|
|
49
|
+
HttpStatus.FORBIDDEN,
|
|
50
|
+
{error: true}
|
|
51
|
+
)
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
context.state = context.state ?? {}
|
|
56
|
+
context.state.csrfValidated = true
|
|
57
|
+
|
|
58
|
+
await next()
|
|
59
|
+
})
|
|
60
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {getControllerMetadata} from "../../core";
|
|
2
|
+
|
|
3
|
+
export function CsrfToken() {
|
|
4
|
+
return (target: any, propertyKey?: string) => {
|
|
5
|
+
const meta = getControllerMetadata(target.prototype || target)
|
|
6
|
+
const segment = propertyKey ? propertyKey : '@'
|
|
7
|
+
|
|
8
|
+
if (!meta.middlewares[segment]) {
|
|
9
|
+
meta.middlewares[segment] = []
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
meta.middlewares[segment].push(async ({context, next}: any) => {
|
|
13
|
+
const token = context.state?.csrfToken
|
|
14
|
+
if (token) {
|
|
15
|
+
context.reply.header('X-CSRF-Token', token)
|
|
16
|
+
}
|
|
17
|
+
await next()
|
|
18
|
+
})
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import {METADATA_KEYS} from "../constants/decorators.constant";
|
|
3
|
+
import {getControllerMetadata} from "../../core/controller";
|
|
4
|
+
import {RouteMetaInterface} from "../../types";
|
|
5
|
+
|
|
6
|
+
export interface HealthCheckOptions {
|
|
7
|
+
path?: string;
|
|
8
|
+
tags?: string[];
|
|
9
|
+
summary?: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
excludeFromDocs?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface HealthCheckMetadata {
|
|
15
|
+
options: HealthCheckOptions;
|
|
16
|
+
routeMeta?: RouteMetaInterface;
|
|
17
|
+
controllerPrefix?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const DEFAULT_HEALTH_CHECK_OPTIONS: HealthCheckOptions = {
|
|
21
|
+
path: '/health',
|
|
22
|
+
tags: ['Health'],
|
|
23
|
+
summary: 'Health check endpoint',
|
|
24
|
+
description: 'Returns the health status of the application',
|
|
25
|
+
excludeFromDocs: false,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export function HealthCheck(options: HealthCheckOptions = {}) {
|
|
29
|
+
return (target: any, propertyKey: string) => {
|
|
30
|
+
const mergedOptions = {...DEFAULT_HEALTH_CHECK_OPTIONS, ...options};
|
|
31
|
+
const controllerMeta = getControllerMetadata(target.prototype || target);
|
|
32
|
+
const route = controllerMeta.routes.find(r => r.propertyKey === propertyKey);
|
|
33
|
+
|
|
34
|
+
const metadata: HealthCheckMetadata = {
|
|
35
|
+
options: mergedOptions,
|
|
36
|
+
routeMeta: route,
|
|
37
|
+
controllerPrefix: controllerMeta.prefix,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
Reflect.defineMetadata(METADATA_KEYS.HEALTH_CHECK, metadata, target, propertyKey);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function getHealthCheckMetadata(target: any, propertyKey: string): HealthCheckMetadata | undefined {
|
|
45
|
+
return Reflect.getMetadata(METADATA_KEYS.HEALTH_CHECK, target, propertyKey);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function isHealthCheck(target: any, propertyKey: string): boolean {
|
|
49
|
+
return Reflect.hasMetadata(METADATA_KEYS.HEALTH_CHECK, target, propertyKey);
|
|
50
|
+
}
|
|
@@ -5,7 +5,10 @@ export * from "./routable.decorator"
|
|
|
5
5
|
export * from "./parametrable.decorator"
|
|
6
6
|
export * from "./injection.decorator"
|
|
7
7
|
export * from "./guard.decorator"
|
|
8
|
+
export * from "./csrf-guard.decorator"
|
|
9
|
+
export * from "./csrf-token.decorator"
|
|
8
10
|
export * from "./api-response.decorator"
|
|
9
11
|
export * from "./api.decorator"
|
|
10
12
|
export * from "./route-interaction.decorator"
|
|
13
|
+
export * from "./health-check.decorator"
|
|
11
14
|
export * from "./mcp.decorator"
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import {HttpStatus, HttpMethod} from "./enums";
|
|
2
|
+
import {RaitonResponses} from "./responses/helpers";
|
|
3
|
+
import {ApplicationInterface} from "../types/application";
|
|
4
|
+
import {RequestContext} from "../core/context";
|
|
5
|
+
|
|
6
|
+
export interface HealthCheckConfig {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
path: string;
|
|
9
|
+
response?: {
|
|
10
|
+
status?: 'healthy' | 'unhealthy' | 'degraded';
|
|
11
|
+
statusCode?: HttpStatus;
|
|
12
|
+
message?: string;
|
|
13
|
+
};
|
|
14
|
+
checks?: HealthCheckCheck[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type HealthCheckStatus = 'healthy' | 'unhealthy' | 'degraded';
|
|
18
|
+
|
|
19
|
+
export interface HealthCheckResult {
|
|
20
|
+
name: string;
|
|
21
|
+
status: HealthCheckStatus;
|
|
22
|
+
message?: string;
|
|
23
|
+
duration?: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface HealthCheckCheck {
|
|
27
|
+
name: string;
|
|
28
|
+
check: () => Promise<{ status: HealthCheckStatus; message?: string }> | { status: HealthCheckStatus; message?: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const DEFAULT_HEALTH_CHECK_CONFIG: HealthCheckConfig = {
|
|
32
|
+
enabled: true,
|
|
33
|
+
path: '/health',
|
|
34
|
+
response: {
|
|
35
|
+
status: 'healthy',
|
|
36
|
+
statusCode: HttpStatus.OK,
|
|
37
|
+
message: 'Service is healthy',
|
|
38
|
+
},
|
|
39
|
+
checks: [],
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export class HealthCheckManager {
|
|
43
|
+
private static _config: HealthCheckConfig = {...DEFAULT_HEALTH_CHECK_CONFIG};
|
|
44
|
+
private static _customHandler: ((ctx: RequestContext) => Promise<any> | any) | null = null;
|
|
45
|
+
|
|
46
|
+
static configure(config: Partial<HealthCheckConfig>): void {
|
|
47
|
+
this._config = {...this._config, ...config};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static getConfig(): HealthCheckConfig {
|
|
51
|
+
return {...this._config};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static registerCustomHandler(handler: (ctx: RequestContext) => Promise<any> | any): void {
|
|
55
|
+
this._customHandler = handler;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static async runChecks(): Promise<HealthCheckResult[]> {
|
|
59
|
+
const results: HealthCheckResult[] = [];
|
|
60
|
+
|
|
61
|
+
for (const check of this._config.checks || []) {
|
|
62
|
+
const start = Date.now();
|
|
63
|
+
try {
|
|
64
|
+
const result = await check.check();
|
|
65
|
+
results.push({
|
|
66
|
+
name: check.name,
|
|
67
|
+
status: result.status,
|
|
68
|
+
message: result.message,
|
|
69
|
+
duration: Date.now() - start,
|
|
70
|
+
});
|
|
71
|
+
} catch (error: any) {
|
|
72
|
+
results.push({
|
|
73
|
+
name: check.name,
|
|
74
|
+
status: 'unhealthy',
|
|
75
|
+
message: error.message || 'Check failed',
|
|
76
|
+
duration: Date.now() - start,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return results;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
static async handleHealthCheck(ctx: RequestContext): Promise<any> {
|
|
85
|
+
if (this._customHandler) {
|
|
86
|
+
return this._customHandler(ctx);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const checks = await this.runChecks();
|
|
90
|
+
const timestamp = new Date().toISOString();
|
|
91
|
+
|
|
92
|
+
let overallStatus: HealthCheckStatus = 'healthy';
|
|
93
|
+
if (checks.some(c => c.status === 'unhealthy')) {
|
|
94
|
+
overallStatus = 'unhealthy';
|
|
95
|
+
} else if (checks.some(c => c.status === 'degraded')) {
|
|
96
|
+
overallStatus = 'degraded';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const statusCode = overallStatus === 'unhealthy'
|
|
100
|
+
? HttpStatus.SERVICE_UNAVAILABLE
|
|
101
|
+
: (this._config.response?.statusCode || HttpStatus.OK);
|
|
102
|
+
|
|
103
|
+
return RaitonResponses(
|
|
104
|
+
this._config.response?.message || `Service is ${overallStatus}`,
|
|
105
|
+
{
|
|
106
|
+
status: overallStatus,
|
|
107
|
+
timestamp,
|
|
108
|
+
checks: checks.length > 0 ? checks : undefined,
|
|
109
|
+
uptime: process.uptime(),
|
|
110
|
+
version: process.env.npm_package_version || '0.0.0',
|
|
111
|
+
},
|
|
112
|
+
statusCode,
|
|
113
|
+
{error: overallStatus === 'unhealthy'}
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function hasRegisteredHealthCheck(app: ApplicationInterface): boolean {
|
|
119
|
+
const config = HealthCheckManager.getConfig();
|
|
120
|
+
const rootScope = (app as any).root;
|
|
121
|
+
if (!rootScope?.router) return false;
|
|
122
|
+
|
|
123
|
+
const routes = rootScope.router.getRoutes();
|
|
124
|
+
return routes.some((route: any) =>
|
|
125
|
+
route.path === config.path && route.method === HttpMethod.GET
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function registerDefaultHealthCheck(app: ApplicationInterface): void {
|
|
130
|
+
const config = HealthCheckManager.getConfig();
|
|
131
|
+
if (!config.enabled) return;
|
|
132
|
+
if (hasRegisteredHealthCheck(app)) return;
|
|
133
|
+
|
|
134
|
+
app.get(config.path, (ctx: RequestContext) => {
|
|
135
|
+
return HealthCheckManager.handleHealthCheck(ctx);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
@@ -7,6 +7,7 @@ export * from "./plugins/index"
|
|
|
7
7
|
export * from "./runtime/index"
|
|
8
8
|
export * from "./mcp/index"
|
|
9
9
|
export * from "./exceptions/index"
|
|
10
|
+
export * from "./health-check"
|
|
10
11
|
export * from "./controllers"
|
|
11
12
|
export * from "./data-transfer-object"
|
|
12
13
|
export * from "./view-model"
|