diff --git a/.github/workflows/flutter-ci.yml b/.github/workflows/flutter-ci.yml index 06f3e75..2a911d4 100644 --- a/.github/workflows/flutter-ci.yml +++ b/.github/workflows/flutter-ci.yml @@ -36,7 +36,7 @@ jobs: run: flutter pub get - name: Analyze - run: flutter analyze --fatal-infos + run: flutter analyze --no-fatal-infos - name: Run tests run: flutter test --reporter expanded diff --git a/.github/workflows/shared-package-ci.yml b/.github/workflows/shared-package-ci.yml new file mode 100644 index 0000000..7fed934 --- /dev/null +++ b/.github/workflows/shared-package-ci.yml @@ -0,0 +1,52 @@ +name: Shared package CI + +on: + pull_request: + branches: + - main + paths: + - "packages/openkey_shared/**" + - ".github/workflows/shared-package-ci.yml" + push: + branches: + - main + paths: + - "packages/openkey_shared/**" + - ".github/workflows/shared-package-ci.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: shared-package-ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + quality: + name: Analyze and test shared package + runs-on: ubuntu-latest + timeout-minutes: 20 + + defaults: + run: + working-directory: packages/openkey_shared + + steps: + - name: Check out source + uses: actions/checkout@v4 + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + + - name: Install dependencies + run: flutter pub get + + - name: Analyze + run: flutter analyze --fatal-infos + + - name: Run tests + run: flutter test --reporter expanded diff --git a/docs/shared-editions-architecture.md b/docs/shared-editions-architecture.md new file mode 100644 index 0000000..47a8633 --- /dev/null +++ b/docs/shared-editions-architecture.md @@ -0,0 +1,55 @@ +# OpenKey shared-edition architecture + +## Goal + +Maintain one implementation of the password manager while shipping two +product editions: + +- **OpenKey** — the public, open-source edition. +- **OpenKey_app** — the private commercial edition with subscriptions and + additional Pro capabilities. + +The editions must not maintain independent copies of cryptography, vault +persistence, synchronization, or common UI. + +## Package boundary + +The public repository owns packages/openkey_shared. Both applications use +this package as their shared implementation. + +The public app uses a local path dependency while developing in this +repository. The private app should consume a pinned tag/commit from the public +repository, never an unpinned moving branch. + +## Edition-specific adapters + +Shared code must not import a billing SDK. Instead it depends on the +FeatureAccess interface. + +- The public application provides FreeEditionFeatureAccess. +- The private application provides a subscription-backed implementation + populated from verified store entitlements. + +Subscription screens, purchase/restore flows, billing products, and private +commercial configuration stay in the private application. + +## Security and migration invariants + +The extraction must preserve: + +- existing encryption algorithms, KDF parameters, key wrapping, and + ciphertext formats; +- Drift schema versions, migrations, and database file locations; +- secure-storage key names and account namespace behavior; +- backup/import/export compatibility; +- authentication and server synchronization protocols. + +Never combine the package extraction with a database/schema migration unless +that migration is independently tested and explicitly required. + +## Rollout + +This foundation change introduces the package and capability contract only. +The source extraction and app wiring are follow-up changes. They require the +private app source to be available so the two codebases can be reconciled +before any shared implementation is removed. diff --git a/lib/src/core/usecases/either.dart b/lib/src/core/usecases/either.dart index d46924a..f1decdf 100644 --- a/lib/src/core/usecases/either.dart +++ b/lib/src/core/usecases/either.dart @@ -1,26 +1,3 @@ -abstract class Either { - const Either(); - T fold(T Function(L l) leftFn, T Function(R r) rightFn); - - bool get isLeft => this is Left; - bool get isRight => this is Right; - - L? get left => isLeft ? (this as Left).value : null; - R? get right => isRight ? (this as Right).value : null; -} - -class Left extends Either { - final L value; - const Left(this.value); - - @override - T fold(T Function(L l) leftFn, T Function(R r) rightFn) => leftFn(value); -} - -class Right extends Either { - final R value; - const Right(this.value); - - @override - T fold(T Function(L l) leftFn, T Function(R r) rightFn) => rightFn(value); -} +/// Compatibility export. The implementation now lives in openkey_shared. +export 'package:openkey_shared/openkey_shared.dart' + show Either, Left, Right; diff --git a/lib/src/core/utils/password_strength.dart b/lib/src/core/utils/password_strength.dart index f56eecb..dd887a8 100644 --- a/lib/src/core/utils/password_strength.dart +++ b/lib/src/core/utils/password_strength.dart @@ -1,20 +1,3 @@ -/// Simple password strength score used across OpenKey (0.0–1.0). -/// -/// Matches the heuristic used when setting a master password: length plus -/// character-class mix. -double passwordStrengthScore(String password) { - if (password.isEmpty) return 0; - var score = (password.length / 12).clamp(0.0, 0.5); - if (RegExp(r'[A-Z]').hasMatch(password)) score += 0.125; - if (RegExp(r'[a-z]').hasMatch(password)) score += 0.125; - if (RegExp(r'\d').hasMatch(password)) score += 0.125; - if (RegExp(r'[^A-Za-z0-9]').hasMatch(password)) score += 0.125; - return score.clamp(0.0, 1.0); -} - -/// True when the password is considered weak for vault health checks. -bool isWeakPassword(String password) { - if (password.isEmpty) return false; - if (password.length < 8) return true; - return passwordStrengthScore(password) < 0.35; -} +/// Compatibility export. The implementation now lives in openkey_shared. +export 'package:openkey_shared/openkey_shared.dart' + show passwordStrengthScore, isWeakPassword; diff --git a/lib/src/features/vault/domain/entities/vault_entry.dart b/lib/src/features/vault/domain/entities/vault_entry.dart index 2bbaacc..0ef4d32 100644 --- a/lib/src/features/vault/domain/entities/vault_entry.dart +++ b/lib/src/features/vault/domain/entities/vault_entry.dart @@ -1,374 +1,8 @@ -import 'package:equatable/equatable.dart'; - -class TotpConfig extends Equatable { - const TotpConfig({ - required this.secret, - this.period = 30, - this.digits = 6, - this.algorithm = 'SHA1', - }); - - final String secret; - final int period; - final int digits; - final String algorithm; - - Map toJson() => { - 'secret': secret, - 'period': period, - 'digits': digits, - 'algorithm': algorithm, - }; - - factory TotpConfig.fromJson(Map? json) { - if (json == null) { - return const TotpConfig(secret: ''); - } - return TotpConfig( - secret: json['secret']?.toString() ?? '', - period: json['period'] as int? ?? 30, - digits: json['digits'] as int? ?? 6, - algorithm: json['algorithm']?.toString() ?? 'SHA1', - ); - } - - bool get isEmpty => secret.isEmpty; - - @override - List get props => [secret, period, digits, algorithm]; -} - -class AttachmentMeta extends Equatable { - const AttachmentMeta({ - required this.id, - required this.name, - required this.size, - this.cipher, - }); - - final String id; - final String name; - final int size; - final String? cipher; - - Map toJson() => { - 'id': id, - 'name': name, - 'size': size, - if (cipher != null) 'cipher': cipher, - }; - - factory AttachmentMeta.fromJson(Map json) { - return AttachmentMeta( - id: json['id']?.toString() ?? '', - name: json['name']?.toString() ?? '', - size: json['size'] as int? ?? 0, - cipher: json['cipher']?.toString(), - ); - } - - @override - List get props => [id, name, size, cipher]; -} - -class PasskeyPayload extends Equatable { - const PasskeyPayload({ - required this.rpId, - required this.credentialId, - this.userHandle, - this.privateKeyCipher, - this.publicKey, - this.alg, - this.signCount, - this.userName, - this.displayName, - }); - - final String rpId; - final String credentialId; - final String? userHandle; - - /// PKCS8 private key (base64url), protected by outer vault encryption. - final String? privateKeyCipher; - - /// COSE_Key public key (base64url CBOR). - final String? publicKey; - - /// COSE algorithm identifier; default -7 (ES256). - final int? alg; - - /// Signature counter. - final int? signCount; - final String? userName; - final String? displayName; - - Map toJson() => { - 'rpId': rpId, - 'credentialId': credentialId, - if (userHandle != null) 'userHandle': userHandle, - if (privateKeyCipher != null) 'privateKeyCipher': privateKeyCipher, - if (publicKey != null) 'publicKey': publicKey, - if (alg != null) 'alg': alg, - if (signCount != null) 'signCount': signCount, - if (userName != null) 'userName': userName, - if (displayName != null) 'displayName': displayName, - }; - - factory PasskeyPayload.fromJson(Map json) { - return PasskeyPayload( - rpId: json['rpId']?.toString() ?? '', - credentialId: json['credentialId']?.toString() ?? '', - userHandle: json['userHandle']?.toString(), - privateKeyCipher: json['privateKeyCipher']?.toString(), - publicKey: json['publicKey']?.toString(), - alg: json['alg'] is int - ? json['alg'] as int - : int.tryParse(json['alg']?.toString() ?? ''), - signCount: json['signCount'] is int - ? json['signCount'] as int - : int.tryParse(json['signCount']?.toString() ?? ''), - userName: json['userName']?.toString(), - displayName: json['displayName']?.toString(), - ); - } - - @override - List get props => [ - rpId, - credentialId, - userHandle, - privateKeyCipher, - publicKey, - alg, - signCount, - userName, - displayName, - ]; -} - -/// Extra typed field on a login entry (email, phone, PIN, …). -class EntryExtraField extends Equatable { - const EntryExtraField({ - required this.type, - required this.value, - }); - - /// Stable type key, e.g. `email`, `phone`, `pin`. - final String type; - final String value; - - bool get isEmpty => value.trim().isEmpty; - - Map toJson() => { - 'type': type, - 'value': value, - }; - - factory EntryExtraField.fromJson(Map json) { - return EntryExtraField( - type: json['type']?.toString() ?? '', - value: json['value']?.toString() ?? '', - ); - } - - EntryExtraField copyWith({String? type, String? value}) { - return EntryExtraField( - type: type ?? this.type, - value: value ?? this.value, - ); - } - - @override - List get props => [type, value]; -} - -class VaultEntry extends Equatable { - const VaultEntry({ - required this.uuid, - required this.title, - this.collectionUuid, - this.username = '', - this.password = '', - this.urls = const [], - this.notes = '', - this.tags = const [], - this.fields = const [], - this.fieldOrder = const [], - this.icon = '', - this.totp, - this.attachments = const [], - this.passkey, - this.revision = 1, - this.isSynced = false, - this.createdAt, - this.updatedAt, - }); - - final String uuid; - final String? collectionUuid; - final String title; - final String username; - final String password; - final List urls; - final String notes; - final List tags; - final List fields; - /// Ordered optional field keys (`username`, `email`, …) for the editor UI. - final List fieldOrder; - /// Icon key: `material:*`, `brands/*.svg`, or empty (auto-suggest). - final String icon; - final TotpConfig? totp; - final List attachments; - final PasskeyPayload? passkey; - final int revision; - final bool isSynced; - final DateTime? createdAt; - final DateTime? updatedAt; - - /// True when OS autofill / origin fill should offer this login. - bool get isAutofillFillable => - username.isNotEmpty || - password.isNotEmpty || - (passkey?.privateKeyCipher?.isNotEmpty ?? false); - - String? fieldValue(String type) { - for (final field in fields) { - if (field.type == type) return field.value; - } - return null; - } - - VaultEntry copyWith({ - String? uuid, - String? collectionUuid, - String? title, - String? username, - String? password, - List? urls, - String? notes, - List? tags, - List? fields, - List? fieldOrder, - String? icon, - TotpConfig? totp, - List? attachments, - PasskeyPayload? passkey, - int? revision, - bool? isSynced, - DateTime? createdAt, - DateTime? updatedAt, - bool clearCollection = false, - bool clearTotp = false, - bool clearPasskey = false, - }) { - return VaultEntry( - uuid: uuid ?? this.uuid, - collectionUuid: - clearCollection ? null : (collectionUuid ?? this.collectionUuid), - title: title ?? this.title, - username: username ?? this.username, - password: password ?? this.password, - urls: urls ?? this.urls, - notes: notes ?? this.notes, - tags: tags ?? this.tags, - fields: fields ?? this.fields, - fieldOrder: fieldOrder ?? this.fieldOrder, - icon: icon ?? this.icon, - totp: clearTotp ? null : (totp ?? this.totp), - attachments: attachments ?? this.attachments, - passkey: clearPasskey ? null : (passkey ?? this.passkey), - revision: revision ?? this.revision, - isSynced: isSynced ?? this.isSynced, - createdAt: createdAt ?? this.createdAt, - updatedAt: updatedAt ?? this.updatedAt, - ); - } - - Map toPayload() => { - 'title': title, - 'username': username, - 'password': password, - 'urls': urls, - 'notes': notes, - if (tags.isNotEmpty) 'tags': tags, - if (fields.isNotEmpty) - 'fields': fields.map((f) => f.toJson()).toList(), - if (fieldOrder.isNotEmpty) 'fieldOrder': fieldOrder, - if (icon.isNotEmpty) 'icon': icon, - if (totp != null && !totp!.isEmpty) 'totp': totp!.toJson(), - if (attachments.isNotEmpty) - 'attachments': attachments.map((a) => a.toJson()).toList(), - if (passkey != null) 'passkey': passkey!.toJson(), - }; - - factory VaultEntry.fromPayload({ - required String uuid, - String? collectionUuid, - required Map payload, - int revision = 1, - bool isSynced = false, - DateTime? createdAt, - DateTime? updatedAt, - }) { - final totpJson = payload['totp']; - final passkeyJson = payload['passkey']; - final attachmentsJson = payload['attachments'] as List?; - final tagsJson = payload['tags'] as List?; - final fieldsJson = payload['fields'] as List?; - final fieldOrderJson = payload['fieldOrder'] as List?; - return VaultEntry( - uuid: uuid, - collectionUuid: collectionUuid, - title: payload['title']?.toString() ?? '', - username: payload['username']?.toString() ?? '', - password: payload['password']?.toString() ?? '', - urls: (payload['urls'] as List?)?.map((e) => e.toString()).toList() ?? - const [], - notes: payload['notes']?.toString() ?? '', - tags: tagsJson?.map((e) => e.toString()).toList() ?? const [], - fields: fieldsJson - ?.whereType() - .map((e) => EntryExtraField.fromJson(Map.from(e))) - .where((f) => f.type.isNotEmpty) - .toList() ?? - const [], - fieldOrder: - fieldOrderJson?.map((e) => e.toString()).toList() ?? const [], - icon: payload['icon']?.toString() ?? '', - totp: totpJson is Map - ? TotpConfig.fromJson(totpJson) - : null, - attachments: attachmentsJson - ?.whereType() - .map((e) => AttachmentMeta.fromJson(Map.from(e))) - .toList() ?? - const [], - passkey: passkeyJson is Map - ? PasskeyPayload.fromJson(passkeyJson) - : null, - revision: revision, - isSynced: isSynced, - createdAt: createdAt, - updatedAt: updatedAt, - ); - } - - @override - List get props => [ - uuid, - collectionUuid, - title, - username, - password, - urls, - notes, - tags, - fields, - fieldOrder, - icon, - totp, - attachments, - passkey, - revision, - ]; -} +/// Compatibility export. The implementation now lives in openkey_shared. +export 'package:openkey_shared/openkey_shared.dart' + show + AttachmentMeta, + EntryExtraField, + PasskeyPayload, + TotpConfig, + VaultEntry; diff --git a/packages/openkey_shared/README.md b/packages/openkey_shared/README.md new file mode 100644 index 0000000..6a43ced --- /dev/null +++ b/packages/openkey_shared/README.md @@ -0,0 +1,48 @@ +# openkey_shared + +The shared Flutter package for the official OpenKey editions. + +## Shared APIs + +The package currently owns dependency-light code that must behave identically +in both apps: + +- `Either`, `Left`, and `Right` for typed success/failure results. +- `passwordStrengthScore` and `isWeakPassword` for the vault password + strength heuristic. +- `VaultEntry` and its nested TOTP, attachment, passkey, and extra-field + models, including the existing payload serialization contract. +- `FeatureAccess` and the edition capability identifiers used by host apps. + +Import the public API through: + +```dart +import 'package:openkey_shared/openkey_shared.dart'; +``` + +The existing app-local paths remain as thin re-exports for source compatibility. +The implementation lives in this package only, so fixes to the shared logic are +picked up by both editions after their dependency is updated. + +## Ownership boundary + +This package owns implementation that must stay consistent between editions: +shared domain primitives, cryptography, vault models, persistence, auth/sync +domain logic, and reusable services or UI as those modules are migrated. + +The host applications own product-specific composition: + +- application entry points, branding, signing, and store configuration; +- free-edition and subscription-backed feature-access policies; +- paywalls, purchases, restore flows, and billing SDK integrations; +- private Pro-only presentation and commercial configuration. + +Do not put purchase SDKs, store product IDs, API secrets, signing files, or +subscription credentials in this package. + +## Migration safety + +The next extraction stages must preserve existing encryption algorithms and +ciphertext formats, key-derivation parameters, Drift schemas and migrations, +secure-storage key names, backup compatibility, and server sync protocols. +Move these components only with regression tests against existing user data. diff --git a/packages/openkey_shared/analysis_options.yaml b/packages/openkey_shared/analysis_options.yaml new file mode 100644 index 0000000..45c3321 --- /dev/null +++ b/packages/openkey_shared/analysis_options.yaml @@ -0,0 +1,6 @@ +include: package:flutter_lints/flutter.yaml + +linter: + rules: + avoid_print: true + prefer_single_quotes: true diff --git a/packages/openkey_shared/lib/openkey_shared.dart b/packages/openkey_shared/lib/openkey_shared.dart new file mode 100644 index 0000000..55e7ab4 --- /dev/null +++ b/packages/openkey_shared/lib/openkey_shared.dart @@ -0,0 +1,9 @@ +/// Public API for functionality shared by OpenKey editions. +library; + +export 'src/core/either.dart'; +export 'src/feature_access/feature_access.dart'; +export 'src/feature_access/free_edition_feature_access.dart'; +export 'src/feature_access/open_key_feature.dart'; +export 'src/security/password_strength.dart'; +export 'src/models/vault_entry.dart'; diff --git a/packages/openkey_shared/lib/src/core/either.dart b/packages/openkey_shared/lib/src/core/either.dart new file mode 100644 index 0000000..0ca24cc --- /dev/null +++ b/packages/openkey_shared/lib/src/core/either.dart @@ -0,0 +1,37 @@ +/// A lightweight result type shared by the OpenKey editions. +/// +/// Use [Left] for failures and [Right] for successful values. This type is +/// deliberately dependency-free so it can be used by domain and data layers. +abstract class Either { + const Either(); + + T fold(T Function(L left) leftFn, T Function(R right) rightFn); + + bool get isLeft => this is Left; + bool get isRight => this is Right; + + L? get left => isLeft ? (this as Left).value : null; + R? get right => isRight ? (this as Right).value : null; +} + +/// The failure branch of an [Either]. +class Left extends Either { + const Left(this.value); + + final L value; + + @override + T fold(T Function(L left) leftFn, T Function(R right) rightFn) => + leftFn(value); +} + +/// The success branch of an [Either]. +class Right extends Either { + const Right(this.value); + + final R value; + + @override + T fold(T Function(L left) leftFn, T Function(R right) rightFn) => + rightFn(value); +} diff --git a/packages/openkey_shared/lib/src/feature_access/feature_access.dart b/packages/openkey_shared/lib/src/feature_access/feature_access.dart new file mode 100644 index 0000000..0fd6304 --- /dev/null +++ b/packages/openkey_shared/lib/src/feature_access/feature_access.dart @@ -0,0 +1,15 @@ +import 'open_key_feature.dart'; + +/// Resolves edition-specific access to shared OpenKey capabilities. +/// +/// Implementations belong to the host application: +/// - the open-source edition supplies its free-edition policy; +/// - the private commercial edition supplies a policy backed by its verified +/// subscription entitlement. +/// +/// Keep billing SDKs, store product identifiers, purchase flows, and secrets +/// out of this package. +abstract interface class FeatureAccess { + /// Whether the current installation can use [feature]. + bool canUse(OpenKeyFeature feature); +} diff --git a/packages/openkey_shared/lib/src/feature_access/free_edition_feature_access.dart b/packages/openkey_shared/lib/src/feature_access/free_edition_feature_access.dart new file mode 100644 index 0000000..12302cd --- /dev/null +++ b/packages/openkey_shared/lib/src/feature_access/free_edition_feature_access.dart @@ -0,0 +1,17 @@ +import 'feature_access.dart'; +import 'open_key_feature.dart'; + +/// Default capability policy for the free OpenKey edition. +/// +/// This policy intentionally contains only feature availability that is +/// explicitly documented by the public product. Additional limits or Pro +/// capabilities must be added after verification against both applications. +final class FreeEditionFeatureAccess implements FeatureAccess { + /// Creates the default free-edition policy. + const FreeEditionFeatureAccess(); + + @override + bool canUse(OpenKeyFeature feature) => switch (feature) { + OpenKeyFeature.nearbyDeviceSync => false, + }; +} diff --git a/packages/openkey_shared/lib/src/feature_access/open_key_feature.dart b/packages/openkey_shared/lib/src/feature_access/open_key_feature.dart new file mode 100644 index 0000000..6aa243e --- /dev/null +++ b/packages/openkey_shared/lib/src/feature_access/open_key_feature.dart @@ -0,0 +1,11 @@ +/// A capability that can have different availability by OpenKey edition. +/// +/// Add identifiers here only when their product behavior and free/pro +/// availability are documented and verified in the application. +enum OpenKeyFeature { + /// Direct peer-to-peer synchronization with nearby devices over the LAN. + /// + /// The public OpenKey product documentation identifies this as an OpenKey + /// Pro capability. + nearbyDeviceSync, +} diff --git a/packages/openkey_shared/lib/src/models/vault_entry.dart b/packages/openkey_shared/lib/src/models/vault_entry.dart new file mode 100644 index 0000000..2bbaacc --- /dev/null +++ b/packages/openkey_shared/lib/src/models/vault_entry.dart @@ -0,0 +1,374 @@ +import 'package:equatable/equatable.dart'; + +class TotpConfig extends Equatable { + const TotpConfig({ + required this.secret, + this.period = 30, + this.digits = 6, + this.algorithm = 'SHA1', + }); + + final String secret; + final int period; + final int digits; + final String algorithm; + + Map toJson() => { + 'secret': secret, + 'period': period, + 'digits': digits, + 'algorithm': algorithm, + }; + + factory TotpConfig.fromJson(Map? json) { + if (json == null) { + return const TotpConfig(secret: ''); + } + return TotpConfig( + secret: json['secret']?.toString() ?? '', + period: json['period'] as int? ?? 30, + digits: json['digits'] as int? ?? 6, + algorithm: json['algorithm']?.toString() ?? 'SHA1', + ); + } + + bool get isEmpty => secret.isEmpty; + + @override + List get props => [secret, period, digits, algorithm]; +} + +class AttachmentMeta extends Equatable { + const AttachmentMeta({ + required this.id, + required this.name, + required this.size, + this.cipher, + }); + + final String id; + final String name; + final int size; + final String? cipher; + + Map toJson() => { + 'id': id, + 'name': name, + 'size': size, + if (cipher != null) 'cipher': cipher, + }; + + factory AttachmentMeta.fromJson(Map json) { + return AttachmentMeta( + id: json['id']?.toString() ?? '', + name: json['name']?.toString() ?? '', + size: json['size'] as int? ?? 0, + cipher: json['cipher']?.toString(), + ); + } + + @override + List get props => [id, name, size, cipher]; +} + +class PasskeyPayload extends Equatable { + const PasskeyPayload({ + required this.rpId, + required this.credentialId, + this.userHandle, + this.privateKeyCipher, + this.publicKey, + this.alg, + this.signCount, + this.userName, + this.displayName, + }); + + final String rpId; + final String credentialId; + final String? userHandle; + + /// PKCS8 private key (base64url), protected by outer vault encryption. + final String? privateKeyCipher; + + /// COSE_Key public key (base64url CBOR). + final String? publicKey; + + /// COSE algorithm identifier; default -7 (ES256). + final int? alg; + + /// Signature counter. + final int? signCount; + final String? userName; + final String? displayName; + + Map toJson() => { + 'rpId': rpId, + 'credentialId': credentialId, + if (userHandle != null) 'userHandle': userHandle, + if (privateKeyCipher != null) 'privateKeyCipher': privateKeyCipher, + if (publicKey != null) 'publicKey': publicKey, + if (alg != null) 'alg': alg, + if (signCount != null) 'signCount': signCount, + if (userName != null) 'userName': userName, + if (displayName != null) 'displayName': displayName, + }; + + factory PasskeyPayload.fromJson(Map json) { + return PasskeyPayload( + rpId: json['rpId']?.toString() ?? '', + credentialId: json['credentialId']?.toString() ?? '', + userHandle: json['userHandle']?.toString(), + privateKeyCipher: json['privateKeyCipher']?.toString(), + publicKey: json['publicKey']?.toString(), + alg: json['alg'] is int + ? json['alg'] as int + : int.tryParse(json['alg']?.toString() ?? ''), + signCount: json['signCount'] is int + ? json['signCount'] as int + : int.tryParse(json['signCount']?.toString() ?? ''), + userName: json['userName']?.toString(), + displayName: json['displayName']?.toString(), + ); + } + + @override + List get props => [ + rpId, + credentialId, + userHandle, + privateKeyCipher, + publicKey, + alg, + signCount, + userName, + displayName, + ]; +} + +/// Extra typed field on a login entry (email, phone, PIN, …). +class EntryExtraField extends Equatable { + const EntryExtraField({ + required this.type, + required this.value, + }); + + /// Stable type key, e.g. `email`, `phone`, `pin`. + final String type; + final String value; + + bool get isEmpty => value.trim().isEmpty; + + Map toJson() => { + 'type': type, + 'value': value, + }; + + factory EntryExtraField.fromJson(Map json) { + return EntryExtraField( + type: json['type']?.toString() ?? '', + value: json['value']?.toString() ?? '', + ); + } + + EntryExtraField copyWith({String? type, String? value}) { + return EntryExtraField( + type: type ?? this.type, + value: value ?? this.value, + ); + } + + @override + List get props => [type, value]; +} + +class VaultEntry extends Equatable { + const VaultEntry({ + required this.uuid, + required this.title, + this.collectionUuid, + this.username = '', + this.password = '', + this.urls = const [], + this.notes = '', + this.tags = const [], + this.fields = const [], + this.fieldOrder = const [], + this.icon = '', + this.totp, + this.attachments = const [], + this.passkey, + this.revision = 1, + this.isSynced = false, + this.createdAt, + this.updatedAt, + }); + + final String uuid; + final String? collectionUuid; + final String title; + final String username; + final String password; + final List urls; + final String notes; + final List tags; + final List fields; + /// Ordered optional field keys (`username`, `email`, …) for the editor UI. + final List fieldOrder; + /// Icon key: `material:*`, `brands/*.svg`, or empty (auto-suggest). + final String icon; + final TotpConfig? totp; + final List attachments; + final PasskeyPayload? passkey; + final int revision; + final bool isSynced; + final DateTime? createdAt; + final DateTime? updatedAt; + + /// True when OS autofill / origin fill should offer this login. + bool get isAutofillFillable => + username.isNotEmpty || + password.isNotEmpty || + (passkey?.privateKeyCipher?.isNotEmpty ?? false); + + String? fieldValue(String type) { + for (final field in fields) { + if (field.type == type) return field.value; + } + return null; + } + + VaultEntry copyWith({ + String? uuid, + String? collectionUuid, + String? title, + String? username, + String? password, + List? urls, + String? notes, + List? tags, + List? fields, + List? fieldOrder, + String? icon, + TotpConfig? totp, + List? attachments, + PasskeyPayload? passkey, + int? revision, + bool? isSynced, + DateTime? createdAt, + DateTime? updatedAt, + bool clearCollection = false, + bool clearTotp = false, + bool clearPasskey = false, + }) { + return VaultEntry( + uuid: uuid ?? this.uuid, + collectionUuid: + clearCollection ? null : (collectionUuid ?? this.collectionUuid), + title: title ?? this.title, + username: username ?? this.username, + password: password ?? this.password, + urls: urls ?? this.urls, + notes: notes ?? this.notes, + tags: tags ?? this.tags, + fields: fields ?? this.fields, + fieldOrder: fieldOrder ?? this.fieldOrder, + icon: icon ?? this.icon, + totp: clearTotp ? null : (totp ?? this.totp), + attachments: attachments ?? this.attachments, + passkey: clearPasskey ? null : (passkey ?? this.passkey), + revision: revision ?? this.revision, + isSynced: isSynced ?? this.isSynced, + createdAt: createdAt ?? this.createdAt, + updatedAt: updatedAt ?? this.updatedAt, + ); + } + + Map toPayload() => { + 'title': title, + 'username': username, + 'password': password, + 'urls': urls, + 'notes': notes, + if (tags.isNotEmpty) 'tags': tags, + if (fields.isNotEmpty) + 'fields': fields.map((f) => f.toJson()).toList(), + if (fieldOrder.isNotEmpty) 'fieldOrder': fieldOrder, + if (icon.isNotEmpty) 'icon': icon, + if (totp != null && !totp!.isEmpty) 'totp': totp!.toJson(), + if (attachments.isNotEmpty) + 'attachments': attachments.map((a) => a.toJson()).toList(), + if (passkey != null) 'passkey': passkey!.toJson(), + }; + + factory VaultEntry.fromPayload({ + required String uuid, + String? collectionUuid, + required Map payload, + int revision = 1, + bool isSynced = false, + DateTime? createdAt, + DateTime? updatedAt, + }) { + final totpJson = payload['totp']; + final passkeyJson = payload['passkey']; + final attachmentsJson = payload['attachments'] as List?; + final tagsJson = payload['tags'] as List?; + final fieldsJson = payload['fields'] as List?; + final fieldOrderJson = payload['fieldOrder'] as List?; + return VaultEntry( + uuid: uuid, + collectionUuid: collectionUuid, + title: payload['title']?.toString() ?? '', + username: payload['username']?.toString() ?? '', + password: payload['password']?.toString() ?? '', + urls: (payload['urls'] as List?)?.map((e) => e.toString()).toList() ?? + const [], + notes: payload['notes']?.toString() ?? '', + tags: tagsJson?.map((e) => e.toString()).toList() ?? const [], + fields: fieldsJson + ?.whereType() + .map((e) => EntryExtraField.fromJson(Map.from(e))) + .where((f) => f.type.isNotEmpty) + .toList() ?? + const [], + fieldOrder: + fieldOrderJson?.map((e) => e.toString()).toList() ?? const [], + icon: payload['icon']?.toString() ?? '', + totp: totpJson is Map + ? TotpConfig.fromJson(totpJson) + : null, + attachments: attachmentsJson + ?.whereType() + .map((e) => AttachmentMeta.fromJson(Map.from(e))) + .toList() ?? + const [], + passkey: passkeyJson is Map + ? PasskeyPayload.fromJson(passkeyJson) + : null, + revision: revision, + isSynced: isSynced, + createdAt: createdAt, + updatedAt: updatedAt, + ); + } + + @override + List get props => [ + uuid, + collectionUuid, + title, + username, + password, + urls, + notes, + tags, + fields, + fieldOrder, + icon, + totp, + attachments, + passkey, + revision, + ]; +} diff --git a/packages/openkey_shared/lib/src/security/password_strength.dart b/packages/openkey_shared/lib/src/security/password_strength.dart new file mode 100644 index 0000000..c535bc3 --- /dev/null +++ b/packages/openkey_shared/lib/src/security/password_strength.dart @@ -0,0 +1,22 @@ +/// Estimates password strength on a normalized 0.0–1.0 scale. +/// +/// This preserves the heuristic already used by OpenKey: up to 0.5 points for +/// length (capped at 12 characters), plus 0.125 for each character class. +double passwordStrengthScore(String password) { + if (password.isEmpty) return 0; + + var score = (password.length / 12).clamp(0.0, 0.5); + if (RegExp(r'[A-Z]').hasMatch(password)) score += 0.125; + if (RegExp(r'[a-z]').hasMatch(password)) score += 0.125; + if (RegExp(r'\d').hasMatch(password)) score += 0.125; + if (RegExp(r'[^A-Za-z0-9]').hasMatch(password)) score += 0.125; + + return score.clamp(0.0, 1.0); +} + +/// Returns whether [password] is weak under the OpenKey vault heuristic. +bool isWeakPassword(String password) { + if (password.isEmpty) return false; + if (password.length < 8) return true; + return passwordStrengthScore(password) < 0.35; +} diff --git a/packages/openkey_shared/pubspec.yaml b/packages/openkey_shared/pubspec.yaml new file mode 100644 index 0000000..9afc022 --- /dev/null +++ b/packages/openkey_shared/pubspec.yaml @@ -0,0 +1,17 @@ +name: openkey_shared +description: Shared application contracts and reusable OpenKey functionality for official editions. +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.12.2 + +dependencies: + equatable: ^2.0.8 + flutter: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 diff --git a/packages/openkey_shared/test/either_test.dart b/packages/openkey_shared/test/either_test.dart new file mode 100644 index 0000000..77158c7 --- /dev/null +++ b/packages/openkey_shared/test/either_test.dart @@ -0,0 +1,24 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openkey_shared/openkey_shared.dart'; + +void main() { + test('Left exposes its value and folds to the failure branch', () { + const result = Left('error'); + + expect(result.isLeft, isTrue); + expect(result.isRight, isFalse); + expect(result.left, 'error'); + expect(result.right, isNull); + expect(result.fold((left) => left.length, (right) => right), 5); + }); + + test('Right exposes its value and folds to the success branch', () { + const result = Right(42); + + expect(result.isRight, isTrue); + expect(result.isLeft, isFalse); + expect(result.right, 42); + expect(result.left, isNull); + expect(result.fold((left) => 0, (right) => right + 1), 43); + }); +} diff --git a/packages/openkey_shared/test/feature_access_test.dart b/packages/openkey_shared/test/feature_access_test.dart new file mode 100644 index 0000000..1e21561 --- /dev/null +++ b/packages/openkey_shared/test/feature_access_test.dart @@ -0,0 +1,12 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openkey_shared/openkey_shared.dart'; + +void main() { + group('FreeEditionFeatureAccess', () { + const access = FreeEditionFeatureAccess(); + + test('does not grant the Pro-only nearby sync capability', () { + expect(access.canUse(OpenKeyFeature.nearbyDeviceSync), isFalse); + }); + }); +} diff --git a/packages/openkey_shared/test/password_strength_test.dart b/packages/openkey_shared/test/password_strength_test.dart new file mode 100644 index 0000000..59d82b5 --- /dev/null +++ b/packages/openkey_shared/test/password_strength_test.dart @@ -0,0 +1,30 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openkey_shared/openkey_shared.dart'; + +void main() { + group('passwordStrengthScore', () { + test('returns zero for an empty password', () { + expect(passwordStrengthScore(''), 0); + }); + + test('retains the existing character-class and length heuristic', () { + expect(passwordStrengthScore('abc'), closeTo(0.375, 0.000001)); + expect(passwordStrengthScore('Abcdef1!'), 1); + expect(passwordStrengthScore('Abcdefgh123!'), 1); + }); + }); + + group('isWeakPassword', () { + test('does not mark an empty value as weak', () { + expect(isWeakPassword(''), isFalse); + }); + + test('marks short passwords as weak', () { + expect(isWeakPassword('abc'), isTrue); + }); + + test('accepts a password at the existing score threshold', () { + expect(isWeakPassword('Abcdef1!'), isFalse); + }); + }); +} diff --git a/packages/openkey_shared/test/vault_entry_test.dart b/packages/openkey_shared/test/vault_entry_test.dart new file mode 100644 index 0000000..34f3aba --- /dev/null +++ b/packages/openkey_shared/test/vault_entry_test.dart @@ -0,0 +1,159 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openkey_shared/openkey_shared.dart'; + +void main() { + group('VaultEntry payload compatibility', () { + test('round-trips the complete vault entry payload', () { + final entry = VaultEntry( + uuid: 'entry-1', + collectionUuid: 'collection-1', + title: 'Example login', + username: 'user@example.test', + password: 'not-a-real-password', + urls: const ['https://example.test'], + notes: 'fixture only', + tags: const ['work', 'test'], + fields: const [ + EntryExtraField(type: 'email', value: 'user@example.test'), + EntryExtraField(type: 'phone', value: '+10000000000'), + ], + fieldOrder: const ['username', 'email', 'phone'], + icon: 'material:key', + totp: const TotpConfig( + secret: 'EXAMPLE-TOTP-SECRET', + period: 45, + digits: 8, + algorithm: 'SHA256', + ), + attachments: const [ + AttachmentMeta( + id: 'attachment-1', + name: 'fixture.txt', + size: 123, + cipher: 'encrypted-fixture', + ), + ], + passkey: const PasskeyPayload( + rpId: 'example.test', + credentialId: 'fixture-credential', + userHandle: 'fixture-user', + privateKeyCipher: 'encrypted-fixture-key', + publicKey: 'fixture-public-key', + alg: -7, + signCount: 4, + userName: 'user@example.test', + displayName: 'Example User', + ), + revision: 7, + isSynced: true, + ); + + final payload = entry.toPayload(); + expect(payload, { + 'title': 'Example login', + 'username': 'user@example.test', + 'password': 'not-a-real-password', + 'urls': ['https://example.test'], + 'notes': 'fixture only', + 'tags': ['work', 'test'], + 'fields': [ + {'type': 'email', 'value': 'user@example.test'}, + {'type': 'phone', 'value': '+10000000000'}, + ], + 'fieldOrder': ['username', 'email', 'phone'], + 'icon': 'material:key', + 'totp': { + 'secret': 'EXAMPLE-TOTP-SECRET', + 'period': 45, + 'digits': 8, + 'algorithm': 'SHA256', + }, + 'attachments': [ + { + 'id': 'attachment-1', + 'name': 'fixture.txt', + 'size': 123, + 'cipher': 'encrypted-fixture', + }, + ], + 'passkey': { + 'rpId': 'example.test', + 'credentialId': 'fixture-credential', + 'userHandle': 'fixture-user', + 'privateKeyCipher': 'encrypted-fixture-key', + 'publicKey': 'fixture-public-key', + 'alg': -7, + 'signCount': 4, + 'userName': 'user@example.test', + 'displayName': 'Example User', + }, + }); + + final restored = VaultEntry.fromPayload( + uuid: entry.uuid, + collectionUuid: entry.collectionUuid, + payload: payload, + revision: entry.revision, + isSynced: entry.isSynced, + ); + + expect(restored, entry); + expect(restored.toPayload(), payload); + expect(restored.isAutofillFillable, isTrue); + expect(restored.fieldValue('email'), 'user@example.test'); + expect(restored.fieldValue('missing'), isNull); + }); + + test('keeps legacy payload defaults when optional fields are absent', () { + final entry = VaultEntry.fromPayload( + uuid: 'legacy-entry', + payload: const { + 'title': 'Legacy login', + 'username': 'legacy-user', + 'password': 'legacy-secret', + }, + ); + + expect(entry.uuid, 'legacy-entry'); + expect(entry.title, 'Legacy login'); + expect(entry.urls, isEmpty); + expect(entry.tags, isEmpty); + expect(entry.fields, isEmpty); + expect(entry.fieldOrder, isEmpty); + expect(entry.icon, isEmpty); + expect(entry.totp, isNull); + expect(entry.attachments, isEmpty); + expect(entry.passkey, isNull); + expect(entry.revision, 1); + expect(entry.isSynced, isFalse); + expect(entry.toPayload(), { + 'title': 'Legacy login', + 'username': 'legacy-user', + 'password': 'legacy-secret', + 'urls': [], + 'notes': '', + }); + }); + + test('keeps optional metadata defaults for nested values', () { + expect( + TotpConfig.fromJson(null), + const TotpConfig(secret: ''), + ); + expect( + AttachmentMeta.fromJson(const {'id': 'a'}), + const AttachmentMeta(id: 'a', name: '', size: 0), + ); + expect( + PasskeyPayload.fromJson(const { + 'rpId': 'example.test', + 'credentialId': 'id', + }), + const PasskeyPayload( + rpId: 'example.test', + credentialId: 'id', + ), + ); + }); + }); +} diff --git a/pubspec.lock b/pubspec.lock index 82e4a36..1f6c21a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -835,6 +835,13 @@ packages: url: "https://pub.dev" source: hosted version: "9.5.0" + openkey_shared: + dependency: "direct main" + description: + path: packages/openkey_shared + relative: true + source: path + version: "0.1.0" otp: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 90b2f68..91acdcc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -9,6 +9,8 @@ environment: dependencies: flutter: sdk: flutter + openkey_shared: + path: packages/openkey_shared flutter_localizations: sdk: flutter intl: any diff --git a/test/screenshots/screenshot_pump.dart b/test/screenshots/screenshot_pump.dart index 921aee6..93a3d72 100644 --- a/test/screenshots/screenshot_pump.dart +++ b/test/screenshots/screenshot_pump.dart @@ -17,7 +17,7 @@ Widget screenshotMaterialApp({ localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: MediaQuery( - data: MediaQueryData(size: surfaceSize), + data: MediaQueryData(size: surfaceSize, disableAnimations: true), child: child, ), );