From b2839e163368ee0de5a83d9588aa68076964a6fc Mon Sep 17 00:00:00 2001 From: Justin Hernandez Date: Tue, 12 Aug 2025 16:39:15 -0700 Subject: [PATCH] Chore: improve ai context (#883) * add gigamind context * updates * update ai context * doc updates * add migration context * docs: refine commit checks and mobile app instructions (#884) * docs: refine commit checks and add mobile app guidelines * cr feedback * quality updates * format md file * updates * future proof tests --- .cursor/rules/compliance-verification.mdc | 118 +++++++ .cursor/rules/cryptographic-circuits.mdc | 53 ++++ .cursor/rules/data-models.mdc | 65 ++++ .cursor/rules/identity-verification-flow.mdc | 61 ++++ .cursor/rules/mobile-sdk-migration.mdc | 307 +++++++++++++++++++ .cursorignore | 4 +- .cursorrules | 210 +++++++++++++ .giga/specifications.json | 27 ++ AGENTS.md | 78 ++++- README.md | 10 + app/AGENTS.md | 97 ++++++ docs/development-patterns.md | 206 +++++++++++++ docs/nfc-implementation.md | 273 +++++++++++++++++ docs/testing-guide.md | 272 ++++++++++++++++ noir/AGENTS.md | 64 ++++ packages/mobile-sdk-alpha/AGENTS.md | 75 +++++ 16 files changed, 1916 insertions(+), 4 deletions(-) create mode 100644 .cursor/rules/compliance-verification.mdc create mode 100644 .cursor/rules/cryptographic-circuits.mdc create mode 100644 .cursor/rules/data-models.mdc create mode 100644 .cursor/rules/identity-verification-flow.mdc create mode 100644 .cursor/rules/mobile-sdk-migration.mdc create mode 100644 .cursorrules create mode 100644 .giga/specifications.json create mode 100644 app/AGENTS.md create mode 100644 docs/development-patterns.md create mode 100644 docs/nfc-implementation.md create mode 100644 docs/testing-guide.md diff --git a/.cursor/rules/compliance-verification.mdc b/.cursor/rules/compliance-verification.mdc new file mode 100644 index 000000000..9932014af --- /dev/null +++ b/.cursor/rules/compliance-verification.mdc @@ -0,0 +1,118 @@ +--- +description: Specification for analyzing compliance verification systems including OFAC checks, age verification, and forbidden country validation +version: 1.0.0 +status: draft +owners: + - team: compliance-platform + - team: mobile-identity +lastUpdated: 2025-01-12 +specId: compliance-verification +importanceScore: 95 +importanceJustification: Direct implementation of critical regulatory compliance requirements with multiple verification layers and sophisticated identity validation. +contextUsageNote: If this file is used to add in-context notes, include a single italicized line stating what specific information was used from this file in sentence case. +--- + +# Compliance Verification System Specification + +## 1. Multi-Factor Compliance Verification + +- OFAC (Office of Foreign Assets Control) checks across three dimensions: + * Passport number verification + * Name + Date of Birth verification + * Name + Year of Birth verification +- Age verification with "olderThan" checks and day-level granularity +- Forbidden countries validation using efficient packed lists +- Timestamp-based verification with 24-hour window validation + +### Matching and Normalization Requirements + +- **Names MUST be normalized** prior to matching (case-folding, Unicode NFKC, diacritics removal) and compared using a fuzzy algorithm with a documented threshold (e.g., Jaro–Winkler >= 0.92). Record the algorithm and threshold in circuit public inputs. +- **Date inputs MUST be ISO 8601** (YYYY-MM-DD). For year-of-birth checks, explicitly state whether defaulting to Jan-01 is permitted or whether circuits encode year-only comparisons. +- **Passport numbers MUST be normalized** for whitespace and punctuation and validated against country-specific formats where available. + +### Time and Replay Control + +- All time comparisons MUST use UTC. Define an allowed clock drift (e.g., ±5 minutes) and reject proofs outside the 24-hour window adjusted by drift. +- The timestamp MUST be bound into the proof signature/statement to prevent replay. +- For mobile clients, avoid trusting device wall-clock alone; obtain a trusted time anchor (e.g., server-signed time token or chain block timestamp) and include it in the proof. + +### Privacy and PII Handling + +- No raw PII (names, DoB, passport numbers) may leave the device. PII MUST be committed via domain-separated hashes (e.g., Poseidon("ofac-v1" || value) with per-issuer salt). +- All on-chain data MUST remain non-linkable to the underlying identity; only nullifiers/commitments are published. + +### Forbidden Countries "Packed List" + +- Define the data structure (bitset vs Bloom filter). If Bloom filter is used, specify acceptable false positive rate (e.g., ≤ 1e-6) and version the filter seed. +- Distribution MUST be integrity-protected (JWS/JWT or Merkle root) with key rotation and a KID. Specify update cadence and cache TTL. + +## 2. Document Validation Architecture + +- Enforces date validation within specific time windows +- Validates forbidden countries against predefined restricted lists +- Implements age requirements through date comparison +- Manages multiple verification circuits based on signature types + +### Circuit Catalog and Versioning + +- Maintain a registry of circuit IDs, semantic versions, and public input schemas. Clients fetch the active set via a signed manifest. +- Define an upgrade policy (grace period, deprecation windows) and backward-compatibility expectations. + +### Mobile Proof Generation Constraints + +- Provide target proof generation limits for RN clients (e.g., <60s on mid-tier devices, <300MB peak memory). +- Define a fallback to a remote prover that never receives raw PII/witness; only receives commitments and obtains a zero-knowledge witness via on-device secure enclave or chunked witness encryption. +- Clearly separate on-device vs server responsibilities to minimize battery impact and avoid UI jank (background task, progress events). + +## 3. Verification Rules Engine + +- Custom document verification workflow combining multiple proof types +- Parallel verification paths for different identity document types +- Sequential verification steps through commitment registration +- Integration with external compliance data sources + +### External Data Source Integration + +- Specify SLAs (latency, availability) and client-side retry/backoff policy. All calls MUST be idempotent and resumable. +- Implement signed data snapshots with ETag/versioning for offline-first behavior; cache with explicit TTLs and verify signatures before use. +- Do not transmit any raw PII to external providers; only use hashed/committed forms compatible with the circuits. +- Define deterministic error codes for user feedback and analytics without leaking sensitive data. + +## 4. Identity Registry Management + +- Maintains Merkle trees for identity commitments and DSC keys +- Implements OFAC compliance checks with multiple verification roots +- Manages nullifier tracking to prevent duplicate registrations +- Handles CSCA root verification for document signing authority + +### Registry Parameters + +- For each Merkle tree, define tree height, hash function (e.g., Poseidon params), and root rotation cadence. Publish active roots and deprecation windows on-chain. +- Specify chain IDs and contract addresses for each environment (dev/test/prod) and the required finality before roots are considered valid. +- Nullifiers MUST be domain-separated by purpose (e.g., "register", "kyc-check") to prevent unintended linkability across workflows. +- Define revocation list handling (CSCA/DSC CRLs), update cadence, and signature verification process. Cache with signed manifests and KID-based key rotation. + +## 5. Implementation Guidelines + +### Circuit Versioning Strategy + +- Use semantic versioning (MAJOR.MINOR.PATCH) for all circuits +- MAJOR version changes require new circuit deployment and client migration +- MINOR version changes maintain backward compatibility +- PATCH version changes are bug fixes only + +### Error Handling and Recovery + +- Implement graceful degradation when external services are unavailable +- Provide clear error messages for users without exposing sensitive data +- Log non-identifying metadata for debugging and analytics +- Implement retry mechanisms with exponential backoff + +### Security Considerations + +- All cryptographic operations must use approved algorithms and key sizes +- Implement proper key management and rotation procedures +- Ensure secure random number generation for all cryptographic operations +- Regular security audits and penetration testing + +$END$ diff --git a/.cursor/rules/cryptographic-circuits.mdc b/.cursor/rules/cryptographic-circuits.mdc new file mode 100644 index 000000000..7ab17aba8 --- /dev/null +++ b/.cursor/rules/cryptographic-circuits.mdc @@ -0,0 +1,53 @@ +--- +description: Technical documentation of the zero-knowledge proof circuits, including register circuits, DSC proofs, and disclosure proofs with their validation mechanisms +version: 1.0.0 +status: draft +owners: + - team: cryptography + - team: mobile-identity +lastUpdated: 2025-01-12 +specId: cryptographic-circuits +importanceScore: 85 +importanceJustification: Core cryptographic implementation specification for zero-knowledge proofs and circuit validation. +contextUsageNote: If this file is used to add in-context notes, include a single italicized line stating what specific information was used from this file in sentence case. +--- + +# Cryptographic Circuits Specification + +## 1. Register Circuits + +### Identity Commitment Generation +- Poseidon hash-based commitment scheme +- Domain separation for different commitment types +- Nullifier generation for duplicate prevention + +### Circuit Parameters +- Field size and security parameters +- Hash function specifications +- Public input validation rules + +## 2. DSC Proofs + +### Document Signer Certificate Validation +- Certificate chain verification +- Signature algorithm support (RSA, ECDSA) +- Revocation list checking + +### Proof Generation Constraints +- Memory and computation limits +- Deterministic randomness requirements +- Proof size optimization + +## 3. Disclosure Proofs + +### Selective Attribute Revelation +- Merkle-based attribute verification +- Privacy-preserving age verification +- Granular field disclosure + +### Circuit Optimization +- Efficient hash function usage +- Minimal public input requirements +- Fast verification algorithms + +$END$ diff --git a/.cursor/rules/data-models.mdc b/.cursor/rules/data-models.mdc new file mode 100644 index 000000000..dda1ade4f --- /dev/null +++ b/.cursor/rules/data-models.mdc @@ -0,0 +1,65 @@ +--- +description: Documentation of core data structures including identity commitments, DSC key commitments, nullifier tracking, and verification configurations +version: 1.0.0 +status: draft +owners: + - team: mobile-identity + - team: backend-api +lastUpdated: 2025-01-12 +specId: data-models +importanceScore: 80 +importanceJustification: Core data structure definitions that ensure consistency across the identity verification system. +contextUsageNote: If this file is used to add in-context notes, include a single italicized line stating what specific information was used from this file in sentence case. +--- + +# Data Models Specification + +## 1. Identity Commitments + +### Commitment Structure +- Poseidon hash of identity data +- Domain separation for different commitment types +- Timestamp and version information + +### Commitment Types +- Passport identity commitments +- EU ID card commitments +- Cross-chain commitment linking + +## 2. DSC Key Commitments + +### Key Commitment Format +- Public key hash with domain separation +- Certificate chain validation data +- Revocation status tracking + +### Key Management +- Key rotation procedures +- Backup and recovery mechanisms +- Security parameter specifications + +## 3. Nullifier Tracking + +### Nullifier Generation +- Domain-separated nullifier creation +- Duplicate prevention mechanisms +- Cross-chain nullifier validation + +### Nullifier Storage +- Efficient storage and retrieval +- Privacy-preserving nullifier management +- Audit trail maintenance + +## 4. Verification Configurations + +### Configuration Parameters +- Circuit version specifications +- Verification threshold settings +- Compliance rule configurations + +### Configuration Management +- Version control and updates +- Environment-specific configurations +- Security parameter management + +$END$ diff --git a/.cursor/rules/identity-verification-flow.mdc b/.cursor/rules/identity-verification-flow.mdc new file mode 100644 index 000000000..37369f5de --- /dev/null +++ b/.cursor/rules/identity-verification-flow.mdc @@ -0,0 +1,61 @@ +--- +description: Detailed documentation of the multi-step identity verification process, including passport and EU ID card verification paths, proof verification pipeline, and attestation workflows +version: 1.0.0 +status: draft +owners: + - team: mobile-identity + - team: compliance-platform +lastUpdated: 2025-01-12 +specId: identity-verification-flow +importanceScore: 90 +importanceJustification: Core workflow specification for the identity verification process with multi-step attestation and proof generation. +contextUsageNote: If this file is used to add in-context notes, include a single italicized line stating what specific information was used from this file in sentence case. +--- + +# Identity Verification Flow Specification + +## 1. Multi-Step Verification Process + +### Passport Verification Path +- NFC chip data extraction and validation +- Document Signer Certificate (DSC) verification +- Zero-knowledge proof generation for privacy +- Multi-stage attestation verification +- Cross-chain verification support + +### EU ID Card Verification Path +- Similar process to passport verification +- Additional EU-specific compliance checks +- Regional document format validation + +## 2. Proof Verification Pipeline + +### Register Circuit Verification +- Identity commitment generation and validation +- Nullifier creation to prevent duplicate registrations +- Merkle tree inclusion proofs for privacy + +### DSC Proof Verification +- Document Signer Certificate validation +- Cryptographic signature verification +- Certificate chain validation + +### Disclosure Proof Verification +- Selective attribute revelation +- Privacy-preserving age verification +- Granular document field disclosure + +## 3. Attestation Workflows + +### User Identifier Verification +- User identifier verification through double-hashing with domain separation: + H2 = Hash("IDH" || Hash("IDH" || userIdentifier)) +- Attestation storage with nullifier tracking +- Support for cross-chain verification results + +### Verification Result Management +- Secure storage of verification results +- Privacy-preserving result sharing +- Audit trail maintenance + +$END$ diff --git a/.cursor/rules/mobile-sdk-migration.mdc b/.cursor/rules/mobile-sdk-migration.mdc new file mode 100644 index 000000000..964a81626 --- /dev/null +++ b/.cursor/rules/mobile-sdk-migration.mdc @@ -0,0 +1,307 @@ +--- +description: Comprehensive migration strategy and testing-first approach for porting identity verification logic from app to mobile-sdk-alpha package +version: 1.0.0 +status: active +owners: + - team: mobile-identity + - team: sdk-platform +lastUpdated: 2025-01-12 +specId: mobile-sdk-migration +importanceScore: 90 +importanceJustification: Critical framework for systematically migrating core identity verification functionality to a partner-consumable SDK while maintaining quality and testing coverage. +contextUsageNote: If this file is used to add in-context notes, include a single italicized line stating what specific information was used from this file in sentence case. +--- + +# Mobile SDK Migration Context + +## Migration Strategy Overview + +### Testing-First Approach +- **Create tests BEFORE migrating logic** to verify functionality works correctly +- **Dual testing environment**: Jest (app) + Vitest (mobile-sdk-alpha) +- **Validation commands**: `yarn test:build` in both app and mobile-sdk-alpha directories +- **Incremental migration**: One checklist item at a time with thorough validation + +### Test Environment Differences + +#### App (Jest) +- **Location**: `app/` directory +- **Config**: `jest.config.cjs` with React Native preset +- **Setup**: `jest.setup.js` with comprehensive mocks +- **Module mapping**: `@/` → `src/`, `@tests/` → `tests/src/` +- **Test command**: `yarn test:build` (builds deps + types + bundle analysis + tests) + +#### Mobile SDK Alpha (Vitest) +- **Location**: `packages/mobile-sdk-alpha/` directory +- **Config**: `vitest.config.ts` with Node environment +- **Setup**: `tests/setup.ts` with console noise suppression +- **Test command**: `yarn test:build` (build + test + types + lint) + +### Migration Validation Workflow + +1. **Pre-migration**: Create comprehensive tests in mobile-sdk-alpha for target functionality +2. **Migration**: Port logic from app to mobile-sdk-alpha +3. **Validation**: Run `yarn test:build` in both directories +4. **Integration**: Update app to consume mobile-sdk-alpha +5. **Final validation**: Ensure app tests pass with new SDK consumption + +## Migration Checklist Items + +### 1. Processing Helpers (MRZ & NFC) +**Current Location**: `app/src/utils/` (MRZ utilities, NFC scanner) +**Target Location**: `packages/mobile-sdk-alpha/src/processing/` +**Testing Strategy**: +- Create MRZ parsing tests with sample passport data +- Create NFC response parser tests with mock NFC data +- Test cross-platform compatibility (React Native vs Web) + +### 2. Validation Module +**Current Location**: `app/src/utils/` (document validation logic) +**Target Location**: `packages/mobile-sdk-alpha/src/validation/` +**Testing Strategy**: +- Unit tests for each validation rule +- Test with valid/invalid document data +- Test edge cases and error conditions + +### 3. Proof Input Generation +**Current Location**: `app/src/utils/proving/` +**Target Location**: `packages/mobile-sdk-alpha/src/proving/` +**Testing Strategy**: +- Test register input generation with mock data +- Test disclose input generation with various scenarios +- Validate TEE input format compliance + +### 4. Crypto Adapters +**Current Location**: `app/src/utils/` (crypto utilities) +**Target Location**: `packages/mobile-sdk-alpha/src/crypto/` +**Testing Strategy**: +- Test WebCrypto vs @noble/* fallback detection +- Test CSPRNG generation across platforms +- Test timing-safe comparison functions +- Parity tests between implementations + +### 5. TEE Session Management +**Current Location**: `app/src/utils/` (WebSocket handling) +**Target Location**: `packages/mobile-sdk-alpha/src/tee/` +**Testing Strategy**: +- Test WebSocket wrapper with mock server +- Test abort, timeout, and progress events +- Test connection lifecycle management + +### 6. Attestation Verification +**Current Location**: `app/src/utils/` (certificate validation) +**Target Location**: `packages/mobile-sdk-alpha/src/attestation/` +**Testing Strategy**: +- Test PCR0 validation with sample data +- Test public key extraction +- Test certificate chain validation + +### 7. Protocol Synchronization +**Current Location**: `app/src/utils/` (protocol tree handling) +**Target Location**: `packages/mobile-sdk-alpha/src/protocol/` +**Testing Strategy**: +- Test protocol tree fetching with pagination +- Test TTL cache behavior +- Test rate limiting and exponential backoff +- Test memory bounds enforcement + +### 8. Artifact Management +**Current Location**: `app/src/utils/` (manifest handling) +**Target Location**: `packages/mobile-sdk-alpha/src/artifacts/` +**Testing Strategy**: +- Test manifest schema validation +- Test CDN download with caching +- Test signature verification +- Test storage adapter integration + +### 9. Scanning Adapters & NFC Lifecycle +**Current Location**: `app/src/utils/nfcScanner.ts` +**Target Location**: `packages/mobile-sdk-alpha/src/adapters/` +**Testing Strategy**: +- Test cross-platform scanner interfaces +- Test React Native MRZ and NFC adapters +- Test screen-on hooks integration +- Test flow chaining (MRZ → NFC) + +### 10. Sample Applications +**Target Location**: `packages/mobile-sdk-alpha/examples/` +**Testing Strategy**: +- Create React Native demo with core flows +- Create web demo with browser adapters +- Test iOS `OpenPassport` URL scheme + +### 11. SDK Integration into App +**Migration Strategy**: +- Replace existing modules with SDK imports +- Update import paths throughout app +- Validate all existing functionality works +- Ensure no regression in app behavior + +### 12. In-SDK Lightweight Demo +**Target Location**: `packages/mobile-sdk-alpha/demo/` +**Testing Strategy**: +- Embedded React Native demo +- Test theming hooks integration +- Validate build and run instructions + +### 13. Partner Feedback Integration +**Enhancements**: +- OAuth-style branding customization +- Callback hooks for async operations +- Expanded document coverage +- Bundle size optimization + +## Testing Best Practices + +### Test Data Management +- **Mock data**: Create comprehensive test fixtures for each module +- **Sensitive data**: Never log PII, credentials, or private keys +- **Redaction**: Use consistent patterns for sensitive field masking +- **Environment flags**: Use `DEBUG_SECRETS_TOKEN` for debug-level secrets + +### Cross-Platform Testing +- **React Native**: Test on both iOS and Android simulators +- **Web**: Test with browser adapters +- **Platform detection**: Test platform-specific code paths +- **Native modules**: Mock native dependencies appropriately + +### Performance Testing +- **Bundle size**: Monitor SDK bundle size impact +- **Memory usage**: Test memory bounds for large operations +- **Network efficiency**: Test rate limiting and caching +- **Startup time**: Measure SDK initialization impact + +### Integration Testing +- **End-to-end flows**: Test complete user journeys +- **Error handling**: Test graceful degradation +- **Recovery mechanisms**: Test error recovery and retry logic +- **Backward compatibility**: Ensure existing app functionality works + +## Migration Validation Checklist + +### Pre-Migration +- [ ] Create comprehensive test suite in mobile-sdk-alpha +- [ ] Define test fixtures and mock data +- [ ] Set up cross-platform testing environment +- [ ] Document current functionality and edge cases + +### During Migration +- [ ] Port logic incrementally (one checklist item at a time) +- [ ] Run `yarn test:build` in mobile-sdk-alpha after each item +- [ ] Validate functionality matches original implementation +- [ ] Update documentation and type definitions + +### Post-Migration +- [ ] Update app to consume mobile-sdk-alpha +- [ ] Run `yarn test:build` in app directory +- [ ] Validate all existing app tests pass +- [ ] Test integration with existing app functionality +- [ ] Performance validation and bundle size analysis + +### Final Validation +- [ ] End-to-end testing of complete flows +- [ ] Cross-platform compatibility verification +- [ ] Partner SDK consumption testing +- [ ] Documentation and example updates +- [ ] Release preparation and versioning + +## Common Migration Patterns + +### Module Structure +```typescript +// Before (app/src/utils/module.ts) +export function processData(data: InputType): OutputType { + // Implementation +} + +// After (packages/mobile-sdk-alpha/src/module/index.ts) +export function processData(data: InputType): OutputType { + // Same implementation with enhanced error handling +} + +// Test (packages/mobile-sdk-alpha/tests/module.test.ts) +describe('processData', () => { + it('should process valid data correctly', () => { + // Test implementation + }); +}); +``` + +### Adapter Pattern +```typescript +// Cross-platform adapter interface +export interface ScannerAdapter { + scan(): Promise; + isSupported(): boolean; +} + +// Platform-specific implementations +export class ReactNativeScannerAdapter implements ScannerAdapter { + // React Native implementation +} + +export class WebScannerAdapter implements ScannerAdapter { + // Web implementation +} +``` + +### Error Handling +```typescript +// Consistent error types across SDK +export class SDKError extends Error { + constructor( + message: string, + public code: string, + public details?: Record + ) { + super(message); + this.name = 'SDKError'; + } +} +``` + +## Security & Privacy Considerations + +### Data Protection +- **Sensitive data**: Never log PII, credentials, or private keys in production +- **Secure storage**: Use appropriate storage mechanisms for sensitive data +- **Cleanup**: Properly clean up sensitive data after use +- **Validation**: Validate all inputs and outputs for security + +### Privacy Features +- **Zero-knowledge proofs**: Ensure privacy-preserving verification +- **Selective disclosure**: Support minimal necessary attribute revelation +- **Identity commitments**: Maintain privacy of identity data +- **Audit trails**: Log access to sensitive operations without exposing data + +## Performance Optimization + +### Bundle Size +- **Tree shaking**: Ensure all exports support tree shaking +- **Code splitting**: Split large modules into smaller chunks +- **Dependency analysis**: Monitor and optimize dependencies +- **Bundle analysis**: Regular bundle size monitoring + +### Runtime Performance +- **Lazy loading**: Load modules only when needed +- **Caching**: Implement appropriate caching strategies +- **Memory management**: Prevent memory leaks in long-running operations +- **Async operations**: Use proper async patterns for non-blocking operations + +## Partner SDK Requirements + +### API Design +- **Consistent interfaces**: Maintain consistent API patterns +- **Type safety**: Provide comprehensive TypeScript definitions +- **Error handling**: Clear error messages and error codes +- **Documentation**: Comprehensive API documentation + +### Integration Support +- **Branding**: Support for partner branding and theming +- **Callbacks**: Async operation callbacks for integration +- **Configuration**: Flexible configuration options +- **Examples**: Comprehensive integration examples + +This context provides a comprehensive framework for executing the migration checklist with a testing-first approach, ensuring quality and reliability throughout the migration process. + +$END$ diff --git a/.cursorignore b/.cursorignore index 4f4289339..9264d2e7c 100644 --- a/.cursorignore +++ b/.cursorignore @@ -161,7 +161,9 @@ app/android/android-passport-reader/app/src/main/assets/tessdata/ *.swp *.swo .DS_Store -.cursor/ +.cursor/cache/ +.cursor/logs/ +.cursor/temp/ # ======================================== # Documentation Build diff --git a/.cursorrules b/.cursorrules new file mode 100644 index 000000000..d0cb43a51 --- /dev/null +++ b/.cursorrules @@ -0,0 +1,210 @@ + +# main-overview + +## Development Guidelines + +- Only modify code directly relevant to the specific request. Avoid changing unrelated functionality. +- Never replace code with placeholders like `# ... rest of the processing ...`. Always include complete code. +- Break problems into smaller steps. Think through each step separately before implementing. +- Always provide a complete PLAN with REASONING based on evidence from code and logs before making changes. +- Explain your OBSERVATIONS clearly, then provide REASONING to identify the exact issue. Add console logs when needed to gather more information. +- **NEVER log sensitive data** including PII (names, DOB, passport numbers, addresses), credentials, tokens, API keys, private keys, or session identifiers. +- **ALWAYS redact/mask sensitive fields** in logs using consistent patterns (e.g., `***-***-1234` for passport numbers, `J*** D***` for names). +- **Use secure centralized logging** with access controls, encryption in transit/at rest, and audit trails for log access. +- **Debug-level secrets require tokenized environment flags** (e.g., `DEBUG_SECRETS_TOKEN=abc123`) with approval workflow and limited lifetime (max 24 hours). +- **Implement periodic log review and retention policies** with automated cleanup of sensitive data and compliance with data protection regulations. + + +# Identity Verification System Architecture + +## Core Components + +1. Identity Verification Hub +- Manages multi-step verification process for passports and EU ID cards +- Handles document attestation through zero-knowledge proofs +- Implements verification paths: E-PASSPORT and EU_ID_CARD +- File: contracts/contracts/IdentityVerificationHubImplV2.sol + +2. Document Verification Processing +- Validates international travel documents using ICAO standards +- Processes Document Signer Certificate (DSC) verification +- Handles multiple cryptographic signature algorithms +- Location: noir/crates/dg1/src/dg1/dg1.nr + +3. OFAC Compliance System +- Three-tier verification approach: + * Name-based sanctions screening + * Name + DOB verification + * Passport number validation +- Merkle tree-based sanctions list verification +- Files: noir/crates/dg1/src/ofac/*.nr + +4. Identity Registry Management +- Maintains separate registries for passports and ID cards +- Handles DSC key commitment registration +- Implements nullifier tracking for duplicate prevention +- File: contracts/contracts/registry/IdentityRegistryImplV1.sol + +## Core Workflows + +1. Document Verification Flow +- NFC chip data extraction and validation +- Zero-knowledge proof generation for privacy +- Multi-stage attestation verification +- Cross-chain verification support + +2. Compliance Verification +- OFAC screening integration +- Age verification without revealing DOB +- Country restriction validation +- Forbidden country checking + +3. Attribute Disclosure Control +- Selective revelation of identity attributes +- Privacy-preserving age verification +- Granular document field disclosure +- Merkle-based attribute verification + +## Business Rules + +1. Document Validation +- Multiple proof types required (Register, DSC, VC) +- Time-based verification with day granularity +- Double-spend prevention through nullifiers + +2. Compliance Requirements +- OFAC validation with multiple check levels +- Age threshold verification +- Country-based restrictions +- Document expiration validation + +3. Privacy Controls +- Minimum necessary attribute disclosure +- Zero-knowledge proof requirements +- Selective attribute revelation +- Identity commitment privacy + +$END$ + +# Self App Development Rules + +## Project Overview +This is a React Native identity verification app with NFC passport reading, zero-knowledge proofs, and smart contracts. The app handles passport/ID verification, OFAC compliance, and privacy-preserving identity attestations. + +## Development Patterns + +### React Native Architecture +- Uses `@react-navigation/native` with `createStaticNavigation` for type-safe navigation +- Platform-specific handling: `Platform.OS === 'ios' ? 'iOS' : 'Android'` +- Native module initialization with `initializeNativeModules()` before any native operations +- Lazy loading for screens using `React.lazy()` + +### Navigation Patterns +- Screens organized by feature modules (passport, home, settings, etc.) +- Custom modal system with `useModal` hook and callback registry +- Haptic feedback integration with `useHapticNavigation` +- Platform-specific initial routes: web uses 'Home', mobile uses 'Splash' + +### State Management +- Zustand for global state management +- Custom hooks for complex state (`useModal`, `useHapticNavigation`) +- AsyncStorage for simple data, SQLite for complex data, Keychain for sensitive data + +## Testing Conventions + +### Jest Setup +- Comprehensive mocks in `jest.setup.js` for all native modules +- Module mapping: `@/` → `src/`, `@tests/` → `tests/src/` +- Mock patterns for Firebase, Keychain, NFC, Analytics, and third-party modules + +### Testing Patterns +- Use `renderHook` for custom hook testing +- Mock console.error to avoid test output clutter +- Test error boundaries and recovery mechanisms +- E2E testing with Maestro for platform-specific flows + +### Database Testing +- SQLite operations mocked with `executeSql` method +- Test utilities in `tests/__setup__/databaseMocks.ts` +- Mock database instance for testing + +## NFC Implementation + +### Cross-Platform Architecture +- iOS: Custom PassportReader Swift module +- Android: Custom RNPassportReaderModule Kotlin implementation +- Unified JavaScript interface with platform detection + +### Authentication Methods +- MRZ Key: Derived from passport number, DOB, and expiry date +- CAN (Card Access Number): 6-digit number for PACE authentication +- PACE: Password Authenticated Connection Establishment +- BAC fallback when PACE fails + +### Error Handling +- Multiple BAC attempts with delays +- Graceful degradation from PACE to BAC +- Real-time status updates and haptic feedback +- Comprehensive error boundaries + +## Code Organization + +### File Structure +- Feature-based organization in `src/` +- Shared utilities in `@/utils` +- Type definitions in `@/types` +- Platform-specific code in `native/` directories +- Tests mirror source structure in `tests/src/` + +### Import Patterns +- Use `@/` alias for src imports +- Use `@tests/` alias for test imports +- Platform-specific imports with conditional rendering + +## Build & Deployment + +### Scripts +- `yarn ios` / `yarn android` for platform-specific builds +- `yarn test` for Jest testing +- `yarn test:e2e:ios` / `yarn test:e2e:android` for E2E +- Fastlane for deployment automation + +### Dependencies +- Yarn workspaces for monorepo management +- Platform-specific native modules +- Tamagui for UI components +- React Navigation for routing + +## Security & Privacy + +### Data Protection +- Sensitive data not logged in production +- Secure storage with Keychain +- Proper cleanup of sensitive data +- Certificate validation for passport data + +### Privacy Features +- Zero-knowledge proof generation +- Selective attribute revelation +- Privacy-preserving age verification +- Identity commitment privacy + +## Common Patterns + +### Error Handling +- Always use try-catch for async operations +- Graceful degradation when native modules fail +- User-friendly error messages +- Comprehensive error boundaries + +### Performance +- Lazy load screens and components +- Bundle size optimization with tree shaking +- Memory leak prevention in native modules +- Proper cleanup in useEffect and component unmount + +### Platform Differences +- Always check Platform.OS before platform-specific code +- Different implementations for iOS/Android when needed +- Platform-specific testing strategies +- Conditional rendering for platform differences diff --git a/.giga/specifications.json b/.giga/specifications.json new file mode 100644 index 000000000..aa55d6e4d --- /dev/null +++ b/.giga/specifications.json @@ -0,0 +1,27 @@ +[ + { + "fileName": "main-overview.mdc", + "path": ".cursorrules", + "description": "Complete system overview of the identity verification platform, covering the passport/ID verification workflow, zero-knowledge proof system, and compliance mechanisms" + }, + { + "fileName": "identity-verification-flow.mdc", + "path": ".cursor/rules/identity-verification-flow.mdc", + "description": "Detailed documentation of the multi-step identity verification process, including passport and EU ID card verification paths, proof verification pipeline, and attestation workflows" + }, + { + "fileName": "cryptographic-circuits.mdc", + "path": ".cursor/rules/cryptographic-circuits.mdc", + "description": "Technical documentation of the zero-knowledge proof circuits, including register circuits, DSC proofs, and disclosure proofs with their validation mechanisms" + }, + { + "fileName": "data-models.mdc", + "path": ".cursor/rules/data-models.mdc", + "description": "Documentation of core data structures including identity commitments, DSC key commitments, nullifier tracking, and verification configurations" + }, + { + "fileName": "compliance-verification.mdc", + "path": ".cursor/rules/compliance-verification.mdc", + "description": "Details of the compliance verification system including OFAC checks, age verification, forbidden country validation, and timestamp-based verifications" + } +] diff --git a/AGENTS.md b/AGENTS.md index 48d0f5f44..44d61d729 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,17 +15,61 @@ This repository is a Yarn v4 monorepo with several workspaces: ### Setup +- Ensure Node.js 22.x is installed (see `.nvmrc` for exact version), then: + - `nvm use` + - `corepack enable && corepack prepare yarn@stable --activate` + - Verify: `node -v && yarn -v` - Run `yarn install` once before running any other commands. This installs root dependencies and sets up husky hooks. +### Pre-PR Checklist + +Before creating a PR, ensure: + +#### Code Quality + +- [ ] `yarn nice` (or equivalent) passes in affected workspaces +- [ ] `yarn types` passes across the repo +- [ ] `yarn test` passes in affected packages +- [ ] `yarn build` succeeds for all workspaces + +#### AI Review Preparation + +- [ ] Clear commit messages following conventional format +- [ ] PR description includes context for AI reviewers +- [ ] Complex changes have inline comments explaining intent +- [ ] Security-sensitive changes flagged for special review + +#### Follow-up Planning + +- [ ] Identify any known issues that need separate PRs +- [ ] Note any performance implications +- [ ] Document any breaking changes + +### Post-PR Validation + +After PR creation: + +#### Automated Checks + +- [ ] CI pipeline passes all stages +- [ ] No new linting/formatting issues introduced +- [ ] Type checking passes in all affected workspaces +- [ ] Build artifacts generated successfully + +#### Review Integration + +- [ ] Address CodeRabbitAI feedback (or document why not) +- [ ] Resolve any security warnings +- [ ] Verify performance benchmarks still pass +- [ ] Confirm no sensitive data exposed in logs/comments + ### Commit Checks Before committing, run the following commands: ```bash # Fix linting and formatting issues automatically (for packages that support it) -yarn workspace @selfxyz/mobile-sdk-alpha nice -yarn workspace @selfxyz/common nice -yarn workspace @selfxyz/app nice +yarn workspaces foreach -A -p -v --topological-dev --since=HEAD run nice --if-present # Lint all packages in parallel yarn lint @@ -40,6 +84,34 @@ yarn workspace @selfxyz/contracts build yarn types ``` +### Workflow Commands + +#### Pre-PR Validation + +```bash +# Run all checks before PR - only on changed workspaces since main +# Format and lint changed workspaces (workspace-specific scripts first, then fallback to root) +yarn workspaces foreach -A -p -v --topological-dev --since=origin/main run nice --if-present + +# Run global checks across all workspaces +yarn lint && yarn types && yarn build && yarn test + +# Alternative: Run workspace-specific checks for changed workspaces only +# yarn workspaces foreach -A -p -v --topological-dev --since=origin/main run lint --if-present +# yarn workspaces foreach -A -p -v --topological-dev --since=origin/main run types --if-present +# yarn workspaces foreach -A -p -v --topological-dev --since=origin/main run build --if-present +# yarn workspaces foreach -A -p -v --topological-dev --since=origin/main run test --if-present +``` + +#### Post-PR Cleanup + +```bash +# After addressing review feedback +yarn nice # Fix any formatting issues in affected workspaces +yarn test # Ensure tests still pass +yarn types # Verify type checking +``` + ### Tests - Run unit tests where available: diff --git a/README.md b/README.md index 4d27050d3..874616ec2 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,16 @@ This project requires **Node.js 22.x**. Use the included `.nvmrc` to match the v Run `yarn install` to bootstrap dependencies and husky hooks. Gitleaks will scan staged changes on each commit via `yarn gitleaks`. +## Development Documentation + +For detailed development patterns and conventions, see: + +- **[Development Patterns](docs/development-patterns.md)** - React Native architecture, navigation, state management, and code organization +- **[Testing Guide](docs/testing-guide.md)** - Jest configuration, mock patterns, testing strategies, and E2E testing +- **[NFC Implementation](docs/nfc-implementation.md)** - Cross-platform NFC passport reading, authentication methods, and error handling + +These guides provide comprehensive context for AI-assisted development with ChatGPT Codex, Cursor, and CodeRabbit AI. + ## Contributing We are actively looking for contributors. Please check the [open issues](https://github.com/selfxyz/self/issues) if you don't know were to start! We offer bounties for significant contributions. diff --git a/app/AGENTS.md b/app/AGENTS.md new file mode 100644 index 000000000..c62a73e85 --- /dev/null +++ b/app/AGENTS.md @@ -0,0 +1,97 @@ +# AGENTS Instructions + +## Prerequisites + +- Node.js 22.x (`nvm use`), Yarn via Corepack (`corepack enable && corepack prepare yarn@stable --activate`) +- macOS/iOS: + - Xcode and Command Line Tools, CocoaPods (Ruby installed) + - From `app/ios`: `bundle install && bundle exec pod install` or from `app`: `npx pod-install` +- Android: + - Android SDK + Emulator, ANDROID_HOME configured, JDK 17 (set JAVA_HOME) +- Helpful: Watchman (macOS), `yarn install` at repo root + +## Pre-PR Checklist + +Before creating a PR for the mobile app: + +### Code Quality +- [ ] `yarn nice` passes (fixes linting and formatting) +- [ ] `yarn types` passes (TypeScript validation) +- [ ] `yarn test` passes (unit tests) +- [ ] App builds successfully on target platforms + +### Mobile-Specific Validation +- [ ] iOS build succeeds: `yarn ios` (simulator) +- [ ] Android build succeeds: `yarn android` (emulator/device) +- [ ] Web build succeeds: `yarn web` +- [ ] NFC functionality tested (if applicable) +- [ ] No sensitive data in logs (PII, credentials, tokens) + +### AI Review Preparation +- [ ] Complex native module changes documented +- [ ] Platform-specific code paths explained +- [ ] Security-sensitive operations flagged +- [ ] Performance implications noted + +## Post-PR Validation + +After PR creation: + +### Automated Checks +- [ ] CI pipeline passes all stages +- [ ] No new linting/formatting issues +- [ ] Type checking passes +- [ ] Build artifacts generated successfully + +### Mobile-Specific Checks +- [ ] App launches without crashes +- [ ] Core functionality works on target platforms +- [ ] No memory leaks introduced +- [ ] Bundle size within acceptable limits + +### Review Integration +- [ ] Address CodeRabbitAI feedback +- [ ] Resolve any security warnings +- [ ] Verify NFC/security features still work +- [ ] Confirm no sensitive data exposed + +## Recommended Workflow + +```bash +# Fix formatting and linting issues +yarn nice + +# Lint source files +yarn lint + +# Check types +yarn types + +# Run tests +yarn test +``` + +## Workflow Commands + +### Pre-PR Validation +```bash +# Run all checks before PR +yarn nice +yarn lint +yarn types +yarn test +yarn ios # Test iOS build +yarn android # Test Android build +``` + +### Post-PR Cleanup +```bash +# After addressing review feedback +yarn nice # Fix any formatting issues +yarn test # Ensure tests still pass +yarn types # Verify type checking +``` + +## Running the App + +- `yarn ios` diff --git a/docs/development-patterns.md b/docs/development-patterns.md new file mode 100644 index 000000000..8d75f6609 --- /dev/null +++ b/docs/development-patterns.md @@ -0,0 +1,206 @@ +# Self App Development Patterns + +## React Native Architecture + +### Navigation System +The app uses `@react-navigation/native` with `createStaticNavigation` for type-safe navigation. Screens are organized by feature modules and use platform-specific initial routes. + +```typescript +// Navigation setup pattern +export const navigationScreens = { + ...miscScreens, + ...passportScreens, + ...homeScreens, + ...proveScreens, + ...settingsScreens, + ...recoveryScreens, + ...devScreens, + // Feature screens added last to override others + ...getAesopScreens(), +}; + +// Platform-specific initial routes +initialRouteName: Platform.OS === 'web' ? 'Home' : 'Splash' +``` + +### Modal System +Custom modal system using `useModal` hook with callback registry for handling button presses and dismissals. + +```typescript +const { showModal, dismissModal, visible } = useModal({ + titleText: 'Modal Title', + bodyText: 'Modal content', + buttonText: 'Action', + onButtonPress: async () => { + // Handle button press + }, + onModalDismiss: () => { + // Handle modal dismiss + }, +}); +``` + +### Platform-Specific Handling +Always check platform before implementing platform-specific code: + +```typescript +if (Platform.OS === 'ios') { + // iOS-specific implementation +} else { + // Android-specific implementation +} +``` + +### Native Module Initialization +Critical for NFC and other native functionality: + +```typescript +// Initialize native modules before any native operations +const modulesReady = await initializeNativeModules(); +if (!modulesReady) { + console.warn('Native modules not ready, proceeding with limited functionality'); +} +``` + +## State Management + +### Hook-Based State +- Custom hooks for complex state management (`useModal`, `useHapticNavigation`) +- Zustand for global state management +- React Navigation state for screen-specific data + +### Data Persistence +- **AsyncStorage**: Simple key-value storage +- **SQLite**: Complex data (proof history) +- **Keychain**: Sensitive data (biometrics, encryption keys) + +## Testing Conventions + +### Jest Configuration +- Comprehensive mocks in `jest.setup.js` for all native modules +- Module mapping for clean imports +- Test-specific TypeScript configuration + +### Mock Patterns +All React Native native modules are mocked with realistic return values: + +```javascript +jest.mock('react-native-keychain', () => ({ + SECURITY_LEVEL_ANY: 'MOCK_SECURITY_LEVEL_ANY', + setGenericPassword: jest.fn(), + getGenericPassword: jest.fn(), + resetGenericPassword: jest.fn(), + ACCESSIBLE: { + WHEN_UNLOCKED: 'AccessibleWhenUnlocked', + // ... other constants + }, +})); +``` + +### Testing Patterns +- Use `renderHook` for custom hook testing +- Mock console.error to avoid test output clutter +- Test error boundaries and recovery mechanisms +- E2E testing with Maestro for platform-specific flows + +## NFC Implementation + +### Cross-Platform Architecture +- **iOS**: Custom PassportReader Swift module +- **Android**: Custom RNPassportReaderModule Kotlin implementation +- Unified JavaScript interface with platform detection + +### Authentication Methods +- **MRZ Key**: Derived from passport number, DOB, and expiry date +- **CAN (Card Access Number)**: 6-digit number for PACE authentication +- **PACE**: Password Authenticated Connection Establishment +- **BAC Fallback**: Basic Access Control when PACE fails + +### Error Handling +- Multiple BAC attempts with delays +- Graceful degradation from PACE to BAC +- Real-time status updates and haptic feedback +- Comprehensive error boundaries + +### JavaScript Interface +```typescript +export const scan = async (inputs: Inputs) => { + return Platform.OS === 'android' + ? await scanAndroid(inputs) + : await scanIOS(inputs); +}; +``` + +## Code Organization + +### File Structure +``` +src/ +├── components/ # Reusable UI components +├── screens/ # Screen components by feature +├── navigation/ # Navigation configuration +├── hooks/ # Custom React hooks +├── utils/ # Shared utilities +├── types/ # TypeScript type definitions +├── stores/ # State management +└── providers/ # Context providers +``` + +### Import Patterns +- Use `@/` alias for src imports: `import { Component } from '@/components'` +- Use `@tests/` alias for test imports: `import { mockData } from '@tests/utils'` +- Platform-specific imports with conditional rendering + +## Build & Deployment + +### Scripts +- `yarn ios` / `yarn android` for platform-specific builds +- `yarn test` for Jest testing +- `yarn test:e2e:ios` / `yarn test:e2e:android` for E2E +- Fastlane for deployment automation + +### Dependencies +- Yarn workspaces for monorepo management +- Platform-specific native modules +- Tamagui for UI components +- React Navigation for routing + +## Security & Privacy + +### Data Protection +- Sensitive data not logged in production +- Secure storage with Keychain +- Proper cleanup of sensitive data +- Certificate validation for passport data + +### Privacy Features +- Zero-knowledge proof generation +- Selective attribute revelation +- Privacy-preserving age verification +- Identity commitment privacy + +## Common Patterns + +### Error Handling +```typescript +try { + const result = await riskyOperation(); + return result; +} catch (error) { + console.error('Operation failed:', error); + // Graceful degradation + return fallbackValue; +} +``` + +### Performance Optimization +- Lazy load screens and components +- Bundle size optimization with tree shaking +- Memory leak prevention in native modules +- Proper cleanup in useEffect and component unmount + +### Platform Differences +- Always check Platform.OS before platform-specific code +- Different implementations for iOS/Android when needed +- Platform-specific testing strategies +- Conditional rendering for platform differences diff --git a/docs/nfc-implementation.md b/docs/nfc-implementation.md new file mode 100644 index 000000000..79295b8d6 --- /dev/null +++ b/docs/nfc-implementation.md @@ -0,0 +1,273 @@ +# NFC Implementation Guide + +## Architecture Overview + +### Cross-Platform Implementation +The NFC passport reading system uses platform-specific native modules with a unified JavaScript interface: + +- **iOS**: Custom PassportReader Swift module +- **Android**: Custom RNPassportReaderModule Kotlin implementation +- **JavaScript**: Unified interface with platform detection + +### Data Flow +1. User initiates scan with passport details (MRZ data) +2. Platform-specific native module handles NFC communication +3. Raw passport data returned to JavaScript +4. Data parsed and normalized for processing +5. Zero-knowledge proof generation and verification + +## iOS Implementation + +### PassportReader Module +The iOS implementation uses a custom Swift module with NFC capabilities: + +```swift +func readPassport( + password: String, + type: PACEPasswordType, + tags: [NFCISO7816Tag], + skipCA: Bool, + skipPACE: Bool, + useExtendedMode: Bool, + usePacePolling: Bool, + customDisplayMessage: ((NFCViewDisplayMessage) -> String?)? +) async throws -> Passport +``` + +### Authentication Methods +- **MRZ Key**: Derived from passport number, date of birth, and expiry date +- **CAN (Card Access Number)**: 6-digit number for PACE authentication +- **PACE**: Password Authenticated Connection Establishment + +### Error Handling +- Comprehensive try-catch blocks for each authentication step +- Graceful fallback from PACE to BAC when needed +- User-friendly error messages for different failure scenarios + +## Android Implementation + +### RNPassportReaderModule +The Android implementation uses a custom Kotlin module: + +```kotlin +@ReactMethod +fun scan(opts: ReadableMap, promise: Promise) { + // NFC adapter setup and validation + // Intent handling for tag discovery + // Async task execution for passport reading +} +``` + +### Authentication Flow +1. **PACE Authentication**: Primary method using CAN or MRZ key +2. **BAC Fallback**: Basic Access Control when PACE fails +3. **Retry Logic**: Multiple attempts with delays between retries + +### Intent Handling +- `onNewIntent` in MainActivity routes to RNPassportReaderModule +- Foreground dispatch for NFC tag discovery +- Proper lifecycle management (resume/pause) + +### Android-Specific Workarounds +On certain Android devices, NFC scanner fails to activate on app launch. The automatic workaround uses an event-driven approach: +- `scan()` method sets `shouldEnableNfcOnResume=true` +- Programmatically backgrounds the app using `moveTaskToBack(true)` +- Waits 500ms, then foregrounds it +- NFC enablement happens in `onHostResume()` when activity is properly in foreground + +## JavaScript Interface + +### Unified Scan Function +```typescript +export const scan = async (inputs: Inputs) => { + return Platform.OS === 'android' + ? await scanAndroid(inputs) + : await scanIOS(inputs); +}; +``` + +### Input Parameters +```typescript +interface Inputs { + passportNumber: string; + dateOfBirth: string; + dateOfExpiry: string; + canNumber?: string; + useCan?: boolean; + skipPACE?: boolean; + skipCA?: boolean; + extendedMode?: boolean; + usePacePolling?: boolean; +} +``` + +### Response Processing +- Platform-specific response parsing +- Data normalization for consistent format +- Error handling and validation + +## Authentication Methods + +### MRZ Key Generation +The MRZ key is derived from passport data: +```typescript +const mrzKey = getMRZKey( + passportNumber: string, + dateOfBirth: string, + dateOfExpiry: string +); +``` + +### PACE Authentication +- **Primary Method**: Uses CAN or MRZ key for authentication +- **Extended Mode**: Enhanced security features +- **Polling**: Optional polling mechanism for better reliability + +### BAC (Basic Access Control) +- **Fallback Method**: Used when PACE fails +- **Multiple Attempts**: Up to 3 attempts with delays +- **Error Recovery**: Graceful handling of authentication failures + +## Error Handling Patterns + +### Authentication Failures +- **Access Denied**: Invalid credentials or expired passport +- **BAC Denied**: Basic Access Control failure +- **PACE Exception**: Password Authenticated Connection Establishment failure +- **Card Exception**: General NFC communication issues + +### Retry Mechanisms +- Multiple BAC attempts with delays between retries +- Graceful degradation from PACE to BAC +- Timeout handling for slow operations +- User feedback during retry attempts + +### User Feedback +- Real-time status updates during scanning +- Haptic feedback for different states +- Clear error messages for troubleshooting +- Progress indicators for long operations + +## Performance Optimizations + +### Timeout Management +- Configurable timeouts for different operations +- Platform-specific timeout values +- Graceful timeout handling with user feedback + +### Memory Management +- Proper cleanup of NFC connections +- Resource disposal in finally blocks +- Memory leak prevention +- Component lifecycle management + +### Debug Logging +- Conditional debug logging based on environment +- Performance timing for scan operations +- Detailed error logging for troubleshooting +- Analytics integration for performance monitoring + +## Security Considerations + +### Data Protection +- Sensitive data not logged in production +- Secure storage of authentication keys +- Proper cleanup of sensitive data +- Memory protection for cryptographic operations + +### Certificate Validation +- Document Signer Certificate (DSC) validation +- Certificate chain verification +- Trust store management +- Certificate revocation checking + +### Privacy Features +- Zero-knowledge proof generation +- Selective attribute revelation +- Privacy-preserving age verification +- Identity commitment privacy + +## Testing Strategy + +### Mock Implementations +- Comprehensive mocks for testing without hardware +- Platform-specific mock data +- Error scenario testing +- Performance testing with simulated delays + +### Integration Testing +- Real device testing for critical paths +- Platform-specific test scenarios +- Performance benchmarking +- Security testing with real passports + +### Test Data +- Mock passport data for unit tests +- Test certificates for validation +- Error scenarios for edge case testing +- Performance benchmarks for optimization + +## Platform-Specific Considerations + +### iOS +- NFC capabilities require iOS 13+ +- Background NFC reading limitations +- Privacy permissions and user consent +- App Store review requirements + +### Android +- NFC hardware requirements +- Permission handling +- Background processing limitations +- Device-specific workarounds + +### Web +- No NFC support (fallback to other methods) +- Alternative authentication flows +- Cross-platform compatibility + +## Common Issues and Solutions + +### NFC Not Detected +- Check device NFC capabilities +- Verify NFC is enabled in settings +- Ensure app has proper permissions +- Try device-specific workarounds + +### Authentication Failures +- Verify passport data accuracy +- Check passport expiration +- Try alternative authentication methods +- Implement retry logic with delays + +### Performance Issues +- Optimize timeout values +- Implement proper cleanup +- Monitor memory usage +- Profile NFC operations + +## Best Practices + +### Error Handling +- Always implement comprehensive error handling +- Provide user-friendly error messages +- Log errors for debugging +- Implement graceful degradation + +### Performance +- Optimize timeout values for your use case +- Implement proper resource cleanup +- Monitor memory usage +- Profile NFC operations + +### Security +- Never log sensitive data +- Implement proper certificate validation +- Use secure storage for keys +- Follow platform security guidelines + +### User Experience +- Provide clear feedback during operations +- Implement haptic feedback +- Show progress indicators +- Handle edge cases gracefully diff --git a/docs/testing-guide.md b/docs/testing-guide.md new file mode 100644 index 000000000..434681db8 --- /dev/null +++ b/docs/testing-guide.md @@ -0,0 +1,272 @@ +# Testing Guide + +## Jest Configuration + +### Setup Files +The project uses comprehensive Jest configuration with: +- `jest.setup.js` - Contains mocks for all native modules +- `jest.config.cjs` - Configures transform patterns and module mapping +- `tsconfig.test.json` - Test-specific TypeScript configuration + +### Module Mapping +```javascript +moduleNameMapper: { + '^@env$': '/tests/__setup__/@env.js', + '\\.svg$': '/tests/__setup__/svgMock.js', + '^@/(.*)$': '/src/$1', + '^@tests/(.*)$': '/tests/src/$1', +} +``` + +### Transform Patterns +```javascript +transformIgnorePatterns: [ + 'node_modules/(?!(react-native|@react-native|@react-navigation|@react-native-community|@segment/analytics-react-native|@openpassport|react-native-keychain|react-native-check-version|react-native-nfc-manager|react-native-passport-reader|react-native-gesture-handler|uuid|@stablelib|@react-native-google-signin|react-native-cloud-storage|@react-native-clipboard|@react-native-firebase)/)', +] +``` + +## Mock Patterns + +### Native Module Mocks +All React Native native modules are mocked in `jest.setup.js`: + +#### Firebase Mocks +```javascript +jest.mock('@react-native-firebase/messaging', () => { + return () => ({ + hasPermission: jest.fn(() => Promise.resolve(true)), + requestPermission: jest.fn(() => Promise.resolve(true)), + getToken: jest.fn(() => Promise.resolve('mock-token')), + onMessage: jest.fn(() => jest.fn()), + onNotificationOpenedApp: jest.fn(() => jest.fn()), + getInitialNotification: jest.fn(() => Promise.resolve(null)), + setBackgroundMessageHandler: jest.fn(), + registerDeviceForRemoteMessages: jest.fn(() => Promise.resolve()), + subscribeToTopic: jest.fn(), + unsubscribeFromTopic: jest.fn(), + }); +}); +``` + +#### Keychain Mocks +```javascript +jest.mock('react-native-keychain', () => ({ + SECURITY_LEVEL_ANY: 'MOCK_SECURITY_LEVEL_ANY', + SECURITY_LEVEL_SECURE_SOFTWARE: 'MOCK_SECURITY_LEVEL_SECURE_SOFTWARE', + SECURITY_LEVEL_SECURE_HARDWARE: 'MOCK_SECURITY_LEVEL_SECURE_HARDWARE', + setGenericPassword: jest.fn(), + getGenericPassword: jest.fn(), + resetGenericPassword: jest.fn(), + ACCESSIBLE: { + WHEN_UNLOCKED: 'AccessibleWhenUnlocked', + AFTER_FIRST_UNLOCK: 'AccessibleAfterFirstUnlock', + ALWAYS: 'AccessibleAlways', + WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: 'AccessibleWhenPasscodeSetThisDeviceOnly', + WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'AccessibleWhenUnlockedThisDeviceOnly', + AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 'AccessibleAfterFirstUnlockThisDeviceOnly', + ALWAYS_THIS_DEVICE_ONLY: 'AccessibleAlwaysThisDeviceOnly', + }, + ACCESS_CONTROL: { + USER_PRESENCE: 'UserPresence', + BIOMETRY_ANY: 'BiometryAny', + BIOMETRY_CURRENT_SET: 'BiometryCurrentSet', + DEVICE_PASSCODE: 'DevicePasscode', + APPLICATION_PASSWORD: 'ApplicationPassword', + BIOMETRY_ANY_OR_DEVICE_PASSCODE: 'BiometryAnyOrDevicePasscode', + BIOMETRY_CURRENT_SET_OR_DEVICE_PASSCODE: 'BiometryCurrentSetOrDevicePasscode', + }, +})); +``` + +#### NFC Mocks +```javascript +jest.mock('react-native-nfc-manager', () => ({ + start: jest.fn(), + isSupported: jest.fn().mockResolvedValue(true), + isEnabled: jest.fn().mockResolvedValue(true), + registerTagEvent: jest.fn(), + unregisterTagEvent: jest.fn(), + requestTechnology: jest.fn(), + cancelTechnologyRequest: jest.fn(), + getTag: jest.fn(), + setAlertMessage: jest.fn(), + sendMifareCommand: jest.fn(), + sendCommandAPDU: jest.fn(), + transceive: jest.fn(), + getMaxTransceiveLength: jest.fn(), + setTimeout: jest.fn(), + connect: jest.fn(), + close: jest.fn(), + cleanUpTag: jest.fn(), + default: { + // Same methods as above + }, +})); +``` + +### Database Testing +SQLite operations are mocked for testing: + +```javascript +// Mock react-native-sqlite-storage +jest.mock('react-native-sqlite-storage', () => ({ + enablePromise: jest.fn(), + openDatabase: jest.fn(), +})); + +// Test database instance +const mockDb = { + executeSql: jest.fn(() => Promise.resolve()), +}; + +mockSQLite.openDatabase.mockResolvedValue(mockDb); +``` + +## Test Organization + +### File Structure +``` +tests/ +├── __setup__/ # Global test setup and mocks +├── src/ # Unit tests mirroring source structure +├── integration/ # Integration tests +├── e2e/ # End-to-end tests +└── utils/ # Test utilities and helpers +``` + +### Test File Naming +- Unit tests: `*.test.ts` or `*.test.tsx` +- Integration tests: `*.integration.test.ts` +- E2E tests: Platform-specific YAML files + +## Testing Patterns + +### Hook Testing +Use `renderHook` for testing custom hooks: + +```typescript +import { renderHook } from '@testing-library/react-native'; + +describe('useModal', () => { + it('should return modal functions', () => { + const { result } = renderHook(() => useModal(mockParams)); + + expect(result.current).toHaveProperty('showModal'); + expect(result.current).toHaveProperty('dismissModal'); + expect(result.current).toHaveProperty('visible'); + }); +}); +``` + +### Component Testing +Test React Native components with proper mocking: + +```typescript +import { render, fireEvent } from '@testing-library/react-native'; + +describe('Component', () => { + it('should handle user interactions', () => { + const mockNavigation = { navigate: jest.fn() }; + const { getByText } = render(); + + fireEvent.press(getByText('Button')); + expect(mockNavigation.navigate).toHaveBeenCalledWith('Screen'); + }); +}); +``` + +### Error Testing +Test error boundaries and error handling: + +```typescript +describe('Error handling', () => { + beforeEach(() => { + // Suppress console.error during tests + jest.spyOn(console, 'error').mockImplementation(() => {}); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('should handle errors gracefully', () => { + // Test error scenarios + }); +}); +``` + +## E2E Testing + +### Platform-Specific Flows +- Separate test files for iOS and Android +- Maestro for cross-platform E2E testing +- Platform-specific build commands before E2E tests + +### Test Commands +```bash +# iOS E2E +yarn test:e2e:ios + +# Android E2E +yarn test:e2e:android +``` + +### Test Data Management +- Mock passport data for testing +- Test-specific environment variables +- Cleanup between test runs + +## Performance Testing + +### Bundle Analysis +```bash +# Analyze bundle size +yarn analyze:bundle:ios +yarn analyze:bundle:android + +# Tree shaking analysis +yarn analyze:tree-shaking +``` + +### Memory Testing +- Memory leak detection in tests +- Component lifecycle testing +- Native module cleanup verification + +## Coverage Strategy + +### Coverage Commands +```bash +# Basic coverage +yarn test:coverage + +# CI coverage with multiple formats +yarn test:coverage:ci +``` + +### Coverage Configuration +- Jest coverage reporting with multiple formats +- CI-specific coverage commands +- Coverage thresholds for critical paths + +## Best Practices + +### Test Isolation +- Always clean up mocks between tests +- Use `beforeEach` and `afterEach` for setup/cleanup +- Avoid shared state between tests + +### Mock Management +- Mock at the right level (module vs function) +- Provide realistic mock return values +- Test error scenarios with mocks + +### Async Testing +- Use `async/await` for async operations +- Test both success and failure paths +- Handle promises properly in tests + +### Platform Testing +- Test platform-specific code paths +- Mock platform-specific modules +- Test conditional rendering logic diff --git a/noir/AGENTS.md b/noir/AGENTS.md index 787777ec3..54704361e 100644 --- a/noir/AGENTS.md +++ b/noir/AGENTS.md @@ -12,6 +12,70 @@ - Ensure Rust toolchain is installed and up to date (required by nargo). - From the repository root, run commands inside the `noir/` workspace unless otherwise noted. +## Pre-PR Checklist + +Before creating a PR for noir circuits: + +### Code Quality +- [ ] `nargo fmt` passes (formatting is correct) +- [ ] `nargo check -p ` passes (compilation errors fixed) +- [ ] `nargo test -p ` passes (all tests pass) +- [ ] `nargo build -p ` succeeds (circuit builds correctly) + +### Circuit-Specific Validation +- [ ] Zero-knowledge proof constraints are correct +- [ ] Public inputs/outputs properly defined +- [ ] No arithmetic overflow/underflow +- [ ] Circuit complexity is acceptable +- [ ] Security properties maintained + +### AI Review Preparation +- [ ] Circuit logic documented with comments +- [ ] Mathematical operations explained +- [ ] Security assumptions clearly stated +- [ ] Performance implications noted + +## Post-PR Validation + +After PR creation: + +### Automated Checks +- [ ] CI pipeline passes all stages +- [ ] No new compilation errors +- [ ] All tests pass across all crates +- [ ] Build artifacts generated successfully + +### Circuit-Specific Checks +- [ ] Proof generation still works +- [ ] Verification passes for all test cases +- [ ] No constraint system changes break existing proofs +- [ ] Circuit size within acceptable limits + +### Review Integration +- [ ] Address CodeRabbitAI feedback +- [ ] Resolve any security warnings +- [ ] Verify cryptographic properties +- [ ] Confirm no logical errors introduced + +## Workflow Commands + +### Pre-PR Validation +```bash +# Run all checks before PR +nargo fmt +nargo check -p +nargo test -p +nargo build -p +``` + +### Post-PR Cleanup +```bash +# After addressing review feedback +nargo fmt # Fix any formatting issues +nargo test -p # Ensure tests still pass +nargo check -p # Verify compilation +``` + ### Code Quality For the best development experience: diff --git a/packages/mobile-sdk-alpha/AGENTS.md b/packages/mobile-sdk-alpha/AGENTS.md index b322672eb..7b6ff43bb 100644 --- a/packages/mobile-sdk-alpha/AGENTS.md +++ b/packages/mobile-sdk-alpha/AGENTS.md @@ -62,6 +62,81 @@ For publishing: - Run `yarn validate:exports` to check export configuration - Run `yarn validate:pkg` to verify package conditions +## Pre-PR Checklist + +Before creating a PR for the mobile-sdk-alpha package: + +### Code Quality + +- [ ] `yarn nice` passes (fixes linting and formatting) +- [ ] `yarn types` passes (TypeScript validation) +- [ ] `yarn test` passes (unit tests) +- [ ] `yarn build` succeeds (package builds correctly) + +### SDK-Specific Validation + +- [ ] Exports are properly configured +- [ ] Package conditions are valid +- [ ] No breaking changes to public API (or properly documented) +- [ ] Migration guide updated (if applicable) +- [ ] Integration tests pass + +### AI Review Preparation + +- [ ] API changes documented with examples +- [ ] Breaking changes clearly flagged +- [ ] Performance implications noted +- [ ] Security considerations addressed + +## Post-PR Validation + +After PR creation: + +### Automated Checks + +- [ ] CI pipeline passes all stages +- [ ] No new linting/formatting issues +- [ ] Type checking passes +- [ ] Build artifacts generated successfully + +### SDK-Specific Checks + +- [ ] Package exports validation passes +- [ ] Integration with main app still works +- [ ] No circular dependencies introduced +- [ ] Bundle size impact acceptable + +### Review Integration + +- [ ] Address CodeRabbitAI feedback +- [ ] Resolve any security warnings +- [ ] Verify API compatibility +- [ ] Confirm migration path is clear + +## Workflow Commands + +### Pre-PR Validation + +```bash +# Run all checks before PR +yarn nice +yarn types +yarn test +yarn build +yarn validate:exports +yarn validate:pkg +``` + +### Post-PR Cleanup + +```bash +# After addressing review feedback +yarn nice # Fix any formatting issues +yarn test # Ensure tests still pass +yarn types # Verify type checking +yarn build # Confirm build still works +``` + ## Notes - This package uses TypeScript with strict type checking