diff --git a/.env.example b/.env.example index 69beb91..7e91f5f 100644 --- a/.env.example +++ b/.env.example @@ -11,5 +11,5 @@ POSTGRES_USER="user" POSTGRES_PASSWORD="pwd" # TOKEN_LIFETIME in minutes TOKEN_LIFETIME=600 -# Secret key for registration (bcrypt hash, client sends plaintext key) -REGISTRATION_SECRET_KEY=$2a$10$example.bcrypt.hash.here +# Secret key for registration (plaintext, hashed with bcrypt at startup) +REGISTRATION_SECRET_KEY=your-registration-key diff --git a/bin/.env b/bin/.env index 0936a4f..91cc23e 100644 --- a/bin/.env +++ b/bin/.env @@ -11,5 +11,5 @@ POSTGRES_USER="postgres" POSTGRES_PASSWORD="postgres" # TOKEN_LIFETIME in minutes TOKEN_LIFETIME=600 -# Secret key for registration (bcrypt hash, client sends plaintext) -REGISTRATION_SECRET_KEY=$2a$10$mSo1MvV6U7GazfxceLFDl.gBNPm6lnjClWYsFQesx0SalObvBLIF6 \ No newline at end of file +# Secret key for registration (plaintext, hashed with bcrypt at startup) +REGISTRATION_SECRET_KEY=FtracKer*1405. \ No newline at end of file diff --git a/bin/routes/auth_routes.dart b/bin/routes/auth_routes.dart index 6111df0..a2bb192 100644 --- a/bin/routes/auth_routes.dart +++ b/bin/routes/auth_routes.dart @@ -12,8 +12,15 @@ import 'dart:io'; class AuthRoutes { final DatabaseProvider database; final Map _lastRequest = {}; + final String _registrationKeyHash; - AuthRoutes(this.database); + AuthRoutes(this.database) : _registrationKeyHash = _loadRegistrationKeyHash(); + + static String _loadRegistrationKeyHash() { + final dotenv = DotEnv(); + final key = dotenv['REGISTRATION_SECRET_KEY'] ?? ''; + return BCrypt.hashpw(key, BCrypt.gensalt()); + } Router get routes { final router = Router(); @@ -112,10 +119,7 @@ class AuthRoutes { return response; } - final envDotenv = DotEnv(); - final storedHash = envDotenv['REGISTRATION_SECRET_KEY'] ?? ''; - - if (!BCrypt.checkpw(secretKey, storedHash)) { + if (!BCrypt.checkpw(secretKey, _registrationKeyHash)) { stopwatch.stop(); final response = Response(403, body: jsonEncode({'error': 'Invalid registration key'}), headers: {'Content-Type': 'application/json'}); logRequest(method: 'POST', url: '/reg', status: 403, duration: stopwatch.elapsed, body: body, responseHeaders: response.headers); diff --git a/test/server_test.dart b/test/server_test.dart index e03f371..ac5b187 100644 --- a/test/server_test.dart +++ b/test/server_test.dart @@ -41,7 +41,7 @@ void main() { setUpAll(() async { final env = DotEnv(); env.load(['bin/.env']); - registrationSecretKey = 'FtracKer*1405.'; + registrationSecretKey = env['REGISTRATION_SECRET_KEY'] ?? 'FtracKer*1405.'; stdout.writeln("Starting server..."); p = await Process.start(