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,153 @@
1
+ const Database = require('better-sqlite3');
2
+
3
+ const buildRowService = require('./rowService');
4
+
5
+ describe('rowService', () => {
6
+ let db;
7
+ let rowService;
8
+
9
+ beforeEach(() => {
10
+ db = new Database(':memory:');
11
+ db.exec(`
12
+ CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT);
13
+ CREATE TABLE books (
14
+ id INTEGER PRIMARY KEY,
15
+ title TEXT,
16
+ author_id INTEGER,
17
+ FOREIGN KEY(author_id) REFERENCES authors(id)
18
+ );
19
+ CREATE TABLE empty_defaults (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ note TEXT DEFAULT 'n/a'
22
+ );
23
+ `);
24
+ db.prepare("INSERT INTO authors (name) VALUES ('Ada')").run();
25
+ rowService = buildRowService(db);
26
+ });
27
+
28
+ afterEach(() => {
29
+ db.close();
30
+ });
31
+
32
+ describe('save', () => {
33
+ it('inserts a row with the given fields', () => {
34
+ const result = rowService.save({
35
+ tableName: 'authors',
36
+ fields: { name: 'Grace' },
37
+ });
38
+
39
+ expect(result.changes).toBe(1);
40
+ const row = db
41
+ .prepare('SELECT * FROM authors WHERE id = ?')
42
+ .get(result.lastInsertRowid);
43
+ expect(row.name).toBe('Grace');
44
+ });
45
+
46
+ it('falls back to DEFAULT VALUES when no fields are given', () => {
47
+ const result = rowService.save({
48
+ tableName: 'empty_defaults',
49
+ fields: {},
50
+ });
51
+
52
+ expect(result.changes).toBe(1);
53
+ const row = db
54
+ .prepare('SELECT * FROM empty_defaults WHERE id = ?')
55
+ .get(result.lastInsertRowid);
56
+ expect(row.note).toBe('n/a');
57
+ });
58
+ });
59
+
60
+ describe('update', () => {
61
+ it('updates only the given fields for the matching pk', () => {
62
+ const { lastInsertRowid: id } = rowService.save({
63
+ tableName: 'authors',
64
+ fields: { name: 'Original' },
65
+ });
66
+
67
+ rowService.update({
68
+ tableName: 'authors',
69
+ lookupField: 'id',
70
+ fields: { name: 'Renamed' },
71
+ pks: `${id}`,
72
+ });
73
+
74
+ const row = db.prepare('SELECT * FROM authors WHERE id = ?').get(id);
75
+ expect(row.name).toBe('Renamed');
76
+ });
77
+ });
78
+
79
+ describe('delete', () => {
80
+ it('deletes the row matching the given pk', () => {
81
+ const { lastInsertRowid: id } = rowService.save({
82
+ tableName: 'authors',
83
+ fields: { name: 'ToDelete' },
84
+ });
85
+
86
+ const result = rowService.delete({
87
+ tableName: 'authors',
88
+ lookupField: 'id',
89
+ pks: `${id}`,
90
+ });
91
+
92
+ expect(result.changes).toBe(1);
93
+ expect(
94
+ db.prepare('SELECT * FROM authors WHERE id = ?').get(id),
95
+ ).toBeUndefined();
96
+ });
97
+ });
98
+
99
+ describe('bulkWrite', () => {
100
+ it('inserts multiple rows in one statement', () => {
101
+ rowService.bulkWrite({
102
+ tableName: 'authors',
103
+ fields: [{ name: 'Bulk1' }, { name: 'Bulk2' }],
104
+ });
105
+
106
+ const count = db
107
+ .prepare('SELECT COUNT(*) as total FROM authors')
108
+ .get().total;
109
+ expect(count).toBe(3); // 1 from beforeEach + 2 bulk
110
+ });
111
+ });
112
+
113
+ describe('getForeignKeyInfo', () => {
114
+ it('returns foreign key and joined table info for a valid relation', () => {
115
+ const info = rowService.getForeignKeyInfo('books', 'author_id');
116
+
117
+ expect(info.joinedTableName).toBe('authors');
118
+ expect(info.joinedTableFields.map((f) => f.name)).toEqual(
119
+ expect.arrayContaining(['id', 'name']),
120
+ );
121
+ });
122
+
123
+ it('throws when the field is not a foreign key', () => {
124
+ expect(() => rowService.getForeignKeyInfo('books', 'title')).toThrow(
125
+ "Foreign key not found for field 'title'",
126
+ );
127
+ });
128
+ });
129
+
130
+ describe('get / getCount', () => {
131
+ it('respects whereString/whereStringValues and pagination', () => {
132
+ rowService.save({ tableName: 'authors', fields: { name: 'Beta' } });
133
+
134
+ const results = rowService.get({
135
+ tableName: 'authors',
136
+ whereString: 'WHERE name = ?',
137
+ whereStringValues: ['Beta'],
138
+ limit: 10,
139
+ page: 0,
140
+ });
141
+
142
+ expect(results).toHaveLength(1);
143
+ expect(results[0].name).toBe('Beta');
144
+
145
+ const total = rowService.getCount({
146
+ tableName: 'authors',
147
+ whereString: '',
148
+ whereStringValues: [],
149
+ });
150
+ expect(total).toBe(2);
151
+ });
152
+ });
153
+ });
@@ -78,8 +78,6 @@ module.exports = (db) => {
78
78
  if (indicesString) {
79
79
  db.prepare(indicesString).run();
80
80
  }
81
-
82
- db.prepare(`PRAGMA table_info(${tableName})`).all();
83
81
  } catch (error) {
84
82
  console.log(error);
85
83
  }
@@ -89,42 +87,42 @@ module.exports = (db) => {
89
87
  const { search, ordering, exclude } = options;
90
88
 
91
89
  let query = `SELECT name FROM sqlite_master WHERE type IN ('table', 'view')`;
90
+ const queryValues = [];
92
91
 
93
92
  // if search is provided, search the tables
94
93
  // e.g. search=users
95
94
  if (search) {
96
- query += ` AND name LIKE $searchQuery`;
95
+ query += ` AND name LIKE ?`;
96
+ queryValues.push(`%${search}%`);
97
97
  }
98
98
 
99
99
  // if exclude is passed don't return the some tables
100
100
  // e.g. exclude=['_users', '_roles']
101
- if (exclude) {
102
- const excludeTables = exclude.map((field) => `'${field}'`).join(' ,');
103
- query += `AND name NOT IN (${excludeTables});`;
101
+ if (exclude && exclude.length > 0) {
102
+ query += ` AND name NOT IN (${exclude.map(() => '?').join(', ')})`;
103
+ queryValues.push(...exclude);
104
104
  }
105
105
 
106
106
  // if ordering is provided, order the tables
107
- // e.g. ordering=name (ascending) or ?_ordering=-name (descending)
107
+ // e.g. ordering=name (ascending) or ordering=-name (descending)
108
+ // `name` is the only column this query returns, so it's the only
109
+ // valid ordering target -- ORDER BY can't take a bound parameter for
110
+ // a dynamic column/direction the way a value position can.
108
111
  if (ordering) {
109
- query += ` ORDER BY $ordering`;
112
+ const isDesc = ordering.startsWith('-');
113
+ query += ` ORDER BY name ${isDesc ? 'DESC' : 'ASC'}`;
110
114
  }
111
115
 
112
116
  try {
113
- const tables = db.prepare(query).all({
114
- searchQuery: `%${search}%`,
115
- ordering: `${ordering?.replace('-', '')} ${
116
- ordering?.startsWith('-') ? 'DESC' : 'ASC'
117
- }`,
118
- });
119
- return tables;
117
+ return db.prepare(query).all(...queryValues);
120
118
  } catch (error) {
121
119
  console.log(error);
122
120
  }
123
121
  },
124
122
 
125
123
  checkTableExists(tableName) {
126
- const query = `SELECT name FROM sqlite_master WHERE type='table' AND name='${tableName}'`;
127
- const result = db.prepare(query).get();
124
+ const query = `SELECT name FROM sqlite_master WHERE type='table' AND name = ?`;
125
+ const result = db.prepare(query).get(tableName);
128
126
  return result;
129
127
  },
130
128
  };
@@ -0,0 +1,190 @@
1
+ const Database = require('better-sqlite3');
2
+
3
+ const buildTableService = require('./tableService');
4
+
5
+ describe('tableService', () => {
6
+ let db;
7
+ let tableService;
8
+
9
+ beforeEach(() => {
10
+ db = new Database(':memory:');
11
+ tableService = buildTableService(db);
12
+ });
13
+
14
+ afterEach(() => {
15
+ db.close();
16
+ });
17
+
18
+ describe('createTable', () => {
19
+ it('creates a table with an auto id and timestamp columns by default', () => {
20
+ tableService.createTable('widgets', [{ name: 'title', type: 'TEXT' }]);
21
+
22
+ const columns = db.prepare('PRAGMA table_info(widgets)').all();
23
+ const names = columns.map((c) => c.name);
24
+ expect(names).toEqual(
25
+ expect.arrayContaining(['id', 'title', 'createdAt', 'updatedAt']),
26
+ );
27
+ });
28
+
29
+ it('omits createdAt/updatedAt when disabled', () => {
30
+ tableService.createTable(
31
+ 'no_timestamps',
32
+ [{ name: 'title', type: 'TEXT' }],
33
+ { autoAddCreatedAt: false, autoAddUpdatedAt: false },
34
+ );
35
+
36
+ const columns = db.prepare('PRAGMA table_info(no_timestamps)').all();
37
+ const names = columns.map((c) => c.name);
38
+ expect(names).not.toEqual(
39
+ expect.arrayContaining(['createdAt', 'updatedAt']),
40
+ );
41
+ });
42
+
43
+ it('respects an explicit primary key instead of adding an auto id', () => {
44
+ tableService.createTable('explicit_pk', [
45
+ { name: 'code', type: 'TEXT', primaryKey: true },
46
+ ]);
47
+
48
+ const columns = db.prepare('PRAGMA table_info(explicit_pk)').all();
49
+ expect(columns.find((c) => c.name === 'id')).toBeUndefined();
50
+ expect(columns.find((c) => c.name === 'code').pk).toBe(1);
51
+ });
52
+
53
+ it('applies unique, notNull, and foreign key constraints', () => {
54
+ tableService.createTable('parents', [
55
+ { name: 'label', type: 'TEXT', primaryKey: true },
56
+ ]);
57
+ tableService.createTable('children', [
58
+ {
59
+ name: 'parent_label',
60
+ type: 'TEXT',
61
+ notNull: true,
62
+ unique: true,
63
+ foreignKey: {
64
+ table: 'parents',
65
+ column: 'label',
66
+ onDelete: 'CASCADE',
67
+ onUpdate: 'RESTRICT',
68
+ },
69
+ },
70
+ ]);
71
+
72
+ const fks = db.prepare('PRAGMA foreign_key_list(children)').all();
73
+ expect(fks[0]).toMatchObject({
74
+ table: 'parents',
75
+ from: 'parent_label',
76
+ to: 'label',
77
+ on_delete: 'CASCADE',
78
+ on_update: 'RESTRICT',
79
+ });
80
+ });
81
+
82
+ it('applies a multi-column unique constraint', () => {
83
+ tableService.createTable(
84
+ 'combo_unique',
85
+ [
86
+ { name: 'a', type: 'TEXT' },
87
+ { name: 'b', type: 'TEXT' },
88
+ ],
89
+ {
90
+ multipleUniqueConstraints: {
91
+ name: 'unique_a_b',
92
+ fields: ['a', 'b'],
93
+ },
94
+ },
95
+ );
96
+
97
+ db.prepare("INSERT INTO combo_unique (a, b) VALUES ('x', 'y')").run();
98
+ expect(() =>
99
+ db.prepare("INSERT INTO combo_unique (a, b) VALUES ('x', 'y')").run(),
100
+ ).toThrow();
101
+ });
102
+
103
+ it('logs instead of throwing when the CREATE TABLE statement fails', () => {
104
+ const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
105
+
106
+ // duplicate column names are a genuine SQLite error
107
+ expect(() =>
108
+ tableService.createTable('bad_table', [
109
+ { name: 'x', type: 'TEXT' },
110
+ { name: 'x', type: 'TEXT' },
111
+ ]),
112
+ ).not.toThrow();
113
+
114
+ expect(logSpy).toHaveBeenCalled();
115
+ logSpy.mockRestore();
116
+ });
117
+ });
118
+
119
+ describe('listTables', () => {
120
+ beforeEach(() => {
121
+ tableService.createTable('apples', [{ name: 'x', type: 'TEXT' }], {
122
+ autoAddCreatedAt: false,
123
+ autoAddUpdatedAt: false,
124
+ });
125
+ tableService.createTable('bananas', [{ name: 'x', type: 'TEXT' }], {
126
+ autoAddCreatedAt: false,
127
+ autoAddUpdatedAt: false,
128
+ });
129
+ });
130
+
131
+ it('lists all tables with no options', () => {
132
+ const tables = tableService.listTables().map((t) => t.name);
133
+ expect(tables).toEqual(expect.arrayContaining(['apples', 'bananas']));
134
+ });
135
+
136
+ it('filters by search', () => {
137
+ const tables = tableService.listTables({ search: 'app' });
138
+ expect(tables).toEqual([{ name: 'apples' }]);
139
+ });
140
+
141
+ it('excludes the given table names', () => {
142
+ const tables = tableService
143
+ .listTables({ exclude: ['apples'] })
144
+ .map((t) => t.name);
145
+ expect(tables).not.toContain('apples');
146
+ expect(tables).toContain('bananas');
147
+ });
148
+
149
+ it('orders ascending and descending by name', () => {
150
+ const asc = tableService
151
+ .listTables({ ordering: 'name' })
152
+ .map((t) => t.name);
153
+ const desc = tableService
154
+ .listTables({ ordering: '-name' })
155
+ .map((t) => t.name);
156
+
157
+ expect(asc.indexOf('apples')).toBeLessThan(asc.indexOf('bananas'));
158
+ expect(desc.indexOf('apples')).toBeGreaterThan(desc.indexOf('bananas'));
159
+ });
160
+
161
+ it('logs instead of throwing on a malformed query', () => {
162
+ const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
163
+
164
+ // exclude with an empty array still hits the query path but with no
165
+ // rows to bind -- force a real failure via a closed db instead.
166
+ db.close();
167
+ expect(() => tableService.listTables()).not.toThrow();
168
+
169
+ expect(logSpy).toHaveBeenCalled();
170
+ logSpy.mockRestore();
171
+ });
172
+ });
173
+
174
+ describe('checkTableExists', () => {
175
+ it('returns the row when the table exists', () => {
176
+ tableService.createTable('exists_test', [{ name: 'x', type: 'TEXT' }]);
177
+ expect(tableService.checkTableExists('exists_test')).toMatchObject({
178
+ name: 'exists_test',
179
+ });
180
+ });
181
+
182
+ it('returns undefined when the table does not exist', () => {
183
+ expect(tableService.checkTableExists('nope')).toBeUndefined();
184
+ });
185
+
186
+ it('treats an injection payload as a literal value, not SQL', () => {
187
+ expect(tableService.checkTableExists("x' OR '1'='1")).toBeUndefined();
188
+ });
189
+ });
190
+ });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "swagger": "2.0",
3
3
  "info": {
4
- "version": "0.8.1",
4
+ "version": "0.8.2",
5
5
  "title": "Soul API",
6
6
  "description": "API Documentation for <b>Soul</b>, a SQLite REST and realtime server. "
7
7
  },
@@ -35,7 +35,6 @@
35
35
  "tags": ["Root"],
36
36
  "summary": "Timestamp",
37
37
  "description": "Endpoint to return server timestamp",
38
- "parameters": [],
39
38
  "responses": {
40
39
  "200": {
41
40
  "description": "OK"
@@ -48,7 +47,6 @@
48
47
  "tags": ["Root"],
49
48
  "summary": "Health Check",
50
49
  "description": "Endpoint to return server health status",
51
- "parameters": [],
52
50
  "responses": {
53
51
  "200": {
54
52
  "description": "OK"
@@ -185,6 +183,9 @@
185
183
  },
186
184
  "403": {
187
185
  "description": "Forbidden"
186
+ },
187
+ "409": {
188
+ "description": "Conflict"
188
189
  }
189
190
  }
190
191
  }
@@ -477,7 +478,6 @@
477
478
  "/api/auth/token/obtain": {
478
479
  "post": {
479
480
  "description": "",
480
- "parameters": [],
481
481
  "responses": {
482
482
  "400": {
483
483
  "description": "Bad Request"
@@ -488,7 +488,6 @@
488
488
  "/api/auth/token/refresh": {
489
489
  "get": {
490
490
  "description": "",
491
- "parameters": [],
492
491
  "responses": {
493
492
  "400": {
494
493
  "description": "Bad Request"
@@ -499,7 +498,6 @@
499
498
  "/api/auth/change-password": {
500
499
  "put": {
501
500
  "description": "",
502
- "parameters": [],
503
501
  "responses": {
504
502
  "400": {
505
503
  "description": "Bad Request"
@@ -516,7 +514,6 @@
516
514
  "/api/auth/logout": {
517
515
  "get": {
518
516
  "description": "",
519
- "parameters": [],
520
517
  "responses": {
521
518
  "400": {
522
519
  "description": "Bad Request"
@@ -1,3 +1,5 @@
1
+ const crypto = require('crypto');
2
+
1
3
  const bcrypt = require('bcrypt');
2
4
  const jwt = require('jsonwebtoken');
3
5
 
@@ -9,6 +11,17 @@ const hashPassword = async (password, saltRounds) => {
9
11
  return { hashedPassword, salt };
10
12
  };
11
13
 
14
+ // Synchronous variant for one-shot startup/CLI code paths (initial user
15
+ // creation, `updatesuperuser`) that are invoked without being awaited by
16
+ // their callers — using the async API there would race the process
17
+ // continuing (and, in tests, the app being considered ready) against the
18
+ // hash actually completing on bcrypt's thread pool.
19
+ const hashPasswordSync = (password, saltRounds) => {
20
+ const salt = bcrypt.genSaltSync(saltRounds);
21
+ const hashedPassword = bcrypt.hashSync(password, saltRounds);
22
+ return { hashedPassword, salt };
23
+ };
24
+
12
25
  const comparePasswords = async (plainPassword, hashedPassword) => {
13
26
  const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
14
27
  return isMatch;
@@ -20,7 +33,16 @@ const checkPasswordStrength = (password) => {
20
33
  };
21
34
 
22
35
  const generateToken = async (payload, secret, expiresIn) => {
23
- return jwt.sign(payload, secret, { expiresIn });
36
+ // jsonwebtoken's HS256 signing is deterministic for identical
37
+ // header+payload+secret -- `iat` only has second precision, so two
38
+ // logins for the same user within the same second (same username,
39
+ // userId, isSuperuser, roleIds, and thus same iat/exp) produce
40
+ // byte-identical access/refresh tokens. Since revocation
41
+ // (_revoked_refresh_tokens) is a plain string match, that collision lets
42
+ // logging out one session silently revoke a completely unrelated
43
+ // concurrent session for the same user. `jwtid` guarantees uniqueness
44
+ // regardless of timing.
45
+ return jwt.sign(payload, secret, { expiresIn, jwtid: crypto.randomUUID() });
24
46
  };
25
47
 
26
48
  const decodeToken = async (token, secret) => {
@@ -28,7 +50,7 @@ const decodeToken = async (token, secret) => {
28
50
  const decoded = jwt.verify(token, secret);
29
51
  return decoded;
30
52
  } catch (error) {
31
- throw new Error('Invalid token');
53
+ throw new Error('Invalid token', { cause: error });
32
54
  }
33
55
  };
34
56
 
@@ -69,6 +91,7 @@ const removeFields = async (rows, fields) => {
69
91
 
70
92
  module.exports = {
71
93
  hashPassword,
94
+ hashPasswordSync,
72
95
  comparePasswords,
73
96
  checkPasswordStrength,
74
97
  generateToken,
@@ -0,0 +1,135 @@
1
+ const {
2
+ hashPassword,
3
+ hashPasswordSync,
4
+ comparePasswords,
5
+ checkPasswordStrength,
6
+ generateToken,
7
+ decodeToken,
8
+ toBoolean,
9
+ removeFields,
10
+ } = require('./index');
11
+
12
+ describe('utils', () => {
13
+ describe('hashPassword / comparePasswords', () => {
14
+ it('produces a hash that verifies against the original password', async () => {
15
+ const { hashedPassword, salt } = await hashPassword('Str0ng$Pw!', 10);
16
+
17
+ expect(typeof hashedPassword).toBe('string');
18
+ expect(typeof salt).toBe('string');
19
+ expect(await comparePasswords('Str0ng$Pw!', hashedPassword)).toBe(true);
20
+ expect(await comparePasswords('wrong-password', hashedPassword)).toBe(
21
+ false,
22
+ );
23
+ });
24
+ });
25
+
26
+ describe('hashPasswordSync', () => {
27
+ it('produces a hash that verifies synchronously-generated and async-compared', async () => {
28
+ const { hashedPassword } = hashPasswordSync('Str0ng$Pw!', 10);
29
+
30
+ expect(await comparePasswords('Str0ng$Pw!', hashedPassword)).toBe(true);
31
+ });
32
+ });
33
+
34
+ describe('checkPasswordStrength', () => {
35
+ it('flags a weak password', () => {
36
+ expect(['Too weak', 'Weak']).toContain(checkPasswordStrength('12345678'));
37
+ });
38
+
39
+ it('accepts a strong password', () => {
40
+ expect(checkPasswordStrength('HeK34#C44DMJ')).toBe('Strong');
41
+ });
42
+ });
43
+
44
+ describe('generateToken / decodeToken', () => {
45
+ it('round-trips a payload through a signed token', async () => {
46
+ const token = await generateToken({ userId: 1 }, 'test-secret', '1H');
47
+ const decoded = await decodeToken(token, 'test-secret');
48
+
49
+ expect(decoded.userId).toBe(1);
50
+ });
51
+
52
+ it('throws for a token signed with a different secret', async () => {
53
+ const token = await generateToken({ userId: 1 }, 'secret-a', '1H');
54
+
55
+ await expect(decodeToken(token, 'secret-b')).rejects.toThrow(
56
+ 'Invalid token',
57
+ );
58
+ });
59
+
60
+ it('throws for a malformed token', async () => {
61
+ await expect(decodeToken('not-a-token', 'test-secret')).rejects.toThrow(
62
+ 'Invalid token',
63
+ );
64
+ });
65
+
66
+ it('generates distinct tokens for identical payloads (no jti collision)', async () => {
67
+ // jwt.sign is otherwise deterministic for identical
68
+ // header+payload+secret -- two logins for the same user within the
69
+ // same second (identical iat/exp too) would produce byte-identical
70
+ // tokens without a unique jti, letting revocation of one silently
71
+ // revoke an unrelated concurrent session for that user.
72
+ const payload = { userId: 1, username: 'admin', isSuperuser: 'false' };
73
+ const [tokenA, tokenB] = await Promise.all([
74
+ generateToken(payload, 'test-secret', '1H'),
75
+ generateToken(payload, 'test-secret', '1H'),
76
+ ]);
77
+
78
+ expect(tokenA).not.toBe(tokenB);
79
+
80
+ const [decodedA, decodedB] = await Promise.all([
81
+ decodeToken(tokenA, 'test-secret'),
82
+ decodeToken(tokenB, 'test-secret'),
83
+ ]);
84
+ expect(decodedA.jti).toBeDefined();
85
+ expect(decodedA.jti).not.toBe(decodedB.jti);
86
+ });
87
+
88
+ it('attaches the original jwt error as the cause', async () => {
89
+ try {
90
+ await decodeToken('not-a-token', 'test-secret');
91
+ throw new Error('expected decodeToken to throw');
92
+ } catch (error) {
93
+ expect(error.cause).toBeDefined();
94
+ }
95
+ });
96
+ });
97
+
98
+ describe('toBoolean', () => {
99
+ it.each([
100
+ [true, true],
101
+ [false, false],
102
+ ['true', true],
103
+ ['false', false],
104
+ ['TRUE', true],
105
+ [1, true],
106
+ [0, false],
107
+ ])('converts %p to %p', (input, expected) => {
108
+ expect(toBoolean(input)).toBe(expected);
109
+ });
110
+
111
+ it('throws for a value that cannot be converted', () => {
112
+ expect(() => toBoolean('not-a-boolean')).toThrow(
113
+ 'Invalid value. Cannot convert to boolean.',
114
+ );
115
+ expect(() => toBoolean(2)).toThrow();
116
+ expect(() => toBoolean(null)).toThrow();
117
+ });
118
+ });
119
+
120
+ describe('removeFields', () => {
121
+ it('deletes the given fields from every row, mutating in place', async () => {
122
+ const rows = [
123
+ { id: 1, secret: 'a', keep: 'x' },
124
+ { id: 2, secret: 'b', keep: 'y' },
125
+ ];
126
+
127
+ await removeFields(rows, ['secret']);
128
+
129
+ expect(rows).toEqual([
130
+ { id: 1, keep: 'x' },
131
+ { id: 2, keep: 'y' },
132
+ ]);
133
+ });
134
+ });
135
+ });
@@ -0,0 +1,15 @@
1
+ const winston = require('winston');
2
+
3
+ const config = require('../config');
4
+
5
+ const logger = winston.createLogger({
6
+ level: config.isTest ? 'error' : config.isProduction ? 'info' : 'debug',
7
+ format: winston.format.combine(
8
+ winston.format.timestamp(),
9
+ winston.format.errors({ stack: true }),
10
+ winston.format.json(),
11
+ ),
12
+ transports: [new winston.transports.Console()],
13
+ });
14
+
15
+ module.exports = logger;