import 'dart:io'; import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import '../../security/crypto_manager.dart'; /// Opens the local SQLCipher-encrypted database file. /// /// The hardware-backed 256-bit AES master key is generated on first launch and /// stored in the OS secure vault (Keychain / Keystore / DPAPI) by /// [CryptoManager]; it is handed to SQLCipher through `PRAGMA key` before any /// statement executes. /// /// The native SQLite engine is compiled as SQLCipher through the `sqlite3` /// build-hook define in `pubspec.yaml` (`hooks.user_defines.sqlite3.source`), /// which ships the encrypted engine on every native platform (Android, iOS, /// macOS, Windows, Linux) without dynamic-library override code. QueryExecutor openDatabaseConnection() { return LazyDatabase(() async { final supportDirectory = await getApplicationSupportDirectory(); final databaseFile = File( p.join(supportDirectory.path, 'glp1_companion.db'), ); final masterKey = await CryptoManager().getOrCreateDatabaseEncryptionKey(); return NativeDatabase( databaseFile, setup: (db) { // SQLCipher derives the AES-256 page key from the master-key // passphrase before drift issues its first statement. db.execute("PRAGMA key = '$masterKey';"); }, ); }); }