diff --git a/.claude/README.md b/.claude/README.md new file mode 100644 index 0000000..bcaaf20 --- /dev/null +++ b/.claude/README.md @@ -0,0 +1,435 @@ +# 📚 Documentation Claude pour SecuBox + +Ce rĂ©pertoire contient la documentation et les guides pour travailler avec Claude Code sur le projet SecuBox. + +--- + +## 📁 Fichiers Disponibles + +### 1. `module-prompts.md` +**Prompts d'implĂ©mentation pour les 14 modules de base** + +Contient les spĂ©cifications complĂštes pour chaque module SecuBox existant: +- SecuBox Hub, System Hub +- CrowdSec, Netdata, Netifyd Dashboards +- Network Modes, Client Guardian, Auth Guardian +- WireGuard, Bandwidth Manager, Media Flow +- VHost Manager, CDN Cache, Traffic Shaper + +**Usage**: Copie-colle le prompt du module que tu veux implĂ©menter ou modifier. + +### 2. `module-implementation-guide.md` ⭐ NOUVEAU +**Template structurĂ© pour crĂ©er de nouveaux modules** + +Guide complet avec: +- Template rĂ©utilisable pour tout nouveau module +- Checklist de validation complĂšte +- Exemple dĂ©taillĂ©: KSM Manager (gestion de clĂ©s + Nitrokey) +- Workflow d'implĂ©mentation Ă©tape par Ă©tape +- SpĂ©cifications techniques dĂ©taillĂ©es + +**Usage**: +1. Copie le template +2. Remplis les sections pour ton module +3. Soumets le prompt complet Ă  Claude +4. Valide avec `validate-modules.sh` + +### 3. `settings.local.json` +**Configuration locale de Claude Code** + +Contient les paramĂštres de dĂ©veloppement pour cette session. + +--- + +## 🚀 Quick Start: CrĂ©er un Nouveau Module + +### Étape 1: PrĂ©paration +```bash +# Assure-toi d'ĂȘtre dans le bon rĂ©pertoire +cd /home/reepost/CyberMindStudio/_files/secubox + +# Lis le guide d'implĂ©mentation +cat .claude/module-implementation-guide.md +``` + +### Étape 2: RĂ©diger les SpĂ©cifications + +Ouvre `module-implementation-guide.md` et copie le template. Remplis: + +**Obligatoire**: +- Nom du module +- CatĂ©gorie (Security/Network/System/Performance/Services) +- Description et cas d'utilisation +- 3-5 fonctionnalitĂ©s principales +- MĂ©thodes RPCD (minimum 5-8) +- Configuration UCI +- Views JavaScript (minimum 2-3) + +**RecommandĂ©**: +- DĂ©pendances systĂšme +- SpĂ©cifications de parsing CLI +- Gestion d'erreurs +- Notes de sĂ©curitĂ© + +### Étape 3: Soumettre Ă  Claude + +``` +[Colle ton prompt basĂ© sur le template] +``` + +Claude gĂ©nĂ©rera: +- ✅ Makefile +- ✅ RPCD Backend +- ✅ API Client +- ✅ Views JavaScript +- ✅ Menu JSON +- ✅ ACL JSON +- ✅ README.md + +### Étape 4: Validation + +```bash +# Validation automatique +./secubox-tools/validate-modules.sh + +# VĂ©rification syntaxe JavaScript +node -c luci-app-{module}/htdocs/luci-static/resources/**/*.js + +# Test RPCD sur router (si disponible) +ubus call luci.{module} status +``` + +--- + +## 📖 Exemples d'Utilisation + +### Exemple 1: Module Simple (Monitoring) + +```markdown +## Nouveau Module SecuBox: System Monitor + +**Nom**: luci-app-system-monitor +**CatĂ©gorie**: System +**Description**: Monitoring temps rĂ©el CPU, RAM, Disk, Network + +### FonctionnalitĂ©s: +1. MĂ©triques systĂšme (CPU%, RAM%, Disk%, Temp) +2. Graphiques temps rĂ©el (5min, 1h, 24h) +3. Alertes configurables (seuils) +4. Export donnĂ©es (CSV, JSON) + +### MĂ©thodes RPCD: +- status +- get_metrics +- get_history +- set_alert +- list_alerts + +[... reste du template ...] +``` + +### Exemple 2: Module Complexe (KSM Manager) + +Voir l'exemple complet dans `module-implementation-guide.md` → Section "Exemple Concret: Module KSM" + +22 mĂ©thodes RPCD, 8 views, support HSM hardware, gestion certificats, audit logs, etc. + +### Exemple 3: Module IntĂ©gration (Home Assistant) + +```markdown +## Nouveau Module SecuBox: Home Assistant Bridge + +**Nom**: luci-app-hass-bridge +**CatĂ©gorie**: Services +**Description**: IntĂ©gration bidirectionnelle avec Home Assistant + +### FonctionnalitĂ©s: +1. Auto-discovery MQTT +2. Entities SecuBox → HASS (sensors, switches) +3. Services HASS → SecuBox (actions) +4. Webhooks bidirectionnels +5. Dashboard widgets + +### MĂ©thodes RPCD: +- status +- get_entities +- publish_entity +- trigger_service +- list_webhooks +- add_webhook + +[... reste du template ...] +``` + +--- + +## 🎯 Bonnes Pratiques + +### Naming Conventions + +**Package**: +- Format: `luci-app-{nom-module}` (tout en minuscules, tirets) +- Exemples: `luci-app-cdn-cache`, `luci-app-ksm-manager` + +**RPCD Script**: +- **OBLIGATOIRE**: `luci.{nom-module}` (prĂ©fixe `luci.` requis!) +- Emplacement: `/root/usr/libexec/rpcd/luci.{nom-module}` +- Permissions: ExĂ©cutable (`chmod +x`) + +**UCI Config**: +- Fichier: `/etc/config/{nom-module}` (sans `luci-app-`) +- Exemple: `/etc/config/ksm` pour `luci-app-ksm-manager` + +**Views**: +- Emplacement: `/htdocs/luci-static/resources/view/{module}/` +- Fichiers: `overview.js`, `{feature}.js` + +**API Client**: +- Emplacement: `/htdocs/luci-static/resources/{module}/api.js` +- Export: `L.Class.extend({ ... })` + +### Structure Minimale + +**Petit module** (< 5 mĂ©thodes): +``` +luci-app-{module}/ +├── Makefile +├── README.md +├── htdocs/luci-static/resources/ +│ ├── {module}/ +│ │ └── api.js +│ └── view/{module}/ +│ └── overview.js +└── root/ + ├── usr/ + │ ├── libexec/rpcd/ + │ │ └── luci.{module} + │ └── share/ + │ ├── luci/menu.d/ + │ │ └── luci-app-{module}.json + │ └── rpcd/acl.d/ + │ └── luci-app-{module}.json + └── etc/config/ + └── {module} (optionnel) +``` + +**Module complet** (> 8 mĂ©thodes): +``` +[Structure minimale +] +├── htdocs/luci-static/resources/ +│ └── view/{module}/ +│ ├── overview.js +│ ├── management.js +│ ├── settings.js +│ └── logs.js +└── root/etc/init.d/ + └── {module} (si besoin d'un daemon) +``` + +### Checklist PrĂ©-Commit + +Avant de commiter un nouveau module: + +- [ ] `./secubox-tools/validate-modules.sh` passe ✅ +- [ ] Tous les fichiers JavaScript valident avec `node -c` +- [ ] Tous les JSON valident avec `jsonlint` +- [ ] RPCD script est exĂ©cutable +- [ ] Nom RPCD = `luci.{module}` (avec prĂ©fixe!) +- [ ] README.md complet avec installation/usage +- [ ] Makefile a toutes les dĂ©pendances +- [ ] ACL contient toutes les mĂ©thodes RPCD +- [ ] Menu paths matchent les fichiers view +- [ ] Git commit message descriptif + +--- + +## 🔧 Outils de DĂ©veloppement + +### Validation Automatique + +```bash +# Validation complĂšte de tous les modules +./secubox-tools/validate-modules.sh + +# Validation d'un module spĂ©cifique +./secubox-tools/secubox-debug.sh luci-app-{module} + +# RĂ©paration automatique des problĂšmes courants +./secubox-tools/secubox-repair.sh +``` + +### Build Local + +```bash +# Build tous les packages +./secubox-tools/local-build.sh build + +# Build un package spĂ©cifique +./secubox-tools/local-build.sh build luci-app-{module} + +# Build pour architecture spĂ©cifique +./secubox-tools/local-build.sh build --arch aarch64-cortex-a72 + +# Validation seule (rapide) +./secubox-tools/local-build.sh validate +``` + +### Test sur Router + +```bash +# Transfer IPK +scp build/x86-64/luci-app-{module}_*.ipk root@192.168.1.1:/tmp/ + +# Install sur router +ssh root@192.168.1.1 +opkg install /tmp/luci-app-{module}_*.ipk +/etc/init.d/rpcd restart +/etc/init.d/uhttpd restart + +# Test RPC manuel +ubus list | grep {module} +ubus call luci.{module} status +``` + +--- + +## 📚 Ressources + +### Documentation OpenWrt/LuCI + +- [LuCI API Reference](https://openwrt.github.io/luci/) +- [UCI Configuration](https://openwrt.org/docs/guide-user/base-system/uci) +- [RPCD Guide](https://openwrt.org/docs/techref/rpcd) +- [OpenWrt Packages](https://openwrt.org/packages/start) + +### Exemples de Code + +Tous les 14 modules SecuBox existants servent de rĂ©fĂ©rence: + +**Simples** (bon pour dĂ©buter): +- `luci-app-netdata-dashboard` - Iframe simple + contrĂŽles +- `luci-app-network-modes` - Preset application + +**Moyens**: +- `luci-app-bandwidth-manager` - QoS avec graphiques +- `luci-app-media-flow` - DĂ©tection + stats + +**AvancĂ©s** (patterns complexes): +- `luci-app-wireguard-dashboard` - GĂ©nĂ©ration clĂ©s + QR codes +- `luci-app-auth-guardian` - OAuth + vouchers + sessions +- `luci-app-traffic-shaper` - TC/CAKE intĂ©gration + +### Architecture SecuBox + +``` +SecuBox Hub (luci-app-secubox) + ├── Security Layer + │ ├── CrowdSec Dashboard + │ └── Auth Guardian + ├── Network Layer + │ ├── Network Modes + │ ├── Client Guardian + │ ├── WireGuard Dashboard + │ └── VHost Manager + ├── Traffic Layer + │ ├── Bandwidth Manager + │ ├── Media Flow + │ ├── CDN Cache + │ └── Traffic Shaper + ├── Monitoring Layer + │ ├── Netdata Dashboard + │ ├── Netifyd Dashboard + │ └── System Hub + └── [Nouveau Module] +``` + +--- + +## đŸ€ Contribution + +### Workflow Git + +```bash +# CrĂ©er branche pour nouveau module +git checkout -b feature/luci-app-{module} + +# DĂ©velopper avec validation continue +# ... dĂ©veloppement ... +./secubox-tools/validate-modules.sh + +# Commit +git add luci-app-{module}/ +git commit -m "feat: implement {Module Name} - {brief description}" + +# Push +git push origin feature/luci-app-{module} + +# Tag pour release +git tag v0.0.X +git push origin v0.0.X +``` + +### Format de Commit Messages + +``` +feat: implement KSM Manager - hardware key storage with Nitrokey +fix: correct RPCD method naming in CDN Cache +docs: add installation guide for Traffic Shaper +chore: update dependencies for Bandwidth Manager +refactor: improve error handling in Auth Guardian +``` + +--- + +## 💡 Support + +### Debug Module Issues + +**ProblĂšme**: Module n'apparaĂźt pas dans le menu +- VĂ©rifier menu JSON path +- VĂ©rifier ACL permissions +- RedĂ©marrer uhttpd: `/etc/init.d/uhttpd restart` + +**ProblĂšme**: RPC errors "Object not found" +- VĂ©rifier nom RPCD = `luci.{module}` +- VĂ©rifier RPCD exĂ©cutable: `chmod +x` +- RedĂ©marrer rpcd: `/etc/init.d/rpcd restart` +- Tester ubus: `ubus list | grep {module}` + +**ProblĂšme**: JavaScript errors +- Valider syntaxe: `node -c {file}.js` +- VĂ©rifier imports: `'require {module}/api'` +- Check console browser (F12) + +**ProblĂšme**: Build failures +- VĂ©rifier Makefile dependencies +- VĂ©rifier include path: `../../luci.mk` +- Clean build: `make clean` + +### Demander de l'Aide + +Ouvre une issue GitHub avec: +1. Nom du module +2. Description du problĂšme +3. Logs d'erreur +4. Output de `./secubox-tools/validate-modules.sh` +5. Configuration (anonymisĂ©e si nĂ©cessaire) + +--- + +## 🎉 Success Stories + +Modules dĂ©jĂ  implĂ©mentĂ©s avec succĂšs: + +1. **WireGuard Dashboard** - GĂ©nĂ©ration peers + QR codes +2. **Auth Guardian** - OAuth + vouchers complĂšte +3. **Bandwidth Manager** - QoS avec graphiques temps rĂ©el +4. **Media Flow** - DĂ©tection streaming avec donut chart +5. **CDN Cache** - Hit ratio gauge + cache management +6. **Traffic Shaper** - TC/CAKE avec presets + +Tous validĂ©s ✅ et production-ready 🚀 + +--- + +**Bon dĂ©veloppement avec SecuBox!** 🔧🔐🌐 diff --git a/.claude/module-implementation-guide.md b/.claude/module-implementation-guide.md new file mode 100644 index 0000000..20a6046 --- /dev/null +++ b/.claude/module-implementation-guide.md @@ -0,0 +1,777 @@ +# 🔧 Guide d'ImplĂ©mentation de Nouveaux Modules SecuBox + +Ce guide fournit un framework structurĂ© pour implĂ©menter de nouveaux modules SecuBox avec suivi complet du dĂ©veloppement. + +--- + +## 📋 Template de Prompt d'ImplĂ©mentation + +Utilise ce template pour demander l'implĂ©mentation d'un nouveau module: + +```markdown +## Nouveau Module SecuBox: {NOM_MODULE} + +### 🎯 Contexte et Objectif + +**Nom du module**: luci-app-{nom-module} +**CatĂ©gorie**: [Security / Network / System / Performance / Services] +**Description courte**: {Description en 1-2 phrases} +**Cas d'utilisation**: {Qui utilisera ce module et pourquoi} + +### 📊 FonctionnalitĂ©s Requises + +Liste numĂ©rotĂ©e des fonctionnalitĂ©s principales: + +1. **{FonctionnalitĂ© 1}**: {Description dĂ©taillĂ©e} + - Sous-fonctionnalitĂ© A + - Sous-fonctionnalitĂ© B + +2. **{FonctionnalitĂ© 2}**: {Description dĂ©taillĂ©e} + - Sous-fonctionnalitĂ© A + - Sous-fonctionnalitĂ© B + +3. **{FonctionnalitĂ© 3}**: {Description dĂ©taillĂ©e} + +### 🔌 IntĂ©gration SystĂšme + +**Service systĂšme**: {nom du daemon/service} +**Commandes CLI**: +- `{commande1}` - {description} +- `{commande2}` - {description} + +**Fichiers de configuration**: +- `/etc/{config-file}` - {description} +- `/var/run/{runtime-file}` - {description} + +**DĂ©pendances packages**: +- `{package1}` - {description} +- `{package2}` - {description} + +### 🎹 MĂ©thodes RPCD + +Script: `/usr/libexec/rpcd/luci.{nom-module}` + +#### MĂ©thodes de Base +1. **status**: État du service + - Retour: `{ "running": bool, "enabled": bool, "version": string, ... }` + +2. **get_info**: Informations systĂšme + - Retour: `{ ... }` + +#### MĂ©thodes de Gestion +3. **list_{ressource}**: Liste des ressources + - Retour: `{ "{ressources}": [...] }` + +4. **get_{ressource}**: DĂ©tails d'une ressource + - Params: `id` + - Retour: `{ ... }` + +5. **add_{ressource}**: CrĂ©er une ressource + - Params: `{ param1, param2, ... }` + - Retour: `{ "success": bool, "id": string }` + +6. **update_{ressource}**: Modifier une ressource + - Params: `{ id, param1, param2, ... }` + - Retour: `{ "success": bool }` + +7. **delete_{ressource}**: Supprimer une ressource + - Params: `id` + - Retour: `{ "success": bool }` + +#### MĂ©thodes SpĂ©cifiques +8. **{methode_specifique_1}**: {Description} +9. **{methode_specifique_2}**: {Description} + +### đŸ—„ïž Configuration UCI + +Fichier: `/etc/config/{nom-module}` + +```uci +config global 'main' + option enabled '1' + option {param1} '{valeur}' + option {param2} '{valeur}' + +config {type_section} '{id_section}' + option {param1} '{valeur}' + option {param2} '{valeur}' + list {param_list} '{valeur1}' + list {param_list} '{valeur2}' +``` + +### 🎹 Interface Utilisateur (Views) + +#### Vue 1: Overview/Dashboard +**Fichier**: `htdocs/luci-static/resources/view/{module}/overview.js` + +**ÉlĂ©ments**: +- Status cards (service running, stats) +- Graphiques/visualisations +- Actions rapides +- Liens vers autres vues + +**Auto-refresh**: Oui (5s pour status, 10s pour stats) + +#### Vue 2: {Nom Vue 2} +**Fichier**: `htdocs/luci-static/resources/view/{module}/{vue2}.js` + +**ÉlĂ©ments**: +- Tableau CRUD avec form.GridSection +- Modals pour crĂ©ation/Ă©dition +- Validation des inputs +- Confirmations de suppression + +#### Vue 3: {Nom Vue 3} +**Fichier**: `htdocs/luci-static/resources/view/{module}/{vue3}.js` + +**ÉlĂ©ments**: +- ... + +### 🎯 SpĂ©cifications Techniques + +#### Parsing de Sortie CLI +```bash +# Exemple de commande et parsing attendu +{commande} | {parsing} + +# Output format attendu +{...} +``` + +#### Gestion d'Erreurs +- Erreur si service non installĂ©: `{ "error": "Service not installed" }` +- Erreur si permission refusĂ©e: `{ "error": "Permission denied" }` +- Erreur si ressource inexistante: `{ "error": "Not found" }` + +#### SĂ©curitĂ© +- Validation des inputs: {regex/validation} +- Sanitization des chaĂźnes: Oui/Non +- Permissions requises: {root/user/...} + +### 📩 Livrables Attendus + +**IMPORTANT**: GĂ©nĂšre TOUS les fichiers complets suivants: + +1. **Makefile** avec dĂ©pendances correctes +2. **RPCD Backend** (`/root/usr/libexec/rpcd/luci.{module}`) + - Toutes les mĂ©thodes implĂ©mentĂ©es + - Gestion d'erreurs complĂšte + - JSON valide pour chaque retour +3. **API Client** (`/htdocs/luci-static/resources/{module}/api.js`) + - DĂ©clarations RPC pour toutes les mĂ©thodes + - Fonctions utilitaires (formatage, etc.) +4. **Views JavaScript** (tous les fichiers .js nĂ©cessaires) + - Code complet, pas de placeholders + - Gestion d'erreurs UI + - Auto-refresh oĂč appropriĂ© +5. **Menu JSON** (`/root/usr/share/luci/menu.d/luci-app-{module}.json`) +6. **ACL JSON** (`/root/usr/share/rpcd/acl.d/luci-app-{module}.json`) +7. **UCI Config Template** (optionnel si besoin) +8. **README.md** avec: + - Installation + - Configuration + - Usage + - DĂ©pendances + - Troubleshooting + +### ✅ Checklist de Validation + +Avant de marquer comme terminĂ©, vĂ©rifier: + +- [ ] Tous les fichiers gĂ©nĂ©rĂ©s +- [ ] RPCD script exĂ©cutable (chmod +x) +- [ ] Nom RPCD = `luci.{module}` (convention obligatoire) +- [ ] Tous les appels RPC matchent les mĂ©thodes RPCD +- [ ] Paths menu matchent les fichiers view +- [ ] JavaScript syntaxe valide (node -c) +- [ ] JSON files valides (jsonlint) +- [ ] ACL inclut toutes les mĂ©thodes RPCD +- [ ] DĂ©pendances Makefile complĂštes +- [ ] Gestion d'erreurs implĂ©mentĂ©e partout +- [ ] Documentation README complĂšte + +### 🔄 Workflow d'ImplĂ©mentation + +1. **Phase 1: Backend** + - ImplĂ©menter RPCD avec toutes les mĂ©thodes + - Tester chaque mĂ©thode individuellement avec `ubus call` + +2. **Phase 2: API Client** + - CrĂ©er api.js avec dĂ©clarations RPC + - Ajouter fonctions utilitaires + +3. **Phase 3: Views** + - ImplĂ©menter vue overview (dashboard) + - ImplĂ©menter vues CRUD + - ImplĂ©menter vues spĂ©cifiques + +4. **Phase 4: Configuration** + - Menu JSON + - ACL JSON + - UCI template si nĂ©cessaire + +5. **Phase 5: Validation** + - Run `./secubox-tools/validate-modules.sh` + - VĂ©rifier syntaxe JavaScript + - Tester sur router si possible + +### 📝 Notes d'ImplĂ©mentation + +{Notes spĂ©cifiques, contraintes, choix d'architecture, etc.} + +--- + +## Instructions Finales + +ImplĂ©mente ce module en suivant EXACTEMENT les patterns des 14 modules existants: +- Structure des fichiers identique +- Conventions de nommage cohĂ©rentes +- Style de code similaire +- Validation complĂšte avant livraison + +GĂ©nĂšre tous les fichiers complets. Ne laisse AUCUN placeholder ou TODO. +``` + +--- + +## 🔐 Exemple Concret: Module KSM (Key Storage Manager) + +Voici un exemple d'utilisation du template pour un module de gestion de clĂ©s avec support Nitrokey: + +```markdown +## Nouveau Module SecuBox: Key Storage Manager + +### 🎯 Contexte et Objectif + +**Nom du module**: luci-app-ksm-manager +**CatĂ©gorie**: Security +**Description courte**: Gestionnaire centralisĂ© de clĂ©s cryptographiques avec support hardware (Nitrokey, YubiKey) et stockage sĂ©curisĂ©. +**Cas d'utilisation**: Administrateurs systĂšme gĂ©rant des certificats SSL, clĂ©s SSH, secrets d'application, et tokens avec support HSM/USB. + +### 📊 FonctionnalitĂ©s Requises + +1. **Gestion des ClĂ©s Cryptographiques** + - GĂ©nĂ©ration de clĂ©s (RSA, ECDSA, Ed25519) + - Import/export de clĂ©s (PEM, DER, P12) + - Listing avec mĂ©tadonnĂ©es (type, taille, usage, expiration) + - Suppression sĂ©curisĂ©e (shred) + +2. **Support Hardware Security Modules** + - DĂ©tection automatique Nitrokey/YubiKey (USB) + - Initialisation/PIN management + - GĂ©nĂ©ration de clĂ©s on-chip + - OpĂ©rations cryptographiques (sign, encrypt) + - Backup/restore de tokens + +3. **Stockage SĂ©curisĂ© de Secrets** + - Keystore chiffrĂ© (AES-256-GCM) + - Secrets applicatifs (API keys, passwords) + - Rotation automatique de secrets + - Historique d'accĂšs (audit log) + +4. **IntĂ©gration Certificats** + - GĂ©nĂ©ration CSR (Certificate Signing Request) + - Import certificats (Let's Encrypt, CA interne) + - VĂ©rification chaĂźne de confiance + - Alertes expiration (< 30 jours) + +5. **SSH Key Management** + - GĂ©nĂ©ration de paires SSH + - DĂ©ploiement vers authorized_keys + - Agent SSH avec forward (ssh-agent) + - Support certificats SSH + +### 🔌 IntĂ©gration SystĂšme + +**Services systĂšme**: +- `nitropy` - CLI Nitrokey +- `ykman` - CLI YubiKey +- `gnupg2` - GPG/OpenPGP +- `opensc` - Smart card framework + +**Commandes CLI**: +- `nitropy nk3 list` - Liste Nitrokey connectĂ©es +- `ykman list` - Liste YubiKey connectĂ©es +- `gpg --card-status` - Status carte OpenPGP +- `pkcs11-tool --list-tokens` - Liste tokens PKCS#11 +- `openssl` - GĂ©nĂ©ration clĂ©s/CSR + +**Fichiers de configuration**: +- `/etc/ksm/keystore.db` - Base SQLite chiffrĂ©e +- `/etc/ksm/config.json` - Configuration module +- `/var/log/ksm-audit.log` - Logs d'accĂšs + +**DĂ©pendances packages**: +- `nitropy` - Nitrokey tools +- `yubikey-manager` - YubiKey management +- `gnupg2` - GPG support +- `opensc` - Smart card support +- `openssl` - Crypto operations +- `libccid` - USB CCID driver +- `pcscd` - PC/SC daemon + +### 🎹 MĂ©thodes RPCD + +Script: `/usr/libexec/rpcd/luci.ksm-manager` + +#### MĂ©thodes de Base +1. **status**: État du service + - Retour: `{ "running": bool, "keystore_unlocked": bool, "keys_count": int, "hsm_connected": bool }` + +2. **get_info**: Informations systĂšme + - Retour: `{ "openssl_version": string, "gpg_version": string, "hsm_support": bool }` + +#### MĂ©thodes HSM/Hardware +3. **list_hsm_devices**: Liste devices USB + - Retour: `{ "devices": [{ "type": "nitrokey", "serial": "...", "version": "..." }] }` + +4. **get_hsm_status**: Status d'un device + - Params: `serial` + - Retour: `{ "initialized": bool, "pin_retries": int, "keys_count": int }` + +5. **init_hsm**: Initialiser un HSM + - Params: `serial, admin_pin, user_pin` + - Retour: `{ "success": bool }` + +6. **generate_hsm_key**: GĂ©nĂ©rer clĂ© on-chip + - Params: `serial, key_type, key_size, label` + - Retour: `{ "success": bool, "key_id": string }` + +#### MĂ©thodes Gestion de ClĂ©s +7. **list_keys**: Liste toutes les clĂ©s + - Retour: `{ "keys": [{ "id": string, "label": string, "type": string, "size": int, "created": timestamp }] }` + +8. **generate_key**: GĂ©nĂ©rer une clĂ© logicielle + - Params: `type, size, label, passphrase` + - Retour: `{ "success": bool, "id": string, "public_key": string }` + +9. **import_key**: Importer une clĂ© + - Params: `label, key_data, format, passphrase` + - Retour: `{ "success": bool, "id": string }` + +10. **export_key**: Exporter une clĂ© + - Params: `id, format, include_private, passphrase` + - Retour: `{ "success": bool, "key_data": string }` + +11. **delete_key**: Supprimer une clĂ© + - Params: `id, secure_erase` + - Retour: `{ "success": bool }` + +#### MĂ©thodes Certificats +12. **generate_csr**: GĂ©nĂ©rer CSR + - Params: `key_id, subject_dn, san_list` + - Retour: `{ "success": bool, "csr": string }` + +13. **import_certificate**: Importer certificat + - Params: `key_id, cert_data, chain` + - Retour: `{ "success": bool, "cert_id": string }` + +14. **list_certificates**: Liste certificats + - Retour: `{ "certificates": [{ "id": string, "subject": string, "issuer": string, "valid_until": timestamp }] }` + +15. **verify_certificate**: VĂ©rifier certificat + - Params: `cert_id` + - Retour: `{ "valid": bool, "chain_valid": bool, "expires_in_days": int }` + +#### MĂ©thodes Secrets +16. **store_secret**: Stocker un secret + - Params: `label, secret_data, category, auto_rotate` + - Retour: `{ "success": bool, "secret_id": string }` + +17. **retrieve_secret**: RĂ©cupĂ©rer un secret + - Params: `secret_id` + - Retour: `{ "success": bool, "secret_data": string, "accessed_at": timestamp }` + +18. **list_secrets**: Liste secrets + - Retour: `{ "secrets": [{ "id": string, "label": string, "category": string, "created": timestamp }] }` + +19. **rotate_secret**: Rotation de secret + - Params: `secret_id, new_secret_data` + - Retour: `{ "success": bool, "version": int }` + +#### MĂ©thodes SSH +20. **generate_ssh_key**: GĂ©nĂ©rer paire SSH + - Params: `label, key_type, comment` + - Retour: `{ "success": bool, "key_id": string, "public_key": string }` + +21. **deploy_ssh_key**: DĂ©ployer vers authorized_keys + - Params: `key_id, target_host, target_user` + - Retour: `{ "success": bool }` + +#### MĂ©thodes Audit +22. **get_audit_logs**: Logs d'accĂšs + - Params: `limit, offset, filter_type` + - Retour: `{ "logs": [{ "timestamp": timestamp, "action": string, "user": string, "key_id": string }] }` + +### đŸ—„ïž Configuration UCI + +Fichier: `/etc/config/ksm` + +```uci +config global 'main' + option enabled '1' + option keystore_path '/etc/ksm/keystore.db' + option audit_enabled '1' + option audit_retention '90' + option auto_backup '1' + +config hsm_device 'device_123' + option serial 'NK3-ABC123' + option type 'nitrokey' + option label 'Production HSM' + option enabled '1' + +config key 'key_456' + option label 'SSL Certificate Key' + option type 'rsa' + option size '4096' + option usage 'ssl' + option storage 'hsm' + option hsm_serial 'NK3-ABC123' + option created '2025-01-15T10:00:00Z' + +config secret 'secret_789' + option label 'API Key GitHub' + option category 'api_key' + option auto_rotate '1' + option rotation_days '90' + option created '2025-01-15T10:00:00Z' + +config certificate 'cert_101' + option key_id 'key_456' + option subject 'CN=example.com' + option issuer 'CN=Let's Encrypt' + option valid_from '2025-01-01T00:00:00Z' + option valid_until '2025-04-01T00:00:00Z' + option alert_days '30' +``` + +### 🎹 Interface Utilisateur (Views) + +#### Vue 1: Overview/Dashboard +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/overview.js` + +**ÉlĂ©ments**: +- **Status cards**: Keystore locked/unlocked, HSM connected, Keys count, Expiring certs +- **HSM Devices**: Cards avec serial, type, status (connected/disconnected), PIN retries +- **Quick Stats**: Pie chart types de clĂ©s (RSA/ECDSA/Ed25519) +- **Expiring Certificates**: Timeline avec alertes < 30 jours +- **Recent Activity**: 10 derniĂšres actions d'audit +- **Actions rapides**: Unlock keystore, Generate key, Import certificate + +**Auto-refresh**: 10s pour HSM status, 30s pour stats + +#### Vue 2: Keys Management +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/keys.js` + +**ÉlĂ©ments**: +- **Tableau GridSection** avec: + - Colonnes: Label, Type, Size, Storage (software/hsm), Created, Actions + - Filtres: Type, Storage location + - Tri par date/label +- **Modal Generate Key**: + - Type (RSA/ECDSA/Ed25519) + - Size (dropdown: 2048/3072/4096 pour RSA, 256/384/521 pour ECDSA) + - Storage (software/hsm selector) + - Label, Passphrase + - Button "Generate" → progress → success +- **Modal Import Key**: + - Format (PEM/DER/P12) + - File upload ou paste textarea + - Passphrase si encrypted + - Label +- **Actions inline**: + - View public key (modal avec copy button) + - Export (format selector) + - Delete (confirmation avec secure erase option) + +#### Vue 3: HSM Devices +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/hsm.js` + +**ÉlĂ©ments**: +- **Auto-detect**: Button scan USB devices +- **Device Cards** pour chaque HSM: + - Header: Type icon (Nitrokey/YubiKey) + Serial + Label + - Status: Initialized, PIN retries (progress bar), Keys count + - Actions: Initialize, Change PIN, Generate key on-chip, Backup, Factory reset +- **Modal Initialize HSM**: + - Admin PIN (strength meter) + - User PIN (strength meter) + - Label + - Warning: Factory reset si dĂ©jĂ  initialisĂ© +- **Modal Generate HSM Key**: + - Key type, size, label + - Requires user PIN + - Progress indicator +- **Key list per HSM**: Expandable section showing keys stored on chip + +#### Vue 4: Certificates +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/certificates.js` + +**ÉlĂ©ments**: +- **Tableau certificates**: + - Colonnes: Subject CN, Issuer, Valid from/until, Days remaining, Status + - Color coding: Green (>30d), Orange (7-30d), Red (<7d), Gray (expired) + - Actions: View details, Export PEM, Revoke, Delete +- **Modal Generate CSR**: + - Select key (dropdown) + - Subject DN fields (CN, O, OU, C, ST, L) + - SAN list (domains, IPs) + - Generate button → CSR textarea avec copy + - Download .csr button +- **Modal Import Certificate**: + - Select key to associate + - Certificate PEM (textarea or file upload) + - Certificate chain (optional) + - Validate button → shows cert info before import +- **Certificate Details Modal**: + - Full subject/issuer DN + - Serial number + - Validity dates + - Public key info + - Extensions (Key Usage, Extended Key Usage, SAN) + - Certificate chain visualization + - Verify chain button + +#### Vue 5: Secrets +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/secrets.js` + +**ÉlĂ©ments**: +- **Tableau secrets**: + - Colonnes: Label, Category, Created, Last accessed, Auto-rotate, Actions + - Categories: API Key, Password, Token, Database, Other + - Masked secrets (show button reveals for 10s) +- **Modal Add Secret**: + - Label + - Category (dropdown) + - Secret value (textarea, masked) + - Auto-rotate toggle + rotation days + - Expiration date (optional) +- **Modal View Secret**: + - Shows secret with copy button + - Warning: "This access will be logged" + - Auto-hide after 30 seconds + - Access history table +- **Actions**: + - View/copy (logs access) + - Rotate (enter new value) + - Delete (confirmation) + +#### Vue 6: SSH Keys +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/ssh.js` + +**ÉlĂ©ments**: +- **Tableau SSH keys**: + - Colonnes: Label, Type, Fingerprint, Created, Deployed to, Actions +- **Modal Generate SSH Key**: + - Type (RSA/ECDSA/Ed25519) + - Size (for RSA) + - Comment + - Passphrase (optional) +- **Modal Deploy Key**: + - Select key + - Target host + - Target user + - Port + - Test connection button + - Deploy button +- **Public key display**: Copy to clipboard button + +#### Vue 7: Audit Logs +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/audit.js` + +**ÉlĂ©ments**: +- **Timeline logs**: + - Timestamp, User, Action, Resource (key/secret/cert), Status + - Color coding par action type + - Filtres: Date range, Action type, User, Resource +- **Export logs**: CSV/JSON download +- **Auto-refresh**: 15s + +#### Vue 8: Settings +**Fichier**: `htdocs/luci-static/resources/view/ksm-manager/settings.js` + +**ÉlĂ©ments**: +- **Keystore Settings**: + - Change master password + - Keystore path + - Auto-lock timeout + - Backup schedule +- **Audit Settings**: + - Enable/disable audit + - Retention period (days) + - Log level +- **Alerts Settings**: + - Certificate expiration threshold (days) + - Secret rotation reminder + - HSM disconnect alerts +- **Backup/Restore**: + - Create backup (encrypted archive) + - Restore from backup + - Auto-backup toggle + schedule + +### 🎯 SpĂ©cifications Techniques + +#### Parsing de Sortie CLI + +**Nitrokey List**: +```bash +nitropy nk3 list --json | jq -c '.[]' +# Output: {"path": "/dev/hidraw0", "serial_number": "NK3-ABC123", "firmware_version": "1.2.0"} +``` + +**YubiKey List**: +```bash +ykman list --serials +# Output: NK3-ABC123 +``` + +**OpenSSL Key Generation**: +```bash +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out /tmp/key.pem +openssl rsa -in /tmp/key.pem -pubout -out /tmp/key.pub +``` + +**Certificate Info**: +```bash +openssl x509 -in cert.pem -noout -subject -issuer -dates -serial +``` + +#### Gestion d'Erreurs +- HSM non dĂ©tectĂ©: `{ "error": "HSM not found", "code": "HSM_NOT_FOUND" }` +- PIN incorrect: `{ "error": "Invalid PIN", "retries_left": 2, "code": "INVALID_PIN" }` +- Keystore locked: `{ "error": "Keystore locked", "code": "KEYSTORE_LOCKED" }` +- ClĂ© inexistante: `{ "error": "Key not found", "code": "KEY_NOT_FOUND" }` +- Certificate expirĂ©: `{ "error": "Certificate expired", "code": "CERT_EXPIRED" }` + +#### SĂ©curitĂ© +- **Validation inputs**: + - Serial: `^[A-Z0-9-]+$` + - Label: `^[a-zA-Z0-9 _-]{1,64}$` + - PIN: 6-32 caractĂšres +- **Sanitization**: Toutes les entrĂ©es utilisateur passĂ©es Ă  openssl/gpg +- **Permissions**: Root requis pour accĂšs /dev/hidraw* +- **Audit**: Tous les accĂšs aux secrets loggĂ©s +- **Encryption**: Keystore chiffrĂ© AES-256-GCM avec KDF (PBKDF2) + +### 📩 Livrables Attendus + +GĂ©nĂšre TOUS les fichiers complets: + +1. ✅ **Makefile** avec dĂ©pendances (nitropy, yubikey-manager, gnupg2, opensc, openssl, libccid, pcscd) +2. ✅ **RPCD Backend** avec 22 mĂ©thodes complĂštes +3. ✅ **API Client** avec toutes les dĂ©clarations RPC + utilitaires +4. ✅ **8 Views JavaScript** (overview, keys, hsm, certificates, secrets, ssh, audit, settings) +5. ✅ **Menu JSON** avec 8 entrĂ©es +6. ✅ **ACL JSON** avec toutes les permissions +7. ✅ **README.md** complet avec: + - Guide installation Nitrokey/YubiKey drivers + - Configuration initiale du keystore + - Exemples d'utilisation + - Troubleshooting USB permissions + - Best practices sĂ©curitĂ© + +### ✅ Checklist de Validation + +- [ ] RPCD backend complet avec 22 mĂ©thodes +- [ ] Gestion HSM (Nitrokey + YubiKey) +- [ ] GĂ©nĂ©ration/import/export de clĂ©s +- [ ] Gestion certificats avec CSR +- [ ] Stockage secrets chiffrĂ©s +- [ ] SSH key management +- [ ] Audit logs complets +- [ ] 8 views fonctionnelles +- [ ] Auto-refresh appropriĂ© +- [ ] Validation inputs partout +- [ ] Gestion erreurs complĂšte +- [ ] Nom RPCD = `luci.ksm-manager` +- [ ] Syntaxe JavaScript valide +- [ ] Documentation README + +### 🔄 Workflow d'ImplĂ©mentation + +**Phase 1: Backend Core** +1. ImplĂ©menter dĂ©tection HSM (nitropy/ykman) +2. CrĂ©er keystore SQLite chiffrĂ© +3. ImplĂ©menter mĂ©thodes de base (status, info, list) + +**Phase 2: Key Management** +4. GĂ©nĂ©ration clĂ©s software (openssl) +5. Import/export clĂ©s +6. GĂ©nĂ©ration clĂ©s HSM (PKCS#11) + +**Phase 3: Certificates** +7. GĂ©nĂ©ration CSR +8. Import/validation certificats +9. Alertes expiration + +**Phase 4: Secrets & SSH** +10. Stockage secrets chiffrĂ©s +11. Rotation automatique +12. SSH key management + +**Phase 5: Audit & UI** +13. SystĂšme d'audit logs +14. Toutes les views +15. Auto-refresh et polling + +**Phase 6: Testing** +16. Validation complĂšte +17. Tests avec vrai HSM +18. Documentation + +### 📝 Notes d'ImplĂ©mentation + +**Architecture**: +- Backend SQLite pour metadata + fichiers PEM pour clĂ©s +- Keystore master password → KDF → AES key pour chiffrement +- HSM operations via PKCS#11 (libccid + opensc) +- Audit logs append-only avec rotation + +**Performance**: +- Cache status HSM (TTL 5s) pour Ă©viter USB polling constant +- Index SQLite sur labels, created, expires +- Lazy loading de clĂ©s privĂ©es + +**SĂ©curitĂ©**: +- Keystore auto-lock aprĂšs timeout +- PIN retries limitĂ©s (3 max avant lock) +- Secure memory (mlock) pour clĂ©s en RAM +- Shred files avant delete +- Audit tous les accĂšs + +--- + +## Instructions Finales + +ImplĂ©mente le module **KSM Manager** en suivant exactement le template ci-dessus. + +- Structure identique aux 14 modules SecuBox existants +- Code complet, zĂ©ro placeholders +- Validation complĂšte avant livraison +- Documentation exhaustive + +GĂ©nĂšre TOUS les fichiers listĂ©s. Commence par le backend RPCD, puis API, puis views. +``` + +--- + +## 🎯 Utilisation du Template + +### Pour implĂ©menter un nouveau module: + +1. **Copie le template** de ce fichier +2. **Remplis chaque section** avec les specs de ton module +3. **Soumets le prompt complet** Ă  Claude +4. **Valide** avec `./secubox-tools/validate-modules.sh` +5. **Teste** sur router ou Ă©mulateur + +### Exemples d'autres modules possibles: + +- **luci-app-iot-hub**: Gestion centralisĂ©e dispositifs IoT (MQTT, Zigbee, Z-Wave) +- **luci-app-backup-manager**: Backups automatiques (rsync, rclone, cloud) +- **luci-app-dns-manager**: DNS local avancĂ© (Pi-hole style, DoH, DoT) +- **luci-app-container-manager**: Docker/Podman management +- **luci-app-monitoring-alerts**: Alerting system (Prometheus, Grafana, webhooks) + +Adapte le template selon tes besoins spĂ©cifiques!