Spaces:
Sleeping
Sleeping
Commit ·
2e6d0d7
1
Parent(s): 13def79
feat: add admin routes with argon2 auth
Browse files- Add admin endpoints for runtime configuration and database reset
- Hash and verify admin keys with argon2 using a 5s cached LRU
- Polish the API documentation
- README.md +57 -17
- src/db/seed-settings.js +3 -1
- src/server/index.js +169 -2
- tests/README.md +15 -14
- tests/seed-settings-coverage.test.js +78 -3
- tests/server/coverage-printlog.test.js +18 -0
- tests/server/integration.test.js +113 -1
- tests/server/server.test.js +560 -0
README.md
CHANGED
|
@@ -1,6 +1,17 @@
|
|
| 1 |
# json-api-server
|
| 2 |
|
| 3 |
-
A JSONPlaceholder-compatible REST API built with **Node.js built-ins
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
## Requirements
|
| 6 |
|
|
@@ -54,6 +65,7 @@ Environment files are loaded by `src/config/load-env.js` (auto-run via `src/conf
|
|
| 54 |
| `SEED_API_BASE_URL` | `https://jsonplaceholder.typicode.com` | Base URL for seed data API |
|
| 55 |
| `MAX_BODY_SIZE` | `1048576` | Max request body size in bytes (minimum 1) |
|
| 56 |
| `DEFAULT_PAGE_SIZE` | `10` | Default number of results per page for `_page`/`_limit` pagination |
|
|
|
|
| 57 |
|
| 58 |
---
|
| 59 |
|
|
@@ -149,12 +161,39 @@ GET /api/posts?_sort=id&_order=desc&_limit=2
|
|
| 149 |
|
| 150 |
### System Endpoints
|
| 151 |
|
| 152 |
-
| Path
|
| 153 |
-
|-------------------|--------------------------------------|
|
| 154 |
-
| `GET /`
|
| 155 |
-
| `GET /api`
|
| 156 |
-
| `GET /health`
|
| 157 |
-
| `GET /api/health`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
---
|
| 160 |
|
|
@@ -233,10 +272,10 @@ json-api-server/
|
|
| 233 |
│ └── index.js # HTTP server, routing, middleware, handlers
|
| 234 |
├── tests/
|
| 235 |
│ ├── config/
|
| 236 |
-
│ │ ├── config.test.js # Config defaults and env var branches (
|
| 237 |
│ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
|
| 238 |
│ ├── db/
|
| 239 |
-
│ │ ├── database.test.js # Database CRUD, pagination, search, sort, SQL injection (
|
| 240 |
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 241 |
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 242 |
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
|
@@ -245,16 +284,16 @@ json-api-server/
|
|
| 245 |
│ ├── redis/
|
| 246 |
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options (25)
|
| 247 |
│ ├── server/
|
| 248 |
-
│ │ ├── coverage-printlog.test.js #
|
| 249 |
-
│ │ ├── graceful-shutdown.test.js #
|
| 250 |
-
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (
|
| 251 |
-
│ │ └── server.test.js # Server request handler
|
| 252 |
│ ├── README.md # Testing documentation
|
| 253 |
│ └── helpers/
|
| 254 |
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
| 255 |
│ ├── index.js # startServer / stopServer / request utilities
|
| 256 |
│ └── seed.js # Standalone script to create & seed temp DB
|
| 257 |
-
│ └── seed-settings-coverage.test.js # Seed-settings.js V8 coverage (
|
| 258 |
├── manual/
|
| 259 |
│ ├── curl.sh # Quick curl commands
|
| 260 |
│ └── inspect-queries.sql # SQL queries for database inspection
|
|
@@ -330,12 +369,12 @@ This runs comprehensive queries to inspect row counts, column metadata, relation
|
|
| 330 |
|
| 331 |
## Testing
|
| 332 |
|
| 333 |
-
Uses **vitest** with **V8 native coverage**. **
|
| 334 |
|
| 335 |
```bash
|
| 336 |
npm test # Run all tests once
|
| 337 |
npm run test:watch # Watch mode
|
| 338 |
-
npm run test:coverage # With coverage report (
|
| 339 |
```
|
| 340 |
|
| 341 |
See [tests/README.md](tests/README.md) for full documentation.
|
|
@@ -343,7 +382,7 @@ See [tests/README.md](tests/README.md) for full documentation.
|
|
| 343 |
|
| 344 |
## Implementation Notes
|
| 345 |
|
| 346 |
-
- **Minimal runtime dependencies** — only Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
|
| 347 |
- **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.
|
| 348 |
- **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 349 |
- **Lazy rate-limiter config** — `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
|
@@ -351,6 +390,7 @@ See [tests/README.md](tests/README.md) for full documentation.
|
|
| 351 |
- **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`.
|
| 352 |
- **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.
|
| 353 |
- **SQL injection prevention** — `src/db/index.js` validates `_sort` against a whitelist of known columns and quotes identifiers with `""`; LIKE wildcards (`%`, `_`) are escaped to prevent injection through the `q` parameter
|
|
|
|
| 354 |
- **CORS** enabled on all routes
|
| 355 |
- **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
| 356 |
|
|
|
|
| 1 |
# json-api-server
|
| 2 |
|
| 3 |
+
A JSONPlaceholder-compatible REST API built mostly with **Node.js built-ins** — the only runtime dependency is `argon2` for admin password hashing. Uses `node:sqlite` for storage and a custom Redis client implemented over the raw RESP protocol via TCP sockets.
|
| 4 |
+
|
| 5 |
+
## Technologies Used
|
| 6 |
+
|
| 7 |
+
- **Node.js >= 22** — runtime with built-in `node:sqlite`, `node:http`, `node:net`, etc.
|
| 8 |
+
- **node:sqlite** — SQLite database engine (built-in)
|
| 9 |
+
- **node:http** — HTTP server (built-in, no Express/Fastify)
|
| 10 |
+
- **node:net** — raw TCP sockets for custom Redis RESP client (built-in)
|
| 11 |
+
- **argon2** — secure password hashing for admin authentication (only runtime dependency)
|
| 12 |
+
- **RESP protocol** — custom Redis client implementing the Redis Serialization Protocol over TCP
|
| 13 |
+
- **dotenv** — environment file loading (dev dependency only, skipped in production)
|
| 14 |
+
- **vitest** — test runner with V8 native coverage (dev dependency)
|
| 15 |
|
| 16 |
## Requirements
|
| 17 |
|
|
|
|
| 65 |
| `SEED_API_BASE_URL` | `https://jsonplaceholder.typicode.com` | Base URL for seed data API |
|
| 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 |
|
|
|
|
| 161 |
|
| 162 |
### System Endpoints
|
| 163 |
|
| 164 |
+
| Path | Description |
|
| 165 |
+
|-----------------------------------|--------------------------------------|
|
| 166 |
+
| `GET /` | API info with available endpoints |
|
| 167 |
+
| `GET /api` | API info (same as above) |
|
| 168 |
+
| `GET /health` | Server status (Redis, tables, rate limit config) |
|
| 169 |
+
| `GET /api/health` | Same as above |
|
| 170 |
+
| `GET /api/admin/settings` | List all settings (requires auth) |
|
| 171 |
+
| `PATCH /api/admin/settings/:key` | Update a setting value (requires auth) |
|
| 172 |
+
| `POST /api/admin/reset-database` | Clear data tables and re-seed from JSONPlaceholder (requires auth) |
|
| 173 |
+
|
| 174 |
+
### Admin API
|
| 175 |
+
|
| 176 |
+
Admin endpoints are protected by Bearer token authentication using the `ADMIN_KEY` environment variable. Settings values are stored in the `settings` database table.
|
| 177 |
+
|
| 178 |
+
```bash
|
| 179 |
+
# List all settings
|
| 180 |
+
curl http://localhost:3000/api/admin/settings \
|
| 181 |
+
-H "Authorization: Bearer my-secret-key"
|
| 182 |
+
|
| 183 |
+
# Update a setting
|
| 184 |
+
curl -X PATCH http://localhost:3000/api/admin/settings/NODE_ENV \
|
| 185 |
+
-H "Authorization: Bearer my-secret-key" \
|
| 186 |
+
-H "Content-Type: application/json" \
|
| 187 |
+
-d '{"value": "production"}'
|
| 188 |
+
|
| 189 |
+
# Reset database (clears all data and re-fetches from JSONPlaceholder)
|
| 190 |
+
curl -X POST http://localhost:3000/api/admin/reset-database \
|
| 191 |
+
-H "Authorization: Bearer my-secret-key"
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
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.
|
| 195 |
+
|
| 196 |
+
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.
|
| 197 |
|
| 198 |
---
|
| 199 |
|
|
|
|
| 272 |
│ └── index.js # HTTP server, routing, middleware, handlers
|
| 273 |
├── tests/
|
| 274 |
│ ├── config/
|
| 275 |
+
│ │ ├── config.test.js # Config defaults and env var branches (9)
|
| 276 |
│ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
|
| 277 |
│ ├── db/
|
| 278 |
+
│ │ ├── database.test.js # Database CRUD, pagination, search, sort, SQL injection (10)
|
| 279 |
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 280 |
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 281 |
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
|
|
|
| 284 |
│ ├── redis/
|
| 285 |
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options (25)
|
| 286 |
│ ├── server/
|
| 287 |
+
│ │ ├── coverage-printlog.test.js # Printlog and server export V8 coverage (4)
|
| 288 |
+
│ │ ├── graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1)
|
| 289 |
+
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite (77)
|
| 290 |
+
│ │ └── server.test.js # Server request handler, admin auth, graceful shutdown (13)
|
| 291 |
│ ├── README.md # Testing documentation
|
| 292 |
│ └── helpers/
|
| 293 |
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs)
|
| 294 |
│ ├── index.js # startServer / stopServer / request utilities
|
| 295 |
│ └── seed.js # Standalone script to create & seed temp DB
|
| 296 |
+
│ └── seed-settings-coverage.test.js # Seed-settings.js V8 coverage (4)
|
| 297 |
├── manual/
|
| 298 |
│ ├── curl.sh # Quick curl commands
|
| 299 |
│ └── inspect-queries.sql # SQL queries for database inspection
|
|
|
|
| 369 |
|
| 370 |
## Testing
|
| 371 |
|
| 372 |
+
Uses **vitest** with **V8 native coverage**. **168 tests across 13 test files** cover the full stack — from integration tests (real HTTP server + SQLite) to unit tests for every module.
|
| 373 |
|
| 374 |
```bash
|
| 375 |
npm test # Run all tests once
|
| 376 |
npm run test:watch # Watch mode
|
| 377 |
+
npm run test:coverage # With coverage report (100% statements, 100% branches)
|
| 378 |
```
|
| 379 |
|
| 380 |
See [tests/README.md](tests/README.md) for full documentation.
|
|
|
|
| 382 |
|
| 383 |
## Implementation Notes
|
| 384 |
|
| 385 |
+
- **Minimal runtime dependencies** — only `argon2` for admin password hashing; everything else uses Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
|
| 386 |
- **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.
|
| 387 |
- **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, etc.) for use across the codebase.
|
| 388 |
- **Lazy rate-limiter config** — `src/middleware/rate-limiter.js` reads config inside `createRateLimiter()` (not at module level), allowing different config values per call and making unit testing straightforward.
|
|
|
|
| 390 |
- **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`.
|
| 391 |
- **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.
|
| 392 |
- **SQL injection prevention** — `src/db/index.js` validates `_sort` against a whitelist of known columns and quotes identifiers with `""`; LIKE wildcards (`%`, `_`) are escaped to prevent injection through the `q` parameter
|
| 393 |
+
- **Argon2 auth cache** — `src/server/index.js` caches `ADMIN_KEY` verification results in a `Map` with 5-second TTL, avoiding repeated argon2 hashing on burst admin requests
|
| 394 |
- **CORS** enabled on all routes
|
| 395 |
- **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
| 396 |
|
src/db/seed-settings.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
| 2 |
|
| 3 |
const { getWrappedDb } = require('./index');
|
| 4 |
const { migrate } = require('./migrate');
|
|
|
|
| 5 |
const { SETTING_DEFS } = require('../config/setting-defs');
|
| 6 |
|
| 7 |
async function seedSettings({ database = getWrappedDb(), runMigrate = true } = {}) {
|
|
@@ -24,7 +25,8 @@ async function seedSettings({ database = getWrappedDb(), runMigrate = true } = {
|
|
| 24 |
for (const def of SETTING_DEFS) {
|
| 25 |
const val = process.env[def.key];
|
| 26 |
if (val !== undefined) {
|
| 27 |
-
|
|
|
|
| 28 |
count++;
|
| 29 |
} else {
|
| 30 |
upsert.run(def.key, '', def.description, now);
|
|
|
|
| 2 |
|
| 3 |
const { getWrappedDb } = require('./index');
|
| 4 |
const { migrate } = require('./migrate');
|
| 5 |
+
const argon2 = require('argon2');
|
| 6 |
const { SETTING_DEFS } = require('../config/setting-defs');
|
| 7 |
|
| 8 |
async function seedSettings({ database = getWrappedDb(), runMigrate = true } = {}) {
|
|
|
|
| 25 |
for (const def of SETTING_DEFS) {
|
| 26 |
const val = process.env[def.key];
|
| 27 |
if (val !== undefined) {
|
| 28 |
+
const stored = def.key === 'ADMIN_KEY' ? await argon2.hash(val) : val;
|
| 29 |
+
upsert.run(def.key, stored, def.description, now);
|
| 30 |
count++;
|
| 31 |
} else {
|
| 32 |
upsert.run(def.key, '', def.description, now);
|
src/server/index.js
CHANGED
|
@@ -3,10 +3,13 @@
|
|
| 3 |
const http = require('http');
|
| 4 |
|
| 5 |
const { port, redisOpts, rateLimitMax, rateLimitEnabled,
|
| 6 |
-
rateLimitWindowMs, rateLimitWindowSec, maxBodySize } = require('../config');
|
|
|
|
| 7 |
const RedisClient = require('../redis');
|
| 8 |
const { createRateLimiter } = require('../middleware/rate-limiter');
|
| 9 |
const db = require('../db');
|
|
|
|
|
|
|
| 10 |
|
| 11 |
const redis = new RedisClient(redisOpts);
|
| 12 |
|
|
@@ -200,6 +203,161 @@ function handleHealth(res) {
|
|
| 200 |
});
|
| 201 |
}
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
async function requestHandler(req, res) {
|
| 204 |
const parsed = new URL(req.url, 'http://localhost');
|
| 205 |
const pathname = parsed.pathname;
|
|
@@ -234,6 +392,15 @@ async function requestHandler(req, res) {
|
|
| 234 |
/* v8 ignore next */
|
| 235 |
if (res.writableEnded) return;
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
const route = parseRoute(pathname);
|
| 238 |
if (!route) return notFound(res, `Unknown route: ${pathname}`);
|
| 239 |
if (route.invalidId) return badRequest(res, 'Invalid ID format');
|
|
@@ -308,4 +475,4 @@ if (process.listenerCount('SIGINT') === 0) {
|
|
| 308 |
}
|
| 309 |
|
| 310 |
/* v8 ignore stop */
|
| 311 |
-
module.exports = { server, requestHandler, printLog, closeServer };
|
|
|
|
| 3 |
const http = require('http');
|
| 4 |
|
| 5 |
const { port, redisOpts, rateLimitMax, rateLimitEnabled,
|
| 6 |
+
rateLimitWindowMs, rateLimitWindowSec, maxBodySize, adminKey } = require('../config');
|
| 7 |
+
const argon2 = require('argon2');
|
| 8 |
const RedisClient = require('../redis');
|
| 9 |
const { createRateLimiter } = require('../middleware/rate-limiter');
|
| 10 |
const db = require('../db');
|
| 11 |
+
const { seed } = require('../db/seed');
|
| 12 |
+
const { SETTING_DEFS } = require('../db/seed-settings');
|
| 13 |
|
| 14 |
const redis = new RedisClient(redisOpts);
|
| 15 |
|
|
|
|
| 203 |
});
|
| 204 |
}
|
| 205 |
|
| 206 |
+
const authCache = new Map();
|
| 207 |
+
const AUTH_CACHE_TTL_MS = 5_000;
|
| 208 |
+
|
| 209 |
+
function getCachedAuth(token) {
|
| 210 |
+
const entry = authCache.get(token);
|
| 211 |
+
if (entry && Date.now() - entry.ts < AUTH_CACHE_TTL_MS) {
|
| 212 |
+
return entry.valid;
|
| 213 |
+
}
|
| 214 |
+
authCache.delete(token);
|
| 215 |
+
return undefined;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
function setCachedAuth(token, valid) {
|
| 219 |
+
/* v8 ignore next 5 */
|
| 220 |
+
if (authCache.size > 1000) {
|
| 221 |
+
const cutoff = Date.now() - AUTH_CACHE_TTL_MS;
|
| 222 |
+
for (const [key, entry] of authCache) {
|
| 223 |
+
if (entry.ts < cutoff) authCache.delete(key);
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
authCache.set(token, { valid, ts: Date.now() });
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
function resetAuthCache() {
|
| 230 |
+
authCache.clear();
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
async function checkAdminAuth(req) {
|
| 234 |
+
/* v8 ignore next */
|
| 235 |
+
if (!adminKey) return false;
|
| 236 |
+
const auth = req.headers['authorization'] || '';
|
| 237 |
+
const match = auth.match(/^Bearer\s+(.+)$/i);
|
| 238 |
+
if (!match) return false;
|
| 239 |
+
const token = match[1];
|
| 240 |
+
const cached = getCachedAuth(token);
|
| 241 |
+
if (cached !== undefined) return cached;
|
| 242 |
+
try {
|
| 243 |
+
const d = db.getWrappedDb();
|
| 244 |
+
const row = d.prepare('SELECT value FROM settings WHERE key = ?').get('ADMIN_KEY');
|
| 245 |
+
/* v8 ignore next */
|
| 246 |
+
if (!row) return false;
|
| 247 |
+
const valid = await argon2.verify(row.value, token);
|
| 248 |
+
setCachedAuth(token, valid);
|
| 249 |
+
return valid;
|
| 250 |
+
} catch {
|
| 251 |
+
setCachedAuth(token, false);
|
| 252 |
+
return false;
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
async function handleAdmin(req, res, pathname, method) {
|
| 257 |
+
if (!(await checkAdminAuth(req))) {
|
| 258 |
+
/* v8 ignore start */ if (!adminKey) {
|
| 259 |
+
return json(res, 401, { error: 'Admin not configured', message: 'ADMIN_KEY environment variable is not set' });
|
| 260 |
+
} /* v8 ignore stop */
|
| 261 |
+
return json(res, 401, { error: 'Unauthorized' });
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
const SENSITIVE_KEYS = ['REDIS_PASSWORD', 'ADMIN_KEY'];
|
| 265 |
+
|
| 266 |
+
if (pathname === '/api/admin/settings' && method === 'GET') {
|
| 267 |
+
const rows = db.listAll('settings').map((r) => SENSITIVE_KEYS.includes(r.key) ? { ...r, value: '***' } : r);
|
| 268 |
+
return json(res, 200, rows);
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
const settingsMatch = pathname.match(/^\/api\/admin\/settings\/(.+)$/);
|
| 272 |
+
if (settingsMatch && method === 'PATCH') {
|
| 273 |
+
return await handleAdminPatchSetting(req, res, settingsMatch[1]);
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
if (pathname === '/api/admin/reset-database' && method === 'POST') {
|
| 277 |
+
return await handleAdminResetDatabase(req, res);
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
return notFound(res, `Unknown admin route: ${pathname}`);
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
async function handleAdminPatchSetting(req, res, settingKey) {
|
| 284 |
+
const body = await readBodySafe(req, res);
|
| 285 |
+
if (body === null) return;
|
| 286 |
+
|
| 287 |
+
if (body.value === undefined) {
|
| 288 |
+
return badRequest(res, 'Missing "value" in request body');
|
| 289 |
+
}
|
| 290 |
+
if (body.value === null || typeof body.value === 'object') {
|
| 291 |
+
return badRequest(res, 'Setting value must be a string or number');
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
const d = db.getWrappedDb();
|
| 295 |
+
const existing = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
|
| 296 |
+
|
| 297 |
+
if (!existing) {
|
| 298 |
+
const def = SETTING_DEFS.find(s => s.key === settingKey);
|
| 299 |
+
if (!def) {
|
| 300 |
+
return notFound(res, `Setting '${settingKey}' not found`);
|
| 301 |
+
}
|
| 302 |
+
const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
|
| 303 |
+
d.prepare(`INSERT INTO settings (key, value, description, updated_at) VALUES (?, ?, ?, datetime('now'))`).run(settingKey, valToStore, def.description);
|
| 304 |
+
const created = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
|
| 305 |
+
return json(res, 201, created);
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
const valToStore = settingKey === 'ADMIN_KEY' ? await argon2.hash(body.value) : body.value;
|
| 309 |
+
d.prepare(`UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = ?`).run(valToStore, settingKey);
|
| 310 |
+
const updated = d.prepare('SELECT * FROM settings WHERE key = ?').get(settingKey);
|
| 311 |
+
json(res, 200, updated);
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
let resetLock = Promise.resolve();
|
| 315 |
+
const RESET_LOCK_TIMEOUT_MS = 30_000;
|
| 316 |
+
|
| 317 |
+
async function withResetLock(fn) {
|
| 318 |
+
let release;
|
| 319 |
+
let timer;
|
| 320 |
+
const prev = resetLock;
|
| 321 |
+
resetLock = new Promise((resolve) => { release = resolve; });
|
| 322 |
+
await prev;
|
| 323 |
+
/* v8 ignore next 2 */
|
| 324 |
+
timer = setTimeout(() => { release(); }, RESET_LOCK_TIMEOUT_MS);
|
| 325 |
+
try {
|
| 326 |
+
return await fn();
|
| 327 |
+
} finally {
|
| 328 |
+
clearTimeout(timer);
|
| 329 |
+
release();
|
| 330 |
+
}
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
async function handleAdminResetDatabase(req, res) {
|
| 334 |
+
await withResetLock(async () => {
|
| 335 |
+
const d = db.getWrappedDb();
|
| 336 |
+
d.exec('BEGIN');
|
| 337 |
+
try {
|
| 338 |
+
const deleteOrder = ['photos', 'comments', 'albums', 'posts', 'todos', 'users'];
|
| 339 |
+
for (const table of deleteOrder) {
|
| 340 |
+
d.prepare(`DELETE FROM ${table}`).run();
|
| 341 |
+
}
|
| 342 |
+
/* v8 ignore next */
|
| 343 |
+
if (d.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sqlite_sequence'").get()) {
|
| 344 |
+
d.exec('DELETE FROM sqlite_sequence');
|
| 345 |
+
}
|
| 346 |
+
/* v8 ignore next 4 */
|
| 347 |
+
const fetchFn = async (url) => {
|
| 348 |
+
const response = await globalThis.fetch(url);
|
| 349 |
+
return response.json();
|
| 350 |
+
};
|
| 351 |
+
await seed({ database: d, fetch: fetchFn, runMigrate: false, skipTransaction: true });
|
| 352 |
+
d.exec('COMMIT');
|
| 353 |
+
json(res, 200, { message: 'Database reset and re-seeded successfully' });
|
| 354 |
+
} catch (error) {
|
| 355 |
+
d.exec('ROLLBACK');
|
| 356 |
+
throw error;
|
| 357 |
+
}
|
| 358 |
+
});
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
async function requestHandler(req, res) {
|
| 362 |
const parsed = new URL(req.url, 'http://localhost');
|
| 363 |
const pathname = parsed.pathname;
|
|
|
|
| 392 |
/* v8 ignore next */
|
| 393 |
if (res.writableEnded) return;
|
| 394 |
|
| 395 |
+
if (pathname.startsWith('/api/admin/')) {
|
| 396 |
+
try {
|
| 397 |
+
return await handleAdmin(req, res, pathname, method);
|
| 398 |
+
} catch (err) {
|
| 399 |
+
console.error('[Error]', err);
|
| 400 |
+
return json(res, 500, { error: 'Internal Server Error', message: err.message });
|
| 401 |
+
}
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
const route = parseRoute(pathname);
|
| 405 |
if (!route) return notFound(res, `Unknown route: ${pathname}`);
|
| 406 |
if (route.invalidId) return badRequest(res, 'Invalid ID format');
|
|
|
|
| 475 |
}
|
| 476 |
|
| 477 |
/* v8 ignore stop */
|
| 478 |
+
module.exports = { server, requestHandler, printLog, closeServer, resetAuthCache };
|
tests/README.md
CHANGED
|
@@ -19,7 +19,7 @@ npm run test:coverage # Run with coverage report
|
|
| 19 |
tests/
|
| 20 |
config/
|
| 21 |
config.test.js # Config defaults and env var branches (9 tests)
|
| 22 |
-
load-env.test.js #
|
| 23 |
db/
|
| 24 |
database.test.js # Database CRUD, pagination, search, sort, SQL injection (10 tests)
|
| 25 |
migrate.test.js # Migration success and failure paths (2 tests)
|
|
@@ -30,18 +30,18 @@ tests/
|
|
| 30 |
redis/
|
| 31 |
redis.test.js # RESP protocol encoding/parsing, constructor options (25 tests)
|
| 32 |
server/
|
| 33 |
-
coverage-printlog.test.js #
|
| 34 |
graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1 test)
|
| 35 |
-
integration.test.js # API integration tests — real HTTP + SQLite (
|
| 36 |
-
server.test.js # Server request handler
|
| 37 |
helpers/
|
| 38 |
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
| 39 |
index.js # startServer / stopServer / request utilities
|
| 40 |
seed.js # Standalone script to create & seed temp DB
|
| 41 |
-
seed-settings-coverage.test.js # Seed-settings.js V8 coverage (
|
| 42 |
```
|
| 43 |
|
| 44 |
-
**Total:
|
| 45 |
|
| 46 |
## Test design
|
| 47 |
|
|
@@ -56,12 +56,13 @@ Unit tests cover every source module individually. Each module has its own test
|
|
| 56 |
| Module | Test file | Approach |
|
| 57 |
|--------------------------------|------------------------------|----------|
|
| 58 |
| `config/index.js` | `tests/config/config.test.js` | Module re-imported with different `process.env` values |
|
| 59 |
-
| `
|
|
|
|
| 60 |
| `middleware/rate-limiter.js` | `tests/middleware/rate-limiter.test.js` | Module imported once; `createRateLimiter()` with different configs per test |
|
| 61 |
| `redis/index.js` | `tests/redis/redis.test.js` | RESP encoding/parsing directly; constructor options |
|
| 62 |
-
| `server/index.js` | `tests/server/server.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock |
|
| 63 |
-
| `server/index.js` (child) | `tests/server/graceful-shutdown.test.js` | SIGINT/SIGTERM via child process (V8 coverage) |
|
| 64 |
| `server/index.js` (ESM) | `tests/server/coverage-printlog.test.js` | Dynamic `import()` for V8-covered printLog, startServer, 500 catch |
|
|
|
|
| 65 |
| `db/migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
|
| 66 |
| `db/seed.js` | `tests/db/seed.test.js` | Dependency injection — `database` and `fetch` injected |
|
| 67 |
| `db/seed-settings.js` | `tests/seed-settings-coverage.test.js` | Real DB + mock DB paths (V8 coverage) |
|
|
@@ -90,9 +91,9 @@ npm run test:coverage
|
|
| 90 |
|
| 91 |
| Metric | Coverage |
|
| 92 |
|-------------|----------|
|
| 93 |
-
| Statements |
|
| 94 |
-
| Branches |
|
| 95 |
-
| Functions |
|
| 96 |
-
| Lines |
|
| 97 |
|
| 98 |
-
All source files reach
|
|
|
|
| 19 |
tests/
|
| 20 |
config/
|
| 21 |
config.test.js # Config defaults and env var branches (9 tests)
|
| 22 |
+
load-env.test.js # Chain-loading, override:false, production skip, fallback (7 tests)
|
| 23 |
db/
|
| 24 |
database.test.js # Database CRUD, pagination, search, sort, SQL injection (10 tests)
|
| 25 |
migrate.test.js # Migration success and failure paths (2 tests)
|
|
|
|
| 30 |
redis/
|
| 31 |
redis.test.js # RESP protocol encoding/parsing, constructor options (25 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 |
+
server.test.js # Server request handler, admin auth, graceful shutdown (13 tests)
|
| 37 |
helpers/
|
| 38 |
coverage.js # Shared test utilities (save/restore/setEnv/clearCjs)
|
| 39 |
index.js # startServer / stopServer / request utilities
|
| 40 |
seed.js # Standalone script to create & seed temp DB
|
| 41 |
+
seed-settings-coverage.test.js # Seed-settings.js V8 coverage (4 tests)
|
| 42 |
```
|
| 43 |
|
| 44 |
+
**Total: 168 tests across 13 test files.**
|
| 45 |
|
| 46 |
## Test design
|
| 47 |
|
|
|
|
| 56 |
| Module | Test file | Approach |
|
| 57 |
|--------------------------------|------------------------------|----------|
|
| 58 |
| `config/index.js` | `tests/config/config.test.js` | Module re-imported with different `process.env` values |
|
| 59 |
+
| `config/load-env.js` | `tests/config/load-env.test.js` | Temp env dirs, mocked dotenv; tests chain, override:false, ENOENT, parse errors |
|
| 60 |
+
| `db/index.js` | `tests/db/database.test.js` | Real `node:sqlite` databases; tests pagination, search, sort, SQL injection |
|
| 61 |
| `middleware/rate-limiter.js` | `tests/middleware/rate-limiter.test.js` | Module imported once; `createRateLimiter()` with different configs per test |
|
| 62 |
| `redis/index.js` | `tests/redis/redis.test.js` | RESP encoding/parsing directly; constructor options |
|
| 63 |
+
| `server/index.js` | `tests/server/server.test.js` | `requestHandler()` with mock req/res; CJS cache injection for DB mock; tests auth caching and graceful shutdown (13 tests) |
|
|
|
|
| 64 |
| `server/index.js` (ESM) | `tests/server/coverage-printlog.test.js` | Dynamic `import()` for V8-covered printLog, startServer, 500 catch |
|
| 65 |
+
| `server/index.js` (child) | `tests/server/graceful-shutdown.test.js` | SIGINT/SIGTERM via child process (V8 coverage) |
|
| 66 |
| `db/migrate.js` | `tests/db/migrate.test.js` | Real migration + corrupt DB failure path |
|
| 67 |
| `db/seed.js` | `tests/db/seed.test.js` | Dependency injection — `database` and `fetch` injected |
|
| 68 |
| `db/seed-settings.js` | `tests/seed-settings-coverage.test.js` | Real DB + mock DB paths (V8 coverage) |
|
|
|
|
| 91 |
|
| 92 |
| Metric | Coverage |
|
| 93 |
|-------------|----------|
|
| 94 |
+
| Statements | 100% |
|
| 95 |
+
| Branches | 100% |
|
| 96 |
+
| Functions | 100% |
|
| 97 |
+
| Lines | 100% |
|
| 98 |
|
| 99 |
+
All source files reach 100% V8 coverage across all metrics.
|
tests/seed-settings-coverage.test.js
CHANGED
|
@@ -1,17 +1,51 @@
|
|
| 1 |
-
import { describe, it, expect, vi, afterAll } from 'vitest'
|
| 2 |
import { createRequire } from 'module'
|
| 3 |
import { mkdtempSync, rmSync } from 'fs'
|
| 4 |
import { tmpdir } from 'os'
|
| 5 |
import { join } from 'path'
|
|
|
|
| 6 |
|
| 7 |
const _require = createRequire(import.meta.url)
|
|
|
|
| 8 |
const tmpDir = mkdtempSync(join(tmpdir(), 'ss-cov-'))
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
afterAll(() => {
|
| 11 |
try { rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 12 |
})
|
| 13 |
|
| 14 |
describe('seed-settings.js', () => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
it('calls migrate and seeds env vars when runMigrate is true', async () => {
|
| 16 |
const dbPath = join(tmpDir, 'seed-settings.db')
|
| 17 |
const origDbPath = process.env.DB_PATH
|
|
@@ -36,10 +70,51 @@ describe('seed-settings.js', () => {
|
|
| 36 |
else delete process.env.DB_PATH
|
| 37 |
})
|
| 38 |
|
| 39 |
-
it('
|
| 40 |
const origAdminKey = process.env.ADMIN_KEY
|
| 41 |
-
process.env.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
const mockDb = {
|
| 44 |
prepare: () => ({ run: vi.fn(), get: vi.fn().mockReturnValue({ rowCount: 0 }) }),
|
| 45 |
exec: vi.fn(),
|
|
|
|
| 1 |
+
import { describe, it, expect, vi, afterAll, afterEach } from 'vitest'
|
| 2 |
import { createRequire } from 'module'
|
| 3 |
import { mkdtempSync, rmSync } from 'fs'
|
| 4 |
import { tmpdir } from 'os'
|
| 5 |
import { join } from 'path'
|
| 6 |
+
import { createClearCjs } from './helpers/coverage'
|
| 7 |
|
| 8 |
const _require = createRequire(import.meta.url)
|
| 9 |
+
const clearCjs = createClearCjs(import.meta.url)
|
| 10 |
const tmpDir = mkdtempSync(join(tmpdir(), 'ss-cov-'))
|
| 11 |
|
| 12 |
+
afterEach(() => {
|
| 13 |
+
clearCjs('../src/db/seed-settings.js', '../src/db/index.js', '../src/db/migrate.js', '../src/config/index.js')
|
| 14 |
+
})
|
| 15 |
+
|
| 16 |
afterAll(() => {
|
| 17 |
try { rmSync(tmpDir, { recursive: true, force: true }) } catch {}
|
| 18 |
})
|
| 19 |
|
| 20 |
describe('seed-settings.js', () => {
|
| 21 |
+
it('hashes ADMIN_KEY with argon2 when seeding', { timeout: 10000 }, async () => {
|
| 22 |
+
const origAdminKey = process.env.ADMIN_KEY
|
| 23 |
+
process.env.ADMIN_KEY = 'my-secret-admin-key'
|
| 24 |
+
|
| 25 |
+
const dbPath = join(tmpDir, 'argon2-hash-test.db')
|
| 26 |
+
const origDbPath = process.env.DB_PATH
|
| 27 |
+
process.env.DB_PATH = dbPath
|
| 28 |
+
|
| 29 |
+
clearCjs()
|
| 30 |
+
const seedSettings = _require('../src/db/seed-settings.js').seedSettings
|
| 31 |
+
await seedSettings()
|
| 32 |
+
|
| 33 |
+
const { DatabaseSync } = await import('node:sqlite')
|
| 34 |
+
const db = new DatabaseSync(dbPath)
|
| 35 |
+
const row = db.prepare("SELECT value FROM settings WHERE key = 'ADMIN_KEY'").get()
|
| 36 |
+
db.close()
|
| 37 |
+
|
| 38 |
+
expect(row.value).toMatch(/^\$argon2/)
|
| 39 |
+
|
| 40 |
+
const argon2 = _require('argon2')
|
| 41 |
+
const valid = await argon2.verify(row.value, 'my-secret-admin-key')
|
| 42 |
+
expect(valid).toBe(true)
|
| 43 |
+
|
| 44 |
+
if (origAdminKey !== undefined) process.env.ADMIN_KEY = origAdminKey
|
| 45 |
+
else delete process.env.ADMIN_KEY
|
| 46 |
+
if (origDbPath) process.env.DB_PATH = origDbPath
|
| 47 |
+
else delete process.env.DB_PATH
|
| 48 |
+
})
|
| 49 |
it('calls migrate and seeds env vars when runMigrate is true', async () => {
|
| 50 |
const dbPath = join(tmpDir, 'seed-settings.db')
|
| 51 |
const origDbPath = process.env.DB_PATH
|
|
|
|
| 70 |
else delete process.env.DB_PATH
|
| 71 |
})
|
| 72 |
|
| 73 |
+
it('end-to-end: admin auth works with real argon2 and real DB (no mock)', { timeout: 15000 }, async () => {
|
| 74 |
const origAdminKey = process.env.ADMIN_KEY
|
| 75 |
+
const origDbPath = process.env.DB_PATH
|
| 76 |
+
const origStartServer = process.env.START_SERVER
|
| 77 |
+
const secret = 'my-e2e-secret-key'
|
| 78 |
+
const dbPath = join(tmpDir, 'e2e-admin-auth.db')
|
| 79 |
+
process.env.ADMIN_KEY = secret
|
| 80 |
+
process.env.DB_PATH = dbPath
|
| 81 |
+
process.env.START_SERVER = 'false'
|
| 82 |
+
|
| 83 |
+
clearCjs('../src/db/seed-settings.js', '../src/db/index.js', '../src/db/migrate.js', '../src/config/index.js', '../src/server/index.js')
|
| 84 |
+
const { seedSettings } = _require('../src/db/seed-settings.js')
|
| 85 |
+
await seedSettings()
|
| 86 |
+
|
| 87 |
+
clearCjs('../src/db/seed-settings.js', '../src/db/index.js', '../src/db/migrate.js', '../src/config/index.js')
|
| 88 |
+
vi.resetModules()
|
| 89 |
+
const { requestHandler } = await import('../src/server/index.js')
|
| 90 |
+
|
| 91 |
+
const mkReq = (url, method, headers) => ({ url, method, headers, socket: { remoteAddress: '::1' }, on: () => {} })
|
| 92 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 93 |
+
|
| 94 |
+
const res = mkRes()
|
| 95 |
+
const req = mkReq('/api/admin/settings', 'GET', { authorization: `Bearer ${secret}` })
|
| 96 |
+
await requestHandler(req, res)
|
| 97 |
+
|
| 98 |
+
expect(res.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 99 |
+
const body = JSON.parse(res.end.mock.calls[0][0])
|
| 100 |
+
expect(Array.isArray(body)).toBe(true)
|
| 101 |
+
expect(body.find(r => r.key === 'ADMIN_KEY').value).toBe('***')
|
| 102 |
|
| 103 |
+
const res2 = mkRes()
|
| 104 |
+
const req2 = mkReq('/api/admin/settings', 'GET', { authorization: 'Bearer wrong-key' })
|
| 105 |
+
await requestHandler(req2, res2)
|
| 106 |
+
expect(res2.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 107 |
+
|
| 108 |
+
if (origAdminKey !== undefined) process.env.ADMIN_KEY = origAdminKey
|
| 109 |
+
else delete process.env.ADMIN_KEY
|
| 110 |
+
if (origDbPath) process.env.DB_PATH = origDbPath
|
| 111 |
+
else delete process.env.DB_PATH
|
| 112 |
+
if (origStartServer !== undefined) process.env.START_SERVER = origStartServer
|
| 113 |
+
else delete process.env.START_SERVER
|
| 114 |
+
})
|
| 115 |
+
|
| 116 |
+
it('skips migrate when runMigrate is false', async () => {
|
| 117 |
+
const origAdminKey = process.env.ADMIN_KEY
|
| 118 |
const mockDb = {
|
| 119 |
prepare: () => ({ run: vi.fn(), get: vi.fn().mockReturnValue({ rowCount: 0 }) }),
|
| 120 |
exec: vi.fn(),
|
tests/server/coverage-printlog.test.js
CHANGED
|
@@ -113,4 +113,22 @@ describe('server.js ESM coverage', () => {
|
|
| 113 |
await new Promise((r) => mod.server.close(r))
|
| 114 |
restore(s)
|
| 115 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
})
|
|
|
|
| 113 |
await new Promise((r) => mod.server.close(r))
|
| 114 |
restore(s)
|
| 115 |
})
|
| 116 |
+
|
| 117 |
+
it('covers resetAuthCache and server export', async () => {
|
| 118 |
+
const s = save('START_SERVER', 'DB_PATH')
|
| 119 |
+
process.env.START_SERVER = 'false'
|
| 120 |
+
process.env.DB_PATH = ':memory:'
|
| 121 |
+
|
| 122 |
+
clearCjs('../../src/config/index.js', '../../src/config/load-env.js')
|
| 123 |
+
vi.resetModules()
|
| 124 |
+
const mod = await import('../../src/server/index.js')
|
| 125 |
+
|
| 126 |
+
expect(typeof mod.resetAuthCache).toBe('function')
|
| 127 |
+
expect(() => mod.resetAuthCache()).not.toThrow()
|
| 128 |
+
expect(mod.server).toBeDefined()
|
| 129 |
+
expect(typeof mod.requestHandler).toBe('function')
|
| 130 |
+
expect(typeof mod.printLog).toBe('function')
|
| 131 |
+
|
| 132 |
+
restore(s)
|
| 133 |
+
})
|
| 134 |
})
|
tests/server/integration.test.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
import { beforeAll, afterAll, describe, it, expect } from 'vitest';
|
| 2 |
import { startServer, stopServer, request } from '../helpers';
|
| 3 |
|
| 4 |
beforeAll(async () => {
|
|
|
|
| 5 |
await startServer();
|
| 6 |
}, 20000);
|
| 7 |
|
|
@@ -9,6 +10,10 @@ afterAll(() => {
|
|
| 9 |
stopServer();
|
| 10 |
});
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
describe('Health & Root', () => {
|
| 13 |
it('GET /health returns 200 with server status', async () => {
|
| 14 |
const res = await request('/health');
|
|
@@ -508,3 +513,110 @@ describe('Sorting', () => {
|
|
| 508 |
expect(res.body[1].id).toBe(4);
|
| 509 |
});
|
| 510 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { beforeAll, afterAll, afterEach, describe, it, expect, vi } from 'vitest';
|
| 2 |
import { startServer, stopServer, request } from '../helpers';
|
| 3 |
|
| 4 |
beforeAll(async () => {
|
| 5 |
+
process.env.ADMIN_KEY = 'integration-test-admin-key';
|
| 6 |
await startServer();
|
| 7 |
}, 20000);
|
| 8 |
|
|
|
|
| 10 |
stopServer();
|
| 11 |
});
|
| 12 |
|
| 13 |
+
afterEach(() => {
|
| 14 |
+
vi.unstubAllGlobals();
|
| 15 |
+
});
|
| 16 |
+
|
| 17 |
describe('Health & Root', () => {
|
| 18 |
it('GET /health returns 200 with server status', async () => {
|
| 19 |
const res = await request('/health');
|
|
|
|
| 513 |
expect(res.body[1].id).toBe(4);
|
| 514 |
});
|
| 515 |
});
|
| 516 |
+
|
| 517 |
+
describe('Admin routes', () => {
|
| 518 |
+
let adminToken = 'integration-test-admin-key';
|
| 519 |
+
|
| 520 |
+
it('GET /api/admin/settings returns 401 without Authorization header', async () => {
|
| 521 |
+
const res = await request('/api/admin/settings');
|
| 522 |
+
expect(res.status).toBe(401);
|
| 523 |
+
expect(res.body.error).toBeDefined();
|
| 524 |
+
});
|
| 525 |
+
|
| 526 |
+
it('GET /api/admin/settings returns 401 with wrong token', async () => {
|
| 527 |
+
const res = await request('/api/admin/settings', {
|
| 528 |
+
headers: { authorization: 'Bearer wrong-key' },
|
| 529 |
+
});
|
| 530 |
+
expect(res.status).toBe(401);
|
| 531 |
+
});
|
| 532 |
+
|
| 533 |
+
it('GET /api/admin/settings returns 200 with valid auth', async () => {
|
| 534 |
+
const res = await request('/api/admin/settings', {
|
| 535 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 536 |
+
});
|
| 537 |
+
expect(res.status).toBe(200);
|
| 538 |
+
expect(Array.isArray(res.body)).toBe(true);
|
| 539 |
+
expect(res.body.length).toBeGreaterThan(0);
|
| 540 |
+
});
|
| 541 |
+
|
| 542 |
+
it('GET /api/admin/settings hides sensitive values (ADMIN_KEY, REDIS_PASSWORD)', async () => {
|
| 543 |
+
const res = await request('/api/admin/settings', {
|
| 544 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 545 |
+
});
|
| 546 |
+
expect(res.status).toBe(200);
|
| 547 |
+
const adminKeySetting = res.body.find(s => s.key === 'ADMIN_KEY');
|
| 548 |
+
expect(adminKeySetting).toBeDefined();
|
| 549 |
+
expect(adminKeySetting.value).toBe('***');
|
| 550 |
+
const redisPwSetting = res.body.find(s => s.key === 'REDIS_PASSWORD');
|
| 551 |
+
expect(redisPwSetting).toBeDefined();
|
| 552 |
+
expect(redisPwSetting.value).toBe('***');
|
| 553 |
+
});
|
| 554 |
+
|
| 555 |
+
it('PATCH /api/admin/settings/:key updates a setting value', async () => {
|
| 556 |
+
const res = await request('/api/admin/settings/NODE_ENV', {
|
| 557 |
+
method: 'PATCH',
|
| 558 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 559 |
+
body: { value: 'staging' },
|
| 560 |
+
});
|
| 561 |
+
expect(res.status).toBe(200);
|
| 562 |
+
expect(res.body.value).toBe('staging');
|
| 563 |
+
});
|
| 564 |
+
|
| 565 |
+
it('PATCH /api/admin/settings/:key with invalid body returns 400', async () => {
|
| 566 |
+
const res = await request('/api/admin/settings/NODE_ENV', {
|
| 567 |
+
method: 'PATCH',
|
| 568 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 569 |
+
rawBody: 'not-json',
|
| 570 |
+
});
|
| 571 |
+
expect(res.status).toBe(400);
|
| 572 |
+
});
|
| 573 |
+
|
| 574 |
+
it('PATCH /api/admin/settings/:key for nonexistent setting returns 404', async () => {
|
| 575 |
+
const res = await request('/api/admin/settings/NONEXISTENT_KEY', {
|
| 576 |
+
method: 'PATCH',
|
| 577 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 578 |
+
body: { value: 'test' },
|
| 579 |
+
});
|
| 580 |
+
expect(res.status).toBe(404);
|
| 581 |
+
});
|
| 582 |
+
|
| 583 |
+
it('Unknown admin route returns 404', async () => {
|
| 584 |
+
const res = await request('/api/admin/unknown', {
|
| 585 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 586 |
+
});
|
| 587 |
+
expect(res.status).toBe(404);
|
| 588 |
+
});
|
| 589 |
+
|
| 590 |
+
it('Admin routes use cached auth token on repeated requests', async () => {
|
| 591 |
+
const res1 = await request('/api/admin/settings', {
|
| 592 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 593 |
+
});
|
| 594 |
+
expect(res1.status).toBe(200);
|
| 595 |
+
|
| 596 |
+
const res2 = await request('/api/admin/settings', {
|
| 597 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 598 |
+
});
|
| 599 |
+
expect(res2.status).toBe(200);
|
| 600 |
+
});
|
| 601 |
+
|
| 602 |
+
it('POST /api/admin/reset-database re-seeds successfully', async () => {
|
| 603 |
+
const payload = {
|
| 604 |
+
users: [{ id: 1, name: 'Alice', username: 'alice', email: 'alice@example.com', phone: '1', website: 'w', address: { city: 'Hanoi' }, company: { name: 'ACME' } }],
|
| 605 |
+
posts: [{ id: 1, userId: 1, title: 'Post', body: 'Body' }],
|
| 606 |
+
comments: [{ id: 1, postId: 1, name: 'Commenter', email: 'c@example.com', body: 'Comment' }],
|
| 607 |
+
albums: [{ id: 1, userId: 1, title: 'Album' }],
|
| 608 |
+
photos: [{ id: 1, albumId: 1, title: 'Photo', url: 'u', thumbnailUrl: 't' }],
|
| 609 |
+
todos: [{ id: 1, userId: 1, title: 'Todo', completed: true }],
|
| 610 |
+
};
|
| 611 |
+
vi.stubGlobal('fetch', async (url) => ({
|
| 612 |
+
ok: true,
|
| 613 |
+
json: async () => payload[new URL(url).pathname.slice(1)],
|
| 614 |
+
}));
|
| 615 |
+
const res = await request('/api/admin/reset-database', {
|
| 616 |
+
method: 'POST',
|
| 617 |
+
headers: { authorization: `Bearer ${adminToken}` },
|
| 618 |
+
});
|
| 619 |
+
expect(res.status).toBe(200);
|
| 620 |
+
expect(res.body.message).toContain('reset');
|
| 621 |
+
});
|
| 622 |
+
});
|
tests/server/server.test.js
CHANGED
|
@@ -78,6 +78,79 @@ describe('server.js', () => {
|
|
| 78 |
restore(s)
|
| 79 |
})
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
it('covers listen block', async () => {
|
| 82 |
const s = save('PORT', 'REDIS_URL')
|
| 83 |
setEnv({ PORT: '0', REDIS_URL: '' })
|
|
@@ -162,6 +235,159 @@ describe('server.js', () => {
|
|
| 162 |
restore(s)
|
| 163 |
})
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
it('covers Redis connected path in IIFE', async () => {
|
| 166 |
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH')
|
| 167 |
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-redis.db') })
|
|
@@ -220,4 +446,338 @@ describe('server.js', () => {
|
|
| 220 |
}
|
| 221 |
restore(s)
|
| 222 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
})
|
|
|
|
| 78 |
restore(s)
|
| 79 |
})
|
| 80 |
|
| 81 |
+
it('rejects invalid pagination params with 400', async () => {
|
| 82 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH')
|
| 83 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-pag.db') })
|
| 84 |
+
const mockDb = {
|
| 85 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 86 |
+
getWrappedDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 87 |
+
listAll: () => [],
|
| 88 |
+
getOne: () => null,
|
| 89 |
+
insertOne: () => null,
|
| 90 |
+
updateOne: () => null,
|
| 91 |
+
deleteOne: () => null,
|
| 92 |
+
nextId: () => 1,
|
| 93 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos'],
|
| 94 |
+
}
|
| 95 |
+
clearCjs('../../src/server/index.js', '../../src/db/index.js', '../../src/middleware/rate-limiter.js')
|
| 96 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 97 |
+
_require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 98 |
+
try {
|
| 99 |
+
vi.resetModules()
|
| 100 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 101 |
+
const mkReq = (url) => ({ url, method: 'GET', headers: {}, socket: { remoteAddress: '::1' }, on: () => {} })
|
| 102 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 103 |
+
|
| 104 |
+
const badParams = ['_page=abc', '_limit=-1', '_start=NaN', '_end=1.5']
|
| 105 |
+
for (const param of badParams) {
|
| 106 |
+
const res = mkRes()
|
| 107 |
+
await requestHandler(mkReq(`/api/users?${param}`), res)
|
| 108 |
+
expect(res.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
const goodRes = mkRes()
|
| 112 |
+
await requestHandler(mkReq('/api/users?_page=1&_limit=5'), goodRes)
|
| 113 |
+
expect(goodRes.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 114 |
+
} finally {
|
| 115 |
+
delete _require.cache[resolvedDb]
|
| 116 |
+
}
|
| 117 |
+
restore(s)
|
| 118 |
+
})
|
| 119 |
+
|
| 120 |
+
it('returns 400 for non-numeric ID in route', async () => {
|
| 121 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH')
|
| 122 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-id.db') })
|
| 123 |
+
const mockDb = {
|
| 124 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 125 |
+
getWrappedDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 126 |
+
listAll: () => [],
|
| 127 |
+
getOne: () => null,
|
| 128 |
+
insertOne: () => null,
|
| 129 |
+
updateOne: () => null,
|
| 130 |
+
deleteOne: () => null,
|
| 131 |
+
nextId: () => 1,
|
| 132 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos'],
|
| 133 |
+
}
|
| 134 |
+
clearCjs('../../src/server/index.js', '../../src/db/index.js', '../../src/middleware/rate-limiter.js')
|
| 135 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 136 |
+
_require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 137 |
+
try {
|
| 138 |
+
vi.resetModules()
|
| 139 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 140 |
+
const mkReq = (url) => ({ url, method: 'GET', headers: {}, socket: { remoteAddress: '::1' }, on: () => {} })
|
| 141 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 142 |
+
|
| 143 |
+
const res = mkRes()
|
| 144 |
+
await requestHandler(mkReq('/api/users/abc'), res)
|
| 145 |
+
expect(res.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 146 |
+
const body = JSON.parse(res.end.mock.calls[0][0])
|
| 147 |
+
expect(body.error).toBe('Invalid ID format')
|
| 148 |
+
} finally {
|
| 149 |
+
delete _require.cache[resolvedDb]
|
| 150 |
+
}
|
| 151 |
+
restore(s)
|
| 152 |
+
})
|
| 153 |
+
|
| 154 |
it('covers listen block', async () => {
|
| 155 |
const s = save('PORT', 'REDIS_URL')
|
| 156 |
setEnv({ PORT: '0', REDIS_URL: '' })
|
|
|
|
| 235 |
restore(s)
|
| 236 |
})
|
| 237 |
|
| 238 |
+
it('covers admin routes', async () => {
|
| 239 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY', 'MAX_BODY_SIZE')
|
| 240 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-admin.db'), ADMIN_KEY: 'secret', MAX_BODY_SIZE: '100' })
|
| 241 |
+
|
| 242 |
+
const argon2Mock = _require('argon2')
|
| 243 |
+
argon2Mock.verify = vi.fn().mockImplementation((hash, pwd) => Promise.resolve(pwd === 'secret'))
|
| 244 |
+
argon2Mock.hash = vi.fn().mockResolvedValue('$argon2id$v=19$m=65536,t=3,p=4$mockedhash')
|
| 245 |
+
|
| 246 |
+
const settingsTable = [
|
| 247 |
+
{ key: 'ADMIN_KEY', value: '$argon2id$v=19$m=65536,t=3,p=4$mockedhash', description: 'Admin key', updated_at: '2025-01-01' },
|
| 248 |
+
{ key: 'NODE_ENV', value: 'development', description: 'Environment', updated_at: '2025-01-01' },
|
| 249 |
+
{ key: 'REDIS_PASSWORD', value: 'mockpassword', description: 'Redis password', updated_at: '2025-01-01' },
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
const mockDb = {
|
| 253 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 254 |
+
getWrappedDb: () => ({
|
| 255 |
+
prepare: (sql) => {
|
| 256 |
+
if (sql.includes('SELECT value FROM settings')) {
|
| 257 |
+
return { get: () => settingsTable[0] }
|
| 258 |
+
}
|
| 259 |
+
if (sql.includes('SELECT * FROM settings WHERE key')) {
|
| 260 |
+
return { get: (key) => settingsTable.find(s => s.key === key) || null }
|
| 261 |
+
}
|
| 262 |
+
if (sql.includes('UPDATE settings SET')) {
|
| 263 |
+
return { run: () => { settingsTable[0].value = 'updated' } }
|
| 264 |
+
}
|
| 265 |
+
return { all: () => settingsTable, get: () => null, run: () => {} }
|
| 266 |
+
},
|
| 267 |
+
exec: () => {},
|
| 268 |
+
}),
|
| 269 |
+
listAll: () => settingsTable,
|
| 270 |
+
getOne: () => null,
|
| 271 |
+
insertOne: () => null,
|
| 272 |
+
updateOne: () => null,
|
| 273 |
+
deleteOne: () => null,
|
| 274 |
+
nextId: () => 1,
|
| 275 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 279 |
+
const resolvedRedis = _require.resolve('../../src/redis/index.js')
|
| 280 |
+
const resolvedSeed = _require.resolve('../../src/db/seed.js')
|
| 281 |
+
const mockRedisClass = function() { return { connect: vi.fn().mockResolvedValue(), ping: vi.fn().mockResolvedValue(), connected: false, quit: vi.fn().mockResolvedValue() } }
|
| 282 |
+
|
| 283 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 284 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 285 |
+
const origSeedCache = _require.cache[resolvedSeed]
|
| 286 |
+
const origArgon2Verify = argon2Mock.verify
|
| 287 |
+
const origArgon2Hash = argon2Mock.hash
|
| 288 |
+
_require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 289 |
+
_require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
|
| 290 |
+
_require.cache[resolvedSeed] = {
|
| 291 |
+
exports: { seed: vi.fn().mockResolvedValue() },
|
| 292 |
+
id: resolvedSeed, filename: resolvedSeed, loaded: true,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
try {
|
| 296 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js', '../../src/config/index.js', '../../src/config/load-env.js')
|
| 297 |
+
vi.resetModules()
|
| 298 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 299 |
+
const mkReq = (url, method, headers = {}, body) => ({
|
| 300 |
+
url, method, headers: { ...headers }, socket: { remoteAddress: '::1' },
|
| 301 |
+
destroy: () => {},
|
| 302 |
+
on: (evt, cb) => {
|
| 303 |
+
if (evt === 'data' && body) cb(body)
|
| 304 |
+
if (evt === 'end') queueMicrotask(() => cb())
|
| 305 |
+
},
|
| 306 |
+
})
|
| 307 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 308 |
+
|
| 309 |
+
const res0 = mkRes()
|
| 310 |
+
await requestHandler(mkReq('/api/admin/settings', 'GET'), res0)
|
| 311 |
+
expect(res0.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 312 |
+
|
| 313 |
+
const res1 = mkRes()
|
| 314 |
+
await requestHandler(mkReq('/api/admin/settings', 'GET', { authorization: 'Bearer wrong' }), res1)
|
| 315 |
+
expect(res1.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 316 |
+
|
| 317 |
+
settingsTable[0].value = '$argon2id$v=19$m=65536,t=3,p=4$mockedhash'
|
| 318 |
+
const res2 = mkRes()
|
| 319 |
+
await requestHandler(mkReq('/api/admin/settings', 'GET', { authorization: 'Bearer secret' }), res2)
|
| 320 |
+
expect(res2.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 321 |
+
const body2 = JSON.parse(res2.end.mock.calls[0][0])
|
| 322 |
+
expect(body2.find(r => r.key === 'REDIS_PASSWORD').value).toBe('***')
|
| 323 |
+
expect(body2.find(r => r.key === 'ADMIN_KEY').value).toBe('***')
|
| 324 |
+
|
| 325 |
+
const res3 = mkRes()
|
| 326 |
+
await requestHandler(mkReq('/api/admin/settings/NODE_ENV', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 'production' })), res3)
|
| 327 |
+
expect(res3.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 328 |
+
|
| 329 |
+
const res4 = mkRes()
|
| 330 |
+
await requestHandler(mkReq('/api/admin/settings/NONEXISTENT', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 'x' })), res4)
|
| 331 |
+
expect(res4.writeHead).toHaveBeenCalledWith(404, expect.anything())
|
| 332 |
+
|
| 333 |
+
// PATCH a whitelisted setting not yet in DB → 201 Created
|
| 334 |
+
const resCreate = mkRes()
|
| 335 |
+
await requestHandler(mkReq('/api/admin/settings/DEFAULT_PAGE_SIZE', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 20 })), resCreate)
|
| 336 |
+
expect(resCreate.writeHead).toHaveBeenCalledWith(201, expect.anything())
|
| 337 |
+
|
| 338 |
+
// PATCH ADMIN_KEY when not yet in DB → INSERT + hash path
|
| 339 |
+
const origAdminRow = settingsTable.shift()
|
| 340 |
+
const resCreateAdmin = mkRes()
|
| 341 |
+
await requestHandler(mkReq('/api/admin/settings/ADMIN_KEY', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 'new-secret' })), resCreateAdmin)
|
| 342 |
+
expect(resCreateAdmin.writeHead).toHaveBeenCalledWith(201, expect.anything())
|
| 343 |
+
settingsTable.unshift(origAdminRow)
|
| 344 |
+
|
| 345 |
+
const res5 = mkRes()
|
| 346 |
+
await requestHandler(mkReq('/api/admin/settings/ADMIN_KEY', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: 'newadmin' })), res5)
|
| 347 |
+
expect(res5.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 348 |
+
|
| 349 |
+
const res6 = mkRes()
|
| 350 |
+
await requestHandler(mkReq('/api/admin/settings/NODE_ENV', 'PATCH', { authorization: 'Bearer secret' }, '{invalid'), res6)
|
| 351 |
+
expect(res6.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 352 |
+
|
| 353 |
+
const res7 = mkRes()
|
| 354 |
+
await requestHandler(mkReq('/api/admin/settings/NODE_ENV', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({})), res7)
|
| 355 |
+
expect(res7.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 356 |
+
|
| 357 |
+
const res8 = mkRes()
|
| 358 |
+
await requestHandler(mkReq('/api/admin/unknown', 'GET', { authorization: 'Bearer secret' }), res8)
|
| 359 |
+
expect(res8.writeHead).toHaveBeenCalledWith(404, expect.anything())
|
| 360 |
+
|
| 361 |
+
const res9 = mkRes()
|
| 362 |
+
await requestHandler(mkReq('/api/admin/settings/NODE_ENV', 'PATCH', { authorization: 'Bearer secret' }, JSON.stringify({ value: null })), res9)
|
| 363 |
+
expect(res9.writeHead).toHaveBeenCalledWith(400, expect.anything())
|
| 364 |
+
|
| 365 |
+
const resReset = mkRes()
|
| 366 |
+
await requestHandler(mkReq('/api/admin/reset-database', 'POST', { authorization: 'Bearer secret' }), resReset)
|
| 367 |
+
expect(resReset.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 368 |
+
|
| 369 |
+
argon2Mock.verify = vi.fn().mockRejectedValue(new Error('verify fail'))
|
| 370 |
+
const resThrow = mkRes()
|
| 371 |
+
await requestHandler(mkReq('/api/admin/settings', 'GET', { authorization: 'Bearer uncached' }), resThrow)
|
| 372 |
+
expect(resThrow.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 373 |
+
|
| 374 |
+
// oversized body on admin PATCH → 413
|
| 375 |
+
argon2Mock.verify = vi.fn().mockImplementation((hash, pwd) => Promise.resolve(pwd === 'secret'))
|
| 376 |
+
const resBulk = mkRes()
|
| 377 |
+
await requestHandler(mkReq('/api/admin/settings/NODE_ENV', 'PATCH', { authorization: 'Bearer secret' }, 'x'.repeat(200)), resBulk)
|
| 378 |
+
expect(resBulk.writeHead).toHaveBeenCalledWith(413, expect.anything())
|
| 379 |
+
} finally {
|
| 380 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 381 |
+
else delete _require.cache[resolvedDb]
|
| 382 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 383 |
+
else delete _require.cache[resolvedRedis]
|
| 384 |
+
if (origSeedCache) _require.cache[resolvedSeed] = origSeedCache
|
| 385 |
+
else delete _require.cache[resolvedSeed]
|
| 386 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 387 |
+
}
|
| 388 |
+
restore(s)
|
| 389 |
+
})
|
| 390 |
+
|
| 391 |
it('covers Redis connected path in IIFE', async () => {
|
| 392 |
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH')
|
| 393 |
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-redis.db') })
|
|
|
|
| 446 |
}
|
| 447 |
restore(s)
|
| 448 |
})
|
| 449 |
+
|
| 450 |
+
it('covers graceful shutdown on SIGINT/SIGTERM', async () => {
|
| 451 |
+
const s = save('PORT', 'REDIS_URL')
|
| 452 |
+
setEnv({ PORT: '0', REDIS_URL: '' })
|
| 453 |
+
delete process.env.START_SERVER
|
| 454 |
+
|
| 455 |
+
const oldSigint = process.listeners('SIGINT')
|
| 456 |
+
const oldSigterm = process.listeners('SIGTERM')
|
| 457 |
+
process.removeAllListeners('SIGINT')
|
| 458 |
+
process.removeAllListeners('SIGTERM')
|
| 459 |
+
|
| 460 |
+
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
| 461 |
+
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {})
|
| 462 |
+
|
| 463 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js', '../../src/redis/index.js')
|
| 464 |
+
vi.resetModules()
|
| 465 |
+
|
| 466 |
+
const mockClient = {
|
| 467 |
+
connect: vi.fn().mockResolvedValue(),
|
| 468 |
+
ping: vi.fn().mockResolvedValue(),
|
| 469 |
+
connected: false,
|
| 470 |
+
quit: vi.fn().mockResolvedValue(),
|
| 471 |
+
send: vi.fn().mockResolvedValue(),
|
| 472 |
+
}
|
| 473 |
+
const resolvedRedis = _require.resolve('../../src/redis/index.js')
|
| 474 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 475 |
+
_require.cache[resolvedRedis] = {
|
| 476 |
+
exports: function() { return mockClient },
|
| 477 |
+
id: resolvedRedis, filename: resolvedRedis, loaded: true,
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
try {
|
| 481 |
+
const mod = await import('../../src/server/index.js')
|
| 482 |
+
|
| 483 |
+
await new Promise((resolve) => {
|
| 484 |
+
if (mod.server.listening) return resolve()
|
| 485 |
+
mod.server.on('listening', resolve)
|
| 486 |
+
})
|
| 487 |
+
|
| 488 |
+
process.emit('SIGINT')
|
| 489 |
+
await new Promise(r => setTimeout(r, 50))
|
| 490 |
+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('SIGINT'))
|
| 491 |
+
expect(mod.server.listening).toBe(false)
|
| 492 |
+
|
| 493 |
+
logSpy.mockClear()
|
| 494 |
+
|
| 495 |
+
process.emit('SIGTERM')
|
| 496 |
+
await new Promise(r => setTimeout(r, 50))
|
| 497 |
+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('SIGTERM'))
|
| 498 |
+
expect(mod.server.listening).toBe(false)
|
| 499 |
+
} finally {
|
| 500 |
+
logSpy.mockRestore()
|
| 501 |
+
exitSpy.mockRestore()
|
| 502 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 503 |
+
else delete _require.cache[resolvedRedis]
|
| 504 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 505 |
+
for (const fn of oldSigint) process.on('SIGINT', fn)
|
| 506 |
+
for (const fn of oldSigterm) process.on('SIGTERM', fn)
|
| 507 |
+
}
|
| 508 |
+
restore(s)
|
| 509 |
+
})
|
| 510 |
+
|
| 511 |
+
it('caches argon2 verification results to avoid repeated calls', async () => {
|
| 512 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
|
| 513 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-cache.db'), ADMIN_KEY: 'secret' })
|
| 514 |
+
|
| 515 |
+
const argon2 = _require('argon2')
|
| 516 |
+
const verifySpy = vi.spyOn(argon2, 'verify').mockImplementation((hash, pwd) => Promise.resolve(pwd === 'secret'))
|
| 517 |
+
|
| 518 |
+
const settingsTable = [
|
| 519 |
+
{ key: 'ADMIN_KEY', value: '$argon2id$v=19$m=65536,t=3,p=4$mockedhash', description: 'Admin key', updated_at: '2025-01-01' },
|
| 520 |
+
]
|
| 521 |
+
|
| 522 |
+
const mockDb = {
|
| 523 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 524 |
+
getWrappedDb: () => ({
|
| 525 |
+
prepare: (sql) => {
|
| 526 |
+
if (sql.includes('SELECT value FROM settings')) return { get: () => settingsTable[0] }
|
| 527 |
+
return { all: () => settingsTable, get: () => null, run: () => {} }
|
| 528 |
+
},
|
| 529 |
+
exec: () => {},
|
| 530 |
+
}),
|
| 531 |
+
listAll: () => settingsTable,
|
| 532 |
+
getOne: () => null, insertOne: () => null, updateOne: () => null,
|
| 533 |
+
deleteOne: () => null, nextId: () => 1,
|
| 534 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 538 |
+
const resolvedRedis = _require.resolve('../../src/redis/index.js')
|
| 539 |
+
const mockRedisClass = function() { return { connect: vi.fn().mockResolvedValue(), ping: vi.fn().mockResolvedValue(), connected: false, quit: vi.fn().mockResolvedValue() } }
|
| 540 |
+
|
| 541 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 542 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 543 |
+
_require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 544 |
+
_require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
|
| 545 |
+
|
| 546 |
+
try {
|
| 547 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 548 |
+
vi.resetModules()
|
| 549 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 550 |
+
const mkReq = (headers = {}) => ({
|
| 551 |
+
url: '/api/admin/settings', method: 'GET', headers,
|
| 552 |
+
socket: { remoteAddress: '::1' }, on: () => {},
|
| 553 |
+
})
|
| 554 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 555 |
+
|
| 556 |
+
const res1 = mkRes()
|
| 557 |
+
await requestHandler(mkReq({ authorization: 'Bearer secret' }), res1)
|
| 558 |
+
expect(res1.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 559 |
+
const firstCalls = verifySpy.mock.calls.length
|
| 560 |
+
|
| 561 |
+
const res2 = mkRes()
|
| 562 |
+
await requestHandler(mkReq({ authorization: 'Bearer secret' }), res2)
|
| 563 |
+
expect(res2.writeHead).toHaveBeenCalledWith(200, expect.anything())
|
| 564 |
+
expect(verifySpy.mock.calls.length).toBe(firstCalls)
|
| 565 |
+
|
| 566 |
+
const res3 = mkRes()
|
| 567 |
+
await requestHandler(mkReq({ authorization: 'Bearer wrong' }), res3)
|
| 568 |
+
expect(res3.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 569 |
+
expect(verifySpy.mock.calls.length).toBe(firstCalls + 1)
|
| 570 |
+
|
| 571 |
+
const res4 = mkRes()
|
| 572 |
+
await requestHandler(mkReq({ authorization: 'Bearer wrong' }), res4)
|
| 573 |
+
expect(res4.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 574 |
+
expect(verifySpy.mock.calls.length).toBe(firstCalls + 1)
|
| 575 |
+
} finally {
|
| 576 |
+
verifySpy.mockRestore()
|
| 577 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 578 |
+
else delete _require.cache[resolvedDb]
|
| 579 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 580 |
+
else delete _require.cache[resolvedRedis]
|
| 581 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 582 |
+
}
|
| 583 |
+
restore(s)
|
| 584 |
+
})
|
| 585 |
+
|
| 586 |
+
it('returns 500 when admin handler throws unexpectedly', async () => {
|
| 587 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
|
| 588 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-admin-500.db'), ADMIN_KEY: 'secret' })
|
| 589 |
+
|
| 590 |
+
const arModule = _require('argon2')
|
| 591 |
+
const origArVerify = arModule.verify
|
| 592 |
+
const origArHash = arModule.hash
|
| 593 |
+
arModule.verify = vi.fn().mockResolvedValue(true)
|
| 594 |
+
arModule.hash = vi.fn().mockResolvedValue('$argon2id$mockhash')
|
| 595 |
+
|
| 596 |
+
const mockDbThrows = {
|
| 597 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 598 |
+
getWrappedDb: () => ({
|
| 599 |
+
prepare: (sql) => {
|
| 600 |
+
if (sql.includes('SELECT value FROM settings')) return { get: () => ({ value: '$argon2id$mockhash' }) }
|
| 601 |
+
return { all: () => [], get: () => null, run: () => {} }
|
| 602 |
+
},
|
| 603 |
+
exec: () => {},
|
| 604 |
+
}),
|
| 605 |
+
listAll: () => { throw new Error('unexpected db error') },
|
| 606 |
+
getOne: () => null, insertOne: () => null, updateOne: () => null,
|
| 607 |
+
deleteOne: () => null, nextId: () => 1,
|
| 608 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 612 |
+
const resolvedRedis = _require.resolve('../../src/redis/index.js')
|
| 613 |
+
const resolvedSeed = _require.resolve('../../src/db/seed.js')
|
| 614 |
+
const mockRedisClass = function() { return { connect: vi.fn().mockResolvedValue(), ping: vi.fn().mockResolvedValue(), connected: false, quit: vi.fn().mockResolvedValue() } }
|
| 615 |
+
|
| 616 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 617 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 618 |
+
const origSeedCache = _require.cache[resolvedSeed]
|
| 619 |
+
_require.cache[resolvedDb] = { exports: mockDbThrows, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 620 |
+
_require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
|
| 621 |
+
_require.cache[resolvedSeed] = { exports: { seed: vi.fn().mockResolvedValue() }, id: resolvedSeed, filename: resolvedSeed, loaded: true }
|
| 622 |
+
|
| 623 |
+
try {
|
| 624 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 625 |
+
vi.resetModules()
|
| 626 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 627 |
+
const mkReq = (headers = {}) => ({
|
| 628 |
+
url: '/api/admin/settings', method: 'GET', headers,
|
| 629 |
+
socket: { remoteAddress: '::1' }, on: () => {},
|
| 630 |
+
})
|
| 631 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 632 |
+
|
| 633 |
+
const res = mkRes()
|
| 634 |
+
await requestHandler(mkReq({ authorization: 'Bearer secret' }), res)
|
| 635 |
+
expect(res.writeHead).toHaveBeenCalledWith(500, expect.anything())
|
| 636 |
+
} finally {
|
| 637 |
+
arModule.verify = origArVerify
|
| 638 |
+
arModule.hash = origArHash
|
| 639 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 640 |
+
else delete _require.cache[resolvedDb]
|
| 641 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 642 |
+
else delete _require.cache[resolvedRedis]
|
| 643 |
+
if (origSeedCache) _require.cache[resolvedSeed] = origSeedCache
|
| 644 |
+
else delete _require.cache[resolvedSeed]
|
| 645 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 646 |
+
}
|
| 647 |
+
restore(s)
|
| 648 |
+
})
|
| 649 |
+
|
| 650 |
+
it('returns 500 when reset-database seed fails', async () => {
|
| 651 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
|
| 652 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-reset-fail.db'), ADMIN_KEY: 'secret' })
|
| 653 |
+
|
| 654 |
+
const argon2 = _require('argon2')
|
| 655 |
+
const origVerify = argon2.verify
|
| 656 |
+
const origHash = argon2.hash
|
| 657 |
+
argon2.verify = vi.fn().mockResolvedValue(true)
|
| 658 |
+
argon2.hash = vi.fn().mockResolvedValue('$argon2id$mockhash')
|
| 659 |
+
|
| 660 |
+
const wrappedDb = {
|
| 661 |
+
prepare: (sql) => {
|
| 662 |
+
if (sql.includes('SELECT value FROM settings')) return { get: () => ({ value: '$argon2id$mockhash' }) }
|
| 663 |
+
return { all: () => [], get: () => null, run: () => {} }
|
| 664 |
+
},
|
| 665 |
+
exec: vi.fn(),
|
| 666 |
+
}
|
| 667 |
+
const mockDbSeedFail = {
|
| 668 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 669 |
+
getWrappedDb: () => wrappedDb,
|
| 670 |
+
listAll: () => [{ key: 'foo', value: 'bar' }],
|
| 671 |
+
getOne: () => null, insertOne: () => null, updateOne: () => null,
|
| 672 |
+
deleteOne: () => null, nextId: () => 1,
|
| 673 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 677 |
+
const resolvedRedis = _require.resolve('../../src/redis/index.js')
|
| 678 |
+
const resolvedSeed = _require.resolve('../../src/db/seed.js')
|
| 679 |
+
const mockRedisClass = function() { return { connect: vi.fn().mockResolvedValue(), ping: vi.fn().mockResolvedValue(), connected: false, quit: vi.fn().mockResolvedValue() } }
|
| 680 |
+
|
| 681 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 682 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 683 |
+
const origSeedCache = _require.cache[resolvedSeed]
|
| 684 |
+
_require.cache[resolvedDb] = { exports: mockDbSeedFail, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 685 |
+
_require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
|
| 686 |
+
_require.cache[resolvedSeed] = { exports: { seed: vi.fn().mockRejectedValue(new Error('seed fail')) }, id: resolvedSeed, filename: resolvedSeed, loaded: true }
|
| 687 |
+
|
| 688 |
+
try {
|
| 689 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 690 |
+
vi.resetModules()
|
| 691 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 692 |
+
const mkReq = (headers = {}, body) => ({
|
| 693 |
+
url: '/api/admin/reset-database', method: 'POST', headers,
|
| 694 |
+
socket: { remoteAddress: '::1' }, on: () => {},
|
| 695 |
+
body: body ? JSON.stringify(body) : '',
|
| 696 |
+
})
|
| 697 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 698 |
+
|
| 699 |
+
const res = mkRes()
|
| 700 |
+
await requestHandler(mkReq({ authorization: 'Bearer secret', 'content-type': 'application/json' }), res)
|
| 701 |
+
expect(res.writeHead).toHaveBeenCalledWith(500, expect.anything())
|
| 702 |
+
expect(mockDbSeedFail.getWrappedDb().exec).toHaveBeenCalledWith('ROLLBACK')
|
| 703 |
+
} finally {
|
| 704 |
+
argon2.verify = origVerify
|
| 705 |
+
argon2.hash = origHash
|
| 706 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 707 |
+
else delete _require.cache[resolvedDb]
|
| 708 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 709 |
+
else delete _require.cache[resolvedRedis]
|
| 710 |
+
delete _require.cache[resolvedSeed]
|
| 711 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 712 |
+
}
|
| 713 |
+
restore(s)
|
| 714 |
+
})
|
| 715 |
+
|
| 716 |
+
it('caches argon2 errors so repeated failures skip verify', async () => {
|
| 717 |
+
const s = save('START_SERVER', 'PORT', 'REDIS_URL', 'DB_PATH', 'ADMIN_KEY')
|
| 718 |
+
setEnv({ START_SERVER: 'false', PORT: '0', REDIS_URL: '', DB_PATH: path.join(tmpDir, 'srv-cache-err.db'), ADMIN_KEY: 'secret' })
|
| 719 |
+
|
| 720 |
+
const argon2 = _require('argon2')
|
| 721 |
+
const verifySpy = vi.spyOn(argon2, 'verify').mockImplementation((hash, pwd) => {
|
| 722 |
+
if (pwd === 'throw') throw new Error('argon2 crash')
|
| 723 |
+
return Promise.resolve(pwd === 'secret')
|
| 724 |
+
})
|
| 725 |
+
|
| 726 |
+
const settingsTable = [
|
| 727 |
+
{ key: 'ADMIN_KEY', value: '$argon2id$v=19$m=65536,t=3,p=4$mockedhash', description: 'Admin key', updated_at: '2025-01-01' },
|
| 728 |
+
]
|
| 729 |
+
|
| 730 |
+
const mockDb = {
|
| 731 |
+
getDb: () => ({ prepare: () => ({ all: () => [], get: () => null, run: () => {} }), exec: () => {} }),
|
| 732 |
+
getWrappedDb: () => ({
|
| 733 |
+
prepare: (sql) => {
|
| 734 |
+
if (sql.includes('SELECT value FROM settings')) return { get: () => settingsTable[0] }
|
| 735 |
+
return { all: () => settingsTable, get: () => null, run: () => {} }
|
| 736 |
+
},
|
| 737 |
+
exec: () => {},
|
| 738 |
+
}),
|
| 739 |
+
listAll: () => settingsTable,
|
| 740 |
+
getOne: () => null, insertOne: () => null, updateOne: () => null,
|
| 741 |
+
deleteOne: () => null, nextId: () => 1,
|
| 742 |
+
TABLES: ['users', 'posts', 'comments', 'albums', 'photos', 'todos', 'settings'],
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
const resolvedDb = _require.resolve('../../src/db/index.js')
|
| 746 |
+
const resolvedRedis = _require.resolve('../../src/redis/index.js')
|
| 747 |
+
const mockRedisClass = function() { return { connect: vi.fn().mockResolvedValue(), ping: vi.fn().mockResolvedValue(), connected: false, quit: vi.fn().mockResolvedValue() } }
|
| 748 |
+
|
| 749 |
+
const origDbCache = _require.cache[resolvedDb]
|
| 750 |
+
const origRedisCache = _require.cache[resolvedRedis]
|
| 751 |
+
_require.cache[resolvedDb] = { exports: mockDb, id: resolvedDb, filename: resolvedDb, loaded: true }
|
| 752 |
+
_require.cache[resolvedRedis] = { exports: mockRedisClass, id: resolvedRedis, filename: resolvedRedis, loaded: true }
|
| 753 |
+
|
| 754 |
+
try {
|
| 755 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 756 |
+
vi.resetModules()
|
| 757 |
+
const { requestHandler } = await import('../../src/server/index.js')
|
| 758 |
+
const mkReq = (headers = {}) => ({
|
| 759 |
+
url: '/api/admin/settings', method: 'GET', headers,
|
| 760 |
+
socket: { remoteAddress: '::1' }, on: () => {},
|
| 761 |
+
})
|
| 762 |
+
const mkRes = () => ({ writeHead: vi.fn(), end: vi.fn(), setHeader: vi.fn(), writableEnded: false })
|
| 763 |
+
|
| 764 |
+
const res1 = mkRes()
|
| 765 |
+
await requestHandler(mkReq({ authorization: 'Bearer throw' }), res1)
|
| 766 |
+
expect(res1.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 767 |
+
expect(verifySpy).toHaveBeenCalledTimes(1)
|
| 768 |
+
|
| 769 |
+
const res2 = mkRes()
|
| 770 |
+
await requestHandler(mkReq({ authorization: 'Bearer throw' }), res2)
|
| 771 |
+
expect(res2.writeHead).toHaveBeenCalledWith(401, expect.anything())
|
| 772 |
+
expect(verifySpy).toHaveBeenCalledTimes(1)
|
| 773 |
+
} finally {
|
| 774 |
+
verifySpy.mockRestore()
|
| 775 |
+
if (origDbCache) _require.cache[resolvedDb] = origDbCache
|
| 776 |
+
else delete _require.cache[resolvedDb]
|
| 777 |
+
if (origRedisCache) _require.cache[resolvedRedis] = origRedisCache
|
| 778 |
+
else delete _require.cache[resolvedRedis]
|
| 779 |
+
clearCjs('../../src/server/index.js', '../../src/middleware/rate-limiter.js')
|
| 780 |
+
}
|
| 781 |
+
restore(s)
|
| 782 |
+
})
|
| 783 |
})
|