soul-cli 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/.env.sample +11 -2
  2. package/.github/dependabot.yml +9 -0
  3. package/.github/pull_request_template.md +8 -0
  4. package/.github/workflows/ci.yml +33 -0
  5. package/.github/workflows/pr-title.yml +27 -0
  6. package/.github/workflows/release.yml +44 -0
  7. package/.husky/pre-commit +0 -3
  8. package/.release-please-manifest.json +3 -0
  9. package/AGENTS.md +31 -0
  10. package/CHANGELOG.md +35 -0
  11. package/CLAUDE.md +1 -0
  12. package/README.md +16 -8
  13. package/ROADMAP.md +154 -0
  14. package/SECURITY.md +19 -0
  15. package/docs/extensions-examples.md +96 -16
  16. package/docs/ws-examples.md +4 -0
  17. package/eslint.config.js +29 -0
  18. package/package.json +44 -24
  19. package/release-please-config.json +10 -0
  20. package/scripts/dev.sh +64 -0
  21. package/src/cli.test.js +128 -0
  22. package/src/config/index.js +10 -2
  23. package/src/config/index.test.js +120 -0
  24. package/src/controllers/auth/common.js +1 -16
  25. package/src/controllers/auth/common.test.js +23 -0
  26. package/src/controllers/auth/tables.js +1 -1
  27. package/src/controllers/auth/token.js +30 -7
  28. package/src/controllers/auth/user.js +20 -20
  29. package/src/controllers/auth/user.test.js +232 -0
  30. package/src/controllers/auth.test.js +445 -0
  31. package/src/controllers/rows.js +159 -112
  32. package/src/controllers/rows.test.js +88 -1
  33. package/src/controllers/tables.js +63 -17
  34. package/src/controllers/tables.test.js +185 -0
  35. package/src/db/index.test.js +21 -0
  36. package/src/extensions.js +105 -36
  37. package/src/extensions.test.js +340 -0
  38. package/src/index.js +37 -20
  39. package/src/index.test.js +118 -0
  40. package/src/middlewares/api.js +1 -1
  41. package/src/middlewares/api.test.js +29 -0
  42. package/src/middlewares/auth.js +11 -48
  43. package/src/middlewares/auth.test.js +105 -0
  44. package/src/middlewares/validation.test.js +60 -0
  45. package/src/schemas/index.js +3 -1
  46. package/src/schemas/rows.js +15 -5
  47. package/src/schemas/tables.js +28 -4
  48. package/src/server.js +85 -4
  49. package/src/services/authService.js +33 -3
  50. package/src/services/authService.test.js +115 -0
  51. package/src/services/rowService.js +25 -18
  52. package/src/services/rowService.test.js +153 -0
  53. package/src/services/tableService.js +15 -17
  54. package/src/services/tableService.test.js +190 -0
  55. package/src/swagger/swagger.json +4 -7
  56. package/src/tests/index.js +1 -1
  57. package/src/utils/index.js +25 -2
  58. package/src/utils/index.test.js +135 -0
  59. package/src/utils/logger.js +15 -0
  60. package/src/utils/sql.js +112 -0
  61. package/src/utils/sql.test.js +115 -0
  62. package/src/websocket.js +47 -8
  63. package/src/websocket.test.js +121 -0
  64. package/.eslintignore +0 -2
  65. package/.eslintrc.js +0 -24
  66. package/.github/workflows/npm-publish.yml +0 -23
  67. package/src/middlewares/logger.js +0 -13
@@ -0,0 +1,340 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+ const express = require('express');
5
+ const cookieParser = require('cookie-parser');
6
+ const supertest = require('supertest');
7
+
8
+ // mirrors the real app's middleware setup closely enough for these tests
9
+ // -- auth-wrapped extension routes read req.cookies, which only exists
10
+ // with cookie-parser applied.
11
+ const createApp = () => express().use(cookieParser());
12
+
13
+ describe('setupExtensions', () => {
14
+ let extensionsDir;
15
+
16
+ afterEach(() => {
17
+ if (extensionsDir) {
18
+ fs.rmSync(extensionsDir, { recursive: true, force: true });
19
+ extensionsDir = undefined;
20
+ }
21
+ jest.dontMock('./config');
22
+ jest.resetModules();
23
+ });
24
+
25
+ const loadWithExtensionsDir = (files) => {
26
+ extensionsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'soul-ext-'));
27
+ Object.entries(files).forEach(([filename, content]) => {
28
+ fs.writeFileSync(path.join(extensionsDir, filename), content);
29
+ });
30
+
31
+ jest.resetModules();
32
+ jest.doMock('./config', () => ({
33
+ ...jest.requireActual('./config'),
34
+ extensions: { path: extensionsDir },
35
+ }));
36
+
37
+ return require('./extensions').setupExtensions;
38
+ };
39
+
40
+ it('does nothing (just logs) when no extensions path is configured', async () => {
41
+ jest.resetModules();
42
+ jest.doMock('./config', () => ({
43
+ ...jest.requireActual('./config'),
44
+ extensions: { path: null },
45
+ }));
46
+ const { setupExtensions } = require('./extensions');
47
+ const logger = require('./utils/logger');
48
+ const infoSpy = jest.spyOn(logger, 'info').mockImplementation(() => {});
49
+
50
+ const app = createApp();
51
+ await setupExtensions(app, {});
52
+
53
+ expect(infoSpy).toHaveBeenCalledWith(
54
+ expect.stringContaining('No extensions directory'),
55
+ );
56
+ infoSpy.mockRestore();
57
+ });
58
+
59
+ it('registers GET/POST/PUT/DELETE/PATCH routes, each with db access', async () => {
60
+ const setupExtensions = loadWithExtensionsDir({
61
+ 'api.js': `
62
+ module.exports = {
63
+ getRoute: {
64
+ method: 'GET',
65
+ path: '/ext/get',
66
+ handler: (req, res, db) => res.json({ method: 'GET', hasDb: !!db }),
67
+ },
68
+ postRoute: {
69
+ method: 'POST',
70
+ path: '/ext/post',
71
+ handler: (req, res, db) => res.json({ method: 'POST', hasDb: !!db }),
72
+ },
73
+ putRoute: {
74
+ method: 'PUT',
75
+ path: '/ext/put',
76
+ handler: (req, res, db) => res.json({ method: 'PUT', hasDb: !!db }),
77
+ },
78
+ deleteRoute: {
79
+ method: 'DELETE',
80
+ path: '/ext/delete',
81
+ handler: (req, res, db) => res.json({ method: 'DELETE', hasDb: !!db }),
82
+ },
83
+ patchRoute: {
84
+ method: 'PATCH',
85
+ path: '/ext/patch',
86
+ handler: (req, res, db) => res.json({ method: 'PATCH', hasDb: !!db }),
87
+ },
88
+ };
89
+ `,
90
+ });
91
+
92
+ const app = createApp();
93
+ const fakeDb = { marker: 'the-real-db' };
94
+ await setupExtensions(app, fakeDb);
95
+
96
+ const agent = supertest(app);
97
+
98
+ expect((await agent.get('/ext/get')).body).toEqual({
99
+ method: 'GET',
100
+ hasDb: true,
101
+ });
102
+ expect((await agent.post('/ext/post')).body).toEqual({
103
+ method: 'POST',
104
+ hasDb: true,
105
+ });
106
+ expect((await agent.put('/ext/put')).body).toEqual({
107
+ method: 'PUT',
108
+ hasDb: true,
109
+ });
110
+ expect((await agent.delete('/ext/delete')).body).toEqual({
111
+ method: 'DELETE',
112
+ hasDb: true,
113
+ });
114
+ // PATCH used to be silently unsupported -- it's now handled generically
115
+ // like any other method Express itself supports.
116
+ expect((await agent.patch('/ext/patch')).body).toEqual({
117
+ method: 'PATCH',
118
+ hasDb: true,
119
+ });
120
+ });
121
+
122
+ it('logs a warning and skips a route with a genuinely unsupported method', async () => {
123
+ const setupExtensions = loadWithExtensionsDir({
124
+ 'api.js': `
125
+ module.exports = {
126
+ bogus: {
127
+ method: 'FOOBAR',
128
+ path: '/ext/bogus',
129
+ handler: (req, res) => res.json({ ok: true }),
130
+ },
131
+ };
132
+ `,
133
+ });
134
+ const logger = require('./utils/logger');
135
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => {});
136
+
137
+ const app = createApp();
138
+ await setupExtensions(app, {});
139
+
140
+ expect(warnSpy).toHaveBeenCalledWith(
141
+ expect.stringContaining("unsupported method 'FOOBAR'"),
142
+ );
143
+ warnSpy.mockRestore();
144
+ });
145
+
146
+ it('merges routes from every .js file in the extensions directory, ignoring non-.js files', async () => {
147
+ const setupExtensions = loadWithExtensionsDir({
148
+ 'users.js': `
149
+ module.exports = {
150
+ fromUsers: {
151
+ method: 'GET',
152
+ path: '/ext/from-users-file',
153
+ handler: (req, res) => res.json({ file: 'users.js' }),
154
+ },
155
+ };
156
+ `,
157
+ 'reports.js': `
158
+ module.exports = {
159
+ fromReports: {
160
+ method: 'GET',
161
+ path: '/ext/from-reports-file',
162
+ handler: (req, res) => res.json({ file: 'reports.js' }),
163
+ },
164
+ };
165
+ `,
166
+ 'readme.md': '# not an extension, should be ignored',
167
+ });
168
+
169
+ const app = createApp();
170
+ await setupExtensions(app, {});
171
+ const agent = supertest(app);
172
+
173
+ expect((await agent.get('/ext/from-users-file')).body).toEqual({
174
+ file: 'users.js',
175
+ });
176
+ expect((await agent.get('/ext/from-reports-file')).body).toEqual({
177
+ file: 'reports.js',
178
+ });
179
+ });
180
+
181
+ describe('auth-wrapped extension routes', () => {
182
+ let generateToken;
183
+ let realConfig;
184
+
185
+ beforeAll(() => {
186
+ // ensure the default tables/role exist for the table-scoped
187
+ // permission test below, idempotently safe to call regardless of
188
+ // what other test files have already done against the shared db.
189
+ require('./index');
190
+ generateToken = require('./utils').generateToken;
191
+ realConfig = require('./config');
192
+ });
193
+
194
+ it('auth: true rejects a request with no access token', async () => {
195
+ const setupExtensions = loadWithExtensionsDir({
196
+ 'api.js': `
197
+ module.exports = {
198
+ protectedRoute: {
199
+ method: 'GET',
200
+ path: '/ext/protected',
201
+ auth: true,
202
+ handler: (req, res) => res.json({ ok: true }),
203
+ },
204
+ };
205
+ `,
206
+ });
207
+ const app = createApp();
208
+ await setupExtensions(app, {});
209
+
210
+ const res = await supertest(app).get('/ext/protected');
211
+ expect(res.status).toBe(401);
212
+ });
213
+
214
+ it('auth: true allows any authenticated request', async () => {
215
+ const setupExtensions = loadWithExtensionsDir({
216
+ 'api.js': `
217
+ module.exports = {
218
+ protectedRoute: {
219
+ method: 'GET',
220
+ path: '/ext/protected',
221
+ auth: true,
222
+ handler: (req, res) => res.json({ ok: true }),
223
+ },
224
+ };
225
+ `,
226
+ });
227
+ const app = createApp();
228
+ await setupExtensions(app, {});
229
+
230
+ const token = await generateToken(
231
+ { username: 'ext-user', isSuperuser: false, roleIds: [1] },
232
+ realConfig.tokenSecret,
233
+ '1H',
234
+ );
235
+
236
+ const res = await supertest(app)
237
+ .get('/ext/protected')
238
+ .set('Cookie', [`accessToken=${token}`]);
239
+ expect(res.status).toBe(200);
240
+ });
241
+
242
+ it('auth: { superuserOnly: true } rejects a non-superuser', async () => {
243
+ const setupExtensions = loadWithExtensionsDir({
244
+ 'api.js': `
245
+ module.exports = {
246
+ adminRoute: {
247
+ method: 'GET',
248
+ path: '/ext/admin',
249
+ auth: { superuserOnly: true },
250
+ handler: (req, res) => res.json({ ok: true }),
251
+ },
252
+ };
253
+ `,
254
+ });
255
+ const app = createApp();
256
+ await setupExtensions(app, {});
257
+
258
+ const token = await generateToken(
259
+ { username: 'ext-user', isSuperuser: false, roleIds: [1] },
260
+ realConfig.tokenSecret,
261
+ '1H',
262
+ );
263
+
264
+ const res = await supertest(app)
265
+ .get('/ext/admin')
266
+ .set('Cookie', [`accessToken=${token}`]);
267
+ expect(res.status).toBe(403);
268
+ });
269
+
270
+ it('auth: { superuserOnly: true } allows a superuser', async () => {
271
+ const setupExtensions = loadWithExtensionsDir({
272
+ 'api.js': `
273
+ module.exports = {
274
+ adminRoute: {
275
+ method: 'GET',
276
+ path: '/ext/admin',
277
+ auth: { superuserOnly: true },
278
+ handler: (req, res) => res.json({ ok: true }),
279
+ },
280
+ };
281
+ `,
282
+ });
283
+ const app = createApp();
284
+ await setupExtensions(app, {});
285
+
286
+ const token = await generateToken(
287
+ { username: 'ext-admin', isSuperuser: true },
288
+ realConfig.tokenSecret,
289
+ '1H',
290
+ );
291
+
292
+ const res = await supertest(app)
293
+ .get('/ext/admin')
294
+ .set('Cookie', [`accessToken=${token}`]);
295
+ expect(res.status).toBe(200);
296
+ });
297
+
298
+ it('auth: { table } checks table permission for the request method', async () => {
299
+ const setupExtensions = loadWithExtensionsDir({
300
+ 'api.js': `
301
+ module.exports = {
302
+ readUsers: {
303
+ method: 'GET',
304
+ path: '/ext/users-search',
305
+ auth: { table: 'users' },
306
+ handler: (req, res) => res.json({ ok: true }),
307
+ },
308
+ deleteUsers: {
309
+ method: 'DELETE',
310
+ path: '/ext/users-purge',
311
+ auth: { table: 'users' },
312
+ handler: (req, res) => res.json({ ok: true }),
313
+ },
314
+ };
315
+ `,
316
+ });
317
+ const app = createApp();
318
+ await setupExtensions(app, {});
319
+
320
+ // the default role (role id 1) has read-only access to tables that
321
+ // existed when it was created -- see createDefaultTables().
322
+ const token = await generateToken(
323
+ { username: 'ext-reader', isSuperuser: false, roleIds: [1] },
324
+ realConfig.tokenSecret,
325
+ '1H',
326
+ );
327
+ const cookie = [`accessToken=${token}`];
328
+
329
+ const readRes = await supertest(app)
330
+ .get('/ext/users-search')
331
+ .set('Cookie', cookie);
332
+ expect(readRes.status).toBe(200);
333
+
334
+ const deleteRes = await supertest(app)
335
+ .delete('/ext/users-purge')
336
+ .set('Cookie', cookie);
337
+ expect(deleteRes.status).toBe(403);
338
+ });
339
+ });
340
+ });
package/src/index.js CHANGED
@@ -2,15 +2,16 @@
2
2
 
3
3
  const express = require('express');
4
4
  const bodyParser = require('body-parser');
5
- const winston = require('winston');
6
5
  const expressWinston = require('express-winston');
7
6
  const cors = require('cors');
7
+ const helmet = require('helmet');
8
8
  const rateLimit = require('express-rate-limit');
9
9
  const swaggerUi = require('swagger-ui-express');
10
10
  const cookieParser = require('cookie-parser');
11
11
 
12
12
  const config = require('./config/index');
13
13
  const db = require('./db/index');
14
+ const logger = require('./utils/logger');
14
15
 
15
16
  const rootRoutes = require('./routes/index');
16
17
  const tablesRoutes = require('./routes/tables');
@@ -22,31 +23,42 @@ const { setupExtensions } = require('./extensions');
22
23
  const {
23
24
  createDefaultTables,
24
25
  createInitialUser,
25
- removeRevokedRefreshTokens,
26
26
  checkAuthConfigs,
27
27
  } = require('./controllers/auth');
28
28
 
29
29
  const { runCLICommands } = require('./commands');
30
- const { authConstants } = require('./constants');
31
30
 
32
31
  const app = express();
33
32
 
34
33
  app.use(bodyParser.json());
34
+ // body-parser v2 leaves req.body undefined when there is no body (v1 set {}).
35
+ // The request validators expect `body` to be present, so keep the v1 behaviour.
36
+ app.use((req, res, next) => {
37
+ if (req.body === undefined) {
38
+ req.body = {};
39
+ }
40
+ next();
41
+ });
35
42
  app.use(cookieParser());
43
+ app.use(helmet());
36
44
 
37
45
  // Activate wal mode
38
46
  db.exec('PRAGMA journal_mode = WAL');
39
47
 
40
48
  // Enable CORS
41
49
  let corsOrigin = config.cors.origin;
50
+ const isWildcardOrigin = corsOrigin.includes('*');
42
51
 
43
- if (corsOrigin.includes('*')) {
52
+ if (isWildcardOrigin) {
44
53
  corsOrigin = '*';
54
+ logger.warn(
55
+ "CORS_ORIGIN_WHITELIST includes '*' -- credentialed requests (cookies) will be rejected by browsers for a wildcard origin, so credentials are disabled. Set an explicit origin list to allow cookie-based auth cross-origin.",
56
+ );
45
57
  }
46
58
 
47
59
  const corsOptions = {
48
60
  origin: corsOrigin,
49
- credentials: true,
61
+ credentials: !isWildcardOrigin,
50
62
  allowedHeaders: ['Content-Type', 'Authorization'],
51
63
  };
52
64
 
@@ -56,16 +68,10 @@ app.use(cors(corsOptions));
56
68
  if (config.verbose !== null) {
57
69
  app.use(
58
70
  expressWinston.logger({
59
- transports: [new winston.transports.Console()],
60
- format: winston.format.combine(
61
- winston.format.colorize(),
62
-
63
- winston.format.json(),
64
- ),
71
+ winstonInstance: logger,
65
72
  meta: false,
66
73
  msg: 'HTTP {{req.method}} {{req.url}}',
67
74
  expressFormat: true,
68
-
69
75
  colorize: false,
70
76
  }),
71
77
  );
@@ -91,17 +97,11 @@ if (config.auth) {
91
97
  createDefaultTables();
92
98
  createInitialUser();
93
99
  } else {
94
- console.warn(
95
- 'Warning: Soul is running in open mode without authentication or authorization for API endpoints. Please be aware that your API endpoints will not be secure.',
100
+ logger.warn(
101
+ 'Soul is running in open mode without authentication or authorization for API endpoints. Please be aware that your API endpoints will not be secure.',
96
102
  );
97
103
  }
98
104
 
99
- // remove revoked refresh tokens every X days
100
- setInterval(
101
- removeRevokedRefreshTokens,
102
- authConstants.REVOKED_REFRESH_TOKENS_REMOVAL_TIME_RANGE,
103
- );
104
-
105
105
  // If the user has passed custom CLI commands run the command and exit to avoid running the server
106
106
  runCLICommands();
107
107
 
@@ -114,4 +114,21 @@ app.use('/api/auth', authRoutes);
114
114
 
115
115
  setupExtensions(app, db);
116
116
 
117
+ // Final error-handling middleware: catches errors passed via next(err) or
118
+ // thrown/rejected in async route handlers (Express 5 forwards these
119
+ // automatically). Logs full detail server-side and returns a sanitized
120
+ // message -- never the raw error/stack -- to the client.
121
+ // eslint-disable-next-line no-unused-vars
122
+ app.use((err, req, res, next) => {
123
+ logger.error(err.message, { stack: err.stack });
124
+
125
+ if (res.headersSent) {
126
+ return;
127
+ }
128
+
129
+ res.status(err.status || 500).json({
130
+ message: err.status ? err.message : 'Internal server error',
131
+ });
132
+ });
133
+
117
134
  module.exports = app;
@@ -0,0 +1,118 @@
1
+ const supertest = require('supertest');
2
+
3
+ describe('app bootstrap (src/index.js)', () => {
4
+ // config is a singleton fixed for the whole test run (AUTH=true, no rate
5
+ // limiting, non-wildcard CORS from .env or CI defaults) -- these branches
6
+ // depend on config values that differ per-scenario, so build a fresh app
7
+ // per test with a mocked config instead of relying on ambient env state
8
+ // (which would also make wildcard-CORS coverage depend on whether a local
9
+ // .env happens to be present).
10
+ const freshAppWith = (configOverrides) => {
11
+ jest.resetModules();
12
+ jest.doMock('./config/index', () => ({
13
+ ...jest.requireActual('./config/index'),
14
+ ...configOverrides,
15
+ }));
16
+ return require('./index');
17
+ };
18
+
19
+ afterEach(() => {
20
+ jest.dontMock('./config/index');
21
+ jest.resetModules();
22
+ });
23
+
24
+ it('returns a sanitized 500 (no stack trace) for an unexpected error, via the global error handler', async () => {
25
+ const app = require('./index');
26
+
27
+ // malformed JSON is rejected by body-parser before any route handler
28
+ // runs, so this exercises the global error middleware, not a
29
+ // controller's own try/catch.
30
+ const res = await supertest(app)
31
+ .post('/api/tables')
32
+ .set('Content-Type', 'application/json')
33
+ .send('{ not valid json');
34
+
35
+ expect(res.status).toBe(400);
36
+ // a real stack trace is multi-line, with frames like
37
+ // "at functionName (/path/to/file.js:12:34)" -- the parser's own
38
+ // one-line message (safe to show for a 4xx) shouldn't be confused
39
+ // with that.
40
+ expect(res.body.message).not.toMatch(/\n\s*at .+:\d+:\d+/);
41
+ expect(res.body).not.toHaveProperty('stack');
42
+ });
43
+
44
+ it('disables CORS credentials for a wildcard origin', async () => {
45
+ const app = freshAppWith({ cors: { origin: ['*'] } });
46
+
47
+ const res = await supertest(app)
48
+ .get('/api/health')
49
+ .set('Origin', 'http://example.com');
50
+
51
+ expect(res.headers['access-control-allow-origin']).toBe('*');
52
+ expect(res.headers['access-control-allow-credentials']).toBeUndefined();
53
+ });
54
+
55
+ it('enables CORS credentials for an explicit origin list', async () => {
56
+ const app = freshAppWith({
57
+ cors: { origin: ['http://trusted.example.com'] },
58
+ });
59
+
60
+ const res = await supertest(app)
61
+ .get('/api/health')
62
+ .set('Origin', 'http://trusted.example.com');
63
+
64
+ expect(res.headers['access-control-allow-origin']).toBe(
65
+ 'http://trusted.example.com',
66
+ );
67
+ expect(res.headers['access-control-allow-credentials']).toBe('true');
68
+ });
69
+
70
+ it('applies rate limiting when enabled', async () => {
71
+ const app = freshAppWith({
72
+ rateLimit: { enabled: true, windowMs: 60000, max: 2 },
73
+ });
74
+ const agent = supertest(app);
75
+
76
+ await agent.get('/api/health');
77
+ await agent.get('/api/health');
78
+ const limited = await agent.get('/api/health');
79
+
80
+ expect(limited.status).toBe(429);
81
+ });
82
+
83
+ it('warns and skips default-table/initial-user setup when auth is disabled', async () => {
84
+ jest.resetModules();
85
+ jest.doMock('./config/index', () => ({
86
+ ...jest.requireActual('./config/index'),
87
+ auth: false,
88
+ }));
89
+
90
+ // the warning fires synchronously while ./index loads, so the spy has
91
+ // to be attached (against this same fresh module registry) beforehand.
92
+ const logger = require('./utils/logger');
93
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => {});
94
+
95
+ require('./index');
96
+
97
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('open mode'));
98
+ warnSpy.mockRestore();
99
+ });
100
+
101
+ it('logs HTTP requests when verbose logging is enabled', async () => {
102
+ const app = freshAppWith({ verbose: 'console' });
103
+
104
+ const res = await supertest(app).get('/api/health');
105
+
106
+ expect(res.status).toBe(200);
107
+ });
108
+
109
+ it('does not rate limit when disabled', async () => {
110
+ const app = freshAppWith({ rateLimit: { enabled: false } });
111
+ const agent = supertest(app);
112
+
113
+ for (let i = 0; i < 5; i++) {
114
+ const res = await agent.get('/api/health');
115
+ expect(res.status).not.toBe(429);
116
+ }
117
+ });
118
+ });
@@ -56,7 +56,7 @@ const processRowRequest = async (req, res, next) => {
56
56
  if (validation.errorStatus) {
57
57
  return res.status(400).json({
58
58
  message: validation.message,
59
- error: validation.details,
59
+ error: validation.error,
60
60
  });
61
61
  }
62
62
  }
@@ -0,0 +1,29 @@
1
+ // config.auth is fixed to true for the whole test run (set via the npm test
2
+ // script), so the "AUTH is disabled but an auth-only table was requested"
3
+ // branch can only be exercised by mocking config directly. Other modules
4
+ // required transitively (e.g. src/db/index.js) still need a real-shaped
5
+ // config, so start from the actual module and only override `auth`.
6
+ jest.mock('../config', () => ({
7
+ ...jest.requireActual('../config'),
8
+ auth: false,
9
+ }));
10
+
11
+ const { processRowRequest } = require('./api');
12
+
13
+ describe('processRowRequest', () => {
14
+ it('returns 403 when an auth-endpoint table is requested with AUTH disabled', async () => {
15
+ const req = { params: { name: '_users' }, method: 'GET' };
16
+ const res = { status: jest.fn().mockReturnThis(), send: jest.fn() };
17
+ const next = jest.fn();
18
+
19
+ await processRowRequest(req, res, next);
20
+
21
+ expect(res.status).toHaveBeenCalledWith(403);
22
+ expect(res.send).toHaveBeenCalledWith(
23
+ expect.objectContaining({
24
+ message: expect.stringContaining('AUTH'),
25
+ }),
26
+ );
27
+ expect(next).not.toHaveBeenCalled();
28
+ });
29
+ });