soul-cli 0.8.2 → 0.9.3

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 (57) hide show
  1. package/.env.sample +11 -2
  2. package/.github/dependabot.yml +9 -0
  3. package/.github/workflows/ci.yml +33 -0
  4. package/.github/workflows/npm-publish.yml +19 -6
  5. package/.husky/pre-commit +0 -3
  6. package/README.md +14 -7
  7. package/ROADMAP.md +154 -0
  8. package/docs/extensions-examples.md +96 -16
  9. package/docs/ws-examples.md +4 -0
  10. package/eslint.config.js +29 -0
  11. package/package.json +40 -20
  12. package/scripts/dev.sh +64 -0
  13. package/src/cli.test.js +128 -0
  14. package/src/config/index.js +10 -2
  15. package/src/config/index.test.js +120 -0
  16. package/src/controllers/auth/common.js +1 -16
  17. package/src/controllers/auth/common.test.js +23 -0
  18. package/src/controllers/auth/tables.js +1 -1
  19. package/src/controllers/auth/token.js +30 -7
  20. package/src/controllers/auth/user.js +20 -20
  21. package/src/controllers/auth/user.test.js +232 -0
  22. package/src/controllers/auth.test.js +445 -0
  23. package/src/controllers/rows.js +159 -112
  24. package/src/controllers/rows.test.js +88 -1
  25. package/src/controllers/tables.js +63 -17
  26. package/src/controllers/tables.test.js +185 -0
  27. package/src/db/index.test.js +21 -0
  28. package/src/extensions.js +105 -36
  29. package/src/extensions.test.js +340 -0
  30. package/src/index.js +29 -20
  31. package/src/index.test.js +118 -0
  32. package/src/middlewares/api.js +1 -1
  33. package/src/middlewares/api.test.js +29 -0
  34. package/src/middlewares/auth.js +11 -48
  35. package/src/middlewares/auth.test.js +105 -0
  36. package/src/middlewares/validation.test.js +60 -0
  37. package/src/schemas/index.js +3 -1
  38. package/src/schemas/rows.js +15 -5
  39. package/src/schemas/tables.js +28 -4
  40. package/src/server.js +83 -1
  41. package/src/services/authService.js +33 -3
  42. package/src/services/authService.test.js +115 -0
  43. package/src/services/rowService.js +25 -18
  44. package/src/services/rowService.test.js +153 -0
  45. package/src/services/tableService.js +15 -17
  46. package/src/services/tableService.test.js +190 -0
  47. package/src/swagger/swagger.json +4 -7
  48. package/src/utils/index.js +25 -2
  49. package/src/utils/index.test.js +135 -0
  50. package/src/utils/logger.js +15 -0
  51. package/src/utils/sql.js +112 -0
  52. package/src/utils/sql.test.js +115 -0
  53. package/src/websocket.js +46 -8
  54. package/src/websocket.test.js +121 -0
  55. package/.eslintignore +0 -2
  56. package/.eslintrc.js +0 -24
  57. package/src/middlewares/logger.js +0 -13
@@ -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,29 @@ 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
15
  const { handler: soulStudioHandler } = await import(
12
16
  'soul-studio/build/handler.js'
13
17
  );
14
- app.use('/studio', soulStudioHandler);
18
+ // Deliberately not `app.use('/studio', soulStudioHandler)`: Express
19
+ // strips the mount prefix from `req.url` before invoking a path-mounted
20
+ // middleware, but soul-studio's adapter-node build has `paths.base:
21
+ // '/studio'` baked in at build time and resolves its own routes
22
+ // against the *unstripped* URL -- so a stripped `/login` never matches
23
+ // its `/studio/login` route and every request 404s. Mounting at the
24
+ // root and filtering by path ourselves leaves `req.url` untouched.
25
+ app.use((req, res, next) => {
26
+ if (req.url === '/studio' || req.url.startsWith('/studio/')) {
27
+ return soulStudioHandler(req, res, next);
28
+ }
29
+ next();
30
+ });
15
31
  })();
16
32
  }
17
33
 
@@ -39,4 +55,70 @@ server.on('upgrade', (request, socket, head) => {
39
55
  });
40
56
  });
41
57
 
58
+ // remove revoked refresh tokens every X days
59
+ const revokedTokensCleanupInterval = setInterval(
60
+ removeRevokedRefreshTokens,
61
+ authConstants.REVOKED_REFRESH_TOKENS_REMOVAL_TIME_RANGE,
62
+ );
63
+
64
+ let shuttingDown = false;
65
+
66
+ const shutdown = (signal) => {
67
+ if (shuttingDown) {
68
+ return;
69
+ }
70
+ shuttingDown = true;
71
+
72
+ logger.info(`Received ${signal}, shutting down gracefully...`);
73
+
74
+ // force-exit if cleanup hangs
75
+ const forceExitTimer = setTimeout(() => {
76
+ logger.error('Graceful shutdown timed out, forcing exit');
77
+ process.exit(1);
78
+ }, 10000);
79
+ forceExitTimer.unref();
80
+
81
+ clearInterval(revokedTokensCleanupInterval);
82
+
83
+ wss.clients.forEach((client) => client.close());
84
+ wss.close();
85
+
86
+ server.close((err) => {
87
+ if (err) {
88
+ logger.error('Error while closing HTTP server', { error: err.message });
89
+ }
90
+
91
+ try {
92
+ db.close();
93
+ } catch (error) {
94
+ logger.error('Error while closing database connection', {
95
+ error: error.message,
96
+ });
97
+ }
98
+
99
+ clearTimeout(forceExitTimer);
100
+ process.exit(0);
101
+ });
102
+ };
103
+
104
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
105
+ process.on('SIGINT', () => shutdown('SIGINT'));
106
+
107
+ process.on('uncaughtException', (error) => {
108
+ logger.error('Uncaught exception', {
109
+ error: error.message,
110
+ stack: error.stack,
111
+ });
112
+ shutdown('uncaughtException');
113
+ });
114
+
115
+ process.on('unhandledRejection', (reason) => {
116
+ const error = reason instanceof Error ? reason : new Error(String(reason));
117
+ logger.error('Unhandled promise rejection', {
118
+ error: error.message,
119
+ stack: error.stack,
120
+ });
121
+ shutdown('unhandledRejection');
122
+ });
123
+
42
124
  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
+ });
@@ -1,4 +1,5 @@
1
1
  const { apiConstants } = require('../constants');
2
+ const { quoteIdentifier } = require('../utils/sql');
2
3
 
3
4
  module.exports = (db) => {
4
5
  return {
@@ -36,19 +37,15 @@ module.exports = (db) => {
36
37
  },
37
38
 
38
39
  save(data) {
39
- // wrap text values in quotes
40
- const fieldsString = Object.keys(data.fields)
41
- .map((field) => `'${field}'`)
40
+ const fieldNames = Object.keys(data.fields);
41
+ const fieldsString = fieldNames
42
+ .map((field) => quoteIdentifier(field))
42
43
  .join(', ');
43
-
44
- // wrap text values in quotes
45
- const valuesString = Object.values(data.fields).map((value) => value);
46
- const placeholders = Object.values(data.fields)
47
- .map(() => '?')
48
- .join(',');
44
+ const valuesString = Object.values(data.fields);
45
+ const placeholders = fieldNames.map(() => '?').join(',');
49
46
 
50
47
  let values = `(${fieldsString}) VALUES (${placeholders})`;
51
- if (valuesString === '') {
48
+ if (fieldNames.length === 0) {
52
49
  values = 'DEFAULT VALUES';
53
50
  }
54
51
 
@@ -69,7 +66,7 @@ module.exports = (db) => {
69
66
  .join(',');
70
67
 
71
68
  const query = `INSERT INTO ${tableName} (${fieldNames
72
- .map((field) => `'${field}'`)
69
+ .map((field) => quoteIdentifier(field))
73
70
  .join(', ')}) VALUES ${valuesString}`;
74
71
 
75
72
  const statement = db.prepare(query);
@@ -80,16 +77,26 @@ module.exports = (db) => {
80
77
  update(data) {
81
78
  const pks = data.pks.split(',');
82
79
  const placeholders = pks.map(() => '?').join(',');
83
- const query = `UPDATE ${data.tableName} SET ${data.fieldsString} WHERE ${data.lookupField} in (${placeholders})`;
80
+ const fieldNames = Object.keys(data.fields);
81
+ const setString = fieldNames
82
+ .map((field) => `${quoteIdentifier(field)} = ?`)
83
+ .join(', ');
84
+ const query = `UPDATE ${
85
+ data.tableName
86
+ } SET ${setString} WHERE ${quoteIdentifier(
87
+ data.lookupField,
88
+ )} in (${placeholders})`;
84
89
  const statement = db.prepare(query);
85
- const result = statement.run(...pks);
90
+ const result = statement.run(...Object.values(data.fields), ...pks);
86
91
  return result;
87
92
  },
88
93
 
89
94
  delete(data) {
90
95
  const pks = data.pks.split(',');
91
96
  const placeholders = pks.map(() => '?').join(',');
92
- const query = `DELETE FROM ${data.tableName} WHERE ${data.lookupField} in (${placeholders})`;
97
+ const query = `DELETE FROM ${data.tableName} WHERE ${quoteIdentifier(
98
+ data.lookupField,
99
+ )} in (${placeholders})`;
93
100
  const statement = db.prepare(query);
94
101
  const result = statement.run(...pks);
95
102
  return result;
@@ -97,8 +104,8 @@ module.exports = (db) => {
97
104
 
98
105
  getForeignKeyInfo(tableName, field) {
99
106
  const foreignKey = db
100
- .prepare(`PRAGMA foreign_key_list(${tableName})`)
101
- .all()
107
+ .prepare('SELECT * FROM pragma_foreign_key_list(?)')
108
+ .all(tableName)
102
109
  .find((fk) => fk.from === field);
103
110
 
104
111
  if (!foreignKey) {
@@ -107,8 +114,8 @@ module.exports = (db) => {
107
114
 
108
115
  const joinedTableName = foreignKey.table;
109
116
  const joinedTableFields = db
110
- .prepare(`PRAGMA table_info(${joinedTableName})`)
111
- .all();
117
+ .prepare('SELECT * FROM pragma_table_info(?)')
118
+ .all(joinedTableName);
112
119
 
113
120
  return { foreignKey, joinedTableName, joinedTableFields };
114
121
  },