Metadata-Version: 2.4
Name: titanvault
Version: 1.0.0
Summary: The Secure, Lightweight, and Type-Safe Local Storage for the Future
Project-URL: Homepage, https://github.com/Phenphet-K/titanvault
Project-URL: Repository, https://github.com/Phenphet-K/titanvault
Project-URL: Documentation, https://github.com/Phenphet-K/titanvault#readme
Author-email: Phenphet-K <your-email@example.com>
License: MIT License
        
        Copyright (c) 2025 TitanVault Contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: aes,database,encryption,orm,security,sqlite,storage
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Database
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cryptography>=42.0.0
Provides-Extra: dev
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest>=7.4; extra == 'dev'
Description-Content-Type: text/markdown

# 🔐 TitanVault

> **The Secure, Lightweight, and Type-Safe Local Storage for the Future**

TitanVault is a Python library for local-first encrypted data storage. It gives you an ORM-like API backed by SQLite, where every record is transparently encrypted with **AES-256-GCM** before it ever touches disk. No configuration required.

---

## ✨ Features

| Feature | Detail |
|---|---|
| **Type-Safe API** | Define schemas with plain Python type annotations — full IDE auto-complete |
| **AES-256-GCM Encryption** | Authenticated encryption at rest — every record, always |
| **PBKDF2 Key Derivation** | 600,000 iterations (NIST 2023 recommendation) |
| **Zero-Config SQLite** | Tables are created and migrated automatically |
| **Atomic Transactions** | ACID-compliant writes via `save_many()` and `vault.transaction()` |
| **Fluent Query Builder** | `.filter()`, `.order_by()`, `.limit()`, `.first()`, `.count()` |
| **Minimal Dependencies** | Only `cryptography` (the gold-standard Python crypto library) |

---

## 📦 Installation

```bash
pip install titanvault
```

**Requirements:** Python 3.10+, `cryptography>=41.0.0`

---

## 🚀 Quick Start

```python
from titanvault import Vault, TitanModel

# 1. Define your schema — just type annotations, no boilerplate
class SecretKey(TitanModel):
    service: str
    username: str
    password: str

# 2. Open (or create) an encrypted vault
vault = Vault("my_vault.db", secret_key="super-secret-password")

# 3. Save a record — encrypted automatically
new_key = SecretKey(service="Github", username="titan", password="gh_abc123")
vault.save(new_key)
print(new_key._id)  # Auto-generated UUID: "a1b2c3d4-..."

# 4. Query — decrypted and returned as a typed object
result = vault.query(SecretKey).filter(service="Github").first()
print(result.username)   # titan  (with full IDE auto-complete)
print(result.password)   # gh_abc123

vault.close()
```

---

## 📖 Usage Guide

### Defining Models

```python
from titanvault import TitanModel

class ApiCredential(TitanModel):
    provider: str
    api_key: str
    is_active: bool = True
    rate_limit: int = 1000

class UserNote(TitanModel):
    title: str
    body: str
    category: str = "general"
```

Every subclass of `TitanModel` is automatically a `@dataclass`. The following metadata fields are managed by the Vault:

| Field | Type | Description |
|---|---|---|
| `_id` | `str` | UUID v4 primary key |
| `_created_at` | `str` | ISO-8601 UTC timestamp of first save |
| `_updated_at` | `str` | ISO-8601 UTC timestamp of last save |

---

### Opening a Vault

```python
# Option A: Manual lifecycle
vault = Vault("path/to/vault.db", secret_key="my-password")
# ... use vault ...
vault.close()

# Option B: Context manager (recommended)
with Vault("path/to/vault.db", secret_key="my-password") as vault:
    # ... use vault ...
```

---

### Saving Records

```python
# Single record
key = ApiCredential(provider="OpenAI", api_key="sk-...")
vault.save(key)
print(key._id)  # UUID assigned after save

# Update (pass the same record again)
key.api_key = "sk-new-key"
vault.save(key)  # upsert — _created_at preserved, _updated_at refreshed

# Bulk save (atomic — all succeed or all fail)
records = [
    ApiCredential(provider=f"Service{i}", api_key=f"key-{i}")
    for i in range(100)
]
vault.save_many(records)
```

---

### Querying Records

```python
# Get all records of a type
all_keys = vault.query(ApiCredential).all()

# Filter by one or more fields
active_keys = vault.query(ApiCredential).filter(is_active=True).all()

# Get the first match
openai_key = vault.query(ApiCredential).filter(provider="OpenAI").first()

# Check existence
exists = vault.query(ApiCredential).filter(provider="OpenAI").exists()

# Count
total = vault.query(ApiCredential).count()

# Order by a field
sorted_keys = vault.query(ApiCredential).order_by("provider").all()
sorted_desc = vault.query(ApiCredential).order_by("provider", desc=True).all()

# Pagination
page = vault.query(ApiCredential).order_by("provider").offset(10).limit(10).all()

# Get by UUID
record = vault.get(ApiCredential, "a1b2c3d4-...")

# Total count (fast — no decryption)
n = vault.count(ApiCredential)
```

---

### Deleting Records

```python
# Delete a record object
vault.delete(key)

# Delete by UUID
vault.delete_by_id(ApiCredential, "a1b2c3d4-...")

# Drop an entire collection (⚠️ irreversible)
vault.drop_collection(ApiCredential)
```

---

### Atomic Transactions

```python
# Explicit transaction block
with vault.transaction():
    vault.save(record_a)
    vault.save(record_b)
    vault.delete(old_record)
# All committed on block exit, rolled back on any exception
```

---

## 🔒 Security Architecture

```
User Password
      │
      ▼
PBKDF2-HMAC-SHA256 (600,000 iterations + 32-byte random salt)
      │
      ▼
  AES-256 Key
      │
      ├── For each save():
      │       JSON(record) ──► AES-256-GCM(nonce=random 12B) ──► BLOB on disk
      │
      └── For each read():
              BLOB on disk ──► AES-256-GCM decrypt ──► JSON ──► Python object
```

**Key properties:**
- **Confidentiality:** AES-256 (256-bit key) — computationally infeasible to brute-force
- **Integrity:** GCM authentication tag — any tampering raises `DecryptionError`
- **Freshness:** New random nonce per record — same plaintext produces different ciphertext
- **Password hardening:** PBKDF2 with 600K iterations slows brute-force password attacks
- **Zero plaintext on disk:** Field values are never stored unencrypted

---

## ⚙️ Schema Evolution (Auto-Migration)

Adding new optional fields with defaults to an existing model "just works":

```python
# Version 1 (data already saved)
class SecretKey(TitanModel):
    service: str
    password: str

# Version 2 (add a new optional field — old records use the default)
class SecretKey(TitanModel):
    service: str
    password: str
    notes: str = ""       # ← new field; old records will read "" automatically
    tags: str = "[]"      # ← another new field
```

---

## 🧪 Running Tests

```bash
pip install -e ".[dev]"
pytest
pytest --cov=titanvault --cov-report=term-missing  # with coverage
```

---

## 🗺️ Roadmap

- [x] Encrypted Blob Storage (large file support)
- [ ] End-to-End Encrypted Cloud Sync
- [x] Argon2id key derivation (memory-hard, stronger than PBKDF2)
- [ ] Quantum-Resistant Key Exchange (CRYSTALS-Kyber)
- [ ] Async (asyncio) API

---

## � Credits

**Created and maintained by:** Phenphet-k

---

## �📄 License

MIT License — see [LICENSE](LICENSE) for details.
