# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

ERitors Scribe is an Electron + Next.js desktop application for writers. It uses SQLite with WASM for local storage, supports offline mode with PIN authentication, and encrypts user data with AES-256-CBC.

## Commands

```bash
# Development (starts Next.js on port 4000 + Electron with hot reload)
npm run dev

# Build for specific platform
npm run build:mac
npm run build:win
npm run build:linux
npm run build:all
```

## Architecture

### Process Model

```
Renderer (Next.js)  <--IPC-->  Main Process  <-->  SQLite DB
       via window.electron.invoke()
```

- **Main process**: `electron/main.ts` - Window management, IPC handlers, OS integration
- **Preload script**: `electron/preload.ts` - Secure contextBridge API
- **Renderer**: Next.js App Router with static export (`output: 'export'`)

### Key Directories

- `electron/` - Main process code (IPC handlers, database, storage)
- `electron/ipc/` - IPC handlers organized by domain (book, chapter, character, etc.)
- `electron/database/` - SQLite service, models, repositories, encryption
- `electron/storage/SecureStorage.ts` - OS-level secure storage (macOS Keychain, Windows DPAPI)
- `app/` - Next.js pages (App Router)
- `context/` - React contexts for state management (13+ contexts)
- `components/` - React components
- `lib/locales/` - i18n translations (fr.json, en.json)

### IPC Handler Pattern

All IPC handlers use `createHandler<TBody, TReturn>()` factory in `electron/database/LocalSystem.ts`:

```typescript
// electron/ipc/book.ipc.ts
ipcMain.handle('db:book:books', createHandler<void, BookProps[]>(
    async (userId, _body, lang) => Book.getBooks(userId, lang)
));

// Frontend usage
const books = await window.electron.invoke('db:book:books');
```

The factory auto-injects `userId` and `lang` from secure storage, handles errors uniformly.

### State Management

Context-based architecture with providers:
- `UserContext` - Authenticated user
- `BookContext` - Current book
- `OfflineContext` - Offline mode state
- `SessionContext` - Session data
- `LangContext` - i18n

### Database

- One SQLite file per user: `eritors-local-{userId}.db`
- Uses `node-sqlite3-wasm` (WASM-based SQLite)
- AES-256-CBC encryption for stored data
- PBKDF2 key derivation (100K iterations)
- Schema in `electron/database/schema.ts`

### Security

- `contextIsolation: true`, `nodeIntegration: false`, `sandbox: true`
- OS-level secure storage for tokens and encryption keys
- Per-user encryption keys stored in SecureStorage
- Offline PIN hashed with bcrypt

## TypeScript Configuration

- `tsconfig.json` - Next.js/React (renderer)
- `tsconfig.electron.json` - Electron main process
- `tsconfig.preload.json` - Preload script

## Build Output

- `dist/` - Compiled TypeScript
- `out/` - Next.js static export
- `release/` - Electron builder output (DMG, NSIS, AppImage)
