# Maat Journal Decryption Tool

This tool allows you to decrypt your Maat Journal export files using your recovery phrase, giving you full control over your data. The tool includes automatic version detection and migration support for future-proof data access.

## 🔒 Security First

**Your recovery phrase is the key to your data.** Keep it safe and never share it with anyone.

- ✅ **Your data is encrypted with industry-standard cryptography**
- ✅ **Only you can decrypt your data with your recovery phrase**
- ✅ **The encryption is the same strength used by Bitcoin wallets**
- ✅ **Your recovery phrase never leaves your device**

## 📋 Requirements

- Python 3.9 or higher
- Your 12-word recovery phrase from Maat Journal
- The encrypted export file from your app

## 🚀 Quick Start

### 1. Install Dependencies

```bash
# Run the installation script (creates virtual environment automatically)
./install.sh
```

This script will:
- Create a virtual environment
- Install all required dependencies
- Provide usage instructions

**Note:** The script always uses a virtual environment to avoid conflicts with system Python packages.

### 2. Create .env File

Create a `.env` file in the same directory as the script:

```bash
RECOVERY_PHRASE="word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12"
```

**Replace the words with your actual 12-word recovery phrase from Maat Journal.**

### 3. Run the Decryption Tool

```bash
python maat_decrypt.py --input your_export.json
```

The tool will create a `your_export_decrypted.json` file with your readable journal entries.

## 📖 Detailed Usage

### Basic Usage

```bash
# Decrypt with automatic output filename (JSON format)
python maat_decrypt.py --input my_export.json

# Decrypt to plain text for easy reading
python maat_decrypt.py --input my_export.json --format text

# Specify custom output file
python maat_decrypt.py --input my_export.json --output readable_entries.json

# Export to plain text with custom filename
python maat_decrypt.py --input my_export.json --format text --output my_journal.txt

# Quiet mode (minimal output)
python maat_decrypt.py --input my_export.json --quiet
```

### Command Line Options

- `--input, -i`: Path to your encrypted export file (required)
- `--output, -o`: Path for the decrypted output file (optional)
- `--format, -f`: Output format: `json` (default) or `text` (plain text for reading)
- `--quiet, -q`: Suppress progress messages
- `--version, -v`: Show version information
- `--help, -h`: Show help message

### Output Formats

The tool supports two output formats:

**JSON Format (default)**
- Structured data with all metadata
- Suitable for data analysis or importing to other tools
- File extension: `.json`

**Text Format**
- Plain text file for easy reading
- Includes dates, mood ratings, and content
- Entries sorted by date (newest first)
- File extension: `.txt`

Example text output:
```
Maat Journal - Decrypted Entries
==================================================

Entry #1
Date: January 15, 2025 at 2:30 PM
Mood: Happy
------------------------------
Today was a great day! I accomplished...

Entry #2
Date: January 14, 2025 at 9:15 AM
Mood: Calm
------------------------------
Reflecting on yesterday's events...
```

### .env File Locations

The tool will look for your `.env` file in these locations (in order):

1. Current working directory (`.env`)
2. Script directory (`scripts/.env`)
3. Home directory (`.maat-journal/.env`)

## 🔄 Version Support

The decryption tool automatically detects and handles different Maat export format versions:

- **Current Version**: 1.0
- **Supported Versions**: 1.0 (and future versions)
- **Automatic Migration**: The tool can migrate data between versions
- **Backward Compatibility**: Old export files continue to work

### Version Detection

The tool looks for the `maat_export_format_version` field in your export metadata. If not found, it assumes version 1.0.

### Future-Proof Design

As Maat Journal evolves and adds new features, the decryption tool will automatically handle different export formats, ensuring your data remains accessible.

## 🔧 Troubleshooting

### "Missing required dependencies"

```bash
pip install python-dotenv mnemonic pycryptodome
```

### "No .env file found"

Create a `.env` file with your recovery phrase:
```bash
echo 'RECOVERY_PHRASE="your 12 words here"' > .env
```

### "Recovery phrase must be exactly 12 words"

Make sure your recovery phrase has exactly 12 words, separated by spaces.

### "Decryption failed - wrong key or corrupted data"

- Double-check your recovery phrase spelling
- Make sure you're using the correct recovery phrase for this export
- The export file might be corrupted

### "Failed to decrypt X entries"

Some entries might be corrupted or encrypted with a different key. Check the `failed_entries` section in the output file for details.

## 🔐 How It Works

The decryption process follows these steps:

1. **Recovery Phrase → Seed**: Your 12 words are converted to a cryptographic seed using BIP39 standard
2. **Seed → Master Key**: The seed is used to derive a master encryption key using HKDF-SHA256
3. **Decrypt Entries**: Each journal entry is decrypted using AES-256-GCM encryption
4. **Output**: The decrypted data is saved as readable JSON

### Technical Details

- **Encryption**: AES-256-GCM (same as Bitcoin wallets)
- **Key Derivation**: HKDF-SHA256 with salt `"maat-journal-v1"` and info `"master-encryption-key"`
- **Recovery Phrase**: BIP39 standard (12 words, 128 bits of entropy)
- **Format**: Base64 encoded (IV + ciphertext + authentication tag)

## 📁 Output Format

The decrypted file contains:

```json
{
  "backup_metadata": {
    "created_at": "2024-01-01T12:00:00Z",
    "format_version": "2.0",
    "total_entries": 100,
    "is_encrypted": false,
    "decrypted_at": "2024-01-01T12:30:00Z",
    "decryption_tool": "maat-journal-decrypt-tool",
    "decryption_version": "1.0.0"
  },
  "journal_entries": [
    {
      "id": "entry-uuid",
      "content": "Your journal entry text here...",
      "created_at": "2024-01-01T12:00:00Z",
      "mood_rating": 8,
      "metadata": {
        "word_count": 150,
        "tags": ["personal", "reflection"]
      }
    }
  ],
  "failed_entries": [
    {
      "entry_id": "entry-uuid",
      "index": 5,
      "error": "Decryption failed - wrong key"
    }
  ]
}
```

## 🛡️ Security Best Practices

### Keep Your Recovery Phrase Safe

- ✅ Write it down on paper and store it securely
- ✅ Never share it with anyone
- ✅ Don't store it in plain text on your computer
- ✅ Consider using a password manager for backup

### Handle Decrypted Data Carefully

- ✅ The decrypted file contains your personal data
- ✅ Store it securely and delete when no longer needed
- ✅ Don't share the decrypted file with others
- ✅ Consider encrypting the decrypted file for additional security

### File Management

- ✅ Keep your `.env` file secure and separate from the decrypted data
- ✅ Delete the decrypted file after use
- ✅ Use secure deletion tools for sensitive files

## 🤝 Support

If you encounter issues:

1. Check the troubleshooting section above
2. Verify your recovery phrase is correct
3. Make sure you're using the right export file
4. Check that all dependencies are installed

## 📄 License

This tool is part of Maat Journal and follows the same license as the main application.

## 🔗 Related Links

- [Maat Journal App](https://github.com/your-repo/maat-journal)
- [Encryption Documentation](https://github.com/your-repo/maat-journal/docs/encryption.md)
- [BIP39 Standard](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki)
- [HKDF RFC 5869](https://tools.ietf.org/html/rfc5869)
