the-mews/app/lib/application/key_store.dart
2026-10-11 22:07:35 +03:00

41 lines
1.4 KiB
Dart

import 'dart:io';
/// The private keys of imported client certificates, as PEM files in the app's
/// own storage. The database keeps the public certificate; the key stays out
/// of it, so a copy of the database never carries a reader's identity.
///
/// The operations are synchronous on purpose: they touch one small file at a
/// time, only when the reader imports or uses an identity, and staying off the
/// event loop keeps them completing within a single interaction.
class KeyStore {
KeyStore(this._root);
/// The directory the keys live in, resolved lazily because finding it asks
/// the platform.
final Future<Directory> Function() _root;
Future<File> _file(int id) async {
final root = await _root();
return File('${root.path}${Platform.pathSeparator}$id.pem');
}
/// Stores the key of the certificate with this id.
Future<void> save(int id, String pem) async {
final file = await _file(id);
file.parent.createSync(recursive: true);
file.writeAsStringSync(pem);
}
/// The key of the certificate with this id, or null when there is none.
Future<String?> read(int id) async {
final file = await _file(id);
if (!file.existsSync()) return null;
return file.readAsStringSync();
}
/// Removes the key of the certificate with this id.
Future<void> delete(int id) async {
final file = await _file(id);
if (file.existsSync()) file.deleteSync();
}
}