soul-cli 0.11.0 → 0.12.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 CHANGED
@@ -27,5 +27,6 @@ REFRESH_TOKEN_EXPIRATION_TIME=2D
27
27
  INITIAL_USER_USERNAME
28
28
  INITIAL_USER_PASSWORD
29
29
  TOKEN_SECRET
30
+ ANON_ROLE
30
31
 
31
32
  START_WITH_STUDIO=false
package/.prettierrc ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "trailingComma": "all"
4
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "0.11.0"
2
+ ".": "0.12.0"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.12.0](https://github.com/thevahidal/soul/compare/soul-cli-v0.11.0...soul-cli-v0.12.0) (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * add anonymous role for requests without a token ([2bb7f2e](https://github.com/thevahidal/soul/commit/2bb7f2edfc72363ad83dc6677319efc14c066d8c))
9
+ * add atomic batch endpoint for row writes ([#275](https://github.com/thevahidal/soul/issues/275)) ([760bd39](https://github.com/thevahidal/soul/commit/760bd397b98837dee72264223e8ad1d9f6493b9e))
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * allow read-only access to auth tables when auth is off ([5428103](https://github.com/thevahidal/soul/commit/54281030d0f11a3df7a0cb14c397dc7d2e24c9c3))
15
+
3
16
  ## [0.11.0](https://github.com/thevahidal/soul/compare/soul-cli-v0.10.0...soul-cli-v0.11.0) (2026-11-16)
4
17
 
5
18
 
package/README.md CHANGED
@@ -73,6 +73,7 @@ Options:
73
73
  --iup, --initialuserpassword Initial user password [string]
74
74
 
75
75
  --ts, --tokensecret Token Secret [string]
76
+ --ar, --anonrole Role name for requests without a token [string]
76
77
  --atet, --accesstokenexpirationtime Access Token Expiration Time (Default: 5H) [string]
77
78
  --rtet, --refreshtokenexpirationtime Refresh Token Expiration Time (Default: 1D) [string]
78
79
  -S, --studio Start Soul Studio in parallel
@@ -102,6 +103,8 @@ Run the Soul command with the necessary parameters:
102
103
 
103
104
  ```
104
105
 
106
+ > Note: Without `-a`, the auth tables (`_users`, `_roles`, `_roles_permissions`, `_users_roles`) are read-only.
107
+
105
108
  > Note: When configuring your JWT Secret, it is recommended to use a long string value for enhanced security. It is advisable to use a secret that is at least 10 characters in length.
106
109
 
107
110
  In this example:
@@ -0,0 +1,55 @@
1
+ ## Batch
2
+
3
+ `POST /api/batch` runs several row writes (insert, update, delete) in one transaction. If any operation fails, none are applied.
4
+
5
+ Each operation is the REST call you would make on its own: a `method`, a `path` and an optional `body`. Supported paths are `/api/tables/<table-name>/rows` (`POST`) and `/api/tables/<table-name>/rows/<pks>` (`PUT`, `DELETE`, with `?_lookup_field=` supported).
6
+
7
+ ```bash
8
+ curl --request POST \
9
+ --url http://localhost:8000/api/batch \
10
+ --header 'Content-Type: application/json' \
11
+ --data '{
12
+ "operations": [
13
+ {
14
+ "method": "POST",
15
+ "path": "/api/tables/Album/rows",
16
+ "body": { "fields": { "Title": "New Album", "ArtistId": 1 } }
17
+ },
18
+ {
19
+ "method": "PUT",
20
+ "path": "/api/tables/Artist/rows/1",
21
+ "body": { "fields": { "Name": "Renamed" } }
22
+ },
23
+ { "method": "DELETE", "path": "/api/tables/Album/rows/2" }
24
+ ]
25
+ }'
26
+ ```
27
+
28
+ Response: one result per operation, in order.
29
+
30
+ ```json
31
+ {
32
+ "results": [
33
+ { "status": 201, "body": { "message": "Row inserted", "data": {} } },
34
+ { "status": 200, "body": { "message": "Row updated", "data": {} } },
35
+ { "status": 200, "body": { "message": "Row deleted", "data": {} } }
36
+ ]
37
+ }
38
+ ```
39
+
40
+ If an operation fails, the whole batch is rolled back and the response has the status of the failure plus the `index` of the failing operation:
41
+
42
+ ```json
43
+ {
44
+ "message": "table Album has no column named Nope",
45
+ "index": 0
46
+ }
47
+ ```
48
+
49
+ ### Limits
50
+
51
+ - Between 1 and 100 operations per request.
52
+ - Only row writes. `GET` and other paths are rejected.
53
+ - Tables `_users`, `_roles`, `_users_roles` and `_roles_permissions` are not allowed.
54
+ - In auth mode, every operation needs the same table permission as the equivalent single request. If one is denied, the response is `403` and nothing is written.
55
+ - WebSocket events are sent only after the batch commits.
@@ -38,6 +38,7 @@ soul -d ./Chinook_Sqlite.sqlite -p 8000
38
38
  3. [/api/auth/](api/auth-examples.md) Examples for Authentication / Authorization endpoints
39
39
  1. [/api/{table-name}/rows/](api/rows-auth-examples.md) Examples for Rows endpoints in Auth mode
40
40
  4. [/api/](api/root-examples.md) Examples for Root endpoints
41
+ 5. [/api/batch](api/batch-examples.md) Examples for atomic batches of row writes
41
42
 
42
43
  ## Handling Errors
43
44
 
package/docs/auth.md CHANGED
@@ -101,6 +101,16 @@ Soul uses the `default` role to assign permissions to new users.
101
101
 
102
102
  The same happens when Soul boots up, but for all existing tables, making sure that all tables have the `default` role assigned to them.
103
103
 
104
+ ###### Anonymous Role
105
+
106
+ Set `ANON_ROLE` (or `--anonrole`) to the name of a role to let requests without an access token through, limited to that role's permissions. For example, to make the `posts` table publicly readable:
107
+
108
+ 1. Create a role named `public` in `_roles`.
109
+ 2. Add a `_roles_permissions` row for it with `table_name` `posts` and `read` `true`.
110
+ 3. Start Soul with `ANON_ROLE=public`.
111
+
112
+ The anon role also applies to logged-in users, on top of their own roles. It never applies to system tables (names starting with `_`), and an invalid or expired token is still rejected with a 401.
113
+
104
114
  ##### Users Roles
105
115
 
106
116
  To assign roles to users we have a join table called `_users_roles` with the following attributes:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soul-cli",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "A SQLite REST and Realtime server",
5
5
  "main": "src/server.js",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -64,6 +64,12 @@ if (process.env.NO_CLI !== 'true') {
64
64
  type: 'string',
65
65
  demandOption: false,
66
66
  })
67
+ .options('ar', {
68
+ alias: 'anonrole',
69
+ describe: 'Role name applied to requests without an access token',
70
+ type: 'string',
71
+ demandOption: false,
72
+ })
67
73
  .options('atet', {
68
74
  alias: 'accesstokenexpirationtime',
69
75
  describe: 'JWT expiration time for access token',
@@ -37,6 +37,7 @@ const envVarsSchema = Joi.object()
37
37
  INITIAL_USER_PASSWORD: Joi.string(),
38
38
 
39
39
  TOKEN_SECRET: Joi.string(),
40
+ ANON_ROLE: Joi.string(),
40
41
  ACCESS_TOKEN_EXPIRATION_TIME: Joi.string(),
41
42
  REFRESH_TOKEN_EXPIRATION_TIME: Joi.string(),
42
43
  })
@@ -82,6 +83,10 @@ if (argv.refreshtokenexpirationtime) {
82
83
  env.REFRESH_TOKEN_EXPIRATION_TIME = argv.refreshtokenexpirationtime;
83
84
  }
84
85
 
86
+ if (argv.anonrole) {
87
+ env.ANON_ROLE = argv.anonrole;
88
+ }
89
+
85
90
  if (argv.initialuserusername) {
86
91
  env.INITIAL_USER_USERNAME = argv.initialuserusername;
87
92
  }
@@ -127,6 +132,8 @@ module.exports = {
127
132
  envVars.REFRESH_TOKEN_EXPIRATION_TIME ||
128
133
  '3D',
129
134
 
135
+ anonRole: argv.anonrole || envVars.ANON_ROLE || null,
136
+
130
137
  initialUserUsername:
131
138
  argv.initialuserusername || envVars.INITIAL_USER_USERNAME,
132
139
  initialUserPassword:
@@ -30,6 +30,16 @@ describe('Config', () => {
30
30
  expect(config.rateLimit.max).toBe(10);
31
31
  });
32
32
 
33
+ it('reads the anonymous role from ANON_ROLE and defaults to null', () => {
34
+ process.env.ANON_ROLE = 'public';
35
+ jest.resetModules();
36
+ expect(require('./index').anonRole).toBe('public');
37
+
38
+ delete process.env.ANON_ROLE;
39
+ jest.resetModules();
40
+ expect(require('./index').anonRole).toBeNull();
41
+ });
42
+
33
43
  it('reads cookie SameSite/Secure from COOKIE_SAMESITE and COOKIE_SECURE', () => {
34
44
  process.env.COOKIE_SAMESITE = 'none';
35
45
  process.env.COOKIE_SECURE = 'true';
@@ -23,7 +23,7 @@ module.exports = {
23
23
  PERMISSION_NOT_DEFINED_ERROR: 'Permission not defined for this role',
24
24
  ROLE_NOT_FOUND_ERROR: 'Role not found for this user',
25
25
  AUTH_SET_TO_FALSE_ERROR:
26
- 'You can not access this endpoint while AUTH is set to false',
26
+ 'Auth tables are read-only while AUTH is set to false',
27
27
  RESERVED_TABLE_NAME_ERROR:
28
28
  'The table name is reserved. Please choose a different name for the table.',
29
29
  SERVER_ERROR: 'Server error',
@@ -0,0 +1,128 @@
1
+ const config = require('../config');
2
+ const db = require('../db/index');
3
+ const { authService } = require('../services');
4
+ const { dbConstants, responseMessages } = require('../constants');
5
+ const { invalidRequestError } = require('../utils/sql');
6
+ const { broadcastToTable } = require('../middlewares/broadcast');
7
+ const rowSchemas = require('../schemas/rows');
8
+ const { insertRow, updateRows, deleteRows } = require('./rows');
9
+
10
+ const ROW_PATH = /^\/api\/tables\/([^/]+)\/rows(?:\/([^/]+))?$/;
11
+
12
+ const routes = {
13
+ POST: {
14
+ schema: rowSchemas.insertRowInTable,
15
+ run: ({ params, body }) =>
16
+ insertRow({ tableName: params.name, fields: body.fields }),
17
+ },
18
+ PUT: {
19
+ schema: rowSchemas.updateRowInTableByPK,
20
+ run: ({ params, query, body }) =>
21
+ updateRows({
22
+ tableName: params.name,
23
+ pks: params.pks,
24
+ fields: body.fields,
25
+ lookupField: query._lookup_field,
26
+ }),
27
+ },
28
+ DELETE: {
29
+ schema: rowSchemas.deleteRowInTableByPK,
30
+ run: ({ params, query }) =>
31
+ deleteRows({
32
+ tableName: params.name,
33
+ pks: params.pks,
34
+ lookupField: query._lookup_field,
35
+ }),
36
+ },
37
+ };
38
+
39
+ // Validate and authorize one operation; returns what is needed to run it.
40
+ const prepareOperation = ({ method, path, body = {} }, user) => {
41
+ const url = new URL(path, 'http://soul');
42
+ const match = ROW_PATH.exec(url.pathname);
43
+
44
+ if (!match) {
45
+ throw invalidRequestError(`Unsupported path '${path}'`);
46
+ }
47
+
48
+ const [, name, pks] = match;
49
+ const { schema, run } = routes[method];
50
+ const { value, error } = schema.validate({
51
+ params: pks ? { name, pks } : { name },
52
+ query: Object.fromEntries(url.searchParams),
53
+ body,
54
+ cookies: {},
55
+ });
56
+
57
+ if (error) {
58
+ throw invalidRequestError(error.message);
59
+ }
60
+
61
+ if (dbConstants.reservedTableNames.includes(name)) {
62
+ throw invalidRequestError(`Table '${name}' is not allowed in a batch`);
63
+ }
64
+
65
+ if (
66
+ config.auth &&
67
+ !authService.hasTablePermission({
68
+ payload: user || null,
69
+ tableName: name,
70
+ verb: method,
71
+ })
72
+ ) {
73
+ throw invalidRequestError(
74
+ responseMessages.errorMessage.NOT_AUTHORIZED_ERROR,
75
+ 403,
76
+ );
77
+ }
78
+
79
+ return { tableName: name, run: () => run(value) };
80
+ };
81
+
82
+ const withIndex = (index, fn) => {
83
+ try {
84
+ return fn();
85
+ } catch (error) {
86
+ error.index = index;
87
+ throw error;
88
+ }
89
+ };
90
+
91
+ const batch = async (req, res) => {
92
+ /*
93
+ #swagger.tags = ['Rows']
94
+ #swagger.summary = 'Batch'
95
+ #swagger.description = 'Run row inserts, updates and deletes atomically: if one fails, none are applied.'
96
+ #swagger.parameters['body'] = {
97
+ in: 'body',
98
+ required: true,
99
+ type: 'object',
100
+ schema: { $ref: '#/definitions/BatchRequestBody' }
101
+ }
102
+ */
103
+ try {
104
+ const operations = req.body.operations.map((operation, index) =>
105
+ withIndex(index, () => prepareOperation(operation, req.user)),
106
+ );
107
+
108
+ const results = db.transaction(() =>
109
+ operations.map((operation, index) => withIndex(index, operation.run)),
110
+ )();
111
+
112
+ res.json({
113
+ results: results.map(({ status, body }) => ({ status, body })),
114
+ });
115
+
116
+ results.forEach(({ broadcast }, index) =>
117
+ broadcastToTable(operations[index].tableName, broadcast),
118
+ );
119
+ } catch (error) {
120
+ res.status(error.status || 400).json({
121
+ message: error.message,
122
+ index: error.index,
123
+ error: error.body?.error,
124
+ });
125
+ }
126
+ };
127
+
128
+ module.exports = { batch };
@@ -0,0 +1,180 @@
1
+ const supertest = require('supertest');
2
+
3
+ const app = require('../index');
4
+ const config = require('../config');
5
+ const db = require('../db/index');
6
+ const { generateToken } = require('../utils');
7
+ const { websocketSubscribers } = require('../websocket');
8
+
9
+ const requestWithSupertest = supertest(app);
10
+
11
+ const tokenFor = (payload) => generateToken(payload, config.tokenSecret, '1H');
12
+
13
+ const postBatch = async (operations, payload = { isSuperuser: true }) =>
14
+ requestWithSupertest
15
+ .post('/api/batch')
16
+ .set('Cookie', [`accessToken=${await tokenFor(payload)}`])
17
+ .send({ operations });
18
+
19
+ const countUsers = (firstName) =>
20
+ db
21
+ .prepare('SELECT COUNT(*) AS total FROM users WHERE firstName = ?')
22
+ .get(firstName).total;
23
+
24
+ const insertUser = (firstName) => ({
25
+ method: 'POST',
26
+ path: '/api/tables/users/rows',
27
+ body: { fields: { firstName } },
28
+ });
29
+
30
+ describe('POST /api/batch', () => {
31
+ it('applies every operation and returns results in order', async () => {
32
+ const res = await postBatch([
33
+ insertUser('BatchOk'),
34
+ {
35
+ method: 'PUT',
36
+ path: '/api/tables/users/rows/1',
37
+ body: { fields: { lastName: 'BatchUpdated' } },
38
+ },
39
+ insertUser('BatchOkTwo'),
40
+ ]);
41
+
42
+ expect(res.status).toEqual(200);
43
+ expect(res.body.results.map((r) => r.status)).toEqual([201, 200, 201]);
44
+ expect(countUsers('BatchOk')).toEqual(1);
45
+ expect(countUsers('BatchOkTwo')).toEqual(1);
46
+ expect(
47
+ db.prepare('SELECT lastName FROM users WHERE id = 1').get().lastName,
48
+ ).toEqual('BatchUpdated');
49
+ });
50
+
51
+ it('supports delete and _lookup_field', async () => {
52
+ db.prepare("INSERT INTO users (firstName) VALUES ('BatchDelete')").run();
53
+
54
+ const res = await postBatch([
55
+ {
56
+ method: 'DELETE',
57
+ path: '/api/tables/users/rows/BatchDelete?_lookup_field=firstName',
58
+ },
59
+ ]);
60
+
61
+ expect(res.status).toEqual(200);
62
+ expect(countUsers('BatchDelete')).toEqual(0);
63
+ });
64
+
65
+ it('rolls back everything when an operation fails', async () => {
66
+ const res = await postBatch([
67
+ insertUser('BatchRollback'),
68
+ {
69
+ method: 'PUT',
70
+ path: '/api/tables/users/rows/1',
71
+ body: { fields: { nope: 'x' } },
72
+ },
73
+ ]);
74
+
75
+ expect(res.status).toEqual(400);
76
+ expect(res.body.index).toEqual(1);
77
+ expect(countUsers('BatchRollback')).toEqual(0);
78
+ });
79
+
80
+ it('rolls back when a delete matches no rows', async () => {
81
+ const res = await postBatch([
82
+ insertUser('BatchRollbackDelete'),
83
+ { method: 'DELETE', path: '/api/tables/users/rows/999999' },
84
+ ]);
85
+
86
+ expect(res.status).toEqual(404);
87
+ expect(res.body).toMatchObject({ index: 1, error: 'not_found' });
88
+ expect(countUsers('BatchRollbackDelete')).toEqual(0);
89
+ });
90
+
91
+ it.each([
92
+ ['an unsupported path', { method: 'POST', path: '/api/other' }],
93
+ [
94
+ 'a reserved table',
95
+ {
96
+ method: 'POST',
97
+ path: '/api/tables/_users/rows',
98
+ body: { fields: { username: 'x' } },
99
+ },
100
+ ],
101
+ ['a missing pk', { method: 'PUT', path: '/api/tables/users/rows' }],
102
+ [
103
+ 'an unknown table',
104
+ insertUser('x') && {
105
+ method: 'POST',
106
+ path: '/api/tables/missing_table/rows',
107
+ body: { fields: { a: 1 } },
108
+ },
109
+ ],
110
+ ])('rejects %s', async (_, operation) => {
111
+ const res = await postBatch([insertUser('BatchRejected'), operation]);
112
+
113
+ expect(res.status).toBeGreaterThanOrEqual(400);
114
+ expect(res.body.index).toEqual(1);
115
+ expect(countUsers('BatchRejected')).toEqual(0);
116
+ });
117
+
118
+ it('rejects an invalid body', async () => {
119
+ const empty = await postBatch([]);
120
+ const badMethod = await postBatch([{ method: 'GET', path: '/x' }]);
121
+
122
+ expect(empty.status).toEqual(400);
123
+ expect(badMethod.status).toEqual(400);
124
+ });
125
+
126
+ it('rejects more than 100 operations', async () => {
127
+ const res = await postBatch(
128
+ Array.from({ length: 101 }, () => insertUser('BatchTooMany')),
129
+ );
130
+
131
+ expect(res.status).toEqual(400);
132
+ expect(countUsers('BatchTooMany')).toEqual(0);
133
+ });
134
+
135
+ it('returns 401 without a token', async () => {
136
+ const res = await requestWithSupertest
137
+ .post('/api/batch')
138
+ .send({ operations: [insertUser('BatchNoToken')] });
139
+
140
+ expect(res.status).toEqual(401);
141
+ });
142
+
143
+ it('returns 403 and writes nothing when a table is not permitted', async () => {
144
+ const res = await postBatch([insertUser('BatchForbidden')], {
145
+ isSuperuser: false,
146
+ roleIds: [],
147
+ });
148
+
149
+ expect(res.status).toEqual(403);
150
+ expect(res.body.index).toEqual(0);
151
+ expect(countUsers('BatchForbidden')).toEqual(0);
152
+ });
153
+
154
+ describe('broadcasts', () => {
155
+ const send = jest.fn();
156
+
157
+ beforeEach(() => {
158
+ send.mockClear();
159
+ websocketSubscribers.set('users', new Set([{ ws: { send } }]));
160
+ });
161
+
162
+ afterEach(() => websocketSubscribers.delete('users'));
163
+
164
+ it('sends events after a successful commit', async () => {
165
+ await postBatch([insertUser('BatchEvent')]);
166
+
167
+ expect(send).toHaveBeenCalledTimes(1);
168
+ expect(JSON.parse(send.mock.calls[0][0]).type).toEqual('INSERT');
169
+ });
170
+
171
+ it('sends nothing when the batch is rolled back', async () => {
172
+ await postBatch([
173
+ insertUser('BatchNoEvent'),
174
+ { method: 'DELETE', path: '/api/tables/users/rows/999999' },
175
+ ]);
176
+
177
+ expect(send).not.toHaveBeenCalled();
178
+ });
179
+ });
180
+ });