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.
- package/.env.sample +11 -2
- package/.github/dependabot.yml +9 -0
- package/.github/workflows/ci.yml +33 -0
- package/.github/workflows/npm-publish.yml +19 -6
- package/.husky/pre-commit +0 -3
- package/README.md +14 -7
- package/ROADMAP.md +154 -0
- package/docs/extensions-examples.md +96 -16
- package/docs/ws-examples.md +4 -0
- package/eslint.config.js +29 -0
- package/package.json +40 -20
- 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 +29 -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 +83 -1
- 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/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 +46 -8
- package/src/websocket.test.js +121 -0
- package/.eslintignore +0 -2
- package/.eslintrc.js +0 -24
- package/src/middlewares/logger.js +0 -13
package/scripts/dev.sh
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Boots a local Soul dev instance with a ready-to-use superuser.
|
|
3
|
+
#
|
|
4
|
+
# The initial user Soul creates is never a superuser by default -- there's
|
|
5
|
+
# no flag to create one directly, it has to be promoted via the
|
|
6
|
+
# `updatesuperuser` CLI command after the fact, against the same DB file
|
|
7
|
+
# (not :memory:, since a separate process can't reach another process's
|
|
8
|
+
# in-memory db). On first run this script does that dance once; on later
|
|
9
|
+
# runs the DB already has a superuser, so it just starts the server.
|
|
10
|
+
set -euo pipefail
|
|
11
|
+
|
|
12
|
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
13
|
+
cd "$ROOT"
|
|
14
|
+
|
|
15
|
+
DB_PATH="${SOUL_DEV_DB:-$ROOT/.dev.db}"
|
|
16
|
+
PORT="${SOUL_DEV_PORT:-8000}"
|
|
17
|
+
TOKEN_SECRET="${SOUL_DEV_TOKEN_SECRET:-dev-only-secret-not-for-production}"
|
|
18
|
+
USERNAME="${SOUL_DEV_USERNAME:-admin}"
|
|
19
|
+
PASSWORD="${SOUL_DEV_PASSWORD:-Str0ngTestPw!1}"
|
|
20
|
+
CORS_ORIGIN="${SOUL_DEV_CORS_ORIGIN:-http://localhost:3000}"
|
|
21
|
+
|
|
22
|
+
# Studio runs on a different port -- cross-origin cookie auth needs these
|
|
23
|
+
# (see COOKIE_SAMESITE/COOKIE_SECURE in src/config/index.js).
|
|
24
|
+
export COOKIE_SAMESITE="${SOUL_DEV_COOKIE_SAMESITE:-none}"
|
|
25
|
+
export COOKIE_SECURE="${SOUL_DEV_COOKIE_SECURE:-true}"
|
|
26
|
+
|
|
27
|
+
SERVER_ARGS=(
|
|
28
|
+
src/server.js
|
|
29
|
+
-d "$DB_PATH"
|
|
30
|
+
-p "$PORT"
|
|
31
|
+
-a
|
|
32
|
+
--ts "$TOKEN_SECRET"
|
|
33
|
+
--iuu "$USERNAME"
|
|
34
|
+
--iup "$PASSWORD"
|
|
35
|
+
--cors "$CORS_ORIGIN"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if [[ ! -f "$DB_PATH" ]]; then
|
|
39
|
+
echo "==> First run: creating $USERNAME and promoting to superuser..."
|
|
40
|
+
|
|
41
|
+
node "${SERVER_ARGS[@]}" &
|
|
42
|
+
SERVER_PID=$!
|
|
43
|
+
for i in $(seq 1 30); do
|
|
44
|
+
curl -sf "http://localhost:$PORT/api/health" >/dev/null 2>&1 && break
|
|
45
|
+
sleep 0.5
|
|
46
|
+
done
|
|
47
|
+
kill "$SERVER_PID" 2>/dev/null || true
|
|
48
|
+
wait "$SERVER_PID" 2>/dev/null || true
|
|
49
|
+
|
|
50
|
+
# updatesuperuser exits 1 on success (existing, harmless CLI quirk) --
|
|
51
|
+
# `|| true` so `set -e` doesn't treat that as a real failure. Checked by
|
|
52
|
+
# output text instead of exit code.
|
|
53
|
+
PROMOTE_OUTPUT="$(node src/server.js updatesuperuser --id=1 --is_superuser=true -d "$DB_PATH" 2>&1 || true)"
|
|
54
|
+
echo "$PROMOTE_OUTPUT"
|
|
55
|
+
if [[ "$PROMOTE_OUTPUT" != *"updated successfully"* ]]; then
|
|
56
|
+
echo "==> Failed to promote $USERNAME to superuser, aborting." >&2
|
|
57
|
+
rm -f "$DB_PATH"
|
|
58
|
+
exit 1
|
|
59
|
+
fi
|
|
60
|
+
|
|
61
|
+
echo "==> $USERNAME / $PASSWORD is now a superuser. Starting for real..."
|
|
62
|
+
fi
|
|
63
|
+
|
|
64
|
+
exec node "${SERVER_ARGS[@]}"
|
package/src/cli.test.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
const { spawnSync, spawn } = require('child_process');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
// src/cli.js and src/commands.js run their real logic based on
|
|
5
|
+
// process.argv/NO_CLI at module-load time (yargs' demandOption, the
|
|
6
|
+
// updatesuperuser command dispatch), so they can't be exercised by
|
|
7
|
+
// requiring them directly in-process the way the rest of the app is
|
|
8
|
+
// tested -- these spawn the actual `soul` entrypoint as a real
|
|
9
|
+
// subprocess and assert on its stdout/exit code, the same way a user
|
|
10
|
+
// would invoke the CLI.
|
|
11
|
+
//
|
|
12
|
+
// --env points at a file that doesn't exist so a developer's own local
|
|
13
|
+
// .env (which sets AUTH=true, a token secret, etc.) can't leak into
|
|
14
|
+
// these tests and make them depend on machine-specific state.
|
|
15
|
+
const SERVER_ENTRY = path.join(__dirname, 'server.js');
|
|
16
|
+
const NO_ENV_FILE = '/tmp/soul-cli-test-no-such-env-file';
|
|
17
|
+
|
|
18
|
+
const runCli = (args, options = {}) =>
|
|
19
|
+
spawnSync('node', [SERVER_ENTRY, '--env', NO_ENV_FILE, ...args], {
|
|
20
|
+
encoding: 'utf-8',
|
|
21
|
+
timeout: 8000,
|
|
22
|
+
env: { PATH: process.env.PATH },
|
|
23
|
+
...options,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('CLI (spawned as a real subprocess)', () => {
|
|
27
|
+
it('exits non-zero with a usage error when --database is missing', () => {
|
|
28
|
+
const result = runCli([]);
|
|
29
|
+
|
|
30
|
+
expect(result.status).not.toBe(0);
|
|
31
|
+
expect(result.stdout + result.stderr).toContain(
|
|
32
|
+
'Missing required argument: d',
|
|
33
|
+
);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('prints help and exits 0 for --help', () => {
|
|
37
|
+
const result = runCli(['--help']);
|
|
38
|
+
|
|
39
|
+
expect(result.status).toBe(0);
|
|
40
|
+
expect(result.stdout).toContain('Usage: soul [options]');
|
|
41
|
+
expect(result.stdout).toContain('--database');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('updatesuperuser exits non-zero when neither --password nor --is_superuser is given', () => {
|
|
45
|
+
const result = runCli(['-d', ':memory:', 'updatesuperuser', '--id=1']);
|
|
46
|
+
|
|
47
|
+
expect(result.status).not.toBe(0);
|
|
48
|
+
expect(result.stdout).toContain(
|
|
49
|
+
'Please provide either the --password or --is_superuser flag',
|
|
50
|
+
);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('updatesuperuser reports a missing user and exits non-zero', () => {
|
|
54
|
+
const result = runCli([
|
|
55
|
+
'-d',
|
|
56
|
+
':memory:',
|
|
57
|
+
'-a',
|
|
58
|
+
'--ts=test-secret-0123456789',
|
|
59
|
+
'--iuu=admin',
|
|
60
|
+
'--iup=Str0ngTestPw!1',
|
|
61
|
+
'updatesuperuser',
|
|
62
|
+
'--id=999',
|
|
63
|
+
'--password=AnotherStr0ngPw!1',
|
|
64
|
+
]);
|
|
65
|
+
|
|
66
|
+
expect(result.status).not.toBe(0);
|
|
67
|
+
expect(result.stdout).toContain('User not found');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('updatesuperuser --is_superuser=true actually promotes the user instead of crashing on the DB write', () => {
|
|
71
|
+
// regression test: --is_superuser is parsed by yargs as a native JS
|
|
72
|
+
// boolean, which better-sqlite3 can't bind directly -- this used to
|
|
73
|
+
// throw "SQLite3 can only bind numbers, strings, bigints, buffers, and
|
|
74
|
+
// null" from inside a catch block with no process.exit(), so the
|
|
75
|
+
// process never terminated and this spawnSync call would hang until
|
|
76
|
+
// its timeout instead of failing fast.
|
|
77
|
+
const result = runCli([
|
|
78
|
+
'-d',
|
|
79
|
+
':memory:',
|
|
80
|
+
'-a',
|
|
81
|
+
'--ts=test-secret-0123456789',
|
|
82
|
+
'--iuu=admin',
|
|
83
|
+
'--iup=Str0ngTestPw!1',
|
|
84
|
+
'updatesuperuser',
|
|
85
|
+
'--id=1',
|
|
86
|
+
'--is_superuser=true',
|
|
87
|
+
]);
|
|
88
|
+
|
|
89
|
+
expect(result.stdout).not.toContain('SQLite3 can only bind');
|
|
90
|
+
expect(result.stdout).toContain('updated successfully');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('starts the server and shuts down cleanly on SIGTERM', (done) => {
|
|
94
|
+
const child = spawn(
|
|
95
|
+
'node',
|
|
96
|
+
[SERVER_ENTRY, '--env', NO_ENV_FILE, '-d', ':memory:', '-p', '0'],
|
|
97
|
+
{ env: { PATH: process.env.PATH } },
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
let stdout = '';
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
child.kill('SIGKILL');
|
|
103
|
+
done(
|
|
104
|
+
new Error(`server did not start in time; stdout so far:\n${stdout}`),
|
|
105
|
+
);
|
|
106
|
+
}, 12000);
|
|
107
|
+
|
|
108
|
+
child.stdout.on('data', (chunk) => {
|
|
109
|
+
stdout += chunk.toString();
|
|
110
|
+
|
|
111
|
+
if (stdout.includes('Soul is running')) {
|
|
112
|
+
child.kill('SIGTERM');
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
child.on('exit', (code, signal) => {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
try {
|
|
119
|
+
expect(stdout).toContain('Soul is running');
|
|
120
|
+
// a clean shutdown exits on its own rather than being force-killed
|
|
121
|
+
expect(signal).not.toBe('SIGKILL');
|
|
122
|
+
done();
|
|
123
|
+
} catch (error) {
|
|
124
|
+
done(error);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}, 15000);
|
|
128
|
+
});
|
package/src/config/index.js
CHANGED
|
@@ -28,6 +28,9 @@ const envVarsSchema = Joi.object()
|
|
|
28
28
|
|
|
29
29
|
EXTENSIONS: Joi.string().default(null),
|
|
30
30
|
|
|
31
|
+
COOKIE_SAMESITE: Joi.string().valid('lax', 'strict', 'none').default('lax'),
|
|
32
|
+
COOKIE_SECURE: Joi.boolean().default(false),
|
|
33
|
+
|
|
31
34
|
START_WITH_STUDIO: Joi.boolean().default(false),
|
|
32
35
|
|
|
33
36
|
INITIAL_USER_USERNAME: Joi.string(),
|
|
@@ -131,13 +134,18 @@ module.exports = {
|
|
|
131
134
|
|
|
132
135
|
rateLimit: {
|
|
133
136
|
enabled: argv['rate-limit-enabled'] || envVars.RATE_LIMIT_ENABLED,
|
|
134
|
-
windowMs: envVars.
|
|
135
|
-
max: envVars.
|
|
137
|
+
windowMs: envVars.RATE_LIMIT_WINDOW_MS,
|
|
138
|
+
max: envVars.RATE_LIMIT_MAX_REQUESTS,
|
|
136
139
|
},
|
|
137
140
|
|
|
138
141
|
extensions: {
|
|
139
142
|
path: argv.extensions || envVars.EXTENSIONS,
|
|
140
143
|
},
|
|
141
144
|
|
|
145
|
+
cookie: {
|
|
146
|
+
sameSite: envVars.COOKIE_SAMESITE,
|
|
147
|
+
secure: envVars.COOKIE_SECURE,
|
|
148
|
+
},
|
|
149
|
+
|
|
142
150
|
startWithStudio: argv.studio || envVars.START_WITH_STUDIO,
|
|
143
151
|
};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
describe('Config', () => {
|
|
2
|
+
const originalEnv = { ...process.env };
|
|
3
|
+
|
|
4
|
+
afterEach(() => {
|
|
5
|
+
process.env = { ...originalEnv };
|
|
6
|
+
jest.resetModules();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it('reads rate limit window and max from RATE_LIMIT_WINDOW_MS and RATE_LIMIT_MAX_REQUESTS', () => {
|
|
10
|
+
process.env.RATE_LIMIT_ENABLED = 'true';
|
|
11
|
+
process.env.RATE_LIMIT_WINDOW_MS = '2000';
|
|
12
|
+
process.env.RATE_LIMIT_MAX_REQUESTS = '3';
|
|
13
|
+
|
|
14
|
+
jest.resetModules();
|
|
15
|
+
const config = require('./index');
|
|
16
|
+
|
|
17
|
+
expect(config.rateLimit.enabled).toBe(true);
|
|
18
|
+
expect(config.rateLimit.windowMs).toBe(2000);
|
|
19
|
+
expect(config.rateLimit.max).toBe(3);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('falls back to schema defaults when rate limit env vars are not set', () => {
|
|
23
|
+
delete process.env.RATE_LIMIT_WINDOW_MS;
|
|
24
|
+
delete process.env.RATE_LIMIT_MAX_REQUESTS;
|
|
25
|
+
|
|
26
|
+
jest.resetModules();
|
|
27
|
+
const config = require('./index');
|
|
28
|
+
|
|
29
|
+
expect(config.rateLimit.windowMs).toBe(1000);
|
|
30
|
+
expect(config.rateLimit.max).toBe(10);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('reads cookie SameSite/Secure from COOKIE_SAMESITE and COOKIE_SECURE', () => {
|
|
34
|
+
process.env.COOKIE_SAMESITE = 'none';
|
|
35
|
+
process.env.COOKIE_SECURE = 'true';
|
|
36
|
+
|
|
37
|
+
jest.resetModules();
|
|
38
|
+
const config = require('./index');
|
|
39
|
+
|
|
40
|
+
expect(config.cookie.sameSite).toBe('none');
|
|
41
|
+
expect(config.cookie.secure).toBe(true);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('falls back to lax/false when cookie env vars are not set', () => {
|
|
45
|
+
delete process.env.COOKIE_SAMESITE;
|
|
46
|
+
delete process.env.COOKIE_SECURE;
|
|
47
|
+
|
|
48
|
+
jest.resetModules();
|
|
49
|
+
const config = require('./index');
|
|
50
|
+
|
|
51
|
+
expect(config.cookie.sameSite).toBe('lax');
|
|
52
|
+
expect(config.cookie.secure).toBe(false);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('throws when the environment fails schema validation', () => {
|
|
56
|
+
process.env.NODE_ENV = 'not-a-real-environment';
|
|
57
|
+
|
|
58
|
+
jest.resetModules();
|
|
59
|
+
expect(() => require('./index')).toThrow('Config validation error');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe('CLI argument overrides', () => {
|
|
63
|
+
afterEach(() => {
|
|
64
|
+
jest.dontMock('../cli');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('prefers CLI args over env vars for every overridable setting', () => {
|
|
68
|
+
jest.doMock('../cli', () => ({
|
|
69
|
+
yargs: {
|
|
70
|
+
argv: {
|
|
71
|
+
port: 9999,
|
|
72
|
+
verbose: 'console',
|
|
73
|
+
database: 'cli.db',
|
|
74
|
+
cors: 'http://a.com,http://b.com',
|
|
75
|
+
auth: true,
|
|
76
|
+
'rate-limit-enabled': true,
|
|
77
|
+
tokensecret: 'cli-secret',
|
|
78
|
+
accesstokenexpirationtime: '1H',
|
|
79
|
+
refreshtokenexpirationtime: '2D',
|
|
80
|
+
initialuserusername: 'cliuser',
|
|
81
|
+
initialuserpassword: 'clipass',
|
|
82
|
+
studio: true,
|
|
83
|
+
extensions: '/some/path',
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
}));
|
|
87
|
+
|
|
88
|
+
jest.resetModules();
|
|
89
|
+
const config = require('./index');
|
|
90
|
+
|
|
91
|
+
expect(config.port).toBe(9999);
|
|
92
|
+
expect(config.verbose).toBe('console');
|
|
93
|
+
expect(config.db.filename).toBe('cli.db');
|
|
94
|
+
expect(config.cors.origin).toEqual(['http://a.com', 'http://b.com']);
|
|
95
|
+
expect(config.auth).toBe(true);
|
|
96
|
+
expect(config.rateLimit.enabled).toBe(true);
|
|
97
|
+
expect(config.tokenSecret).toBe('cli-secret');
|
|
98
|
+
expect(config.accessTokenExpirationTime).toBe('1H');
|
|
99
|
+
expect(config.refreshTokenExpirationTime).toBe('2D');
|
|
100
|
+
expect(config.initialUserUsername).toBe('cliuser');
|
|
101
|
+
expect(config.initialUserPassword).toBe('clipass');
|
|
102
|
+
expect(config.startWithStudio).toBe(true);
|
|
103
|
+
expect(config.extensions.path).toBe('/some/path');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('falls back to a wildcard CORS origin when nothing is configured', () => {
|
|
107
|
+
// set explicitly (rather than deleting) so this doesn't depend on
|
|
108
|
+
// whether a local .env file happens to define this key -- dotenv
|
|
109
|
+
// only fills *missing* process.env keys, so deleting it here would
|
|
110
|
+
// let a developer's own .env leak into the test.
|
|
111
|
+
process.env.CORS_ORIGIN_WHITELIST = '*';
|
|
112
|
+
jest.doMock('../cli', () => ({ yargs: { argv: {} } }));
|
|
113
|
+
|
|
114
|
+
jest.resetModules();
|
|
115
|
+
const config = require('./index');
|
|
116
|
+
|
|
117
|
+
expect(config.cors.origin).toEqual(['*']);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
});
|
|
@@ -1,18 +1,3 @@
|
|
|
1
|
-
const { rowService } = require('../../services');
|
|
2
|
-
const { dbConstants } = require('../../constants');
|
|
3
|
-
|
|
4
|
-
const { USERS_TABLE } = dbConstants;
|
|
5
|
-
|
|
6
|
-
const isUsernameTaken = (username) => {
|
|
7
|
-
const users = rowService.get({
|
|
8
|
-
tableName: USERS_TABLE,
|
|
9
|
-
whereString: 'WHERE username=?',
|
|
10
|
-
whereStringValues: [username],
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
return users.length > 0;
|
|
14
|
-
};
|
|
15
|
-
|
|
16
1
|
const checkAuthConfigs = ({ auth, tokenSecret }) => {
|
|
17
2
|
if (auth && !tokenSecret) {
|
|
18
3
|
throw new Error(
|
|
@@ -21,4 +6,4 @@ const checkAuthConfigs = ({ auth, tokenSecret }) => {
|
|
|
21
6
|
}
|
|
22
7
|
};
|
|
23
8
|
|
|
24
|
-
module.exports = {
|
|
9
|
+
module.exports = { checkAuthConfigs };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
const { checkAuthConfigs } = require('./common');
|
|
2
|
+
|
|
3
|
+
describe('checkAuthConfigs', () => {
|
|
4
|
+
it('throws when auth is enabled but no token secret is provided', () => {
|
|
5
|
+
expect(() =>
|
|
6
|
+
checkAuthConfigs({ auth: true, tokenSecret: undefined }),
|
|
7
|
+
).toThrow(
|
|
8
|
+
'You need to provide a token secret either from the CLI or from your environment variables',
|
|
9
|
+
);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('does not throw when auth is enabled and a token secret is provided', () => {
|
|
13
|
+
expect(() =>
|
|
14
|
+
checkAuthConfigs({ auth: true, tokenSecret: 'some-secret' }),
|
|
15
|
+
).not.toThrow();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('does not throw when auth is disabled, regardless of token secret', () => {
|
|
19
|
+
expect(() =>
|
|
20
|
+
checkAuthConfigs({ auth: false, tokenSecret: undefined }),
|
|
21
|
+
).not.toThrow();
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -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 (
|
|
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 = {
|
|
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
|
-
|
|
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 (
|
|
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 = {
|
|
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
|
|
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 <
|
|
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
|
-
|
|
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
|
-
|
|
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 } =
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 } =
|
|
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({
|