soul-cli 0.8.1 → 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 (71) hide show
  1. package/.all-contributorsrc +9 -0
  2. package/.bruno/auth/folder.bru +8 -0
  3. package/.bruno/auth/obtain-access-token.bru +25 -0
  4. package/.bruno/bruno.json +6 -0
  5. package/.bruno/environments/local.bru +3 -0
  6. package/.bruno/rows/folder.bru +8 -0
  7. package/.bruno/rows/list-rows-with-ordering.bru +25 -0
  8. package/.bruno/tables/folder.bru +8 -0
  9. package/.bruno/tables/list-tables.bru +16 -0
  10. package/.env.sample +11 -2
  11. package/.github/dependabot.yml +9 -0
  12. package/.github/workflows/ci.yml +33 -0
  13. package/.github/workflows/npm-publish.yml +19 -6
  14. package/.husky/pre-commit +0 -3
  15. package/README.md +46 -7
  16. package/ROADMAP.md +154 -0
  17. package/assets/images/soul-RA-app.png +0 -0
  18. package/assets/images/soul-standalone.png +0 -0
  19. package/docs/extensions-examples.md +96 -16
  20. package/docs/self-hosting.md +54 -0
  21. package/docs/ws-examples.md +4 -0
  22. package/eslint.config.js +29 -0
  23. package/package.json +40 -20
  24. package/scripts/dev.sh +64 -0
  25. package/src/cli.test.js +128 -0
  26. package/src/config/index.js +10 -2
  27. package/src/config/index.test.js +120 -0
  28. package/src/controllers/auth/common.js +1 -16
  29. package/src/controllers/auth/common.test.js +23 -0
  30. package/src/controllers/auth/tables.js +1 -1
  31. package/src/controllers/auth/token.js +30 -7
  32. package/src/controllers/auth/user.js +20 -20
  33. package/src/controllers/auth/user.test.js +232 -0
  34. package/src/controllers/auth.test.js +445 -0
  35. package/src/controllers/rows.js +183 -120
  36. package/src/controllers/rows.test.js +119 -2
  37. package/src/controllers/tables.js +63 -17
  38. package/src/controllers/tables.test.js +185 -0
  39. package/src/db/index.test.js +21 -0
  40. package/src/extensions.js +105 -36
  41. package/src/extensions.test.js +340 -0
  42. package/src/index.js +29 -20
  43. package/src/index.test.js +118 -0
  44. package/src/middlewares/api.js +1 -1
  45. package/src/middlewares/api.test.js +29 -0
  46. package/src/middlewares/auth.js +11 -48
  47. package/src/middlewares/auth.test.js +105 -0
  48. package/src/middlewares/validation.test.js +60 -0
  49. package/src/schemas/index.js +3 -1
  50. package/src/schemas/rows.js +16 -6
  51. package/src/schemas/tables.js +28 -4
  52. package/src/server.js +83 -1
  53. package/src/services/authService.js +33 -3
  54. package/src/services/authService.test.js +115 -0
  55. package/src/services/rowService.js +39 -14
  56. package/src/services/rowService.test.js +153 -0
  57. package/src/services/tableService.js +15 -17
  58. package/src/services/tableService.test.js +190 -0
  59. package/src/swagger/swagger.json +4 -7
  60. package/src/tests/globalSetup.js +8 -1
  61. package/src/tests/index.js +23 -0
  62. package/src/utils/index.js +25 -2
  63. package/src/utils/index.test.js +135 -0
  64. package/src/utils/logger.js +15 -0
  65. package/src/utils/sql.js +112 -0
  66. package/src/utils/sql.test.js +115 -0
  67. package/src/websocket.js +46 -8
  68. package/src/websocket.test.js +121 -0
  69. package/.eslintignore +0 -2
  70. package/.eslintrc.js +0 -24
  71. package/src/middlewares/logger.js +0 -13
@@ -1,6 +1,7 @@
1
1
  const { authService } = require('../../services');
2
2
  const { responseMessages, authConstants } = require('../../constants');
3
3
  const config = require('../../config');
4
+ const logger = require('../../utils/logger');
4
5
  const {
5
6
  comparePasswords,
6
7
  generateToken,
@@ -66,7 +67,8 @@ const obtainAccessToken = async (req, res) => {
66
67
  });
67
68
 
68
69
  roleIds = roleData.roleIds;
69
- } catch (err) {
70
+ } catch (error) {
71
+ logger.error(error.message, { stack: error.stack });
70
72
  return res
71
73
  .status(401)
72
74
  .send({ message: errorMessage.ROLE_NOT_FOUND_ERROR });
@@ -95,7 +97,12 @@ const obtainAccessToken = async (req, res) => {
95
97
  );
96
98
 
97
99
  // set the token in the cookie
98
- let cookieOptions = { httpOnly: true, secure: false, Path: '/' };
100
+ let cookieOptions = {
101
+ httpOnly: true,
102
+ secure: config.cookie.secure,
103
+ sameSite: config.cookie.sameSite,
104
+ Path: '/',
105
+ };
99
106
  res.cookie(authConstants.ACCESS_TOKEN_SUBJECT, accessToken, cookieOptions);
100
107
  res.cookie(
101
108
  authConstants.REFRESH_TOKEN_SUBJECT,
@@ -116,7 +123,7 @@ const obtainAccessToken = async (req, res) => {
116
123
  }
117
124
  */
118
125
  } catch (error) {
119
- console.log(error);
126
+ logger.error(error.message, { stack: error.stack });
120
127
  return res.status(500).json({
121
128
  message: errorMessage.SERVER_ERROR,
122
129
  });
@@ -174,7 +181,8 @@ const refreshAccessToken = async (req, res) => {
174
181
  });
175
182
 
176
183
  roleIds = roleData.roleIds;
177
- } catch (err) {
184
+ } catch (error) {
185
+ logger.error(error.message, { stack: error.stack });
178
186
  return res
179
187
  .status(401)
180
188
  .send({ message: errorMessage.ROLE_NOT_FOUND_ERROR });
@@ -203,7 +211,12 @@ const refreshAccessToken = async (req, res) => {
203
211
  );
204
212
 
205
213
  // set the token in the cookie
206
- let cookieOptions = { httpOnly: true, secure: false, Path: '/' };
214
+ let cookieOptions = {
215
+ httpOnly: true,
216
+ secure: config.cookie.secure,
217
+ sameSite: config.cookie.sameSite,
218
+ Path: '/',
219
+ };
207
220
  res.cookie(authConstants.ACCESS_TOKEN_SUBJECT, accessToken, cookieOptions);
208
221
  res.cookie(
209
222
  authConstants.REFRESH_TOKEN_SUBJECT,
@@ -223,7 +236,9 @@ const refreshAccessToken = async (req, res) => {
223
236
  }
224
237
  }
225
238
  */
226
- } catch (error) {
239
+ } catch {
240
+ // an invalid/expired refresh token is a routine client-side condition,
241
+ // not an unexpected server error -- not logged as one.
227
242
  res.status(403).send({ message: errorMessage.INVALID_REFRESH_TOKEN_ERROR });
228
243
  /*
229
244
  #swagger.responses[401] = {
@@ -272,13 +287,21 @@ const removeTokens = async (req, res) => {
272
287
  }
273
288
  */
274
289
  } catch (error) {
290
+ logger.error(error.message, { stack: error.stack });
275
291
  res.status(500).send({ message: errorMessage.SERVER_ERROR });
276
292
  }
277
293
  };
278
294
 
279
295
  const removeRevokedRefreshTokens = () => {
296
+ // expires_at stores a JWT `exp` claim (Unix seconds, INTEGER affinity).
297
+ // CURRENT_TIMESTAMP is a TEXT datetime string -- comparing INTEGER < TEXT
298
+ // in SQLite falls back to storage-class ordering (INTEGER always sorts
299
+ // below TEXT) rather than a real numeric comparison, so that previously
300
+ // matched (and deleted) every row regardless of actual expiry.
301
+ // strftime('%s','now') returns the current time in the same Unix-seconds
302
+ // form as expires_at, so this compares correctly.
280
303
  authService.deleteRevokedRefreshTokens({
281
- lookupField: `WHERE expires_at < CURRENT_TIMESTAMP`,
304
+ lookupField: `WHERE expires_at < strftime('%s','now')`,
282
305
  });
283
306
  };
284
307
 
@@ -6,8 +6,10 @@ const {
6
6
  authConstants,
7
7
  } = require('../../constants');
8
8
  const config = require('../../config');
9
+ const logger = require('../../utils/logger');
9
10
  const {
10
11
  hashPassword,
12
+ hashPasswordSync,
11
13
  checkPasswordStrength,
12
14
  comparePasswords,
13
15
  } = require('../../utils');
@@ -20,8 +22,7 @@ const { successMessage, errorMessage, infoMessage } = responseMessages;
20
22
 
21
23
  const updateSuperuser = async (fields) => {
22
24
  const { id, password, is_superuser } = fields;
23
- let newHashedPassword, newSalt;
24
- let fieldsString = '';
25
+ const updateFields = {};
25
26
 
26
27
  try {
27
28
  // find the user by using the id field
@@ -34,8 +35,12 @@ const updateSuperuser = async (fields) => {
34
35
  }
35
36
 
36
37
  // check if the is_superuser field is passed
38
+ // stored as the string 'true'/'false' (matching every other write path
39
+ // for this column, e.g. createInitialUser/registerUser below) --
40
+ // better-sqlite3 can't bind a native JS boolean, which is what the CLI's
41
+ // yargs `type: 'boolean'` parsing hands us here.
37
42
  if (is_superuser !== undefined) {
38
- fieldsString = `${tableFields.IS_SUPERUSER} = '${is_superuser}'`;
43
+ updateFields[tableFields.IS_SUPERUSER] = String(is_superuser);
39
44
  }
40
45
 
41
46
  // if the password is sent from the CLI, update it
@@ -51,23 +56,17 @@ const updateSuperuser = async (fields) => {
51
56
  }
52
57
 
53
58
  //hash the password
54
- const { hashedPassword, salt } = await hashPassword(
55
- password,
56
- SALT_ROUNDS,
57
- );
58
- newHashedPassword = hashedPassword;
59
- newSalt = salt;
60
-
61
- fieldsString = `${fieldsString ? fieldsString + ', ' : ''} ${
62
- tableFields.HASHED_PASSWORD
63
- } = '${newHashedPassword}', ${tableFields.SALT} = '${newSalt}'`;
59
+ const { hashedPassword, salt } = hashPasswordSync(password, SALT_ROUNDS);
60
+
61
+ updateFields[tableFields.HASHED_PASSWORD] = hashedPassword;
62
+ updateFields[tableFields.SALT] = salt;
64
63
  }
65
64
 
66
65
  // update the user
67
66
  rowService.update({
68
67
  tableName: USERS_TABLE,
69
68
  lookupField: tableFields.ID,
70
- fieldsString,
69
+ fields: updateFields,
71
70
  pks: `${id}`,
72
71
  });
73
72
 
@@ -194,7 +193,7 @@ const registerUser = async (req, res) => {
194
193
  }
195
194
  */
196
195
  } catch (error) {
197
- console.log(error);
196
+ logger.error(error.message, { stack: error.stack });
198
197
  res.status(500).send({ message: errorMessage.SERVER_ERROR });
199
198
  }
200
199
  };
@@ -283,7 +282,10 @@ const changePassword = async (req, res) => {
283
282
  rowService.update({
284
283
  tableName: USERS_TABLE,
285
284
  lookupField: tableFields.ID,
286
- fieldsString: `${tableFields.HASHED_PASSWORD} = '${hashedPassword}', ${tableFields.SALT} = '${salt}'`,
285
+ fields: {
286
+ [tableFields.HASHED_PASSWORD]: hashedPassword,
287
+ [tableFields.SALT]: salt,
288
+ },
287
289
  pks: `${user.id}`,
288
290
  });
289
291
 
@@ -301,6 +303,7 @@ const changePassword = async (req, res) => {
301
303
  }
302
304
  */
303
305
  } catch (error) {
306
+ logger.error(error.message, { stack: error.stack });
304
307
  res.status(500).send({ message: errorMessage.SERVER_ERROR });
305
308
  }
306
309
  };
@@ -346,10 +349,7 @@ const createInitialUser = async () => {
346
349
  }
347
350
 
348
351
  // hash the password
349
- const { hashedPassword, salt } = await hashPassword(
350
- password,
351
- SALT_ROUNDS,
352
- );
352
+ const { hashedPassword, salt } = hashPasswordSync(password, SALT_ROUNDS);
353
353
 
354
354
  // create the initial user
355
355
  const { lastInsertRowid: userId } = rowService.save({
@@ -0,0 +1,232 @@
1
+ // updateSuperuser/createInitialUser are CLI/startup-only paths that call
2
+ // process.exit() directly (no `return` after it, since in the real process
3
+ // exit() never returns) -- fully mock their dependencies and make the
4
+ // process.exit spy throw, mirroring exit's real effect of halting execution,
5
+ // so these can be tested without ever touching the real DB or actually
6
+ // killing the Jest worker.
7
+ jest.mock('../../services', () => ({
8
+ authService: {
9
+ getAllUsers: jest.fn(),
10
+ getUsersByUsername: jest.fn(),
11
+ getUsersById: jest.fn(),
12
+ getDefaultRole: jest.fn(),
13
+ },
14
+ rowService: {
15
+ save: jest.fn(),
16
+ update: jest.fn(),
17
+ },
18
+ }));
19
+
20
+ const { authService, rowService } = require('../../services');
21
+ const config = require('../../config');
22
+ const { createInitialUser, updateSuperuser } = require('./user');
23
+
24
+ describe('createInitialUser / updateSuperuser (CLI-only paths)', () => {
25
+ let exitSpy;
26
+ let consoleLogSpy;
27
+ let consoleErrorSpy;
28
+
29
+ beforeEach(() => {
30
+ jest.clearAllMocks();
31
+ exitSpy = jest.spyOn(process, 'exit').mockImplementation((code) => {
32
+ throw new Error(`process.exit(${code})`);
33
+ });
34
+ consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
35
+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
36
+ });
37
+
38
+ afterEach(() => {
39
+ exitSpy.mockRestore();
40
+ consoleLogSpy.mockRestore();
41
+ consoleErrorSpy.mockRestore();
42
+ });
43
+
44
+ describe('createInitialUser', () => {
45
+ let originalUsername;
46
+ let originalPassword;
47
+
48
+ beforeEach(() => {
49
+ originalUsername = config.initialUserUsername;
50
+ originalPassword = config.initialUserPassword;
51
+ authService.getAllUsers.mockReturnValue([]);
52
+ authService.getUsersByUsername.mockReturnValue([]);
53
+ authService.getDefaultRole.mockReturnValue([{ id: 1 }]);
54
+ rowService.save.mockReturnValue({ lastInsertRowid: 42 });
55
+ });
56
+
57
+ afterEach(() => {
58
+ config.initialUserUsername = originalUsername;
59
+ config.initialUserPassword = originalPassword;
60
+ });
61
+
62
+ it('does nothing (no exit) when users already exist', async () => {
63
+ authService.getAllUsers.mockReturnValue([{ id: 1 }]);
64
+
65
+ await createInitialUser();
66
+
67
+ expect(exitSpy).not.toHaveBeenCalled();
68
+ expect(rowService.save).not.toHaveBeenCalled();
69
+ });
70
+
71
+ it('exits when INITIAL_USER_USERNAME is missing', async () => {
72
+ config.initialUserUsername = undefined;
73
+ config.initialUserPassword = 'Str0ng$Pw!';
74
+
75
+ await createInitialUser();
76
+
77
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
78
+ expect.stringContaining('INITIAL_USER_USERNAME'),
79
+ );
80
+ expect(exitSpy).toHaveBeenCalledWith(1);
81
+ expect(rowService.save).not.toHaveBeenCalled();
82
+ });
83
+
84
+ it('exits when INITIAL_USER_PASSWORD is missing', async () => {
85
+ config.initialUserUsername = 'admin';
86
+ config.initialUserPassword = undefined;
87
+
88
+ await createInitialUser();
89
+
90
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
91
+ expect.stringContaining('INITIAL_USER_PASSWORD'),
92
+ );
93
+ expect(exitSpy).toHaveBeenCalledWith(1);
94
+ expect(rowService.save).not.toHaveBeenCalled();
95
+ });
96
+
97
+ it('exits when the username is already taken', async () => {
98
+ config.initialUserUsername = 'admin';
99
+ config.initialUserPassword = 'Str0ng$Pw!';
100
+ authService.getUsersByUsername.mockReturnValue([{ id: 1 }]);
101
+
102
+ await createInitialUser();
103
+
104
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
105
+ expect.stringContaining('taken'),
106
+ );
107
+ expect(exitSpy).toHaveBeenCalledWith(1);
108
+ expect(rowService.save).not.toHaveBeenCalled();
109
+ });
110
+
111
+ it('exits when the password is weak', async () => {
112
+ config.initialUserUsername = 'admin';
113
+ config.initialUserPassword = '12345678';
114
+
115
+ await createInitialUser();
116
+
117
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
118
+ expect.stringContaining('weak'),
119
+ );
120
+ expect(exitSpy).toHaveBeenCalledWith(1);
121
+ expect(rowService.save).not.toHaveBeenCalled();
122
+ });
123
+
124
+ it('exits when no default role exists', async () => {
125
+ config.initialUserUsername = 'admin';
126
+ config.initialUserPassword = 'Str0ng$Pw!';
127
+ authService.getDefaultRole.mockReturnValue([]);
128
+
129
+ await createInitialUser();
130
+
131
+ expect(exitSpy).toHaveBeenCalledWith(1);
132
+ // the user row is saved before the default-role check runs
133
+ expect(rowService.save).toHaveBeenCalledTimes(1);
134
+ });
135
+
136
+ it('creates the user and role when everything is valid', async () => {
137
+ config.initialUserUsername = 'admin';
138
+ config.initialUserPassword = 'Str0ng$Pw!';
139
+
140
+ await createInitialUser();
141
+
142
+ expect(exitSpy).not.toHaveBeenCalled();
143
+ expect(rowService.save).toHaveBeenCalledTimes(2);
144
+ expect(consoleLogSpy).toHaveBeenCalledWith(
145
+ expect.stringContaining('Initial user created successfully'),
146
+ );
147
+ });
148
+ });
149
+
150
+ describe('updateSuperuser', () => {
151
+ beforeEach(() => {
152
+ authService.getUsersById.mockReturnValue([{ id: 1, username: 'admin' }]);
153
+ });
154
+
155
+ it('exits when the user id does not exist', async () => {
156
+ authService.getUsersById.mockReturnValue([]);
157
+
158
+ await updateSuperuser({
159
+ id: 999,
160
+ password: undefined,
161
+ is_superuser: true,
162
+ });
163
+
164
+ expect(consoleLogSpy).toHaveBeenCalledWith(
165
+ expect.stringContaining('not found'),
166
+ );
167
+ expect(exitSpy).toHaveBeenCalledWith(1);
168
+ expect(rowService.update).not.toHaveBeenCalled();
169
+ });
170
+
171
+ it('exits when the new password is weak', async () => {
172
+ await updateSuperuser({
173
+ id: 1,
174
+ password: 'weak',
175
+ is_superuser: undefined,
176
+ });
177
+
178
+ expect(consoleLogSpy).toHaveBeenCalledWith(
179
+ expect.stringContaining('weak'),
180
+ );
181
+ expect(exitSpy).toHaveBeenCalledWith(1);
182
+ expect(rowService.update).not.toHaveBeenCalled();
183
+ });
184
+
185
+ it('updates only is_superuser when no password is given, coerced to a string for SQLite binding', async () => {
186
+ await updateSuperuser({ id: 1, password: undefined, is_superuser: true });
187
+
188
+ // better-sqlite3 can't bind a native boolean; every other write path
189
+ // for this column (createInitialUser/registerUser) stores the string
190
+ // 'true'/'false', so this must match that convention, not the raw
191
+ // boolean the CLI's yargs `type: 'boolean'` parsing hands in.
192
+ expect(rowService.update).toHaveBeenCalledWith(
193
+ expect.objectContaining({
194
+ fields: { is_superuser: 'true' },
195
+ pks: '1',
196
+ }),
197
+ );
198
+ expect(consoleLogSpy).toHaveBeenCalledWith(
199
+ expect.stringContaining('updated successfully'),
200
+ );
201
+ });
202
+
203
+ it('coerces is_superuser: false to the string "false"', async () => {
204
+ await updateSuperuser({
205
+ id: 1,
206
+ password: undefined,
207
+ is_superuser: false,
208
+ });
209
+
210
+ expect(rowService.update).toHaveBeenCalledWith(
211
+ expect.objectContaining({
212
+ fields: { is_superuser: 'false' },
213
+ pks: '1',
214
+ }),
215
+ );
216
+ });
217
+
218
+ it('updates the password when a strong password is given', async () => {
219
+ await updateSuperuser({
220
+ id: 1,
221
+ password: 'Str0ng$Pw!',
222
+ is_superuser: undefined,
223
+ });
224
+
225
+ expect(rowService.update).toHaveBeenCalledTimes(1);
226
+ const [[call]] = rowService.update.mock.calls;
227
+ expect(Object.keys(call.fields)).toEqual(
228
+ expect.arrayContaining(['hashed_password', 'salt']),
229
+ );
230
+ });
231
+ });
232
+ });