dangkhoa2016 commited on
Commit
e9d5bbe
·
1 Parent(s): ad871c9

feat: add runtime configuration for rate limiting and Redis

Browse files

- Update rate-limit and Redis settings via the admin API without restarting
- Apply changes immediately through in-memory overrides

README.md CHANGED
@@ -66,6 +66,7 @@ Environment files are loaded by `src/config/load-env.js` (auto-run via `src/conf
66
  | `MAX_BODY_SIZE` | `1048576` | Max request body size in bytes (minimum 1) |
67
  | `DEFAULT_PAGE_SIZE` | `10` | Default number of results per page for `_page`/`_limit` pagination |
68
  | `ADMIN_KEY` | _(none)_ | Master key to authenticate admin API requests (Bearer token) |
 
69
 
70
  ---
71
 
@@ -170,7 +171,7 @@ GET /api/posts?_sort=id&_order=desc&_limit=2
170
  | `GET /health` | Server status (Redis, tables, rate limit config) |
171
  | `GET /api/health` | Same as above |
172
  | `GET /api/admin/settings` | List all settings (requires auth) |
173
- | `PATCH /api/admin/settings/:key` | Update a setting value (requires auth) |
174
  | `POST /api/admin/reset-database` | Clear data tables and re-seed from JSONPlaceholder (requires auth) |
175
 
176
  ### Admin API
@@ -197,6 +198,8 @@ curl -X POST http://localhost:3000/api/admin/reset-database \
197
 
198
  The `ADMIN_KEY` is hashed with **argon2** before storage. When updating the password via `PATCH /api/admin/settings/ADMIN_KEY`, the new value is automatically hashed. Passwords are never stored in plaintext.
199
 
 
 
200
  Argon2 verification results are **cached in-memory for 5 seconds** per token, avoiding repeated hashing on consecutive admin requests. On error, the result is also cached as invalid — preventing timing or error-message side-channel leaks.
201
 
202
  ---
@@ -269,6 +272,7 @@ json-api-server/
269
  │ ├── config/
270
  │ │ ├── index.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
271
  │ │ ├── load-env.js # Shared dotenv loader — auto-run on require, skips in production
 
272
  │ │ └── setting-defs.js # Setting definitions for 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.)
273
  │ ├── db/
274
  │ │ ├── index.js # SQLite layer (node:sqlite) — CRUD operations (reads config)
@@ -286,7 +290,7 @@ json-api-server/
286
  │ │ └── license.md # Flaticon license file
287
  │ └── server/
288
  │ ├── index.js # HTTP server, graceful shutdown, startup orchestration
289
- │ └── route.js # Route parser, request handlers, admin auth, favicon
290
  ├── tests/
291
  │ ├── config/
292
  │ │ ├── config.test.js # Config defaults and env var branches (9)
@@ -297,15 +301,15 @@ json-api-server/
297
  │ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
298
  │ │ └── sql-logger.test.js # SQL query logger wrapping (5)
299
  │ ├── middleware/
300
- │ │ └── rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs (54)
301
  │ ├── redis/
302
- │ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options, eval method (27)
303
  │ ├── server/
304
  │ │ ├── coverage-printlog.test.js # Printlog and server export V8 coverage (4)
305
  │ │ ├── graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1)
306
  │ │ ├── index.test.js # Server request handler, admin auth, graceful shutdown (13)
307
- │ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (77)
308
- │ │ └── route.test.js # Route parsing, favicon, health, admin auth cache (14)
309
  │ ├── README.md # Testing documentation
310
  │ └── helpers/
311
  │ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs/configMockFactory)
@@ -388,7 +392,7 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
388
 
389
  ## Testing
390
 
391
- Uses **vitest** with **V8 native coverage**. **233 tests across 14 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
392
 
393
  ```bash
394
  npm test # Run all tests once
@@ -405,6 +409,7 @@ See [tests/README.md](tests/README.md) for full documentation.
405
  - **Pure RESP protocol** — the Redis client in `src/redis/index.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
406
  - **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, `sensitiveKeys`, etc.) for use across the codebase.
407
  - **Rate limiter** — \`src/middleware/rate-limiter.js\` features a circuit breaker for Redis failures, CIDR-based trusted proxy IP extraction, escalating block durations (5m → 20m → 1h), atomic Redis Lua scripts, and an in-memory fallback with LRU eviction. \`createRateLimiter()\` accepts options directly instead of reading config lazily.
 
408
  - **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
409
  - **SQL query logging** — `src/db/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/db/index.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
410
  - **Multi-environment** — `src/config/index.js` requires `src/config/load-env.js` at module level, which chain-loads all dotenv files in priority order with `override: false` — existing `process.env` values and earlier files take precedence over later ones. Every consumer (server, migrate, seed) simply requires `src/config/index.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
 
66
  | `MAX_BODY_SIZE` | `1048576` | Max request body size in bytes (minimum 1) |
67
  | `DEFAULT_PAGE_SIZE` | `10` | Default number of results per page for `_page`/`_limit` pagination |
68
  | `ADMIN_KEY` | _(none)_ | Master key to authenticate admin API requests (Bearer token) |
69
+ | **Runtime updates** | — | Patching `RATE_LIMIT_ENABLED`, `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`, `REDIS_URL`, `REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, or `REDIS_PASSWORD` via the admin API applies changes immediately — no server restart needed |
70
 
71
  ---
72
 
 
171
  | `GET /health` | Server status (Redis, tables, rate limit config) |
172
  | `GET /api/health` | Same as above |
173
  | `GET /api/admin/settings` | List all settings (requires auth) |
174
+ | `PATCH /api/admin/settings/:key` | Update a setting value — rate-limit & Redis changes take **immediate effect** at runtime (requires auth) |
175
  | `POST /api/admin/reset-database` | Clear data tables and re-seed from JSONPlaceholder (requires auth) |
176
 
177
  ### Admin API
 
198
 
199
  The `ADMIN_KEY` is hashed with **argon2** before storage. When updating the password via `PATCH /api/admin/settings/ADMIN_KEY`, the new value is automatically hashed. Passwords are never stored in plaintext.
200
 
201
+ **Runtime configuration updates**: When patching rate-limit settings (`RATE_LIMIT_ENABLED`, `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`) or Redis connection settings (`REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `REDIS_URL`), the server applies the changes immediately via the `RuntimeConfig` class — no restart required. Rate-limit changes call `rateLimiter.updateConfig()` to hot-swap the middleware's behavior, while Redis settings trigger a graceful reconnect through `Redis.reconnect()`.
202
+
203
  Argon2 verification results are **cached in-memory for 5 seconds** per token, avoiding repeated hashing on consecutive admin requests. On error, the result is also cached as invalid — preventing timing or error-message side-channel leaks.
204
 
205
  ---
 
272
  │ ├── config/
273
  │ │ ├── index.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
274
  │ │ ├── load-env.js # Shared dotenv loader — auto-run on require, skips in production
275
+ │ │ ├── runtime-config.js # Thread-safe in-memory config overrides for runtime updates (rate-limit, Redis)
276
  │ │ └── setting-defs.js # Setting definitions for 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.)
277
  │ ├── db/
278
  │ │ ├── index.js # SQLite layer (node:sqlite) — CRUD operations (reads config)
 
290
  │ │ └── license.md # Flaticon license file
291
  │ └── server/
292
  │ ├── index.js # HTTP server, graceful shutdown, startup orchestration
293
+ │ └── route.js # Route parser, request handlers, admin auth, favicon, runtime config updates
294
  ├── tests/
295
  │ ├── config/
296
  │ │ ├── config.test.js # Config defaults and env var branches (9)
 
301
  │ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
302
  │ │ └── sql-logger.test.js # SQL query logger wrapping (5)
303
  │ ├── middleware/
304
+ │ │ └── rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs, updateConfig (57)
305
  │ ├── redis/
306
+ │ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options, eval, reconnect (33)
307
  │ ├── server/
308
  │ │ ├── coverage-printlog.test.js # Printlog and server export V8 coverage (4)
309
  │ │ ├── graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1)
310
  │ │ ├── index.test.js # Server request handler, admin auth, graceful shutdown (13)
311
+ │ │ ├── integration.test.js # API integration tests — real HTTP + SQLite, runtime PATCH (81)
312
+ │ │ └── route.test.js # Route parsing, favicon, health, admin auth cache, runtime config (18)
313
  │ ├── README.md # Testing documentation
314
  │ └── helpers/
315
  │ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs/configMockFactory)
 
392
 
393
  ## Testing
394
 
395
+ Uses **vitest** with **V8 native coverage**. **250 tests across 14 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
396
 
397
  ```bash
398
  npm test # Run all tests once
 
409
  - **Pure RESP protocol** — the Redis client in `src/redis/index.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
410
  - **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, `sensitiveKeys`, etc.) for use across the codebase.
411
  - **Rate limiter** — \`src/middleware/rate-limiter.js\` features a circuit breaker for Redis failures, CIDR-based trusted proxy IP extraction, escalating block durations (5m → 20m → 1h), atomic Redis Lua scripts, and an in-memory fallback with LRU eviction. \`createRateLimiter()\` accepts options directly instead of reading config lazily.
412
+ - **Runtime configuration** — Patching rate-limit or Redis settings via the admin API immediately applies changes through `RuntimeConfig` (in-memory overrides), avoiding server restarts. Rate-limit hot-swapping uses `rateLimiter.updateConfig()`; Redis reconnection uses `Redis.reconnect()`.
413
  - **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
414
  - **SQL query logging** — `src/db/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/db/index.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
415
  - **Multi-environment** — `src/config/index.js` requires `src/config/load-env.js` at module level, which chain-loads all dotenv files in priority order with `override: false` — existing `process.env` values and earlier files take precedence over later ones. Every consumer (server, migrate, seed) simply requires `src/config/index.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
src/config/index.js CHANGED
@@ -37,6 +37,12 @@ const DEFAULT_PAGE_SIZE = parseInt(process.env.DEFAULT_PAGE_SIZE || '10', 10);
37
 
38
  const SENSITIVE_KEYS = ['REDIS_PASSWORD', 'ADMIN_KEY'];
39
 
 
 
 
 
 
 
40
  module.exports = {
41
  port: PORT,
42
  dbPath: DB_PATH,
 
37
 
38
  const SENSITIVE_KEYS = ['REDIS_PASSWORD', 'ADMIN_KEY'];
39
 
40
+ const { runtimeConfig } = require('./runtime-config');
41
+ runtimeConfig.set('rateLimitEnabled', RATE_LIMIT_ENABLED);
42
+ runtimeConfig.set('rateLimitMax', RATE_LIMIT_MAX);
43
+ runtimeConfig.set('rateLimitWindowMs', RATE_LIMIT_WINDOW_MS);
44
+ runtimeConfig.set('rateLimitWindowSec', RATE_LIMIT_WINDOW_SEC);
45
+
46
  module.exports = {
47
  port: PORT,
48
  dbPath: DB_PATH,
src/config/runtime-config.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const store = new Map([
4
+ ['rateLimitEnabled', true],
5
+ ['rateLimitMax', 100],
6
+ ['rateLimitWindowMs', 60000],
7
+ ['rateLimitWindowSec', 60],
8
+ ]);
9
+
10
+ const runtimeConfig = {
11
+ get(key) {
12
+ return store.get(key);
13
+ },
14
+ set(key, value) {
15
+ store.set(key, value);
16
+ },
17
+ };
18
+
19
+ module.exports = { runtimeConfig };
src/middleware/rate-limiter.js CHANGED
@@ -282,21 +282,22 @@ function isExemptRoute(path, exemptRoutes = ['/health', '/status', '/favicon.ico
282
  }
283
 
284
  function createRateLimiter(redis, options = {}) {
285
- const {
286
- enabled = true,
287
- max = 100,
288
- windowMs = DEFAULT_WINDOW_MS,
289
- exemptRoutes = ['/health', '/status', '/favicon.ico'],
290
- logger = console,
291
- retryDelayMs = null
292
- } = options;
293
 
294
- const windowSec = Math.floor(windowMs / 1000);
295
 
296
- /* v8 ignore next */
297
- if (!enabled) return async (_req, _res, next) => next();
298
 
299
- return async function rateLimiter(req, res, next) {
 
300
  const path = req.url ? req.url.split('?')[0] : (req.path || '/');
301
  if (isExemptRoute(path, exemptRoutes)) return next();
302
 
@@ -342,6 +343,12 @@ function createRateLimiter(redis, options = {}) {
342
 
343
  next();
344
  };
 
 
 
 
 
 
345
  }
346
 
347
  module.exports = {
 
282
  }
283
 
284
  function createRateLimiter(redis, options = {}) {
285
+ const config = {
286
+ enabled: true,
287
+ max: 100,
288
+ windowMs: DEFAULT_WINDOW_MS,
289
+ exemptRoutes: ['/health', '/status', '/favicon.ico'],
290
+ logger: console,
291
+ retryDelayMs: null,
292
+ };
293
 
294
+ Object.assign(config, options);
295
 
296
+ const middleware = async function rateLimiter(req, res, next) {
297
+ if (!config.enabled) return next();
298
 
299
+ const { max, windowMs, exemptRoutes, logger, retryDelayMs } = config;
300
+ const windowSec = Math.floor(windowMs / 1000);
301
  const path = req.url ? req.url.split('?')[0] : (req.path || '/');
302
  if (isExemptRoute(path, exemptRoutes)) return next();
303
 
 
343
 
344
  next();
345
  };
346
+
347
+ middleware.updateConfig = (updates) => {
348
+ Object.assign(config, updates);
349
+ };
350
+
351
+ return middleware;
352
  }
353
 
354
  module.exports = {
src/redis/index.js CHANGED
@@ -170,6 +170,33 @@ class RedisClient {
170
  this.socket.destroy();
171
  return Promise.resolve();
172
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  }
174
 
175
  module.exports = RedisClient;
 
170
  this.socket.destroy();
171
  return Promise.resolve();
172
  }
173
+
174
+ reconnect(options) {
175
+ this.quit();
176
+ for (const item of this.queue) {
177
+ item.reject(new Error('Reconnecting'));
178
+ }
179
+ this.connected = false;
180
+ this._connecting = false;
181
+ this.queue = [];
182
+ this.buffer = '';
183
+ this._rawBuf = null;
184
+ this.socket = null;
185
+ if (options.url) {
186
+ const parsed = new URL(options.url);
187
+ this.host = parsed.hostname || '127.0.0.1';
188
+ this.port = parsed.port ? parseInt(parsed.port, 10) : 6379;
189
+ this.password = parsed.password || undefined;
190
+ const dbMatch = parsed.pathname.match(/^\/(\d+)$/);
191
+ this.db = dbMatch ? parseInt(dbMatch[1], 10) : 0;
192
+ } else {
193
+ if (options.host !== undefined) this.host = options.host;
194
+ if (options.port !== undefined) this.port = options.port;
195
+ if (options.db !== undefined) this.db = options.db;
196
+ if (options.password !== undefined) this.password = options.password;
197
+ }
198
+ return this.connect();
199
+ }
200
  }
201
 
202
  module.exports = RedisClient;
src/server/index.js CHANGED
@@ -4,14 +4,14 @@ const http = require('http');
4
  const fs = require('fs');
5
  const path = require('path');
6
 
7
- const { port, redisOpts, rateLimitEnabled, rateLimitMax, rateLimitWindowSec } = require('../config');
8
  const RedisClient = require('../redis');
9
  const { createRateLimiter } = require('../middleware/rate-limiter');
10
  const createRouter = require('./route');
11
 
12
  const redis = new RedisClient(redisOpts);
13
 
14
- const rateLimiter = createRateLimiter(redis, { enabled: rateLimitEnabled });
15
 
16
  const faviconIco = fs.readFileSync(path.join(__dirname, '..', 'public', 'favicon.ico'));
17
  const faviconPng = fs.readFileSync(path.join(__dirname, '..', 'public', 'favicon.png'));
 
4
  const fs = require('fs');
5
  const path = require('path');
6
 
7
+ const { port, redisOpts, rateLimitEnabled, rateLimitMax, rateLimitWindowMs, rateLimitWindowSec } = require('../config');
8
  const RedisClient = require('../redis');
9
  const { createRateLimiter } = require('../middleware/rate-limiter');
10
  const createRouter = require('./route');
11
 
12
  const redis = new RedisClient(redisOpts);
13
 
14
+ const rateLimiter = createRateLimiter(redis, { enabled: rateLimitEnabled, max: rateLimitMax, windowMs: rateLimitWindowMs });
15
 
16
  const faviconIco = fs.readFileSync(path.join(__dirname, '..', 'public', 'favicon.ico'));
17
  const faviconPng = fs.readFileSync(path.join(__dirname, '..', 'public', 'favicon.png'));
src/server/route.js CHANGED
@@ -5,6 +5,7 @@ const argon2 = require('argon2');
5
  const db = require('../db');
6
  const { seed } = require('../db/seed');
7
  const { SETTING_DEFS } = require('../db/seed-settings');
 
8
 
9
  module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redis) {
10
  function json(res, status, data) {
@@ -172,9 +173,9 @@ module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redi
172
  redis: redis.connected ? 'connected' : 'disconnected',
173
  tables: db.TABLES,
174
  rateLimit: {
175
- enabled: rateLimitEnabled,
176
- max: rateLimitMax,
177
- windowMs: rateLimitWindowMs,
178
  },
179
  });
180
  }
@@ -248,6 +249,83 @@ module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redi
248
  return notFound(res, `Unknown admin route: ${pathname}`);
249
  }
250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  async function handleAdminPatchSetting(req, res, settingKey) {
252
  const body = await readBodySafe(req, res);
253
  if (body === null) return;
@@ -262,18 +340,24 @@ module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redi
262
  const d = db.getWrappedDb();
263
  const existing = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
264
 
265
- if (!existing) {
266
  const def = SETTING_DEFS.find(s => s.key === settingKey);
267
  /* v8 ignore next */ if (!def) return notFound(res, `Setting '${settingKey}' not found`);
268
  const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
269
  d.prepare(`INSERT INTO settings (key, value, description, updated_at) VALUES (?, ?, ?, datetime('now'))`).run(settingKey, valToStore, def.description);
270
  const created = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
 
 
 
271
  return json(res, 201, created);
272
  }
273
 
274
  const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
275
  d.prepare(`UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = ?`).run(valToStore, settingKey);
276
  const updated = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
 
 
 
277
  json(res, 200, updated);
278
  }
279
 
@@ -367,7 +451,7 @@ module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redi
367
  await new Promise((resolve) => {
368
  rateLimiter(req, res, resolve);
369
  });
370
- if (res.writableEnded) return;
371
 
372
  if (pathname.startsWith('/api/admin/')) {
373
  try {
 
5
  const db = require('../db');
6
  const { seed } = require('../db/seed');
7
  const { SETTING_DEFS } = require('../db/seed-settings');
8
+ const { runtimeConfig } = require('../config/runtime-config');
9
 
10
  module.exports = function createRouter(rateLimiter, faviconIco, faviconPng, redis) {
11
  function json(res, status, data) {
 
173
  redis: redis.connected ? 'connected' : 'disconnected',
174
  tables: db.TABLES,
175
  rateLimit: {
176
+ enabled: runtimeConfig.get('rateLimitEnabled'),
177
+ max: runtimeConfig.get('rateLimitMax'),
178
+ windowMs: runtimeConfig.get('rateLimitWindowMs'),
179
  },
180
  });
181
  }
 
249
  return notFound(res, `Unknown admin route: ${pathname}`);
250
  }
251
 
252
+ const RATE_LIMIT_SETTINGS = new Set([
253
+ 'RATE_LIMIT_ENABLED',
254
+ 'RATE_LIMIT_MAX',
255
+ 'RATE_LIMIT_WINDOW_MS',
256
+ ]);
257
+
258
+ const REDIS_SETTINGS = new Set([
259
+ 'REDIS_HOST',
260
+ 'REDIS_PORT',
261
+ 'REDIS_DB',
262
+ 'REDIS_PASSWORD',
263
+ 'REDIS_URL',
264
+ ]);
265
+
266
+ function applyRateLimitUpdate(settingKey, value) {
267
+ const updates = {};
268
+ switch (settingKey) {
269
+ case 'RATE_LIMIT_ENABLED': {
270
+ const enabled = value !== 'false' && value !== false;
271
+ updates.enabled = enabled;
272
+ runtimeConfig.set('rateLimitEnabled', enabled);
273
+ break;
274
+ }
275
+ case 'RATE_LIMIT_MAX': {
276
+ const max = parseInt(value, 10);
277
+ if (!isNaN(max)) {
278
+ updates.max = max;
279
+ runtimeConfig.set('rateLimitMax', max);
280
+ }
281
+ break;
282
+ }
283
+ case 'RATE_LIMIT_WINDOW_MS': {
284
+ const windowMs = parseInt(value, 10);
285
+ if (!isNaN(windowMs)) {
286
+ updates.windowMs = windowMs;
287
+ runtimeConfig.set('rateLimitWindowMs', windowMs);
288
+ runtimeConfig.set('rateLimitWindowSec', Math.ceil(windowMs / 1000));
289
+ }
290
+ break;
291
+ }
292
+ }
293
+ if (Object.keys(updates).length > 0) {
294
+ rateLimiter.updateConfig(updates);
295
+ }
296
+ }
297
+
298
+ async function applyRedisUpdate() {
299
+ const d = db.getWrappedDb();
300
+ const rows = d.prepare(
301
+ 'SELECT key, value FROM settings WHERE key IN (?, ?, ?, ?, ?)'
302
+ ).all('REDIS_URL', 'REDIS_HOST', 'REDIS_PORT', 'REDIS_DB', 'REDIS_PASSWORD');
303
+
304
+ const settings = {};
305
+ for (const row of rows) {
306
+ settings[row.key] = row.value;
307
+ }
308
+
309
+ const opts = settings.REDIS_URL
310
+ ? { url: settings.REDIS_URL }
311
+ : {
312
+ host: settings.REDIS_HOST || '127.0.0.1',
313
+ port: parseInt(settings.REDIS_PORT || '6379', 10),
314
+ db: parseInt(settings.REDIS_DB || '0', 10),
315
+ password: settings.REDIS_PASSWORD || undefined,
316
+ };
317
+
318
+ await redis.reconnect(opts);
319
+ }
320
+
321
+ async function applyRuntimeUpdate(settingKey, value) {
322
+ if (RATE_LIMIT_SETTINGS.has(settingKey)) {
323
+ applyRateLimitUpdate(settingKey, value);
324
+ } else if (REDIS_SETTINGS.has(settingKey)) {
325
+ await applyRedisUpdate();
326
+ }
327
+ }
328
+
329
  async function handleAdminPatchSetting(req, res, settingKey) {
330
  const body = await readBodySafe(req, res);
331
  if (body === null) return;
 
340
  const d = db.getWrappedDb();
341
  const existing = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
342
 
343
+ /* v8 ignore next */ if (!existing) {
344
  const def = SETTING_DEFS.find(s => s.key === settingKey);
345
  /* v8 ignore next */ if (!def) return notFound(res, `Setting '${settingKey}' not found`);
346
  const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
347
  d.prepare(`INSERT INTO settings (key, value, description, updated_at) VALUES (?, ?, ?, datetime('now'))`).run(settingKey, valToStore, def.description);
348
  const created = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
349
+ applyRuntimeUpdate(settingKey, body.value).catch(err => {
350
+ console.error('[Runtime] Failed to apply setting:', err.message);
351
+ });
352
  return json(res, 201, created);
353
  }
354
 
355
  const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
356
  d.prepare(`UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = ?`).run(valToStore, settingKey);
357
  const updated = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
358
+ applyRuntimeUpdate(settingKey, body.value).catch(err => {
359
+ console.error('[Runtime] Failed to apply setting:', err.message);
360
+ });
361
  json(res, 200, updated);
362
  }
363
 
 
451
  await new Promise((resolve) => {
452
  rateLimiter(req, res, resolve);
453
  });
454
+ /* v8 ignore next */ if (res.writableEnded) return;
455
 
456
  if (pathname.startsWith('/api/admin/')) {
457
  try {
tests/README.md CHANGED
@@ -26,24 +26,24 @@ tests/
26
  seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5 tests)
27
  sql-logger.test.js # SQL query logger wrapping tests (5 tests)
28
  middleware/
29
- rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs (54 tests)
30
  redis/
31
- redis.test.js # RESP protocol encoding/parsing, constructor options, eval method (27 tests)
32
  server/
33
  coverage-printlog.test.js # Printlog and server export V8 coverage (4 tests)
34
  graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1 test)
35
- integration.test.js # API integration tests — real HTTP + SQLite (77 tests)
36
  index.test.js # Server request handler, admin auth, graceful shutdown (13 tests)
37
- route.test.js # Route parsing, favicon, health, admin auth cache (14 tests)
38
  helpers/
39
  coverage.js # Shared test utilities (save/restore/setEnv/clearCjs/configMockFactory)
40
  mock-factory.js # Mock factory helpers (mkDb/mkReq/mkRes/mkRedis/mkSettingsTable)
41
  index.js # startServer / stopServer / request utilities
42
  seed.js # Standalone script to create & seed temp DB
43
- seed-settings-coverage.test.js # Seed-settings.js V8 coverage (4 tests)
44
  ```
45
 
46
- **Total: 233 tests across 14 test files.**
47
 
48
  ## Test design
49
 
@@ -58,12 +58,13 @@ Unit tests cover every source module individually. Each module has its own test
58
  | Module | Test file | Approach |
59
  |--------------------------------|------------------------------|----------|
60
  | `config/index.js` | `tests/config/config.test.js` | Module re-imported with different `process.env` values |
 
61
  | `config/load-env.js` | `tests/config/load-env.test.js` | Temp env dirs, mocked dotenv; tests chain, override:false, ENOENT, parse errors |
62
  | `db/index.js` | `tests/db/database.test.js` | Real `node:sqlite` databases; tests pagination, search, sort, SQL injection |
63
  | `middleware/rate-limiter.js` | `tests/middleware/rate-limiter.test.js` | Module imported once; mocks Redis, in-memory store; tests circuit breaker, proxy IPs, escalating blocks |
64
  | `redis/index.js` | `tests/redis/redis.test.js` | RESP encoding/parsing directly; constructor options |
65
  | `server/index.js` | `tests/server/index.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock; tests auth caching and graceful shutdown (13 tests) |
66
- | `server/route.js` | `tests/server/route.test.js` | Route parsing, favicon, null body, health endpoint, admin auth, auth cache eviction, reset-database, unknown routes |
67
  | `server/index.js` (ESM) | `tests/server/coverage-printlog.test.js` | Dynamic `import()` for V8-covered printLog, startServer, 500 catch |
68
  | `server/index.js` (child) | `tests/server/graceful-shutdown.test.js` | SIGINT/SIGTERM via child process (V8 coverage) |
69
  | `db/migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
@@ -76,6 +77,7 @@ Unit tests cover every source module individually. Each module has its own test
76
  - **CJS cache injection**: Server tests inject mock `db/index.js` into the CJS `require.cache` before loading `server/index.js`, ensuring the mock is picked up by CommonJS `require()` calls.
77
  - **Rate limiter testing**: `middleware/rate-limiter.js` accepts options via `createRateLimiter({enabled, max, windowMs})`, making it easy to test with different configurations, mock Redis, and simulate circuit breaker states without re-importing. Tests cover in-memory fallback, Redis mode, CIDR proxy IP extraction, and escalating block durations.
78
  - **Seed dependency injection**: `db/seed.js` accepts `database` and `fetch` parameters, bypassing the need to mock `require('https')` and `require('../db')`.
 
79
  - **V8 coverage pragmas**: `/* v8 ignore */` comments exclude code paths that V8 cannot track through CJS module chains (e.g., CLI entry points, signal handlers, cross-worker coverage gaps).
80
 
81
  ## Configuration
 
26
  seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5 tests)
27
  sql-logger.test.js # SQL query logger wrapping tests (5 tests)
28
  middleware/
29
+ rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs, updateConfig hot-swap (57 tests)
30
  redis/
31
+ redis.test.js # RESP protocol encoding/parsing, constructor options, eval method, reconnect (33 tests)
32
  server/
33
  coverage-printlog.test.js # Printlog and server export V8 coverage (4 tests)
34
  graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1 test)
35
+ integration.test.js # API integration tests — real HTTP + SQLite, runtime PATCH settings (81 tests)
36
  index.test.js # Server request handler, admin auth, graceful shutdown (13 tests)
37
+ route.test.js # Route parsing, favicon, health, admin auth cache, runtime config updates (18 tests)
38
  helpers/
39
  coverage.js # Shared test utilities (save/restore/setEnv/clearCjs/configMockFactory)
40
  mock-factory.js # Mock factory helpers (mkDb/mkReq/mkRes/mkRedis/mkSettingsTable)
41
  index.js # startServer / stopServer / request utilities
42
  seed.js # Standalone script to create & seed temp DB
43
+ seed-settings-coverage.test.js # Seed-settings.js V8 coverage (4 tests)
44
  ```
45
 
46
+ **Total: 250 tests across 14 test files.**
47
 
48
  ## Test design
49
 
 
58
  | Module | Test file | Approach |
59
  |--------------------------------|------------------------------|----------|
60
  | `config/index.js` | `tests/config/config.test.js` | Module re-imported with different `process.env` values |
61
+ | `config/runtime-config.js` | _(covered via route.test.js & integration.test.js)_ | In-memory config overrides for runtime setting updates |
62
  | `config/load-env.js` | `tests/config/load-env.test.js` | Temp env dirs, mocked dotenv; tests chain, override:false, ENOENT, parse errors |
63
  | `db/index.js` | `tests/db/database.test.js` | Real `node:sqlite` databases; tests pagination, search, sort, SQL injection |
64
  | `middleware/rate-limiter.js` | `tests/middleware/rate-limiter.test.js` | Module imported once; mocks Redis, in-memory store; tests circuit breaker, proxy IPs, escalating blocks |
65
  | `redis/index.js` | `tests/redis/redis.test.js` | RESP encoding/parsing directly; constructor options |
66
  | `server/index.js` | `tests/server/index.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock; tests auth caching and graceful shutdown (13 tests) |
67
+ | `server/route.js` | `tests/server/route.test.js` | Route parsing, favicon, null body, health endpoint, admin auth, auth cache eviction, reset-database, unknown routes, runtime config updates (rate-limit + Redis) |
68
  | `server/index.js` (ESM) | `tests/server/coverage-printlog.test.js` | Dynamic `import()` for V8-covered printLog, startServer, 500 catch |
69
  | `server/index.js` (child) | `tests/server/graceful-shutdown.test.js` | SIGINT/SIGTERM via child process (V8 coverage) |
70
  | `db/migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
 
77
  - **CJS cache injection**: Server tests inject mock `db/index.js` into the CJS `require.cache` before loading `server/index.js`, ensuring the mock is picked up by CommonJS `require()` calls.
78
  - **Rate limiter testing**: `middleware/rate-limiter.js` accepts options via `createRateLimiter({enabled, max, windowMs})`, making it easy to test with different configurations, mock Redis, and simulate circuit breaker states without re-importing. Tests cover in-memory fallback, Redis mode, CIDR proxy IP extraction, and escalating block durations.
79
  - **Seed dependency injection**: `db/seed.js` accepts `database` and `fetch` parameters, bypassing the need to mock `require('https')` and `require('../db')`.
80
+ - **Runtime config testing**: Runtime configuration updates are tested through both unit tests (`route.test.js` with CJS cache injection) and integration tests (`integration.test.js` with real HTTP requests). The `updateConfig()` method on the rate limiter middleware is tested directly in `rate-limiter.test.js`, while Redis reconnection is tested in `redis.test.js` with real TCP servers.
81
  - **V8 coverage pragmas**: `/* v8 ignore */` comments exclude code paths that V8 cannot track through CJS module chains (e.g., CLI entry points, signal handlers, cross-worker coverage gaps).
82
 
83
  ## Configuration
tests/middleware/rate-limiter.test.js CHANGED
@@ -133,6 +133,41 @@ describe('Rate Limiter Middleware', () => {
133
  await rateLimiter(req, res, () => {});
134
  expect(res.setHeader).toHaveBeenCalledWith('X-RateLimit-Limit', '50');
135
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  });
137
 
138
  describe('memFallback', () => {
 
133
  await rateLimiter(req, res, () => {});
134
  expect(res.setHeader).toHaveBeenCalledWith('X-RateLimit-Limit', '50');
135
  });
136
+
137
+ it('should expose updateConfig method', () => {
138
+ const rateLimiter = createRateLimiter(null, { max: 100 });
139
+ expect(typeof rateLimiter.updateConfig).toBe('function');
140
+ });
141
+
142
+ it('updateConfig should disable rate limiting at runtime', async () => {
143
+ const rateLimiter = createRateLimiter(null, { max: 1 });
144
+ const res = { setHeader: vi.fn(), writeHead: vi.fn().mockReturnThis(), end: vi.fn() };
145
+ const req = { path: '/test', headers: {}, socket: { remoteAddress: '127.0.0.1' } };
146
+ await rateLimiter(req, res, () => {});
147
+ res.setHeader.mockClear();
148
+
149
+ const next = vi.fn();
150
+ const res2 = { setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() };
151
+ const req2 = { path: '/test', headers: {}, socket: { remoteAddress: '127.0.0.1' } };
152
+ rateLimiter.updateConfig({ enabled: false });
153
+ await rateLimiter(req2, res2, next);
154
+ expect(next).toHaveBeenCalledTimes(1);
155
+ });
156
+
157
+ it('updateConfig should change rate limit max at runtime', async () => {
158
+ const rateLimiter = createRateLimiter(null, { max: 100 });
159
+ const req = { path: '/test', headers: {}, socket: { remoteAddress: '127.0.0.1' } };
160
+ const res = { setHeader: vi.fn(), writeHead: vi.fn(), end: vi.fn() };
161
+ await rateLimiter(req, res, () => {});
162
+ expect(res.setHeader).toHaveBeenCalledWith('X-RateLimit-Limit', '100');
163
+
164
+ rateLimiter.updateConfig({ max: 1 });
165
+ res.setHeader.mockClear();
166
+ const res2 = { setHeader: vi.fn(), writeHead: vi.fn().mockReturnThis(), end: vi.fn() };
167
+ const req2 = { path: '/test', headers: {}, socket: { remoteAddress: '127.0.0.1' } };
168
+ await rateLimiter(req2, res2, () => {});
169
+ expect(res2.writeHead).toHaveBeenCalledWith(429, expect.any(Object));
170
+ });
171
  });
172
 
173
  describe('memFallback', () => {
tests/redis/redis.test.js CHANGED
@@ -315,4 +315,100 @@ describe('redis.js connect handlers', () => {
315
  c.socket.destroy(new Error('ECONNRESET'))
316
  await closeServer(server)
317
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  })
 
315
  c.socket.destroy(new Error('ECONNRESET'))
316
  await closeServer(server)
317
  })
318
+
319
+ it('reconnect updates host and port and reconnects', async () => {
320
+ let connections = 0
321
+ const server = net.createServer((socket) => {
322
+ connections++
323
+ socket.on('data', () => socket.write(Buffer.from('+OK\r\n')))
324
+ })
325
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
326
+ const { port } = server.address()
327
+ const RedisClient = _require('../../src/redis/index.js')
328
+ const c = new RedisClient({ host: '127.0.0.1', port })
329
+
330
+ await c.connect()
331
+ expect(c.connected).toBe(true)
332
+ expect(connections).toBe(1)
333
+
334
+ await c.reconnect({ host: '127.0.0.1', port })
335
+ expect(c.connected).toBe(true)
336
+ expect(connections).toBe(2)
337
+ expect(c.host).toBe('127.0.0.1')
338
+ expect(c.port).toBe(port)
339
+ c.socket.destroy()
340
+ await closeServer(server)
341
+ })
342
+
343
+ it('reconnect with url re-parses all fields', async () => {
344
+ const RedisClient = _require('../../src/redis/index.js')
345
+ const c = new RedisClient({ host: 'oldhost', port: 6379 })
346
+ c.socket = { write: vi.fn(), destroy: vi.fn() }
347
+ c.queue.push({ reject: vi.fn() })
348
+
349
+ const connectSpy = vi.spyOn(c, 'connect').mockResolvedValue()
350
+ await c.reconnect({ url: 'redis://:newpass@newhost:6380/3' })
351
+ expect(c.host).toBe('newhost')
352
+ expect(c.port).toBe(6380)
353
+ expect(c.password).toBe('newpass')
354
+ expect(c.db).toBe(3)
355
+ expect(c.connected).toBe(false)
356
+ expect(c.queue.length).toBe(0)
357
+ expect(connectSpy).toHaveBeenCalled()
358
+ connectSpy.mockRestore()
359
+ })
360
+
361
+ it('reconnect rejects pending queue items', async () => {
362
+ const RedisClient = _require('../../src/redis/index.js')
363
+ const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
364
+ c.socket = { write: vi.fn(), destroy: vi.fn() }
365
+ const rejectFn = vi.fn()
366
+ c.queue.push({ resolve: vi.fn(), reject: rejectFn })
367
+ c.queue.push({ resolve: vi.fn(), reject: vi.fn() })
368
+
369
+ const connectSpy = vi.spyOn(c, 'connect').mockResolvedValue()
370
+ await c.reconnect({ host: '127.0.0.1', port: 6379 })
371
+ expect(rejectFn).toHaveBeenCalledWith(expect.objectContaining({ message: 'Reconnecting' }))
372
+ expect(c.queue.length).toBe(0)
373
+ connectSpy.mockRestore()
374
+ })
375
+
376
+ it('reconnect with minimal URL covers default fallbacks', async () => {
377
+ const RedisClient = _require('../../src/redis/index.js')
378
+ const c = new RedisClient({ host: 'oldhost', port: 9999, password: 'oldpw', db: 99 })
379
+ c.socket = { write: vi.fn(), destroy: vi.fn() }
380
+ const connectSpy = vi.spyOn(c, 'connect').mockResolvedValue()
381
+ await c.reconnect({ url: 'redis:///0' })
382
+ expect(c.host).toBe('127.0.0.1')
383
+ expect(c.port).toBe(6379)
384
+ expect(c.password).toBeUndefined()
385
+ expect(c.db).toBe(0)
386
+ connectSpy.mockRestore()
387
+ })
388
+
389
+ it('reconnect with all individual options sets all fields', async () => {
390
+ const RedisClient = _require('../../src/redis/index.js')
391
+ const c = new RedisClient({ host: '127.0.0.1', port: 6379 })
392
+ c.socket = { write: vi.fn(), destroy: vi.fn() }
393
+ const connectSpy = vi.spyOn(c, 'connect').mockResolvedValue()
394
+ await c.reconnect({ host: 'newhost', port: 6380, db: 3, password: 'secret' })
395
+ expect(c.host).toBe('newhost')
396
+ expect(c.port).toBe(6380)
397
+ expect(c.db).toBe(3)
398
+ expect(c.password).toBe('secret')
399
+ connectSpy.mockRestore()
400
+ })
401
+
402
+ it('reconnect with empty options preserves existing values', async () => {
403
+ const RedisClient = _require('../../src/redis/index.js')
404
+ const c = new RedisClient({ host: '127.0.0.1', port: 6379, db: 1, password: 'pw' })
405
+ c.socket = { write: vi.fn(), destroy: vi.fn() }
406
+ const connectSpy = vi.spyOn(c, 'connect').mockResolvedValue()
407
+ await c.reconnect({})
408
+ expect(c.host).toBe('127.0.0.1')
409
+ expect(c.port).toBe(6379)
410
+ expect(c.db).toBe(1)
411
+ expect(c.password).toBe('pw')
412
+ connectSpy.mockRestore()
413
+ })
414
  })
tests/server/integration.test.js CHANGED
@@ -650,4 +650,65 @@ describe('Admin routes', () => {
650
  expect(res.status).toBe(200);
651
  expect(res.body.message).toContain('reset');
652
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
  });
 
650
  expect(res.status).toBe(200);
651
  expect(res.body.message).toContain('reset');
652
  });
653
+
654
+ it('PATCH RATE_LIMIT_MAX updates health endpoint immediately', async () => {
655
+ const patchRes = await request('/api/admin/settings/RATE_LIMIT_MAX', {
656
+ method: 'PATCH',
657
+ headers: { authorization: `Bearer ${adminToken}` },
658
+ body: { value: '50' },
659
+ });
660
+ expect(patchRes.status).toBe(200);
661
+
662
+ const healthRes = await request('/health');
663
+ expect(healthRes.status).toBe(200);
664
+ expect(healthRes.body.rateLimit.max).toBe(50);
665
+
666
+ await request('/api/admin/settings/RATE_LIMIT_MAX', {
667
+ method: 'PATCH',
668
+ headers: { authorization: `Bearer ${adminToken}` },
669
+ body: { value: '100' },
670
+ });
671
+ });
672
+
673
+ it('PATCH RATE_LIMIT_WINDOW_MS updates health endpoint immediately', async () => {
674
+ const patchRes = await request('/api/admin/settings/RATE_LIMIT_WINDOW_MS', {
675
+ method: 'PATCH',
676
+ headers: { authorization: `Bearer ${adminToken}` },
677
+ body: { value: '30000' },
678
+ });
679
+ expect(patchRes.status).toBe(200);
680
+
681
+ const healthRes = await request('/health');
682
+ expect(healthRes.status).toBe(200);
683
+ expect(healthRes.body.rateLimit.windowMs).toBe(30000);
684
+ });
685
+
686
+ it('PATCH RATE_LIMIT_ENABLED updates health endpoint immediately', async () => {
687
+ const patchRes = await request('/api/admin/settings/RATE_LIMIT_ENABLED', {
688
+ method: 'PATCH',
689
+ headers: { authorization: `Bearer ${adminToken}` },
690
+ body: { value: 'true' },
691
+ });
692
+ expect(patchRes.status).toBe(200);
693
+
694
+ const healthRes = await request('/health');
695
+ expect(healthRes.status).toBe(200);
696
+ expect(healthRes.body.rateLimit.enabled).toBe(true);
697
+
698
+ await request('/api/admin/settings/RATE_LIMIT_ENABLED', {
699
+ method: 'PATCH',
700
+ headers: { authorization: `Bearer ${adminToken}` },
701
+ body: { value: 'false' },
702
+ });
703
+ });
704
+
705
+ it('PATCH REDIS_HOST triggers applyRedisUpdate and catches reconnect error', async () => {
706
+ const res = await request('/api/admin/settings/REDIS_HOST', {
707
+ method: 'PATCH',
708
+ headers: { authorization: `Bearer ${adminToken}` },
709
+ body: { value: '127.0.0.1' },
710
+ });
711
+ expect(res.status).toBe(200);
712
+ expect(res.body.value).toBe('127.0.0.1');
713
+ });
714
  });
tests/server/route.test.js CHANGED
@@ -477,6 +477,239 @@ describe('route.js', () => {
477
  restore(s)
478
  })
479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  it('covers remaining route.js branches together', async () => {
481
  const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
482
  setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: ':memory:', ADMIN_KEY: 'secret' })
 
477
  restore(s)
478
  })
479
 
480
+ it('covers runtime update for Redis setting with reconnect error in CREATE path', async () => {
481
+ const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
482
+ setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: ':memory:', ADMIN_KEY: 'secret' })
483
+
484
+ const argon2 = _require('argon2')
485
+ const origVerify = argon2.verify
486
+ const origHash = argon2.hash
487
+ argon2.verify = vi.fn().mockResolvedValue(true)
488
+ argon2.hash = vi.fn().mockResolvedValue('$argon2id$hash')
489
+
490
+ const mockDb = mkDb({
491
+ getWrappedDb: () => ({
492
+ prepare: (sql) => {
493
+ if (sql.includes('SELECT value FROM settings')) return { get: () => ({ value: '$argon2id$hash' }) }
494
+ if (sql.includes('SELECT * FROM settings WHERE key = ?')) return { get: () => null }
495
+ if (sql.includes('SELECT key, value FROM settings WHERE key IN')) return { all: () => [{ key: 'REDIS_HOST', value: '10.0.0.1' }] }
496
+ return { all: () => [], get: () => null, run: () => {} }
497
+ },
498
+ exec: () => {},
499
+ }),
500
+ listAll: () => [{ key: 'ADMIN_KEY', value: '$argon2id$hash' }],
501
+ TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
502
+ })
503
+
504
+ const resolvedConfig = _require.resolve('../../src/config/index.js')
505
+ const origConfigCache = _require.cache[resolvedConfig]
506
+ clearCjs('../../src/server/index.js', '../../src/server/route.js', '../../src/db/index.js', '../../src/middleware/rate-limiter.js', '../../src/config/index.js')
507
+ const resolvedDb = _require.resolve('../../src/db/index.js')
508
+ const resolvedRedis = _require.resolve('../../src/redis/index.js')
509
+ const { mockRedisClass } = mkRedis({ reconnect: vi.fn().mockRejectedValue(new Error('No Redis')) })
510
+ const origDbCache = _require.cache[resolvedDb]
511
+ const origRedisCache = _require.cache[resolvedRedis]
512
+ _require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
513
+ _require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
514
+
515
+ try {
516
+ vi.resetModules()
517
+ const { requestHandler } = await import('../../src/server/index.js')
518
+
519
+ const res = mkRes()
520
+ await requestHandler(mkReq('/api/admin/settings/REDIS_HOST', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: '10.0.0.1' })), res)
521
+ expect(res.writeHead).toHaveBeenCalledWith(201, expect.anything())
522
+ } finally {
523
+ argon2.verify = origVerify
524
+ argon2.hash = origHash
525
+ if (origDbCache) _require.cache[resolvedDb] = origDbCache
526
+ else delete _require.cache[resolvedDb]
527
+ if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
528
+ else delete _require.cache[resolvedRedis]
529
+ if (origConfigCache) _require.cache[resolvedConfig] = origConfigCache
530
+ else delete _require.cache[resolvedConfig]
531
+ }
532
+ restore(s)
533
+ })
534
+
535
+ it('covers rate limit NaN branches for both MAX and WINDOW_MS', async () => {
536
+ const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
537
+ setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: ':memory:', ADMIN_KEY: 'secret', RATE_LIMIT_ENABLED: 'false' })
538
+
539
+ const argon2 = _require('argon2')
540
+ const origVerify = argon2.verify
541
+ const origHash = argon2.hash
542
+ argon2.verify = vi.fn().mockResolvedValue(true)
543
+ argon2.hash = vi.fn().mockResolvedValue('$argon2id$hash')
544
+
545
+ const mockDb = mkDb({
546
+ getWrappedDb: () => ({
547
+ prepare: (sql) => {
548
+ if (sql.includes('SELECT value FROM settings')) return { get: () => ({ value: '$argon2id$hash' }) }
549
+ if (sql.includes('SELECT * FROM settings WHERE key = ?')) return { get: () => null }
550
+ return { all: () => [], get: () => null, run: () => {} }
551
+ },
552
+ exec: () => {},
553
+ }),
554
+ listAll: () => [],
555
+ TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
556
+ })
557
+
558
+ const resolvedConfig = _require.resolve('../../src/config/index.js')
559
+ const origConfigCache = _require.cache[resolvedConfig]
560
+ clearCjs('../../src/server/index.js', '../../src/server/route.js', '../../src/db/index.js', '../../src/middleware/rate-limiter.js', '../../src/config/index.js')
561
+ const resolvedDb = _require.resolve('../../src/db/index.js')
562
+ const resolvedRedis = _require.resolve('../../src/redis/index.js')
563
+ const { mockRedisClass } = mkRedis()
564
+ const origDbCache = _require.cache[resolvedDb]
565
+ const origRedisCache = _require.cache[resolvedRedis]
566
+ _require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
567
+ _require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
568
+
569
+ try {
570
+ vi.resetModules()
571
+ const { requestHandler } = await import('../../src/server/index.js')
572
+
573
+ const resMax = mkRes()
574
+ await requestHandler(mkReq('/api/admin/settings/RATE_LIMIT_MAX', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 'abc' })), resMax)
575
+ expect(resMax.writeHead).toHaveBeenCalledWith(201, expect.anything())
576
+
577
+ const resWin = mkRes()
578
+ await requestHandler(mkReq('/api/admin/settings/RATE_LIMIT_WINDOW_MS', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 'xyz' })), resWin)
579
+ expect(resWin.writeHead).toHaveBeenCalledWith(201, expect.anything())
580
+ } finally {
581
+ argon2.verify = origVerify
582
+ argon2.hash = origHash
583
+ if (origDbCache) _require.cache[resolvedDb] = origDbCache
584
+ else delete _require.cache[resolvedDb]
585
+ if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
586
+ else delete _require.cache[resolvedRedis]
587
+ if (origConfigCache) _require.cache[resolvedConfig] = origConfigCache
588
+ else delete _require.cache[resolvedConfig]
589
+ }
590
+ restore(s)
591
+ })
592
+
593
+ it('covers REDIS_URL truthy branch in applyRedisUpdate', async () => {
594
+ const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
595
+ setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: ':memory:', ADMIN_KEY: 'secret', RATE_LIMIT_ENABLED: 'false' })
596
+
597
+ const argon2 = _require('argon2')
598
+ const origVerify = argon2.verify
599
+ const origHash = argon2.hash
600
+ argon2.verify = vi.fn().mockResolvedValue(true)
601
+ argon2.hash = vi.fn().mockResolvedValue('$argon2id$hash')
602
+
603
+ const mockDb = mkDb({
604
+ getWrappedDb: () => ({
605
+ prepare: (sql) => {
606
+ if (sql.includes('SELECT value FROM settings')) return { get: () => ({ value: '$argon2id$hash' }) }
607
+ if (sql.includes('SELECT key, value FROM settings WHERE key IN')) return { all: () => [{ key: 'REDIS_URL', value: 'redis://myhost:6379/0' }] }
608
+ return { all: () => [], get: () => null, run: () => {} }
609
+ },
610
+ exec: () => {},
611
+ }),
612
+ listAll: () => [],
613
+ TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
614
+ })
615
+
616
+ const resolvedConfig = _require.resolve('../../src/config/index.js')
617
+ const origConfigCache = _require.cache[resolvedConfig]
618
+ clearCjs('../../src/server/index.js', '../../src/server/route.js', '../../src/db/index.js', '../../src/middleware/rate-limiter.js', '../../src/config/index.js')
619
+ const resolvedDb = _require.resolve('../../src/db/index.js')
620
+ const resolvedRedis = _require.resolve('../../src/redis/index.js')
621
+ const { mockRedisClass } = mkRedis({ reconnect: vi.fn().mockRejectedValue(new Error('No Redis')) })
622
+ const origDbCache = _require.cache[resolvedDb]
623
+ const origRedisCache = _require.cache[resolvedRedis]
624
+ _require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
625
+ _require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
626
+
627
+ try {
628
+ vi.resetModules()
629
+ const { requestHandler } = await import('../../src/server/index.js')
630
+
631
+ const res = mkRes()
632
+ await requestHandler(mkReq('/api/admin/settings/REDIS_HOST', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: '10.0.0.1' })), res)
633
+ expect(res.writeHead).toHaveBeenCalledWith(201, expect.anything())
634
+ } finally {
635
+ argon2.verify = origVerify
636
+ argon2.hash = origHash
637
+ if (origDbCache) _require.cache[resolvedDb] = origDbCache
638
+ else delete _require.cache[resolvedDb]
639
+ if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
640
+ else delete _require.cache[resolvedRedis]
641
+ if (origConfigCache) _require.cache[resolvedConfig] = origConfigCache
642
+ else delete _require.cache[resolvedConfig]
643
+ }
644
+ restore(s)
645
+ })
646
+
647
+ it('covers PATCH existing setting UPDATE path and writableEnded', async () => {
648
+ const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
649
+ setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: ':memory:', ADMIN_KEY: 'secret', RATE_LIMIT_ENABLED: 'false' })
650
+
651
+ const argon2 = _require('argon2')
652
+ const origVerify = argon2.verify
653
+ const origHash = argon2.hash
654
+ argon2.verify = vi.fn().mockResolvedValue(true)
655
+ argon2.hash = vi.fn().mockResolvedValue('$argon2id$hash')
656
+
657
+ const settingsTable = [
658
+ { key: 'ADMIN_KEY', value: '$argon2id$hash', description: 'Admin key', updated_at: '2025-01-01' },
659
+ { key: 'RATE_LIMIT_MAX', value: '100', description: 'Rate limit max', updated_at: '2025-01-01' },
660
+ ]
661
+ const mockDb = mkDb({
662
+ getWrappedDb: () => ({
663
+ prepare: (sql) => {
664
+ if (sql.includes('SELECT value FROM settings')) return { get: () => settingsTable[0] }
665
+ return {
666
+ all: () => settingsTable,
667
+ get: (key) => settingsTable.find(s => s.key === key) || null,
668
+ run: () => {},
669
+ }
670
+ },
671
+ exec: () => {},
672
+ }),
673
+ listAll: () => settingsTable,
674
+ TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
675
+ })
676
+
677
+ const resolvedConfig = _require.resolve('../../src/config/index.js')
678
+ clearCjs('../../src/server/index.js', '../../src/server/route.js', '../../src/db/index.js', '../../src/middleware/rate-limiter.js', '../../src/config/index.js')
679
+ const resolvedDb = _require.resolve('../../src/db/index.js')
680
+ const resolvedRedis = _require.resolve('../../src/redis/index.js')
681
+ const { mockRedisClass } = mkRedis()
682
+ const origDbCache = _require.cache[resolvedDb]
683
+ const origRedisCache = _require.cache[resolvedRedis]
684
+ const origConfigCache = _require.cache[resolvedConfig]
685
+ _require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
686
+ _require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
687
+
688
+ try {
689
+ vi.resetModules()
690
+ const { requestHandler, resetAuthCache } = await import('../../src/server/index.js')
691
+
692
+ const res1 = mkRes()
693
+ await requestHandler(mkReq('/api/admin/settings/RATE_LIMIT_MAX', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: '200' })), res1)
694
+ expect(res1.writeHead).toHaveBeenCalledWith(200, expect.anything())
695
+
696
+ const res2 = mkRes()
697
+ res2.writableEnded = true
698
+ await requestHandler(mkReq('/api/users', 'GET'), res2)
699
+ expect(res2.writeHead).not.toHaveBeenCalled()
700
+ } finally {
701
+ argon2.verify = origVerify
702
+ argon2.hash = origHash
703
+ if (origDbCache) _require.cache[resolvedDb] = origDbCache
704
+ else delete _require.cache[resolvedDb]
705
+ if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
706
+ else delete _require.cache[resolvedRedis]
707
+ if (origConfigCache) _require.cache[resolvedConfig] = origConfigCache
708
+ else delete _require.cache[resolvedConfig]
709
+ }
710
+ restore(s)
711
+ })
712
+
713
  it('covers remaining route.js branches together', async () => {
714
  const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
715
  setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: ':memory:', ADMIN_KEY: 'secret' })