diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md new file mode 100644 index 0000000..9a8a0e1 --- /dev/null +++ b/.agents/AGENTS.md @@ -0,0 +1,148 @@ +# AGENTS.md + +This file documents how AI agents should interact with this Rust codebase for the CCC (Copious Cipher Chain) cryptography system. + +## Project Overview + +A multi-crate Rust workspace providing cryptographic primitives (AEAD, KDF, MAC, Hash, KEM) via pluggable providers (currently wolfSSL/wolfCrypt). The project targets mobile platforms (iOS, Android, macOS) and interoperates with a Dart/Flutter frontend via FFI. + +**Workspace members:** +- `crates/ccc-crypto-core` — Core types, traits, algorithm enums, registry +- `crates/ccc-crypto-wolfssl` — wolfSSL provider implementation +- `tests/conformance` — Conformance test binary with NIST/RFC vectors + +## Build and Test Commands + +### Basic commands +```sh +# Run all tests across workspace +cargo test --workspace + +# Run tests for a specific package +cargo test -p ccc-crypto-core +cargo test -p ccc-crypto-wolfssl + +# Run conformance tests (binary) +cargo run -p ccc-conformance-tests + +# Build for specific target (aliases defined in .cargo/config.toml) +cargo build-ios +cargo build-android-arm64 +cargo build-macos-arm64 +cargo build-all-apple +``` + +### Running a single test +```sh +# Run all tests matching a string pattern +cargo test --workspace + +# Example: run only KEM-related tests +cargo test --workspace kem + +# Run specific test function +cargo test --workspace test_function_name + +# Compile without running +cargo test --workspace --no-run +``` + +### Linting and formatting +```sh +# Format code (uses rustfmt from rust-toolchain.toml) +cargo fmt + +# Check for clippy warnings +cargo clippy --workspace -- -D warnings + +# Combined check +cargo fmt --check && cargo clippy --workspace -- -D warnings +``` + +## Code Style Guidelines + +### Imports and module organization +1. **Standard library first** — `use std::...` before workspace crates +2. **Workspace/crate imports second** — `use ccc_crypto_core::...` or `use crate::...` +3. **External dependencies last** — third-party crates from `[dependencies]` +4. **Group related items** — use parentheses to group multi-line imports: + ```rust + use ccc_crypto_core::{ + algorithms::{AeadAlgorithm, HashAlgorithm}, + error::CryptoError, + types::{KemKeyPair, KemEncapResult}, + }; + ``` + +### File structure and documentation +1. **Module headers** — Every `.rs` file starts with a `//!` doc comment explaining its purpose +2. **Section separators** — Use ASCII art dividers (`// ─────────────`) to separate logical sections +3. **Public APIs** — Document all public items with `///` comments; use `# Parameters`, `# Returns`, `# Errors` where applicable +4. **Algorithm constants** — When defining enum discriminants, comment the matching Dart constant value: + ```rust + /// AES-256-GCM. Dart constant `12`. + AesGcm256 = 12, + ``` + +### Naming conventions +- **Types**: PascalCase (`CryptoError`, `ProviderCapabilities`, `WolfSslProvider`) +- **Functions/methods**: snake_case (`encrypt_aead`, `derive_key`, `from_u32`) +- **Modules**: snake_case (`algorithms`, `capabilities`, `error`) +- **Constants/enum variants**: PascalCase with full names (`AesGcm256`, `MlKem768`) +- **Private items**: Prefix with underscore if needed for clarity (`_unused_var`) + +### Type system and generics +1. Prefer `Result` over `panic!` for recoverable errors +2. Use `#[repr(u32)]` on enums that cross FFI boundaries (match Dart `int` values) +3. Mark sensitive data with `zeroize::Zeroize` / `ZeroizeOnDrop`: + ```rust + #[derive(Zeroize, ZeroizeOnDrop)] + pub struct KemKeyPair { ... } + ``` +4. Use `OnceLock` for lazy-initialized singleton-like state + +### Error handling +1. **Use `thiserror`** — Define error enums with `#[derive(Error)]`: + ```rust + #[derive(Debug, Error)] + pub enum CryptoError { + #[error("unsupported algorithm: {0}")] + UnsupportedAlgorithm(String), + + #[error("authentication failed")] + AuthenticationFailed, // Do not leak details to users + } + ``` +2. **Authentication failures** — Surface only `AuthenticationFailed` to end users; never leak raw error details +3. **Internal errors** — Use `InternalError(String)` for unexpected library errors with diagnostics + +### Formatting rules +1. **Max line length**: 100 characters (rustfmt default) +2. **Brace style**: Allman/stroustrup hybrid — opening brace on same line for items, next line for blocks +3. **Single-line matches** — Keep simple match arms on one line when concise +4. **Multi-line chains** — Use `.` at start of continuation lines: + ```rust + let result = provider + .encrypt_aead(algo, key, nonce, plaintext, aad)? + .to_hex(); + ``` + +### Testing conventions +1. **Test vectors as static slices** — Define test data in `static` arrays with clear naming (`AEAD_VECS`, `KDF_VECTORS`) +2. **Cross-provider conformance** — Tests should verify identical output across different providers +3. **NIST/RFC references** — Comment the source of each vector (e.g., "RFC 8439 §2.8.2") + +### Platform-specific code +1. Use conditional compilation for platform differences: `#[cfg(target_os = "...")]` +2. Linker flags and build scripts should be in `.cargo/config.toml` or `build.rs` +3. Document target-specific behavior in module headers + +## Important Notes + +- **Dart compatibility**: All algorithm discriminant values (`#[repr(u32)]`) must match constants in `cipher_constants.dart`. Changing them requires coordinated changes across Rust and Dart codebases. +- **Wire format consistency**: Output byte layouts (e.g., `ciphertext || tag` for AEAD) must match the Dart implementation exactly for conformance tests to pass. +- **Security-sensitive data**: Always use `zeroize` types for keys, nonces, and shared secrets; never log raw cryptographic material. + +## Existing Rules + +No `.cursor/rules/`, `.cursorrules`, or `.github/copilot-instructions.md` files exist in this repository. Follow the conventions documented above. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md deleted file mode 100644 index ed45955..0000000 --- a/.github/copilot-instructions.md +++ /dev/null @@ -1,194 +0,0 @@ -# LetUsMsg Flutter App - AI Coding Agent Instructions - -**Project**: LetUsMsg (Flutter cross-platform messaging app) -**Focus**: gRPC relay-based secure messaging with local Hive persistence - -## Architecture Overview - -### Core Components -1. **Relay Communication** (`flutter_src/lib/relay/`) - - `grpc_service.dart`: gRPC client managing streaming messages from relay servers and sending messages - - Handles message sequences, acknowledgments, and connection state - - Uses `fixnum.Int64` for protobuf compatibility (common error: forgetting `import 'package:fixnum/fixnum.dart'`) - - **Key workflow**: `registerClient()` → `streamMessages()` → `_procMessage()` → `ackMessages()` - -2. **Data Layer** (`flutter_src/lib/data/`) - - Hive CE (encrypted local DB) for persistent storage - - Models: `MyselfData`, `ChannelData`, `MessageData`, `RelayPoolData`, `RelayStateData`, `CCCData` and more look at the path `flutter_src/lib/data/` - - All models use `@HiveType()` annotations; code generation required (`build_runner`) - - **Message storage**: Size-based approach (active box + archived boxes per channel) - -3. **Processing Layer** (`flutter_src/lib/proc/`) - - `proc_main.dart`: Central orchestrator - - Abstract base classes: `ProcConnAbstract`, `ProcMsgAbstract`, `NetworkSendAbstract` - - Handles cryptography, message sending, incoming stream processing - - Runs message background work via `worker_manager` isolates - -4. **State Management** (`flutter_src/lib/bloc/`) - - BLoC pattern (custom, not `flutter_bloc` package) - - `AppState`: Global singleton for `appNotify`, `conn`, `fcm`, `msgNotify`, `proc` - - `ConnectionStateUI`: Connection state per relay (connecting/registered/disconnected) - - Changes broadcast via callbacks: `StreamMsgCallback`, `StreamCloseCallback`, `StreamCountCallback` - -5. **UI Layer** (`flutter_src/lib/`) - - `main.dart`: Multi-platform entry (macOS, iOS, Android, Linux, Windows) - - Platform detection: `Platform.isMacOS`, `Platform.isIOS`, etc. - - Custom widgets in `widgetz/`; theme via `flex_color_scheme` -∏ -## Key Workflows & Patterns - -### Message Relay Flow -``` -User sends → UI callback → NetworkSendAbstract.sendMessage() - → gRPC stub.sendMessage(Message) - → Relay server → other clients receive via streamMessages() - → _procMessage() processes with sequence tracking - → _lastMsgSeq == serverSeq → ackMessages(AckRequest) - → Clear cached messages, reset _firstMsgSeq/_lastMsgSeq -``` - -### gRPC Type Handling (Critical) -- **Protobuf definitions**: `proto/letusmsg.proto` defines service `MessagingService` -- **Generated stubs**: `flutter_src/lib/gen/proto/letusmsg.pbgrpc.dart` (auto-generated) -- **Integer types**: Always use `Int64` (from `fixnum`) for protobuf `int64` fields - - Common error: `Int16(_lastMsgSeq)` → use `Int64(_lastMsgSeq)` instead - - Nullable fields: `Int64?` requires conditional: `_lastMsgSeq == -1 ? null : Int64(_lastMsgSeq)` -- **Method calls**: Use named parameters, e.g., `_stub.ackMessages(request: ackRequest, options: ...)` - -### Hive Data Generation -- All Hive models require code generation -- **Build command**: `flutter pub run build_runner build --delete-conflicting-outputs` -- Files: `*_data.g.dart` (auto-generated adapters) -- Models must have: `@HiveType()`, `@HiveField(0)` annotations -- **Storage locations**: `dataDir` (from args or default app docs dir) - -### Multi-Platform Desktop Window Management -- macOS/Windows/Linux: Use `window_manager` (see `main.dart`) -- Mobile (iOS/Android): Firebase initialization required -- Window options: Title, size (600x800 default), titlebar style, min/max dimensions - -## Common Pitfalls & Solutions - -### Notification Tap Handling (Critical for Mobile) -The app handles notifications from **three sources**: -1. **FCM (Firebase Cloud Messaging)** - Remote push notifications (`relay/fcm.dart`) -2. **flutter_local_notifications** - Local notifications (`notifications/local_notification.dart`) -3. **URI Deep Links** - Custom scheme `com.letusmsg://` via `app_links` package - -**Three App States for Notification Taps:** -| State | FCM Handler | Local Notification Handler | URI Deep Link | -|-------|-------------|---------------------------|---------------| -| **Terminated (cold start)** | `getInitialMessage()` | `getNotificationAppLaunchDetails()` | `getInitialLink()` | -| **Background (warm start)** | `onMessageOpenedApp` stream | `onDidReceiveNotificationResponse` callback | `uriLinkStream` | -| **Foreground (hot)** | `onMessage` stream | `onDidReceiveNotificationResponse` callback | `uriLinkStream` | - -**Key Pattern**: Always check for "initial message/link" on app startup because callbacks aren't registered when app is terminated. Store in `MyApp.pendingDeepLink` and process after splash screen via `MyApp.processPendingDeepLink()`. - -**Deep Link Handler**: All notification taps route through `utilz/deep_link_handler.dart`: -- `DeepLinkArgs.fromUri()` - Parse URI deep links -- `DeepLinkArgs.fromFcmData()` - Parse FCM notification data payload -- `DeepLinkArgs.fromPayload()` - Parse local notification payload string - -**FCM Data Payload Structure** (server sends this): -```json -{ - "data": { - "channel": "abc123-channel-uuid" - } -} -``` - -**URI Deep Link Format**: -- Open channel: `com.letusmsg://chat?channel=abc123` -- Accept invite: `com.letusmsg://chat?invite-code=89ae57b9-4435-4956-b735-37bd5af00a5e` - -**Flow for Cold Start from Notification**: -1. User taps notification → App launches -2. `FCM.init()` calls `getInitialMessage()` → stores in `initialMessageData` if callback not ready -3. `_setupNotificationHandlers()` checks `initialMessageData` → sets `MyApp.pendingDeepLink` -4. Splash finishes → `MyApp.processPendingDeepLink()` → `DeepLinkHandler.handle()` → navigate to channel - -## Build & Test Commands - -**Manual Flutter commands**: -```bash -flutter pub get # Install deps -flutter pub run build_runner build --delete-conflicting-outputs # Hive codegen -flutter run -v # Run with logs -flutter test # Run unit tests (test/) -``` - -## Project-Specific Dependencies - -- **gRPC/Protobuf**: `grpc: ^4.1.0`, `fixnum: ^1.1.1` (strict version to avoid dependency issues) -- **State Management**: `provider: ^6.1.2` (lightweight, not flutter_bloc) -- **Local Storage**: `hive_ce: ^2.10.1` (encrypted), `path_provider: ^2.0.15` -- **Async**: `worker_manager: ^7.2.6` (for background isolates) -- **Firebase**: `firebase_core`, `firebase_messaging` (mobile only, see `main.dart`) -- **Notifications**: `flutter_local_notifications` (local notifications with cold start support) -- **Deep Linking**: `app_links: ^6.4.0` (URI scheme and universal links) -- **UI**: `flex_color_scheme` (dynamic theming), `flutter_svg` (SVG support) -- **Custom packages** (git-based): - - `lum_loading_animations` (internal) - - `linkify_text` (forked, improved regex) - -## File Organization - -``` -flutter_src/ -├── lib/ -│ ├── main.dart # Entry point, platform detection -│ ├── app.dart # App widget -│ ├── bloc/ # State management -│ │ ├── app_state.dart # Global singleton -│ │ ├── conn_state_UI.dart # Connection per relay -│ │ └── ... -│ ├── data/ # Hive models & persistence -│ │ ├── myself_data.dart -│ │ ├── my_hive.dart # Hive box manager -│ │ └── ... -│ ├── notifications/ # Push & local notifications -│ │ ├── local_notification.dart # flutter_local_notifications wrapper -│ │ └── permissions.dart # Notification permission handling -│ ├── proc/ # Business logic & processing -│ │ ├── proc_main.dart -│ │ └── *_abstract.dart # Abstract interfaces -│ ├── relay/ # gRPC communication -│ │ ├── grpc_service.dart # Main gRPC client -│ │ └── fcm.dart # Firebase Cloud Messaging -│ ├── utilz/ # Utilities -│ │ ├── deep_link_handler.dart # Deep link & notification routing -│ │ └── Llog.dart # Logging configuration -│ ├── widgetz/ # UI widgets -│ └── ... -├── pubspec.yaml # Dependencies -└── ... -proto/ -├── letusmsg.proto # Protobuf definitions -``` - -## Next Steps for Contributors -- **First-time setup**: Run `flutter pub get` and `flutter pub run build_runner build --delete-conflicting-outputs` -- **Understand gRPC service**: Read `relay/grpc_service.dart` (callbacks, state machine) -- **Understand meessage flow**: `proc/proc_bg_msg.dart` is the message processing engine -- **Hive persistence**: Review `data/my_hive.dart` and size-based message storage in `new_message_storage_architecture.md` -- **Adding features**: Use abstract base classes in `proc/` and follow BLoC pattern in `bloc/` -- **Testing**: Add tests to `test/` and run `flutter test` - -## Notes -- **Logging**: Uses `logger` package; configure in `utilz/Llog.dart` -- **Crypto**: Phase 1 implemented via `cryptography: ^2.7.0`; see `proc/crypt_abstract.dart` -- **CCC** (Copius Cipher Chain): Internal message protocol; see `data/ccc_data.dart` - -## Instructions for AI Coding Agent -- Follow the established architecture and coding patterns. -- his project is using dart lang and flutter framework. you are an elite coder who knows the dart lang design patterns and the flutter design patterns that are the most recent and popular, and you apply those with pricision, focusing on an amazing user experience, focusing on responsive design (because this app will run on mobile phones and desktop) -- make sure to follow the code and design patterns for this project, that includes file names, notifications, and popups and confirmation popups; there is an app constants and app theme constants that should be used and provided more details of the app design; do your research; -- this is the worlds most secure messaging app. the app is design so that the main isolate is dedicated to the UI and there is a background isolate that handles a lot of IO for the app, for example local storage with hive db, networking with grpc, and encryption. -- prioritize efficiency and clean code: avoid duplicate logic/UI; extract reusable widgets/helpers for repeated behavior so there is one place to maintain changes. -- DO NOT remove any existing features! you can ask me questions for more clarity on your solutions and fixes. -- please ask me any questions and share you design before changing code -- if you create documents use .rst format and name the files in lowercase -- if you create code files, follow the existing naming patterns and file organization -- if you create new features, make sure to add tests for them in the test/ directory and follow the existing testing patterns -- if you create new classes and methods(more than 5 lines of code) , make sure to add doc comments and follow the existing code style and patterns diff --git a/.gitignore b/.gitignore index 177e096..402ae18 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # J3G +.android-toolchain-bin/ build/ tmp/