feat(block1): inventory walking skeleton + first quick-add slice
Stand up the Tanemaki monorepo and the first end-to-end vertical slice of Block 1 (offline, encrypted inventory): add a seed → see it in a categorized, searchable list → it persists → reopen and it's still there. Architecture (state management like G1nkgo, adapted to Tane's reality): - flutter_bloc (Cubit-first), but the encrypted Drift DB is the single source of truth; cubits stream from repositories (no hydrated_bloc/Hive, which would write plaintext at rest). - get_it composition root; go_router; slang i18n (ES/EN, Weblate-friendly JSON). Workspace & core: - pub workspace: packages/commons_core (pure Dart) + apps/app_seeds (Flutter). - commons_core primitives: UUIDv7 IdGen, Hybrid Logical Clock, Quantity value type (+ plant-aware QuantityKind), IdentityService root-seed stub. Data & security: - Drift schemaVersion=1 with all 10 Block-1 tables + common CRDT columns (HLC updated_at, last_author, tombstones); Movement append-only. - SQLCipher via an injectable executor that refuses to open a plaintext DB; DB key + root seed in the OS keystore (separate secrets). - Exported drift_schema_v1.json + migration scaffold. Tests (near-TDD; nothing merges without tests): - commons_core units (24), Drift migration test, "no plaintext at rest" security guard (runs where SQLCipher is present, skips otherwise), repository, widget, full quick-add flow, file-reopen persistence, and a no-hardcoded-strings i18n guard. GitLab CI: format + analyze + test + coverage. Follow-on Block-1 stories (item detail/edit, species catalog, germination UI) and all of Block 2 remain out of scope.
This commit is contained in:
parent
57c0eeadaf
commit
040f15a898
131 changed files with 19855 additions and 20 deletions
38
apps/app_seeds/lib/db/database.dart
Normal file
38
apps/app_seeds/lib/db/database.dart
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import 'package:drift/drift.dart';
|
||||
|
||||
import 'enums.dart';
|
||||
import 'tables.dart';
|
||||
|
||||
part 'database.g.dart';
|
||||
|
||||
/// The encrypted local inventory database (SQLCipher via an injected executor).
|
||||
///
|
||||
/// The executor is passed in so production wires SQLCipher while tests can use
|
||||
/// an in-memory database — the schema and queries are identical either way.
|
||||
@DriftDatabase(
|
||||
tables: [
|
||||
Varieties,
|
||||
VarietyVernacularNames,
|
||||
Species,
|
||||
SpeciesCommonNames,
|
||||
Lots,
|
||||
GerminationTests,
|
||||
Movements,
|
||||
Parties,
|
||||
Attachments,
|
||||
ExternalLinks,
|
||||
],
|
||||
)
|
||||
class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase(super.e);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 1;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration => MigrationStrategy(
|
||||
onCreate: (m) async => m.createAll(),
|
||||
// Step-by-step upgrades (from1To2, …) are generated into
|
||||
// schema_versions.dart when schemaVersion is bumped. See data-model §5.
|
||||
);
|
||||
}
|
||||
10194
apps/app_seeds/lib/db/database.g.dart
Normal file
10194
apps/app_seeds/lib/db/database.g.dart
Normal file
File diff suppressed because it is too large
Load diff
61
apps/app_seeds/lib/db/encrypted_executor.dart
Normal file
61
apps/app_seeds/lib/db/encrypted_executor.dart
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:sqlcipher_flutter_libs/sqlcipher_flutter_libs.dart';
|
||||
import 'package:sqlite3/open.dart';
|
||||
import 'package:sqlite3/sqlite3.dart';
|
||||
|
||||
/// Routes package:sqlite3 to the **SQLCipher** build instead of plain SQLite.
|
||||
///
|
||||
/// - Android: the bundled SQLCipher `.so` (from sqlcipher_flutter_libs).
|
||||
/// - Linux: the system `libsqlcipher.so` (dev machines / CI install it).
|
||||
/// - iOS & macOS: SQLCipher is linked into the app binary — no override needed.
|
||||
void useSqlCipher() {
|
||||
open
|
||||
..overrideFor(OperatingSystem.android, openCipherOnAndroid)
|
||||
..overrideFor(OperatingSystem.linux, _openLinuxCipher);
|
||||
}
|
||||
|
||||
DynamicLibrary _openLinuxCipher() {
|
||||
// The dev package ships `libsqlcipher.so`; the runtime package only the
|
||||
// versioned `libsqlcipher.so.0`. Accept either.
|
||||
try {
|
||||
return DynamicLibrary.open('libsqlcipher.so');
|
||||
} on ArgumentError {
|
||||
return DynamicLibrary.open('libsqlcipher.so.0');
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens [file] as an encrypted database using the raw 256-bit [keyHex].
|
||||
///
|
||||
/// Verifies SQLCipher is actually linked (`PRAGMA cipher_version`) and refuses
|
||||
/// to fall back to plaintext — enforcing "no plaintext at rest, ever".
|
||||
QueryExecutor openEncryptedExecutor(File file, String keyHex) {
|
||||
return LazyDatabase(() async {
|
||||
if (Platform.isAndroid) {
|
||||
await applyWorkaroundToOpenSqlCipherOnOldAndroidVersions();
|
||||
}
|
||||
return NativeDatabase.createInBackground(
|
||||
file,
|
||||
isolateSetup: useSqlCipher,
|
||||
setup: (db) => applyKeyAndVerify(db, keyHex),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Applies the SQLCipher key to [db] and asserts encryption is active.
|
||||
///
|
||||
/// `x'…'` passes the key as raw bytes, skipping the KDF (our key is already a
|
||||
/// random 256-bit value from the OS keystore). Exposed for the security test.
|
||||
void applyKeyAndVerify(Database db, String keyHex) {
|
||||
db.execute('PRAGMA key = "x\'$keyHex\'";');
|
||||
final cipher = db.select('PRAGMA cipher_version;');
|
||||
if (cipher.isEmpty) {
|
||||
throw StateError(
|
||||
'SQLCipher is not linked: PRAGMA cipher_version is empty. Encryption at '
|
||||
'rest is mandatory — refusing to open a plaintext database.',
|
||||
);
|
||||
}
|
||||
}
|
||||
27
apps/app_seeds/lib/db/enums.dart
Normal file
27
apps/app_seeds/lib/db/enums.dart
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// Domain enums stored by **name** (never by index) via Drift `textEnum`, so
|
||||
// the stored keys are stable across migrations. Per data-model §5.2, values
|
||||
// may only be appended, never renumbered or reused; when sync arrives, readers
|
||||
// must tolerate unknown values (map to a safe default). No sync yet in Block 1.
|
||||
|
||||
/// Per-lot visibility (data-model §2.3). Used by the future sharing layer.
|
||||
enum OfferStatus { private, shared, exchange, sell }
|
||||
|
||||
/// Append-only event kinds on a Lot (data-model §2.4).
|
||||
enum MovementType {
|
||||
received,
|
||||
given,
|
||||
sown,
|
||||
harvested,
|
||||
germinationTest,
|
||||
split,
|
||||
discarded,
|
||||
}
|
||||
|
||||
/// A counterparty is a person or a collective (data-model §2.5).
|
||||
enum PartyKind { person, collective }
|
||||
|
||||
/// Attachment media kind (data-model §2.1).
|
||||
enum AttachmentKind { photo, doc }
|
||||
|
||||
/// Polymorphic parent of an Attachment / ExternalLink.
|
||||
enum ParentType { variety, lot, movement }
|
||||
30
apps/app_seeds/lib/db/sync_columns.dart
Normal file
30
apps/app_seeds/lib/db/sync_columns.dart
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import 'package:drift/drift.dart';
|
||||
|
||||
/// Common columns on every *mutable* row (data-model §1). Carries the metadata
|
||||
/// needed to merge across devices later (CRDT), even before sync exists.
|
||||
///
|
||||
/// `updatedAt` stores a packed [Hlc] string; `isDeleted` is a tombstone —
|
||||
/// rows are never physically deleted, so they can merge correctly.
|
||||
mixin SyncColumns on Table {
|
||||
TextColumn get id => text()();
|
||||
IntColumn get createdAt => integer()();
|
||||
TextColumn get updatedAt => text()(); // packed HLC
|
||||
TextColumn get lastAuthor => text()(); // public key / device id
|
||||
BoolColumn get isDeleted => boolean().withDefault(const Constant(false))();
|
||||
IntColumn get schemaRowVersion => integer().withDefault(const Constant(1))();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {id};
|
||||
}
|
||||
|
||||
/// Common columns on *append-only* rows (only `Movement` for now). Immutable
|
||||
/// events: no `updatedAt`/`isDeleted` — a correction is a new compensating row.
|
||||
mixin AppendOnlyColumns on Table {
|
||||
TextColumn get id => text()();
|
||||
IntColumn get createdAt => integer()();
|
||||
TextColumn get lastAuthor => text()();
|
||||
IntColumn get schemaRowVersion => integer().withDefault(const Constant(1))();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {id};
|
||||
}
|
||||
107
apps/app_seeds/lib/db/tables.dart
Normal file
107
apps/app_seeds/lib/db/tables.dart
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import 'package:drift/drift.dart';
|
||||
|
||||
import 'enums.dart';
|
||||
import 'sync_columns.dart';
|
||||
|
||||
/// The identity/accession — one row per distinct thing in the inventory.
|
||||
/// Only [label] is mandatory (progressive disclosure).
|
||||
class Varieties extends Table with SyncColumns {
|
||||
TextColumn get label => text()();
|
||||
TextColumn get speciesId => text().nullable()(); // → Species
|
||||
TextColumn get cultivarName => text().nullable()();
|
||||
TextColumn get category =>
|
||||
text().nullable()(); // free text, prefilled from family
|
||||
TextColumn get notes => text().nullable()();
|
||||
}
|
||||
|
||||
/// The multiple common names of a Variety (separate table so concurrent adds
|
||||
/// merge as a set).
|
||||
class VarietyVernacularNames extends Table with SyncColumns {
|
||||
TextColumn get varietyId => text()();
|
||||
TextColumn get name => text()();
|
||||
TextColumn get language => text().nullable()();
|
||||
TextColumn get region => text().nullable()();
|
||||
}
|
||||
|
||||
/// Bundled, mostly read-only name catalog (Wikidata CC0 + GBIF CC-BY).
|
||||
class Species extends Table with SyncColumns {
|
||||
TextColumn get scientificName => text()();
|
||||
TextColumn get wikidataQid => text().nullable()();
|
||||
IntColumn get gbifKey => integer().nullable()();
|
||||
TextColumn get family => text().nullable()();
|
||||
BoolColumn get isBundled => boolean().withDefault(const Constant(false))();
|
||||
}
|
||||
|
||||
/// Localized common names for the catalog (bundled).
|
||||
class SpeciesCommonNames extends Table with SyncColumns {
|
||||
TextColumn get speciesId => text()();
|
||||
TextColumn get name => text()();
|
||||
TextColumn get language => text().nullable()();
|
||||
}
|
||||
|
||||
/// A homogeneous batch held for a Variety — its own year and its own unit.
|
||||
/// Quantity (commons_core value type) is flattened into columns here.
|
||||
class Lots extends Table with SyncColumns {
|
||||
TextColumn get varietyId => text()();
|
||||
IntColumn get harvestYear => integer().nullable()();
|
||||
TextColumn get quantityKind => text().nullable()(); // QuantityKind.name
|
||||
RealColumn get quantityPrecise => real().nullable()();
|
||||
TextColumn get quantityLabel => text().nullable()();
|
||||
TextColumn get storageLocation => text().nullable()();
|
||||
TextColumn get offerStatus =>
|
||||
textEnum<OfferStatus>().withDefault(const Constant('private'))();
|
||||
TextColumn get seedbankId => text().nullable()();
|
||||
}
|
||||
|
||||
/// Optional germination history for a Lot; percent is derived in code.
|
||||
class GerminationTests extends Table with SyncColumns {
|
||||
TextColumn get lotId => text()();
|
||||
IntColumn get testedOn => integer().nullable()(); // date, ms since epoch
|
||||
IntColumn get sampleSize => integer().nullable()();
|
||||
IntColumn get germinatedCount => integer().nullable()();
|
||||
TextColumn get notes => text().nullable()();
|
||||
}
|
||||
|
||||
/// The append-only event log on a Lot — history + provenance DAG.
|
||||
class Movements extends Table with AppendOnlyColumns {
|
||||
TextColumn get lotId => text()();
|
||||
TextColumn get type => textEnum<MovementType>()();
|
||||
IntColumn get occurredOn => integer().nullable()(); // date, ms since epoch
|
||||
TextColumn get counterpartyId => text().nullable()(); // → Party
|
||||
TextColumn get quantityKind => text().nullable()();
|
||||
RealColumn get quantityPrecise => real().nullable()();
|
||||
TextColumn get quantityLabel => text().nullable()();
|
||||
TextColumn get parentMovementId => text().nullable()(); // provenance DAG
|
||||
TextColumn get plantareId => text().nullable()(); // reserved (social layer)
|
||||
TextColumn get notes => text().nullable()();
|
||||
}
|
||||
|
||||
/// A person or collective you exchange with.
|
||||
class Parties extends Table with SyncColumns {
|
||||
TextColumn get displayName => text()();
|
||||
TextColumn get publicKey => text().nullable()();
|
||||
TextColumn get kind =>
|
||||
textEnum<PartyKind>().withDefault(const Constant('person'))();
|
||||
TextColumn get note => text().nullable()();
|
||||
}
|
||||
|
||||
/// Photos/docs. Polymorphic parent. Photo bytes are stored in-DB (encrypted at
|
||||
/// rest by SQLCipher) via [bytes]; external files use [uri]. Storing bytes here
|
||||
/// keeps the "no plaintext at rest" rule for photos in Block 1; an external
|
||||
/// encrypted file store is a later optimization.
|
||||
class Attachments extends Table with SyncColumns {
|
||||
TextColumn get parentType => textEnum<ParentType>()();
|
||||
TextColumn get parentId => text()();
|
||||
TextColumn get kind => textEnum<AttachmentKind>()();
|
||||
TextColumn get uri => text().nullable()();
|
||||
BlobColumn get bytes => blob().nullable()();
|
||||
TextColumn get mimeType => text().nullable()();
|
||||
}
|
||||
|
||||
/// Any pasted URL (Wikipedia, forum…). Polymorphic parent.
|
||||
class ExternalLinks extends Table with SyncColumns {
|
||||
TextColumn get parentType => textEnum<ParentType>()();
|
||||
TextColumn get parentId => text()();
|
||||
TextColumn get url => text()();
|
||||
TextColumn get title => text().nullable()();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue