@meghjs/mcp 0.0.0-stage → 0.7.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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
@@ -0,0 +1,256 @@
1
+ ---
2
+ title: Deployment
3
+ description: Building a Megh app, running it in production, containers, process managers and migrations.
4
+ ---
5
+
6
+ # Deployment
7
+
8
+ A Megh app is a plain Node.js program. You compile it to JavaScript, set
9
+ `NODE_ENV=production`, and run the entry file with Node 22 or newer.
10
+
11
+ ## Building
12
+
13
+ ```bash
14
+ npx megh build # or: npm run build in a scaffolded app
15
+ ```
16
+
17
+ `megh build` compiles the project with the project's own `tsc`:
18
+
19
+ - It uses `tsconfig.build.json`, else `tsconfig.json` (with a warning), or
20
+ the file passed with `-p, --project <file>`.
21
+ - It deletes the output folder (`outDir`, default `dist`) first.
22
+ - It copies every non-TypeScript file under `src/` (JSON, templates, images…)
23
+ into the output folder. Dotfiles are skipped.
24
+ - It fails if `typescript` is not installed in the project.
25
+
26
+ The output is **CommonJS**, one `.js` file per source file:
27
+ `src/serve.ts` becomes `dist/serve.js`, and `src/controllers/` becomes
28
+ `dist/controllers/`. Megh itself ships only a CommonJS build. Keep
29
+ `"module": "CommonJS"` in `tsconfig.json`, as the scaffold does.
30
+
31
+ You can also run `tsc -p tsconfig.build.json` directly. You then have to copy
32
+ any assets yourself.
33
+
34
+ ## Starting
35
+
36
+ ```bash
37
+ npx megh start # or: npm start
38
+ ```
39
+
40
+ `megh start` runs the compiled entry with `node --enable-source-maps`. It sets
41
+ `NODE_ENV=production` unless `NODE_ENV` is already set, and forwards `SIGINT`
42
+ and `SIGTERM` to the app. It looks for the entry in this order:
43
+
44
+ 1. `--entry <file>`
45
+ 2. `megh.entry` in `package.json`
46
+ 3. `main` in `package.json` (a `src/*.ts` path is mapped to the output folder)
47
+ 4. `serve.js`, `server.js`, `main.js`, `index.js` in the output folder
48
+
49
+ If none exists it stops with `No compiled entry file found (tried …)` and
50
+ asks you to run `megh build` first or pass `--entry`.
51
+
52
+ `megh start` is optional. Running Node yourself works the same:
53
+
54
+ ```bash
55
+ NODE_ENV=production node --enable-source-maps dist/serve.js
56
+ ```
57
+
58
+ Start the app from the project root. Megh reads `.env` and resolves
59
+ auto-discovered folders (`src/controllers`, `src/tasks`) relative to the
60
+ current working directory.
61
+
62
+ ## Environment
63
+
64
+ | Variable | Effect |
65
+ |----------|--------|
66
+ | `NODE_ENV` | Anything other than `development` (including unset) is production |
67
+ | `HOST` | Interface `run()` listens on. Default `0.0.0.0` |
68
+ | `PORT` | Port `run()` listens on when you don't pass one. Default `4000` |
69
+ | `LOG_LEVEL` | Log level. Default `info` |
70
+ | `MEGH_DOTENV` | `false` stops Megh loading `.env` |
71
+ | `DATABASE_URL`, `DB_*` | MeghORM connection |
72
+
73
+ In production mode (`app.isDevelopment()` is `false`):
74
+
75
+ - 5xx responses say only `Internal Server Error`, without the message, data or
76
+ stack. See [Error Handling](/core-concept/error-handling).
77
+ - Logs are JSON lines on stdout, even if `pino-pretty` is installed. See
78
+ [Logging](/advanced/logging).
79
+ - `/ready` leaves out the reason a health check failed.
80
+ - Anything you put behind `if (app.isDevelopment())`, such as the OpenAPI
81
+ docs in the scaffold, is off.
82
+
83
+ ::: warning Keep `NODE_ENV=development` out of a deployed `.env`
84
+ Values already in the environment win over `.env`. If a `.env` in the working
85
+ directory sets `NODE_ENV=development` and nothing else sets `NODE_ENV`, the app
86
+ runs in development mode and sends error details to clients. Projects created
87
+ with 0.6.0 or later leave `NODE_ENV` out of `.env`; older projects should
88
+ remove it. Don't ship `.env` to production; set real environment variables
89
+ instead.
90
+ :::
91
+
92
+ `app.run()` listens on `PORT`, else `4000`, unless you pass a port. A port
93
+ passed to `run()` wins. An invalid `PORT` stops startup with an error.
94
+
95
+ See [Configuration](/core-concept/configuration) for typed config classes.
96
+
97
+ ## Health checks
98
+
99
+ Turn on `/health` and `/ready` for load balancers and orchestrators:
100
+
101
+ ```ts
102
+ app.useHealth();
103
+ ```
104
+
105
+ Point liveness probes at `/health` and readiness probes at `/ready`. Both
106
+ skip middleware and `@Authorized`. See [Health Checks](/advanced/health).
107
+
108
+ ## Graceful shutdown
109
+
110
+ On `SIGTERM` or `SIGINT`, `run()` stops accepting connections, waits for
111
+ in-flight requests, stops scheduled tasks and workers, runs `onClose` hooks
112
+ and exits with code 0. It exits with code 1 if that takes longer than
113
+ `shutdownTimeout` (default 10 seconds). See
114
+ [Application: Shutting down](/getting-started/application#shutting-down).
115
+
116
+ Give the app at least `shutdownTimeout` before your platform kills it. In
117
+ Kubernetes, `terminationGracePeriodSeconds` defaults to 30 seconds, which is
118
+ enough for the default.
119
+
120
+ ## Docker
121
+
122
+ A multi-stage build compiles with dev dependencies and ships only production
123
+ ones:
124
+
125
+ ```dockerfile [Dockerfile]
126
+ FROM node:22-slim AS build
127
+ WORKDIR /app
128
+ COPY package*.json ./
129
+ RUN npm ci
130
+ COPY . .
131
+ RUN npm run build
132
+
133
+ FROM node:22-slim
134
+ WORKDIR /app
135
+ ENV NODE_ENV=production
136
+ COPY package*.json ./
137
+ RUN npm ci --omit=dev
138
+ COPY --from=build /app/dist ./dist
139
+ USER node
140
+ EXPOSE 4000
141
+ CMD ["node", "--enable-source-maps", "dist/serve.js"]
142
+ ```
143
+
144
+ ```text [.dockerignore]
145
+ node_modules
146
+ dist
147
+ .env
148
+ .env.*
149
+ coverage
150
+ ```
151
+
152
+ - Run `node` directly in `CMD` (exec form), so `SIGTERM` reaches the app.
153
+ - `WORKDIR` matters: it is the working directory Megh resolves paths from.
154
+ - Optional integrations are peer dependencies. Anything the app calls in
155
+ production (`@fastify/cors`, `@fastify/swagger`…) must be in
156
+ `dependencies`, not `devDependencies`, or `npm ci --omit=dev` leaves it out
157
+ and the app throws at startup.
158
+
159
+ ## Process managers
160
+
161
+ Without containers, keep the app running with a process manager.
162
+
163
+ **PM2**:
164
+
165
+ ```bash
166
+ NODE_ENV=production pm2 start dist/serve.js --name api --kill-timeout 15000
167
+ ```
168
+
169
+ Set `--kill-timeout` above `shutdownTimeout`; PM2's own default is shorter.
170
+
171
+ **systemd**:
172
+
173
+ ```ini [/etc/systemd/system/api.service]
174
+ [Service]
175
+ WorkingDirectory=/srv/api
176
+ ExecStart=/usr/bin/node --enable-source-maps dist/serve.js
177
+ Environment=NODE_ENV=production
178
+ EnvironmentFile=/etc/api.env
179
+ Restart=on-failure
180
+ User=api
181
+
182
+ [Install]
183
+ WantedBy=multi-user.target
184
+ ```
185
+
186
+ systemd sends `SIGTERM` on stop and waits 90 seconds by default.
187
+
188
+ ## Migrations on deploy
189
+
190
+ Run migrations once per deploy, before the new version takes traffic, for
191
+ example as a release step, a Kubernetes `Job` or an init container.
192
+
193
+ In the runtime image, run the built migrations with `megh migrate
194
+ --compiled`. It loads the `.js` files from `dist/` (the tsconfig `outDir`),
195
+ so it needs `@meghjs/cli` installed but not the sources or a writable
196
+ `node_modules`. Without a `src/` folder this is the default, so plain
197
+ `megh migrate` works there too. Set `DATABASE_URL`. See
198
+ [Database Commands](/cli/database).
199
+
200
+ ```bash
201
+ npx megh migrate --compiled
202
+ npx megh migrate:status --compiled
203
+ ```
204
+
205
+ Where the sources are available (the build stage, a CI job), `megh migrate`
206
+ compiles `src/` with SWC instead.
207
+
208
+ `megh migrate --seed` and `megh db:seed` refuse to seed when
209
+ `NODE_ENV=production` unless you add `--force`.
210
+
211
+ To migrate without `@meghjs/cli` in the image, compile a small script with
212
+ the app. It uses the same connection settings as `useMeghORM()`:
213
+
214
+ ```ts [src/migrate.ts]
215
+ import path from 'path';
216
+ import { Migrations, createDatabase, resolveDatabaseOptions } from '@meghjs/core';
217
+
218
+ async function main() {
219
+ const db = createDatabase(resolveDatabaseOptions());
220
+ try {
221
+ const folder = path.join(__dirname, 'database/migrations');
222
+ const ran = await new Migrations(db, { folder }).latest();
223
+ console.log(ran.length ? `Migrated: ${ran.join(', ')}` : 'Nothing to migrate');
224
+ } finally {
225
+ await db.destroy();
226
+ }
227
+ }
228
+
229
+ main().catch((err) => {
230
+ console.error(err);
231
+ process.exit(1);
232
+ });
233
+ ```
234
+
235
+ ```bash
236
+ node dist/migrate.js
237
+ ```
238
+
239
+ ## Scheduled tasks and replicas
240
+
241
+ The scheduler runs in every process that calls `useScheduler`. With three
242
+ replicas, or PM2 in cluster mode, each `@Cron` job runs three times. Megh has
243
+ no built-in leader election or lock.
244
+
245
+ Run tasks in one process only, for example a separate deployment with
246
+ `RUN_SCHEDULER=true`:
247
+
248
+ ```ts [src/app.ts]
249
+ if (process.env.RUN_SCHEDULER === 'true') {
250
+ app.useScheduler([ReportTask, CleanupTask]);
251
+ }
252
+ ```
253
+
254
+ For work that must happen exactly once, enqueue a job from the task and let a
255
+ [queue](/advanced/queue) worker process it. See
256
+ [Scheduler](/advanced/scheduler).
@@ -0,0 +1,307 @@
1
+ ---
2
+ title: Security Hardening
3
+ description: What Megh protects by default, and the checklist for running an app in production.
4
+ ---
5
+
6
+ # Security Hardening
7
+
8
+ Megh ships with safe defaults for the parts it owns. The rest, such as CORS,
9
+ security headers and rate limits, depends on your app, so you turn it on
10
+ yourself. The checklist below shows how.
11
+
12
+ ## What Megh does by default
13
+
14
+ ### `@Authorized` fails closed
15
+
16
+ A route marked `@Authorized` (or `.authorized()` on an inline route) is never
17
+ served without an authorization handler. If you forget
18
+ `app.useAuthorization(...)`, every request gets **403**, and startup logs a
19
+ warning:
20
+
21
+ ```text
22
+ GET /admin uses @Authorized but no authorization handler is registered;
23
+ every request will be denied (403). Call app.useAuthorization(YourAuthorization).
24
+ ```
25
+
26
+ An `authorize` method that returns `false` also answers 403. See
27
+ [Authentication](/core-concept/authentication).
28
+
29
+ ### DTOs reject unknown properties
30
+
31
+ `@Body()` and `@Query()` DTOs are validated with `whitelist` and
32
+ `forbidNonWhitelisted`. A property the DTO doesn't declare fails with 400, so
33
+ a client can't slip `isAdmin: true` into a model. See
34
+ [Validation](/core-concept/validation).
35
+
36
+ ### 5xx details stay on the server
37
+
38
+ Unless `NODE_ENV=development`, a 5xx response is only:
39
+
40
+ ```json
41
+ { "code": 500, "status": "Error", "message": "Internal Server Error" }
42
+ ```
43
+
44
+ The real message, payload and stack are logged, not sent. 4xx messages are
45
+ sent as written, so don't put internal details in them. `/ready` likewise
46
+ hides why a health check failed outside development.
47
+
48
+ ### Uploads stay in their folder
49
+
50
+ `FileStorage` treats uploads as untrusted. By default it:
51
+
52
+ - saves files under a random UUID name that keeps the extension;
53
+ - rejects filenames containing `/`, `\`, `..` or null bytes;
54
+ - keeps every path, including `to`, inside `baseDir`. When saving or reading
55
+ it checks this again after following symlinks;
56
+ - accepts only an allowlist of extensions (images, PDF, office files,
57
+ text/CSV, zip, audio and video). HTML, SVG and JS are rejected;
58
+ - never overwrites an existing file.
59
+
60
+ The MIME type is not checked unless you set `allowedMimeTypes`. See
61
+ [File Uploads](/advanced/file-uploads).
62
+
63
+ ### Download headers are escaped
64
+
65
+ `Results.OkStream(stream, { filename })` builds `Content-Disposition` so a
66
+ filename can't inject headers: the plain `filename` keeps only safe ASCII and
67
+ the real name goes in the RFC 5987 `filename*` parameter.
68
+
69
+ ### Logs leave out credentials
70
+
71
+ - Error logs record the method, URL, status and error. Request headers and
72
+ bodies are not logged.
73
+ - Database passwords are replaced by `***` in connection log lines and
74
+ connection errors.
75
+ - A client's `x-request-id` is only reused if it matches
76
+ `^[\w.:-]{1,128}$`; anything else is replaced by a generated ID, so it
77
+ can't forge log lines.
78
+
79
+ The URL includes the query string, so keep tokens out of query parameters.
80
+
81
+ ## Checklist
82
+
83
+ ### Restrict CORS
84
+
85
+ `useCors` passes its options to `@fastify/cors`. The scaffold uses
86
+ `origin: '*'`; list your front-ends instead:
87
+
88
+ ```ts
89
+ app.useCors({
90
+ origin: ['https://app.example.com', /\.example\.com$/],
91
+ credentials: true,
92
+ });
93
+ ```
94
+
95
+ Browsers refuse credentialed requests when the allowed origin is `*`.
96
+
97
+ ### Add security headers
98
+
99
+ `app.useSecurityHeaders()` sends these headers on every response, including
100
+ errors and 404s:
101
+
102
+ | Header | Default |
103
+ | --- | --- |
104
+ | `Content-Security-Policy` | `default-src 'self'`, no plugins, no inline script, no framing by other sites |
105
+ | `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` |
106
+ | `X-Frame-Options` | `SAMEORIGIN` |
107
+ | `Referrer-Policy` | `no-referrer` |
108
+ | `Cross-Origin-Opener-Policy` | `same-origin` |
109
+ | `Cross-Origin-Resource-Policy` | `same-origin` |
110
+ | `X-Content-Type-Options` | `nosniff` |
111
+ | `Origin-Agent-Cluster`, `X-DNS-Prefetch-Control`, `X-Download-Options`, `X-Permitted-Cross-Domain-Policies` | `?1`, `off`, `noopen`, `none` |
112
+ | `X-XSS-Protection` | `0`, which turns off the old XSS filter (it caused more holes than it closed) |
113
+
114
+ ```ts [src/app.ts]
115
+ app.useSecurityHeaders();
116
+ ```
117
+
118
+ Pass `false` to leave a header out, or change it:
119
+
120
+ ```ts
121
+ app.useSecurityHeaders({
122
+ contentSecurityPolicy: {
123
+ directives: {
124
+ imgSrc: ["'self'", 'https://cdn.example.com'], // camelCase or 'img-src'
125
+ upgradeInsecureRequests: false, // drop a default
126
+ },
127
+ },
128
+ strictTransportSecurity: { maxAge: 63072000, preload: true },
129
+ frameOptions: 'DENY',
130
+ crossOriginResourcePolicy: 'cross-origin', // a public asset API
131
+ headers: { 'Permissions-Policy': 'camera=(), microphone=()' },
132
+ });
133
+ ```
134
+
135
+ - `contentSecurityPolicy: { reportOnly: true }` sends
136
+ `Content-Security-Policy-Report-Only`, so you can try a policy before
137
+ enforcing it. `useDefaults: false` starts from an empty policy.
138
+ - `crossOriginEmbedderPolicy` is off unless you set it, since it blocks
139
+ cross-origin images and scripts.
140
+ - `headers` adds any other header, or removes a default with `false`.
141
+ - A header a route sets itself wins over the default.
142
+ - The API docs page from `useOpenApi()` keeps its own CSP. Swagger UI sends
143
+ a policy that fits it, and Scalar needs inline script, so both still load.
144
+
145
+ Megh checks the options at startup and throws on a value that could break or
146
+ inject a header, such as a newline or a `;` in a CSP source.
147
+
148
+ ### Add rate limits
149
+
150
+ `app.useRateLimit()` limits each client to 100 requests a minute, counted per
151
+ IP in memory. Over the limit, the client gets **429** in Megh's error shape,
152
+ with `Retry-After`:
153
+
154
+ ```ts [src/app.ts]
155
+ app.useRateLimit(); // 100 a minute
156
+ app.useRateLimit({ max: 300, window: '5m' }); // window: ms, '30s', '15m', '1 hour'
157
+ ```
158
+
159
+ Every limited response carries `RateLimit-Limit`, `RateLimit-Remaining` and
160
+ `RateLimit-Reset` (seconds left in the window). Pass `headers: false` to hide
161
+ them.
162
+
163
+ Give a sensitive route a tighter limit with `@RateLimit()`, on a method or a
164
+ whole controller. It gets its own counter, so login attempts don't use up the
165
+ app-wide allowance. `@RateLimit(false)` takes a route out:
166
+
167
+ ```ts [src/controllers/auth.controller.ts]
168
+ import { ApiController, Get, Post, RateLimit } from '@meghjs/core';
169
+
170
+ @ApiController('/auth')
171
+ export class AuthController {
172
+ @Post('/login')
173
+ @RateLimit({ max: 5, window: '15m' })
174
+ login() {}
175
+
176
+ @Get('/status')
177
+ @RateLimit(false)
178
+ status() {}
179
+ }
180
+ ```
181
+
182
+ Inline routes take `.rateLimit({ ... })`. `@RateLimit()` works without
183
+ `useRateLimit()`: then only the routes that declare a limit are limited, as
184
+ with `useRateLimit({ global: false })`.
185
+
186
+ More options:
187
+
188
+ ```ts
189
+ app.useRateLimit({
190
+ key: (req) => String(req.headers['x-api-key'] ?? req.ip), // count per API key
191
+ skip: (req) => req.ip === '10.0.0.5', // internal callers
192
+ message: 'Slow down',
193
+ });
194
+ ```
195
+
196
+ Things to know:
197
+
198
+ - **Behind a proxy**, `request.ip` is the proxy's address unless you set
199
+ `trustProxy` (next section). Without it, every client shares one counter.
200
+ Set it to a hop count or the proxy's address, never `true`: with `true`,
201
+ clients can send their own `X-Forwarded-For` and get a fresh counter on
202
+ every request. Megh warns at boot when rate limiting runs with
203
+ `trustProxy: true`.
204
+ - **Several replicas** each count on their own with the memory store. Pass
205
+ an ioredis client so they share one count:
206
+
207
+ ```ts
208
+ import Redis from 'ioredis';
209
+
210
+ app.useRateLimit({ redis: new Redis(process.env.REDIS_URL!) });
211
+ ```
212
+
213
+ Megh does not close a client you pass in. For another backend, implement
214
+ `RateLimitStore` (`hit(key, windowMs)` returns `{ count, resetAt }`) and pass
215
+ it as `store`.
216
+ - A route's own limit (`@RateLimit`) is one counter per handler. With URI
217
+ versioning, `/v1/login` and `/v2/login` share it, so `@Version(['1', '2'])`
218
+ doesn't double the attempts a client gets.
219
+ - **IPv6 clients** are counted per `/64` network, because one host usually
220
+ owns a whole `/64` and could rotate addresses inside it to dodge the limit.
221
+ Change it with `ipv6Subnet` (`128` counts each address). IPv4 is counted
222
+ per address.
223
+ - **The memory store holds at most 100,000 clients.** Past that it drops the
224
+ oldest windows first and logs a warning once, so a flood of new addresses
225
+ can't exhaust memory. Dropped clients start a fresh count. Raise the cap
226
+ with `store: new MemoryRateLimitStore({ maxKeys: 500_000 })`, or use Redis.
227
+ - **If the store fails** (Redis is down), requests get 500. Set
228
+ `failOpen: true` to let them through instead; the error is still logged.
229
+ - `/health` and `/ready` from `useHealth()` are never limited, so probes keep
230
+ answering. Unknown URLs are limited, so scanning for paths counts.
231
+ - Limits use a fixed window: a client can send up to `max` at the end of one
232
+ window and `max` more at the start of the next.
233
+
234
+ ### Terminate HTTPS at a proxy
235
+
236
+ Serve HTTPS from a load balancer, ingress or reverse proxy, and keep the app
237
+ on plain HTTP inside the network. Tell Fastify to trust the proxy so
238
+ `request.ip`, `request.protocol` and `request.hostname` come from the
239
+ `X-Forwarded-*` headers:
240
+
241
+ ```ts
242
+ const app = Megh.createApplication({
243
+ server: { trustProxy: 1 }, // one proxy in front; or its address, e.g. '10.0.0.0/8'
244
+ });
245
+ ```
246
+
247
+ Don't use `trustProxy: true`. Common proxies, such as nginx with
248
+ `$proxy_add_x_forwarded_for` and AWS ALB, **append** the client's address to
249
+ `X-Forwarded-For` instead of replacing it. With `true`, Fastify takes the
250
+ leftmost entry, which the client wrote, so clients can spoof their IP and
251
+ dodge rate limits. A hop count (the number of proxies you run) or the
252
+ proxies' addresses make Fastify read the entry your own proxy added. Bind to `127.0.0.1` (`HOST=127.0.0.1`) when the proxy runs on the same
253
+ machine. To terminate TLS in Node instead, pass `server.https`.
254
+
255
+ ### Limit body sizes
256
+
257
+ Fastify rejects JSON bodies over 1 MiB with 413. Lower it if your API takes
258
+ small payloads:
259
+
260
+ ```ts
261
+ Megh.createApplication({ server: { bodyLimit: 100 * 1024 } }); // 100 KB
262
+ ```
263
+
264
+ `useMultipart()` limits each file to 10 MB by default. Set `limits` to
265
+ change it, and cap the number of files and fields too:
266
+
267
+ ```ts
268
+ app.useMultipart({ limits: { fileSize: 5 * 1024 * 1024, files: 1, fields: 10 } });
269
+ ```
270
+
271
+ ### Keep secrets in the environment
272
+
273
+ - Read secrets from environment variables or your platform's secret store.
274
+ The scaffold's `.gitignore` already leaves out `.env` and `.env.local`.
275
+ - Don't bake `.env` into images. Add it to `.dockerignore`.
276
+ - Fail fast when a secret is missing: `env.getOrThrow('JWT_SECRET')`. See
277
+ [Configuration](/core-concept/configuration).
278
+
279
+ ### Keep the OpenAPI docs in development
280
+
281
+ `useOpenApi()` serves the docs whenever you call it. Gate it, as the scaffold
282
+ does:
283
+
284
+ ```ts
285
+ if (app.isDevelopment()) {
286
+ app.useOpenApi(OpenApiConfig);
287
+ }
288
+ ```
289
+
290
+ If you need public docs, put them behind authentication at the proxy.
291
+
292
+ ### Set `NODE_ENV=production`
293
+
294
+ Everything above that depends on production mode (hidden 5xx details, hidden
295
+ health errors, docs off) needs `NODE_ENV` to be anything but `development`.
296
+ See [Deployment](/production/deployment#environment).
297
+
298
+ ### Audit dependencies
299
+
300
+ ```bash
301
+ npm audit --omit=dev
302
+ npx megh doctor
303
+ ```
304
+
305
+ `npm audit` reports known vulnerabilities. `megh doctor` checks that Node,
306
+ `@meghjs/core` and the CLI versions line up. Keep Megh, Fastify and the
307
+ `@fastify/*` plugins current, and run the audit in CI.