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.
- package/.env.sample +11 -2
- package/.github/dependabot.yml +9 -0
- package/.github/pull_request_template.md +8 -0
- package/.github/workflows/ci.yml +33 -0
- package/.github/workflows/pr-title.yml +27 -0
- package/.github/workflows/release.yml +44 -0
- package/.husky/pre-commit +0 -3
- package/.release-please-manifest.json +3 -0
- package/AGENTS.md +31 -0
- package/CHANGELOG.md +35 -0
- package/CLAUDE.md +1 -0
- package/README.md +16 -8
- package/ROADMAP.md +154 -0
- package/SECURITY.md +19 -0
- package/docs/extensions-examples.md +96 -16
- package/docs/ws-examples.md +4 -0
- package/eslint.config.js +29 -0
- package/package.json +44 -24
- package/release-please-config.json +10 -0
- package/scripts/dev.sh +64 -0
- package/src/cli.test.js +128 -0
- package/src/config/index.js +10 -2
- package/src/config/index.test.js +120 -0
- package/src/controllers/auth/common.js +1 -16
- package/src/controllers/auth/common.test.js +23 -0
- package/src/controllers/auth/tables.js +1 -1
- package/src/controllers/auth/token.js +30 -7
- package/src/controllers/auth/user.js +20 -20
- package/src/controllers/auth/user.test.js +232 -0
- package/src/controllers/auth.test.js +445 -0
- package/src/controllers/rows.js +159 -112
- package/src/controllers/rows.test.js +88 -1
- package/src/controllers/tables.js +63 -17
- package/src/controllers/tables.test.js +185 -0
- package/src/db/index.test.js +21 -0
- package/src/extensions.js +105 -36
- package/src/extensions.test.js +340 -0
- package/src/index.js +37 -20
- package/src/index.test.js +118 -0
- package/src/middlewares/api.js +1 -1
- package/src/middlewares/api.test.js +29 -0
- package/src/middlewares/auth.js +11 -48
- package/src/middlewares/auth.test.js +105 -0
- package/src/middlewares/validation.test.js +60 -0
- package/src/schemas/index.js +3 -1
- package/src/schemas/rows.js +15 -5
- package/src/schemas/tables.js +28 -4
- package/src/server.js +85 -4
- package/src/services/authService.js +33 -3
- package/src/services/authService.test.js +115 -0
- package/src/services/rowService.js +25 -18
- package/src/services/rowService.test.js +153 -0
- package/src/services/tableService.js +15 -17
- package/src/services/tableService.test.js +190 -0
- package/src/swagger/swagger.json +4 -7
- package/src/tests/index.js +1 -1
- package/src/utils/index.js +25 -2
- package/src/utils/index.test.js +135 -0
- package/src/utils/logger.js +15 -0
- package/src/utils/sql.js +112 -0
- package/src/utils/sql.test.js +115 -0
- package/src/websocket.js +47 -8
- package/src/websocket.test.js +121 -0
- package/.eslintignore +0 -2
- package/.eslintrc.js +0 -24
- package/.github/workflows/npm-publish.yml +0 -23
- package/src/middlewares/logger.js +0 -13
|
@@ -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
|
-
|
|
40
|
-
const fieldsString =
|
|
41
|
-
.map((field) =>
|
|
40
|
+
const fieldNames = Object.keys(data.fields);
|
|
41
|
+
const fieldsString = fieldNames
|
|
42
|
+
.map((field) => quoteIdentifier(field))
|
|
42
43
|
.join(', ');
|
|
43
|
-
|
|
44
|
-
|
|
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 (
|
|
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) =>
|
|
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
|
|
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 ${
|
|
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(
|
|
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(
|
|
111
|
-
.all();
|
|
117
|
+
.prepare('SELECT * FROM pragma_table_info(?)')
|
|
118
|
+
.all(joinedTableName);
|
|
112
119
|
|
|
113
120
|
return { foreignKey, joinedTableName, joinedTableFields };
|
|
114
121
|
},
|
|
@@ -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
|
|
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
|
-
|
|
103
|
-
|
|
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
|
|
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
|
-
|
|
112
|
+
const isDesc = ordering.startsWith('-');
|
|
113
|
+
query += ` ORDER BY name ${isDesc ? 'DESC' : 'ASC'}`;
|
|
110
114
|
}
|
|
111
115
|
|
|
112
116
|
try {
|
|
113
|
-
|
|
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=
|
|
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
|
+
});
|
package/src/swagger/swagger.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"swagger": "2.0",
|
|
3
3
|
"info": {
|
|
4
|
-
"version": "0.8.
|
|
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"
|
package/src/tests/index.js
CHANGED
|
@@ -10,7 +10,7 @@ const dropTestTable = (table = 'users') => {
|
|
|
10
10
|
const dropTestDatabase = async (path = 'test.db') => {
|
|
11
11
|
// delete test database file e.g. test.db
|
|
12
12
|
try {
|
|
13
|
-
await unlink(path), console.log(`successfully deleted ${path}`);
|
|
13
|
+
(await unlink(path), console.log(`successfully deleted ${path}`));
|
|
14
14
|
} catch (error) {
|
|
15
15
|
console.error('there was an error:', error);
|
|
16
16
|
}
|
package/src/utils/index.js
CHANGED
|
@@ -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
|
-
|
|
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,
|