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
@@ -1,5 +1,6 @@
1
1
  const config = require('../config');
2
- const { decodeToken, toBoolean } = require('../utils/index');
2
+ const { decodeToken } = require('../utils/index');
3
+ const logger = require('../utils/logger');
3
4
  const { apiConstants, responseMessages } = require('../constants');
4
5
  const { authService } = require('../services');
5
6
 
@@ -20,69 +21,31 @@ const hasAccess = async (req, res, next) => {
20
21
  config.tokenSecret,
21
22
  );
22
23
  req.user = payload;
23
- } catch (error) {
24
+ } catch {
25
+ // an invalid/expired access token is a routine client-side
26
+ // condition, not an unexpected server error -- not logged as one.
24
27
  return res
25
28
  .status(401)
26
29
  .send({ message: errorMessage.INVALID_ACCESS_TOKEN_ERROR });
27
30
  }
28
31
 
29
- // if the user is a super_user, allow access on the resource
30
- if (toBoolean(payload.isSuperuser)) {
31
- return next();
32
- }
33
-
34
32
  // if the endpoint is set to be accessed by any user regardless of there roles, then allow access
35
33
  if (apiConstants.universalAccessEndpoints.includes(originalURL)) {
36
34
  return next();
37
35
  }
38
36
 
39
- // if table_name is not passed from the router throw unauthorized error
40
- if (!tableName) {
41
- return res
42
- .status(403)
43
- .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
44
- }
45
-
46
- // if the user is not a super user, fetch the permission of the user from the DB
47
- const rolePermissions = authService.getPermissionByRoleIds({
48
- roleIds: payload.roleIds,
49
- });
50
-
51
- const resourcePermission = rolePermissions.filter(
52
- (row) => row.table_name === tableName,
53
- );
54
-
55
- if (resourcePermission.length <= 0) {
56
- return res
57
- .status(403)
58
- .send({ message: errorMessage.PERMISSION_NOT_DEFINED_ERROR });
37
+ if (authService.hasTablePermission({ payload, tableName, verb })) {
38
+ return next();
59
39
  }
60
40
 
61
- // If the user has permission on the table in at least in one of the roles then allow access on the table
62
- let hasPermission = false;
63
-
64
- resourcePermission.some((resource) => {
65
- const httpMethod =
66
- apiConstants.httpMethodDefinitions[verb].toLowerCase();
67
-
68
- if (toBoolean(resource[httpMethod])) {
69
- hasPermission = true;
70
- return true;
71
- }
72
- });
73
-
74
- if (hasPermission) {
75
- next();
76
- } else {
77
- return res
78
- .status(403)
79
- .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
80
- }
41
+ return res
42
+ .status(403)
43
+ .send({ message: errorMessage.NOT_AUTHORIZED_ERROR });
81
44
  } else {
82
45
  next();
83
46
  }
84
47
  } catch (error) {
85
- console.log(error);
48
+ logger.error(error.message, { stack: error.stack });
86
49
  res.status(401).send({ message: error.message });
87
50
  }
88
51
  };
@@ -0,0 +1,105 @@
1
+ jest.mock('../config', () => ({ auth: false, tokenSecret: 'test-secret' }));
2
+ jest.mock('../utils/index', () => ({ decodeToken: jest.fn() }));
3
+ jest.mock('../utils/logger', () => ({ error: jest.fn() }));
4
+ jest.mock('../services', () => ({
5
+ authService: { hasTablePermission: jest.fn() },
6
+ }));
7
+
8
+ const config = require('../config');
9
+ const { decodeToken } = require('../utils/index');
10
+ const { authService } = require('../services');
11
+ const { hasAccess } = require('./auth');
12
+
13
+ describe('hasAccess', () => {
14
+ let req, res, next;
15
+
16
+ beforeEach(() => {
17
+ jest.clearAllMocks();
18
+ config.auth = false;
19
+ req = {
20
+ params: {},
21
+ method: 'GET',
22
+ originalUrl: '/api/tables/items/rows',
23
+ cookies: {},
24
+ };
25
+ res = { status: jest.fn().mockReturnThis(), send: jest.fn() };
26
+ next = jest.fn();
27
+ });
28
+
29
+ it('calls next() without checking anything when auth is disabled', async () => {
30
+ config.auth = false;
31
+
32
+ await hasAccess(req, res, next);
33
+
34
+ expect(next).toHaveBeenCalledTimes(1);
35
+ expect(decodeToken).not.toHaveBeenCalled();
36
+ expect(res.status).not.toHaveBeenCalled();
37
+ });
38
+
39
+ it('returns 401 when the access token is missing/invalid', async () => {
40
+ config.auth = true;
41
+ decodeToken.mockRejectedValue(new Error('invalid token'));
42
+
43
+ await hasAccess(req, res, next);
44
+
45
+ expect(res.status).toHaveBeenCalledWith(401);
46
+ expect(next).not.toHaveBeenCalled();
47
+ });
48
+
49
+ it('allows access to universal endpoints once authenticated, regardless of table permission', async () => {
50
+ config.auth = true;
51
+ decodeToken.mockResolvedValue({ userId: 1, isSuperuser: false });
52
+ req.originalUrl = '/api/auth/change-password';
53
+
54
+ await hasAccess(req, res, next);
55
+
56
+ expect(next).toHaveBeenCalledTimes(1);
57
+ expect(authService.hasTablePermission).not.toHaveBeenCalled();
58
+ });
59
+
60
+ it('calls next() when the permission check passes', async () => {
61
+ config.auth = true;
62
+ const payload = { userId: 1, isSuperuser: true };
63
+ decodeToken.mockResolvedValue(payload);
64
+ authService.hasTablePermission.mockReturnValue(true);
65
+ req.params.name = 'items';
66
+
67
+ await hasAccess(req, res, next);
68
+
69
+ expect(authService.hasTablePermission).toHaveBeenCalledWith({
70
+ payload,
71
+ tableName: 'items',
72
+ verb: 'GET',
73
+ });
74
+ expect(next).toHaveBeenCalledTimes(1);
75
+ });
76
+
77
+ it('returns 403 when the permission check fails', async () => {
78
+ config.auth = true;
79
+ decodeToken.mockResolvedValue({
80
+ userId: 1,
81
+ isSuperuser: false,
82
+ roleIds: [1],
83
+ });
84
+ authService.hasTablePermission.mockReturnValue(false);
85
+ req.params.name = 'items';
86
+
87
+ await hasAccess(req, res, next);
88
+
89
+ expect(res.status).toHaveBeenCalledWith(403);
90
+ expect(next).not.toHaveBeenCalled();
91
+ });
92
+
93
+ it('returns 401 and logs when an unexpected error is thrown', async () => {
94
+ config.auth = true;
95
+ decodeToken.mockResolvedValue({ userId: 1, isSuperuser: true });
96
+ authService.hasTablePermission.mockImplementation(() => {
97
+ throw new Error('boom');
98
+ });
99
+
100
+ await hasAccess(req, res, next);
101
+
102
+ expect(res.status).toHaveBeenCalledWith(401);
103
+ expect(res.send).toHaveBeenCalledWith({ message: 'boom' });
104
+ });
105
+ });
@@ -0,0 +1,60 @@
1
+ const Joi = require('joi');
2
+
3
+ const { validator, customValidator } = require('./validation');
4
+
5
+ const schema = Joi.object({
6
+ body: Joi.object({ name: Joi.string().required() }).required(),
7
+ params: Joi.object().required(),
8
+ query: Joi.object().required(),
9
+ cookies: Joi.object().required(),
10
+ });
11
+
12
+ describe('validator', () => {
13
+ it('calls next() and normalizes req.* to the validated values on success', () => {
14
+ const req = { body: { name: 'ok' }, params: {}, query: {}, cookies: {} };
15
+ const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
16
+ const next = jest.fn();
17
+
18
+ validator(schema)(req, res, next);
19
+
20
+ expect(next).toHaveBeenCalledTimes(1);
21
+ expect(res.status).not.toHaveBeenCalled();
22
+ expect(req.body).toEqual({ name: 'ok' });
23
+ });
24
+
25
+ it('returns a 400 with the Joi error details on failure', () => {
26
+ const req = { body: {}, params: {}, query: {}, cookies: {} };
27
+ const res = { status: jest.fn().mockReturnThis(), json: jest.fn() };
28
+ const next = jest.fn();
29
+
30
+ validator(schema)(req, res, next);
31
+
32
+ expect(next).not.toHaveBeenCalled();
33
+ expect(res.status).toHaveBeenCalledWith(400);
34
+ expect(res.json).toHaveBeenCalledWith(
35
+ expect.objectContaining({
36
+ message: expect.stringContaining('name'),
37
+ }),
38
+ );
39
+ });
40
+ });
41
+
42
+ describe('customValidator', () => {
43
+ it('returns errorStatus: false on success', () => {
44
+ const req = { body: { name: 'ok' }, params: {}, query: {}, cookies: {} };
45
+
46
+ const result = customValidator(schema)(req);
47
+
48
+ expect(result.errorStatus).toBe(false);
49
+ });
50
+
51
+ it('returns errorStatus: true with the Joi error message/details on failure', () => {
52
+ const req = { body: {}, params: {}, query: {}, cookies: {} };
53
+
54
+ const result = customValidator(schema)(req);
55
+
56
+ expect(result.errorStatus).toBe(true);
57
+ expect(result.message).toEqual(expect.stringContaining('name'));
58
+ expect(result.error).toBeDefined();
59
+ });
60
+ });
@@ -17,10 +17,12 @@ const transaction = Joi.object({
17
17
  .required(),
18
18
  }).required(),
19
19
 
20
+ // .unknown(true): see the comment in schemas/tables.js -- rejects
21
+ // unrelated cookies the browser sends otherwise.
20
22
  cookies: Joi.object({
21
23
  refreshToken: Joi.string().optional(),
22
24
  accessToken: Joi.string().optional(),
23
- }),
25
+ }).unknown(true),
24
26
  });
25
27
 
26
28
  module.exports = {
@@ -14,10 +14,12 @@ const listTableRows = Joi.object({
14
14
  name: Joi.string(),
15
15
  }).required(),
16
16
  body: Joi.object().required(),
17
+ // .unknown(true): see the comment in schemas/tables.js -- rejects
18
+ // unrelated cookies the browser sends otherwise.
17
19
  cookies: Joi.object({
18
20
  refreshToken: Joi.string().optional(),
19
21
  accessToken: Joi.string().optional(),
20
- }),
22
+ }).unknown(true),
21
23
  });
22
24
 
23
25
  const insertRowInTable = Joi.object({
@@ -32,10 +34,12 @@ const insertRowInTable = Joi.object({
32
34
  body: Joi.object({
33
35
  fields: Joi.object().required(),
34
36
  }).required(),
37
+ // .unknown(true): see the comment in schemas/tables.js -- rejects
38
+ // unrelated cookies the browser sends otherwise.
35
39
  cookies: Joi.object({
36
40
  refreshToken: Joi.string().optional(),
37
41
  accessToken: Joi.string().optional(),
38
- }),
42
+ }).unknown(true),
39
43
  });
40
44
 
41
45
  const getRowInTableByPK = Joi.object({
@@ -56,10 +60,12 @@ const getRowInTableByPK = Joi.object({
56
60
  pks: Joi.string().required(),
57
61
  }).required(),
58
62
  body: Joi.object().required(),
63
+ // .unknown(true): see the comment in schemas/tables.js -- rejects
64
+ // unrelated cookies the browser sends otherwise.
59
65
  cookies: Joi.object({
60
66
  refreshToken: Joi.string().optional(),
61
67
  accessToken: Joi.string().optional(),
62
- }),
68
+ }).unknown(true),
63
69
  });
64
70
 
65
71
  const updateRowInTableByPK = Joi.object({
@@ -80,10 +86,12 @@ const updateRowInTableByPK = Joi.object({
80
86
  body: Joi.object({
81
87
  fields: Joi.object().required(),
82
88
  }).required(),
89
+ // .unknown(true): see the comment in schemas/tables.js -- rejects
90
+ // unrelated cookies the browser sends otherwise.
83
91
  cookies: Joi.object({
84
92
  refreshToken: Joi.string().optional(),
85
93
  accessToken: Joi.string().optional(),
86
- }),
94
+ }).unknown(true),
87
95
  });
88
96
 
89
97
  const deleteRowInTableByPK = Joi.object({
@@ -102,10 +110,12 @@ const deleteRowInTableByPK = Joi.object({
102
110
  pks: Joi.string().required(),
103
111
  }).required(),
104
112
  body: Joi.object().required(),
113
+ // .unknown(true): see the comment in schemas/tables.js -- rejects
114
+ // unrelated cookies the browser sends otherwise.
105
115
  cookies: Joi.object({
106
116
  refreshToken: Joi.string().optional(),
107
117
  accessToken: Joi.string().optional(),
108
- }),
118
+ }).unknown(true),
109
119
  });
110
120
 
111
121
  module.exports = {
@@ -7,10 +7,16 @@ const listTables = Joi.object({
7
7
  }).required(),
8
8
  params: Joi.object().required(),
9
9
  body: Joi.object().required(),
10
+ // .unknown(true): the browser sends every cookie for the domain,
11
+ // including ones unrelated to Soul (other local apps/extensions sharing
12
+ // the same hostname, e.g. `localhost` cookies aren't scoped by port) --
13
+ // without this, Joi rejects the whole request with e.g.
14
+ // `"cookies.csrftoken" is not allowed` the moment an unrecognized cookie
15
+ // is present, regardless of whether Soul's own auth cookies are valid.
10
16
  cookies: Joi.object({
11
17
  refreshToken: Joi.string().optional(),
12
18
  accessToken: Joi.string().optional(),
13
- }),
19
+ }).unknown(true),
14
20
  });
15
21
 
16
22
  const createTable = Joi.object({
@@ -75,10 +81,16 @@ const createTable = Joi.object({
75
81
  )
76
82
  .required(),
77
83
  }),
84
+ // .unknown(true): the browser sends every cookie for the domain,
85
+ // including ones unrelated to Soul (other local apps/extensions sharing
86
+ // the same hostname, e.g. `localhost` cookies aren't scoped by port) --
87
+ // without this, Joi rejects the whole request with e.g.
88
+ // `"cookies.csrftoken" is not allowed` the moment an unrecognized cookie
89
+ // is present, regardless of whether Soul's own auth cookies are valid.
78
90
  cookies: Joi.object({
79
91
  refreshToken: Joi.string().optional(),
80
92
  accessToken: Joi.string().optional(),
81
- }),
93
+ }).unknown(true),
82
94
  });
83
95
 
84
96
  const getTableSchema = Joi.object({
@@ -91,10 +103,16 @@ const getTableSchema = Joi.object({
91
103
  .required(),
92
104
  }),
93
105
  body: Joi.object().required(),
106
+ // .unknown(true): the browser sends every cookie for the domain,
107
+ // including ones unrelated to Soul (other local apps/extensions sharing
108
+ // the same hostname, e.g. `localhost` cookies aren't scoped by port) --
109
+ // without this, Joi rejects the whole request with e.g.
110
+ // `"cookies.csrftoken" is not allowed` the moment an unrecognized cookie
111
+ // is present, regardless of whether Soul's own auth cookies are valid.
94
112
  cookies: Joi.object({
95
113
  refreshToken: Joi.string().optional(),
96
114
  accessToken: Joi.string().optional(),
97
- }),
115
+ }).unknown(true),
98
116
  });
99
117
 
100
118
  const deleteTable = Joi.object({
@@ -107,10 +125,16 @@ const deleteTable = Joi.object({
107
125
  .required(),
108
126
  }),
109
127
  body: Joi.object().required(),
128
+ // .unknown(true): the browser sends every cookie for the domain,
129
+ // including ones unrelated to Soul (other local apps/extensions sharing
130
+ // the same hostname, e.g. `localhost` cookies aren't scoped by port) --
131
+ // without this, Joi rejects the whole request with e.g.
132
+ // `"cookies.csrftoken" is not allowed` the moment an unrecognized cookie
133
+ // is present, regardless of whether Soul's own auth cookies are valid.
110
134
  cookies: Joi.object({
111
135
  refreshToken: Joi.string().optional(),
112
136
  accessToken: Joi.string().optional(),
113
- }),
137
+ }).unknown(true),
114
138
  });
115
139
 
116
140
  module.exports = {
package/src/server.js CHANGED
@@ -5,13 +5,28 @@ const http = require('http');
5
5
  const app = require('./index');
6
6
  const { wss } = require('./websocket');
7
7
  const config = require('./config/index');
8
+ const db = require('./db/index');
9
+ const logger = require('./utils/logger');
10
+ const { removeRevokedRefreshTokens } = require('./controllers/auth');
11
+ const { authConstants } = require('./constants');
8
12
 
9
13
  if (config.startWithStudio) {
10
14
  (async () => {
11
- const { handler: soulStudioHandler } = await import(
12
- 'soul-studio/build/handler.js'
13
- );
14
- app.use('/studio', soulStudioHandler);
15
+ const { handler: soulStudioHandler } =
16
+ await import('soul-studio/build/handler.js');
17
+ // Deliberately not `app.use('/studio', soulStudioHandler)`: Express
18
+ // strips the mount prefix from `req.url` before invoking a path-mounted
19
+ // middleware, but soul-studio's adapter-node build has `paths.base:
20
+ // '/studio'` baked in at build time and resolves its own routes
21
+ // against the *unstripped* URL -- so a stripped `/login` never matches
22
+ // its `/studio/login` route and every request 404s. Mounting at the
23
+ // root and filtering by path ourselves leaves `req.url` untouched.
24
+ app.use((req, res, next) => {
25
+ if (req.url === '/studio' || req.url.startsWith('/studio/')) {
26
+ return soulStudioHandler(req, res, next);
27
+ }
28
+ next();
29
+ });
15
30
  })();
16
31
  }
17
32
 
@@ -39,4 +54,70 @@ server.on('upgrade', (request, socket, head) => {
39
54
  });
40
55
  });
41
56
 
57
+ // remove revoked refresh tokens every X days
58
+ const revokedTokensCleanupInterval = setInterval(
59
+ removeRevokedRefreshTokens,
60
+ authConstants.REVOKED_REFRESH_TOKENS_REMOVAL_TIME_RANGE,
61
+ );
62
+
63
+ let shuttingDown = false;
64
+
65
+ const shutdown = (signal) => {
66
+ if (shuttingDown) {
67
+ return;
68
+ }
69
+ shuttingDown = true;
70
+
71
+ logger.info(`Received ${signal}, shutting down gracefully...`);
72
+
73
+ // force-exit if cleanup hangs
74
+ const forceExitTimer = setTimeout(() => {
75
+ logger.error('Graceful shutdown timed out, forcing exit');
76
+ process.exit(1);
77
+ }, 10000);
78
+ forceExitTimer.unref();
79
+
80
+ clearInterval(revokedTokensCleanupInterval);
81
+
82
+ wss.clients.forEach((client) => client.close());
83
+ wss.close();
84
+
85
+ server.close((err) => {
86
+ if (err) {
87
+ logger.error('Error while closing HTTP server', { error: err.message });
88
+ }
89
+
90
+ try {
91
+ db.close();
92
+ } catch (error) {
93
+ logger.error('Error while closing database connection', {
94
+ error: error.message,
95
+ });
96
+ }
97
+
98
+ clearTimeout(forceExitTimer);
99
+ process.exit(0);
100
+ });
101
+ };
102
+
103
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
104
+ process.on('SIGINT', () => shutdown('SIGINT'));
105
+
106
+ process.on('uncaughtException', (error) => {
107
+ logger.error('Uncaught exception', {
108
+ error: error.message,
109
+ stack: error.stack,
110
+ });
111
+ shutdown('uncaughtException');
112
+ });
113
+
114
+ process.on('unhandledRejection', (reason) => {
115
+ const error = reason instanceof Error ? reason : new Error(String(reason));
116
+ logger.error('Unhandled promise rejection', {
117
+ error: error.message,
118
+ stack: error.stack,
119
+ });
120
+ shutdown('unhandledRejection');
121
+ });
122
+
42
123
  module.exports = {};
@@ -1,7 +1,7 @@
1
- const db = require('../db');
2
- const rowService = require('./rowService')(db);
1
+ const buildRowService = require('./rowService');
3
2
 
4
- const { constantRoles, dbConstants } = require('../constants');
3
+ const { constantRoles, dbConstants, apiConstants } = require('../constants');
4
+ const { toBoolean } = require('../utils');
5
5
 
6
6
  const {
7
7
  USERS_TABLE,
@@ -13,6 +13,8 @@ const {
13
13
  } = dbConstants;
14
14
 
15
15
  module.exports = (db) => {
16
+ const rowService = buildRowService(db);
17
+
16
18
  return {
17
19
  getUsersByUsername({ username }) {
18
20
  const users = rowService.get({
@@ -106,5 +108,33 @@ module.exports = (db) => {
106
108
  const result = statement.run();
107
109
  return result;
108
110
  },
111
+
112
+ // Shared by the REST `hasAccess` middleware and the WebSocket connection
113
+ // handler so the two auth surfaces can't drift apart.
114
+ hasTablePermission({ payload, tableName, verb }) {
115
+ if (toBoolean(payload.isSuperuser)) {
116
+ return true;
117
+ }
118
+
119
+ if (!tableName) {
120
+ return false;
121
+ }
122
+
123
+ const rolePermissions = this.getPermissionByRoleIds({
124
+ roleIds: payload.roleIds,
125
+ });
126
+ const resourcePermission = rolePermissions.filter(
127
+ (row) => row.table_name === tableName,
128
+ );
129
+
130
+ if (resourcePermission.length <= 0) {
131
+ return false;
132
+ }
133
+
134
+ const httpMethod = apiConstants.httpMethodDefinitions[verb].toLowerCase();
135
+ return resourcePermission.some((resource) =>
136
+ toBoolean(resource[httpMethod]),
137
+ );
138
+ },
109
139
  };
110
140
  };
@@ -0,0 +1,115 @@
1
+ const Database = require('better-sqlite3');
2
+
3
+ const buildAuthService = require('./authService');
4
+
5
+ // hasTablePermission is exercised in the rest of the suite only via
6
+ // superuser tokens (which short-circuit at the very first check) or via
7
+ // fully-mocked authService (middlewares/auth.test.js) -- neither path ever
8
+ // runs its real, non-superuser permission-lookup logic. Test that directly
9
+ // here against a real in-memory DB.
10
+ describe('authService.hasTablePermission', () => {
11
+ let db;
12
+ let authService;
13
+
14
+ beforeEach(() => {
15
+ db = new Database(':memory:');
16
+ // production's tableFields uses 'create'/'update'/'delete' as the raw
17
+ // column names -- these are SQL keywords, so quote them explicitly.
18
+ db.exec(`
19
+ CREATE TABLE _roles_permissions (
20
+ id INTEGER PRIMARY KEY,
21
+ role_id INTEGER,
22
+ table_name TEXT,
23
+ "create" BOOLEAN,
24
+ read BOOLEAN,
25
+ "update" BOOLEAN,
26
+ "delete" BOOLEAN
27
+ );
28
+ `);
29
+ authService = buildAuthService(db);
30
+ });
31
+
32
+ afterEach(() => {
33
+ db.close();
34
+ });
35
+
36
+ const insertPermission = (perm) => {
37
+ db.prepare(
38
+ `INSERT INTO _roles_permissions (role_id, table_name, "create", read, "update", "delete") VALUES (?, ?, ?, ?, ?, ?)`,
39
+ ).run(
40
+ perm.role_id,
41
+ perm.table_name,
42
+ perm.create ?? 0,
43
+ perm.read ?? 0,
44
+ perm.update ?? 0,
45
+ perm.delete ?? 0,
46
+ );
47
+ };
48
+
49
+ it('always allows a superuser, regardless of table or permissions', () => {
50
+ expect(
51
+ authService.hasTablePermission({
52
+ payload: { isSuperuser: true },
53
+ tableName: 'anything',
54
+ verb: 'DELETE',
55
+ }),
56
+ ).toBe(true);
57
+ });
58
+
59
+ it('denies when no tableName is provided', () => {
60
+ expect(
61
+ authService.hasTablePermission({
62
+ payload: { isSuperuser: false, roleIds: [1] },
63
+ tableName: undefined,
64
+ verb: 'GET',
65
+ }),
66
+ ).toBe(false);
67
+ });
68
+
69
+ it('denies when no permission row exists for the table', () => {
70
+ expect(
71
+ authService.hasTablePermission({
72
+ payload: { isSuperuser: false, roleIds: [1] },
73
+ tableName: 'items',
74
+ verb: 'GET',
75
+ }),
76
+ ).toBe(false);
77
+ });
78
+
79
+ it('denies when a permission row exists but the verb is not granted', () => {
80
+ insertPermission({ role_id: 1, table_name: 'items', read: 1 });
81
+
82
+ expect(
83
+ authService.hasTablePermission({
84
+ payload: { isSuperuser: false, roleIds: [1] },
85
+ tableName: 'items',
86
+ verb: 'DELETE',
87
+ }),
88
+ ).toBe(false);
89
+ });
90
+
91
+ it('allows when a permission row grants the requested verb', () => {
92
+ insertPermission({ role_id: 1, table_name: 'items', read: 1 });
93
+
94
+ expect(
95
+ authService.hasTablePermission({
96
+ payload: { isSuperuser: false, roleIds: [1] },
97
+ tableName: 'items',
98
+ verb: 'GET',
99
+ }),
100
+ ).toBe(true);
101
+ });
102
+
103
+ it('allows when any of the user roles grants the requested verb', () => {
104
+ insertPermission({ role_id: 1, table_name: 'items', read: 0 });
105
+ insertPermission({ role_id: 2, table_name: 'items', read: 1 });
106
+
107
+ expect(
108
+ authService.hasTablePermission({
109
+ payload: { isSuperuser: false, roleIds: [1, 2] },
110
+ tableName: 'items',
111
+ verb: 'GET',
112
+ }),
113
+ ).toBe(true);
114
+ });
115
+ });